1#!/usr/bin/env python3
2#
3#  Copyright (c) 2016, The OpenThread Authors.
4#  All rights reserved.
5#
6#  Redistribution and use in source and binary forms, with or without
7#  modification, are permitted provided that the following conditions are met:
8#  1. Redistributions of source code must retain the above copyright
9#     notice, this list of conditions and the following disclaimer.
10#  2. Redistributions in binary form must reproduce the above copyright
11#     notice, this list of conditions and the following disclaimer in the
12#     documentation and/or other materials provided with the distribution.
13#  3. Neither the name of the copyright holder nor the
14#     names of its contributors may be used to endorse or promote products
15#     derived from this software without specific prior written permission.
16#
17#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27#  POSSIBILITY OF SUCH DAMAGE.
28#
29import os
30from enum import Enum
31
32import coap
33import dtls
34import ipv6
35import lowpan
36import mesh_cop
37import message
38import mle
39import net_crypto
40import network_data
41import network_diag
42import network_layer
43import simulator
44import sniffer
45from tlvs_parsing import SubTlvsFactory
46
47# This extended address will generate the MESH_LOCAL_PREFIX
48EXTENDED_PANID = '000db80000000000'
49MESH_LOCAL_PREFIX = 'fd00:db8::/64'
50MESH_LOCAL_PREFIX_REGEX_PATTERN = '^fd00:0?db8:0{0,4}:0{0,4}'
51ROUTING_LOCATOR = '64/:0:ff:fe00:/16'
52ROUTING_LOCATOR_REGEX_PATTERN = r'.*:(0)?:0{0,2}ff:fe00:\w{1,4}$'
53LINK_LOCAL = 'fe80:/112'
54LINK_LOCAL_REGEX_PATTERN = '^fe80:.*'
55ALOC_FLAG_REGEX_PATTERN = '.*:fc..$'
56LINK_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS = 'ff32:40:fd00:db8:0:0:0:1'
57REALM_LOCAL_All_THREAD_NODES_MULTICAST_ADDRESS = 'ff33:40:fd00:db8:0:0:0:1'
58REALM_LOCAL_ALL_NODES_ADDRESS = 'ff03::1'
59REALM_LOCAL_ALL_ROUTERS_ADDRESS = 'ff03::2'
60LINK_LOCAL_ALL_NODES_ADDRESS = 'ff02::1'
61LINK_LOCAL_ALL_ROUTERS_ADDRESS = 'ff02::2'
62
63DOMAIN_PREFIX = 'fd00:7d03:7d03:7d03::/64'
64DOMAIN_PREFIX_REGEX_PATTERN = '^fd00:7d03:7d03:7d03:'
65DOMAIN_PREFIX_ALTER = 'fd00:7d04:7d04:7d04::/64'
66
67PORT_OFFSET = int(os.getenv('PORT_OFFSET', '0'))
68BACKBONE_PREFIX = f'{0x9100 + PORT_OFFSET:04x}::/64'
69BACKBONE_PREFIX_REGEX_PATTERN = f'^{0x9100 + PORT_OFFSET:04x}:'
70BACKBONE_DOCKER_NETWORK_NAME = f'backbone{PORT_OFFSET}'
71BACKBONE_IFNAME = 'eth0'
72
73OTBR_DOCKER_IMAGE = os.getenv('OTBR_DOCKER_IMAGE', 'otbr-ot12-backbone-ci')
74OTBR_DOCKER_NAME_PREFIX = f'otbr_{PORT_OFFSET}_'
75
76ALL_NETWORK_BBRS_ADDRESS = 'ff32:40:fd00:db8:0:0:0:3'
77
78ALL_DOMAIN_BBRS_ADDRESS = 'ff32:40:fd00:7d03:7d03:7d03:0:3'
79ALL_DOMAIN_BBRS_ADDRESS_ALTER = 'ff32:40:fd00:7d04:7d04:7d04:0:3'
80
81ONLINK_GUA_PREFIX = '2021::/64'
82
83# Any address starts with 'fd' are considered on-link address.
84ONLINK_PREFIX_REGEX_PATTERN = '^fd'
85
86DEFAULT_NETWORK_KEY = bytearray([
87    0x00,
88    0x11,
89    0x22,
90    0x33,
91    0x44,
92    0x55,
93    0x66,
94    0x77,
95    0x88,
96    0x99,
97    0xaa,
98    0xbb,
99    0xcc,
100    0xdd,
101    0xee,
102    0xff,
103])
104
105
106class ADDRESS_TYPE(Enum):
107    LINK_LOCAL = 'LINK_LOCAL'
108    GLOBAL = 'GLOBAL'
109    RLOC = 'RLOC'
110    ALOC = 'ALOC'
111    ML_EID = 'ML_EID'
112    DUA = 'DUA'
113    BACKBONE_GUA = 'BACKBONE_GUA'
114    OMR = 'OMR'
115    ONLINK_ULA = 'ONLINK_ULA'
116    ONLINK_GUA = 'ONLINK_GUA'
117
118
119RSSI = {
120    'LINK_QULITY_0': -100,
121    'LINK_QULITY_1': -95,
122    'LINK_QULITY_2': -85,
123    'LINK_QULITY_3': -65,
124}
125
126SNIFFER_ID = int(os.getenv('SNIFFER_ID', 34))
127PANID = 0xface
128
129MAX_NEIGHBOR_AGE = 100
130INFINITE_COST_TIMEOUT = 90
131
132MAX_ADVERTISEMENT_INTERVAL = 32
133MLE_END_DEVICE_TIMEOUT = 100
134
135AQ_TIMEOUT = 3
136ADDRESS_QUERY_INITIAL_RETRY_DELAY = 15
137DEFAULT_CHILD_TIMEOUT = 6
138VIRTUAL_TIME = int(os.getenv('VIRTUAL_TIME', 0))
139PARENT_AGGREGATIOIN_DELAY = 5
140DUA_DAD_DELAY = 5
141DEFAULT_BBR_REGISTRATION_JITTER = 2
142DEFAULT_ROUTER_SELECTION_JITTER = 1
143
144LEADER_NOTIFY_SED_BY_CHILD_UPDATE_REQUEST = True
145
146THREAD_VERSION_1_1 = 2
147THREAD_VERSION_1_2 = 3
148
149
150def create_default_network_data_prefix_sub_tlvs_factories():
151    return {
152        network_data.TlvType.HAS_ROUTE:
153            network_data.HasRouteFactory(routes_factory=network_data.RoutesFactory(
154                route_factory=network_data.RouteFactory())),
155        network_data.TlvType.BORDER_ROUTER:
156            network_data.BorderRouterFactory(),
157        network_data.TlvType.LOWPAN_ID:
158            network_data.LowpanIdFactory(),
159    }
160
161
162def create_default_network_data_prefix_sub_tlvs_factory():
163    return network_data.PrefixSubTlvsFactory(
164        sub_tlvs_factories=create_default_network_data_prefix_sub_tlvs_factories())
165
166
167def create_default_network_data_service_sub_tlvs_factories():
168    return {network_data.TlvType.SERVER: network_data.ServerFactory()}
169
170
171def create_default_network_data_service_sub_tlvs_factory():
172    return network_data.ServiceSubTlvsFactory(
173        sub_tlvs_factories=create_default_network_data_service_sub_tlvs_factories())
174
175
176def create_default_network_data_commissioning_data_sub_tlvs_factories():
177    return {
178        mesh_cop.TlvType.CHANNEL: mesh_cop.ChannelFactory(),
179        mesh_cop.TlvType.STEERING_DATA: mesh_cop.SteeringDataFactory(),
180        mesh_cop.TlvType.BORDER_AGENT_LOCATOR: mesh_cop.BorderAgentLocatorFactory(),
181        mesh_cop.TlvType.COMMISSIONER_SESSION_ID: mesh_cop.CommissionerSessionIdFactory(),
182        mesh_cop.TlvType.COMMISSIONER_UDP_PORT: mesh_cop.CommissionerUdpPortFactory(),
183    }
184
185
186def create_default_network_data_commissioning_data_sub_tlvs_factory():
187    return network_data.CommissioningDataSubTlvsFactory(
188        sub_tlvs_factories=create_default_network_data_commissioning_data_sub_tlvs_factories())
189
190
191def create_default_network_data_tlvs_factories():
192    return {
193        network_data.TlvType.PREFIX:
194            network_data.PrefixFactory(sub_tlvs_factory=create_default_network_data_prefix_sub_tlvs_factory()),
195        network_data.TlvType.SERVICE:
196            network_data.ServiceFactory(sub_tlvs_factory=create_default_network_data_service_sub_tlvs_factory()),
197        network_data.TlvType.COMMISSIONING:
198            network_data.CommissioningDataFactory(
199                sub_tlvs_factory=create_default_network_data_commissioning_data_sub_tlvs_factory()),
200    }
201
202
203def create_default_network_data_tlvs_factory():
204    return network_data.NetworkDataTlvsFactory(sub_tlvs_factories=create_default_network_data_tlvs_factories())
205
206
207def create_default_mle_tlv_route64_factory():
208    return mle.Route64Factory(link_quality_and_route_data_factory=mle.LinkQualityAndRouteDataFactory())
209
210
211def create_default_mle_tlv_network_data_factory():
212    return mle.NetworkDataFactory(network_data_tlvs_factory=create_default_network_data_tlvs_factory())
213
214
215def create_default_mle_tlv_address_registration_factory():
216    return mle.AddressRegistrationFactory(
217        addr_compressed_factory=mle.AddressCompressedFactory(),
218        addr_full_factory=mle.AddressFullFactory(),
219    )
220
221
222def create_default_mle_tlv_thread_discovery_factory():
223    return mle.ThreadDiscoveryFactory(thread_discovery_tlvs_factory=create_default_thread_discovery_tlvs_factory())
224
225
226def create_default_thread_discovery_tlvs_factory():
227    return mesh_cop.ThreadDiscoveryTlvsFactory(sub_tlvs_factories=create_default_thread_discovery_sub_tlvs_factories())
228
229
230def create_default_thread_discovery_sub_tlvs_factories():
231    return {
232        mesh_cop.TlvType.DISCOVERY_REQUEST: mesh_cop.DiscoveryRequestFactory(),
233        mesh_cop.TlvType.DISCOVERY_RESPONSE: mesh_cop.DiscoveryResponseFactory(),
234        mesh_cop.TlvType.EXTENDED_PANID: mesh_cop.ExtendedPanidFactory(),
235        mesh_cop.TlvType.NETWORK_NAME: mesh_cop.NetworkNameFactory(),
236        mesh_cop.TlvType.STEERING_DATA: mesh_cop.SteeringDataFactory(),
237        mesh_cop.TlvType.JOINER_UDP_PORT: mesh_cop.JoinerUdpPortFactory(),
238        mesh_cop.TlvType.COMMISSIONER_UDP_PORT: mesh_cop.CommissionerUdpPortFactory(),
239    }
240
241
242def create_default_mle_tlvs_factories():
243    return {
244        mle.TlvType.SOURCE_ADDRESS: mle.SourceAddressFactory(),
245        mle.TlvType.MODE: mle.ModeFactory(),
246        mle.TlvType.TIMEOUT: mle.TimeoutFactory(),
247        mle.TlvType.CHALLENGE: mle.ChallengeFactory(),
248        mle.TlvType.RESPONSE: mle.ResponseFactory(),
249        mle.TlvType.LINK_LAYER_FRAME_COUNTER: mle.LinkLayerFrameCounterFactory(),
250        mle.TlvType.MLE_FRAME_COUNTER: mle.MleFrameCounterFactory(),
251        mle.TlvType.ROUTE64: create_default_mle_tlv_route64_factory(),
252        mle.TlvType.ADDRESS16: mle.Address16Factory(),
253        mle.TlvType.LEADER_DATA: mle.LeaderDataFactory(),
254        mle.TlvType.NETWORK_DATA: create_default_mle_tlv_network_data_factory(),
255        mle.TlvType.TLV_REQUEST: mle.TlvRequestFactory(),
256        mle.TlvType.SCAN_MASK: mle.ScanMaskFactory(),
257        mle.TlvType.CONNECTIVITY: mle.ConnectivityFactory(),
258        mle.TlvType.LINK_MARGIN: mle.LinkMarginFactory(),
259        mle.TlvType.STATUS: mle.StatusFactory(),
260        mle.TlvType.VERSION: mle.VersionFactory(),
261        mle.TlvType.ADDRESS_REGISTRATION: create_default_mle_tlv_address_registration_factory(),
262        mle.TlvType.CHANNEL: mle.ChannelFactory(),
263        mle.TlvType.PANID: mle.PanIdFactory(),
264        mle.TlvType.ACTIVE_TIMESTAMP: mle.ActiveTimestampFactory(),
265        mle.TlvType.PENDING_TIMESTAMP: mle.PendingTimestampFactory(),
266        mle.TlvType.CSL_CHANNEL: mle.CslChannelFactory(),
267        mle.TlvType.CSL_SYNCHRONIZED_TIMEOUT: mle.CslSynchronizedTimeoutFactory(),
268        mle.TlvType.CSL_CLOCK_ACCURACY: mle.CslClockAccuracyFactory(),
269        mle.TlvType.ACTIVE_OPERATIONAL_DATASET: mle.ActiveOperationalDatasetFactory(),
270        mle.TlvType.PENDING_OPERATIONAL_DATASET: mle.PendingOperationalDatasetFactory(),
271        mle.TlvType.TIME_REQUEST: mle.TimeRequestFactory(),
272        mle.TlvType.TIME_PARAMETER: mle.TimeParameterFactory(),
273        mle.TlvType.THREAD_DISCOVERY: create_default_mle_tlv_thread_discovery_factory(),
274        mle.TlvType.LINK_METRICS_QUERY: mle.LinkMetricsQueryFactory(),
275        mle.TlvType.LINK_METRICS_MANAGEMENT: mle.LinkMetricsManagementFactory(),
276        mle.TlvType.LINK_METRICS_REPORT: mle.LinkMetricsReportFactory(),
277        mle.TlvType.LINK_PROBE: mle.LinkProbeFactory(),
278    }
279
280
281def create_default_mle_crypto_engine(network_key):
282    return net_crypto.CryptoEngine(crypto_material_creator=net_crypto.MleCryptoMaterialCreator(network_key))
283
284
285def create_default_mle_message_factory(network_key):
286    return mle.MleMessageFactory(
287        aux_sec_hdr_factory=net_crypto.AuxiliarySecurityHeaderFactory(),
288        mle_command_factory=mle.MleCommandFactory(tlvs_factories=create_default_mle_tlvs_factories()),
289        crypto_engine=create_default_mle_crypto_engine(network_key),
290    )
291
292
293def create_deafult_network_tlvs_factories():
294    return {
295        network_layer.TlvType.TARGET_EID:
296            network_layer.TargetEidFactory(),
297        network_layer.TlvType.MAC_EXTENDED_ADDRESS:
298            network_layer.MacExtendedAddressFactory(),
299        network_layer.TlvType.RLOC16:
300            network_layer.Rloc16Factory(),
301        network_layer.TlvType.ML_EID:
302            network_layer.MlEidFactory(),
303        network_layer.TlvType.STATUS:
304            network_layer.StatusFactory(),
305        network_layer.TlvType.TIME_SINCE_LAST_TRANSACTION:
306            network_layer.TimeSinceLastTransactionFactory(),
307        network_layer.TlvType.ROUTER_MASK:
308            network_layer.RouterMaskFactory(),
309        network_layer.TlvType.ND_OPTION:
310            network_layer.NdOptionFactory(),
311        network_layer.TlvType.ND_DATA:
312            network_layer.NdDataFactory(),
313        network_layer.TlvType.THREAD_NETWORK_DATA:
314            network_layer.ThreadNetworkDataFactory(create_default_network_data_tlvs_factory()),
315        network_layer.TlvType.XTAL_ACCURACY:
316            network_layer.XtalAccuracyFactory(),
317        # Routing information are distributed in a Thread network by MLE Routing TLV
318        # which is in fact MLE Route64 TLV. Thread specificaton v1.1. - Chapter 5.20
319        network_layer.TlvType.MLE_ROUTING:
320            create_default_mle_tlv_route64_factory(),
321        network_layer.TlvType.IPv6_ADDRESSES:
322            network_layer.IPv6AddressesFactory(),
323    }
324
325
326def create_default_network_tlvs_factory():
327    return SubTlvsFactory(sub_tlvs_factories=create_deafult_network_tlvs_factories())
328
329
330def create_default_mesh_cop_tlvs_factories():
331    return {
332        mesh_cop.TlvType.CHANNEL: mesh_cop.ChannelFactory(),
333        mesh_cop.TlvType.PAN_ID: mesh_cop.PanidFactory(),
334        mesh_cop.TlvType.EXTENDED_PANID: mesh_cop.ExtendedPanidFactory(),
335        mesh_cop.TlvType.NETWORK_NAME: mesh_cop.NetworkNameFactory(),
336        mesh_cop.TlvType.PSKC: mesh_cop.PSKcFactory(),
337        mesh_cop.TlvType.NETWORK_KEY: mesh_cop.NetworkKeyFactory(),
338        mesh_cop.TlvType.NETWORK_KEY_SEQUENCE_COUNTER: mesh_cop.NetworkKeySequenceCounterFactory(),
339        mesh_cop.TlvType.NETWORK_MESH_LOCAL_PREFIX: mesh_cop.NetworkMeshLocalPrefixFactory(),
340        mesh_cop.TlvType.STEERING_DATA: mesh_cop.SteeringDataFactory(),
341        mesh_cop.TlvType.BORDER_AGENT_LOCATOR: mesh_cop.BorderAgentLocatorFactory(),
342        mesh_cop.TlvType.COMMISSIONER_ID: mesh_cop.CommissionerIdFactory(),
343        mesh_cop.TlvType.COMMISSIONER_SESSION_ID: mesh_cop.CommissionerSessionIdFactory(),
344        mesh_cop.TlvType.SECURITY_POLICY: mesh_cop.SecurityPolicyFactory(),
345        mesh_cop.TlvType.GET: mesh_cop.GetFactory(),
346        mesh_cop.TlvType.ACTIVE_TIMESTAMP: mesh_cop.ActiveTimestampFactory(),
347        mesh_cop.TlvType.COMMISSIONER_UDP_PORT: mesh_cop.CommissionerUdpPortFactory(),
348        mesh_cop.TlvType.STATE: mesh_cop.StateFactory(),
349        mesh_cop.TlvType.JOINER_DTLS_ENCAPSULATION: mesh_cop.JoinerDtlsEncapsulationFactory(),
350        mesh_cop.TlvType.JOINER_UDP_PORT: mesh_cop.JoinerUdpPortFactory(),
351        mesh_cop.TlvType.JOINER_IID: mesh_cop.JoinerIIDFactory(),
352        mesh_cop.TlvType.JOINER_ROUTER_LOCATOR: mesh_cop.JoinerRouterLocatorFactory(),
353        mesh_cop.TlvType.JOINER_ROUTER_KEK: mesh_cop.JoinerRouterKEKFactory(),
354        mesh_cop.TlvType.PROVISIONING_URL: mesh_cop.ProvisioningUrlFactory(),
355        mesh_cop.TlvType.VENDOR_NAME: mesh_cop.VendorNameFactory(),
356        mesh_cop.TlvType.VENDOR_MODEL: mesh_cop.VendorModelFactory(),
357        mesh_cop.TlvType.VENDOR_SW_VERSION: mesh_cop.VendorSWVersionFactory(),
358        mesh_cop.TlvType.VENDOR_DATA: mesh_cop.VendorDataFactory(),
359        mesh_cop.TlvType.VENDOR_STACK_VERSION: mesh_cop.VendorStackVersionFactory(),
360        mesh_cop.TlvType.UDP_ENCAPSULATION: mesh_cop.UdpEncapsulationFactory(),
361        mesh_cop.TlvType.IPV6_ADDRESS: mesh_cop.Ipv6AddressFactory(),
362        mesh_cop.TlvType.PENDING_TIMESTAMP: mesh_cop.PendingTimestampFactory(),
363        mesh_cop.TlvType.DELAY_TIMER: mesh_cop.DelayTimerFactory(),
364        mesh_cop.TlvType.CHANNEL_MASK: mesh_cop.ChannelMaskFactory(),
365        mesh_cop.TlvType.COUNT: mesh_cop.CountFactory(),
366        mesh_cop.TlvType.PERIOD: mesh_cop.PeriodFactory(),
367        mesh_cop.TlvType.SCAN_DURATION: mesh_cop.ScanDurationFactory(),
368        mesh_cop.TlvType.ENERGY_LIST: mesh_cop.EnergyListFactory(),
369    }
370
371
372def create_default_mesh_cop_tlvs_factory():
373    return SubTlvsFactory(sub_tlvs_factories=create_default_mesh_cop_tlvs_factories())
374
375
376def create_default_network_diag_tlv_factories():
377    return {
378        network_diag.TlvType.EXT_ADDRESS: network_layer.MacExtendedAddressFactory(),
379        network_diag.TlvType.ADDRESS16: mle.Address16Factory(),
380        network_diag.TlvType.MODE: mle.ModeFactory(),
381        network_diag.TlvType.POLLING_PERIOD: mle.TimeoutFactory(),
382        network_diag.TlvType.CONNECTIVITY: mle.ConnectivityFactory(),
383        network_diag.TlvType.ROUTE64: create_default_mle_tlv_route64_factory(),
384        network_diag.TlvType.LEADER_DATA: mle.LeaderDataFactory(),
385        network_diag.TlvType.NETWORK_DATA: create_default_mle_tlv_network_data_factory(),
386        network_diag.TlvType.IPV6_ADDRESS_LIST: network_diag.Ipv6AddressListFactory(),
387        network_diag.TlvType.MAC_COUNTERS: network_diag.MacCountersFactory(),
388        network_diag.TlvType.BATTERY_LEVEL: network_diag.BatteryLevelFactory(),
389        network_diag.TlvType.SUPPLY_VOLTAGE: network_diag.SupplyVoltageFactory(),
390        network_diag.TlvType.CHILD_TABLE: network_diag.ChildTableFactory(),
391        network_diag.TlvType.CHANNEL_PAGES: network_diag.ChannelPagesFactory(),
392        network_diag.TlvType.TYPE_LIST: network_diag.TypeListFactory(),
393        network_diag.TlvType.MAX_CHILD_TIMEOUT: network_diag.MaxChildTimeoutFactory()
394    }
395
396
397def create_default_network_diag_tlvs_factory():
398    return SubTlvsFactory(sub_tlvs_factories=create_default_network_diag_tlv_factories())
399
400
401def create_default_uri_path_based_payload_factories():
402    network_layer_tlvs_factory = create_default_network_tlvs_factory()
403    mesh_cop_tlvs_factory = create_default_mesh_cop_tlvs_factory()
404    network_diag_tlvs_factory = create_default_network_diag_tlvs_factory()
405
406    return {
407        '/a/as': network_layer_tlvs_factory,
408        '/a/aq': network_layer_tlvs_factory,
409        '/a/ar': network_layer_tlvs_factory,
410        '/a/ae': network_layer_tlvs_factory,
411        '/a/an': network_layer_tlvs_factory,
412        '/a/sd': network_layer_tlvs_factory,
413        '/c/lp': mesh_cop_tlvs_factory,
414        '/c/cs': mesh_cop_tlvs_factory,
415        '/d/da': network_diag_tlvs_factory,
416        '/d/dg': network_diag_tlvs_factory,
417        '/d/dq': network_diag_tlvs_factory,
418        '/d/dr': network_diag_tlvs_factory,
419        '/n/mr': network_layer_tlvs_factory,
420        '/n/dr': network_layer_tlvs_factory,
421        '/n/dn': network_layer_tlvs_factory,
422    }
423
424
425def create_default_coap_message_factory():
426    return coap.CoapMessageFactory(
427        options_factory=coap.CoapOptionsFactory(),
428        uri_path_based_payload_factories=create_default_uri_path_based_payload_factories(),
429        message_id_to_uri_path_binder=coap.CoapMessageIdToUriPathBinder(),
430    )
431
432
433def create_default_ipv6_hop_by_hop_options_factories():
434    return {109: ipv6.MPLOptionFactory()}
435
436
437def create_default_ipv6_hop_by_hop_options_factory():
438    return ipv6.HopByHopOptionsFactory(options_factories=create_default_ipv6_hop_by_hop_options_factories())
439
440
441def create_default_based_on_src_dst_ports_udp_payload_factory(network_key):
442    mle_message_factory = create_default_mle_message_factory(network_key)
443    coap_message_factory = create_default_coap_message_factory()
444    dtls_message_factory = create_default_dtls_message_factory()
445
446    return ipv6.UdpBasedOnSrcDstPortsPayloadFactory(
447        src_dst_port_based_payload_factories={
448            19788: mle_message_factory,
449            61631: coap_message_factory,
450            1000: dtls_message_factory,
451            5683: coap_message_factory,
452            5684: dtls_message_factory,
453        })
454
455
456def create_default_dtls_message_factory():
457    return dtls.MessageFactory()
458
459
460def create_default_ipv6_icmp_body_factories():
461    return {
462        ipv6.ICMP_DESTINATION_UNREACHABLE: ipv6.ICMPv6DestinationUnreachableFactory(),
463        ipv6.ICMP_ECHO_REQUEST: ipv6.ICMPv6EchoBodyFactory(),
464        ipv6.ICMP_ECHO_RESPONSE: ipv6.ICMPv6EchoBodyFactory(),
465        'default': ipv6.BytesPayloadFactory(),
466    }
467
468
469def create_default_ipv6_upper_layer_factories(network_key):
470    return {
471        ipv6.IPV6_NEXT_HEADER_UDP:
472            ipv6.UDPDatagramFactory(
473                udp_header_factory=ipv6.UDPHeaderFactory(),
474                udp_payload_factory=create_default_based_on_src_dst_ports_udp_payload_factory(network_key),
475            ),
476        ipv6.IPV6_NEXT_HEADER_ICMP:
477            ipv6.ICMPv6Factory(body_factories=create_default_ipv6_icmp_body_factories()),
478    }
479
480
481def create_default_lowpan_extension_headers_factories():
482    return {
483        ipv6.IPV6_NEXT_HEADER_HOP_BY_HOP:
484            lowpan.LowpanHopByHopFactory(hop_by_hop_options_factory=create_default_ipv6_hop_by_hop_options_factory())
485    }
486
487
488def create_default_ipv6_extension_headers_factories():
489    return {
490        ipv6.IPV6_NEXT_HEADER_HOP_BY_HOP:
491            ipv6.HopByHopFactory(hop_by_hop_options_factory=create_default_ipv6_hop_by_hop_options_factory())
492    }
493
494
495def create_default_ipv6_packet_factory(network_key):
496    return ipv6.IPv6PacketFactory(
497        ehf=create_default_ipv6_extension_headers_factories(),
498        ulpf=create_default_ipv6_upper_layer_factories(network_key),
499    )
500
501
502def create_default_lowpan_decompressor(context_manager):
503    return lowpan.LowpanDecompressor(
504        lowpan_ip_header_factory=lowpan.LowpanIpv6HeaderFactory(context_manager=context_manager),
505        lowpan_extension_headers_factory=lowpan.LowpanExtensionHeadersFactory(
506            ext_headers_factories=create_default_lowpan_extension_headers_factories()),
507        lowpan_udp_header_factory=lowpan.LowpanUdpHeaderFactory(),
508    )
509
510
511def create_default_thread_context_manager():
512    context_manager = lowpan.ContextManager()
513    context_manager[0] = lowpan.Context(MESH_LOCAL_PREFIX)
514
515    return context_manager
516
517
518def create_default_lowpan_parser(context_manager, network_key=DEFAULT_NETWORK_KEY):
519    return lowpan.LowpanParser(
520        lowpan_mesh_header_factory=lowpan.LowpanMeshHeaderFactory(),
521        lowpan_decompressor=create_default_lowpan_decompressor(context_manager),
522        lowpan_fragements_buffers_manager=lowpan.LowpanFragmentsBuffersManager(),
523        ipv6_packet_factory=create_default_ipv6_packet_factory(network_key),
524    )
525
526
527def create_default_thread_message_factory(network_key=DEFAULT_NETWORK_KEY):
528    context_manager = create_default_thread_context_manager()
529    lowpan_parser = create_default_lowpan_parser(context_manager, network_key)
530
531    return message.MessageFactory(lowpan_parser=lowpan_parser)
532
533
534def create_default_thread_sniffer(use_message_factory=True):
535    return sniffer.Sniffer(create_default_thread_message_factory() if use_message_factory else None)
536
537
538def create_default_simulator(use_message_factory=True):
539    if VIRTUAL_TIME:
540        return simulator.VirtualTime(use_message_factory=use_message_factory)
541    return simulator.RealTime(use_message_factory=use_message_factory)
542