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