pypcapkit 1.6.2__pp312-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (770) hide show
  1. pcapkit/__init__.py +107 -0
  2. pcapkit/__main__.py +158 -0
  3. pcapkit/all.py +168 -0
  4. pcapkit/const/__init__.py +143 -0
  5. pcapkit/const/arp/__init__.py +35 -0
  6. pcapkit/const/arp/hardware.py +195 -0
  7. pcapkit/const/arp/operation.py +145 -0
  8. pcapkit/const/dccp/__init__.py +58 -0
  9. pcapkit/const/dccp/ack_vector_state.py +73 -0
  10. pcapkit/const/dccp/drop_code.py +79 -0
  11. pcapkit/const/dccp/feature.py +106 -0
  12. pcapkit/const/dccp/option.py +133 -0
  13. pcapkit/const/dccp/packet_type.py +103 -0
  14. pcapkit/const/dccp/reset_code.py +115 -0
  15. pcapkit/const/esp/__init__.py +49 -0
  16. pcapkit/const/esp/cipher.py +265 -0
  17. pcapkit/const/esp/integrity.py +154 -0
  18. pcapkit/const/ftp/__init__.py +35 -0
  19. pcapkit/const/ftp/command.py +659 -0
  20. pcapkit/const/ftp/return_code.py +409 -0
  21. pcapkit/const/hip/__init__.py +121 -0
  22. pcapkit/const/hip/certificate.py +91 -0
  23. pcapkit/const/hip/cipher.py +79 -0
  24. pcapkit/const/hip/di.py +73 -0
  25. pcapkit/const/hip/ecdsa_curve.py +73 -0
  26. pcapkit/const/hip/ecdsa_low_curve.py +70 -0
  27. pcapkit/const/hip/eddsa_curve.py +79 -0
  28. pcapkit/const/hip/esp_transform_suite.py +112 -0
  29. pcapkit/const/hip/group.py +100 -0
  30. pcapkit/const/hip/hi_algorithm.py +100 -0
  31. pcapkit/const/hip/hit_suite.py +82 -0
  32. pcapkit/const/hip/nat_traversal.py +76 -0
  33. pcapkit/const/hip/notify_message.py +214 -0
  34. pcapkit/const/hip/packet.py +103 -0
  35. pcapkit/const/hip/parameter.py +391 -0
  36. pcapkit/const/hip/registration.py +82 -0
  37. pcapkit/const/hip/registration_failure.py +98 -0
  38. pcapkit/const/hip/suite.py +85 -0
  39. pcapkit/const/hip/transport.py +73 -0
  40. pcapkit/const/http/__init__.py +52 -0
  41. pcapkit/const/http/error_code.py +108 -0
  42. pcapkit/const/http/frame.py +109 -0
  43. pcapkit/const/http/method.py +329 -0
  44. pcapkit/const/http/setting.py +110 -0
  45. pcapkit/const/http/status_code.py +347 -0
  46. pcapkit/const/icmp/__init__.py +52 -0
  47. pcapkit/const/icmp/destination_unreachable_code.py +111 -0
  48. pcapkit/const/icmp/parameter_problem_code.py +70 -0
  49. pcapkit/const/icmp/time_exceeded_code.py +67 -0
  50. pcapkit/const/icmp/type.py +179 -0
  51. pcapkit/const/icmpv6/__init__.py +52 -0
  52. pcapkit/const/icmpv6/destination_unreachable_code.py +91 -0
  53. pcapkit/const/icmpv6/parameter_problem_code.py +94 -0
  54. pcapkit/const/icmpv6/time_exceeded_code.py +67 -0
  55. pcapkit/const/icmpv6/type.py +209 -0
  56. pcapkit/const/ieee802_11/__init__.py +52 -0
  57. pcapkit/const/ieee802_11/control_subtype.py +106 -0
  58. pcapkit/const/ieee802_11/data_subtype.py +97 -0
  59. pcapkit/const/ieee802_11/extension_subtype.py +70 -0
  60. pcapkit/const/ieee802_11/management_subtype.py +109 -0
  61. pcapkit/const/ieee802_11/type.py +73 -0
  62. pcapkit/const/igmp/__init__.py +37 -0
  63. pcapkit/const/igmp/record_type.py +73 -0
  64. pcapkit/const/igmp/type.py +112 -0
  65. pcapkit/const/ipv4/__init__.py +79 -0
  66. pcapkit/const/ipv4/classification_level.py +77 -0
  67. pcapkit/const/ipv4/option_class.py +69 -0
  68. pcapkit/const/ipv4/option_number.py +151 -0
  69. pcapkit/const/ipv4/protection_authority.py +77 -0
  70. pcapkit/const/ipv4/qs_function.py +65 -0
  71. pcapkit/const/ipv4/router_alert.py +268 -0
  72. pcapkit/const/ipv4/tos_del.py +65 -0
  73. pcapkit/const/ipv4/tos_ecn.py +69 -0
  74. pcapkit/const/ipv4/tos_pre.py +77 -0
  75. pcapkit/const/ipv4/tos_rel.py +65 -0
  76. pcapkit/const/ipv4/tos_thr.py +65 -0
  77. pcapkit/const/ipv4/ts_flag.py +67 -0
  78. pcapkit/const/ipv6/__init__.py +70 -0
  79. pcapkit/const/ipv6/extension_header.py +86 -0
  80. pcapkit/const/ipv6/option.py +151 -0
  81. pcapkit/const/ipv6/option_action.py +69 -0
  82. pcapkit/const/ipv6/qs_function.py +65 -0
  83. pcapkit/const/ipv6/router_alert.py +280 -0
  84. pcapkit/const/ipv6/routing.py +94 -0
  85. pcapkit/const/ipv6/seed_id.py +69 -0
  86. pcapkit/const/ipv6/smf_dpd_mode.py +65 -0
  87. pcapkit/const/ipv6/tagger_id.py +76 -0
  88. pcapkit/const/ipx/__init__.py +37 -0
  89. pcapkit/const/ipx/packet.py +86 -0
  90. pcapkit/const/ipx/socket.py +121 -0
  91. pcapkit/const/l2tp/__init__.py +30 -0
  92. pcapkit/const/l2tp/type.py +65 -0
  93. pcapkit/const/linux/__init__.py +28 -0
  94. pcapkit/const/linux/arphrd.py +91 -0
  95. pcapkit/const/mh/__init__.py +259 -0
  96. pcapkit/const/mh/access_type.py +106 -0
  97. pcapkit/const/mh/ack_status_code.py +85 -0
  98. pcapkit/const/mh/ani_suboption.py +88 -0
  99. pcapkit/const/mh/auth_subtype.py +67 -0
  100. pcapkit/const/mh/binding_ack_flag.py +82 -0
  101. pcapkit/const/mh/binding_error.py +65 -0
  102. pcapkit/const/mh/binding_revocation.py +73 -0
  103. pcapkit/const/mh/binding_update_flag.py +97 -0
  104. pcapkit/const/mh/cga_extension.py +80 -0
  105. pcapkit/const/mh/cga_sec.py +71 -0
  106. pcapkit/const/mh/cga_type.py +82 -0
  107. pcapkit/const/mh/dhcp_support_mode.py +67 -0
  108. pcapkit/const/mh/dns_status_code.py +79 -0
  109. pcapkit/const/mh/dsmip6_tls_packet.py +76 -0
  110. pcapkit/const/mh/dsmipv6_home_address.py +88 -0
  111. pcapkit/const/mh/enumerating_algorithm.py +70 -0
  112. pcapkit/const/mh/fb_ack_status.py +76 -0
  113. pcapkit/const/mh/fb_action.py +85 -0
  114. pcapkit/const/mh/fb_indication_trigger.py +79 -0
  115. pcapkit/const/mh/fb_type.py +73 -0
  116. pcapkit/const/mh/flow_id_status.py +91 -0
  117. pcapkit/const/mh/flow_id_suboption.py +85 -0
  118. pcapkit/const/mh/handoff_type.py +85 -0
  119. pcapkit/const/mh/handover_ack_flag.py +70 -0
  120. pcapkit/const/mh/handover_ack_status.py +106 -0
  121. pcapkit/const/mh/handover_initiate_flag.py +73 -0
  122. pcapkit/const/mh/handover_initiate_status.py +76 -0
  123. pcapkit/const/mh/home_address_reply.py +85 -0
  124. pcapkit/const/mh/lla_code.py +77 -0
  125. pcapkit/const/mh/lma_mag_suboption.py +73 -0
  126. pcapkit/const/mh/mn_group_id.py +73 -0
  127. pcapkit/const/mh/mn_id_subtype.py +91 -0
  128. pcapkit/const/mh/operator_id.py +77 -0
  129. pcapkit/const/mh/option.py +274 -0
  130. pcapkit/const/mh/packet.py +133 -0
  131. pcapkit/const/mh/qos_attribute.py +103 -0
  132. pcapkit/const/mh/revocation_status_code.py +97 -0
  133. pcapkit/const/mh/revocation_trigger.py +100 -0
  134. pcapkit/const/mh/status_code.py +246 -0
  135. pcapkit/const/mh/traffic_selector.py +76 -0
  136. pcapkit/const/mh/upa_status.py +85 -0
  137. pcapkit/const/mh/upn_reason.py +94 -0
  138. pcapkit/const/ngap/__init__.py +44 -0
  139. pcapkit/const/ngap/procedure_code.py +223 -0
  140. pcapkit/const/ngap/protocol_ie.py +937 -0
  141. pcapkit/const/ospf/__init__.py +37 -0
  142. pcapkit/const/ospf/authentication.py +79 -0
  143. pcapkit/const/ospf/packet.py +85 -0
  144. pcapkit/const/pcapng/__init__.py +71 -0
  145. pcapkit/const/pcapng/block_type.py +166 -0
  146. pcapkit/const/pcapng/filter_type.py +62 -0
  147. pcapkit/const/pcapng/hash_algorithm.py +73 -0
  148. pcapkit/const/pcapng/option_type.py +422 -0
  149. pcapkit/const/pcapng/record_type.py +70 -0
  150. pcapkit/const/pcapng/secrets_type.py +69 -0
  151. pcapkit/const/pcapng/tls_key_label.py +89 -0
  152. pcapkit/const/pcapng/verdict_type.py +67 -0
  153. pcapkit/const/radiotap/__init__.py +116 -0
  154. pcapkit/const/radiotap/ampdu_flags.py +85 -0
  155. pcapkit/const/radiotap/channel_flags.py +94 -0
  156. pcapkit/const/radiotap/eht_known.py +124 -0
  157. pcapkit/const/radiotap/field_type.py +165 -0
  158. pcapkit/const/radiotap/flags.py +85 -0
  159. pcapkit/const/radiotap/he_data1_known.py +103 -0
  160. pcapkit/const/radiotap/he_data2_known.py +88 -0
  161. pcapkit/const/radiotap/he_mu_flags1_known.py +85 -0
  162. pcapkit/const/radiotap/he_mu_flags2_known.py +67 -0
  163. pcapkit/const/radiotap/he_mu_other_user_known.py +85 -0
  164. pcapkit/const/radiotap/lsig_data1.py +67 -0
  165. pcapkit/const/radiotap/mcs_known.py +85 -0
  166. pcapkit/const/radiotap/rx_flags.py +64 -0
  167. pcapkit/const/radiotap/s1g_known.py +85 -0
  168. pcapkit/const/radiotap/timestamp_flags.py +67 -0
  169. pcapkit/const/radiotap/tx_flags.py +82 -0
  170. pcapkit/const/radiotap/usig_common_known.py +85 -0
  171. pcapkit/const/radiotap/vht_coding.py +73 -0
  172. pcapkit/const/radiotap/vht_flags.py +84 -0
  173. pcapkit/const/radiotap/vht_known.py +90 -0
  174. pcapkit/const/reg/__init__.py +54 -0
  175. pcapkit/const/reg/apptype/__init__.py +164 -0
  176. pcapkit/const/reg/apptype/apptype.py +5233 -0
  177. pcapkit/const/reg/apptype/dccp.py +112 -0
  178. pcapkit/const/reg/apptype/sctp.py +432 -0
  179. pcapkit/const/reg/apptype/tcp.py +25154 -0
  180. pcapkit/const/reg/apptype/udp.py +24563 -0
  181. pcapkit/const/reg/ethertype.py +740 -0
  182. pcapkit/const/reg/linktype.py +811 -0
  183. pcapkit/const/reg/transtype.py +552 -0
  184. pcapkit/const/sctp/__init__.py +49 -0
  185. pcapkit/const/sctp/cause_code.py +146 -0
  186. pcapkit/const/sctp/chunk.py +164 -0
  187. pcapkit/const/sctp/parameter.py +170 -0
  188. pcapkit/const/sctp/payload_protocol_identifier.py +325 -0
  189. pcapkit/const/sslv2/__init__.py +37 -0
  190. pcapkit/const/sslv2/handshake_type.py +88 -0
  191. pcapkit/const/sslv2/version.py +64 -0
  192. pcapkit/const/tcp/__init__.py +47 -0
  193. pcapkit/const/tcp/checksum.py +69 -0
  194. pcapkit/const/tcp/flags.py +96 -0
  195. pcapkit/const/tcp/mp_tcp_option.py +95 -0
  196. pcapkit/const/tcp/option.py +210 -0
  197. pcapkit/const/tls/__init__.py +44 -0
  198. pcapkit/const/tls/content_type.py +99 -0
  199. pcapkit/const/tls/extension_type.py +382 -0
  200. pcapkit/const/tls/handshake_type.py +154 -0
  201. pcapkit/const/vlan/__init__.py +32 -0
  202. pcapkit/const/vlan/priority_level.py +85 -0
  203. pcapkit/corekit/__init__.py +64 -0
  204. pcapkit/corekit/checksum/__init__.py +24 -0
  205. pcapkit/corekit/checksum/internet.py +253 -0
  206. pcapkit/corekit/context.py +248 -0
  207. pcapkit/corekit/decorators.py +328 -0
  208. pcapkit/corekit/enum.py +742 -0
  209. pcapkit/corekit/fields/__init__.py +46 -0
  210. pcapkit/corekit/fields/collections.py +646 -0
  211. pcapkit/corekit/fields/field.py +643 -0
  212. pcapkit/corekit/fields/ipaddress.py +582 -0
  213. pcapkit/corekit/fields/misc.py +843 -0
  214. pcapkit/corekit/fields/numbers.py +1279 -0
  215. pcapkit/corekit/fields/strings.py +445 -0
  216. pcapkit/corekit/infoclass.py +1231 -0
  217. pcapkit/corekit/io.py +980 -0
  218. pcapkit/corekit/module.py +133 -0
  219. pcapkit/corekit/multidict.py +676 -0
  220. pcapkit/corekit/packet.py +179 -0
  221. pcapkit/corekit/protochain.py +266 -0
  222. pcapkit/corekit/schema/__init__.py +20 -0
  223. pcapkit/corekit/schema/byteorder.py +89 -0
  224. pcapkit/corekit/schema/ipaddress.py +210 -0
  225. pcapkit/corekit/schema/jumbogram.py +66 -0
  226. pcapkit/corekit/schema/padding.py +50 -0
  227. pcapkit/corekit/schema/shortread.py +150 -0
  228. pcapkit/corekit/sentinels.py +597 -0
  229. pcapkit/corekit/version.py +40 -0
  230. pcapkit/dumpkit/__init__.py +14 -0
  231. pcapkit/dumpkit/common.py +778 -0
  232. pcapkit/dumpkit/null.py +72 -0
  233. pcapkit/dumpkit/pcap.py +292 -0
  234. pcapkit/foundation/__init__.py +63 -0
  235. pcapkit/foundation/analysis/__init__.py +27 -0
  236. pcapkit/foundation/analysis/dtls.py +61 -0
  237. pcapkit/foundation/analysis/ip.py +88 -0
  238. pcapkit/foundation/analysis/tcp.py +87 -0
  239. pcapkit/foundation/engines/__init__.py +35 -0
  240. pcapkit/foundation/engines/_pcap_backend.py +358 -0
  241. pcapkit/foundation/engines/dpkt.py +680 -0
  242. pcapkit/foundation/engines/engine.py +318 -0
  243. pcapkit/foundation/engines/pcap.py +259 -0
  244. pcapkit/foundation/engines/pcap_ct.py +469 -0
  245. pcapkit/foundation/engines/pcapng.py +513 -0
  246. pcapkit/foundation/engines/pypcap.py +386 -0
  247. pcapkit/foundation/engines/pypcapfile.py +477 -0
  248. pcapkit/foundation/engines/pyshark.py +374 -0
  249. pcapkit/foundation/engines/scapy.py +451 -0
  250. pcapkit/foundation/extraction.py +1833 -0
  251. pcapkit/foundation/reassembly/__init__.py +55 -0
  252. pcapkit/foundation/reassembly/data/__init__.py +43 -0
  253. pcapkit/foundation/reassembly/data/data.py +300 -0
  254. pcapkit/foundation/reassembly/data/dtls.py +186 -0
  255. pcapkit/foundation/reassembly/data/ip.py +203 -0
  256. pcapkit/foundation/reassembly/data/tcp.py +296 -0
  257. pcapkit/foundation/reassembly/dtls.py +340 -0
  258. pcapkit/foundation/reassembly/ip.py +639 -0
  259. pcapkit/foundation/reassembly/ipv4.py +80 -0
  260. pcapkit/foundation/reassembly/ipv6.py +206 -0
  261. pcapkit/foundation/reassembly/reassembly.py +605 -0
  262. pcapkit/foundation/reassembly/tcp.py +870 -0
  263. pcapkit/foundation/registry/__init__.py +56 -0
  264. pcapkit/foundation/registry/foundation.py +362 -0
  265. pcapkit/foundation/registry/protocols/__init__.py +67 -0
  266. pcapkit/foundation/registry/protocols/application.py +119 -0
  267. pcapkit/foundation/registry/protocols/internet.py +506 -0
  268. pcapkit/foundation/registry/protocols/link.py +378 -0
  269. pcapkit/foundation/registry/protocols/misc.py +352 -0
  270. pcapkit/foundation/registry/protocols/protocol.py +519 -0
  271. pcapkit/foundation/registry/protocols/transport.py +647 -0
  272. pcapkit/foundation/traceflow/__init__.py +45 -0
  273. pcapkit/foundation/traceflow/data/__init__.py +17 -0
  274. pcapkit/foundation/traceflow/data/data.py +193 -0
  275. pcapkit/foundation/traceflow/data/tcp.py +212 -0
  276. pcapkit/foundation/traceflow/tcp.py +581 -0
  277. pcapkit/foundation/traceflow/traceflow.py +593 -0
  278. pcapkit/interface/__init__.py +23 -0
  279. pcapkit/interface/core.py +265 -0
  280. pcapkit/interface/misc.py +186 -0
  281. pcapkit/interface/registry.py +116 -0
  282. pcapkit/protocols/__init__.py +95 -0
  283. pcapkit/protocols/application/NotImplemented/bgp.py +0 -0
  284. pcapkit/protocols/application/NotImplemented/dhcp.py +0 -0
  285. pcapkit/protocols/application/NotImplemented/dhcpv6.py +0 -0
  286. pcapkit/protocols/application/NotImplemented/dns.py +0 -0
  287. pcapkit/protocols/application/NotImplemented/imap.py +0 -0
  288. pcapkit/protocols/application/NotImplemented/ldap.py +0 -0
  289. pcapkit/protocols/application/NotImplemented/mqtt.py +0 -0
  290. pcapkit/protocols/application/NotImplemented/nntp.py +0 -0
  291. pcapkit/protocols/application/NotImplemented/ntp.py +0 -0
  292. pcapkit/protocols/application/NotImplemented/onc_rpc.py +0 -0
  293. pcapkit/protocols/application/NotImplemented/pop.py +0 -0
  294. pcapkit/protocols/application/NotImplemented/rip.py +0 -0
  295. pcapkit/protocols/application/NotImplemented/rtp.py +0 -0
  296. pcapkit/protocols/application/NotImplemented/sip.py +0 -0
  297. pcapkit/protocols/application/NotImplemented/smtp.py +0 -0
  298. pcapkit/protocols/application/NotImplemented/snmp.py +0 -0
  299. pcapkit/protocols/application/NotImplemented/ssh.py +0 -0
  300. pcapkit/protocols/application/NotImplemented/telnet.py +0 -0
  301. pcapkit/protocols/application/NotImplemented/xmpp.py +0 -0
  302. pcapkit/protocols/application/__init__.py +79 -0
  303. pcapkit/protocols/application/application.py +189 -0
  304. pcapkit/protocols/application/drarp/__init__.py +14 -0
  305. pcapkit/protocols/application/drarp/protocol.py +53 -0
  306. pcapkit/protocols/application/dtls/__init__.py +30 -0
  307. pcapkit/protocols/application/dtls/data.py +150 -0
  308. pcapkit/protocols/application/dtls/protocol.py +1137 -0
  309. pcapkit/protocols/application/dtls/schema.py +157 -0
  310. pcapkit/protocols/application/ftp/__init__.py +27 -0
  311. pcapkit/protocols/application/ftp/data.py +72 -0
  312. pcapkit/protocols/application/ftp/protocol.py +410 -0
  313. pcapkit/protocols/application/ftp/schema.py +21 -0
  314. pcapkit/protocols/application/ftp_data/__init__.py +14 -0
  315. pcapkit/protocols/application/ftp_data/protocol.py +97 -0
  316. pcapkit/protocols/application/http/__init__.py +14 -0
  317. pcapkit/protocols/application/http/protocol.py +773 -0
  318. pcapkit/protocols/application/httpv1/__init__.py +28 -0
  319. pcapkit/protocols/application/httpv1/data.py +98 -0
  320. pcapkit/protocols/application/httpv1/protocol.py +610 -0
  321. pcapkit/protocols/application/httpv1/schema.py +29 -0
  322. pcapkit/protocols/application/httpv2/__init__.py +61 -0
  323. pcapkit/protocols/application/httpv2/data.py +347 -0
  324. pcapkit/protocols/application/httpv2/protocol.py +1724 -0
  325. pcapkit/protocols/application/httpv2/schema.py +430 -0
  326. pcapkit/protocols/application/ngap/__init__.py +29 -0
  327. pcapkit/protocols/application/ngap/data.py +124 -0
  328. pcapkit/protocols/application/ngap/protocol.py +578 -0
  329. pcapkit/protocols/application/ngap/schema.py +29 -0
  330. pcapkit/protocols/application/ospf/__init__.py +29 -0
  331. pcapkit/protocols/application/ospf/data.py +79 -0
  332. pcapkit/protocols/application/ospf/protocol.py +544 -0
  333. pcapkit/protocols/application/ospf/schema.py +109 -0
  334. pcapkit/protocols/application/rarp/__init__.py +14 -0
  335. pcapkit/protocols/application/rarp/protocol.py +111 -0
  336. pcapkit/protocols/application/ssl/__init__.py +43 -0
  337. pcapkit/protocols/application/ssl/data.py +322 -0
  338. pcapkit/protocols/application/ssl/protocol.py +1522 -0
  339. pcapkit/protocols/application/sslv2/__init__.py +32 -0
  340. pcapkit/protocols/application/sslv2/data.py +93 -0
  341. pcapkit/protocols/application/sslv2/protocol.py +543 -0
  342. pcapkit/protocols/application/sslv2/schema.py +304 -0
  343. pcapkit/protocols/application/sslv3/__init__.py +14 -0
  344. pcapkit/protocols/application/sslv3/protocol.py +51 -0
  345. pcapkit/protocols/application/tls/__init__.py +25 -0
  346. pcapkit/protocols/application/tls/data.py +40 -0
  347. pcapkit/protocols/application/tls/protocol.py +561 -0
  348. pcapkit/protocols/application/tls/schema.py +44 -0
  349. pcapkit/protocols/data.py +76 -0
  350. pcapkit/protocols/internet/NotImplemented/ecn.py +0 -0
  351. pcapkit/protocols/internet/NotImplemented/shim6.py +0 -0
  352. pcapkit/protocols/internet/__init__.py +87 -0
  353. pcapkit/protocols/internet/ah/__init__.py +25 -0
  354. pcapkit/protocols/internet/ah/data.py +39 -0
  355. pcapkit/protocols/internet/ah/protocol.py +343 -0
  356. pcapkit/protocols/internet/ah/schema.py +57 -0
  357. pcapkit/protocols/internet/esp/__init__.py +25 -0
  358. pcapkit/protocols/internet/esp/data.py +71 -0
  359. pcapkit/protocols/internet/esp/protocol.py +1509 -0
  360. pcapkit/protocols/internet/esp/schema.py +46 -0
  361. pcapkit/protocols/internet/hip/__init__.py +169 -0
  362. pcapkit/protocols/internet/hip/data.py +1109 -0
  363. pcapkit/protocols/internet/hip/protocol.py +5697 -0
  364. pcapkit/protocols/internet/hip/schema.py +1654 -0
  365. pcapkit/protocols/internet/hopopt/__init__.py +80 -0
  366. pcapkit/protocols/internet/hopopt/data.py +445 -0
  367. pcapkit/protocols/internet/hopopt/protocol.py +2346 -0
  368. pcapkit/protocols/internet/hopopt/schema.py +686 -0
  369. pcapkit/protocols/internet/icmp/__init__.py +14 -0
  370. pcapkit/protocols/internet/icmp/protocol.py +201 -0
  371. pcapkit/protocols/internet/icmpv4/__init__.py +38 -0
  372. pcapkit/protocols/internet/icmpv4/data.py +153 -0
  373. pcapkit/protocols/internet/icmpv4/protocol.py +652 -0
  374. pcapkit/protocols/internet/icmpv4/schema.py +135 -0
  375. pcapkit/protocols/internet/icmpv6/__init__.py +40 -0
  376. pcapkit/protocols/internet/icmpv6/data.py +174 -0
  377. pcapkit/protocols/internet/icmpv6/protocol.py +735 -0
  378. pcapkit/protocols/internet/icmpv6/schema.py +144 -0
  379. pcapkit/protocols/internet/igmp/__init__.py +25 -0
  380. pcapkit/protocols/internet/igmp/data.py +59 -0
  381. pcapkit/protocols/internet/igmp/protocol.py +491 -0
  382. pcapkit/protocols/internet/igmp/schema.py +54 -0
  383. pcapkit/protocols/internet/igmpv1/__init__.py +14 -0
  384. pcapkit/protocols/internet/igmpv1/protocol.py +63 -0
  385. pcapkit/protocols/internet/igmpv2/__init__.py +14 -0
  386. pcapkit/protocols/internet/igmpv2/protocol.py +65 -0
  387. pcapkit/protocols/internet/igmpv3/__init__.py +32 -0
  388. pcapkit/protocols/internet/igmpv3/data.py +150 -0
  389. pcapkit/protocols/internet/igmpv3/protocol.py +587 -0
  390. pcapkit/protocols/internet/igmpv3/schema.py +373 -0
  391. pcapkit/protocols/internet/internet.py +566 -0
  392. pcapkit/protocols/internet/ip/__init__.py +14 -0
  393. pcapkit/protocols/internet/ip/protocol.py +205 -0
  394. pcapkit/protocols/internet/ipsec/__init__.py +14 -0
  395. pcapkit/protocols/internet/ipsec/protocol.py +48 -0
  396. pcapkit/protocols/internet/ipv4/__init__.py +68 -0
  397. pcapkit/protocols/internet/ipv4/data.py +470 -0
  398. pcapkit/protocols/internet/ipv4/protocol.py +2293 -0
  399. pcapkit/protocols/internet/ipv4/schema.py +747 -0
  400. pcapkit/protocols/internet/ipv6/__init__.py +25 -0
  401. pcapkit/protocols/internet/ipv6/data.py +83 -0
  402. pcapkit/protocols/internet/ipv6/protocol.py +731 -0
  403. pcapkit/protocols/internet/ipv6/schema.py +176 -0
  404. pcapkit/protocols/internet/ipv6_ext/__init__.py +25 -0
  405. pcapkit/protocols/internet/ipv6_ext/data.py +52 -0
  406. pcapkit/protocols/internet/ipv6_ext/protocol.py +718 -0
  407. pcapkit/protocols/internet/ipv6_ext/schema.py +397 -0
  408. pcapkit/protocols/internet/ipv6_frag/__init__.py +25 -0
  409. pcapkit/protocols/internet/ipv6_frag/data.py +41 -0
  410. pcapkit/protocols/internet/ipv6_frag/protocol.py +320 -0
  411. pcapkit/protocols/internet/ipv6_frag/schema.py +51 -0
  412. pcapkit/protocols/internet/ipv6_opts/__init__.py +83 -0
  413. pcapkit/protocols/internet/ipv6_opts/data.py +462 -0
  414. pcapkit/protocols/internet/ipv6_opts/protocol.py +2335 -0
  415. pcapkit/protocols/internet/ipv6_opts/schema.py +695 -0
  416. pcapkit/protocols/internet/ipv6_route/__init__.py +34 -0
  417. pcapkit/protocols/internet/ipv6_route/data.py +113 -0
  418. pcapkit/protocols/internet/ipv6_route/protocol.py +936 -0
  419. pcapkit/protocols/internet/ipv6_route/schema.py +299 -0
  420. pcapkit/protocols/internet/ipx/__init__.py +26 -0
  421. pcapkit/protocols/internet/ipx/data.py +59 -0
  422. pcapkit/protocols/internet/ipx/protocol.py +387 -0
  423. pcapkit/protocols/internet/ipx/schema.py +53 -0
  424. pcapkit/protocols/internet/mh/__init__.py +433 -0
  425. pcapkit/protocols/internet/mh/data.py +2464 -0
  426. pcapkit/protocols/internet/mh/protocol.py +11753 -0
  427. pcapkit/protocols/internet/mh/schema.py +3367 -0
  428. pcapkit/protocols/link/NotImplemented/dsl.py +0 -0
  429. pcapkit/protocols/link/NotImplemented/eapol.py +1 -0
  430. pcapkit/protocols/link/NotImplemented/fddi.py +0 -0
  431. pcapkit/protocols/link/NotImplemented/isdn.py +0 -0
  432. pcapkit/protocols/link/NotImplemented/ndp.py +0 -0
  433. pcapkit/protocols/link/NotImplemented/ppp.py +0 -0
  434. pcapkit/protocols/link/__init__.py +80 -0
  435. pcapkit/protocols/link/arp/__init__.py +27 -0
  436. pcapkit/protocols/link/arp/data.py +73 -0
  437. pcapkit/protocols/link/arp/protocol.py +513 -0
  438. pcapkit/protocols/link/arp/schema.py +49 -0
  439. pcapkit/protocols/link/c_tag/__init__.py +14 -0
  440. pcapkit/protocols/link/c_tag/protocol.py +99 -0
  441. pcapkit/protocols/link/ethernet/__init__.py +25 -0
  442. pcapkit/protocols/link/ethernet/data.py +27 -0
  443. pcapkit/protocols/link/ethernet/protocol.py +221 -0
  444. pcapkit/protocols/link/ethernet/schema.py +72 -0
  445. pcapkit/protocols/link/frad/__init__.py +25 -0
  446. pcapkit/protocols/link/frad/data.py +47 -0
  447. pcapkit/protocols/link/frad/protocol.py +470 -0
  448. pcapkit/protocols/link/frad/schema.py +112 -0
  449. pcapkit/protocols/link/gre/__init__.py +25 -0
  450. pcapkit/protocols/link/gre/data.py +64 -0
  451. pcapkit/protocols/link/gre/protocol.py +396 -0
  452. pcapkit/protocols/link/gre/schema.py +91 -0
  453. pcapkit/protocols/link/ieee802_11/__init__.py +30 -0
  454. pcapkit/protocols/link/ieee802_11/data.py +171 -0
  455. pcapkit/protocols/link/ieee802_11/protocol.py +612 -0
  456. pcapkit/protocols/link/ieee802_11/schema.py +163 -0
  457. pcapkit/protocols/link/inarp/__init__.py +14 -0
  458. pcapkit/protocols/link/inarp/protocol.py +55 -0
  459. pcapkit/protocols/link/l2tp/__init__.py +26 -0
  460. pcapkit/protocols/link/l2tp/data.py +72 -0
  461. pcapkit/protocols/link/l2tp/protocol.py +285 -0
  462. pcapkit/protocols/link/l2tp/schema.py +122 -0
  463. pcapkit/protocols/link/l2tpv2/__init__.py +14 -0
  464. pcapkit/protocols/link/l2tpv2/protocol.py +440 -0
  465. pcapkit/protocols/link/link.py +226 -0
  466. pcapkit/protocols/link/linux_sll/__init__.py +14 -0
  467. pcapkit/protocols/link/linux_sll/protocol.py +421 -0
  468. pcapkit/protocols/link/linux_sll1/__init__.py +25 -0
  469. pcapkit/protocols/link/linux_sll1/data.py +41 -0
  470. pcapkit/protocols/link/linux_sll1/protocol.py +247 -0
  471. pcapkit/protocols/link/linux_sll1/schema.py +46 -0
  472. pcapkit/protocols/link/linux_sll2/__init__.py +25 -0
  473. pcapkit/protocols/link/linux_sll2/data.py +47 -0
  474. pcapkit/protocols/link/linux_sll2/protocol.py +257 -0
  475. pcapkit/protocols/link/linux_sll2/schema.py +52 -0
  476. pcapkit/protocols/link/loopback/__init__.py +25 -0
  477. pcapkit/protocols/link/loopback/data.py +25 -0
  478. pcapkit/protocols/link/loopback/protocol.py +334 -0
  479. pcapkit/protocols/link/loopback/schema.py +33 -0
  480. pcapkit/protocols/link/netlink/__init__.py +25 -0
  481. pcapkit/protocols/link/netlink/data.py +40 -0
  482. pcapkit/protocols/link/netlink/protocol.py +390 -0
  483. pcapkit/protocols/link/netlink/schema.py +44 -0
  484. pcapkit/protocols/link/radiotap/__init__.py +103 -0
  485. pcapkit/protocols/link/radiotap/data.py +768 -0
  486. pcapkit/protocols/link/radiotap/protocol.py +2264 -0
  487. pcapkit/protocols/link/radiotap/schema.py +662 -0
  488. pcapkit/protocols/link/s_tag/__init__.py +14 -0
  489. pcapkit/protocols/link/s_tag/protocol.py +102 -0
  490. pcapkit/protocols/link/vlan/__init__.py +27 -0
  491. pcapkit/protocols/link/vlan/data.py +47 -0
  492. pcapkit/protocols/link/vlan/protocol.py +269 -0
  493. pcapkit/protocols/link/vlan/schema.py +77 -0
  494. pcapkit/protocols/misc/__init__.py +60 -0
  495. pcapkit/protocols/misc/checksum/__init__.py +28 -0
  496. pcapkit/protocols/misc/checksum/ip_pseudo/__init__.py +25 -0
  497. pcapkit/protocols/misc/checksum/ip_pseudo/data.py +41 -0
  498. pcapkit/protocols/misc/checksum/ip_pseudo/protocol.py +692 -0
  499. pcapkit/protocols/misc/checksum/ip_pseudo/schema.py +118 -0
  500. pcapkit/protocols/misc/no_payload/__init__.py +25 -0
  501. pcapkit/protocols/misc/no_payload/data.py +17 -0
  502. pcapkit/protocols/misc/no_payload/protocol.py +164 -0
  503. pcapkit/protocols/misc/no_payload/schema.py +17 -0
  504. pcapkit/protocols/misc/pcap/__init__.py +30 -0
  505. pcapkit/protocols/misc/pcap/frame/__init__.py +26 -0
  506. pcapkit/protocols/misc/pcap/frame/data.py +62 -0
  507. pcapkit/protocols/misc/pcap/frame/protocol.py +673 -0
  508. pcapkit/protocols/misc/pcap/frame/schema.py +47 -0
  509. pcapkit/protocols/misc/pcap/header/__init__.py +26 -0
  510. pcapkit/protocols/misc/pcap/header/data.py +52 -0
  511. pcapkit/protocols/misc/pcap/header/protocol.py +391 -0
  512. pcapkit/protocols/misc/pcap/header/schema.py +103 -0
  513. pcapkit/protocols/misc/pcapng/__init__.py +160 -0
  514. pcapkit/protocols/misc/pcapng/data.py +1102 -0
  515. pcapkit/protocols/misc/pcapng/protocol.py +6960 -0
  516. pcapkit/protocols/misc/pcapng/schema.py +2825 -0
  517. pcapkit/protocols/misc/raw/__init__.py +25 -0
  518. pcapkit/protocols/misc/raw/data.py +35 -0
  519. pcapkit/protocols/misc/raw/protocol.py +188 -0
  520. pcapkit/protocols/misc/raw/schema.py +24 -0
  521. pcapkit/protocols/protocol.py +3145 -0
  522. pcapkit/protocols/schema.py +1295 -0
  523. pcapkit/protocols/transport/NotImplemented/rsvp.py +0 -0
  524. pcapkit/protocols/transport/__init__.py +47 -0
  525. pcapkit/protocols/transport/dccp/__init__.py +57 -0
  526. pcapkit/protocols/transport/dccp/data.py +275 -0
  527. pcapkit/protocols/transport/dccp/protocol.py +1525 -0
  528. pcapkit/protocols/transport/dccp/schema.py +381 -0
  529. pcapkit/protocols/transport/sctp/__init__.py +147 -0
  530. pcapkit/protocols/transport/sctp/data.py +633 -0
  531. pcapkit/protocols/transport/sctp/protocol.py +3937 -0
  532. pcapkit/protocols/transport/sctp/schema.py +1007 -0
  533. pcapkit/protocols/transport/tcp/__init__.py +108 -0
  534. pcapkit/protocols/transport/tcp/data.py +637 -0
  535. pcapkit/protocols/transport/tcp/protocol.py +3640 -0
  536. pcapkit/protocols/transport/tcp/schema.py +1131 -0
  537. pcapkit/protocols/transport/transport.py +371 -0
  538. pcapkit/protocols/transport/udp/__init__.py +25 -0
  539. pcapkit/protocols/transport/udp/data.py +38 -0
  540. pcapkit/protocols/transport/udp/protocol.py +384 -0
  541. pcapkit/protocols/transport/udp/schema.py +44 -0
  542. pcapkit/py.typed +0 -0
  543. pcapkit/toolkit/__init__.py +88 -0
  544. pcapkit/toolkit/dpkt.py +909 -0
  545. pcapkit/toolkit/pcap.py +510 -0
  546. pcapkit/toolkit/pcap_ct.py +160 -0
  547. pcapkit/toolkit/pcapng.py +287 -0
  548. pcapkit/toolkit/pypcap.py +158 -0
  549. pcapkit/toolkit/pypcapfile.py +917 -0
  550. pcapkit/toolkit/pyshark.py +628 -0
  551. pcapkit/toolkit/scapy.py +761 -0
  552. pcapkit/utilities/__init__.py +41 -0
  553. pcapkit/utilities/chardet.py +64 -0
  554. pcapkit/utilities/compat.py +173 -0
  555. pcapkit/utilities/config.py +446 -0
  556. pcapkit/utilities/contextvars.py +57 -0
  557. pcapkit/utilities/datetime.py +117 -0
  558. pcapkit/utilities/exceptions.py +845 -0
  559. pcapkit/utilities/importlib.py +123 -0
  560. pcapkit/utilities/inspect.py +55 -0
  561. pcapkit/utilities/logging.py +395 -0
  562. pcapkit/utilities/pickle.py +181 -0
  563. pcapkit/utilities/warnings.py +538 -0
  564. pcapkit/vendor/__init__.py +220 -0
  565. pcapkit/vendor/__main__.py +253 -0
  566. pcapkit/vendor/arp/__init__.py +27 -0
  567. pcapkit/vendor/arp/hardware.py +29 -0
  568. pcapkit/vendor/arp/operation.py +29 -0
  569. pcapkit/vendor/dccp/__init__.py +44 -0
  570. pcapkit/vendor/dccp/ack_vector_state.py +29 -0
  571. pcapkit/vendor/dccp/drop_code.py +29 -0
  572. pcapkit/vendor/dccp/feature.py +29 -0
  573. pcapkit/vendor/dccp/option.py +29 -0
  574. pcapkit/vendor/dccp/packet_type.py +29 -0
  575. pcapkit/vendor/dccp/reset_code.py +29 -0
  576. pcapkit/vendor/default.py +823 -0
  577. pcapkit/vendor/esp/__init__.py +32 -0
  578. pcapkit/vendor/esp/cipher.py +114 -0
  579. pcapkit/vendor/esp/integrity.py +111 -0
  580. pcapkit/vendor/ftp/__init__.py +27 -0
  581. pcapkit/vendor/ftp/command.py +577 -0
  582. pcapkit/vendor/ftp/return_code.py +363 -0
  583. pcapkit/vendor/hip/__init__.py +94 -0
  584. pcapkit/vendor/hip/certificate.py +29 -0
  585. pcapkit/vendor/hip/cipher.py +29 -0
  586. pcapkit/vendor/hip/di.py +29 -0
  587. pcapkit/vendor/hip/ecdsa_curve.py +29 -0
  588. pcapkit/vendor/hip/ecdsa_low_curve.py +29 -0
  589. pcapkit/vendor/hip/eddsa_curve.py +85 -0
  590. pcapkit/vendor/hip/esp_transform_suite.py +29 -0
  591. pcapkit/vendor/hip/group.py +87 -0
  592. pcapkit/vendor/hip/hi_algorithm.py +29 -0
  593. pcapkit/vendor/hip/hit_suite.py +29 -0
  594. pcapkit/vendor/hip/nat_traversal.py +29 -0
  595. pcapkit/vendor/hip/notify_message.py +29 -0
  596. pcapkit/vendor/hip/packet.py +88 -0
  597. pcapkit/vendor/hip/parameter.py +88 -0
  598. pcapkit/vendor/hip/registration.py +29 -0
  599. pcapkit/vendor/hip/registration_failure.py +29 -0
  600. pcapkit/vendor/hip/suite.py +29 -0
  601. pcapkit/vendor/hip/transport.py +29 -0
  602. pcapkit/vendor/http/__init__.py +39 -0
  603. pcapkit/vendor/http/error_code.py +94 -0
  604. pcapkit/vendor/http/frame.py +91 -0
  605. pcapkit/vendor/http/method.py +309 -0
  606. pcapkit/vendor/http/setting.py +93 -0
  607. pcapkit/vendor/http/status_code.py +233 -0
  608. pcapkit/vendor/icmp/__init__.py +40 -0
  609. pcapkit/vendor/icmp/destination_unreachable_code.py +80 -0
  610. pcapkit/vendor/icmp/parameter_problem_code.py +80 -0
  611. pcapkit/vendor/icmp/time_exceeded_code.py +80 -0
  612. pcapkit/vendor/icmp/type.py +78 -0
  613. pcapkit/vendor/icmpv6/__init__.py +40 -0
  614. pcapkit/vendor/icmpv6/destination_unreachable_code.py +80 -0
  615. pcapkit/vendor/icmpv6/parameter_problem_code.py +80 -0
  616. pcapkit/vendor/icmpv6/time_exceeded_code.py +73 -0
  617. pcapkit/vendor/icmpv6/type.py +78 -0
  618. pcapkit/vendor/ieee802_11/__init__.py +54 -0
  619. pcapkit/vendor/ieee802_11/control_subtype.py +107 -0
  620. pcapkit/vendor/ieee802_11/data_subtype.py +106 -0
  621. pcapkit/vendor/ieee802_11/extension_subtype.py +95 -0
  622. pcapkit/vendor/ieee802_11/management_subtype.py +102 -0
  623. pcapkit/vendor/ieee802_11/type.py +90 -0
  624. pcapkit/vendor/igmp/__init__.py +27 -0
  625. pcapkit/vendor/igmp/record_type.py +88 -0
  626. pcapkit/vendor/igmp/type.py +77 -0
  627. pcapkit/vendor/ipv4/__init__.py +59 -0
  628. pcapkit/vendor/ipv4/classification_level.py +90 -0
  629. pcapkit/vendor/ipv4/option_class.py +80 -0
  630. pcapkit/vendor/ipv4/option_number.py +105 -0
  631. pcapkit/vendor/ipv4/protection_authority.py +84 -0
  632. pcapkit/vendor/ipv4/qs_function.py +78 -0
  633. pcapkit/vendor/ipv4/router_alert.py +94 -0
  634. pcapkit/vendor/ipv4/tos_del.py +78 -0
  635. pcapkit/vendor/ipv4/tos_ecn.py +95 -0
  636. pcapkit/vendor/ipv4/tos_pre.py +84 -0
  637. pcapkit/vendor/ipv4/tos_rel.py +78 -0
  638. pcapkit/vendor/ipv4/tos_thr.py +78 -0
  639. pcapkit/vendor/ipv4/ts_flag.py +79 -0
  640. pcapkit/vendor/ipv6/__init__.py +53 -0
  641. pcapkit/vendor/ipv6/extension_header.py +220 -0
  642. pcapkit/vendor/ipv6/option.py +104 -0
  643. pcapkit/vendor/ipv6/option_action.py +90 -0
  644. pcapkit/vendor/ipv6/qs_function.py +78 -0
  645. pcapkit/vendor/ipv6/router_alert.py +93 -0
  646. pcapkit/vendor/ipv6/routing.py +87 -0
  647. pcapkit/vendor/ipv6/seed_id.py +81 -0
  648. pcapkit/vendor/ipv6/smf_dpd_mode.py +78 -0
  649. pcapkit/vendor/ipv6/tagger_id.py +81 -0
  650. pcapkit/vendor/ipx/__init__.py +39 -0
  651. pcapkit/vendor/ipx/packet.py +149 -0
  652. pcapkit/vendor/ipx/socket.py +240 -0
  653. pcapkit/vendor/l2tp/__init__.py +21 -0
  654. pcapkit/vendor/l2tp/type.py +79 -0
  655. pcapkit/vendor/linux/__init__.py +21 -0
  656. pcapkit/vendor/linux/arphrd.py +100 -0
  657. pcapkit/vendor/mh/__init__.py +206 -0
  658. pcapkit/vendor/mh/access_type.py +87 -0
  659. pcapkit/vendor/mh/ack_status_code.py +88 -0
  660. pcapkit/vendor/mh/ani_suboption.py +88 -0
  661. pcapkit/vendor/mh/auth_subtype.py +83 -0
  662. pcapkit/vendor/mh/binding_ack_flag.py +164 -0
  663. pcapkit/vendor/mh/binding_error.py +78 -0
  664. pcapkit/vendor/mh/binding_revocation.py +87 -0
  665. pcapkit/vendor/mh/binding_update_flag.py +163 -0
  666. pcapkit/vendor/mh/cga_extension.py +91 -0
  667. pcapkit/vendor/mh/cga_sec.py +91 -0
  668. pcapkit/vendor/mh/cga_type.py +74 -0
  669. pcapkit/vendor/mh/dhcp_support_mode.py +77 -0
  670. pcapkit/vendor/mh/dns_status_code.py +87 -0
  671. pcapkit/vendor/mh/dsmip6_tls_packet.py +87 -0
  672. pcapkit/vendor/mh/dsmipv6_home_address.py +87 -0
  673. pcapkit/vendor/mh/enumerating_algorithm.py +82 -0
  674. pcapkit/vendor/mh/fb_ack_status.py +87 -0
  675. pcapkit/vendor/mh/fb_action.py +88 -0
  676. pcapkit/vendor/mh/fb_indication_trigger.py +87 -0
  677. pcapkit/vendor/mh/fb_type.py +88 -0
  678. pcapkit/vendor/mh/flow_id_status.py +87 -0
  679. pcapkit/vendor/mh/flow_id_suboption.py +87 -0
  680. pcapkit/vendor/mh/handoff_type.py +87 -0
  681. pcapkit/vendor/mh/handover_ack_flag.py +159 -0
  682. pcapkit/vendor/mh/handover_ack_status.py +87 -0
  683. pcapkit/vendor/mh/handover_initiate_flag.py +159 -0
  684. pcapkit/vendor/mh/handover_initiate_status.py +87 -0
  685. pcapkit/vendor/mh/home_address_reply.py +87 -0
  686. pcapkit/vendor/mh/lla_code.py +97 -0
  687. pcapkit/vendor/mh/lma_mag_suboption.py +88 -0
  688. pcapkit/vendor/mh/mn_group_id.py +87 -0
  689. pcapkit/vendor/mh/mn_id_subtype.py +87 -0
  690. pcapkit/vendor/mh/operator_id.py +87 -0
  691. pcapkit/vendor/mh/option.py +83 -0
  692. pcapkit/vendor/mh/packet.py +82 -0
  693. pcapkit/vendor/mh/qos_attribute.py +87 -0
  694. pcapkit/vendor/mh/revocation_status_code.py +87 -0
  695. pcapkit/vendor/mh/revocation_trigger.py +87 -0
  696. pcapkit/vendor/mh/status_code.py +91 -0
  697. pcapkit/vendor/mh/traffic_selector.py +87 -0
  698. pcapkit/vendor/mh/upa_status.py +87 -0
  699. pcapkit/vendor/mh/upn_reason.py +87 -0
  700. pcapkit/vendor/ngap/__init__.py +31 -0
  701. pcapkit/vendor/ngap/procedure_code.py +233 -0
  702. pcapkit/vendor/ngap/protocol_ie.py +201 -0
  703. pcapkit/vendor/ospf/__init__.py +27 -0
  704. pcapkit/vendor/ospf/authentication.py +29 -0
  705. pcapkit/vendor/ospf/packet.py +29 -0
  706. pcapkit/vendor/pcapng/__init__.py +55 -0
  707. pcapkit/vendor/pcapng/block_type.py +102 -0
  708. pcapkit/vendor/pcapng/filter_type.py +77 -0
  709. pcapkit/vendor/pcapng/hash_algorithm.py +82 -0
  710. pcapkit/vendor/pcapng/option_type.py +477 -0
  711. pcapkit/vendor/pcapng/record_type.py +81 -0
  712. pcapkit/vendor/pcapng/secrets_type.py +80 -0
  713. pcapkit/vendor/pcapng/tls_key_label.py +180 -0
  714. pcapkit/vendor/pcapng/verdict_type.py +79 -0
  715. pcapkit/vendor/radiotap/__init__.py +86 -0
  716. pcapkit/vendor/radiotap/ampdu_flags.py +46 -0
  717. pcapkit/vendor/radiotap/channel_flags.py +51 -0
  718. pcapkit/vendor/radiotap/eht_known.py +59 -0
  719. pcapkit/vendor/radiotap/field_type.py +151 -0
  720. pcapkit/vendor/radiotap/flags.py +307 -0
  721. pcapkit/vendor/radiotap/he_data1_known.py +54 -0
  722. pcapkit/vendor/radiotap/he_data2_known.py +49 -0
  723. pcapkit/vendor/radiotap/he_mu_flags1_known.py +48 -0
  724. pcapkit/vendor/radiotap/he_mu_flags2_known.py +42 -0
  725. pcapkit/vendor/radiotap/he_mu_other_user_known.py +38 -0
  726. pcapkit/vendor/radiotap/lsig_data1.py +40 -0
  727. pcapkit/vendor/radiotap/mcs_known.py +48 -0
  728. pcapkit/vendor/radiotap/rx_flags.py +39 -0
  729. pcapkit/vendor/radiotap/s1g_known.py +46 -0
  730. pcapkit/vendor/radiotap/timestamp_flags.py +40 -0
  731. pcapkit/vendor/radiotap/tx_flags.py +44 -0
  732. pcapkit/vendor/radiotap/usig_common_known.py +48 -0
  733. pcapkit/vendor/radiotap/vht_coding.py +42 -0
  734. pcapkit/vendor/radiotap/vht_flags.py +44 -0
  735. pcapkit/vendor/radiotap/vht_known.py +47 -0
  736. pcapkit/vendor/reg/__init__.py +47 -0
  737. pcapkit/vendor/reg/apptype/__init__.py +36 -0
  738. pcapkit/vendor/reg/apptype/apptype.py +1320 -0
  739. pcapkit/vendor/reg/apptype/dccp.py +27 -0
  740. pcapkit/vendor/reg/apptype/sctp.py +27 -0
  741. pcapkit/vendor/reg/apptype/tcp.py +27 -0
  742. pcapkit/vendor/reg/apptype/udp.py +27 -0
  743. pcapkit/vendor/reg/ethertype.py +175 -0
  744. pcapkit/vendor/reg/linktype.py +210 -0
  745. pcapkit/vendor/reg/transtype.py +116 -0
  746. pcapkit/vendor/sctp/__init__.py +37 -0
  747. pcapkit/vendor/sctp/cause_code.py +29 -0
  748. pcapkit/vendor/sctp/chunk.py +29 -0
  749. pcapkit/vendor/sctp/parameter.py +29 -0
  750. pcapkit/vendor/sctp/payload_protocol_identifier.py +34 -0
  751. pcapkit/vendor/sslv2/__init__.py +24 -0
  752. pcapkit/vendor/sslv2/handshake_type.py +100 -0
  753. pcapkit/vendor/sslv2/version.py +95 -0
  754. pcapkit/vendor/tcp/__init__.py +35 -0
  755. pcapkit/vendor/tcp/checksum.py +80 -0
  756. pcapkit/vendor/tcp/flags.py +180 -0
  757. pcapkit/vendor/tcp/mp_tcp_option.py +90 -0
  758. pcapkit/vendor/tcp/option.py +103 -0
  759. pcapkit/vendor/tls/__init__.py +30 -0
  760. pcapkit/vendor/tls/content_type.py +142 -0
  761. pcapkit/vendor/tls/extension_type.py +151 -0
  762. pcapkit/vendor/tls/handshake_type.py +154 -0
  763. pcapkit/vendor/vlan/__init__.py +23 -0
  764. pcapkit/vendor/vlan/priority_level.py +97 -0
  765. pypcapkit-1.6.2.dist-info/METADATA +199 -0
  766. pypcapkit-1.6.2.dist-info/RECORD +770 -0
  767. pypcapkit-1.6.2.dist-info/WHEEL +5 -0
  768. pypcapkit-1.6.2.dist-info/entry_points.txt +3 -0
  769. pypcapkit-1.6.2.dist-info/licenses/LICENSE +29 -0
  770. pypcapkit-1.6.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1833 @@
1
+ # -*- coding: utf-8 -*-
2
+ # pylint: disable=import-outside-toplevel,fixme
3
+ # mypy: disable-error-code=dict-item
4
+ """Extractor for PCAP Files
5
+ ==============================
6
+
7
+ .. module:: pcapkit.foundation.extraction
8
+
9
+ :mod:`pcapkit.foundation.extraction` contains
10
+ :class:`~pcapkit.foundation.extraction.Extractor`, which reads the frames of a
11
+ capture file through an engine, and optionally reassembles, traces and dumps
12
+ them.
13
+
14
+ """
15
+ import collections
16
+ import functools
17
+ import importlib
18
+ import io
19
+ import os
20
+ import sys
21
+ import types
22
+ import weakref
23
+ from typing import TYPE_CHECKING, Generic, TypeVar, cast
24
+
25
+ from dictdumper.dumper import Dumper
26
+
27
+ from pcapkit.corekit.context import ContextRegistry
28
+ from pcapkit.corekit.io import PeekableStream, SeekableReader, can_seek
29
+ from pcapkit.corekit.module import ModuleDescriptor
30
+ from pcapkit.dumpkit.common import make_dumper
31
+ from pcapkit.foundation.engines import _pcap_backend
32
+ from pcapkit.foundation.engines.engine import Engine, EngineBase
33
+ from pcapkit.foundation.engines.pcap import PCAP as PCAP_Engine
34
+ from pcapkit.foundation.engines.pcapng import PCAPNG as PCAPNG_Engine
35
+ from pcapkit.foundation.reassembly import ReassemblyManager
36
+ from pcapkit.foundation.reassembly.data import ReassemblyData
37
+ from pcapkit.foundation.reassembly.reassembly import Reassembly, ReassemblyBase
38
+ from pcapkit.foundation.traceflow import TraceFlowManager
39
+ from pcapkit.foundation.traceflow.data import TraceFlowData
40
+ from pcapkit.foundation.traceflow.traceflow import TraceFlow, TraceFlowBase
41
+ from pcapkit.interface.registry import restore_shipped, restore_shipped_dumper, same_entry
42
+ from pcapkit.utilities.exceptions import (CallableError, FileNotFound, FormatError, IterableError,
43
+ RegistryError, UnsupportedCall, stacklevel)
44
+ from pcapkit.utilities.logging import get_logger
45
+ from pcapkit.utilities.warnings import (AttributeWarning, EngineWarning, ExtractionWarning,
46
+ FormatWarning, RegistryWarning, warn)
47
+
48
+ if TYPE_CHECKING:
49
+ from io import BufferedReader
50
+ from types import ModuleType, TracebackType
51
+ from typing import (IO, Any, Callable, DefaultDict, Iterable, Mapping, Optional, Tuple, Type,
52
+ Union)
53
+
54
+ from dpkt.dpkt import Packet as DPKTPacket
55
+ from pcapfile.structs import pcap_packet as PCAPFilePacket
56
+ from pyshark.packet.packet import Packet as PySharkPacket
57
+ from scapy.packet import Packet as ScapyPacket
58
+ from typing_extensions import Literal
59
+
60
+ from pcapkit.corekit.context import ProtocolContext
61
+ from pcapkit.foundation.reassembly.dtls import DTLS as DTLS_Reassembly
62
+ from pcapkit.foundation.reassembly.ipv4 import IPv4 as IPv4_Reassembly
63
+ from pcapkit.foundation.reassembly.ipv6 import IPv6 as IPv6_Reassembly
64
+ from pcapkit.foundation.reassembly.tcp import TCP as TCP_Reassembly
65
+ from pcapkit.foundation.traceflow.tcp import TCP as TCP_TraceFlow
66
+ from pcapkit.protocols.misc.pcap.frame.protocol import Frame
67
+ from pcapkit.protocols.misc.pcapng.protocol import PCAPNG
68
+ from pcapkit.protocols.protocol import ProtocolBase
69
+
70
+ #: Every key registered in :attr:`Extractor.__output__` and in
71
+ #: :attr:`TraceFlow.__output__
72
+ #: <pcapkit.foundation.traceflow.traceflow.TraceFlow.__output__>` -- both
73
+ #: registries expose the same keys, so ``'cap'`` and the ``'txt'``/``'xml'``
74
+ #: aliases are spellable for a type checker as they are accepted at runtime.
75
+ Formats = Literal['pcap', 'cap', 'json', 'tree', 'text', 'txt', 'plist', 'xml']
76
+ # NOTE: deliberately duplicated verbatim in ``pcapkit.interface.misc``; update
77
+ # both copies when a new engine lands.
78
+ Engines = Literal['default', 'pcapkit', 'dpkt', 'scapy', 'pyshark', 'pypcap', 'pcap_ct',
79
+ 'pypcapfile']
80
+ Layers = Literal['link', 'internet', 'transport', 'application', 'none']
81
+
82
+ # NOTE: the PyPCAP and PCAP_CT engines dissect nothing, so their packet is the
83
+ # ``(timestamp, bytes)`` pair ``pcap.pcap`` yields; one member covers both.
84
+ Packet = Union[Frame, PCAPNG, ScapyPacket, DPKTPacket, PySharkPacket,
85
+ PCAPFilePacket, Tuple[float, bytes]]
86
+
87
+ Protocols = Union[str, ProtocolBase, Type[ProtocolBase]]
88
+ # NOTE: every caller discards the result, so any two-argument callback is
89
+ # accepted, e.g. ``lambda e, f: sys.stdout.write(str(f))``.
90
+ VerboseHandler = Callable[['Extractor', Packet], Any]
91
+
92
+ __all__ = ['Extractor']
93
+
94
+ #: logging.Logger: Module-level logger, a child of the package-wide
95
+ #: :data:`pcapkit.utilities.logging.logger`.
96
+ logger = get_logger(__name__)
97
+
98
+ _P = TypeVar('_P')
99
+
100
+
101
+ #: Engines whose library opens the input by *path*,
102
+ #: :attr:`Extractor._ifnm <pcapkit.foundation.extraction.Extractor._ifnm>`, rather than reading
103
+ #: :attr:`Extractor._ifile <pcapkit.foundation.extraction.Extractor._ifile>`, so they cannot take an
104
+ #: unnamed stream.
105
+ _PATH_ENGINES = frozenset({'scapy', 'pyshark', 'pypcap', 'pcap_ct'})
106
+
107
+
108
+ def _release_input(ifile: 'IO[bytes]') -> 'None':
109
+ """Close an input stream from a finaliser, if it is still open.
110
+
111
+ The one close both backstops of :issue:`606` perform --
112
+ :meth:`Extractor.__del__ <pcapkit.foundation.extraction.Extractor.__del__>`
113
+ and the :class:`weakref.finalize` held in
114
+ :attr:`Extractor._finalizer <pcapkit.foundation.extraction.Extractor._finalizer>`.
115
+ It takes the stream rather than the extractor, so that a finaliser built on
116
+ it holds no reference that would keep the extractor alive; deciding whether
117
+ the stream is the extractor's to close is the caller's business, cf.
118
+ :meth:`Extractor._owns_input <pcapkit.foundation.extraction.Extractor._owns_input>`.
119
+
120
+ Args:
121
+ ifile: The stream to close.
122
+
123
+ Note:
124
+ A finaliser must not raise, so the close is guarded: that is what a close
125
+ during interpreter shutdown can fail at.
126
+
127
+ """
128
+ try:
129
+ if not ifile.closed:
130
+ ifile.close()
131
+ except (OSError, ValueError): # pragma: no cover
132
+ # Nothing useful can be reported from a finaliser, and raising here
133
+ # would only produce an "Exception ignored in __del__" on stderr.
134
+ pass
135
+
136
+
137
+ class Extractor(Generic[_P]):
138
+ """Extractor for PCAP files.
139
+
140
+ Notes:
141
+ For supported engines, please refer to
142
+ :meth:`~pcapkit.foundation.extraction.Extractor.run`.
143
+
144
+ .. versionchanged:: 1.1.1.post2
145
+
146
+ ``strict`` is renamed ``reasm_strict``, with no alias, and
147
+ ``reasm_store`` is inserted after it, so a positional argument from
148
+ ``trace`` onwards moves one place along.
149
+
150
+ .. versionchanged:: 1.5.0
151
+
152
+ ``layer`` and ``protocol`` stop the dissection where they say, which
153
+ 1.4.x ignored (:issue:`356`). A stream given as ``fin`` is left open:
154
+ only a file the extractor opened itself is closed (:issue:`610`).
155
+ ``reasm_timeout``, ``trace_bidirectional`` and ``trace_analyse`` are
156
+ inserted among the positional parameters and ``context`` is appended,
157
+ so a positional argument after ``reasm_store`` has to move to a
158
+ keyword. Flows are traced bidirectionally by default. :attr:`engine`
159
+ is typed :class:`~pcapkit.foundation.engines.engine.EngineBase`, the
160
+ base every engine derives from (:issue:`1022`). A callback given as
161
+ ``verbose`` is called on every engine, where the third-party engines
162
+ replaced it with their own printer (:issue:`1874`).
163
+
164
+ .. versionchanged:: 1.6.0
165
+
166
+ ``dtls`` is inserted after ``tcp``, so a positional argument from
167
+ ``buffer_size`` onwards moves one place along.
168
+
169
+ """
170
+ if TYPE_CHECKING:
171
+ #: Input file name.
172
+ _ifnm: 'str'
173
+ #: Output file name.
174
+ _ofnm: 'Optional[str]'
175
+ #: Output file extension, bare, i.e. without the leading ``.`` --
176
+ #: ``'json'``, not ``'.json'``. Normalised by
177
+ #: :meth:`~pcapkit.foundation.extraction.Extractor.make_name`, whose
178
+ #: docstring is the contract; the engines compose a per-frame filename
179
+ #: as ``f'{name}.{ext._fext}'`` and supply the dot themselves.
180
+ _fext: 'Optional[str]'
181
+
182
+ #: Auto extract flag. It indicates if the extraction process should
183
+ #: continue automatically until the EOF is reached.
184
+ _flag_a: 'bool'
185
+ #: Store data flag. It indicates if the extracted frames should be
186
+ #: stored in memory.
187
+ _flag_d: 'bool'
188
+ #: EOF flag. It indicates if the EOF is reached.
189
+ _flag_e: 'bool'
190
+ #: Split file flag, i.e. dump each frame into different files.
191
+ _flag_f: 'bool'
192
+ #: No output file, i.e., no output file is to be generated.
193
+ _flag_q: 'bool'
194
+ #: Output opened flag. It indicates if :meth:`~pcapkit.foundation.extraction.Extractor._open_output`
195
+ #: has replaced the writer class in :attr:`_ofile` with the writer.
196
+ _flag_o: 'bool'
197
+ #: Reassembly flag. It indicates if datagram reassembly is enabled.
198
+ #: Every engine reads it to decide whether to feed
199
+ #: :attr:`~pcapkit.foundation.extraction.Extractor._reasm`, and the
200
+ #: engines that cannot reassemble clear it on startup.
201
+ _flag_r: 'bool'
202
+ #: Trace flag. It indicates if the flow tracing is enabled.
203
+ _flag_t: 'bool'
204
+ #: Verbose flag. It indicates if verbose output is enabled, whether by
205
+ #: ``verbose=True`` or by a callback, which
206
+ #: :attr:`~pcapkit.foundation.extraction.Extractor._vfunc_default`
207
+ #: tells apart.
208
+ _flag_v: 'bool'
209
+ #: No EOF flag. It is useful when the input is a live capture on a pipe or
210
+ #: on standard input, where reaching the end of what has arrived so far
211
+ #: does not mean the capture is over: the extraction retries instead of
212
+ #: stopping. It retries only while the input is still producing, though --
213
+ #: see :meth:`~pcapkit.foundation.extraction.Extractor._note_eof_progress`
214
+ #: for the rule and for what it narrows, without which an exhausted stream
215
+ #: spins forever (:issue:`620`).
216
+ _flag_n: 'bool'
217
+ #: Input filename flag. It indicates if the input file is a file
218
+ #: name or a binary IO object. For the latter, we should not close
219
+ #: the file object after extraction.
220
+ _flag_s: 'bool'
221
+
222
+ #: Verbose callback function.
223
+ _vfunc: 'VerboseHandler'
224
+ #: Default verbose printer flag. It is set only by ``verbose=True``,
225
+ #: which asks for the default output, and an engine whose frames are
226
+ #: not PyPCAPKit's own replaces
227
+ #: :attr:`~pcapkit.foundation.extraction.Extractor._vfunc` with its own
228
+ #: printer only when it is set. A callback given as ``verbose`` leaves
229
+ #: it unset, so every engine keeps that callback (:issue:`1874`).
230
+ _vfunc_default: 'bool'
231
+
232
+ #: Frame number.
233
+ _frnum: 'int'
234
+ #: Frame records.
235
+ _frame: 'list[Packet]'
236
+
237
+ #: Frame record for reassembly.
238
+ _reasm: 'ReassemblyManager'
239
+ #: Frame record for flow tracing.
240
+ _trace: 'TraceFlowManager'
241
+
242
+ #: IPv4 flag. It indicates if the IPv4 reassembly and/or flow tracing
243
+ #: is enabled.
244
+ _ipv4: 'bool'
245
+ #: IPv6 flag. It indicates if the IPv6 reassembly and/or flow tracing
246
+ #: is enabled.
247
+ _ipv6: 'bool'
248
+ #: TCP flag. It indicates if the TCP reassembly and/or flow tracing
249
+ #: is enabled.
250
+ _tcp: 'bool'
251
+ #: DTLS flag. It indicates if the DTLS handshake-message reassembly is
252
+ #: enabled.
253
+ _dtls: 'bool'
254
+
255
+ #: Extract til protocol.
256
+ _exptl: 'Protocols'
257
+ #: Extract til layer.
258
+ _exlyr: 'Layers'
259
+ #: Caller supplied parsing context, cf. :mod:`pcapkit.corekit.context`.
260
+ _exctx: 'ContextRegistry'
261
+ #: Extraction engine name.
262
+ _exnam: 'Engines'
263
+ #: Extraction engine instance.
264
+ _exeng: 'EngineBase[_P]'
265
+ #: The pcap backend probe, shared by engine selection and the engine's
266
+ #: constructor so that an extraction probes once (:issue:`2113`).
267
+ _exprb: '_pcap_backend.Memo'
268
+
269
+ #: Input file object.
270
+ _ifile: 'BufferedReader'
271
+ #: Backstop that closes :attr:`_ifile` when the extractor is collected
272
+ #: before :meth:`_cleanup` has run, registered only when the stream is
273
+ #: this class's own to close (:issue:`1997`), else :data:`None`.
274
+ #: :meth:`__del__` alone is not enough, as GraalPy never calls it; a
275
+ #: :class:`weakref.finalize` runs there and on CPython alike.
276
+ _finalizer: 'Optional[weakref.finalize]'
277
+ #: Output writer. It holds the writer class until :meth:`_open_output`
278
+ #: replaces it with the writer, or under split mode with a factory.
279
+ _ofile: 'Dumper | Type[Dumper]'
280
+
281
+ #: Position of the input stream at the previous end of stream, or
282
+ #: :data:`None` before the first one. Comparing it against the position
283
+ #: at the next end of stream is what tells a live capture that has paused
284
+ #: -- retry, more may arrive -- from one that is finished, which is the
285
+ #: termination condition for ``no_eof`` (:issue:`620`).
286
+ _eof_mark: 'Optional[int]'
287
+
288
+ #: Magic number.
289
+ _magic: 'bytes'
290
+ #: Output format.
291
+ _offmt: 'Formats'
292
+
293
+ #: List of potential PCAP file extensions.
294
+ PCAP_EXT = ['.pcap', '.cap', '.pcapng']
295
+
296
+ ##########################################################################
297
+ # Defaults.
298
+ ##########################################################################
299
+
300
+ #: Format dumper mapping for writing output files. Each value pairs the dumper,
301
+ #: as a module descriptor or a :class:`dictdumper.dumper.Dumper` subclass, with
302
+ #: the file extension of its format.
303
+ __output__ = collections.defaultdict(
304
+ lambda: (ModuleDescriptor('pcapkit.dumpkit', 'NotImplementedIO'), None),
305
+ {
306
+ 'pcap': (ModuleDescriptor('pcapkit.dumpkit', 'PCAPIO'), '.pcap'),
307
+ 'cap': (ModuleDescriptor('pcapkit.dumpkit', 'PCAPIO'), '.pcap'),
308
+ 'plist': (ModuleDescriptor('dictdumper', 'PLIST'), '.plist'),
309
+ 'xml': (ModuleDescriptor('dictdumper', 'PLIST'), '.plist'),
310
+ 'json': (ModuleDescriptor('dictdumper', 'JSON'), '.json'),
311
+ 'tree': (ModuleDescriptor('dictdumper', 'Tree'), '.txt'),
312
+ 'text': (ModuleDescriptor('dictdumper', 'Tree'), '.txt'),
313
+ 'txt': (ModuleDescriptor('dictdumper', 'Tree'), '.txt'),
314
+ },
315
+ ) # type: DefaultDict[str, tuple[ModuleDescriptor[Dumper] | Type[Dumper], str | None]]
316
+
317
+ #: Engine mapping for extracting frames. The values should be a module descriptor
318
+ #: or an :class:`~pcapkit.foundation.engines.engine.EngineBase` subclass: every
319
+ #: built-in derives from the base directly, and the public ``register_engine``
320
+ #: additionally admits only :class:`~pcapkit.foundation.engines.engine.Engine`
321
+ #: subclasses.
322
+ __engine__ = {
323
+ 'scapy': ModuleDescriptor('pcapkit.foundation.engines.scapy', 'Scapy'),
324
+ 'dpkt': ModuleDescriptor('pcapkit.foundation.engines.dpkt', 'DPKT'),
325
+ 'pyshark': ModuleDescriptor('pcapkit.foundation.engines.pyshark', 'PyShark'),
326
+ 'pypcap': ModuleDescriptor('pcapkit.foundation.engines.pypcap', 'PyPCAP'),
327
+ # NOTE: ``pcap-ct`` installs the same ``pcap`` module as ``pypcap`` but is an independent
328
+ # project; ``PCAP_CT.__engine_module__`` explains how ``import_test`` tells them apart.
329
+ 'pcap_ct': ModuleDescriptor('pcapkit.foundation.engines.pcap_ct', 'PCAP_CT'),
330
+ 'pypcapfile': ModuleDescriptor('pcapkit.foundation.engines.pypcapfile', 'PyPCAPFile'),
331
+ } # type: dict[str, ModuleDescriptor[EngineBase] | Type[EngineBase]]
332
+
333
+ #: Reassembly support mapping for extracting frames. The values should be a module
334
+ #: descriptor or a :class:`~pcapkit.foundation.reassembly.reassembly.ReassemblyBase`
335
+ #: subclass: every built-in derives from the base directly, and the public
336
+ #: ``register_reassembly`` additionally admits only
337
+ #: :class:`~pcapkit.foundation.reassembly.reassembly.Reassembly` subclasses.
338
+ __reassembly__ = {
339
+ 'ipv4': ModuleDescriptor('pcapkit.foundation.reassembly.ipv4', 'IPv4'),
340
+ 'ipv6': ModuleDescriptor('pcapkit.foundation.reassembly.ipv6', 'IPv6'),
341
+ 'tcp': ModuleDescriptor('pcapkit.foundation.reassembly.tcp', 'TCP'),
342
+ 'dtls': ModuleDescriptor('pcapkit.foundation.reassembly.dtls', 'DTLS'),
343
+ } # type: dict[str, ModuleDescriptor[ReassemblyBase] | Type[ReassemblyBase]]
344
+
345
+ #: Flow tracing support mapping for extracting frames. The values should be a module
346
+ #: descriptor or a :class:`~pcapkit.foundation.traceflow.traceflow.TraceFlowBase`
347
+ #: subclass: every built-in derives from the base directly, and the public
348
+ #: ``register_traceflow`` additionally admits only
349
+ #: :class:`~pcapkit.foundation.traceflow.traceflow.TraceFlow` subclasses.
350
+ __traceflow__ = {
351
+ 'tcp': ModuleDescriptor('pcapkit.foundation.traceflow.tcp', 'TCP'),
352
+ } # type: dict[str, ModuleDescriptor[TraceFlowBase] | Type[TraceFlowBase]]
353
+
354
+ # Read-only copies of the registries as shipped. A public registrar
355
+ # handed the built-in a name shipped with restores this entry, so an
356
+ # override can be undone (#1363).
357
+ _shipped_output = types.MappingProxyType(dict(__output__))
358
+ _shipped_engine = types.MappingProxyType(dict(__engine__))
359
+ _shipped_reassembly = types.MappingProxyType(dict(__reassembly__))
360
+ _shipped_traceflow = types.MappingProxyType(dict(__traceflow__))
361
+
362
+ ##########################################################################
363
+ # Properties.
364
+ ##########################################################################
365
+
366
+ @property
367
+ def length(self) -> 'int':
368
+ """Frame number (of current extracted frame or all)."""
369
+ return self._frnum
370
+
371
+ @property
372
+ def format(self) -> 'Formats':
373
+ """Format of output file.
374
+
375
+ Raises:
376
+ UnsupportedCall: If :attr:`self._flag_q <pcapkit.foundation.extraction.Extractor._flag_q>`
377
+ is set as :data:`True`, as output is disabled by initialisation parameter.
378
+
379
+ """
380
+ if self._flag_q:
381
+ raise UnsupportedCall("'Extractor(nofile=True)' object has no attribute 'format'")
382
+ return self._offmt
383
+
384
+ @property
385
+ def input(self) -> 'str':
386
+ """Name of input PCAP file.
387
+
388
+ For a binary IO object without a :obj:`str` ``name``, a placeholder
389
+ naming its type, e.g. ``<BytesIO>``.
390
+
391
+ """
392
+ return self._ifnm
393
+
394
+ @property
395
+ def output(self) -> 'str':
396
+ """Name of output file.
397
+
398
+ Raises:
399
+ UnsupportedCall: If :attr:`self._flag_q <pcapkit.foundation.extraction.Extractor._flag_q>`
400
+ is set as :data:`True`, as output is disabled by initialisation parameter.
401
+
402
+ """
403
+ if self._flag_q:
404
+ raise UnsupportedCall("'Extractor(nofile=True)' object has no attribute 'output'")
405
+ return cast('str', self._ofnm)
406
+
407
+ @property
408
+ def frame(self) -> 'tuple[Packet, ...]':
409
+ """Extracted frames.
410
+
411
+ Raises:
412
+ UnsupportedCall: If :attr:`self._flag_d <pcapkit.foundation.extraction.Extractor._flag_d>`
413
+ is :data:`False`, as storing frame data is disabled.
414
+
415
+ """
416
+ if self._flag_d:
417
+ return tuple(self._frame)
418
+ raise UnsupportedCall("'Extractor(store=False)' object has no attribute 'frame'")
419
+
420
+ @property
421
+ def reassembly(self) -> 'ReassemblyData':
422
+ """Frame record for reassembly.
423
+
424
+ * ``ipv4`` -- tuple of IPv4 payload fragment (:term:`reasm.ipv4.datagram`)
425
+ * ``ipv6`` -- tuple of IPv6 payload fragment (:term:`reasm.ipv6.datagram`)
426
+ * ``tcp`` -- tuple of TCP payload fragment (:term:`reasm.tcp.datagram`)
427
+ * ``dtls`` -- tuple of DTLS handshake message (:term:`reasm.dtls.datagram`)
428
+
429
+ Raises:
430
+ UnsupportedCall: If :attr:`self._flag_r <pcapkit.foundation.extraction.Extractor._flag_r>`
431
+ is :data:`False`, as reassembly is disabled.
432
+
433
+ .. versionchanged:: 1.1.1
434
+
435
+ Raises :exc:`~pcapkit.utilities.exceptions.UnsupportedCall` when
436
+ reassembly is disabled, where 1.1.0 built the record regardless.
437
+
438
+ """
439
+ if self._flag_r:
440
+ data = ReassemblyData(
441
+ ipv4=tuple(self._reasm.ipv4.datagram) if self._ipv4 else None,
442
+ ipv6=tuple(self._reasm.ipv6.datagram) if self._ipv6 else None,
443
+ tcp=tuple(self._reasm.tcp.datagram) if self._tcp else None,
444
+ dtls=tuple(self._reasm.dtls.datagram) if self._dtls else None,
445
+ )
446
+ return data
447
+ raise UnsupportedCall("'Extractor(reassembly=False)' object has no attribute 'reassembly'")
448
+
449
+ @property
450
+ def trace(self) -> 'TraceFlowData':
451
+ """Index table for traced flow.
452
+
453
+ * ``tcp`` -- tuple of TCP flows (:term:`trace.tcp.index`)
454
+
455
+ Raises:
456
+ UnsupportedCall: If :attr:`self._flag_t <pcapkit.foundation.extraction.Extractor._flag_t>`
457
+ is :data:`False`, as flow tracing is disabled.
458
+
459
+ .. versionchanged:: 1.1.1
460
+
461
+ Raises :exc:`~pcapkit.utilities.exceptions.UnsupportedCall` when
462
+ flow tracing is disabled, where 1.1.0 built the record regardless.
463
+
464
+ """
465
+ if self._flag_t:
466
+ data = TraceFlowData(
467
+ tcp=tuple(self._trace.tcp.index) if self._tcp else None,
468
+ )
469
+ return data
470
+ raise UnsupportedCall("'Extractor(trace=False)' object has no attribute 'trace'")
471
+
472
+ @property
473
+ def engine(self) -> 'EngineBase[_P]':
474
+ """PCAP extraction engine."""
475
+ return self._exeng
476
+
477
+ @property
478
+ def magic_number(self) -> 'bytes':
479
+ """Magic number of input PCAP file."""
480
+ return self._magic
481
+
482
+ ##########################################################################
483
+ # Methods.
484
+ ##########################################################################
485
+
486
+ @classmethod
487
+ def register_dumper(cls, format: 'str', dumper: 'ModuleDescriptor[Dumper] | Type[Dumper]', ext: 'str') -> 'None':
488
+ r"""Register a new dumper class.
489
+
490
+ Notes:
491
+ The fully qualified class name of the new dumper class
492
+ should be ``{dumper.module}.{dumper.name}``.
493
+
494
+ The overwrite guard fires only when the incumbent dumper differs
495
+ from the replacement, so re-registering the exact same object is
496
+ a silent no-op rather than a warning about nothing displaced --
497
+ the identity guard of the code-keyed registrars (:issue:`718`,
498
+ :issue:`739`). ``__output__``
499
+ maps each format to a ``(dumper, ext)`` pair, so the identity
500
+ check compares the incumbent *dumper* (index ``0``), not the
501
+ pair -- a re-registration that only changes ``ext`` is still
502
+ identity-equal on the dumper and stays silent, since the dumper
503
+ is what "the same object" means here, not the pair as a whole.
504
+ ``__output__`` is also a :class:`collections.defaultdict`,
505
+ unlike the engine, reassembly and flow tracing registries;
506
+ :meth:`dict.get` does not invoke
507
+ the default factory the way ``cls.__output__[format]`` would, so
508
+ it stays non-inserting here as well.
509
+
510
+ The dumper ``format`` shipped with, as its descriptor or as the
511
+ class it names, restores the shipped entry rather than storing
512
+ the class, so an override can be undone and the deferred import
513
+ is kept (:issue:`1363`, :issue:`1364`).
514
+
515
+ Arguments:
516
+ format: format name
517
+ dumper: module descriptor or a :class:`dictdumper.dumper.Dumper` subclass
518
+ ext: file extension
519
+
520
+ Raises:
521
+ RegistryError: If ``dumper`` is not a class, or not a
522
+ :class:`dictdumper.dumper.Dumper` subclass, such as
523
+ :class:`~pcapkit.dumpkit.common.Dumper`.
524
+
525
+ Warns:
526
+ RegistryWarning: If a different dumper is already registered for
527
+ ``format``; it is overwritten.
528
+
529
+ .. versionchanged:: 1.3.0
530
+
531
+ ``dumper``, a module descriptor or a class, replaces the ``module``
532
+ and ``class_`` name pair, with no alias.
533
+
534
+ """
535
+ shipped = cls._shipped_output.get(format)
536
+ if isinstance(dumper, ModuleDescriptor) and (shipped is None or dumper != shipped[0]):
537
+ dumper = dumper.klass
538
+ if shipped is not None and same_entry(shipped[0], dumper):
539
+ restore_shipped_dumper(cls.__output__, format, shipped, ext)
540
+ return
541
+ if not isinstance(dumper, type):
542
+ raise RegistryError(f'dumper must be a class, not {dumper!r}')
543
+ if not issubclass(dumper, Dumper):
544
+ raise RegistryError(f'dumper must be a Dumper subclass, not {dumper!r}')
545
+ incumbent_entry = cls.__output__.get(format)
546
+ incumbent = incumbent_entry[0] if incumbent_entry is not None else None
547
+ if incumbent is not None and incumbent is not dumper:
548
+ warn(f'dumper {format} already registered, overwriting', RegistryWarning)
549
+ cls.__output__[format] = (dumper, ext)
550
+
551
+ @classmethod
552
+ def register_engine(cls, name: 'str', engine: 'ModuleDescriptor[Engine] | Type[Engine]') -> 'None':
553
+ r"""Register a new extraction engine.
554
+
555
+ Notes:
556
+ The fully qualified class name of the new extraction engine
557
+ should be ``{engine.module}.{engine.name}``.
558
+
559
+ The overwrite guard fires only when the incumbent differs from
560
+ the replacement, so re-registering the exact same object is a
561
+ silent no-op rather than a warning about nothing displaced --
562
+ the identity guard of the code-keyed registrars (:issue:`718`,
563
+ :issue:`739`).
564
+
565
+ The one built-in admitted is the engine ``name`` shipped with, as
566
+ its descriptor or as the class it names: it restores the shipped
567
+ entry, so an override can be undone (:issue:`1363`).
568
+
569
+ Arguments:
570
+ name: engine name
571
+ engine: module descriptor or an :class:`~pcapkit.foundation.engines.engine.Engine`
572
+ subclass; a class deriving only from
573
+ :class:`~pcapkit.foundation.engines.engine.EngineBase` is refused, as
574
+ that is the base for pcapkit's own engines, which the library
575
+ registers itself (GitHub issue :issue:`1016`), unless it is the
576
+ engine ``name`` shipped with
577
+
578
+ Raises:
579
+ RegistryError: If ``engine`` is not a class, or not an
580
+ :class:`~pcapkit.foundation.engines.engine.Engine` subclass.
581
+
582
+ Warns:
583
+ RegistryWarning: If a different class is already registered under
584
+ ``name``; it is overwritten.
585
+
586
+ .. versionchanged:: 1.3.0
587
+
588
+ ``engine``, a module descriptor or a class, replaces the ``module``
589
+ and ``class_`` name pair, with no alias, and the engine name it
590
+ took as ``engine`` is ``name``.
591
+
592
+ """
593
+ # The shipped built-in is matched before the descriptor is resolved, so
594
+ # restoring an optional engine does not import it (#1363).
595
+ shipped = cls._shipped_engine.get(name)
596
+ if isinstance(engine, ModuleDescriptor) and engine != shipped:
597
+ engine = engine.klass
598
+ if shipped is not None and same_entry(shipped, engine):
599
+ restore_shipped(cls.__engine__, name, shipped, 'engine')
600
+ return
601
+ if not isinstance(engine, type):
602
+ raise RegistryError(f'engine must be a class, not {engine!r}')
603
+ # NOTE: the public door admits ``Engine`` subclasses only, not bare ``EngineBase``, which
604
+ # lacks the ``engine=`` hook (#513, #1016); a shipped built-in is restored above (#1363).
605
+ if not issubclass(engine, Engine):
606
+ raise RegistryError(f'engine must be an Engine subclass, not {engine!r}')
607
+ cls._register_internal_engine(name, engine)
608
+
609
+ @classmethod
610
+ def _register_internal_engine(cls, name: 'str', engine: 'ModuleDescriptor[EngineBase] | Type[EngineBase]') -> 'None':
611
+ """Register an engine for pcapkit's own use, bypassing the public guard.
612
+
613
+ Unlike :meth:`register_engine`, accepts a class deriving only from
614
+ :class:`~pcapkit.foundation.engines.engine.EngineBase`, which is how every
615
+ built-in engine is written. Not part of the public API.
616
+
617
+ Arguments:
618
+ name: engine name
619
+ engine: module descriptor or an
620
+ :class:`~pcapkit.foundation.engines.engine.EngineBase` subclass
621
+
622
+ Raises:
623
+ RegistryError: If ``engine`` is not an :class:`~pcapkit.foundation.engines.engine.EngineBase` subclass.
624
+
625
+ Warns:
626
+ RegistryWarning: If a different class is already registered under
627
+ ``name``; it is overwritten.
628
+
629
+ """
630
+ if isinstance(engine, ModuleDescriptor):
631
+ engine = engine.klass
632
+ if not issubclass(engine, EngineBase):
633
+ raise RegistryError(f'Extractor._register_internal_engine: engine must be an EngineBase subclass, not {engine!r}')
634
+ incumbent = cls.__engine__.get(name)
635
+ if incumbent is not None and incumbent is not engine:
636
+ warn(f'engine {name} already registered, overwriting', RegistryWarning)
637
+ cls.__engine__[name] = engine
638
+
639
+ @classmethod
640
+ def register_reassembly(cls, protocol: 'str', reassembly: 'ModuleDescriptor[Reassembly] | Type[Reassembly]') -> 'None':
641
+ r"""Register a new reassembly engine.
642
+
643
+ Notes:
644
+ The fully qualified class name of the new reassembly engine
645
+ should be ``{reassembly.module}.{reassembly.name}``.
646
+
647
+ The overwrite guard fires only when the incumbent differs from
648
+ the replacement, so re-registering the exact same object is a
649
+ silent no-op rather than a warning about nothing displaced --
650
+ the identity guard of the code-keyed registrars (:issue:`718`,
651
+ :issue:`739`).
652
+
653
+ The one built-in admitted is the class ``protocol`` shipped with,
654
+ as its descriptor or as the class it names: it restores the
655
+ shipped entry, so an override can be undone (:issue:`1363`).
656
+
657
+ Arguments:
658
+ protocol: protocol name
659
+ reassembly: module descriptor or a
660
+ :class:`~pcapkit.foundation.reassembly.reassembly.Reassembly` subclass; a class deriving
661
+ only from :class:`~pcapkit.foundation.reassembly.reassembly.ReassemblyBase` is refused, as
662
+ that is the base for pcapkit's own classes, which the library registers
663
+ itself (GitHub issue :issue:`1016`), unless it is the class
664
+ ``protocol`` shipped with
665
+
666
+ Raises:
667
+ RegistryError: If ``reassembly`` is not a class, or not a
668
+ :class:`~pcapkit.foundation.reassembly.reassembly.Reassembly` subclass.
669
+
670
+ Warns:
671
+ RegistryWarning: If a different class is already registered under
672
+ ``protocol``; it is overwritten.
673
+
674
+ .. versionchanged:: 1.3.0
675
+
676
+ ``reassembly``, a module descriptor or a class, replaces the
677
+ ``module`` and ``class_`` name pair, with no alias.
678
+
679
+ """
680
+ shipped = cls._shipped_reassembly.get(protocol)
681
+ if isinstance(reassembly, ModuleDescriptor) and reassembly != shipped:
682
+ reassembly = reassembly.klass
683
+ if shipped is not None and same_entry(shipped, reassembly):
684
+ restore_shipped(cls.__reassembly__, protocol, shipped, 'reassembly')
685
+ return
686
+ if not isinstance(reassembly, type):
687
+ raise RegistryError(f'reassembly must be a class, not {reassembly!r}')
688
+ # NOTE: ``Reassembly`` rather than ``ReassemblyBase``, as in :meth:`register_engine`
689
+ # (#1016); built-ins go through :meth:`_register_internal_reassembly` (#1363).
690
+ if not issubclass(reassembly, Reassembly):
691
+ raise RegistryError(f'reassembly must be a Reassembly subclass, not {reassembly!r}')
692
+ cls._register_internal_reassembly(protocol, reassembly)
693
+
694
+ @classmethod
695
+ def _register_internal_reassembly(cls, protocol: 'str', reassembly: 'ModuleDescriptor[ReassemblyBase] | Type[ReassemblyBase]') -> 'None':
696
+ """Register a reassembly class for pcapkit's own use, bypassing the public guard.
697
+
698
+ Unlike :meth:`register_reassembly`, accepts a class deriving only from
699
+ :class:`~pcapkit.foundation.reassembly.reassembly.ReassemblyBase`, which is how every
700
+ built-in is written. Not part of the public API.
701
+
702
+ Arguments:
703
+ protocol: protocol name
704
+ reassembly: module descriptor or a
705
+ :class:`~pcapkit.foundation.reassembly.reassembly.ReassemblyBase` subclass
706
+
707
+ Raises:
708
+ RegistryError: If ``reassembly`` is not a
709
+ :class:`~pcapkit.foundation.reassembly.reassembly.ReassemblyBase` subclass.
710
+
711
+ Warns:
712
+ RegistryWarning: If a different class is already registered under
713
+ ``protocol``; it is overwritten.
714
+
715
+ """
716
+ if isinstance(reassembly, ModuleDescriptor):
717
+ reassembly = reassembly.klass
718
+ if not issubclass(reassembly, ReassemblyBase):
719
+ raise RegistryError(f'Extractor._register_internal_reassembly: reassembly must be a ReassemblyBase subclass, not {reassembly!r}')
720
+ incumbent = cls.__reassembly__.get(protocol)
721
+ if incumbent is not None and incumbent is not reassembly:
722
+ warn(f'reassembly {protocol} already registered, overwriting', RegistryWarning)
723
+ cls.__reassembly__[protocol] = reassembly
724
+
725
+ @classmethod
726
+ def register_traceflow(cls, protocol: 'str', traceflow: 'ModuleDescriptor[TraceFlow] | Type[TraceFlow]') -> 'None':
727
+ r"""Register a new flow tracing engine.
728
+
729
+ Notes:
730
+ The fully qualified class name of the new flow tracing engine
731
+ should be ``{traceflow.module}.{traceflow.name}``.
732
+
733
+ The overwrite guard fires only when the incumbent differs from
734
+ the replacement, so re-registering the exact same object is a
735
+ silent no-op rather than a warning about nothing displaced --
736
+ the identity guard of the code-keyed registrars (:issue:`718`,
737
+ :issue:`739`).
738
+
739
+ The one built-in admitted is the class ``protocol`` shipped with,
740
+ as its descriptor or as the class it names: it restores the
741
+ shipped entry, so an override can be undone (:issue:`1363`).
742
+
743
+ Arguments:
744
+ protocol: protocol name
745
+ traceflow: module descriptor or a
746
+ :class:`~pcapkit.foundation.traceflow.traceflow.TraceFlow` subclass; a class deriving
747
+ only from :class:`~pcapkit.foundation.traceflow.traceflow.TraceFlowBase` is refused, as
748
+ that is the base for pcapkit's own classes, which the library registers
749
+ itself (GitHub issue :issue:`1016`), unless it is the class
750
+ ``protocol`` shipped with
751
+
752
+ Raises:
753
+ RegistryError: If ``traceflow`` is not a class, or not a
754
+ :class:`~pcapkit.foundation.traceflow.traceflow.TraceFlow` subclass.
755
+
756
+ Warns:
757
+ RegistryWarning: If a different class is already registered under
758
+ ``protocol``; it is overwritten.
759
+
760
+ .. versionchanged:: 1.3.0
761
+
762
+ ``traceflow``, a module descriptor or a class, replaces the
763
+ ``module`` and ``class_`` name pair, with no alias.
764
+
765
+ """
766
+ shipped = cls._shipped_traceflow.get(protocol)
767
+ if isinstance(traceflow, ModuleDescriptor) and traceflow != shipped:
768
+ traceflow = traceflow.klass
769
+ if shipped is not None and same_entry(shipped, traceflow):
770
+ restore_shipped(cls.__traceflow__, protocol, shipped, 'traceflow')
771
+ return
772
+ if not isinstance(traceflow, type):
773
+ raise RegistryError(f'traceflow must be a class, not {traceflow!r}')
774
+ # NOTE: ``TraceFlow`` rather than ``TraceFlowBase``, as in :meth:`register_engine`
775
+ # (#1016); built-ins go through :meth:`_register_internal_traceflow` (#1363).
776
+ if not issubclass(traceflow, TraceFlow):
777
+ raise RegistryError(f'traceflow must be a TraceFlow subclass, not {traceflow!r}')
778
+ cls._register_internal_traceflow(protocol, traceflow)
779
+
780
+ @classmethod
781
+ def _register_internal_traceflow(cls, protocol: 'str', traceflow: 'ModuleDescriptor[TraceFlowBase] | Type[TraceFlowBase]') -> 'None':
782
+ """Register a traceflow class for pcapkit's own use, bypassing the public guard.
783
+
784
+ Unlike :meth:`register_traceflow`, accepts a class deriving only from
785
+ :class:`~pcapkit.foundation.traceflow.traceflow.TraceFlowBase`, which is how every
786
+ built-in is written. Not part of the public API.
787
+
788
+ Arguments:
789
+ protocol: protocol name
790
+ traceflow: module descriptor or a
791
+ :class:`~pcapkit.foundation.traceflow.traceflow.TraceFlowBase` subclass
792
+
793
+ Raises:
794
+ RegistryError: If ``traceflow`` is not a
795
+ :class:`~pcapkit.foundation.traceflow.traceflow.TraceFlowBase` subclass.
796
+
797
+ Warns:
798
+ RegistryWarning: If a different class is already registered under
799
+ ``protocol``; it is overwritten.
800
+
801
+ """
802
+ if isinstance(traceflow, ModuleDescriptor):
803
+ traceflow = traceflow.klass
804
+ if not issubclass(traceflow, TraceFlowBase):
805
+ raise RegistryError(f'Extractor._register_internal_traceflow: traceflow must be a TraceFlowBase subclass, not {traceflow!r}')
806
+ incumbent = cls.__traceflow__.get(protocol)
807
+ if incumbent is not None and incumbent is not traceflow:
808
+ warn(f'traceflow {protocol} already registered, overwriting', RegistryWarning)
809
+ cls.__traceflow__[protocol] = traceflow
810
+
811
+ def run(self) -> 'None': # pylint: disable=inconsistent-return-statements
812
+ """Start extraction.
813
+
814
+ We use :meth:`~pcapkit.foundation.extraction.Extractor.import_test` to check if
815
+ a certain engine is available or not. For supported engines, each engine has
816
+ different driver method:
817
+
818
+ * Default drivers:
819
+
820
+ - PCAP Format: :class:`pcapkit.foundation.engines.pcap.PCAP`
821
+ - PCAP-NG Format: :class:`pcapkit.foundation.engines.pcapng.PCAPNG`
822
+
823
+ * DPKT driver: :class:`pcapkit.foundation.engines.dpkt.DPKT`
824
+ * Scapy driver: :class:`pcapkit.foundation.engines.scapy.Scapy`
825
+ * PyShark driver: :class:`pcapkit.foundation.engines.pyshark.PyShark`
826
+ * PyPCAP driver: :class:`pcapkit.foundation.engines.pypcap.PyPCAP`
827
+ * pcap-ct driver: :class:`pcapkit.foundation.engines.pcap_ct.PCAP_CT`
828
+ * PyPCAPFile driver: :class:`pcapkit.foundation.engines.pypcapfile.PyPCAPFile`
829
+
830
+ Note:
831
+ An unavailable engine is not reported here: :meth:`__init__` settles
832
+ the engine, and warns about it, before calling this method.
833
+
834
+ Raises:
835
+ FormatError: If the selected engine cannot read the input's format --
836
+ for the :term:`default engine`, if it is neither PCAP nor PCAP-NG -- or if
837
+ the built-in PCAP-NG engine reads a PCAP-NG input to PCAP output.
838
+
839
+ :rtype: None
840
+ """
841
+ eng = self._select_engine()
842
+ if eng is not None:
843
+ logger.debug('using engine %s (%s)', eng.name, eng.module)
844
+ with self._exprb:
845
+ self._exeng = eng(self)
846
+ self._exeng.run()
847
+ self._open_output()
848
+
849
+ # start iteration
850
+ self.record_frames()
851
+ return
852
+
853
+ if self._magic in PCAP_Engine.MAGIC_NUMBER:
854
+ logger.debug('magic number %r identifies a PCAP file', self._magic)
855
+ self._exeng = cast('EngineBase[_P]', PCAP_Engine(self))
856
+ elif self._magic in PCAPNG_Engine.MAGIC_NUMBER:
857
+ logger.debug('magic number %r identifies a PCAP-NG file', self._magic)
858
+ self._exeng = cast('EngineBase[_P]', PCAPNG_Engine(self))
859
+ else:
860
+ raise FormatError(f'unknown file format: {self._magic!r}')
861
+
862
+ # start engine
863
+ self._exeng.run()
864
+ self._open_output()
865
+
866
+ # start iteration
867
+ self.record_frames()
868
+
869
+ def _select_engine(self) -> 'Optional[Type[EngineBase]]':
870
+ """Settle which extraction engine will actually run.
871
+
872
+ An engine that is unknown, not installed, or rules itself out via
873
+ :meth:`~pcapkit.foundation.engines.engine.EngineBase.unsupported_reason`
874
+ is replaced by the :term:`default engine`, and :attr:`self._exnam
875
+ <pcapkit.foundation.extraction.Extractor._exnam>` is updated to match.
876
+ :meth:`__init__` calls this before choosing the output format, so that
877
+ the choice reflects the engine that runs rather than the one requested.
878
+
879
+ Calling it again is silent: a fallback has already set the name to
880
+ ``'default'``, and an engine that passed the checks passes them again.
881
+
882
+ Warns:
883
+ pcapkit.utilities.warnings.EngineWarning: If the extraction engine is not
884
+ available: its dependency is not installed, its
885
+ :meth:`~pcapkit.foundation.engines.engine.EngineBase.unsupported_reason`
886
+ rules it out, or the supplied engine is unknown.
887
+
888
+ Returns:
889
+ The engine class to run, or :data:`None` for the default engine,
890
+ which :meth:`run` picks from the input's magic number.
891
+
892
+ """
893
+ logger.debug('requested extraction engine: %s', self._exnam)
894
+
895
+ if self._exnam in self.__engine__: # check if engine is supported
896
+ eng = self.__engine__[self._exnam]
897
+ if isinstance(eng, ModuleDescriptor):
898
+ eng = eng.klass
899
+
900
+ # An engine may rule itself out before the import is even attempted.
901
+ # Asking it is necessary because ``import_test`` can only see whether
902
+ # the top-level module imports, which is not the same question: a
903
+ # package whose *submodules* fail leaves the guard satisfied and the
904
+ # failure to escape from the engine's constructor instead. The base
905
+ # class answers :data:`None`, so only engines with a real limitation
906
+ # override it.
907
+ #
908
+ # NOTE: one probe serves both calls of this method and the engine's
909
+ # constructor in ``run``, rather than one each (#2113).
910
+ if not hasattr(self, '_exprb'):
911
+ self._exprb = _pcap_backend.Memo()
912
+ with self._exprb:
913
+ reason = eng.unsupported_reason()
914
+ if reason is not None:
915
+ logger.debug('engine %s is unavailable: %s', eng.name, reason)
916
+ warn(f'engine {eng.name} is not supported on this interpreter '
917
+ f'({reason}); using default engine instead',
918
+ EngineWarning, stacklevel=stacklevel())
919
+ self._exnam = 'default'
920
+ elif self.import_test(eng.module, name=eng.name) is not None: # type: ignore[arg-type]
921
+ return eng
922
+ else:
923
+ # ``import_test`` has already warned that the package is absent;
924
+ # warning again here would report one problem twice.
925
+ self._exnam = 'default' # using default/pcapkit engine
926
+
927
+ if self._exnam not in ('default', 'pcapkit'):
928
+ warn(f'unsupported extraction engine: {self._exnam!r}; '
929
+ 'using default engine instead', EngineWarning, stacklevel=stacklevel())
930
+ self._exnam = 'default' # using default/pcapkit engine
931
+ return None
932
+
933
+ @staticmethod
934
+ def import_test(engine: 'str', *, name: 'Optional[str]' = None) -> 'Optional[ModuleType]':
935
+ """Test import for extraction engine.
936
+
937
+ Args:
938
+ engine: Extraction engine module name.
939
+ name: Extraction engine display name.
940
+
941
+ Warns:
942
+ pcapkit.utilities.warnings.EngineWarning: If the engine module is not installed.
943
+
944
+ Returns:
945
+ If succeeded, returns the module; otherwise, returns :data:`None`.
946
+
947
+ """
948
+ try:
949
+ module = importlib.import_module(engine)
950
+ except ImportError:
951
+ module = None
952
+ logger.debug('engine module %r is not importable', engine)
953
+ label = f'{name} (`{engine}`)' if name else engine
954
+ warn(f'engine {label} is not installed; '
955
+ 'using default engine instead', EngineWarning, stacklevel=stacklevel())
956
+ return module
957
+
958
+ @classmethod
959
+ def make_name(cls, fin: 'str | IO[bytes]' = 'in.pcap', fout: 'str' = 'out',
960
+ fmt: 'Formats' = 'tree', extension: 'bool' = True, *, files: 'bool' = False,
961
+ nofile: 'bool' = False) -> 'tuple[str, Optional[str], Formats, Optional[str], bool]':
962
+ """Generate input and output filenames.
963
+
964
+ The method will perform following processing:
965
+
966
+ 1. sanitise ``fin`` as the input PCAP filename; ``in.pcap`` as default value and
967
+ append ``.pcap`` extension if needed and ``extension`` is :data:`True`; as well
968
+ as test if the file exists; for a binary IO object, use its ``name``,
969
+ or a placeholder such as ``<BytesIO>`` if it has no :obj:`str` one;
970
+ 2. if ``nofile`` is :data:`True`, skips following processing;
971
+ 3. look up the output file extension registered for ``fmt``; should none be
972
+ registered, then it raises :exc:`~pcapkit.utilities.exceptions.FormatError`;
973
+ 4. create the parent directory of ``fout``, and with ``files`` the ``fout``
974
+ directory itself;
975
+ 5. it will also append corresponding file extension to the output file name if needed
976
+ and ``extension`` is :data:`True`.
977
+
978
+ And the method returns the generated input and output filenames as follows:
979
+
980
+ 0. input filename
981
+ 1. output filename / directory name
982
+ 2. output format
983
+ 3. output file extension, bare, i.e. **without** the leading ``.``, so
984
+ that a caller composing a per-frame filename writes
985
+ ``f'{name}.{ext}'``
986
+ 4. if split each frame into different files
987
+
988
+ Args:
989
+ fin: Input filename or a binary IO object.
990
+ fout: Output filename.
991
+ fmt: Output file format.
992
+ extension: If append ``.pcap`` file extension to the input filename
993
+ if ``fin`` does not have such file extension; if check and append extensions
994
+ to output file.
995
+ files: If split each frame into different files.
996
+ nofile: If no output file is to be dumped.
997
+
998
+ Returns:
999
+ Generated input and output filenames.
1000
+
1001
+ Raises:
1002
+ FileNotFound: If input file does not exist.
1003
+ FormatError: If no file extension is registered for ``fmt``.
1004
+
1005
+ """
1006
+ if isinstance(fin, str):
1007
+ if extension: # pylint: disable=else-if-used
1008
+ ifnm = fin if os.path.splitext(fin)[1] in cls.PCAP_EXT else f'{fin}.pcap'
1009
+ else:
1010
+ ifnm = fin
1011
+
1012
+ if not os.path.isfile(ifnm):
1013
+ raise FileNotFound(2, 'No such file or directory', ifnm)
1014
+ else:
1015
+ # NOTE: a binary IO object need not have a ``str`` ``name`` (#1506); it is only a label
1016
+ # here, so fall back to a ``<BytesIO>``-style one, after Python's own ``<stdin>``.
1017
+ name = getattr(fin, 'name', None)
1018
+ ifnm = name if isinstance(name, str) else f'<{type(fin).__name__}>'
1019
+
1020
+ if nofile:
1021
+ ofnm = None
1022
+ ext = None
1023
+ else:
1024
+ # NOTE: ``__output__`` is a defaultdict; subscripting would insert an
1025
+ # unknown format into the registry before the error below is raised.
1026
+ entry = cls.__output__.get(fmt)
1027
+ registered = entry[1] if entry is not None else None
1028
+ if registered is None:
1029
+ raise FormatError(f'unknown output format: {fmt!r}')
1030
+
1031
+ # NOTE: registered extensions carry the leading dot but the value returned is bare, so
1032
+ # strip it once here; per-frame names otherwise read ``Frame 1..json`` (#358).
1033
+ ext = registered[1:] if registered.startswith('.') else registered
1034
+
1035
+ if (parent := os.path.split(fout)[0]):
1036
+ os.makedirs(parent, exist_ok=True)
1037
+
1038
+ if files:
1039
+ ofnm = fout
1040
+ os.makedirs(ofnm, exist_ok=True)
1041
+ elif extension:
1042
+ # NOTE: The dot belongs to the separator here, not to ``ext``.
1043
+ ofnm = fout if os.path.splitext(fout)[1] == f'.{ext}' else f'{fout}.{ext}'
1044
+ else:
1045
+ ofnm = fout
1046
+
1047
+ return ifnm, ofnm, fmt, ext, files
1048
+
1049
+ def record_header(self) -> 'EngineBase[_P]':
1050
+ """Read global header.
1051
+
1052
+ The method parses the global header with the matching built-in engine --
1053
+ :class:`~pcapkit.foundation.engines.pcap.PCAP` for a PCAP file, or
1054
+ :class:`~pcapkit.foundation.engines.pcapng.PCAPNG` for the first section
1055
+ header block of a PCAP-NG file -- rewinds the input to its start, and
1056
+ returns that engine, which holds the parsed header.
1057
+
1058
+ Unless output is disabled, the engine also dumps the parsed header, under
1059
+ the name of ``Global Header`` for PCAP and ``Section Header 1`` for
1060
+ PCAP-NG, and sets :attr:`self._offmt <Extractor._offmt>` to the output
1061
+ format.
1062
+
1063
+ This is the shared global-header step of the third-party engines --
1064
+ :class:`~pcapkit.foundation.engines.dpkt.DPKT`,
1065
+ :class:`~pcapkit.foundation.engines.scapy.Scapy` and
1066
+ :class:`~pcapkit.foundation.engines.pyshark.PyShark` -- which call it at
1067
+ setup, so their output opens with the header record dumped above and
1068
+ :attr:`format` is set even for a capture with no frames.
1069
+
1070
+ Raises:
1071
+ FormatError: If the input is neither a PCAP nor a PCAP-NG file.
1072
+
1073
+ """
1074
+ # pylint: disable=attribute-defined-outside-init,protected-access
1075
+ if self._magic in PCAP_Engine.MAGIC_NUMBER:
1076
+ engine = PCAP_Engine(self)
1077
+ engine.run()
1078
+
1079
+ self._ifile.seek(0, os.SEEK_SET)
1080
+ return engine # type: ignore[return-value]
1081
+
1082
+ if self._magic in PCAPNG_Engine.MAGIC_NUMBER:
1083
+ engine = PCAPNG_Engine(self) # type: ignore[assignment]
1084
+ engine.run()
1085
+
1086
+ self._ifile.seek(0, os.SEEK_SET)
1087
+ return engine # type: ignore[return-value]
1088
+
1089
+ raise FormatError(f'unknown file format: {self._magic!r}')
1090
+
1091
+ def _open_output(self, **kwargs: 'Any') -> 'None':
1092
+ """Create the output writer.
1093
+
1094
+ The built-in engines call this at their global-header step. The PCAP
1095
+ engine passes the header's fields as ``protocol``, ``byteorder``,
1096
+ ``nanosecond``, ``version``, ``thiszone``, ``sigfigs`` and ``snaplen``:
1097
+ :class:`~pcapkit.dumpkit.pcap.PCAPIO` writes its own global header from
1098
+ them, and the other writers ignore them. The PCAP-NG engine passes none.
1099
+ :meth:`run` calls it again, without arguments, after the engine has
1100
+ started, for the engines that have no such step. Only the first call has
1101
+ an effect.
1102
+
1103
+ Under split mode, i.e. :attr:`self._flag_f <Extractor._flag_f>` is
1104
+ :data:`True`, :attr:`self._ofile <Extractor._ofile>` stays a factory,
1105
+ with ``kwargs`` bound, that the engines call once per output file.
1106
+
1107
+ Args:
1108
+ **kwargs: Global header fields for the writer.
1109
+
1110
+ """
1111
+ if self._flag_q or self._flag_o:
1112
+ return
1113
+ self._flag_o = True
1114
+
1115
+ if self._flag_f:
1116
+ self._ofile = functools.partial(self._ofile, **kwargs) # type: ignore[misc]
1117
+ else:
1118
+ self._ofile = self._ofile(self._ofnm, **kwargs)
1119
+
1120
+ def record_frames(self) -> 'None':
1121
+ """Read packet frames.
1122
+
1123
+ The method calls :meth:`self._exeng.read_frame <pcapkit.foundation.engines.engine.EngineBase.read_frame>`
1124
+ to parse each frame from the input PCAP file; and
1125
+ performs cleanup by calling :meth:`self._exeng.close <pcapkit.foundation.engines.engine.EngineBase.close>`
1126
+ upon completion of the parsing process.
1127
+
1128
+ Notes:
1129
+ Under non-auto mode, i.e. :attr:`self._flag_a <Extractor._flag_a>` is
1130
+ :data:`False`, the method performs no action.
1131
+
1132
+ """
1133
+ if self._flag_a:
1134
+ logger.debug('reading frames from %s', self._ifnm)
1135
+ while True:
1136
+ try:
1137
+ self._exeng.read_frame()
1138
+ except (EOFError, StopIteration):
1139
+ warn('EOF reached', ExtractionWarning, stacklevel=stacklevel())
1140
+
1141
+ # ``no_eof`` retries -- but only while the input is still
1142
+ # producing, or an exhausted stream spins here forever (#620).
1143
+ if self._flag_n and self._note_eof_progress():
1144
+ continue
1145
+
1146
+ # quit when EOF
1147
+ break
1148
+ except KeyboardInterrupt:
1149
+ logger.debug('interrupted after %d frame(s)', self._frnum)
1150
+ self._cleanup()
1151
+ raise
1152
+
1153
+ logger.debug('read %d frame(s) from %s', self._frnum, self._ifnm)
1154
+ self._cleanup()
1155
+
1156
+ ##########################################################################
1157
+ # Data models.
1158
+ ##########################################################################
1159
+
1160
+ def __init__(self,
1161
+ fin: 'Optional[str | IO[bytes]]' = None, fout: 'Optional[str]' = None, format: 'Optional[Formats]' = None, # basic settings # pylint: disable=redefined-builtin
1162
+ auto: 'bool' = True, extension: 'bool' = True, store: 'bool' = True, # internal settings # pylint: disable=line-too-long
1163
+ files: 'bool' = False, nofile: 'bool' = False, verbose: 'bool | VerboseHandler' = False, # output settings # pylint: disable=line-too-long
1164
+ engine: 'Optional[Engines]' = None, layer: 'Optional[Layers]' = None, protocol: 'Optional[Protocols]' = None, # extraction settings # pylint: disable=line-too-long
1165
+ reassembly: 'bool' = False, reasm_strict: 'bool' = True, reasm_store: 'bool' = True, # reassembly settings # pylint: disable=line-too-long
1166
+ reasm_timeout: 'Optional[float]' = None, # reassembly settings # pylint: disable=line-too-long
1167
+ trace: 'bool' = False, trace_fout: 'Optional[str]' = None, trace_format: 'Optional[Formats]' = None, # trace settings # pylint: disable=line-too-long
1168
+ trace_byteorder: 'Literal["big", "little"]' = sys.byteorder, trace_nanosecond: 'bool' = False, # trace settings # pylint: disable=line-too-long
1169
+ trace_bidirectional: 'bool' = True, trace_analyse: 'bool' = False, # trace settings # pylint: disable=line-too-long
1170
+ ip: 'bool' = False, ipv4: 'bool' = False, ipv6: 'bool' = False, tcp: 'bool' = False, # reassembly/trace settings # pylint: disable=line-too-long
1171
+ dtls: 'bool' = False, # reassembly settings # pylint: disable=line-too-long
1172
+ buffer_size: 'int' = io.DEFAULT_BUFFER_SIZE, buffer_save: 'bool' = False, buffer_path: 'Optional[str]' = None, # buffer settings # pylint: disable=line-too-long
1173
+ no_eof: 'bool' = False, # EOF settings # pylint: disable=line-too-long
1174
+ context: 'Optional[ContextRegistry | ProtocolContext | Mapping[str, ProtocolContext] | Iterable[ProtocolContext]]' = None) -> 'None': # context settings # pylint: disable=line-too-long
1175
+ """Initialise PCAP Reader.
1176
+
1177
+ Args:
1178
+ fin: file name to be read or a binary IO object;
1179
+ if file not exist, raise :exc:`~pcapkit.utilities.exceptions.FileNotFound`
1180
+ fout: file name to be written
1181
+ format: file format of output
1182
+
1183
+ auto: if automatically run till EOF
1184
+ extension: if check and append extensions to output file
1185
+ store: if store extracted packet info
1186
+
1187
+ files: if split each frame into different files
1188
+ nofile: if no output file is to be dumped
1189
+ verbose: a :obj:`bool` value or a function takes the :class:`Extractor`
1190
+ instance and current parsed frame (depends on engine selected) as
1191
+ parameters to print verbose output information
1192
+
1193
+ engine: extraction engine to be used
1194
+ layer: extract til which layer
1195
+ protocol: extract til which protocol
1196
+
1197
+ reassembly: if perform reassembly
1198
+ reasm_strict: if set strict flag for reassembly
1199
+ reasm_store: if store reassembled datagrams
1200
+ reasm_timeout: reassembly timeout in seconds, measured on the
1201
+ *capture's* own clock rather than the host's, since an offline
1202
+ parser has no other notion of time passing; :data:`None` selects
1203
+ each protocol's own default -- 60 seconds for IPv4
1204
+ (:rfc:`1122#section-3.3.2`) and IPv6 (:rfc:`8200#section-4.5`),
1205
+ disabled for TCP, which no specification gives a deadline. Pass
1206
+ :data:`math.inf` to disable it everywhere; DTLS reassembly takes
1207
+ none (:rfc:`6347#section-4.2.3`)
1208
+
1209
+ trace: if trace TCP traffic flows
1210
+ trace_fout: path name for flow tracer if necessary
1211
+ trace_format: output file format of flow tracer
1212
+ trace_byteorder: output file byte order
1213
+ trace_nanosecond: output nanosecond-resolution file flag
1214
+ trace_bidirectional: whether both halves of a conversation are
1215
+ traced as one flow, which is the default; :data:`False` traces
1216
+ a flow per direction
1217
+ trace_analyse: whether each traced flow reassembles its application
1218
+ layer, so that its ``packet`` can be read. Off by default,
1219
+ because it buffers every traced payload -- a cost tracing does
1220
+ not otherwise pay. Unavailable on the ``pyshark`` engine, which
1221
+ reports dissected fields rather than the octets behind them
1222
+
1223
+ ip: if record data for IPv4 & IPv6 reassembly (must be used with ``reassembly=True``)
1224
+ ipv4: if perform IPv4 reassembly (must be used with ``reassembly=True``)
1225
+ ipv6: if perform IPv6 reassembly (must be used with ``reassembly=True``)
1226
+ tcp: if perform TCP reassembly and/or flow tracing
1227
+ (must be used with ``reassembly=True`` or ``trace=True``)
1228
+ dtls: if perform DTLS handshake-message reassembly (must be used
1229
+ with ``reassembly=True``); the default engine alone supports it
1230
+
1231
+ buffer_size: buffer size for reading input file (for :class:`~pcapkit.corekit.io.SeekableReader` only)
1232
+ buffer_save: if save buffer to file (for :class:`~pcapkit.corekit.io.SeekableReader` only)
1233
+ buffer_path: path name for buffer file if necessary (for :class:`~pcapkit.corekit.io.SeekableReader` only)
1234
+
1235
+ no_eof: if not raise :exc:`EOFError` when reach EOF -- retry instead,
1236
+ which is what a live capture on a pipe or on standard input wants,
1237
+ since a read there blocks until the writer produces more or closes.
1238
+ Retrying stops as soon as one retry finds nothing new, so an
1239
+ exhausted input finishes rather than spinning; on a *seekable*
1240
+ input, where nothing blocks, that means a file still being appended
1241
+ to ends at the data present when the extraction reached it
1242
+
1243
+ context: caller supplied parsing context for protocols that need
1244
+ information not carried on the wire, keyed by protocol index
1245
+ ID -- cf. :mod:`pcapkit.corekit.context`. Accepts a
1246
+ :class:`~pcapkit.corekit.context.ContextRegistry`, a single
1247
+ :class:`~pcapkit.corekit.context.ProtocolContext`, a mapping,
1248
+ or any iterable of contexts. The channel is honoured by the
1249
+ :term:`default engine`, whose PCAP and PCAP-NG readers parse
1250
+ with :mod:`pcapkit`'s own protocol implementations; the third
1251
+ party engines ignore it.
1252
+
1253
+ Warns:
1254
+ pcapkit.utilities.warnings.FormatWarning: Warns under the following circumstances:
1255
+
1256
+ * If using PCAP output for TCP flow tracing while the extraction engine is
1257
+ PyShark or PyPCAPFile.
1258
+ * If using PCAP output while the extraction engine is a third-party
1259
+ one, i.e. DPKT, Scapy, PyShark, PyPCAP, pcap-ct or PyPCAPFile.
1260
+ * If output file format is not supported.
1261
+
1262
+ In each case the engine is the one that will actually run: a
1263
+ requested engine that is unavailable falls back to the default
1264
+ engine first, which supports PCAP output.
1265
+
1266
+ pcapkit.utilities.warnings.EngineWarning: If the requested extraction
1267
+ engine is not available: its dependency is not installed, its
1268
+ :meth:`~pcapkit.foundation.engines.engine.EngineBase.unsupported_reason`
1269
+ rules it out, or the supplied engine is unknown.
1270
+ pcapkit.utilities.warnings.AttributeWarning: If ``trace_analyse`` is
1271
+ requested while the extraction engine is PyShark.
1272
+
1273
+ Raises:
1274
+ UnsupportedCall: If ``fin`` is a stream without a :obj:`str` ``name``
1275
+ and the engine that will run -- Scapy, PyShark, PyPCAP or
1276
+ pcap-ct -- opens its input by path.
1277
+
1278
+ """
1279
+ if fin is None:
1280
+ fin = 'in.pcap'
1281
+ if fout is None:
1282
+ fout = 'out'
1283
+ if format is None:
1284
+ format = 'tree'
1285
+
1286
+ # NOTE: settled first, since the format and trace checks depend on which
1287
+ # engine *runs*: an unavailable one falls back to the default engine.
1288
+ self._exnam = cast('Engines', (engine or 'default').lower()) # extract using engine
1289
+ self._select_engine()
1290
+
1291
+ # NOTE: these engines' adapters hand the writer a plain :obj:`dict` with no record
1292
+ # header, so the PCAP writer has nothing to write; the flow tracer gets the same fix below.
1293
+ if (self._exnam in ('dpkt', 'scapy', 'pyshark', 'pypcap', 'pcap_ct', 'pypcapfile')
1294
+ and format in ('pcap', 'cap')):
1295
+ warn(f"'Extractor(engine={self._exnam})' does not support 'format={format}'; "
1296
+ "using 'format=\"json\"' instead", FormatWarning, stacklevel=stacklevel())
1297
+ format = 'json'
1298
+
1299
+ # NOTE: these engines open ``_ifnm`` as a path, so a stream without a ``str`` name would
1300
+ # be opened as a file named ``<BytesIO>`` (#1506); refuse before anything runs.
1301
+ if (self._exnam in _PATH_ENGINES and not isinstance(fin, str)
1302
+ and not isinstance(getattr(fin, 'name', None), str)):
1303
+ raise UnsupportedCall(f"'Extractor(engine={self._exnam})' requires a file on disk, "
1304
+ f'but the {type(fin).__name__} given as fin has no name; '
1305
+ 'the engine opens savefiles by name and cannot read an '
1306
+ 'in-memory stream')
1307
+
1308
+ ifnm, ofnm, fmt, oext, files = self.make_name(fin, fout, format, extension, files=files, nofile=nofile)
1309
+
1310
+ self._ifnm = ifnm # input file name
1311
+ self._ofnm = ofnm # output file name
1312
+ self._fext = oext # output file extension
1313
+
1314
+ self._flag_a = auto # auto extract flag
1315
+ self._flag_d = store # store data flag
1316
+ self._flag_e = False # EOF flag
1317
+ self._flag_f = files # split file flag
1318
+ self._flag_q = nofile # no output flag
1319
+ self._flag_o = False # output opened flag
1320
+ self._flag_r = reassembly # reassembly flag
1321
+ self._flag_t = trace # trace flag
1322
+ self._flag_v = False # verbose flag
1323
+ self._flag_s = isinstance(fin, str) # input filename flag
1324
+ self._flag_n = no_eof # no EOF flag
1325
+ self._eof_mark = None # stream position at the last EOF
1326
+
1327
+ # verbose callback function
1328
+ if isinstance(verbose, bool):
1329
+ self._flag_v = verbose
1330
+ self._vfunc_default = verbose
1331
+ if verbose:
1332
+ # NOTE: ``verbose=True`` and ``-v`` ask for user-facing output, so this stays on
1333
+ # ``print`` rather than logging; only PCAP and PCAPNG keep this callback.
1334
+ self._vfunc = lambda e, f: print(
1335
+ f'Frame {e._frnum:>3d}: {cast("Frame | PCAPNG", f).protochain}' # pylint: disable=protected-access
1336
+ )
1337
+ else:
1338
+ self._vfunc = lambda e, f: None
1339
+ else:
1340
+ self._flag_v = True
1341
+ self._vfunc_default = False
1342
+ self._vfunc = verbose
1343
+
1344
+ self._frnum = 0 # frame number
1345
+ self._frame = [] # frame record
1346
+
1347
+ self._ipv4 = ipv4 or ip # IPv4 Reassembly
1348
+ self._ipv6 = ipv6 or ip # IPv6 Reassembly
1349
+ self._tcp = tcp # TCP Reassembly
1350
+ self._dtls = dtls # DTLS Reassembly
1351
+
1352
+ self._exptl = protocol or 'null' # extract til protocol
1353
+ self._exlyr = cast('Layers', (layer or 'none').lower()) # extract til layer
1354
+ self._exctx = ContextRegistry.make(context) # caller supplied context
1355
+
1356
+ if reassembly:
1357
+ reasm_obj_ipv4 = reasm_obj_ipv6 = reasm_obj_tcp = reasm_obj_dtls = None
1358
+
1359
+ if self._ipv4:
1360
+ logger.debug('IPv4 reassembly enabled')
1361
+
1362
+ reasm_cls_ipv4 = self.__reassembly__['ipv4']
1363
+ if isinstance(reasm_cls_ipv4, ModuleDescriptor):
1364
+ reasm_cls_ipv4 = reasm_cls_ipv4.klass
1365
+ self.__reassembly__['ipv4'] = reasm_cls_ipv4 # update mapping upon import
1366
+ reasm_obj_ipv4 = cast('IPv4_Reassembly', reasm_cls_ipv4(strict=reasm_strict, store=reasm_store,
1367
+ timeout=reasm_timeout))
1368
+ if self._ipv6:
1369
+ logger.debug('IPv6 reassembly enabled')
1370
+
1371
+ reasm_cls_ipv6 = self.__reassembly__['ipv6']
1372
+ if isinstance(reasm_cls_ipv6, ModuleDescriptor):
1373
+ reasm_cls_ipv6 = reasm_cls_ipv6.klass
1374
+ self.__reassembly__['ipv6'] = reasm_cls_ipv6 # update mapping upon import
1375
+ reasm_obj_ipv6 = cast('IPv6_Reassembly', reasm_cls_ipv6(strict=reasm_strict, store=reasm_store,
1376
+ timeout=reasm_timeout))
1377
+ if self._tcp:
1378
+ logger.debug('TCP reassembly enabled')
1379
+
1380
+ reasm_cls_tcp = self.__reassembly__['tcp']
1381
+ if isinstance(reasm_cls_tcp, ModuleDescriptor):
1382
+ reasm_cls_tcp = reasm_cls_tcp.klass
1383
+ self.__reassembly__['tcp'] = reasm_cls_tcp # update mapping upon import
1384
+ reasm_obj_tcp = cast('TCP_Reassembly', reasm_cls_tcp(strict=reasm_strict, store=reasm_store,
1385
+ timeout=reasm_timeout))
1386
+ if self._dtls:
1387
+ logger.debug('DTLS reassembly enabled')
1388
+
1389
+ reasm_cls_dtls = self.__reassembly__['dtls']
1390
+ if isinstance(reasm_cls_dtls, ModuleDescriptor):
1391
+ reasm_cls_dtls = reasm_cls_dtls.klass
1392
+ self.__reassembly__['dtls'] = reasm_cls_dtls # update mapping upon import
1393
+ # NOTE: no ``timeout``: the RFC gives DTLS handshake reassembly none.
1394
+ reasm_obj_dtls = cast('DTLS_Reassembly', reasm_cls_dtls(strict=reasm_strict, store=reasm_store))
1395
+
1396
+ self._reasm = ReassemblyManager(
1397
+ ipv4=reasm_obj_ipv4,
1398
+ ipv6=reasm_obj_ipv6,
1399
+ tcp=reasm_obj_tcp,
1400
+ dtls=reasm_obj_dtls,
1401
+ )
1402
+
1403
+ if trace:
1404
+ trace_obj_tcp = None
1405
+
1406
+ # NOTE: these adapters report plain :obj:`dict` frames the PCAP dumper cannot serialise,
1407
+ # and ``None`` means ``'pcap'`` (#406); DPKT and Scapy build frame records (#1507).
1408
+ if (self._exnam in ('pyshark', 'pypcapfile')
1409
+ and trace_format in ('pcap', 'cap', None)):
1410
+ warn(f"'Extractor(engine={self._exnam})' does not support 'trace_format={trace_format}'; "
1411
+ "using 'trace_format=\"json\"' instead", FormatWarning, stacklevel=stacklevel())
1412
+ trace_format = 'json'
1413
+
1414
+ # NOTE: PyShark hands the tracer fields, not octets, so there is no payload to
1415
+ # reassemble; refuse rather than return an empty answer that looks real.
1416
+ if trace_analyse and self._exnam == 'pyshark':
1417
+ warn(f"'Extractor(engine={self._exnam})' does not expose packet payloads; "
1418
+ "using 'trace_analyse=False' instead", AttributeWarning,
1419
+ stacklevel=stacklevel())
1420
+ trace_analyse = False
1421
+
1422
+ if self._tcp:
1423
+ logger.debug('TCP flow tracing enabled')
1424
+
1425
+ trace_cls_tcp = self.__traceflow__['tcp']
1426
+ if isinstance(trace_cls_tcp, ModuleDescriptor):
1427
+ trace_cls_tcp = trace_cls_tcp.klass
1428
+ self.__traceflow__['tcp'] = trace_cls_tcp # update mapping upon import
1429
+ trace_obj_tcp = cast('TCP_TraceFlow', trace_cls_tcp(fout=trace_fout, format=trace_format,
1430
+ byteorder=trace_byteorder, nanosecond=trace_nanosecond,
1431
+ bidirectional=trace_bidirectional,
1432
+ analyse=trace_analyse))
1433
+
1434
+ self._trace = TraceFlowManager(
1435
+ tcp=trace_obj_tcp,
1436
+ )
1437
+
1438
+ if self._flag_s:
1439
+ logger.debug('opening input file %s', ifnm)
1440
+ self._ifile = open(ifnm, 'rb') # input file # pylint: disable=unspecified-encoding,consider-using-with
1441
+ else:
1442
+ logger.debug('reading from the pre-opened stream %r', fin)
1443
+ self._ifile = cast('BufferedReader', fin)
1444
+
1445
+ # NOTE: a Windows pipe says it is seekable and then does not seek (#2097).
1446
+ if not can_seek(self._ifile):
1447
+ logger.debug('input stream is not seekable, wrapping it in SeekableReader')
1448
+ # NOTE: ``stream_closing`` follows ownership, closing only a handle this class opened; a
1449
+ # non-seekable stream always came from the caller, so this matches ``_cleanup`` (#610).
1450
+ self._ifile = SeekableReader(self._ifile, buffer_size, buffer_save, buffer_path,
1451
+ stream_closing=self._flag_s)
1452
+ elif not hasattr(self._ifile, 'peek'):
1453
+ logger.debug('input stream has no peek(), wrapping it in PeekableStream')
1454
+ self._ifile = cast('BufferedReader', PeekableStream(self._ifile))
1455
+
1456
+ # NOTE: the #606 backstop for an extraction abandoned before EOF, a ``weakref.finalize`` as
1457
+ # GraalPy never calls ``__del__`` (#1997); it holds the owned stream only, never ``self``.
1458
+ self._finalizer = None
1459
+ if self._owns_input():
1460
+ self._finalizer = weakref.finalize(self, _release_input, self._ifile)
1461
+
1462
+ if not self._flag_q:
1463
+ output, ext = self.__output__[fmt]
1464
+ if ext is None:
1465
+ warn(f'unsupported output format: {fmt!r}; disabled file output feature',
1466
+ FormatWarning, stacklevel=stacklevel())
1467
+ if isinstance(output, ModuleDescriptor):
1468
+ output = output.klass
1469
+ self.__output__[fmt] = (output, ext) # update mapping upon import
1470
+ dumper = make_dumper(output)
1471
+
1472
+ # NOTE: make_dumper() names every subclass it builds 'DictDumper', so the
1473
+ # useful name is the output class it wraps.
1474
+ logger.debug('dumping %s output to %s via %s', fmt, ofnm, output.__name__)
1475
+ # NOTE: only the writer *class*; :meth:`_open_output` creates the writer
1476
+ # once the engine has read the global header the PCAP writer needs.
1477
+ self._ofile = dumper # output file
1478
+ else:
1479
+ logger.debug('file output disabled')
1480
+
1481
+ # NOTE: peek() reads the magic number without moving the file pointer,
1482
+ # but may return other than 4 bytes, hence the [:4].
1483
+ try:
1484
+ self._magic = self._ifile.peek(4)[:4]
1485
+ if len(self._magic) < 4:
1486
+ # NOTE: a pipe or raw stream may answer ``peek``'s one read with fewer
1487
+ # than four octets, so read them instead and seek back (#1586).
1488
+ position = self._ifile.tell()
1489
+ self._magic = self._ifile.read(4)
1490
+ self._ifile.seek(position, os.SEEK_SET)
1491
+
1492
+ self.run() # start extraction
1493
+ except BaseException:
1494
+ # NOTE: a raising constructor leaves the caller nothing to close (#2100), so ``_cleanup``
1495
+ # releases input and engine (#2107); ``failed`` skips the trace and keeps this error.
1496
+ self._cleanup(failed=True)
1497
+ raise
1498
+
1499
+ def __iter__(self) -> 'Extractor':
1500
+ """Iterate and parse PCAP frame.
1501
+
1502
+ Raises:
1503
+ IterableError: If :attr:`self._flag_a <pcapkit.foundation.extraction.Extractor._flag_a>`
1504
+ is :data:`True`, as such operation is not applicable.
1505
+
1506
+ """
1507
+ if not self._flag_a:
1508
+ return self
1509
+ raise IterableError("'Extractor(auto=True)' object is not iterable")
1510
+
1511
+ def __next__(self) -> '_P':
1512
+ """Iterate and parse next PCAP frame.
1513
+
1514
+ It will call :meth:`self._exeng.read_frame <pcapkit.foundation.engines.engine.EngineBase.read_frame>`
1515
+ to parse next PCAP frame internally, until the EOF reached;
1516
+ then it calls :meth:`self._cleanup <_cleanup>` for the aftermath.
1517
+
1518
+ """
1519
+ while True:
1520
+ try:
1521
+ return self._exeng.read_frame()
1522
+ except (EOFError, StopIteration) as error:
1523
+ warn('EOF reached', ExtractionWarning, stacklevel=stacklevel())
1524
+
1525
+ # See :meth:`_note_eof_progress`: ``no_eof`` retries a live capture
1526
+ # that has merely paused, and gives up on an exhausted one (#620).
1527
+ if self._flag_n and self._note_eof_progress():
1528
+ continue
1529
+
1530
+ self._cleanup()
1531
+ raise StopIteration from error # pylint: disable=raise-missing-from
1532
+ except KeyboardInterrupt:
1533
+ self._cleanup()
1534
+ raise
1535
+
1536
+ def __call__(self) -> '_P':
1537
+ """Works as a simple wrapper for the iteration protocol.
1538
+
1539
+ Raises:
1540
+ CallableError: If :attr:`self._flag_a <pcapkit.foundation.extraction.Extractor._flag_a>`
1541
+ is :data:`True`, as such operation is not applicable.
1542
+
1543
+ """
1544
+ if not self._flag_a:
1545
+ while True:
1546
+ try:
1547
+ return self._exeng.read_frame()
1548
+ except (EOFError, StopIteration):
1549
+ warn('EOF reached', ExtractionWarning, stacklevel=stacklevel())
1550
+
1551
+ # See :meth:`_note_eof_progress`. Once the input is finished
1552
+ # there is no frame left to return, so the error is the only
1553
+ # truthful answer this form can give -- ``no_eof`` defers it
1554
+ # rather than suppressing it outright (#620).
1555
+ if self._flag_n and self._note_eof_progress():
1556
+ continue
1557
+
1558
+ self._cleanup()
1559
+ raise
1560
+ except KeyboardInterrupt:
1561
+ self._cleanup()
1562
+ raise
1563
+ raise CallableError("'Extractor(auto=True)' object is not callable")
1564
+
1565
+ def __enter__(self) -> 'Extractor':
1566
+ """Uses :class:`Extractor` as a context manager."""
1567
+ return self
1568
+
1569
+ def __exit__(self, exc_type: 'Type[BaseException] | None', exc_value: 'BaseException | None',
1570
+ traceback: 'TracebackType | None') -> 'None': # pylint: disable=unused-argument
1571
+ """Release what this class holds when the ``with`` block exits.
1572
+
1573
+ The engine is always closed. The input stream is closed only *if this
1574
+ class owns it* -- the rule of :issue:`610`, as :meth:`_owns_input` writes
1575
+ it down and :meth:`_cleanup` and the backstops already follow. A stream
1576
+ the caller supplied stays open for the caller to close, so leaving the
1577
+ block does not close it behind the caller's back (:issue:`1999`).
1578
+
1579
+ For a caller's non-seekable stream, the stream this class owns is the
1580
+ :class:`~pcapkit.corekit.io.SeekableReader` wrapped around it, and that
1581
+ wrapper is closed; it was built with ``stream_closing`` off, so closing
1582
+ it leaves the caller's stream underneath open.
1583
+
1584
+ Both go through :meth:`_release`, the close path :meth:`_cleanup` shares.
1585
+ Unlike :meth:`_cleanup`, this neither finishes the flow tracer nor sets
1586
+ :attr:`_flag_e`: leaving the block is not the end of the capture -- an
1587
+ extraction with ``auto=False`` may be left before end of file, or on an
1588
+ error -- so there is nothing it can truthfully report as over, and an
1589
+ extraction that did reach the end has already been through
1590
+ :meth:`_cleanup`. An error from the engine's close propagates.
1591
+
1592
+ """
1593
+ logger.debug('closing %s on context exit after %d frame(s)', self._ifnm, self._frnum)
1594
+ # NOTE: ownership, not the ``with`` statement, decides who closes the
1595
+ # input (#610, #1999); entering the block does not take the caller's stream.
1596
+ self._release()
1597
+
1598
+ def __del__(self) -> 'None':
1599
+ """Release the input stream if this class still owns an open one.
1600
+
1601
+ A backstop for the extraction that is *abandoned* rather than finished:
1602
+ with ``auto=False`` the caller drives :meth:`__next__` itself, and one that
1603
+ stops before end of file never reaches :meth:`_cleanup` at all, so the
1604
+ ownership rule there never gets to run. The handle then survives until the
1605
+ interpreter collects it, and CPython announces that with a
1606
+ ``ResourceWarning`` raised wherever collection happens to run, which can be
1607
+ far from the code that abandoned the handle (:issue:`606`).
1608
+
1609
+ GraalPy never calls this method, so the same close is also registered as
1610
+ the :class:`weakref.finalize` in :attr:`_finalizer`, which runs on either
1611
+ interpreter (:issue:`1997`). This method stays for whoever calls it
1612
+ directly, a subclass extending it through :func:`super` among them, and
1613
+ both are safe to run for one stream: whichever comes second finds it
1614
+ already closed.
1615
+
1616
+ This is a backstop and not the recommended route: collection is not
1617
+ deterministic, and :class:`Extractor` takes part in a reference cycle
1618
+ through its engine, so a handle can outlive its last reference until the
1619
+ cyclic collector runs. Use :class:`Extractor` as a context manager -- see
1620
+ :meth:`__enter__` -- where the moment of release matters.
1621
+
1622
+ Note:
1623
+ A finaliser must not raise, so this reads through
1624
+ :attr:`~object.__dict__` rather than attribute access. That matters
1625
+ for more than tidiness: ``_flag_s`` is assigned early in
1626
+ :meth:`__init__` and ``_ifile`` only much later, so a constructor
1627
+ that fails in between -- an unreadable path, or a negative
1628
+ ``reasm_timeout`` with ``reassembly=True`` and ``ip``, ``ipv4``,
1629
+ ``ipv6`` or ``tcp`` set -- leaves an instance whose flag says "mine"
1630
+ and which has no stream at all. The close itself is guarded too, that
1631
+ being what a close during interpreter shutdown can fail at.
1632
+
1633
+ """
1634
+ if not self._owns_input():
1635
+ return
1636
+ _release_input(self.__dict__['_ifile'])
1637
+
1638
+ ##########################################################################
1639
+ # Utilities.
1640
+ ##########################################################################
1641
+
1642
+ def _owns_input(self) -> 'bool':
1643
+ """Whether the input stream is this class's to close.
1644
+
1645
+ The one place the ownership rule of :issue:`610` is written down, so that
1646
+ :meth:`_cleanup`, :meth:`__exit__`, :meth:`__del__` and the registration
1647
+ of :attr:`_finalizer` cannot drift apart on it.
1648
+
1649
+ Returns:
1650
+ :data:`True` when the input stream was opened by this class and is
1651
+ therefore its to release -- ``fin`` given as a path, i.e.
1652
+ :attr:`self._flag_s <Extractor._flag_s>` set, or a
1653
+ :class:`~pcapkit.corekit.io.SeekableReader` this class wrapped around
1654
+ a caller's non-seekable stream. :data:`False` for a stream the caller
1655
+ supplied and still owns, and :data:`False` when there is no stream at
1656
+ all.
1657
+
1658
+ Note:
1659
+ The :data:`True` cases are written as separate tests rather than
1660
+ folded together because they *can* in principle coincide -- a path
1661
+ naming something non-seekable would be opened here and then wrapped --
1662
+ and the answer has to be :data:`True` for both halves of it. That
1663
+ cannot arise, since :meth:`make_name` admits a path only through
1664
+ :func:`os.path.isfile`, which is :data:`False` for a FIFO or a device,
1665
+ and a regular file is always seekable. The second test is therefore
1666
+ defensive rather than dead, and is the reason
1667
+ ``SeekableReader(..., stream_closing=self._flag_s)`` passes the flag
1668
+ instead of :data:`False`.
1669
+
1670
+ """
1671
+ # NOTE: read through ``__dict__`` and answered for the stream, so a constructor that
1672
+ # failed between setting ``_flag_s`` and ``_ifile`` yields :data:`False`, not an error.
1673
+ ifile = self.__dict__.get('_ifile')
1674
+ if ifile is None:
1675
+ return False
1676
+ if self.__dict__.get('_flag_s'):
1677
+ return True
1678
+ return isinstance(ifile, SeekableReader)
1679
+
1680
+ def _detach_finalizer(self) -> 'None':
1681
+ """Unregister :attr:`_finalizer`, once the input has been closed on purpose.
1682
+
1683
+ A finished extraction then leaves nothing registered against its stream:
1684
+ neither a second close at collection nor a reference that keeps the stream
1685
+ alive until the extractor is collected.
1686
+
1687
+ """
1688
+ # NOTE: read through ``__dict__``, as ``_owns_input`` does, for an
1689
+ # instance whose constructor did not get as far as registering one.
1690
+ finalizer = self.__dict__.get('_finalizer')
1691
+ if finalizer is not None:
1692
+ finalizer.detach()
1693
+
1694
+ def _note_eof_progress(self) -> 'bool':
1695
+ """Record this end of stream, and say whether the input advanced to reach it.
1696
+
1697
+ This is the termination condition for ``no_eof``. The flag means
1698
+ "end of stream is not necessarily the end of the capture" -- which is true
1699
+ of a live capture, and is why :mod:`pcapkit.__main__` sets it for
1700
+ ``fin='-'`` -- so the extraction retries rather than stopping. Without a
1701
+ way to decide when the stream is *genuinely* finished, an exhausted one
1702
+ raises end of stream again on every retry, which is the spin
1703
+ :issue:`620` reported.
1704
+
1705
+ The signal is the input's own position. End of stream is raised by
1706
+ :func:`~pcapkit.corekit.decorators.prepare` when the bytes remaining in
1707
+ the stream measure zero, and it restores the position before raising, so
1708
+ the position at end of stream is stable. Two consecutive ends of stream at
1709
+ the *same* position therefore mean nothing arrived between them.
1710
+
1711
+ What "between them" covers, exactly
1712
+ -----------------------------------
1713
+
1714
+ For a **pipe**, everything, and the live-capture case is safe. A blocking
1715
+ read on a pipe whose writer is open but idle *blocks*; it does not report
1716
+ end of stream. So a pipe reports it only once the writer has closed --
1717
+ permanently -- and a capture that merely pauses never reaches here at all.
1718
+
1719
+ For a **seekable regular file**, only the microseconds between two
1720
+ immediately consecutive probes, because such a file does not block -- it
1721
+ reports end of stream at once. So an extraction over a file that is still
1722
+ being appended to ends at the data present when it got there, rather than
1723
+ following the writer. That is a deliberate narrowing, and it is measured:
1724
+ a file gaining its last record 0.6s in yields five of its six frames here,
1725
+ where an unbounded retry yields all six. Unbounded retrying is the defect
1726
+ :issue:`620` reports, so *some* stopping rule had to be chosen, and a
1727
+ timed grace period would only make the cut-off intermittent rather than
1728
+ absent.
1729
+ Following a growing file wants a deliberate policy of its own; see the
1730
+ note in :file:`docs/source/changelog/1.5.0.rst`.
1731
+
1732
+ Warning:
1733
+ **Not idempotent.** Each call consumes one end-of-stream observation
1734
+ by overwriting :attr:`_eof_mark`, so calling it twice for one end of
1735
+ stream spends the retry it would have granted. Call it exactly once
1736
+ per handler, which is what each call site does.
1737
+
1738
+ Returns:
1739
+ :data:`True` when retrying may yet produce a frame -- this is the first
1740
+ end of stream, or the input has advanced since the last one.
1741
+ :data:`False` when the input is standing still and the loop should stop.
1742
+
1743
+ """
1744
+ try:
1745
+ position = self._ifile.tell()
1746
+ except (OSError, ValueError):
1747
+ # An input that cannot say where it is cannot be shown to be making
1748
+ # progress either, and stopping is the safe answer: the alternative
1749
+ # is the unbounded loop this method exists to end.
1750
+ return False
1751
+
1752
+ previous, self._eof_mark = self._eof_mark, position
1753
+ return previous is None or position > previous
1754
+
1755
+ def _cleanup(self, *, failed: 'bool' = False) -> 'None':
1756
+ """Cleanup after extraction & analysis.
1757
+
1758
+ The method sets :attr:`self._flag_e <pcapkit.foundation.extraction.Extractor._flag_e>`
1759
+ as :data:`True` and then calls :meth:`_release`, which closes the input
1760
+ file *if this class opened it* and calls
1761
+ :meth:`self._exeng.close <pcapkit.foundation.engines.engine.EngineBase.close>`.
1762
+
1763
+ That proviso is the whole of it: a handle opened here -- ``fin`` given as
1764
+ a path, i.e. :attr:`self._flag_s <Extractor._flag_s>` set -- is closed,
1765
+ and a stream the caller supplied is left alone for the caller to close
1766
+ when it is done with it.
1767
+
1768
+ It also tells the flow tracer the capture has ended, via
1769
+ :meth:`TraceFlow.finish <pcapkit.foundation.traceflow.traceflow.TraceFlow.finish>`.
1770
+ That is the point at which a traced flow nothing has superseded can be
1771
+ said to be over, so it is where such a flow is finalised and its callbacks
1772
+ run. This method can run more than once for one extraction -- each call to
1773
+ :meth:`__next__` or :meth:`__call__` that reaches the end of a
1774
+ caller-supplied stream runs it again -- so ``finish`` is required to be
1775
+ idempotent rather than guarded here.
1776
+
1777
+ Arguments:
1778
+ failed: whether the extraction stopped on an error instead, which is
1779
+ the constructor raising (:issue:`2100`, :issue:`2107`). The input
1780
+ and the engine are still released, but the capture has not ended,
1781
+ so the flow tracer is not finished -- its callbacks would report
1782
+ flows of a capture that was never read to its end -- and
1783
+ :attr:`_flag_e` is not set. The constructor may have failed before
1784
+ choosing an engine, as an unknown format does, and then there is
1785
+ none to close. An :exc:`Exception` from the engine's close is
1786
+ logged rather than raised, so it cannot replace the error that
1787
+ stopped the constructor.
1788
+
1789
+ """
1790
+ # pylint: disable=attribute-defined-outside-init
1791
+ logger.debug('cleaning up after %d frame(s) from %s', self._frnum, self._ifnm)
1792
+ if failed:
1793
+ self._release(failed=True)
1794
+ return
1795
+
1796
+ self._flag_e = True
1797
+ if self._flag_t and self._tcp:
1798
+ self._trace.tcp.finish()
1799
+ self._release()
1800
+
1801
+ def _release(self, *, failed: 'bool' = False) -> 'None':
1802
+ """Close the input this class owns, and the engine.
1803
+
1804
+ The one close path, shared by :meth:`_cleanup` and :meth:`__exit__`, so
1805
+ that the two cannot drift apart on what is released or in which order.
1806
+
1807
+ Arguments:
1808
+ failed: see :meth:`_cleanup`. When set, a missing engine is skipped and
1809
+ an :exc:`Exception` from its close is logged rather than raised.
1810
+
1811
+ """
1812
+ # NOTE: ownership, not seekability, decides who closes the input (#610): keying on
1813
+ # ``not self._flag_s`` leaks our own handle (#606) and closes the caller's.
1814
+ if self._owns_input():
1815
+ self._ifile.close()
1816
+ self._detach_finalizer()
1817
+
1818
+ if not failed:
1819
+ self._exeng.close()
1820
+ return
1821
+
1822
+ # NOTE: read through ``__dict__``, as ``_owns_input`` does: a constructor
1823
+ # that failed before choosing an engine leaves no ``_exeng`` (#2107).
1824
+ engine = self.__dict__.get('_exeng')
1825
+ if engine is None:
1826
+ return
1827
+ try:
1828
+ engine.close()
1829
+ except Exception: # pylint: disable=broad-except
1830
+ # NOTE: the error that stopped the constructor is the one to report;
1831
+ # letting the close's escape here would replace it (#2107).
1832
+ logger.debug('engine %s failed to close after the constructor raised',
1833
+ type(engine).__name__, exc_info=True)