All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
-
netprotocols.reassembly: IPv4 and IPv6 fragment reassembly (#379). The new module, imported asnetprotocols.reassemblyand not re-exported by the package (import netprotocolsdoes not import it), shipsFragmentReassembler, the library's one object that keeps state across frames.feed(packet, frame, *, timestamp, ref=None)takes a decodedPacketwith the frame it came from, finds the outermost IP header that is a fragment, and returns the events the frame caused;advance(timestamp)moves the capture clock andclose()discards what is left, andusageis aUsage(flows, bytes). The events are frozen, slotted, keyword-only dataclasses,Datagram(the whole datagram with its header rebuilt per RFC 791 §3.1 and RFC 8200 §4.5,payload_offsetandheader_ref),Overlap,Retransmission,Evicted,ExpiredandAnomaly, whose union isFragmentEvent; each names its frames asSpan(ref, start, end, timestamp, hop_limit)values and the frame that caused it ascompleting_ref,Nonefor an expiry, an eviction to make room,advance()andclose(). Datagrams are keyed byFragmentKey(version, src, dst, protocol, identification). Overlapping IPv4 fragments are resolved by anOverlapPolicyper target network (targets, longest prefix):first(the default),last,bsd,linux,windowsandsolaris, whose results match Suricata'sDefragSturgesNovak*vectors,discard, andlinux-discard, which matches the running Linux kernel on the trains oftests/fixtures/reassembly/linux_overlaps.pcap; an overlap whose bytes differ is anOverlapunder every policy, and an overlapping IPv6 fragment discards its datagram (RFC 5722 §4, erratum 3089), after which the key keeps no state. The fragment rules (oversize, misaligned, empty, inconsistent end, incomplete IPv6 header chain, RFC 1858's tiny and offset-1 fragments, truncation, TTL or Hop Limit and Next Header changes, and an IPv4 datagram completed more than 30 seconds after its first fragment) areAnomalyKindvalues, andChecksumMode(DROP,KEEP,AUTO, the default, withlocal) decides what a bad IPv4 header checksum does,AUTOaccepting Windows' offloaded 0 asCHECKSUM_OFFLOAD.FragmentBoundscaps the bytes one datagram and all of them hold, the datagrams held and the pieces per datagram, charging the measuredFLOW_OVERHEAD(1,024 bytes) andPIECE_OVERHEAD(512 bytes), and sets the age (60 s) and idle timeouts on capture timestamps (SECOND), which everyfeed()advances, a frame without fragments included;FragmentTargetsets a policy and timeouts per target network,NO_TIMEOUTturning one off. A datagram that would alone exceedmax_total_bytesis discarded at once; otherwise the datagram whose first fragment came first is evicted to make room, the arriving fragment's own included.Direction,BoundandTimeoutcomplete the event types. -
netprotocols.reassembly: TCP stream reassembly (#380).StreamReassemblertakes the samefeed(packet, frame, *, timestamp, ref=None),advance(),close()andusageasFragmentReassembler, keys each TCP connection byflow_key()of the packet's first TCP layer and the IP header nearest before it, and delivers each direction as a byte stream numbered from the byte after the SYN, or from the first segment's first byte when the capture began mid-stream (Anomaly(MIDSTREAM)), across sequence-number wraps. New events, inStreamEventwith the sharedOverlap,Retransmission,Evicted,ExpiredandAnomaly:StreamData(bytes that became contiguous, delivered at once, spans tiling them),StreamEnd(EndReason:FIN,RST,IDLE,AGE,EVICTED,CLOSE),OutOfOrder,Gap(GapReason:CAP,TRUNCATED,FLUSH,ACKED) andLateData. Overlapping bytes not yet delivered are resolved byOverlapPolicy.FIRST(the default) orLAST, per receiver throughtargets; delivered bytes are final, and a repeat of them is compared with the bytes retained fromretain_bytesbelow the peer's highest acknowledgement, anOverlapkeeping the delivered version and flaggedcontraryunderlastwhen they differ, aRetransmission(verified=False)when they are no longer retained. A hole the peer acknowledges past and that stays openack_gap_grace(1 s) is declared aGap(ACKED)by the frame that confirms it, capped at the highest offset received (Anomaly(ACK_BEYOND_DATA)), and bytes arriving for it later areLateDatawhile its record is held. An RST isAnomaly(RST_RECEIVED)at once and ends the connection withStreamEnd(RST)only at the closed timeout after it, atclose(), or at once on a SYN with a new ISN (Anomaly(SYN_AFTER_RST)); data after it continues the stream (Anomaly(DATA_AFTER_RST)). The other anomaly kinds the stream rules add areBEFORE_STREAM_START,SYN_DATA,ISN_CHANGED,DATA_WITHOUT_ACK,INCONSISTENT_FIN,DATA_AFTER_FIN,RST_WITH_DATA,SELF_CONNECTED,OUT_OF_WINDOWandURGENT.ChecksumModejudges the IPv4 header and TCP checksums, and underAUTOtakes a TCP checksum equal to the folded pseudo-header sum, with or without the segment's length, as offloaded, from thelocalnetworks or from any source without them.StreamBoundssetsmax_flow_bytes(4 MiB),max_total_bytes(128 MiB),max_flows(65,536),retain_bytes(64 KiB), the idle timeouts of new (60 s), established (3,600 s) and closed (120 s) connections, an optionalage_timeoutandack_gap_grace; a connection is chargedFLOW_OVERHEADandPIECE_OVERHEADper direction, a connection over its cap sheds retained bytes and then declares its lowest hole aGap(CAP), and the least recently active connection not yet carrying data both ways is evicted first. The names are innetprotocols.reassembly.__all__only. -
The capture readers read binary streams, one record or block at a time (#371).
read_pcap(),read_pcapng(),read_captures()andread_packets()now take, besidebytes,bytearrayandmemoryview, a file opened withopen(path, "rb"), anio.BytesIO, a pipe, or any other object whoseread(size)returns up tosizebytes andb""only at the end. A stream is read forward from its current position and never seeked, closed or read throughreadinto,seekortell, so memory holds about one record or block rather than the whole capture: reading a crafted 8 MiB capture of frames up to 65,535 bytes from a file peaks below four times its longest block undertracemalloc, where amemoryviewof it is still copied whole. Noreadcall asks for more than 1 MiB, so a record or block that declares more bytes than the stream holds, 4 GiB included, allocates no more than the stream gives before it raises.read_pcap()andread_pcapng()read nothing on the call;read_captures()andread_packets()read the 4-byte magic number on the call, as they check it there for a buffer, and dispatch with those bytes already consumed. Frames, timestamps, interfaces and errors are those the same bytes give as a buffer: a stream that ends inside a header, a record, a block or its trailing length raisesMalformedCaptureErrorwhen iteration reaches it, with thefield,offset,expectedandactuala buffer cut there gives, the offset counted from the stream's position when reading started, and the frames before it stay valid. Every object with the buffer protocol, anmmapincluded, is still read as a buffer, copied when iteration starts;bytesinput behaves exactly as before. One parsing path serves both: a reader holds a window of the capture, which for a buffer is the whole of it and for a stream is refilled from the stream when a header or block runs past it.CapturedFrame.datais plainbytesin every case.read_pcapng()on a stream that does not start with a Section Header Block raises after reading its first 4 bytes, with a message that gives those magic bytes and not the stream's length, which would take reading the whole stream; the error'sfield,offset,expectedandactualare a buffer's. A stream whosereadreturnsNone, as a non-blocking one with no bytes ready does, raisesTypeError. An input that is neither a buffer nor a stream, such as a list of ints or an object with only__bytes__, which the readers used to pass throughbytes(), now raisesAttributeErrorfor its missingread. The module docstring, README and ARCHITECTURE describe it, andtests/test_pcap.pyruns every reader test onbytes, amemoryview, anio.BytesIO, a stream with nothing butread, and one that returns at most 7 bytes per call, and checks that each input kind gives every fixture and every truncation of three captures the same outcome. -
read_packets()andCapturedPacket: the pcapng interface each frame was captured on (#372). The newnetprotocols.read_packets(buffer)detects classic pcap or pcapng asread_captures()does, checking the magic number on the call itself, and yieldsCapturedPacket(timestamp, data, interface_id, interface_name), whosetimestampanddataare the onesread_captures()gives. For a frame from a pcapng Enhanced Packet Block,interface_idis the block's Interface ID andinterface_namethat Interface Description Block'sif_nameoption (code 2) decoded as UTF-8, orNonewhen the block has noif_name; for a Simple Packet Block, which records no interface, and for a classic-pcap record, both areNone. The interface list resets at each Section Header Block, as theif_tsresollist already did. Anif_namevalue running past the end of the options list is cut there, and a value ends at its first zero byte, which draft-ietf-opsawg-pcapng has readers treat as a string terminator, so the bytes after it are never decoded. The first non-emptyif_nameis used: an empty one, one with nothing before its first zero byte among them, is passed over as an emptyif_tsresolis. Anif_namewhose bytes before its first zero byte are not valid UTF-8 raisesMalformedCaptureError(field="if_name",offsetits first bad byte) when iteration reaches the first Enhanced Packet Block that references the interface, so the frames before it are yielded andread_pcapng()andread_captures(), which never decode the name, read the same capture as before.read_captures(),read_pcap(),read_pcapng()andCapturedFrameare unchanged, positional unpackingtimestamp, data = frameincluded;read_pcapng()andread_packets()share one block walk.tests/fixtures/pcapng/interfaces.pcapng, a realdumpcap -i lo -i npifa0capture made by the newscripts/capture_fixtures_pcapng_interfaces.sh, is outside the corpus and its counts. Both names are exported fromnetprotocols. -
HSRPv2InterfaceState: HSRPv2's Interface State TLV (#357). The newnetprotocols.HSRPv2InterfaceState(alsonetprotocols.layer7.HSRPv2InterfaceState) decodes the Interface State TLV, Type 2 and Length 4, in the layout of Wireshark'sepan/dissectors/packet-hsrp.c(commit 6f7207a6, SHA-256b09e0dc1521e1b24e5be80efc8c901d26b4c0be3798464661dd80152fb780a39, the file the earlier HSRP entries read), since HSRPv2 has no RFC:active_groupsandpassive_groups, the names and widths of packet-hsrp.c'shf_hsrp2_active_groupandhf_hsrp2_passive_group(16-bit, lines 777-785), read big-endian in that order at the TLV's value bytes 0 and 2 (lines 544-564; the diagram, lines 80-87).HSRPv2.decode()reads it where packet-hsrp.c does, in the walk of every TLV after the first, wherever it falls among them, andHSRPv2.interface_stategives the first, orNone. Neither count is judged: packet-hsrp.c gives them no range, so any 16-bit value decodes, andbytes(HSRPv2.decode(x)) == xstill holds for every bufferdecode()accepts. A Type 2 TLV of any Length but 4 raisesInvalidFieldError(field="length",offsetits Length byte from the start of the message,expected="4",actualthe Length), as a Group State, Text Authentication or MD5 Authentication TLV of another Length does; packet-hsrp.c shows such a TLV and everything after it as undefined data (lines 594-599). Construction checks that each count fits 16 bits,bytes()gives the 6-byte TLV, Type and Length included, andHSRPv2(tlvs)accepts it among its TLVs.HSRPv2TLVnow refuses Type 2 (field="type"), as it refuses Types 1, 3 and 4, so every TLV of a Type packet-hsrp.c reads has one representation and a round trip gives back an equal object;HSRPv2TLV.type_nameis therefore"unknown (n)"for every Type it accepts. The library andscripts/check_fixtures.pynow agree on the TLV: both hold its Length to 4. -
HSRP.md5_authentication: HSRPv1's MD5 Authentication TLV (#282).HSRPgains a last field,md5_authentication, defaulting toNone, so construction by position or keyword without it is unchanged.HSRP.decode()reads the TLV where Wireshark'sepan/dissectors/packet-hsrp.c(commit 6f7207a6) reads it, since it has no RFC: when the buffer is exactly 50 bytes long (lines 444-445,tvb_captured_length(tvb) == 50) and its bytes 20 and 21 are Type 4 and Length 28 (lines 446-452), asHSRPv2MD5Authentication(algorithm, padding, flags, ip_address, key_id, digest), the digest raw and not verified. The class is shared withHSRPv2rather than a new one, because packet-hsrp.c reads both TLVs with the one functionprocess_hsrp_md5_tlv_sequence()(lines 320-344) and the samehf_hsrp2_md5_*fields (lines 787-815), so their layouts are byte-identical, and sharing it adds no field, signature or type toHSRPv2's API; only its docstring changes, to say both messages carry it. Every other buffer decodes as before, to its 20 bytes withmd5_authenticationNoneand what follows outside the layer: a 50-byte buffer whose bytes 20 and 21 are any other Type or Length, Type 4 with a Length other than 28 among them, which packet-hsrp.c reports as an "Unknown TLV sequence" without failing the message (lines 455-458), and a buffer of any other length, 49 and 51 bytes included. No new error is raised: nothing in the TLV is judged, so a 50-byte buffer is accepted or rejected exactly as its first 20 bytes are, andInvalidFieldErrorandTruncatedHeaderErrorkeep their conditions. In a walk the buffer is the UDP payload the UDP Length bounds, so an Ethernet FCS a capture kept stays in the trailer and cannot lengthen a 50-byte message. The Authentication Data is kept raw beside the TLV, andpassword,auth_data_strandis_default_authare unchanged. The constructor raisesInvalidFieldError(field="md5_authentication") for anything butNoneor anHSRPv2MD5Authentication. The representation is a field rather than a layer chained afterHSRP, asNTPandNTPControlhold their MACs: the TLV has no meaning apart from the message it authenticates, and a field keepsHSRPterminal andbytes()of the one layer the whole message. A layer chained afterHSRPwould have kept itsheader_lenat 20, but neededHSRP.next_protocol()to answer from decode context (the buffer's length, which no field holds), a class decodable only in that one position, and a walk of two layers for one message. -
HSRPAdvertise: Cisco's HSRP interface-state Advertise, Op Code 3 (#281). The newnetprotocols.HSRPAdvertise(alsonetprotocols.layer7.HSRPAdvertise) decodes the 16-byte version 0 message in the layout of Wireshark'sepan/dissectors/packet-hsrp.c(commit 6f7207a6, the file's latest, re-fetched on 2026-11-07 and byte-identical to master's), since the Advertise has no RFC:version,opcode,tlv_type(2 bytes),tlv_length(2 bytes),state,reserved1,active_groupsandpassive_groups(2 bytes each) andreserved2(4 bytes), the names and widths of packet-hsrp.c'shf_hsrp_adv_*fields (lines 662-695) in the order its lines 425-439 read them, withopcode_name(packet-hsrp.c's four Op Code names,"Advertise"for 3),tlv_type_name("HSRP interface state"for 1,"IP redundancy"for 2) andstate_name("Dormant","Passive","Active"for 1-3), each"unknown (n)"otherwise. Every field is kept as its wire value, sobytes(HSRPAdvertise.decode(x)) == x[:16], and the layer is those 16 bytes: whatever follows stays outside it, as withHSRP.decode()judges the Version (0), the Op Code (3), the TLV Type (1 or 2: its high byte, 0 for both, as soon as it is present, and the whole Type once both its bytes are) and the State (1-3), each as soon as its bytes are in the buffer and before the length, raisesInvalidFieldErrorwithoffset0, 1, 2 or 6 for the first that fails, its message namingHSRPv2for a Version of 1 andHSRPfor an Op Code of 0-2, and raisesTruncatedHeaderErroronly for a buffer shorter than 16 bytes whose judged fields all pass. The TLV Length, which packet-hsrp.c reads but holds to no value, the Reserved fields and the group counts are not judged; packet-hsrp.c's 0-256 range for the counts is checked byscripts/check_fixtures.pyonly. Construction checks only that each field fits its width. Random bytes pass the guard 6 times in 2^40, against 18 in 2^24 forHSRP's. Exported fromnetprotocolsandnetprotocols.layer7. -
HSRPv2: HSRPv2 and HSRP for IPv6 messages (#280). The newnetprotocols.HSRPv2(alsonetprotocols.layer7.HSRPv2) holds a message's TLVs, walked with_tlv.py's walker, as a tuple,tlvs, in the layout of Wireshark'sepan/dissectors/packet-hsrp.c(commit 6f7207a6, the file's latest, read on 2026-11-06), since HSRPv2 has no RFC: the Group State TLV (Type 1, Length 40) asHSRPv2GroupState(version, opcode, state, ip_version, group, identifier, priority, hellotime, holdtime, virtual_ip, virtual_ip_padding), withopcode_name,state_name(Disabled 0, Initial 1, Learn 2, Listen 3, Speak 4, Standby 5, Active 6: packet-hsrp.c'sHSRP2_STATE_*values, its "Init" named "Initial" asHSRPnames HSRPv1's),ip_version_nameandvirtual_mac(00:00:0c:9f:fX:XXfor an IPv4 group,00:05:73:a0:0X:XXfor an IPv6 one); the Text Authentication TLV (Type 3, Length 8) asHSRPv2TextAuthentication(auth_data)with HSRPv1'spassword,auth_data_strandis_default_auth; the MD5 Authentication TLV (Type 4, Length 28) asHSRPv2MD5Authentication(algorithm, padding, flags, ip_address, key_id, digest), the digest raw and not verified, withalgorithm_name; and any other TLV asHSRPv2TLV(type, value)withtype_name; the Interface State TLV (Type 2) has its own class,HSRPv2InterfaceState(#357, above).HSRPv2.group_state,text_authenticationandmd5_authenticationread the first of each. The Virtual IP Address field is 16 bytes whatever the IP Version: an IPv4 address takes its first 4 and the other 12 are kept raw asvirtual_ip_padding, which defaults toNoneand is then constructed asbytes(12)for IPv4 andb""for IPv6, soHSRPv2GroupState(..., virtual_ip="192.0.2.1")equals the one built withvirtual_ip_padding=bytes(12), whiledecode()keeps the 12 bytes as sent, sobytes(HSRPv2.decode(x)) == xfor every bufferdecode()accepts.decode()judges the Group State TLV's first eight bytes, each once it is in the buffer and before the length (Type 1, Length 40, Version 2, Op Code 0-2, State 0-6, IP Version 4 or 6, Group at most 4095), raisesTruncatedHeaderErroronly for a buffer shorter than the 42-byte TLV whose leading bytes all pass, and raisesInvalidFieldError, its offset counted from the start of the message, for a TLV walk that breaks, a Group State, Text Authentication or MD5 Authentication TLV of another Length, or a later Group State TLV with a judged field that fails. The message keeps the whole buffer, which a walk ends at UDP's Length. All five classes are exported fromnetprotocolsandnetprotocols.layer7. -
MST BPDUs (IEEE 802.1Q MSTP) decoded past their RST prefix (#299).
STPgainsmst, the Version 3 information of an MST BPDU kept verbatim (the Version 3 Length and the octets it counts;b""for every other BPDU), and accessors that parse it on demand and answerNonewhile it is empty:version_3_length;mst_config_id, anSTPMSTConfigurationIdentifier(format_selector, name, revision_level, digest)with the 32-octetnamekept raw,name_str(up to the first zero octet, UTF-8 with replacement) anddigest_hex_str; the CIST internal fieldscist_internal_root_path_cost,cist_bridge_priority,cist_bridge_mac,cist_bridge_id_strandcist_remaining_hops; the RST prefix's fields under the names they carry in an MST BPDU (802.1Q §14.4, Figure 14-1),cist_regional_root_priority,cist_regional_root_macandcist_regional_root_id_str(the Bridge Identifier'sbridge_priority,bridge_macandbridge_id_str, which hold the CIST Regional Root Identifier) andcist_external_root_path_cost(root_path_cost), the CIST Root Identifier stayingroot_priority,root_macandroot_id_str; andmsti_messages, a tuple ofSTPMSTIMessage(flags, regional_root_priority, regional_root_mac, internal_root_path_cost, bridge_priority, port_priority, remaining_hops), each withmsti_id(the Regional Root Identifier's system ID extension),regional_root_priority_component,regional_root_id_str,bridge_priority_componentandport_priority_component, and the flags by name (topology_change,proposal,learning,forwarding,agreement,master,port_role,port_role_name, which names role 0 Master, as 802.1Q does). Both records are frozen dataclasses, validate their widths (and the MAC) on construction, re-encode withbytes()to their 51 and 16 octets, and are exported fromnetprotocolsandnetprotocols.layer2.STP.decode()fillsmstonly for a BPDU that passes 802.1Q §14.5 e): type 0x02, Protocol Version 3 or greater, 102 or more octets, Version 1 Length 0, and a Version 3 Length of 64 plus 0 to 64 whole 16-octet MSTI messages that lies inside the buffer. In a walk the buffer is the PDU the 802.3 Length bounds; decoded directly, the Version 3 Length ends the BPDU, so Ethernet padding and an FCS after it are not taken in, andbytes(STP.decode(x)) == x[:header_len]still holds. A BPDU that fails the validation decodes as before, its 36-octet RST prefix with the rest after the layer, as §14.5 d) and §14.6 i) prescribe; that covers the two encodings Wireshark'spacket-bpdu.chandles beside the standard one (a Cisco C3550 IOS release's Version 3 Length counting MSTI messages rather than octets, and an alternative format with a Version 3 Length of 0, which Wireshark accepts only when the BPDU's length is the format selector octet plus 39, and 26-octet MSTI messages), both of which have a Version 3 Length below 64. ExtendingSTPrather than adding a class follows the maintainer's design decision on #299, so the registry and the walker's dispatch are unchanged. Againsttests/fixtures/stp.pcap, every one of its ten MST BPDUs decodes with Version 3 Length 96, two MSTI messages and its whole 134 octets as the layer. -
NTPControl: NTP control messages, mode 6 (RFC 9327 §2) (#272). The newnetprotocols.NTPControl(alsonetprotocols.layer7.NTPControl) decodes the 12-byte header intoleap,version, the R, E and M bits asresponse,errorandmore,opcode,sequence,status,association_idandoffset, keeps thecountbytes ofdataraw, and splits what follows intopadding,mac(anNTPMAC, not verified) andremainder, sobytes(NTPControl.decode(x)) == xfor every bufferdecode()accepts. The MAC is looked for where ntpd and ntpsec put it: after the data padded to a multiple of 8 bytes, or, in an error response (R and E set), after the data padded to a multiple of 4, which is right after the 12-byte header when the Count is 0; it is found when exactly 20 or 24 bytes are left from there (a Key ID and a 16-byte MD5 or AES-128-CMAC, or 20-byte SHA-1, digest), and otherwise the bytes up to the next multiple of 4 are the padding and the rest the remainder. The padding is not required to be zero: ntpsec 1.2.2 pads with whatever its buffer held.decode()judges the version (1-4) and the mode (6) at the first byte, at any length, then needs the 12-byte header, then refuses a Count above 468, the most data RFC 9327 allows (InvalidFieldError,field="count",offset10), and a Count past the end of the buffer (TruncatedHeaderError,field="data",offset12,expected12 plus the Count), reading nothing past the header. Display helpers:opcode_name(RFC 9327 Table 1;"reserved (n)"for 0 and 13-30),leap_name,mode(always 6) andcount;error_codeanderror_namefor an error response (Table 9); andsystem_status, the Status split as a newNTPSystemStatus(leap,clock_source,event_count,event_code, withclock_source_nameandevent_namefrom Tables 3 and 4, andfrom_word()) for a response, not an error, to association 0 and opcode 1 (read status), 2 (read variables), 3 (write variables) or 7 (trap response, which for association 0 is a system trap), where RFC 9327 §3.1 and §4 place one,Nonefor every other message. The Status itself stays raw, because whether it is a system, peer, clock or error status word depends on the opcode, the association and the E bit, and a command carries zero there.variablessplits RFC 9327 §4's comma-separatedname=valuetext into(name, value)pairs, a valueNonefor a bare name, commas inside double quotes kept, and never raises, on binary data or a fragment cut mid-item included.NTPControlandNTPSystemStatusare exported fromnetprotocolsandnetprotocols.layer7. -
Typed bodies of OSPF's Router, Network, Summary, AS-external and NSSA LSAs (RFC 2328 §A.4.2-§A.4.5, RFC 3101 §2.3) (#298).
OSPFLSAkeeps its rawbodyand gains four accessors that parse it on demand:router(LS type 1) returns anOSPFRouterLSA(flags, links, reserved)withv,eandb,flags_str(Nt W V E B) andlink_count, its linksOSPFRouterLink(link_id, link_data, type, metric, tos)withtos_countandtype_nameand their TOS entriesOSPFRouterLinkTOS(tos, metric, reserved);network(type 2) anOSPFNetworkLSA(network_mask, attached_routers);summary(types 3 and 4) anOSPFSummaryLSA(network_mask, metric, tos, reserved)ofOSPFSummaryTOS(tos, metric); andexternal(types 5 and 7, the NSSA-LSA having the AS-external-LSA's layout) anOSPFExternalLSA(network_mask, metrics)ofOSPFExternalMetric(e_bit, tos, metric, forwarding_address, external_route_tag), one per TOS, TOS 0 first;bytes()of anOSPFExternalMetricraisesValueErrorfor atosoutside 0-127, the 7 bits after the E bit. Each accessor answersNonefor the other LS types, whose bodies (opaque LSAs among them) stay raw and unchecked. Reserved bytes are carried verbatim, so every record re-encodes withbytes()to the body it came from. The eight record classes are exported fromnetprotocolsandnetprotocols.layer3. The module docstring, ARCHITECTURE and the README describe them. -
RADIUSAttributereads Vendor-Specific (26) attributes (RFC 2865 §5.26, #275).vendor_idis the 4-byte Vendor-Id, read as all four octets as RFC 6929 §2.6 recommends, andNonefor any other type or for data shorter than 4 bytes;vendor_namenames twelve well-known Vendor-Ids, each checked against IANA's Private Enterprise Numbers and spelled as FreeRADIUS 3.2.5's dictionaries spell it (Cisco 9, Microsoft 311, USR 429, Alcatel-ESAM 637, Juniper 2636, Lucent 4846, Telrad 5323, Starent 8164, 3GPP 10415, WISPr 14122, Kineto 16445, WiMAX 24757), and gives"unknown (n)"for any other, never raising.vendor_attributeswalks the String after the Vendor-Id with the shared_tlv.walk_kind_length_value, asRADIUS.parsed_attributeswalks the attribute list, into the newRADIUSVendorAttribute(type, data)(alsonetprotocols.layer7.RADIUSVendorAttribute), whosebytes()is the on-wire Vendor-Type, Vendor-Length and value, the value kept raw. It raisesInvalidFieldError(field="data",offsetrelative todata) for data shorter than 5 bytes (no Vendor-Id, or an empty String, which RFC 2865 §5.26's Length of at least 7 rules out), a Vendor-Length below 2 or past the String, or a Vendor-Type with no Vendor-Length after it, and never fromdecode()orparsed_attributes, so a broken Vendor-Specific leaves the rest of the packet readable. It isNonefor any other type and for the vendors whose FreeRADIUS 3.2.5 dictionary gives another sub-attribute format on itsVENDORline: USR (429,format=4,0), Alcatel-ESAM (637), Lucent (4846) and Kineto (16445, eachformat=2,1), Starent (8164,format=2,2, orformat=1,1in dictionary.starent.vsa1), and Telrad (5323) and WiMAX (24757, eachformat=1,1,c, a continuation byte after the Vendor-Length); their String stays raw indata.valuestill gives a Vendor-Specific's raw bytes, andbytes()of every attribute is unchanged.type_namenow names RFC 6929 §3's Extended-Type-1 to -4 (241-244) and Long-Extended-Type-1 and -2 (245, 246), whose values, Extended-Vendor-Specific (RFC 6929 §4) included, are kept raw withvalueNone.tests/test_radius.pychecks every Vendor-Specific of the capture against astructdecode, every malformed shape, each non-standard vendor and each RFC 6929 type, andtests/test_fuzz.pyholds the new accessors to the attribute accessors' property: the sub-attributes tile the String exactly, orInvalidFieldErroris raised, or the walk isNone, and nothing else raises. The RADIUS module docstring, README and ARCHITECTURE describe it. -
Typed fields of SCTP's DATA, INIT, INIT ACK, SACK and I-DATA chunks (RFC 9260 §3.3.1-3.3.4, RFC 8260 §2.1), and the INIT and INIT ACK parameters as
SCTPParameter(#238).SCTPChunkgains read-only accessors over its rawvalue, each of which answersNonefor a chunk of a type without the field and for a value too short to hold it, so the fields before a cut still read, and each of which butparameters,gap_ack_blocksandduplicate_tsnsnever raises. DATA and I-DATA:tsn,stream_id,user_data(without padding), theimmediate,unordered,beginning_fragmentandending_fragmentflag bits by name (Nonefor other types),ppid(an I-DATA chunk's only when B is set) and, DATA only,stream_sequence_number; I-DATA only,message_idandfragment_sequence_number(0 for a first fragment, B set, whose word holds the PPID, RFC 8260 §2.1). INIT and INIT ACK:initiate_tag,a_rwnd,outbound_streams,inbound_streams,initial_tsnandparameters, a tuple of the newnetprotocols.SCTPParameter(type, value)(alsonetprotocols.layer4.SCTPParameter), walked by the shared_tlv.pywalker, each value without RFC 9260 §3.2.1's padding to 4 bytes and a last parameter sent without its padding accepted,()for a chunk of only the 16 fixed bytes, and raisingInvalidFieldErrorfor parameters that do not walk (a length below 4 or past the value, 1-3 bytes left over for a parameter header), withfield="value"and anoffsetrelative to the chunk'svalue;state_cookie, INIT ACK only, the first State Cookie parameter's value,None(never raising) whereparametersraises. SACK:cumulative_tsn_ack,a_rwnd,num_gap_ack_blocks,num_duplicate_tsns,gap_ack_blocksas(start, end)offset pairs from the Cumulative TSN Ack andduplicate_tsns, bothNonefor a value shorter than the 12 fixed bytes;gap_ack_blocksraisesInvalidFieldErrorfor a value that ends before every block its count declares, andduplicate_tsnsfor one that ends before every block and duplicate TSN the two counts declare, never giving a partial list, withfield="value", anoffsetrelative to the chunk'svaluewhere the first 4-byte entry cut short starts,expected4 andactualthe bytes left from it, and bytes after the declared lists are ignored.SCTPParametervalidates a 16-bit type and a value of at most 65531 bytes,bytes()gives the padded wire form,lengthexcludes the padding andtype_namenames the INIT and INIT ACK parameter types of RFC 9260 §3.3.2.1 and §3.3.3.1, plus the RFC 4895, RFC 4820, RFC 5061, RFC 3758 and RFC 9653 ones an INIT commonly carries,"unknown (n)"otherwise.tests/test_sctp.pychecks every field ofsctp.pcap's INIT, INIT ACK, both DATA chunks and both SACKs against astructdecode of the captured bytes and against the association (each initiate tag is the peer's verification tag, each side's first TSN its initial TSN and the SACK's Cumulative TSN Ack, the INIT ACK's 324-byte State Cookie the COOKIE ECHO's value), every cut of the fixed fields of DATA, I-DATA, INIT and INIT ACK and of every SACK field,parametersat every cut short of the 16 fixed bytes and with or without a last parameter's padding,state_cookieat a cut short of the fixed fields, I-DATA's FSN of 0 from 16 bytes, every chunk type without a field, the SACK count overflows and the parameter walk's failures; the capture holds no I-DATA, so its tests use hand-built chunks. The fuzz suite reads every accessor on every chunk it walks and on drawn DATA, INIT, INIT ACK, SACK and I-DATA chunks, and checksparametersagainst an independent walk, also on drawn INIT and INIT ACK chunks whose parameters (a State Cookie among them) are built to tile and then perhaps changed, cut or extended: the parameters tile the value after the 16 fixed bytes exactly or raiseInvalidFieldErrorat the offset the independent walk gives, andstate_cookieis the first State Cookie's value, orNonewherever they raise. -
sctp.ppid, a dispatch table from an SCTP Payload Protocol Identifier to a decoder, andSCTPChunk.decode_user_data(registry=None)(#238). The table ships empty: this library registers no decoder for any PPID, and a caller registers one as in any other table (netprotocols.registry.TABLE_SCTP_PPID, inTABLES), with keys from 0 to 2**32 - 1, the PPID's width, soregister(),register_all(),derive()anddecode_asraiseInvalidRegistryKeyErroroutside it.decode_user_data()decodes the user data of a DATA or I-DATA chunk with both B and E set through the table ofregistry(the default registry whenNone), and answersNonefor another chunk type, a fragment, a value too short for the user data, and a PPID with no entry or aWITHHELDone; a decoder that rejects the bytes raises its ownProtocolError. The walk is unchanged and ends at SCTP:SCTP.next_protocol()still answersNone, since a packet can carry several DATA chunks with their own PPIDs and a message can be fragmented across chunks, which the walk's single successor cannot express;decode_frame()'sdecode_asaccepts the table's name and no walk reads it. The registry module docstring, README and ARCHITECTURE list the table.
-
ARCHITECTURE.md, the README and docs/CLAIMS.md describe
netprotocols.reassembly, and the design note records what shipped (#379).docs/design/reassembly.rst§1.2 says a frame the reassembler does not apply to still returns the expiries its timestamp triggers, §1.5 addsValueErrorfor a negative timestamp, and §7.2 and §7.6 say the crafted overlap vectors are built inside the tests and tshark's values recorded in the tests and MANIFEST. ARCHITECTURE.md gains a section, Reassembly is a separate, stateful step, a sentence in The decode contract thatdecode()anddecode_frame()keep no state and the reassemblers are the only objects that do, a layout-map entry, and, in the checksum section, that aDatagram's IPv6 header serves asip. The README gains Reassembling fragments, with the loop and the bounds. CLAIMS.md re-derives the count of standard-library modulessrc/imports (17, withbisectandheapq) and adds "reassembles exactly as does" to the claims not to make. -
The documentation names
netprotocols.reassemblyas one way to get a TCP stream (#380). ARCHITECTURE.md's Reassembly is a separate, stateful step describes the stream reassembler and the loop that feeds both reassemblers, and its SCTP, TFTP, BGP, TLS and HTTP paragraphs and layout map name it; the README's section becomes Reassembling fragments and streams, with the loop and both bounds tables, and its BGP, TLS and HTTP rows and Decoding HTTP name it; SECURITY.md keeps TCP reassembly and segment-overlap tricks outsideHTTP's,BGP's andTLS's scope and puts them in the module's, with a retransmission older than the retained bytes as the documented exception; the docstrings oflayer7/http.py,layer7/bgp.py,layer7/stun.py,layer7/tls.pyandchecksum.pysay the same; docs/CLAIMS.md re-derives the stdlib count, unchanged at 17, and says TCP overlaps followfirstorlastonly. The docstrings of the event types and enums the two reassemblers share now cover TCP. The design note records what shipped: §2.1 charges each TCP directionPIECE_OVERHEAD; §2.3 sends an oversize TCP segment out throughGap(CAP)rather thanEvicted, sheds recordedGap(ACKED)ranges after the retained bytes, and gives the flush of the arriving frame's own evicted flow that frame's ref, as §1.4 now says; §4.4 returns a cancelled RST to its connection's class of idle timeout; and §4.7 times each acknowledged hole's grace from the first acknowledgement past it while it is the lowest, declares holes only up to that acknowledgement, and records declared gaps independently of the retained bytes. -
Decoding is faster, most of all on the routing captures, with every decoded field, error and offset unchanged (#250). Four changes, chosen from a
cProfileofdecode_frame()over each routing capture. (1)OSPF,BGPandVRRPbuild their decoded instance directly, asEthernet,ARPandIPv4already did, instead of through the constructor, whose__post_init__repeated every checkdecode()had just run: for OSPF a second walk of the body's framing, every LSA of a Link State Update included. (2)PIM.decode()finds where a message ends from the fields its parser reads (encoded-address families, encodings and widths, Join/Prune group and source counts, Assert's metrics, a Hello's option lengths against its zero tail), without building the typed message, its group sets and its validated encoded addresses only to discard them;PIM.messagestill runs the parser. (3)TCP,UDP,RIPandPIMbuild their decoded instance directly too. (4) Every directly built header stores its fields through each slot's descriptor__set__, bound once at import by the new privatenetprotocols._base.slot_setters(), rather thanobject.__setattr__, which looks the name up on every call. The seven classes of (1) and (3) take the direct path only whendecode()is called on the class itself (VRRP's also forVRRPv6); called on any other subclass, which may add fields or checks of its own,decode()builds it through that subclass's constructor,__init__and__post_init__included, as before. No public name, field type or validation changes, and a differential run of master and this branch over the corpus and 8,000 mutated frames, throughdecode_frame()strict and lax and every class'sdecode(), gives byte-identical output, error types, messages,offset,frame_offset,expectedandactualincluded. Measured with the same-job A/B runner of #365 (scripts/benchmark_ab.py, 16 pairs, 20 repetitions, best of 5; ratio = this branch's time over masterd68b7fb's, CPython 3.13.18, a self-comparison reading 0.996 on the corpus and 1.000 on the routing captures): the 509-frame corpus 0.856 (quartiles 0.838-0.862), the five routing captures 0.687 (0.675-0.702);ospf.pcap0.737,bgp.pcap0.728,pim.pcap0.452,rip.pcap0.785,vrrp.pcap0.713. The subclass test costs nothing measurable: against the branch without it, corpus 0.981 and routing 1.012, inside the noise. Change by change, each against the one before: (1) corpus 0.965, routing 0.872,ospf.pcap0.806,bgp.pcap0.893,vrrp.pcap0.804; (2) corpus 0.987, routing 0.912,pim.pcap0.538; (3) corpus 0.978, routing 0.945,bgp.pcap0.892,rip.pcap0.872,pim.pcap0.897; (4) corpus 0.941, routing 0.903, each routing capture 0.887-0.905, all four measured before the subclass test was added. Againstdpkt 1.9.8on the same machine,benchmark.py --compare --repetitions 30 --trials 9reads dpkt 1.44-1.47× faster on master and 1.20-1.27× on this branch, three runs each; per capture, dpkt's lead goes from 1.58× to 1.14× on OSPF, 1.60× to 1.16× on BGP, 2.26× to 1.01× on PIM, 1.38× to 1.08× on RIP and 1.30× to 0.98× on VRRP (best of 9 per file). These are not the release re-measurement Rule 4 ofdocs/CLAIMS.mdasks for; §1.2 records them beside the 2.9.0 figure. -
ARCHITECTURE.md's decode contract states which accessors raise and which degrade (#350). A type-length-value walk that returns a tuple raises
InvalidFieldErrorwhen its bytes do not walk; lookups and display helpers degrade toNone. The accessors it named outside that split are aligned with it by #361 (below). -
Every accessor that walks a sequence and returns a tuple raises
InvalidFieldErrorwhere its bytes do not walk, andRADIUS's packet-level lookups degrade, as ARCHITECTURE.md's decode contract states (#361). Each of these accessors was released with the behaviour given first, so code that readNone(or()) from a malformed value, or caughtTruncatedHeaderErroror a raise from a RADIUS lookup, needs updating. Where each still answersNonewithout raising is unchanged: there is nothing in its format to walk.SCTPChunk.gap_ack_blocksandduplicate_tsns, not yet released, raise as the #238 entry (above) states.NTP.extension_fieldsnever raised: in an NTPv4 message its walk stopped, and returned the fields before, at 1-3 bytes left for a field header, at a Length below 16 or not a multiple of 4 (RFC 7822 §3), or at a Length past the body, leaving the rest toremainder. It now raisesInvalidFieldErrorthere (protocolNTP,field"body",offsetrelative tobody, whereremainderstarts;expected4,">=16, a multiple of 4"or the Length, andactualthe bytes left or the Length). A walk that ends at the end of the body, or where what is left is 4, 20 or 24 bytes, the MAC, does not raise, and below version 4 it is()as before. So it raises for an NTPv4 message exactly when itsremainderis not empty, a 12-byte DES authenticator (RFC 1305 §C) in a version 4 message among them.NTP.macandNTP.remaindernever raise, as before.PIMHello.address_listraisedTruncatedHeaderError, which is not anInvalidFieldError, for an address that runs past the Address List option's value. It now raisesInvalidFieldErrorthere, with the sameprotocol(PIM),field("body"),offset(relative to the option's value),expectedandactual. A family or encoding it cannot size still raisesInvalidFieldError, and a Hello without the option still answersNone.RADIUS.user_name,nas_ip_address,nas_portandframed_ip_addressread throughparsed_attributesand raised itsInvalidFieldErrorfor a broken attribute anywhere in the packet. They now read the attributes up to the first that does not walk, asSTUN.attribute()does, answer the first value of their type found before it, and answerNone, never raising, when there is none.parsed_attributesstill raises. The tolerant read STUN used is now the privatenetprotocols._tlv.read_until_malformed, which both use.CDP.addressesandCDP.management_addressesansweredNonefor a TLV value shorter than its 4-byte address count, and for an address the count gives that runs past the value. They now raiseInvalidFieldErrorthere (protocolCDPTLV,field"value",offsetrelative to the TLV's value, where the count or the address starts;expectedthe bytes from there through the next field needed to size the address: its 2-byte type and length, then through its Address Length, then the whole address, andactualthe bytes left). A PDU without the TLV still answersNone.IPv6Routing.segmentsansweredNonefor a type 0 (RH0) or type 2 (Mobile IPv6) header whose data after its 4 reserved bytes is not a whole number of 16-byte addresses, which an oddhdr_ext_lengives. It now raisesInvalidFieldErrorthere (field"data",offsetwhere the half address starts, relative todata,expected16,actual8). Every other routing type still answersNone.IPv6Routing.final_destination(), a lookup, answersNonewheresegmentsraises, as it did for such a header before, so checksums and flow keys are unchanged.
-
A 50-byte HSRPv1 message carrying the MD5 Authentication TLV is one 50-byte
HSRPlayer, not 20 (#282). For such a messageheader_lenis 50 where it was 20,bytes()gives all 50 bytes where it gave the first 20, a walk'sconsumedcovers the TLV where it stopped 30 bytes short of the datagram's end, and equality and the hash compare the TLV throughmd5_authentication, so two such messages differing only in the TLV, or one with it and its first 20 bytes alone, are no longer equal.dataclasses.fields(),astuple(),asdict(),repr()and__match_args__of everyHSRPgainmd5_authenticationas their last item, so a positional pattern of ten fields still matches. Every other HSRPv1 message is decoded exactly as before, 20 bytes long, and the set of payloadsHSRP.decode()accepts or rejects is unchanged. -
UDP port 1985 reads the first two bytes before choosing
HSRP,HSRPv2orHSRPAdvertise, andUDPkeeps two payload bytes as decode context, not one (#281).HSRP._for_payload()answersHSRPAdvertisefor a datagram whose first two bytes are00 03, Version 0 and Op Code 3, so a Cisco interface-state Advertise to or from port 1985 now decodes asEthernet→IPv4→UDP→HSRPAdvertisewhere a strict walk raisedInvalidFieldErroratopcodeand a lax one stopped at UDP; the choice holds whereverHSRPis registered, a port named indecode_asincluded. A datagram opening with00 03, which stopped a walk withHSRP'sInvalidFieldErroratopcode, now stops it withHSRPAdvertise'sInvalidFieldErrorattlv_typeas soon as its third byte, the TLV Type's high byte, is nonzero, attlv_typeorstateonce a TLV Type other than 1 or 2 or a State other than 1-3 is present, and otherwise, when it is shorter than 16 bytes, withHSRPAdvertise'sTruncatedHeaderError(frame_offsetat the message). HSRPv1 Hello, Coup and Resign decoding is unchanged, every other Op Code is still rejected byHSRPatopcode, and HSRPv2's dispatch on a first byte of 1 is unchanged.HSRP.decode()called directly on an Advertise still raisesInvalidFieldError(field="opcode",actual=3,offset1), its message now "(Cisco's Advertise: decode it with HSRPAdvertise)" where it said "(Cisco's interface-state Advertise; not decoded)". The Advertise is a separate class, asHSRPv2andNTPControlare, so this entry changes none ofHSRP's fields or its contract; the one change to them in this release is #282'smd5_authentication(above), which makes a 50-byte message carrying the MD5 Authentication TLV one 50-byte layer. To let the hook see the Op Code,UDP.decode()now keeps the first two bytes of its payload as decode context, where it kept the first:UDP._leadis the big-endian 16-bit integer of those two bytes, its low byte 0 when the buffer or a UDP Length of 9 ends the payload after its first byte, and stillNonefor a Length of 8, an empty buffer and a header built or copied withdataclasses.replace(); it stays onecompare=Falsefield outside equality and the hash, sodataclasses.fields(UDP)is unchanged, butasdict()andastuple()of a decodedUDPnow give_leadthat 16-bit value (for an NTP mode 6 request,0xD602where they gave0xD6). The private hookProtocol._for_payload(lead)receives the same integer:NTP._for_payload()reads the mode fromlead >> 8andHSRP._for_payload()the first byte fromlead >> 8, and a subclass outside this library overriding the hook with the first byte in mind must shift it likewise. A single integer was kept, rather than two fields or abytesslice, because it leaves the field list alone and costs nothing on the hot path:UDP.decode()reads the 8-byte header and the two payload bytes with onestructunpack when the buffer holds 10 bytes or more, and falls back to the 8-byte unpack, and itsTruncatedHeaderError, otherwise. Abytesslice measured about 80 ns (12%) slower perUDP.decode()than the tree before, two separate index reads and a shift about 47 ns (7.5%) slower, and the one unpack 6-8% faster (see "Development"). -
UDP port 1985 reads the first byte before choosing
HSRPorHSRPv2, and UDP port 2029 namesHSRPv2(#280).HSRP._for_payload()answersHSRPv2for a first byte of exactly 1, the Group State TLV's Type, andHSRPfor any other, through the mechanismNTP._for_payload()added forNTPControl, so an HSRPv2 message to or from port 1985 now decodes asEthernet→IPv4→UDP→HSRPv2where a strict walk raisedInvalidFieldErroratversion. HSRPv1 decoding is unchanged, every first byte but 0 and 1 is still rejected atversion, andHSRP.decode()called directly on an HSRPv2 message still raisesInvalidFieldError(field="version",actual=1), its message now "(HSRPv2's Group State TLV type: decode it with HSRPv2)" where it said "not decoded". HSRP for IPv6, the HSRPv2 format from and to UDP 2029, to ff02::66, is registered in the defaultudp.porttable asHSRPv2, so it decodes asEthernet→IPv6→UDP→HSRPv2. The dispatch is a separate class rather than a dispatch insideHSRP, asNTPControlis besideNTP, so this entry changes none ofHSRP's fields or its contract and HSRPv2's TLVs get a class of their own; the one change toHSRP's fields and contract in this release is #282'smd5_authentication(above). This entry decodes neither Cisco's Op Code 3 Advertise nor HSRPv1's MD5 Authentication TLV;HSRPAdvertise(#281) andHSRP.md5_authentication(#282), both above in this release, decode them. -
STPdecodes an MST BPDU that passes IEEE 802.1Q §14.5 e) to its Version 3 Length, not to its 36-octet RST prefix (#299). For such a BPDUheader_lenis 38 plus the Version 3 Length (134 for each MST BPDU ofstp.pcap, 36 before),bytes()includes the Version 3 information, a walk'sconsumedcovers it, and equality and the hash compare it through the newmstfield. The constructor raisesInvalidFieldError(field="mst") for anmston a BPDU that is not type 0x02, version 3 or greater with a Version 1 Length of 0, or whose Version 3 Length is not 64 plus 0 to 64 whole MSTI messages or disagrees withlen(mst).port_role_namenames CIST Port Role 0"Master", as 802.1Q does, in such a BPDU,"Unknown"before; an RST BPDU's role 0 is still"Unknown". Every other BPDU, an MST BPDU failing the validation included, decodes exactly as before. The slice the module docstring used to give for recovering the Version 3 information from a walk now finds nothing after a validated MST BPDU; readSTP.mstinstead. -
UDP port 123 reads the mode in the first byte before choosing
NTPorNTPControl(#272).UDP.decode()keeps the first byte of its payload, when the buffer holds one and the Length does not say the payload is empty, as decode context outside its comparison and hash (_lead, likeLLC's andMPLS's), andUDP.next_protocol()hands it to the class its port names through the newProtocol._for_payload(lead), which answers the class itself unless overridden.NTP._for_payload()answersNTPControlfor mode 6, sontpqtraffic to or from port 123 now decodes asEthernet→IPv4→UDP→NTPControlwhere a strict walk used to raiseInvalidFieldError. The registry still holdsNTPat port 123, and the choice applies whereverNTPis registered, a port named indecode_asincluded. Mode 3, 4 and every other time message decodes exactly as before, and mode 7 (ntpdc) is still rejected byNTP.NTP.decode()called directly still rejects mode 6 withInvalidFieldError(field="mode",offset0), whose message now namesNTPControl; mode 7's says it is a private control message. A UDP header built with the constructor, or copied withdataclasses.replace(), has seen no payload and answers the port's class as before.dataclasses.fields(),asdict()andastuple()of aUDPnow include_lead. A mode 6 first byte with a version outside 1-4 (0, or 5-7) now reachesNTPControl, so theInvalidFieldError(field="version",offset0) a walk raises for it namesNTPControlas itsprotocol, where it namedNTP. -
An OSPF LSA of LS type 1 to 5 or 7 whose body lacks its framing is refused (#298).
OSPFLSA()raisesInvalidFieldError(field="body", no offset) for a Router-LSA whose "# links" and per-link "# TOS" do not walk its body exactly (too short for its 4 fixed bytes, a link or its TOS entries past the end, bytes after the last link), and for a Network-, Summary-, AS-external- or NSSA-LSA that is not its fixed part plus whole entries. So doesOSPF()andOSPF.decode()for a Link State Update carrying such an LSA,decode()with the offset of the first byte that breaks it, counted from the start of the OSPF header like its other framing errors; a strict walk raises and a lax one stops after IPv4, as for any malformed OSPF body. Before, any body of the declared length was accepted and kept raw. This makes the typed accessors safe to read, which never raise: the check runs once, at construction, as the packet's own message framing does. Bodies of other LS types are accepted as before.
Ethernet,ARP,IPv4andHTTPbuild a user subclass through its constructor. Theirdecode()builds the instance directly, without__init__or__post_init__, only when called on the library class itself, as the seven classes of #250 already did; called on any other subclass, it builds the instance through that subclass's constructor with the field values the direct path stores, so a field the subclass adds gets its default and its__post_init__runs. Before, a@dataclass(frozen=True, slots=True)subclass that added a field raisedAttributeErrorreading it, and fromrepr()and==, and its__post_init__never ran.HTTPpasses therequest_methodit was given, which its constructor normalizes asdecode()does. Decoding with the library classes is unchanged:scripts/benchmark_ab.py --pairs 8againste017fc3reads a median of 0.994 on the corpus.tests/test_fuzz.py::TestDecodeIntoASubclasscovers the four as it does the seven, anHTTPsubclass'srequest_methodand close-framed body included.
-
Fragment reassembly is tested against real captures, the running kernel and Suricata's vectors (#379).
scripts/capture_fixtures_reassembly.shcaptures, over a veth pair in two netns on 10.9.79.0/24, a 4,000-byte UDP datagram and two dnsmasq TXT answers fragmented by the kernel (tests/fixtures/reassembly/ipv4_udp_fragments.pcap), and ICMP echo trains a script cut into overlapping and duplicated fragments, with the echo replies of the kernel that reassembled or discarded each (linux_overlaps.pcap).tests/test_reassembly.pycompares the datagrams of these captures and ofipv4_fragments.pcapandipv6_fragments.pcapwith tshark's reassembled data and reassembled-in frame, checks every rule, policy and bound on crafted fragments, and runs Hypothesis properties;tests/test_reassembly_memory.py, also run underPYTHONTRACEMALLOC=1in CI, floods a reassembler with 200,000 datagrams and holds the overhead constants to CPython's allocations;tests/typecheck/reassembly_events.pychecks that amatchoverFragmentEventis exhaustive undermypy --strict; andtests/test_exports.pyrecordsreassemblyas a public submodule the package neither re-exports nor imports. -
Stream reassembly is tested against real captures, tshark and a byte-level model (#380).
scripts/capture_fixtures_reassembly_tcp.shcaptures, over a veth pair in two netns on 10.9.80.0/24 withadvmss 536, curl fetching a 200,000-byte body and a chunked response on one connection and a socket client that ends its connection with an RST (tests/fixtures/reassembly/http_stream.pcap, 593 frames).tests/test_stream_reassembly.pyreassembles it,http/http.pcapandtls/tls_session.pcaptoscripts/extract_http_streams.py's streams and to tshark's followed streams (recorded SHA-256), decodes the new capture's HTTP messages from the runs with each message's completing frame equal to the frame tshark completes it in, reads every TLS client's SNI through the runs, checks every rule of the design note's section 4 on crafted segments, each cap and timeout at its limit, and runs Hypothesis properties against a reference model offirstandlast.tests/test_stream_reassembly_memory.py, which CI runs underPYTHONTRACEMALLOC=1, holds a 200,000-SYN flood to its caps and the charges to what CPython allocates.tests/typecheck/reassembly_events.pychecks amatchoverStreamEventis exhaustive. -
scripts/benchmark.pytimes a chosen set of captures, or the frames on which netprotocols and dpkt decode the same protocols (#366).--fixture NAME, repeatable, restricts the workload to the frames of the named captures intests/fixtures, matched by file name with or without.pcapin any letter case; an unknown name is a usage error that lists the valid ones.--same-depthrestricts it, in an untimed pass before timing, to the frames both libraries accept and whose layer chains are equal after a fixed fold: netprotocols'VLAN,MPLS,SNAP,IPv6FragmentandIPv6HopByHopOptionslayers, which dpkt decodes as attributes, are dropped from its chain; dpkt'sEcho,TimeExceed,Unreachandstrobjects, which netprotocols keeps as fields, and its raw payloads are dropped from dpkt's; and the two libraries' names for IPv4, IPv6, ICMP and ICMPv6 are mapped to one name each (NETPROTOCOLS_FOLDED,DPKT_FOLDEDandCOMMON_NAMES). The packet aTimeExceedorUnreachquotes is not dropped, and a frame on which the two reach different protocols, such asLLCagainst dpkt'sIPX, is not kept.--same-depthimplies--compare, combines with--fixture, needs dpkt and says so before reading any frame, prints how many frames it kept out of how many, also when it keeps none, and is defined against dpkt alone, so scapy is timed on the same frames without what it decodes being checked; the comparison's caveats then describe that selection. Both options also restrict the frames--depthreports on;--depthitself still compares raw layer counts and its output on the whole corpus is unchanged.--jsongains aselectionobject with the fixture names, the--same-depthflag and the selected and total frame counts. On the 509-frame corpus--same-depthkeeps 324 frames, 106 of them OSPF; of the other 185, netprotocols decodes further on 173, dpkt on 4 (three ICMP time-exceeded messages whose quoted packet dpkt decodes, and one MPLS pseudowire), the two reach different protocols on 1, netprotocols rejects 5 and dpkt 2.--depthreads 196 frames deeper and 306 the same, the latter including the frames dpkt decodes further. The newtests/test_benchmark.pycovers the selection, the fold and the depth report with dpkt's chain replaced by a stand-in, so it runs without thebenchgroup. Bandit 1.9.4 reads 16 Low (from 17):depth_report()'stry/except/continue(B112) is gone, andRELEASE.md's step 5 baseline says so. -
A design note specifies the opt-in reassembly module for IP fragments and TCP streams (#373).
docs/design/reassembly.rst, built by Sphinx through a toctree indocs/index.rst, sets outnetprotocols.reassemblybefore any code: the input (a decodedPacketand its frame), the reassemblers and their events, frame references asSpans that tile each datagram or byte run and name the completing frame, the per-flow, global and flow-count caps with their eviction, idle and age timeouts on capture time, and their defaults; IPv4 and IPv6 fragment rules (RFC 791, RFC 8200 §4.5, RFC 5722, RFC 6946, RFC 1858) with the named overlap policies; TCP stream rules; the response to each Ptacek & Newsham technique and state-exhaustion flood; the documentation that changes; the test plan; and the split into a fragment issue and a TCP issue with acceptance criteria. It records 17 accepted design decisions, each with the options weighed and its trade-off.decode()anddecode_frame()are unchanged. -
A release checks decode time against the last release before it measures any figure. CI's benchmark gate (#251) compares each pull request only with its merge-base, so slowdowns that each stay under its 5% threshold can add up across a release.
RELEASE.md's step 3 gains an item, run first on the release machine under the load gate andtaskset -c 2: a noise run,scripts/benchmark_ab.py --base HEAD, then the check,--base "v$PREV", with the script's defaults, 16 pairs and CI's 5% threshold. That threshold was set fromubuntu-latest's noise (CLAIMS 1.7), so a noise-run median outside 0.975-1.025 sends the check's result, whatever its exit status, to the maintainer. Exit 1 stops the release until the slowdown is fixed onmasterby its own PR, after which the release starts again from step 1, or the maintainer accepts it with a recorded reason; exit 2 is fixed and the check run again. Since a frame the base decodes less deeply stays in the timing, a release that adds decoders can exit 1 for doing more work, and the Exit 1 case gives a command that counts, of the frames both trees decode, those whose layer count differs, which rules that cause out only at 0. Item 3 first checks thatv$PREVis an ancestor ofHEAD(git merge-base --is-ancestor), records the commit it measures asCANDIDATE, and setsCHECKEDto it only once the result is accepted; after a review fix, step 4 reruns it whengit diff --exit-code -I '^__version__ = ' "$CHECKED" HEADover the benchmark's inputs (src,tests/fixtures,scripts/benchmark_ab.py,scripts/_benchmark_ab_worker.pyandscripts/_pcap.py) exits 1, and step 8 does the same for the commit to be tagged, after gate fixes or before a retag. The result is adrift vs v$PREVrow of the command table in the release's "Re-measured for" section ofdocs/CLAIMS.md, and the release's CHANGELOG entry says the same. -
docs/CLAIMS.md's tree-counted claims are re-derived for 2.12.0 (#366). Each count CLAIMS derives from the tree rather than times was recomputed ate017fc3with the method its section gives; three had moved and are updated in place. §5.3's coverage is 7,485 statements with none missed (from 6,202 with 1 missed,Packet.__eq__'sNotImplementedbranch, on 2026-11-01), by CI'suv run --frozen pytest --cov=netprotocols --cov-report=term, the same on CPython 3.12 and 3.13.18. §5.5'stests/test_registry.pycollects 107 tests (from 66;uv run --frozen pytest tests/test_registry.py --collect-only). §3.2's twosocketcalls are now_base.py:244-249(from 196-201;grep -n 'inet_pton(socket\|inet_ntop(socket' src/netprotocols/_base.py). Unchanged and left as they are: §5.9's AST sweep, still 263 of 296 with the same 33 outside the claim andrandom_mac's the only direct constructor call withoutprotocol=; the corpus's 509 frames in 43 scenarios (§5.1, README.md, MANIFEST.md;tests/conftest.py'scorpus_frames()andtests/fixtures/*.pcap); §5.1'stests/test_corpus.py:135-140; §5.2's 45 round-tripped protocols, 41 of them inTestGeneralizedRoundTrips; §5.7's 85tests/test_walk.pytests and its corpus maxima (10 layers, TLS's 9, 7 for nested headers); §5.9's 37tests/test_diagnostics.pytests; §3.2's 15 stdlib modules; §5.5's eight registry tables; and the 14, 11 and 15 fields ofIPv4,TCPandDHCP(§2.2, README.md, ARCHITECTURE.md). No timed figure and no "Re-measured for" section is touched: those are for the release machine. -
The CI benchmark gate compares the pull request with its merge-base in the same job, and
benchmarks/baseline.jsonis gone (#251). Thebenchmarkjob checks out the full history and the newscripts/benchmark_base.shpicks the base: the merge-base with the base branch for a pull request, otherwise the commit before the push (github.event.beforewhen it is a proper ancestor of the pushed commit, elseHEAD^1). The newscripts/benchmark_ab.pyexports the base'ssrcwithgit archiveand copies the head's, both without bytecode, into one temporary directory, then times them in 16 alternating pairs (an even number is required, so each tree goes first equally often), each measurement a freshpython -I -S -Bprocess of the same interpreter runningscripts/_benchmark_ab_worker.pywith one tree'ssrcfirst onsys.pathandsite-packagesoff, so neither tree, nor the editable install, is importable from the other's process; each process writes its result to a file it is given, so whatever a tree prints is not read as the result, and reports itsnetprotocols.__file__and any module from outside its tree, scanned after the import and after the last decode; the comparison stops if one is. Both trees decode the head'stests/fixtures; every frame either tree raises on is dropped for both, the two counts are printed apart, and each timed run must decode exactly the frames left and reject none. A base or head that cannot be exported, copied or loaded, a missing or empty fixtures directory, a worker result with a missing or wrongly typed field or a time that is not a positive finite number, or a non-finite--threshold, exits 2. The job prints every pair's times and ratio (head time over base time), then the median, minimum, maximum, spread and quartiles, and fails when the median is more than 5% above 1.0. The base contributes only itssrc, so a base withoutbenchmark_ab.py, or with an olderbenchmark.py, is measured the same way. The 5% threshold is set from CI's own noise: ten runs of PR #365's ownbenchmarkjob onubuntu-latest(workflow run 42383097241, job 128434688562 and nine reruns), where neither tree changessrc/, each 16 pairs, read medians of 0.9962, 0.9985, 0.9927, 1.0016, 1.0021, 0.9979, 0.9992, 0.9965, 0.9998 and 0.9969 (0.9927-1.0021, -0.7% to +0.2%), single-pair ratios from 0.945 to 1.062 and a per-run spread of 0.036-0.101, in a job of 31–51 s, so 5% is about seven times the median's largest deviation from 1.0. The newbenchmark-noise.yml, a hand-dispatched workflow, runs the comparison with the base equal to the head on ten runners, to measure it again. Locally, on a 4-vCPU Xeon VM (CPython 3.13.18), on an earlier revision of the script that allowed 15 pairs and skipped only the frames the base raises on, six noise runs of--base HEADwith 15 pairs read medians of 1.0024, 1.0029, 0.9980, 1.0074, 1.0214 and 1.0060 (-0.2% to +2.1%), with per-pair ratios from 0.942 to 1.065, and a head slowed by a busy wait indecode_frameread +17.2% twice at 1.2 µs a frame and +29.7% and +28.0% at 2.5 µs, failing each time; one 16-pair noise run on the revision that requires an even count read a median of 0.9982, with per-pair ratios from 0.968 to 1.041.scripts/benchmark.pyloses--check,--update-baseline,--thresholdand the calibration workload with its normalized figure, which existed only to compare against the committed baseline; it keeps--compare,--depthand--json, and the job still prints--compare's dpkt and scapy figures in a step that gates nothing. The previous baselines stay in git history and in CLAIMS' dated sections. -
The decode paths #250 changed are pinned by property tests.
tests/test_fuzz.py::TestDirectlyBuiltDecodesPassValidationrebuilds every directly built layer through its constructor, from fuzzed walks, from each class'sdecode()on raw fuzz bytes and from the corpus, and checks the constructor accepts it and gives an equal header with the same bytes; it also decodes each class through a subclass with no slots of its own and compares every field. Its raw-bytes property suppresses onlydecode()'sProtocolError, never the constructor's, and carries examples that adecode()check the constructor repeats refuses (TCP's data offset below 5 or past the buffer, OSPF's version, Packet Length below 24 and Hello framing, PIM's and VRRP's versions, VRRP's address count past the buffer, BGP's Length shorter than its header or past the buffer), plus clean RIP and UDP messages, so the default profile fails when any of those checks is dropped from a directly builtdecode().TestDecodeIntoASubclasschecks that a user subclass of each of the seven classes gets its added field's default and runs its__post_init__, that a subclass ofUDPorBGPkeeps the decode context its library class records (the first payload bytes, a following message), and that the library classes,VRRPv6included, never call__init__.tests/test_pim.py::TestMessageEndchecksPIM's message end against its parser's on built messages with bytes changed, cut and appended, on random bodies and on edge cases. Two profiled candidates measured as noise and were not kept: folding the walk's_bounded()and Ethernet's_length()into their callers (corpus 0.995, routing 0.999), and unpacking the fixed header inEthernet.decode()andIPv4.decode()without_unpack_fixed()(corpus 0.998, routing 1.017). The per-frame walk costs each come to about 2% of a frame or less (Ethernet's type-or-length dispatch,_payload_extent(), slicing, the registry lookup,Packetconstruction).scripts/measure_port_guard.pyfor ports 123, 520 and 1985 prints the same figures on master and this branch. -
The capture-seeded RADIUS strategy is cut at the packet's end at least half the time, so its property reaches the attribute walk (#351).
_radius_seededintests/test_fuzz.pydrew its cut uniformly over the captured packet, which leaves the RADIUS Length past the buffer in nearly every example; it now drawsst.one_of(st.just(len(raw)), st.integers(0, len(raw))), the whole-packet-weighted cut_stun_seededuses.TestRADIUSAccessorSafetygains threehypothesis.eventlabels,RADIUS decode: accepted,RADIUS decode: rejectedandRADIUS Vendor-Specific reached: True/False, so--hypothesis-show-statisticsshows each rate. Measured withpytest tests/test_fuzz.py::TestRADIUSAccessorSafety --hypothesis-show-statistics, as a share of the property's examples (decode accepted / walk yields at least one attribute / a Vendor-Specific reached), before and after: under the default profile (200 derandomized examples) 1.49% / 0% / 0% became 13.50% / 11.50% / 8.50%; undernightly(10,000 examples, a random seed each run, so its figures vary from run to run) about 1.5-1.8% / 0.7-1.1% / 0.3-0.6% became about 11.5-12.7% / 8.3-9.5% / 5.6-6.7%. The property draws fromst.one_of(_radius_seeded(), fuzz_input), which Hypothesis flattens into three equally weighted branches (free bytes and a mutated corpus frame being the other two), so about a third of its examples are capture-seeded. Drawn alone over 10,000-example random runs,_radius_seededwent from about 5% / 3% / 1.3% to about 40-43% / 30-32% / 20-22%. Its other examples are the uniform cuts, which still exercise truncation, a mutated Length, and the capture's two 20-byte Accounting-Responses, which hold no attribute, so the draw is not changed further. -
docs/CLAIMS.md§5.9's raise-site count is re-derived (#361), and §5.2 says which ofCDP's andNTP's accessors raise. Its AST sweep gives 271 of the 304raisestatements insrc/(263 of 296 before), atf4b2856; the 33 outside the claim are the same by kind. §5.2 movesCDPandNTPfrom the protocols whose accessors never raise to those that raise onlyInvalidFieldErrorfrom the walk of their body. -
docs/CLAIMS.md§5.9's raise-site count is re-derived (#350). Its AST sweep gives 263 of the 296raisestatements insrc/(230 of 260 before the re-derivation), and the 33 outside the claim are re-listed by kind. -
HSRPv2's Interface State TLV is tested against hand-built vectors, with no capture (#357). No sender of HSRPv2 runs in a Linux netns (see #280's entry below), so the new
tests/test_hsrpv2_interface_state.pypacks its messages field by field withstructandsocket, each labelled hand-built, cross-checked against packet-hsrp.c at commit 6f7207a6 (SHA-256b09e0dc1521e1b24e5be80efc8c901d26b4c0be3798464661dd80152fb780a39; the TLV's diagram, lines 80-87; its reading, lines 544-564; the counts' widths, lines 777-785; the Undefined TLV branch any other Length falls to, lines 594-599): tenVECTORS, 1 active and 0 passive groups after a Hello, 0 and 3 after a Standby Hello, 65535 and 65535, a distinct value in each count (0x1234 and 0xabcd), 2 and 1 in HSRP for IPv6 on UDP 2029, and the TLV between a Text and an MD5 Authentication TLV, last after both, twice, after a second Group State TLV and after a raw TLV of Type 0. tshark 4.2.2 (Ubuntu's 4.2.2-1.1build3) then decoded 24 messages written withstructalone (13 positive, 8 of a wrong Length and 3 truncated) into a temporary pcap outsidetests/fixtures, as Ethernet/IPv4 from 192.0.2.11 to 224.0.0.102 on UDP 1985 or Ethernet/IPv6 from fe80::a:9c3:b to ff02::66 on UDP 2029 (tshark -r <pcap> -V -O hsrp2and-T fields): the tenVECTORS,tests/test_hsrpv2.py's Resign vector,tests/conftest.py'sraw_hsrpv2_interface_stateand the passing message oftests/test_check_fixtures.py's new case, each with Good IPv4 and UDP checksums (UDP only, for IPv6). For twelve of those thirteen tshark showed an "Interface State TLV" whose Active Groups and Passive Groups equal whatHSRPv2.decode()reads from the same bytes: 1 and 0 (four messages), 0 and 3, 65535 and 65535, 4660 and 43981, 2 and 1, 4 and 5, 6 and 7, 8 and 9, and, fortwice, 1 and 0 then 0 and 1. Forafter_raw_tlvit read the Type 0 TLV as undefined and showed the 8 bytes from it on as data, without the Interface State TLV the library decodes after it: packet-hsrp.c stops its walk at any TLV it does not define, whereHSRPv2.decode()keeps it raw and walks on, as it has since #280. tshark labels the TLV "Type=2 Len=6" where 6f7207a6 prints "Len=4": its v4.2.2 source passes2+lento that label (line 555, SHA-256b7090a33c6865cca9f1dba7424199a159ef490bf3ca1706b8628132f8c63509d), and reads the two counts at the same offsets and widths. For the negative cases tshark decoded no Interface State TLV: a Type 2 TLV of Length 0, 3, 5 or 255 after the Group State TLV, of Length 5 after a Text or an MD5 Authentication TLV, of Length 3 after a whole Interface State TLV, and the failing message oftests/test_check_fixtures.py's new case, the same bytes as the Length 5 after a Text Authentication TLV, it showed as data from that TLV on, where the library raisesInvalidFieldErrorat its Length byte (offset 43, 43, 43, 43, 53, 73, 49 and 53); the TLV cut to 3 or 5 bytes, and a lone Type byte, it reported as "Malformed Packet", where the library raises at the walk (field="tlvs", offset 42). The file covers every Length from 0 to 255 at five positions, every truncation, the accessor, any two counts (Hypothesis), construction at every width, equality and the hash,HSRPv2TLV's refusal of Type 2 at any value length, the export, andscripts/check_fixtures.py, which passes every vector and fails exactly the Lengthsdecode()refuses (hsrpv2-tlv-length, every Length from 0 to 255). Intests/test_hsrpv2.pythe Resign vector, renamedv4_resign_interface_state, now decodes its TLV asHSRPv2InterfaceState, the raw-TLV test uses Type 5, the wrong-Length cases add Type 2 at Lengths 0, 3 and 5, andHSRPv2TLV's refused Types are 1-4.tests/strategies.py'shsrpv2_messages()draws Interface State TLVs and no raw TLV of Type 2;tests/test_fuzz.pyaddsinterface_stateto_HSRPV2_ACCESSORSand the class to_HSRPV2_TLV_ACCESSORS, whose seed messages already end in an Interface State TLV a quarter of the time;tests/test_contract.pytruncatesraw_hsrpv2_interface_stateand walks it strict and lax to one 48-byte layer and back, and a Length of 5 to an error.tests/test_check_fixtures.pyadds an Interface State TLV of 5 bytes to itshsrpv2-tlv-lengthcases.scripts/check_fixtures.py's_check_hsrpv2, which already held the TLV's Length to 4, is unchanged but for its docstring, which no longer says the library keeps the TLV raw, and its report overtests/fixtures, and over each directory of committed captures, is byte-identical to the one before. MANIFEST.md's HSRP note states the gap.docs/CLAIMS.md's counts are unchanged:HSRPv2keeps its one strategy. -
The HSRPv2 guard was re-measured with the Interface State TLV's Length judged (#357). With
scripts/measure_port_guard.py --port 1985 --count HSRP --count HSRPv2 --count HSRPAdvertiseand--port 2029 --count HSRPv2, each with and without--one-generator, the output on this tree and on the tree before it (91689bc) is identical but for the line naming the tree: to port 1985, 89,998 of the 90,000 one-generator walks ended withstopped_byset and the same 2 (seed 2's 46-byte payload, unpadded and padded) decoded HSRP, and all 90,000 reseeded ones did; to port 2029, every walk of both draws ended withstopped_byset; none decoded HSRPv2 or HSRPAdvertise. With the Group State TLV's eight judged bytes forced to values they accept (random.Random(0), as #280 measured),HSRPv2.decode()accepted 628 of 100,000 random 300-byte payloads where the tree before accepted 636: 95,760 were turned away for a TLV whose Length runs past the datagram (96,387 before), 1,030 for a Type byte with no Length (1,036), 2,579 for a Group State, Interface State, Text Authentication or MD5 Authentication TLV of another Length (613, 645, 690 and 631; before, 1,938 without the Interface State TLV) and 3 for a later Group State TLV's Version (3). ARCHITECTURE.md states both figures and names the Interface State TLV among the TLVs whose Length the walk judges. -
The HSRPv1 MD5 Authentication TLV is tested against hand-built vectors, with no capture (#282). No sender of the TLV runs in a Linux netns: Yersinia 0.8.2 cannot send it, there is no open-source HSRP daemon, and the crafters that could write one are scapy- or dpkt-based, which this project does not use. The new
tests/test_hsrp_md5.pytherefore packs five 50-byte messages field by field withstructandsocket, each labelled hand-built, cross-checked against packet-hsrp.c at commit 6f7207a6 (the TLV's diagram, lines 100-121; its reading, lines 320-344; the field widths, lines 787-815; the Algorithm's name, lines 313-317; the 50-byte rule, lines 444-459): an Active and a Standby Hello, a Coup, a Resign with Key ID 2^32 - 1 and an all-zero digest, and one with a distinct value in every field (Algorithm 0x77, Padding 0x5a, Flags 0xabcd, sender 198.51.100.9, Key ID 0x01020304). packet-hsrp.c was fetched at 6f7207a6 (SHA-256b09e0dc1521e1b24e5be80efc8c901d26b4c0be3798464661dd80152fb780a39) and the cited lines read against the tests, the TLV looked for at byte 20 (offset + 4past the Virtual IP Address's offset 16) of a buffer whose captured length is exactly 50, and read only for Type 4 and Length 28, anything else reported as "Unknown TLV sequence in HSRPv1 dissection" without failing the message. tshark 4.2.2 (Ubuntu's 4.2.2-1.1build3) then decoded every hand-built MD5 vector, written withstructalone into a temporary pcap outsidetests/fixturesas an Ethernet/IPv4 frame from 192.0.2.11 to 224.0.0.2 on UDP 1985 (tshark -r <pcap> -V -O hsrp): the fiveVECTORSoftests/test_hsrp_md5.py,tests/conftest.py'sraw_hsrp_md5_hello,tests/test_check_fixtures.py'sHSRP_MD5,tests/test_hsrp.py'sHELLOwithMD5_TLVandtests/test_fuzz.py's first seed message with_HSRP_MD5_TLV. Each frame's IPv4 and UDP checksums were Good, and for each of the nine tshark showed an "MD5 Authentication TLV: Type=4 Len=28" whose Algorithm, Padding, Flags, Sender's IP Address, Key ID and MD5 Authentication Data equal theHSRP.md5_authenticationthis library decodes from the same bytes: Algorithm "MD5 (1)", Padding 0x00 and Flags 0 for eight, with Key IDs 1, 1, 7, 4294967295, 1, 1, 1 and 1 and senders 192.0.2.11, 192.0.2.12 or 10.9.195.11 (HSRP_MD5), and fordistinctAlgorithm "Unknown (119)", Padding 0x5a, Flags 43981, sender 198.51.100.9 and Key ID 16909060. For the negative cases, built fromactive_hello, tshark decoded no MD5 Authentication TLV, asHSRP.decode()leaves each at its 20 bytes: in 50 bytes with Type 4 and Length 27, and with Type 0 and Length 28, it reported "Unknown TLV sequence in HSRPv1 dissection, Type=(4) Len=(27)" and "Type=(0) Len=(28)", and a 49-byte message (UDP Length 57) and a 51-byte one (UDP Length 59) it showed as a plain HSRPv1 Hello with no TLV and no expert note. The file covers every length from 0 to 51 bytes, every Type but 4 and every Length but 28, that nothing in the TLV is judged and the guard still judges the first 20 bytes,memoryviewinput, the walk (an FCS after the frame is the trailer; a UDP Length of 49 leaves the TLV outside; a Length of 50 bounds a 51-byte payload), the record shared withHSRPv2, construction, equality, the hash, positional patterns and the checker.tests/test_contract.py's case asserting that a walk left the TLV outsideHSRP(md5-tlvoftest_hsrp_leaves_what_follows_its_message) is replaced bytest_an_hsrp_md5_authentication_tlv_round_trips, which walks a 50-byte message to one 50-byte layer and back byte for byte, strict and lax, andtest_an_hsrp_md5_message_leaves_an_fcs_after_it;test_hsrp_leaves_what_follows_its_messagekeeps its FCS and padding cases and adds a 30-byte TLV of Type 0 and one of Type 4 and Length 27 in a 50-byte buffer and Type 4, Length 28 in 49- and 51-byte buffers, each left outside.tests/test_hsrp.py's walk test now expects the TLV decoded, and its cases that appended the TLV to a message (a direct decode and a checker length case) now append it with an FCS, cut it to 29 bytes or add a 51st byte; the capture tests are untouched.tests/strategies.py'shsrp_messages()draws a message with or without an MD5 TLV,tests/test_fuzz.py's HSRP seeds append the TLV half the time with its Type and Length now and then redrawn, its accessor test checks the 50-byte rule,md5_authenticationjoins_HSRP_ACCESSORS, and a new property checks that a message built with any TLV round-trips throughbytesandmemoryview.tests/conftest.pygainsraw_hsrp_md5_hello, whichtests/test_contract.py's truncation test also cuts. The digest is not verified, by the tests or byscripts/check_fixtures.py: no sender available here computes it the way IOS does, and its coverage has no primary source. MANIFEST.md's HSRP note states the gap.CONTRIBUTING.md's example of a reference to an inherited member namesHSRPAdvertise.header_len, sinceHSRPnow defines its own.docs/CLAIMS.md's counts are unchanged:HSRPkeeps its one strategy. -
scripts/check_fixtures.pychecks the MD5 Authentication TLV of a 50-byte HSRPv1 message (#282)._check_hsrpaccepts a message of 20 or 50 bytes, any other length still failinghsrp-length, judges a 50-byte message's first 20 bytes as before and then, in the new_check_hsrp_md5, its last 30 as packet-hsrp.c reads them: Type 4 (hsrp-md5-type), Length 28 (hsrp-md5-length), Algorithm 1, MD5, the one packet-hsrp.c names (hsrp-md5-algorithm), and the Padding byte zero, as packet-hsrp.c describes it (hsrp-md5-padding). Each such message counts ashsrp-md5. The digest is not verified.tests/test_check_fixtures.pyhas a case for each new failure string and for a 49- and a 51-byte message'shsrp-length, on hand-built frames, andtests/test_hsrp_md5.pychecks that its vectors pass and count. The corpus holds no such message, and the checker's report overtests/fixtures, and over each directory of committed captures, is byte-identical to the one before. -
The port 1985 guard was re-measured with the MD5 Authentication TLV decoded (#282). With
scripts/measure_port_guard.py --port 1985 --count HSRP --count HSRPv2 --count HSRPAdvertise, with and without--one-generator, the output on this tree and on the tree before it (9da02d7) is identical: with it, 89,998 of the 90,000 walks ended withstopped_byset and the same 2 (seed 2's 46-byte payload, unpadded and padded) decoded HSRP; without it, all 90,000 did; none decoded HSRPv2 or HSRPAdvertise. The TLV changes how much of an accepted payloadHSRPholds, not which payloads it accepts, so ARCHITECTURE.md's figures stand; it gains a sentence saying so and its module tree names the TLV. -
The HSRP Advertise is tested against hand-built vectors, with no capture (#281). No sender of the Advertise runs in a Linux netns: Yersinia 0.8.2 builds HSRPv1 Hello, Coup and Resign only, there is no open-source HSRP daemon, and the crafters that could write one are scapy- or dpkt-based, which this project does not use.
tests/test_hsrp_advertise.pytherefore packs its messages field by field withstruct, each labelled hand-built, cross-checked field by field against packet-hsrp.c at commit 6f7207a6 (the diagram, lines 27-37, and the counts' range, lines 39-47; the Op Code, TLV Type and State names, lines 235-240, 260-266 and 268-275; the State read at byte 6, lines 382-385; the fields read, lines 425-439; their widths, lines 662-695). tshark 4.2.2 (Ubuntu's 4.2.2-1.1build3), whose packet-hsrp.c differs from 6f7207a6's in nothing the Advertise reads (#280's comparison), decodes all four of itsVECTORS, wrapped in Ethernet/IPv4 from 192.0.2.11 to 224.0.0.2 with TTL 1 on UDP 1985, as HSRP Advertise messages with good IPv4 and UDP checksums and the fields the tests expect: "Advertise (state Passive)", Adv type "HSRP interface state (1)", Adv length 14, 1 active and 0 passive groups; Dormant, 0 and 3; Active, 256 and 256; and "IP redundancy (2)", Active, 2 and 1, every Reserved field 0; and a fifth frame with a distinct value in every field (TLV Type 2, TLV Length 2571, State 3, reserved1 12, 3342 active, 3856 passive, reserved2 286397204) at the offsets and widths the tests give. packet-hsrp.c gives no value for the TLV Length; the vectors use 14, the bytes from the TLV Type to the end. The file covers every truncation, every judged field at any length (the TLV Type once both its bytes are there, and a nonzero high byte of it alone), exactly which values pass, the fields not judged, construction at every width, the display helpers, and dispatch through Ethernet/IPv4/UDP 1985: every one of the 65,536 two-byte leads,decode_as, a short or failing Advertise in a walk, a one-byte datagram, and a UDP Length of 9 whose payload's00is followed by03past the Length, which stays HSRP's.tests/test_udp.pycovers the new_leadfor every Length and buffer length,bytesandmemoryview, and that it is neither compared, hashed nor shown.tests/strategies.pygainshsrp_advertisements()for the round trip,tests/test_fuzz.pyaddsHSRPAdvertisetoALL_PROTOCOLSand aTestHSRPAdvertiseAccessorSafety, andtests/test_contract.pytruncatestests/conftest.py's newraw_hsrp_advertiseand checks that a walk started atHSRPAdvertiseleaves an FCS, zeros or an MD5 TLV after it. Tests that called_for_payload()with a first byte (tests/test_ntp_control.py,tests/test_hsrpv2.py,tests/test_fuzz.py) now pass the two-byte integer, andtests/test_ntp_control.pychecks_leadagainst the request's first two bytes. Five tests oftests/test_hsrp.pythat walked or checked an Op Code 3 message as one HSRP rejects (a strict and a lax walk, a changed-byte check, the first-failure order and the counters) now use Op Code 4, whichHSRPstill rejects, and its direct-decode test of the Advertise checks the new message; the capture tests are untouched. MANIFEST.md's HSRP note states the gap.docs/CLAIMS.md§5.2 counts the round trips Hypothesis generates for 45 protocols, 41 of them throughROUND_TRIP_STRATEGIES,HSRPAdvertisethe 41st. -
scripts/check_fixtures.pychecks HSRP Advertise messages (#281). A UDP payload on port 1985 that opens with00 03is read by the new_check_hsrp_advertise: exactly 16 bytes (hsrp-advertise-length), from and to port 1985 (hsrp-advertise-port), a TLV Type of 1 or 2 (hsrp-advertise-type), a State of 1-3 (hsrp-advertise-state), active and passive group counts of at most 256 each, packet-hsrp.c's range (hsrp-advertise-groups), and, as this corpus's convention, as for HSRPv1's Reserved byte, both Reserved fields zero (hsrp-advertise-reserved); the TLV Length is not judged. Each counts ashsrpandhsrp-advertise. A 20-byte message with Op Code 3 is therefore an Advertise of the wrong length (hsrp-advertise-length) where it failedhsrp-op-code.tests/test_check_fixtures.pyhas a case for each new failure string, on hand-built frames, itshsrp-op-codecase now setting the Op Code to 4, and a test that an Advertise passes and counts. The corpus holds no Advertise, and the checker's report overtests/fixtures, and over each directory of committed captures, is byte-identical to the one before. -
The port 1985 guard was re-measured with
HSRPAdvertisein the walk (#281). Withscripts/measure_port_guard.py --port 1985 --count HSRP --count HSRPv2 --count HSRPAdvertise --one-generator, on this tree and on the tree before it (d9d500c) alike, 89,998 of the 90,000 walks ended withstopped_byset (100.00% for each set and seed but seed 2's 0-600 byte ones, 99.99% unpadded and padded), the same 2 decoded HSRP and none HSRPv2 or HSRPAdvertise; without--one-generator, every one of the 90,000 walks ended withstopped_byset on both trees, none decoding any of the three. The output of both runs is identical between the trees but for its first line. One payload of each 90,000, the same 300-byte payload of seed 2 in both draws, opens with00 03: the tree before rejected it atHSRP'sopcode, this one atHSRPAdvertise'stlv_type. With the Version and Op Code forced to 0 and 3 (random.Random(0)),HSRPAdvertise.decode()rejected all of 100,000 random 300-byte payloads, 99,999 attlv_typeand 1 atstate, where 2/65,536 x 3/256 predicts 0.04 acceptances; with all four judged fields forced to values they accept, it accepted all 100,000, since nothing after them is judged. ARCHITECTURE.md states both trees' figures, places the Advertise's guard between STUN's and HSRPv2's, and reflows the HSRPv2 paragraph, which now says "the tree that added it" for that tree. -
UDP.decode()was benchmarked against the tree before (d9d500c), interleaved (#281). On the 161 corpus frames that carry a UDP layer, 12 alternating runs of each tree, each pinned withtaskset -c 2and taking the best of 7 repetitions per measure (load average under 0.6):UDP.decode()alone took 591 ns per header on this tree against 628 ns (best; medians 598 and 644), -6%, and 594 against 638 ns on amemoryview(-7%);UDP.decode()andnext_protocol()together 753 against 779 ns (-3%); a wholedecode_frame(lax=True)walk of those frames 6.97 against 6.93 µs per frame (best; medians 7.32 and 7.24), +0.6-1.0%, within the runs' spread. In one process, the two trees'UDPclasses loaded side by side and alternated 20 times on a 48-byte datagram, gave 575-583 ns against 624-634 ns over three runs. The variants rejected above were measured the same way, in one process against the tree before's 631 ns: two index reads and a shift 678 ns, and abytesslice (in a model of the decode, about 80 ns over it). -
HSRPv2 is tested against hand-built vectors, with no capture (#280). No sender of HSRPv2 runs in a Linux netns: Yersinia 0.8.2 builds HSRPv1 only, there is no open-source HSRP daemon, and the crafters that could write one are scapy- or dpkt-based, which this project does not use.
tests/test_hsrpv2.pytherefore packs its messages field by field withstructandsocket, each labelled hand-built, cross-checked field by field against packet-hsrp.c at commit 6f7207a6 (the Group State TLV's diagram, lines 53-78, and its reading, lines 479-543; the Text Authentication TLV's, lines 89-98 and 565-587; the MD5 Authentication TLV's, lines 100-119 and 319-344; the walk, lines 474-601). tshark 4.2.2 (Ubuntu's 4.2.2-1.1build3) dissects the same layout: packet-hsrp.c at Wireshark's tag v4.2.2 differs from 6f7207a6's only in C type names (ginttoint,gchartochar,tvb_get_guint8totvb_get_uint8), the= -1initialisers of itsproto_,hf_andett_variables and theEI_INITof its expert field, which 6f7207a6's drops, whitespace, onecol_add_fstrturnedcol_set_strand the display length of the Interface State and MD5 Authentication TLV items, which 6f7207a6 itself changed, its line numbers unchanged; it decodes all five of itsVECTORS, wrapped in Ethernet/IPv4 to 224.0.0.102 on UDP 1985 or Ethernet/IPv6 to ff02::66 on UDP 2029, as HSRPv2 with good UDP checksums and the fields the tests expect: an IPv4 Hello in Active, group 1, priority 100, Hellotime and Holdtime "Default (3000)" and "Default (10000)", virtual IP 192.0.2.1, with a Text Authentication TLV "Default (cisco)"; an IPv4 Coup in Speak, group 4095, priority 200, 1000 and 3000 ms, 198.51.100.7, with an MD5 Authentication TLV (MD5 (1), padding 0x00, flags 0, 192.0.2.11, key ID 1, digest 000102...0f); an IPv4 Resign in Active, group 0, with an Interface State TLV (1 active group, 0 passive); and two IPv6 Hellos, in Standby, group 10, with a Text Authentication TLV, and in Active, group 1, both virtual IPv6 address fe80::5:73ff:fea0:1. The file covers every truncation, every judged byte at any length, every malformed TLV (a Type without its Length, a Length past the buffer, a typed TLV of another Length, a later Group State TLV that fails), construction, the display helpers and dispatch through Ethernet/IPv4/UDP 1985 and Ethernet/IPv6/UDP 2029.tests/strategies.pygainshsrpv2_messages()(andhsrpv2_group_states(),hsrpv2_md5_authentications()) for the round trip,tests/test_fuzz.pyaddsHSRPv2toALL_PROTOCOLSand aTestHSRPv2AccessorSafety, andtests/test_contract.pytruncatestests/conftest.py's newraw_hsrpv2_hello. Six tests oftests/test_hsrp.pythat walked or checked an HSRPv2 message as HSRPv1 now use a first byte of 2, whichHSRPstill rejects; the capture tests are untouched. MANIFEST.md's HSRP note states the gap.docs/CLAIMS.md§5.2 counts the round trips Hypothesis generates for 44 protocols, 40 of them throughROUND_TRIP_STRATEGIES,NTPControlandHSRPv2among them. -
scripts/check_fixtures.pychecks HSRPv2 messages (#280). A UDP payload on port 2029, or on port 1985 whose first byte is 1, is read by the new_check_hsrpv2: from and to port 1985 over IPv4 and 2029 over IPv6 (hsrpv2-port), whole TLVs (hsrpv2-tlv), the first a Group State TLV (hsrpv2-group-state), each Group State, Interface State, Text Authentication and MD5 Authentication TLV of the length packet-hsrp.c reads (hsrpv2-tlv-length), and in each Group State TLV Version 2 (hsrpv2-version), an Op Code of 0-2 (hsrpv2-op-code), a State of 0-6 (hsrpv2-state), the IP Version of the IP header (hsrpv2-ip-version), a Group of at most 4095 (hsrpv2-group) and in a Hello a Holdtime above the Hellotime (hsrpv2-holdtime), and, as this corpus's conventions, 12 zero bytes after an IPv4 virtual address (hsrpv2-padding) and clear-text Text Authentication data (hsrpv2-auth-data). Port 2029 joins the ports never read as RADIUS.tests/test_check_fixtures.pyhas a case for each new failure string, on hand-built frames; itshsrp-versioncase now sets the Version to 2, since 1 is HSRPv2's. The corpus holds no HSRPv2, and the checker's report overtests/fixturesis byte-identical to the one before. -
The port 1985 guard was re-measured with
HSRPv2in the walk, and port 2029's measured (#280).scripts/measure_port_guard.pygains--port(default 123),--count NAME, repeatable (defaultNTPControl), and--one-generator, which draws the 0-600 byte payloads from the generator that drew the 300-byte ones rather than from a reseeded one; with none of them its output is unchanged (re-run: 61.14-62.88% and 65.44-66.32% on port 123, as ARCHITECTURE.md states). The HSRPv1 figures of ARCHITECTURE.md were taken with that one-generator draw, though its paragraph said they were measured as NTP's, whose 0-600 byte payloads come from a reseeded generator: with the reseeded draw no payload of the 90,000 decodes as HSRP, and with--one-generatorthe 46-byte payload of seed 2 that the paragraph names decodes, unpadded and padded. The HSRPv1 paragraph now namesscripts/measure_port_guard.py --port 1985 --count HSRP --one-generatorand its draw, and the figures are unchanged. With--one-generator --port 1985 --count HSRP --count HSRPv2, on this tree and on the tree before it (93b0ab2) alike, 89,998 of the 90,000 walks to port 1985 ended withstopped_byset (100.00% for each set and seed but seed 2's 0-600 byte ones, 99.99% unpadded and padded), the same 2 decoded HSRP and none HSRPv2. To port 2029 every one of the 90,000 walks ended withstopped_byset on this tree and none decoded HSRPv2, where on the tree before, which registers nothing there, every walk ended at UDP with none set (0.00%); the reseeded draw gives the same on both ports, but for the 2 HSRP decodes. The Group State TLV's judged bytes let through about 2.6 random values in 2^48 (1 x 1 x 1 x 3 x 7 x 2 of the first six bytes' 2^48 values and 4,096 of the 65,536 Groups), and with them forced to values they accept (random.Random(0), Op Code, State, IP Version and Group drawn uniformly from those)HSRPv2.decode()accepted 636 of 100,000 random 300-byte payloads: 96,387 were turned away for a TLV whose Length runs past the datagram, 1,036 for a Type byte with no Length, 1,938 for a Group State, Text Authentication or MD5 Authentication TLV of another Length and 3 for a later Group State TLV's Version. ARCHITECTURE.md states both trees' figures and places HSRPv2's guard between STUN's and BGP's. -
Tests for the MST BPDU decode (#299).
tests/test_stp.pychecks each ofstp.pcap's ten MST BPDUs field by field against an independentstructdecode of the captured bytes and against the topologyscripts/capture_fixtures_stp.shsets up (regionNETProtocols, revision 7, the digest recomputed as 802.1Q §13.8's HMAC-MD5 of the VID-to-MSTID table, MSTIDs 1 and 2, the senders' CIST Bridge Identifiers, MSTI Bridge and Port Priorities, Internal Root Path Costs 0 and 2000, Remaining Hops 20 and 19, and, once forwarding, the Regional Roots), with walks, round trips, padding and FCS trailers and every cut;stp.pcap's RST, Configuration and TCN BPDUs answerNonefrom every MST accessor. Every validation failure (an earlier version, a nonzero Version 1 Length, a Version 3 Length below 64, not 64 plus a multiple of 16, over 64 MSTIs, or past the buffer, an 802.3 Length cutting the PDU) is built from the captured BPDU, as are the two Wireshark-noted encodings, which are hand-built since none was captured: a Version 3 Length of 2 (the C3550's MSTI count), and a 155-octet BPDU in Wireshark's alternative format (Version 3 Length 0, format selector 116, the BPDU's length less 39, aspacket-bpdu.crequires, and the two captured MSTI messages re-laid as 26-octet ones), which tshark 4.2.2 decodes in that format, MSTIDs 1 and 2 included. The CIST aliases are checked against astructdecode of each MST BPDU's prefix and against the topology (A the CIST Regional Root, B in B's first BPDU, External Root Path Cost 0), and answerNonefor the RST, Configuration and TCN BPDUs and every MST BPDU failing validation; a hand-built MST BPDU with CIST Port Role 0 names it Master, and the same BPDU failing validation names it Unknown.tests/strategies.pydraws MST parts from the two records forstp_headers(), the round-trip strategy, andtests/test_fuzz.pyseeds its BPDU fuzzing withstp.pcap, redraws the version and the Version 3 Length, reads every MST accessor and record accessor, and round-trips MST parts built from records, decoded directly and in a walk.tests/strategies.pydraws an RST BPDU's Version 1 Length from 0 to 255, 0 more often than any other value. -
stp.pcap, a real capture of MST, RST and 802.1D BPDUs, andscripts/capture_fixtures_stp.sh, which produces it (#299). mstpd 0.2.0, built from its upstream tag (commit8995e5d), runs the STP of four Linux bridges: A and B, MSTP bridges in one region (NameNETProtocols, Revision Level 7, MSTIs 1 and 2), C forced to RSTP and D to 802.1D. The 17 frames are the first of each kind seen on B's three ports as the links come up in turn: 10 MST BPDUs (Version 3 Length 96, two MSTI messages each), 2 RST BPDUs from C, 4 Configuration BPDUs and 1 Topology Change Notification. The script runs in the initial network namespace, since the kernel hands a bridge's STP to userspace only there, through/sbin/bridge-stp; it installs a temporary helper of its own that claims only itsnpmstp-*bridges, refuses to run if another helper, a running mstpd or annpmstp-*link exists, and removes everything it created on exit. It asserts every frame, the MST Configuration Digest recomputed as 802.1Q §13.8's HMAC-MD5, and tshark's reading of each; three runs gave byte-identical selections. Its Hello Time is 2 s, the only Bridge Hello Time mstpd 0.2.0 accepts. MANIFEST.md, the README and CLAIMS.md count 509 frames across 43 scenarios. -
radius_coa.pcap, a real RADIUS Dynamic Authorization capture (RFC 5176), andscripts/capture_fixtures_radius_coa.sh, which produces it (#337). FreeRADIUS 3.2.5 in netnsnpcoa-slistens as a NAS on UDP 3799 (listen { type = coa }) and answers radclient 3.2.5 in netnsnpcoa-c, on a veth pair in 10.9.237.0/24: a CoA-Request and a Disconnect-Request for the session it holds, each with a Message-Authenticator, are answered by a CoA-ACK and a Disconnect-ACK with one, and the same two requests for a session it does not hold, without one, by a CoA-NAK and a Disconnect-NAK carrying Error-Cause 503 (Session-Context-Not-Found). The script asserts all eight frames;check_fixtures.pyverifies every Request and Response Authenticator and Message-Authenticator with radius.pcap's published secret, andtests/test_radius.pydecodes the capture withdecode_as={"udp.port": {3799: RADIUS}}, round-trips it and verifies them independently. MANIFEST.md, the README and CLAIMS.md count 492 frames across 42 scenarios. -
tests/fixtures/ntp_control.pcap: 21 NTP control messages captured between ntpq and ntpd (#272). The newscripts/capture_fixtures_ntp_control.shruns an ntpsec 1.2.2 ntpd (disable ntp,disable kernel, the LOCAL refclock and an unreachable server, so two associations) in netnsnp272-sat 10.9.172.1 and ntpq innp272-cat 10.9.172.2, over a veth pair on 10.9.172.0/24, and captures seven ntpq runs:rv,as,rv 0 version,rv 0 nosuchvar(an error response, code 5),rv &1(a response in two fragments, the first with the M bit set and 468 bytes of data), and:configauthenticated with MD5 key 3 and SHA-1 key 4 (the second refused with error code 1 and a MAC right after the 12-byte header). The script keeps every mode 6 datagram, asserts the selection by sender, opcode, R/E/M bits and MAC length, verifies every MAC, and checks the headers against ntpq's own output during the run; the test keys are published in MANIFEST.md.scripts/check_fixtures.pyreads a mode 6 message on port 123 with the new_check_ntp_control(): the Count must fit the datagram (ntp-control-truncated), the data be padded to 4 bytes or followed by a 20- or 24-byte MAC after the data padded to 8 bytes, or, in an error response, to 4 bytes, whereNTPControl.decode()looks for it (ntp-control-trailer), and the MAC verify with a published key (ntp-control-unknown-key,ntp-control-md5,ntp-control-sha1), counted asntp-control,ntp-control-md5andntp-control-sha1; the report of every other capture is unchanged.tests/test_check_fixtures.pygains a case for each new failure string, andtests/test_ntp_control.pychecks every captured header against an independentstructread and ntpq's output, the padding, every MAC and the fragments, and checkssystem_statuson hand-built trap responses (opcode 7): a system trap, a peer trap and an error response. The fuzz seeds forNTPControlgain the captured messages. -
The port 123 guard's rejection rate was re-measured with
NTPControlin the walk, by the newscripts/measure_port_guard.py(#272). The script follows 2.7.0's method (ARCHITECTURE.md's:random.Randomseeds 0-2, per seed 10,000 random 300-byte payloads and, from the generator seeded again, 10,000 of uniformly random length 0-600, the latter walked unpadded and padded,decode_frame(..., lax=True)over Ethernet/IPv4/UDP to port 123, counting walks that end withstopped_byset). On this tree the walk stopped for 61.14-62.88% of the 300-byte payloads and 65.44-66.32% of the 0-600 byte ones, padded or not, against 61.15-62.90% and 65.45-66.34% on the tree before it (9654670), which 2.7.0's 61.2-62.9% and 65.5-66.3% round; 1 or 2 payloads of each 10,000 now decode asNTPControl, as the 16 mode 6 first bytes, and a Count that fits, predict (62.5% less 16/256 x 289/65,536 for a 300-byte payload, about 62.47%). ARCHITECTURE.md states both trees' figures. -
Tests for the typed OSPF LSA bodies (#298).
tests/test_ospf.pydecodes every LSA body ofospf.pcap(types 1, 2 and 5) andospf_areas.pcap(types 1, 2, 3, 4, 5 and 7) to hardcoded records, taken forospf_areas.pcapfromospf_areas_lsdb.txtand held to it field by field (Router-LSA flags and links, the network masks of every type, the type-4 mask included, attached routers, metrics, metric type, forwarding address, tag), and forospf.pcap, which has no recorded database, from its script's configuration; both captures are also checked against astructhand-decode. It covers every framing failure (a link count past the body, a partial link, TOS entries past the body, bytes after the links, partial entries of the other types, a type-4 body past its 8 fixed bytes but short of a TOS entry) at construction and at decode with its offset, the frame offset in a walk, a hostile link count,replace(), the accessors of the wrong types, the raw bodies of the others, and an AS-external TOS of 127 encoding while 128, 255 and -1 raise.tests/strategies.pybuilds framed bodies for LS types 1-5 and 7 from the new records, andtests/test_fuzz.pyreads every body accessor of every LSA it walks, round-trips drawn records throughOSPFLSA, and constructs LSAs from free bytes, which raise onlyInvalidFieldError. The tests' default LSA header is an opaque LSA (type 9), whose body any bytes construct, andtests/test_checksum.py's Fletcher tests build type 9 LSAs, with bodies chosen again for the same properties (010203dbgenerating0x63ff,3e000700generating0xffff). -
ospf_areas.pcap, a real OSPFv2 capture across three areas, andscripts/capture_fixtures_ospf_areas.sh, which produces it (#298). Four FRR 8.4 routers in netnsnpospfar-atonpospfar-d, on three veth pairs in 10.9.84.0/24: B (10.0.0.2) is the area border router of area 0 (with A), area 0.0.0.1 (with C, an AS boundary router redistributing 192.0.2.3/32) and NSSA area 0.0.0.2 (with D, redistributing 192.0.2.4/32 as an NSSA-LSA, which B translates). The 52 frames are two adjacencies captured in turn on B's side, D's in area 0.0.0.2 and then A's in area 0, and their Link State Updates carry 23 LSAs of LS types 1, 2, 3, 4, 5 and 7, so Summary-LSAs, an ASBR-summary-LSA and NSSA-LSAs come from real traffic. The script asserts every frame and the exact set of LSAs in each segment, and records FRR's link-state database at the end of each segment intoospf_areas_lsdb.txt, folded in beside the pcap;tests/test_ospf.pypins the composition, round-trips every packet, verifies every LSA checksum and finds every LSA header, Options included, in that database but the three earlier instances it no longer holds.ospf.pcapand its script are unchanged. MANIFEST.md and the README count 463 frames across 40 scenarios. -
tests/fixtures/radius.pcapwas re-captured with Vendor-Specific attributes (#275).scripts/capture_fixtures_radius.shnow has radclient send a Cisco (vendor 9) Cisco-AVPair in each Access-Request, a USR (vendor 429) USR-Connect-Speed in the Accounting-Request Start and a Microsoft (vendor 311) MS-Acct-Auth-Type in the Stop, and the user entry gives each Access-Accept a Cisco-AVPair and a WISPr (vendor 14122) WISPr-Bandwidth-Max-Down; FreeRADIUS 3.2.5 encodes USR's in dictionary.usr'sformat=4,0(a 4-byte Vendor-Type, no Vendor-Length), so the corpus holds a real Vendor-Specific in a format other than RFC 2865 §5.26's recommended one. The script asserts the Vendor-Id of every Vendor-Specific in each frame along with the attribute types, and reads its two namespace/interface pairs withreadinstead of an unquotedset --, so shellcheck passes. The capture is still twelve frames in the same order; the Identifiers, Request Authenticators, every authenticator and Message-Authenticator, the IPv4 identifications, the lengths of the Access-Requests (115 and 116 bytes, from 80 and 81), Access-Accepts (98, from 61) and Accounting-Requests (82 and 116, from 68 and 104) and the timestamps changed, andtests/test_radius.pyfollows the PAP Access-Request's new length and asserts every Vendor-Specific of the capture, read withstruct.scripts/check_fixtures.py's report is unchanged: it verifies the same 12 RADIUS frames, 2 Accounting-Request authenticators, 4 request and 4 reply Message-Authenticators and 6 Response Authenticators.tests/fixtures/MANIFEST.mddescribes the new attributes. -
RELEASE.mddocuments the release procedure, from the preconditions to the post-release checks, and Rule 4 ofdocs/CLAIMS.mdsays what a figure that is not re-measured needs. RELEASE.md is derived from how 2.9.0 was released and from the rules decided after it: the preconditions (milestone, open PRs dependabot's included, a cleanmaster, no tag, the previous version), therelease-X.Y.Zbranch, the re-measurement under the amended Rule 4 with the commands of the latest "Re-measured for" section ofdocs/CLAIMS.md, and the quiet-machine convention those sections record, not Rule 4 (a one-minute load average under 1.0 since 2.9.0, andtaskset -c 2, chosen as a performance core of the i7-1355U measured on so far, which another machine replaces with its own choice), the singlechore(release): X.Y.Zcommit and the wheel size measured from it, and measured again from the commit to be tagged when that is a latermastercommit, the QA ladder with bandit pinned to 1.9.4 and the fixture check failing as CI's does, the PR merged with a merge commit after all of CI, two conventions themasterruleset does not enforce, bounded waits for each dispatched or tag-triggered run, the fuzz and mutation gates dispatched onmaster, tagging themastercommit those gates ran on, what eachrelease.ymlstage guarantees, the retagging rule (a tag is moved or re-pushed only when norelease.ymlrun for it uploaded anything; once anything is published, the fix goes into the next patch release, and a deletion on PyPI never re-opens retagging) and the guard that blocks the retag commands unless PyPI answers 404 for the version and everyrelease.ymlrun for the tag is completed with every job completed, lists apublishjob (or, having failed, lists no jobs at all), has no job of any attempt with an upload step that was not skipped, and has nopublishjob that ran without listing an upload step, the upload step being matched by its normalized name, whichrelease.ymlnow sets to "Publish to PyPI" (tested against 2.9.0's, 2.3.0's and 1.0.0's runs), what PyPI accepts on a re-upload (a byte-identical file silently, a reused name with other contents never, even after deletion, and a missing file only within 14 days of the release's creation), that the unpinned hatchling build requirement can make a rebuild differ from the files on PyPI, which PyPI then refuses, and the post-release checks. Rule 4 now says that each figure is either re-measured, or explicitly marked as not repeated for that release with the version it was last measured in, and never carried over silently. RELEASE.md and CONTRIBUTING's "Mutation testing" section document the mutation audit's scope, which stays aspyproject.tomlsets it: a test meant to kill mutants of an audited module lives in that module's audited test file, and the author of a PR that changes an audited module runs the audit by hand, a convention, sincemutation.ymlhas nopull_requesttrigger and CI does not run the audit on a PR. A change merged to get a release's gates green before its tag, or before a permitted retag, goes into that release's CHANGELOG section. #347's entry moves to 2.9.0's### Developmentand now says that its mutation run was dispatched on the release PR's merge commit before the tag, not run after the release. The move was made afterv2.9.0was tagged and released: the tag'sCHANGELOG.mdstill has the entry under## [Unreleased], and the GitHub release notes, taken from the tag's## [2.9.0]section, do not contain it. The published release is not edited. Another convention GitHub does not enforce is recorded: at most 3 pull requests are open at once. CONTRIBUTING's "Releasing" section points to RELEASE.md, its "Changelog" and "Pull requests" sections state the CHANGELOG rule, the merge conventions and the open-PR cap, the comments infuzz.ymlandmutation.ymlno longer point to CONTRIBUTING's release checklist, anddocs-lint.ymlchecks RELEASE.md's links.
-
netprotocols.registry.WITHHELD, a typed way to opt a key out of dispatch.WITHHELD, the only member of the newWithheldTypeenum, stands in for a class wherever one is registered: indecode_as(decode_frame(frame, decode_as={"udp.port": {1812: WITHHELD}})withholds the key for that walk alone), inRegistry.derive(), and inRegistry.register(),register()andregister_all()on a global or isolated registry. A withheld key dispatches to nothing, exactly as a key that was never registered: the walk ends at the header that named it with its payload undecoded, and a port table still tries the other port of the pair. A withhold in a parent table reaches the children that inherit the key (ip.protointoip.proto.v6), as a registration does. Withholding stays idempotent and never undoes a class registered directly in the same table unlessoverride=Trueis passed;decode_asandderive()always pass it, so a per-walkWITHHELDbeats a global entry and a per-walk class beats a global withhold, for that walk only, and a class registered later fills a withheld key withoutoverride.decode_frame()'sdecode_asandderive()'soverridesare typedMapping[str, Mapping[int, type[Protocol] | WithheldType]], so these call sites passmypy --strict, whichtests/typecheck/withheld.py, now in mypy'sfiles, holds them to. The defaults' IPv6 withhold of protocol 89 (OSPF) now goes through the public path, and the privateRegistry._withhold()andRegistry._withheldare gone: a withheld key is stored asWITHHELDamong the table's own entries.WITHHELDandWithheldTypeare exported fromnetprotocols.registry, not from the top-level package, like the table-name constants. The registry module docstring, README and ARCHITECTURE describe it (#271). -
Packet.trailer, the frame's bytes past its declared lengths.decode_frame()ends every later layer's buffer at the tightest end the enclosing headers declare: an 802.3 Length after Ethernet or VLAN, an IPv4 Total Length (total_length - ihl * 4after the header), an IPv6 Payload Length (payload_length, extension headers included) and a UDP Length (length - 8). The bytes past that end arePacket.trailer, abytescopy,b""when no declared end falls short of the frame; a nested encapsulation (VXLAN, GRE, IP in IP) gives one combined trailer, and an ICMP error'sembedded_chainis bounded the same way.bytes(packet)andconsumedexclude the trailer, so a walked frame isbytes(packet) + frame[packet.consumed : len(frame) - len(packet.trailer)] + packet.trailer, and the BGP, STUN and TLS continuation walks run overframe[packet.consumed : len(frame) - len(packet.trailer)].Packet()takes it as the keyword-onlytrailerargument, abytes,bytearrayormemoryview, stored asbytes; equality and hashing include it,repr()shows it only when it is non-empty, andwith_checksums()carries it over, GRE's checksum input running on into it as far as GRE's own datagram ends. A declared end past the captured frame bounds nothing, so a frame cut by a snap length decodes as before; an IPv4 Total Length, IPv6 Payload Length or UDP Length of 0 bounds nothing; and a UDP Length past the IP end is clamped by the tighter IP end rather than raised. The hook the walk reads (_BOUNDS_PAYLOAD,_payload_extent()) stays private, and_ip_checksum_extent()reads the same per-class arithmetic.tests/test_trailer.pypins the trailer over the corpus, every snap-length prefix, an appended FCS, short-frame padding, nested bounds, ICMP quotes and continuation walks;tests/test_contract.pypins zero, lying and too-short lengths;tests/test_packet.pypins thePacketAPI; andtests/test_fuzz.pypins the round trip over redrawn lengths (#235).
-
Noneindecode_asraisesTypeError. A key mapped toNoneindecode_asorRegistry.derive(), or registered asNonewithRegistry.register()orregister_all(), now raisesTypeErrornaming the table and key and pointing atnetprotocols.registry.WITHHELD, whateverlaxsays; before,Nonewas stored as the key's entry and happened to end the walk there.register(table, key)with no class is still the decorator form (#271). -
Body, ciphertext and chunk layers no longer include the trailer. In a walk, Ethernet padding and a captured FCS past the IP or UDP datagram are
Packet.trailerinstead of the tail of the innermost layer: ESP'sciphertext, SCTP'schunks(soverify()holds on a padded frame or one with a captured FCS), thebodyof ICMPv4, ICMPv6 and IGMP, a PIM Register's packet, RIP's and NTP's bodies, a TFTP DATA's data, a VXLAN inner frame and every other layer that keeps the rest of its buffer. A standalonedecode()is unchanged, and SCTP's zero-tail scan stays as the fallback forSCTP.decode(raw)and for a walk no IP length bounds (#235). -
Padded short frames behave like their unpadded form. A padded empty UDP datagram to port 53 or 67 now raises
TruncatedHeaderError, where before its padding decoded as DNS or DHCP; a padded IPv4 bare TCP ACK to port 443 raisesTruncatedHeaderErrorat the empty payload, where before its padding raisedInvalidFieldErroras a TLS ContentType of 0; and a RADIUS Length that overstates its UDP datagram raisesTruncatedHeaderError, where before it read the bytes after the datagram as attributes (#235). -
Lying IPv4 and UDP lengths raise in a strict walk. An IPv4 Total Length of 1 to
ihl * 4 - 1or a UDP Length of 1 to 7 makesdecode_frame()raiseInvalidFieldErrorwithfield"total_length"or"length",offsetNoneandframe_offsetat the start of that header; a lax walk keeps the header and setsstopped_by. A positive length too short for what follows raises the next decoder'sTruncatedHeaderError.IPv4.decode()andUDP.decode()on their own are unchanged (#235). -
Packetequality andrepr()differ for packets that carry a trailer. Two packets with equal layers andstopped_bybut different trailers are unequal and hash differently, and therepr()of a packet with a non-empty trailer ends intrailer=...(#235). -
checksum.verify()accepts a VRRPv3-over-IPv4 advert checksummed with or without the IPv4 pseudo-header (#242). RFC 5798 §5.2.8 cites only RFC 2460's pseudo-header, which is IPv6's, and keepalived adds the IPv4 one by default; RFC 9568 §5.2.8, which obsoletes RFC 5798, has the IPv4 checksum cover "the VRRP message starting with the Version field and ending after the last IPv4 address", and its §1.1 lists that as a clarification ("it does not include the pseudo-header for IPv4"). keepalived 2.2.8 sends that form underv3_checksum_as_v2, and its keepalived.conf(5) says some manufacturers (e.g. Cisco) interpret RFC 5798 §5.2.8 as applying only to IPv6.verify()returnedFalsefor such an advert; it now returnsTruewhen the checksum matches either form.compute()andPacket.with_checksums()are unchanged and keep producing the pseudo-header form, keepalived's default, sowith_checksums()rewrites an RFC 9568-form advert into it, as it rewrites a whole-message PIM Register to the 8-byte form. VRRPv2, which has no pseudo-header, and VRRPv3 over IPv6, which keeps it in both RFCs, verify as before. Thechecksum,layer3.vrrpandPacket.with_checksums()docstrings, and ARCHITECTURE, say so.
-
Packet.with_checksums()recomputes IGMP and GRE checksums (#300). It carried both over unchanged, sochecksum.verifyreturnedFalsefor an IGMPv1/v2/v3 message or a checksummed GRE header after the call. IGMP's checksum is now refilled over the whole message (RFC 2236 §2.3, RFC 3376 §4.1.2), and GRE's whenever its Checksum field is present (RFC 2784 §2.5), over the header, the rebuilt inner layers and the trailing payload, with the reserved word, key and sequence number kept. A GRE header whosechecksumisNone, because the Checksum-Present bit is clear orfieldsis too short to hold the checksum, is returned unchanged. Both checksum inputs end at the declared end of the nearest enclosing IPv4 or IPv6 datagram, so Ethernet padding and a captured FCS stay out of the sum while remaining in the returned packet; an IPv6 payload length of zero, or a declared end before the layer's required bytes, leaves the input unbounded.tests/test_packet_checksums.pypins that every checksummed layer type in the corpus is refilled tochecksum.compute's value, plus the IGMP versions, the captured IGMP frames, GRE's optional fields and inner packet, and the unchanged GRE cases;tests/test_packet_checksum_extents.pypins the datagram bound over padded IGMP and GRE frames, GRE over IPv6 with an FCS, an intervening AH header, nested GRE, and missing or impossible extents. -
checksum.compute()/verify()end IGMP, ICMPv4 and GRE checksum input at the datagram's declared end when givenip(#316).IGMP.decode()andICMPv4.decode()keep every byte after their header inbody, so a message decoded on its own from a padded frame held the Ethernet padding or a captured FCS, andcompute(layer, ip=ip)summed it: on f7b8d8b a valid IGMPv2 report and an ICMPv4 echo request, each decoded with 18 bytes ofbytes(range(1, 19))padding after it, failedverify(layer, ip=ip).Packet.with_checksums()already bounded IGMP and GRE but not ICMPv4, so a hand-builtPacket(ip, icmp)whose body carried padding was refilled with the padding summed. Givenip, the IP header directly before the layer,compute()andverify()now end the IGMP message, and the ICMPv4 or GRE header and itspayload,ip._payload_extent()bytes after the layer's start; an IPv4 Total Length or IPv6 payload length of 0, an IPv4 Total Length shorter than its header, or an end before the layer's required bytes (IGMP's 4-byte header, ICMPv4's 8-byte header, GRE's whole header) leaves the input unbounded, aswith_checksums()does, and a lying Total Length raises nothing. An IPv4ipwith More Fragments set or a nonzero Fragment Offset leaves it unbounded too, incompute(),verify()andwith_checksums()alike, since a fragment's length covers that fragment and not a message reassembled from it;with_checksums()applies the same rule to an IPv6 Fragment header between the IP header and the layer whose M flag is set or whose Fragment Offset is nonzero (RFC 8200 §4.5), while an atomic fragment, both 0 (RFC 6946), stays bounded; a standalonecompute()cannot see such a header, so an IPv6ipmust carry a Payload Length that covers the whole message. GRE'scompute()ignoredipand summed all ofpayload, so a caller who passed apayloadthat included an FCS now gets the value bounded at the datagram's end. Withoutip, the input is unchanged.with_checksums()now bounds ICMPv4 the same way, and computes IGMP's, ICMPv4's and GRE's sums with the same private helpers ascompute():_datagram_extent(), which_ip_checksum_extent()now calls with the offset of the headers between, and_bounded_checksum(), socompute(layer, ip=ip)equals whatwith_checksums()writes for all three given the same IP context. ICMPv6, whose pseudo-header length is the segment's, still sums whateverbytes(layer)andpayloadhold.tests/test_checksum_datagram_extent.pypins standalone IGMPv1/v2/v3 and ICMPv4 messages with non-zero padding, an FCS and both, with and without IP options; the agreement ofcompute()andwith_checksums()for IGMP, ICMPv4 and GRE over IPv4 and IPv6, a GRE datagram ending in the trailer, zero, lying and too-short lengths and a bound at exactly the required bytes; an ICMPv4 message behind an AH header, and behind one whose datagram ends short of ICMPv4's header; a reassembled 2056-byte ICMPv4 echo checked against a first and a last fragment's header; GRE over IPv6 behind a Segment Routing header; GRE over IPv6 behind a Fragment header with M set, with a nonzero offset, and as an atomic fragment; and the expected sums from its own RFC 1071 arithmetic.
-
Every comparative number the README quotes was re-measured for this release (Rule 4 of
docs/CLAIMS.md), on the 411-frame corpus (39 scenarios; 2.8.0 used 394) and the machine and method 2.8.0 used (i7-1355U, CPython 3.12.12, every timed run pinned to one core and started at a one-minute load average under 1.0), againstdpkt 1.9.8andscapy 2.8.0: dpkt decodes the corpus 1.53× faster (from 1.51×) and netprotocols is 3.0× ahead of scapy (from 3.3×; three runs read 2.90-3.09×, and the cost was not profiled, which is deferred to #250); encode is 1.35× ahead of dpkt on a whole frame (from 1.34×); a warm import takes 54.4 ms againstscapy.all's 226.9 ms (4.2×); the wheel is 293.2 KiB, 9.2× smaller than scapy's; and netprotocols decodes deeper than dpkt on 175 of 411 frames, the same count as at 2.8.0. The per-capture decode figures the README quotes (the routing captures, the 140-frame 2.4.0 corpus, LLDP, the Tier 4 and TLS captures) were not repeated. -
A real capture of RFC 9568-form VRRPv3 adverts joins the corpus, and
scripts/check_fixtures.pyverifies both VRRPv3-over-IPv4 checksum forms (#242). Newscripts/capture_fixtures_vrrp_rfc9568.shruns keepalived 2.2.8, every instance configured withv3_checksum_as_v2, as two routers in netnsnpvr9-a/npvr9-bon10.9.203.0/24: VRID 61 multicast with one address, failing over from A to B, and VRID 62 unicast from A to B with three addresses and a 0.5 s interval. It keeps each router's first two live adverts and its resignation per segment, asserts the composition exactly, and asserts that every kept checksum is the message's sum alone and not the sum behind the IPv4 pseudo-header.tests/fixtures/vrrp_rfc9568.pcapholds the 9 frames (411 across 39 scenarios); tcpdump 4.99.4 reports each asbad vrrp cksum._check_vrrp()now accepts VRRPv3 over IPv4 when its checksum matches the sum behind the IPv4 pseudo-header or the message's sum alone, recomputed independently of the library; an advert that matches only the second is counted asvrrpv3-no-pseudo-header, a key that appears only when nonzero, so the report on every earlier capture is unchanged;vrrp-checksumfails only when neither matches. VRRPv2 and VRRPv3 over IPv6 are checked as before.vrrp.pcapandcapture_fixtures_vrrp.share unchanged. New tests intests/test_checksum.pyandtests/test_vrrp.pycover both forms inverify(), an advert matching neither, VRRPv2 and VRRPv3 over IPv6 refusing the other form,compute()andwith_checksums()returning the pseudo-header form for an RFC 9568-form input, the new capture, and the checker's new paths and stat key. -
scripts/check_fixtures.pyverifies CoA-Request and Disconnect-Request authenticators (#324). It recorded a CoA-Request (Code 43) and a Disconnect-Request (Code 40) only so that their ACKs and NAKs could be paired with them, and never checked their own authenticators. Their Request Authenticator is now verified as an Accounting-Request's is, MD5 over the packet with a zero Authenticator and then the secret (RFC 5176 §2.3, RFC 2866 §3), counted and failed asradius-coa-authenticatorandradius-disconnect-authenticatorbeside the unchangedradius-accounting-authenticator. A Message-Authenticator on either is verified asradius-message-authenticator, HMAC-MD5 under the secret over the packet with both the Authenticator and the attribute's value zeroed, since RFC 5176 §3.4 computes it before the Request Authenticator, which then covers it; an Access-Request's and a Status-Server's are still computed over the Authenticator as sent (RFC 3579 §3.2). A request's two authenticators are reported on their own. The corpus holds neither request, so every capture's report line is unchanged.tests/test_check_fixtures.pybuilds both requests with and without a Message-Authenticator: signed ones pass, a flipped byte of either authenticator fails, a Message-Authenticator computed over the Authenticator as sent fails, a Request Authenticator computed before the Message-Authenticator fails, and a signed CoA-Request or Disconnect-Request followed by its ACK verifies both. -
scripts/check_fixtures.pychecks GRE's RFC 1701 routing, its reserved flags and enhanced GRE (#328)._check_gre()read only the C, K and S bits and ignored the Version, so a packet with the Routing Present (R) bit set had its tunnelled packet read from the Offset word or the Source Route Entries, a Version 1 (PPTP) packet was parsed as Version 0, and nothing looked at the other flags. The C or R bit now makes the Checksum and Offset words present (RFC 1701), and with the R bit the Routing field after the Key and Sequence Number is walked: its last SRE, the first of SRE Length 0, must be the NULL SRE (gre-routing-null), the Offset must point to the first byte of one of its SREs (gre-routing-offset), the C bit's Checksum covers it, and the tunnelled packet after it is checked in turn; an SRE list the packet ends first is a cut header, which passes unread and fails asunchecked-gre-truncatedunder strict, like the optional words before it. RFC 1701's Strict Source Route bit and Recursion Control, bits 4-7, are read and not checked, which RFC 2784 §2.3 allows a receiver implementing RFC 1701, and flags bits 8-12, which RFC 1701 and RFC 2784 both have sent as zero, fail asgre-reserved-flags. A Version other than 0 or 1 fails asgre-version. Version 1 is checked against RFC 2637 §4.1: the K bit must be set (gre-v1-key), the C, R and s bits, Recursion Control and Flags bits 9-12 clear (gre-v1-flags), the Protocol Type0x880B(gre-v1-protocol), the Key's Payload Length the bytes after the Sequence and Acknowledgment Numbers its S and A bits announce (gre-v1-payload-length), and the S bit set exactly when there are any (gre-v1-sequence); its PPP payload is counted asgre-v1-pppand not read, and fails asunchecked-gre-pppunder strict. Every committed capture's report is unchanged.tests/test_check_fixtures.pygains a case for each new failure string and tests of routed packets with and without the C, K and S bits over IPv4 and IPv6, of the SRE walk's ends, Offsets and cut lists, of each reserved flags bit and Version, and of enhanced GRE data and acknowledgment packets, each field RFC 2637 fixes, cut headers and strict mode over IPv4 and IPv6; the header-byte checksum test flips the Strict Source Route bit where it flipped the R bit, which is now read. -
scripts/check_fixtures.pypairs a RADIUS reply only with a request its Code answers, and reads UDP as RADIUS by the server's port (#327). A reply took the most recent unanswered request of its exchange, (client address, client port, server address, server port, Identifier), whatever either Code, so a CoA-ACK could be verified against an Access-Request that shared it and fail; and a datagram was read as RADIUS when either port was 1812, 1813 or 3799, ahead of STUN and NTP, so STUN or NTP sent from or to a client whose ephemeral port was one of those was misread and failed, a STUN Binding success response, whose first byte is Access-Request's Code, asradius-attributes.RadiusExchangesnow records each request's Code with its Authenticator, and_RADIUS_ANSWERS, which replaces_RADIUS_REPLIES, maps each reply Code to the request Codes it answers: Access-Accept, Access-Reject and Access-Challenge to Access-Request (RFC 2865 §3), Accounting-Response to Accounting-Request (RFC 2866 §3), Disconnect-ACK/NAK to Disconnect-Request and CoA-ACK/NAK to CoA-Request (RFC 5176 §2.3), and Access-Accept, Access-Reject and Accounting-Response to Status-Server, which RFC 5997 §2 says a server answers with Access-Accept on an authentication port or Accounting-Response on an accounting port and MAY answer with Access-Reject, while an Access-Challenge is NOT RECOMMENDED and is not paired with one. A reply takes the most recent unanswered request of its exchange whose Code it answers, passing over later ones it cannot; one whose exchange has unanswered requests but none it answers is countedradius-reply-code-mismatch, not checked and the requests left unanswered, and fails asunchecked-radius-reply-code-mismatchunder strict, as an unpaired reply does. A datagram is RADIUS when the server's port, which_radius_server_port()takes as the source port when the first payload byte is a reply Code and the destination port otherwise, is 1812, 1813 or 3799, and neither port is in_NON_RADIUS_PORTS, STUN's 3478, NTP's 123 and HSRP's 1985, the ports the UDP dispatch takes after RADIUS's: 1812→1812 still reads as RADIUS, a reply-coded datagram sent to 1812 from another port does not, and STUN or NTP between its own port and 1812, 1813 or 3799 is checked as STUN or NTP in either direction.radius.pcap's report line is unchanged.tests/test_check_fixtures.pygains a strict exchange case for the new failure string, tests that the eleven request/reply pairs verify, Status-Server's three among them, and that the twenty-nine other pairs of the five request Codes and eight reply Codes are counted as mismatches and leave the request to its real reply, that a reply skips a later request it cannot answer, and that STUN, NTP and other data from 1812, 1813 or 3799, a STUN success response and an NTP reply sent to them, reply-coded NTP from them and HSRP with either port moved to them are not RADIUS, while a reply from those ports, and an exchange between two of them, is; MANIFEST.md's RADIUS secrets note describes the Code pairing and the dispatch (#327). -
tests/test_check_fixtures.pyrequires a case for each member of a failure family, and CI checks the committed captures once (#329). The meta-test counted one case per f-string pattern, so{protocol}-icvwas covered while eitheresp-icvorah-icvkept a case, and likewise{protocol}-unknown-sa,rip-{algorithm},ntp-{algorithm}andstp-{name}-unused-flags. Itsastscan, nowFailureScan, resolves each replacement field: a parameter through every call of its function that passes it ("esp"and"ah"for_verify_icv()), a name through its str bindings in the function or at module level, and the RIP and NTP key algorithms and the BPDU Types that leave Flags bits unused from the checker's_RIP_SAS,_NTP_KEYSand_BPDU_TYPES, sostp-tcn-unused-flags, which the checker cannot emit, needs no case. The fields that take any number or byte string, such asospf-autype-N's, are listed and match any text, and a test fails when a listed field is no longer in a failure string. The scan also follows a conditional expression, anif/elsereturning a bare str, a tuple and a name bound to a str literal, and raises with the file and line for a replacement field it cannot resolve and for a string built by+,%,str.formatorstr.join; synthetic sources test each form. ci.yml ranscripts/check_fixtures.pyover every capture directory on each of the test job's three legs, all three under the runner'spython3, after pytest, which also runs it under each matrix Python; the step now runs once, in the lint job, whatever an earlier step's outcome, andtests/test_workflows.pypins it there as the only step in ci.yml that runs the checker (#329). -
scripts/check_fixtures.pyverifies GRE carried over IPv6 (#326)._check_upper_v6()had no branch for Next Header 47, so GRE over IPv6 passed unchecked, counted as IPv6 alone, and failed asunchecked-protocol-47only under strict. It now dispatches GRE to the same_check_gre()as IPv4 does, over the IPv6 payload as the Payload Length bounds it after any extension headers, so Ethernet padding and an FCS stay out of the RFC 2784 §2.5 checksum, the GRE Checksum is verified when the C bit is set and the inner packet is checked in turn; a fragment carrying GRE is counted as one and not checked, as for every other protocol._check_gre()never read the outer addresses and no longer takes them.gre6.pcap's report line becomes4 frames (grex4, icmpv4x4, ipv4x4, ipv6x4), andscripts/capture_fixtures_gre.shnow stops unless the checker reportsgrex4for it.tests/test_check_fixtures.pygains tests thatgre6.pcap's frames are checked through GRE to their inner echo, that a checksummed GRE packet over IPv6 passes and a tampered one fails asgre-checksum, that bytes after the Payload Length are not summed while a checksum over them too fails, that GRE behind a Destination Options header carrying the Tunnel Encapsulation Limit (RFC 2473 §5.1) is checked, that a first fragment is not summed, that GRE in ESP over IPv6 is checked under strict, and thatmain()reports the new line.tests/fixtures/MANIFEST.mdanddocs/CLAIMS.md§5.1 no longer exceptgre6.pcapfrom what the checker verifies. -
CI builds the docstrings with Sphinx and fails on any broken cross-reference role (#301). Nothing rendered the docstrings, so a role naming no object, or reST that does not parse, went unnoticed. CI's lint job now runs
uv run --frozen sphinx-build -W -n -b dummy docs, with Sphinx 9.1.1 pinned in the dev group.docs/conf.pydocuments every module undernetprotocolsthrough autodoc, private modules and members included, withnitpicky = True; amissing-referencehook resolves a role spelt through a module that re-exports the object (netprotocols.TCP) to its defining module and passes it back to the Python domain, so it resolves only if that object is documented. Standard-library roles resolve through intersphinx against the Python 3.12 inventory rather than anitpick_ignorelist, so they are checked too; the build fetches the inventory from docs.python.org with a 30-second timeout, and a failed fetch fails it. The first nitpicky run reported 23 warnings, all fixed at the docstring: unclosed*emphasis in PIM's(*,G)andAssert(*,G)forms, now literals;:func:onstr, now:class:;InvalidFieldErrorin_base's module docstring andIGMPin PIM's, now fully qualified; inherited members referenced from a subclass (LLDPChassisID/LLDPPortID.subtype_name,AHv6.decode/icv,ICMPv6.body,VRRPv6.addresses,HSRP.header_len), now pointed at the defining class; three STUN roles split across a line wrap, rejoined;netprotocols.MAX_DEPTHas:data:in BGP, STUN and TLS, which the hook does not follow for a non-callable, nownetprotocols.walk.MAX_DEPTH; and Packet's__eq__,__init__and__getitem__, which autodoc does not document, now literals.tests/test_workflows.pyreads the lint job's executedrun:command and accepts only the exactuv run --frozen sphinx-build -W -n -b dummy docscommand, with a literal output directory, in an unconditional lint job step, and requiresnitpicky = Trueand nonitpick_ignore,nitpick_ignore_regex,suppress_warningsorwarn-missing-referencehandler indocs/conf.py. CONTRIBUTING.md's QA ladder and "Docstrings and comments" section describe the check (#301). -
scripts/check_fixtures.pyverifies RADIUS reply authenticators by pairing each reply with its request (#273). It verified each Accounting-Request's Request Authenticator and each Access-Request's and Status-Server's Message-Authenticator, what one frame holds, but no reply's: a Response Authenticator, and a reply's Message-Authenticator, are computed over the matching request's Authenticator, which is in another frame, so onlytests/test_radius.pychecked them.main()now gives each pcap a freshRadiusExchanges, passed through the newexchangesargument ofcheck_capture_frame()andcheck_frame(), which set it in aContextVarfor that one call and reset it afterwards, so no request outlives its file and no tunnel helper's signature changes;_check_udp_payload()now takes the datagram's source and destination addresses. Each request (Access-Request, Accounting-Request, Status-Server, Disconnect-Request, CoA-Request) is recorded under its exchange, (client address, client port, server address, server port, Identifier), and each reply (Access-Accept, Access-Reject, Access-Challenge, Accounting-Response, Disconnect-ACK/NAK, CoA-ACK/NAK) takes the most recent unanswered request of the swapped exchange, so a reused Identifier pairs with the latest request and a request is answered once. The reply's Response Authenticator,MD5(Code+ID+Length+RequestAuth+Attributes+Secret)(RFC 2865 §3), is counted and fails asradius-response-authenticator, and its Message-Authenticator, when present, HMAC-MD5 over the reply with the request's Authenticator in place and the value zeroed (RFC 3579 §3.2), asradius-reply-message-authenticator; each is reported on its own, so a flipped Message-Authenticator byte fails both. MD5 runs withusedforsecurity=Falseand the script stays stdlib-only; UDP port 3799 (RFC 5176) joins 1812 and 1813, so a Dynamic Authorization exchange is checked too. A reply with no earlier request in its pcap is countedradius-reply-unpairedand passes, as a payload the checker cannot read is counteduncheckedand not failed, and fails asunchecked-radius-reply-unpairedunder strict, inside a payload an IPsec ICV vouched for;check_frame()withoutexchangestreats every reply so.radius.pcap's report line gainsradius-reply-message-authenticatorx4andradius-response-authenticatorx6, and no corpus file reports an unpaired reply.tests/test_check_fixtures.pygains a table of capture-level cases, which the every-failure-string meta-test now counts, for the two new failure strings (a flipped Response Authenticator byte; a flipped Message-Authenticator byte, alone and with the Response Authenticator recomputed over it), a strict case for the unpaired one, and tests that every captured reply verifies, that a flipped byte fails each of the six, that a lone reply, inmain()'s report too, or one before its request is counted unpaired and passes, that a request answers once, that a reused Identifier pairs with the most recent unanswered request, that another client address, client port, server port or Identifier is another exchange, that captures share no exchanges, and that Access-Challenge and the four RFC 5176 replies are verified.tests/test_radius.pychecks the replies through the checker too, and MANIFEST.md's RADIUS secrets note describes the pairing. -
CI runs
scripts/check_fixtures.pyover every committed capture, its failure paths are tested, and it verifies GRE checksums (#237). Nothing ran the corpus's stdlib-only checksum oracle after a fixture was captured, so a fixture edited later, or a checker change that broke one, went unnoticed. ci.yml's test job gains a step that runspython3 scripts/check_fixtures.pyovertests/fixturesand over each subdirectory holding agit ls-files-tracked capture (bgp,http,mpls,stun,tls; the script reads one directory without recursing), and fails if any run exits non-zero or no capture is tracked;tests/test_workflows.pypins the step. Newtests/test_check_fixtures.pyloads the script by path, so neither it nor the script importsnetprotocols, and reads frames with the script's own pcap reader. It runs the script in isolated mode over every capture directory but the untrackedstaging/, and for each of the 104 failure patterns the script can emit, its pcap reader's three messages included (literals, and f-string families such asunchecked-protocol-Nandospf-autype-N, found by anastscan of the script) it feeds a frame the checker passes, a committed fixture frame wherever one carries the field, and a minimally tampered copy, and asserts the copy fails with exactly that string. The scan resolves a name bound to an f-string in the same function, and counts a case only for the patterns it matches most specifically, so a literal such asrip-unknown-sacannot stand in for the{protocol}-unknown-safamily; a failure string with no case fails the suite. Strict-mode failures are built inside ESP onesp.pcap's Security Association, with the ICV recomputed from the key MANIFEST.md publishes, andmain()'s exit status, report lines and unreadable-file messages are tested on pcaps written undertmp_path._check_gre()now verifies the Checksum when the C bit is set (RFC 2784 §2.5): the internet checksum over the GRE header, Checksum field zeroed, and the payload, ending at the outer IPv4 Total Length, so Ethernet padding or a trailing FCS is not summed, the same bound every other IPv4 payload check uses. With the C bit clear nothing is read, and a packet shorter than the optional words its flags announce passes unread, or fails as the newunchecked-gre-truncatedunder strict. Itsgre-checksumfailure case flips a Checksum byte of a committedgre_csum.pcapframe, a test asserts that all 4 of that file's frames, the C bit alone set in each, verify, andmain()'s report line for it countsgre-checksumx4; hand-built checksummed frames, with and without the K and S words, test the rest: a correct one passes, a flipped header, Key, Sequence or payload byte failsgre-checksum, an odd-length packet is padded for the sum, and padding or an FCS after the IP datagram neither breaks a correct checksum nor fixes a wrong one, while a checksum computed over that trailer fails.scripts/capture_fixtures_gre.shadds a checksummed (csum) tunnel in its own netns pair,npgrecsaandnpgrecsb, on 10.9.197.0/25 (underlay) and 10.9.197.128/25 (overlay), captured to a separatetests/fixtures/staging/gre_csum.pcapso that the plain-and-keyedgre.pcapit also re-captures keeps its 8 frames and addresses; the script asserts all 4gre_csum.pcapframes, the flags word exactly 0x8000 among them, runs the checker and stops unless it reports 4 verified GRE checksums for that file. It now also stops when a tunnel's echoes go unanswered or veth tx/rx checksum offload cannot be turned off. The capture it produces joins the corpus asgre_csum.pcap(see below). -
Two GRE captures join the corpus:
gre_csum.pcapandgre6.pcap, 4 frames each, 402 across 38 scenarios (#237).scripts/capture_fixtures_gre.shcaptured both.gre_csum.pcapis two ICMPv4 echo exchanges over its checksummed (csum) kernel GRE tunnel, every GRE flags word 0x8000 (the C bit alone),Ethernet→IPv4→GRE→IPv4→ICMPv4;scripts/check_fixtures.pyverifies all 4 GRE Checksums and the inner IPv4/ICMP checksums.gre6.pcapis two ICMPv4 echo exchanges over anip6gretunnel, GRE over IPv6 (RFC 7676), which the script gains as a third capture: netnsnpgre6aandnpgre6b, vethnpgv6a/npgv6bwith tx/rx checksum offload off, underlay fd09:326:1::/64 and overlay 10.9.197.192/30,encaplimit noneso GRE is the IPv6 header's next header,Ethernet→IPv6→GRE→IPv4→ICMPv4. The script asserts every gre6.pcap frame with the standard library, its inner IPv4 header and ICMPv4 checksums included;check_fixtureschecks each frame through GRE to its inner echo (see the #326 entry).tests/fixtures/MANIFEST.mdgains a row and a capture note for each, and it, the README anddocs/CLAIMS.md§5.1 state the new counts. -
CodeQL now analyses
tests/test_gre.pyandtests/test_vlan.py(#277). Every CodeQL run since the files were added reported both under "Could not process some files due to syntax errors", so no query covered them. The cause is the encoding-cookie check in CodeQL's Python extractor (CLI 2.27.4, the version the action runs;semmle/python/parser/tokenizer.pyin its bundledpython3src.zip): it matches.*coding[:=]\s*([-\w.]+)against the raw first and second lines, without PEP 263's requirement that the declaration sit in a comment, which CPython'stokenize.cookie_reenforces with^[ \t\f]*#. The module docstrings opened"""GRE decoding: the flags-driven ...and"""VLAN tag decoding: fields, ..., so the extractor read the encodingstheandfields(the job log's "has encoding 'the'" and "has encoding 'fields'" warnings), failed on the unknown encoding, and reported a parse error at line 0. Bisecting locally with the 2.27.4 bundle confirmed it, its diagnostics readingunknown encoding: theandunknown encoding: fields: a one-line file"""decoding: fields"""fails, as doesx = "decoding: the"and the same docstring on line 2; the same text on line 3, a valid codec name (decoding: utf-8) anddecoding thewithout the colon all parse, and each file minus its docstring parses. Both first lines now read "decoding, covering ..."; a local extraction of the tree then reports no syntax-error diagnostic, and the pull request's CodeQL run, which extracts only changed files on top of master's cached overlay-base database, extracts both files without an encoding warning. No other tracked Python file hascoding:orcoding=in its first two lines. Docstrings only; the tests are unchanged. Newtests/test_encoding_cookies.pyapplies the extractor's pattern to the first two lines of everygit ls-filestracked*.pyfile, read as bytes, and fails with the file, line and name whenever the captured name is not a codeccodecs.lookupknows, so restoring either old first line fails it while a real cookie such as# -*- coding: utf-8 -*-passes. -
uv run mypytype-checksscripts/in strict mode (#276).[tool.mypy] filesnamedsrc,tests/conftest.pyandtests/strategies.py, so the typecheck job never checked the scripts that gate CI and releases. It now addsscripts, withscripts/pyodide/node_modules/excluded, and strict mode reported 77 errors in 8 of the 14 files:check_fixtures.py66 (61 bareCounterannotations, nowCounter[str];read_pcaphad no return type, nowIterator[bytes]; threeno-any-returnfrom sums and offsets built onstruct.unpack, now annotatedint; and onearg-type,_MPLS_NIBBLES.get(nibble)withnibblepossiblyNone, now looked up only when it is not);benchmark.py3 (twoimport-not-foundfordpktandscapy.layers.l2, and iteration over aPacket, which works at run time through the legacy__getitem__protocol mypy does not model, now overPacket.layers);benchmark_encode.py2 (the same twoimport-not-found);benchmark_import.py2 (msrebound from the probe'sstrtofloat, now two names);extract_http_streams.py1 (_tcp_segmentshad no return type); and oneno-any-returneach in theinternet_checksumofipsec_fixture_packets.py,llc_fixture_frames.pyandmpls_fixture_packets.py.check_markers.py,check_mutmut_survivors.py,filter_codeql_sarif.py,survey_protocols.py,_pcap.pyandpyodide/check_in_pyodide.pywere already clean. None of the findings was a run-time bug, and the fixes are annotations or equivalent rewrites with no# type: ignore; the stdlib-only scripts gain no import beyondcollections.abc.Iteratorincheck_fixtures.py. A[[tool.mypy.overrides]]entry setsignore_missing_importsfordpktandscapy: the benchmarks import them lazily, only when they compare against those libraries, and thebenchdependency group that provides them is not installed by the default sync, so mypy cannot resolve them; the override has mypy treat them asAnywhether or not the group is installed, and the typecheck job does not install that group.tests/test_workflows.pypins that the typecheck job runs plainuv run mypyand that[tool.mypy]stays strict withscriptsinfiles. CONTRIBUTING.md's ladder names no mypy scope, so it is unchanged. -
The nightly mutation run no longer caches mutmut state (#239).
mutation.ymlrestoredmutants/and.mutmut-cachefrom the most recent run through anactions/cachestep keyed on the run id with themutmut-nightly-restore key, and since f350cbd (#234) deleted the restoredmutants/mutmut-stats.jsonso that a function added since the cached run would not read "no tests". A review of that fix against mutmut 3.8.0's source and the CI log found the cache saved no work, and the same holds for the pinned 3.8.1: the workflow passes positional filters, and_runkeeps a cached result only when no filter is given (if not mutant_names and result is not None), so every in-scope mutant was re-run anyway; checkout gives the sources a newer mtime than the cached mutant copies, socreate_mutants_for_fileregenerated them (the log read "4 files mutated, 33 ignored, 0 unmodified"); nothing in mutmut references.mutmut-cache; andcopy_src_dirskips existing targets whilecopy_also_copy_filescopies withdirs_exist_ok=True, so a file deleted fromsrc/ortests/lingered in the restored tree. The comment v2.8.0 shipped above the cache step, which said mutmut skips re-running mutants whose inputs have not changed and so saves real work, was wrong for this workflow. The cache step and therm -f mutants/mutmut-stats.jsonstep are removed, so each run starts with nomutants/directory, generates every mutant and traces the configured test selection in full;.mutmut-cacheis dropped from the failure artifact, which still uploads the status listing andmutants/, and the workflow's comments now describe what mutmut does.tests/test_workflows.pyreplaces the test that pinned the stats-file deletion with one that fails on anyrestore-keysin the mutation job, anyactions/cachestep that namesmutantsor.mutmut-cache, and any mention of.mutmut-cache. -
The allocation tests share one tracemalloc helper and pass with tracing already on (#274).
tests/test_cdp.pyandtests/test_sctp.pycalledtracemalloc.start()andstop()unconditionally and read the peak as an absolute value, so with tracing already on, as underPYTHONTRACEMALLOC=1or a profiler, they counted every allocation since interpreter start and switched off tracing they had not started:test_a_long_tail_is_scanned_without_a_copy[zeros]failed underPYTHONTRACEMALLOC=1, and SCTP's looser bound hid the same flaw.tests/test_lldp.pyandtests/test_stp.pydid it right, each with its own copy of the code.tests/conftest.pynow holdsallocation_peak(), a context manager that starts tracing only if it is off, callsreset_peak(), takes a baseline on entry, yields anAllocationPeakwhosepeakis the peak above that baseline once the block exits (even when it raises), and stops tracing only if it started it. All four modules use it, with their bounds unchanged, and SCTP'speak_ofstatic method is gone; no other test drove tracemalloc.tests/test_conftest.pytests the helper with tracing off and on beforehand, including a block that raises, and checks that tracing is left as it was found and that memory held or peaked before entry is not counted. ci.yml's test job gains a step that reruns the allocation modules withPYTHONTRACEMALLOC=1, a targeted rerun because the whole suite is several times slower under tracing, andtests/test_workflows.pypins the step, its environment, and that the modules it lists are exactly those that useallocation_peak, and that no other test module starts, stops or resets tracemalloc itself. -
scripts/survey_protocols.pyfails when scapy'sload_layersis unreadable, and reads it withast(#293).scapy_loaded_layers()returned an empty set when scapy'sconfig.pywas missing or itsload_layersdeclaration did not match the script's regular expression, so every scapylayers/cell was labelled "load_layer(), not inscapy.all" and the run still exited 0, the script's one silent failure path. A first fix kept the regular expression and raised on a miss, but a review found reshapings it still read wrongly with exit 0: a commented-out# 'tls',entry was counted as loaded, a double-quoted"sctp"among single-quoted names was dropped,[...] + EXTRA_LAYERSignored the addition, and a]inside a comment truncated the list. The declaration is now read withast.parse, which builds a syntax tree without executing anything, so it stays safe on the unpacked third-party source: the one statement in the top-levelclass Confthat bindsload_layers(annotated or not, any annotation) must assign a non-empty list display whose elements are all string literals, and those strings are the loaded modules. Anywhere else in the module,load_layersmay appear only as an attribute load that is an operand of a comparison (m in Conf.load_layers) or whoseremovemethod is called (Conf.load_layers.remove(m)); any other node that names it, whether a name, an attribute, a function, class or argument name, an import alias, a keyword argument or the string constant"load_layers", raisesUnreadablewith its line, so a rebinding under anif, anappend, a slice assignment, a@propertyoverride, a module-levelConf.load_layers = [...]orconf.load_layers.append(...), asetattr(Conf, "load_layers", ...)or a nestedclass Conf(Conf)override fails the run. The check is syntactic and reads onlyconfig.py: a name built at run time (getattr(Conf, "load_" + "layers")), a comparison method that mutates its operand, and other modules are not followed. scapy 2.8.0'sarch/__init__.pyappends"tuntap"toconf.load_layerson Linux and BSD, which the survey does not count; no survey check nameslayers/tuntap.py, so no cell depends on it.Unreadableis raised for a missingconfig.py, aSyntaxError, no top-levelclass Confor more than one,load_layersbound in no statement or in more than one (an+=counts), and any other value: a tuple, an empty list, aBinOpsuch as[] + [...]or[...] + EXTRA_LAYERS, a name, or a non-strelement.main()prints the reason to stderr (scapy: FAILED config.py: ...) and exits 1 before printing either table. TheLOAD_LAYERSregular expression is gone. Against the scapy 2.8.0 wheel recorded in docs/CLAIMS.md §7.1 the output is byte-identical and the exit status still 0, as it is for copies with the names double-quoted, the annotation changed tolist[str], the[moved to the next line, a commented-out# 'tls',entry,'sctp'double-quoted, and a]inside a comment; copies withconfig.pydeleted, with[] + [...]and with[...] + EXTRA_LAYERSexit 1. Newtests/test_survey_protocols.pycovers 9 success shapes (scapy 2.8.0's module-level IPv6removeblock among them) and 25 failure shapes over fake trees undertmp_path, each failure both directly and throughmain(). -
docs/CLAIMS.md§5.9 states which raise sites its count covers (#294). It said "every raise site insrc/" attaches structured context and counted "230 raise sites in the library", but the AST count behind the figure has only ever measuredraisestatements that buildInvalidFieldError,TruncatedHeaderError,InvalidMACAddressError,InvalidIPv4AddressError,InvalidManufacturerCodeErrororMaxDepthExceededError, directly or through the_malformedand_too_deephelpers, as 343427b described it.src/holds 260raisestatements, and the other 30 never carried that context:pcap.py's 18MalformedCaptureErrorraises, which set noprotocol, three registry errors, three raises oflayer7/tls.py's private_Unreachedsignal, four stdlibValueError/OSError/KeyErrorraises and two bare re-raises. §5.9 now names the population as the 230 sites that raise a decode or validation error, lists the exception types and helpers, says the other 30 fall outside the claim, and prints the AST snippet that re-derives230 of 260; the same rule gives 60 at 534f889, 203 at 824893d, 206 at 343427b, 228 at f12daf0 and 230 at 2705353. §5.9 also counts the four stdlib raises by file and notes thatvalidate_mac_addrandvalidate_ipv4_addr, which are exported, forward theprotocol=their caller gives, so a direct call without one raises withprotocolNone. ARCHITECTURE.md ("Every raise carries structured context", "every raise site insrc/attachesprotocol") and README.md ("Every exception carries structured context") made the same overbroad claim; both now say every decode or validation error carries it and that capture-file and registry errors leaveprotocolunset, ARCHITECTURE.md points to §5.9 for the exact population, and its error-hierarchy diagram gainsMalformedCaptureError,UnknownTableError,InvalidRegistryKeyErrorandRegistryConflictError, which it had left out. The library is unchanged; whether capture errors should carry structured context is left open.tests/test_diagnostics.py's 37 tests and therandom_macexception still hold. -
scripts/filter_codeql_sarif.pyrejects an empty path argument (#278). Its path arguments were parsed withtype=Path, andPath("")isPath("."), sopython3 scripts/filter_codeql_sarif.py ""filtered every*.sarifunder the working directory and, in a checkout, rewrotetests/fixtures/codeql/python.sarif. CI was never exposed:analyzealways sets a non-emptysarif-outputandupload-sariffails on an emptysarif_file. A new argparsetype,nonempty_path, now rejects an empty or whitespace-only value for the SARIF paths and for--source-rootwithargparse.ArgumentTypeError, so the script exits 2 before it reads any file.tests/test_filter_codeql_sarif.pypins it with empty, space, tab and newline values (alone and after a valid path) run against a copy of the fixture in the working directory, which is left byte-for-byte unchanged, plus a relative valid path that is still filtered; the file's tests go from 102 to 116. -
A written docstring standard, checked in CI, and the
>>>examples insrc/run as doctests (#241). CONTRIBUTING.md's new "Docstrings and comments" section makes the existing style official: PEP 257 layout with an imperative summary, Sphinx reST field lists with no types (the annotations, checked bymypy --strict, hold them),:raises:on every publicdecode(), the two kinds of accessor (display helpers and typed views that degrade and never raise; parsing accessors that raise and say so),RFC 791 §3.1-style citations, and a rule that comments and docstrings state only what the code is or does, with history and decision-making kept here. Ruff now selects all of pydocstyle (D) under thepep257convention forsrc/, replacing theD100/D101/D103slice;tests/andscripts/stay exempt.D105(magic methods) andD107(__init__) are ignored: a magic method's contract is the data model's and the class docstring covers construction, so 39 docstrings restating either would add nothing.D209andD412were auto-fixed acrosssrc/. pydoclint 0.11.1 is a pinned dev dependency, run by the lint job asuv run flake8 srcwith its settings in.flake8: pydoclint's native CLI can switch a single code off only per function, with# noqa, and flake8'sextend-ignoreswitches it off for the whole tree. It ignoresDOC201/DOC402(the house style has no:returns:or:yields:), andDOC502/DOC503, becausedecode()documents the exceptions its helpers raise (_unpack_fixed,raise _malformed(...)factories) and pydoclint reads only the body's ownraisestatements: of the 64 such findings, all but one were that pattern, andDOC501still catches a body that raises with no:raises:field. Return and yield type checks are off along with the docstring types they compare. pytest'saddoptsgain--doctest-modulesand itstestpathsgainsrc(withtests/fuzz/, the Atheris harnesses, ignored), so the CI test job runs the doctests under the coverage gate; the three examples inflow.py,packet.pyandwalk.py, which referred to undefined names, now build a 54-byte Ethernet/IPv4/TCP SYN inline and pass.tests/test_workflows.pypins the pydoclint step and the doctest settings. The findings the wider rule set raised (D205,D401,D102,D104,D301,D400,DOC101/DOC103, oneDOC501) were then fixed package by package, andruff checkandflake8 srcpass with zero findings.- Work markers are banned outright: open work lives in the issue tracker, so a
TODO,FIXME,XXXorHACKin the code adds nothing the issue does not hold and goes stale when the issue changes. EveryTODOinsrc/andtests/was deleted, the behaviour each sat beside being already stated in the docstrings, and an issue or PR number in a comment or docstring now counts as history with no exception.scripts/check_markers.py(stdlib only, offline) scans the git-tracked text files and fails on any of the four words: in capitals, alone or with a pluralsor an_suffix, everywhere, and in any case as well in comments: Python#comments,#comments (at a line's start or after whitespace, a tab included) in shell, YAML, TOML,.cfg,.flake8,.gitignore,.gitattributes,CODEOWNERSandDockerfilefiles,//comments in.jsand.mjsfiles,;and#lines in.inifiles, and..explicit markup lines, comments and directives, in.rstfiles; in Markdown it reads prose only, skipping inline code spans, and stays case-sensitive. It decodes withsurrogateescape, so a Latin-1 file is still scanned, and skips only what is not a regular file (a symlink, a submodule), files that hold a NUL byte, and the rootCHANGELOG.md; the checker and its tests build the words by concatenation, so neither is excluded. ci.yml's lint job runs it, so it is part of the release gate and the local ladder, which CONTRIBUTING.md, the pull-request template, README.md and ARCHITECTURE.md count as six CI gates.tests/test_check_markers.pypins the matching, the encodings and every exclusion, andtests/test_workflows.pythe lint step. - The comment rule was applied across
src/,tests/,scripts/,.github/andpyproject.toml: comments and docstrings were rewritten to state what the code is or does, history and decision-making were deleted, and measurements taken on the fixture corpus or by random walks were replaced by the property they illustrated (computed odds and segment arithmetic stay). The reasons behind CI and configuration settings that those comments held are recorded here:- The coverage gate is
fail_under = 98, below the suite's 99.98% so that a legitimately unreachable branch (Packet's__eq__NotImplementedreturn was the one miss) does not fail CI, and high enough that the bar is held. - The benchmark job blocks at 15% below the committed baseline: its first run measured 3.7% from a baseline recorded on different hardware and run-to-run spread on one machine is about 2%, so 15% is about four times the noise while the regressions it exists to catch moved the number by 30-90%. A failure re-measures once before failing, because a shared runner can lose CPU to a neighbour and a real regression fails both attempts. The job is pinned to the baseline's interpreter because normalization cancels the machine's speed, not the CPython version; a deliberate trade is re-recorded with
--update-baseline. Its step keeps the benchmark's own exit status rather than piping intoteeor wrapping it in a{ }group, either of which would report another command's status. scripts/_pcap.pynever imports netprotocols because its callers, the benchmark, the Pyodide import check and the HTTP stream extractor, must not depend on the code they measure or prove works; sharing one reader among them keeps that independence without writing it three times.- ci.yml's concurrency group starts with the literal
ci, not${{ github.workflow }}: inside aworkflow_callthat expression is the caller's name, so the group matched release.yml's ownRelease-<ref>group on a tag push and GitHub cancelled the run as a self-deadlock. ci.yml is callable so that release.yml runs the same ladder against the tagged commit (a tag push matches neither of ci.yml's own triggers, and a tag can name a commit that never reachedmaster), which is also why the scheduled jobs (fuzz, mutation, Scorecard, CodeQL, docs links) live in their own workflows: a schedule in ci.yml would fire the whole ladder. - Dependabot uses the
uvecosystem because only it parses PEP 735[dependency-groups]; the dev group is matched by package name because Dependabot'sdependency-typeclassifier reports every uv dependency as production; and the CodeQL action's paths are grouped becauseinitandanalyzemust run the same release, so per-path PRs could never merge. - The reproducible-build check compares the sha256 of two back-to-back wheel builds, which catches embedded timestamps and nondeterministic member order without a binary diff;
pip-auditaudits a--no-emit-projectexport because the editable in-tree reference cannot be installed under--require-hashes. - The fuzz and mutation jobs run on Python 3.12 only (they explore, they are not compatibility gates, and Atheris lags new interpreters), cache their Hypothesis database and mutmut results under a run-id key with a prefix restore key (a fixed key restores forever but never saves), and upload their artifacts so a failure can be examined without write access; the CodeQL job uses
build-mode: nonebecause Python has nothing to build, and filters only one query's results undertests/andscripts/because CodeQL's config cannot scope a query to paths. - The release workflow reads the version back out of the built artifact and checks the
vprefix, so a mistagged release fails; attests provenance before publishing so a failed attestation blocks it; publishes withpypa/gh-action-pypi-publishbecause Scorecard's Packaging check recognizes it; and takes the release notes from this file's section for the tag, failing on a missing one. pr-title-lint runs onpull_request, notpull_request_target, so it holds only a read-only token. - docs-lint runs on a docs path filter and weekly, the schedule catching links that die under unchanged files; it passes
GITHUB_TOKENso github.com links go through the API rather than an anonymous rate limit, uses more generous timeouts and retries than lychee's defaults, and excludesimg.shields.io, a CDN that rate-limits CI traffic regardless of whether a badge is broken. - mutmut's
only_mutatelimits mutation to four files, the checksum module, the shared TLV walker, DNS and the HTTP/1.1 grammar, the code whose correctness stakes justify the runtime; mutation.yml's positional filters narrow DNS to its name-compression walk and HTTP to its private module-level functions, since mutmut cannot scope below a file in its config;source_pathsstill names all ofsrcso the mutated copy stays importable. - codeql.yml uses CodeQL's advanced setup, a checked-in workflow, rather than GitHub's default setup, so that the analysis and its action pins live in version control and are reviewed like the other workflows.
.github/ISSUE_TEMPLATE/config.ymlkeeps blank issues enabled because roadmap and design discussions do not fit a form; the templates give the common cases a structure.- ci.yml's pyodide job runs the real Pyodide under Node because that is the same WebAssembly build a browser runs, so the README's browser claim is checked against the real runtime with no browser needed.
- The coverage gate is
- Work markers are banned outright: open work lives in the issue tracker, so a
-
docs/CLAIMS.md's current-tree line citations re-derived after the docstring standard (#309). #241's docstring and comment rewrite moved code insrc/andtests/, so two citations named the wrong lines: §3.2'sinet_pton/inet_ntopcalls are now_base.py:196-201(from 202-207) and §5.1's round-trip assertion istests/test_corpus.py:135-140(from 137-142). Citations pinned to a release or commit stay as recorded: the 2026-11-01 status audit's_base.py:202-207, checked against8fe5076, scapy 2.8.0's and construct28c6e57's sources, and thev2.4.0git grepoutput. No passage in CLAIMS quotes docstring or comment text that #241 removed, and the test, coverage and raise-site counts it cites are unchanged. -
MaxDepthExceededError's docstring covers valid deep segments (#295). It gave only the hostile-input reason, a crafted frame nested deep, though BGP, STUN over TCP and TLS chain one layer per message or record, so a valid TCP segment of many of them exceeds the defaultmax_depthtoo. It now says so, names the remedies, a largermax_depthor a lax walk continued frompacket.consumedwithstart=as many times as it takes, and points tonetprotocols.walkfor the figures rather than repeating them. Docstring only; no behaviour change. -
One decoded layer stays one message under
max_depth(#244). BGP, STUN over TCP and TLS decode one message, or record, per layer and chain to their own class, so a valid TCP segment of more than 29 (the room the default leaves after Ethernet, IPv4 and TCP) exceeds the defaultmax_depth: a strict walk raisesMaxDepthExceededErrorand a lax one stops short. Three designs were weighed and the status quo kept:max_depthcounts every message as a layer, and the remedies are a largermax_depthor a lax walk continued frompacket.consumedwithstart=. One container layer per segment, holding its messages as a tuple the waySCTPholds its chunks, would make depth independent of message count, but would lose "oneBGPinstance is one message" and move every accessor onto a separate message type. Exempting sibling chaining from the depth budget would keep the per-message model, butmax_depthis what bounds a walk over hostile input, so the exemption would need a cap of its own, such as a byte budget of one message per minimum message size (19 bytes for BGP, 5 for a bare TLS record header), a second limit to document and test. ARCHITECTURE.md's decode-contract section now states the rule once for every protocol that decodes one self-delimiting message, or record, per layer and chains to its own class for the next one in the same payload, cross-referencing the per-protocol figures under "Port-based dispatch is best-effort" and inwalk.py. Docs only; no behaviour change. -
The mutation audit's checksum survivors are killed or triaged (#347). The mutation run dispatched on
masterat the release PR's merge commit (#346), beforev2.9.0was tagged, failed on 15 undetected mutants ofchecksum.pythat the checksum PRs of 2.9.0 left behind: 9 in_datagram_extent, 3 in_bounded_checksumand 3 incompute. The mutation audit runs onlytests/test_checksum.py, and the declared-length bound (#235) was pinned in other files, so none of its tests reached it.TestDatagramBoundedChecksumnow pins the bound intests/test_checksum.py, throughcompute()and_datagram_extent()directly: a bounded and an unbounded input, a zero Total Length, the offset and minimum boundaries, IPv4 fragments (More Fragments, a nonzero Fragment Offset, DF alone) and IPv6. 14 are killed; the 15th,_bounded_checksummutant 41, makescovered[:None]replacecovered, which are the same bytes, and is recorded inscripts/mutmut_survivors.txt. This entry was moved here from## [Unreleased]afterv2.9.0was tagged, so the 2.9.0 GitHub release notes do not contain it, and the tag'sCHANGELOG.mdhas it under## [Unreleased].
TLS: TLS record framing (RFC 9846 §5.1, which obsoletes RFC 8446, and RFC 5246 §6.2, TLS 1.2's, which RFC 9846 also obsoletes) and the ClientHello's SNI (RFC 6066) (#196). TCP port 443 dispatches, best-effort like every port entry, to the newnetprotocols.TLS(alsonetprotocols.layer7.TLS), one layer per record: the 5-byte header decoded intocontent_type,legacy_versionandlength, and thefragmentkept raw, sobytes(TLS.decode(x)) == x[:header_len]. No cryptography and no handshake beyond the ClientHello's fields: nothing is decrypted, verified or derived, and the ServerHello, the certificates, the key exchange and every extension but server_name stay raw. Against a wrong port guess,decode()judges each of the header's first three bytes as soon as it is in the buffer, and the length once both its bytes are: a ContentType outside 20-24 (InvalidFieldError,field="content_type", which also turns away SSL 2.0-compatible hellos), a version whose first byte is not 3 or second above 4 ("legacy_version"), then a length above 2^14 + 2048, RFC 5246 §6.2.3's bound ("length"), each withexpectedandactual, and only then raisesTruncatedHeaderErrorfor a record the buffer cuts short or a short header whose first three bytes pass; random bytes pass the header 25 times in 2^24, and over 90,000 random payloads to port 443 every walk stopped and none decoded a TLS layer. As for BGP's messages, records in one segment chain:decode()notes, outside the comparison and hash, whether as much of the next 3 bytes as the segment holds passes the guard, andTLS.next_protocol()then answersTLS; a cut record raisesTruncatedHeaderError, a bare ACK raisesTruncatedHeaderErrorat the empty payload (but an IPv4 one with no TCP options that carries Ethernet's padding hands TLS 6 zero bytes, since the walk does not yet honour IPv4's Total Length, #235, and raisesInvalidFieldErroratcontent_type), and a segment of more than 29 records exceeds the defaultmax_depth, which valid traffic reaches: the smallest protected TLS 1.3 record is 22 bytes (5 of header, 1 of inner content type and a 16-byte AEAD tag around empty Application Data, RFC 9846 §5.2), or 14 with TLS_AES_128_CCM_8_SHA256's 8-byte tag, so 30 of 22 bytes take 660 bytes of a segment. Accessors parse the fragment on demand, never indecode():handshake_type(the first byte of a non-empty Handshake record's fragment, ciphertext for TLS 1.2's encrypted Finished, which the record layer cannot tell apart),client_hello, aTLSClientHello(legacy_version,random,legacy_session_id,cipher_suitesandlegacy_compression_methodsraw, andextensions, a tuple ofTLSExtension(type, data),Nonefor a ClientHello with no extensions block and()for an empty one), andserver_name, the first host_name of the server_name extension decoded as ASCII,Nonewithout one; a record holding less than the ClientHello's length raisesTruncatedHeaderError, and a length inside it that overruns, a session ID over 32 bytes, bytes after the extensions, or a malformed, empty or non-ASCII server name raiseInvalidFieldError, both withfield="fragment"and anoffsetwithin it, inside the server_name extension too. The ClientHello is recognized by the fragment's first byte alone, so a TLS 1.2 encrypted Finished whose ciphertext starts with 1 makes both accessors raise rather than answerNone. Display helpers name the content type, version ("TLS 1.2"), handshake type and extension type as RFC 9846 and the RFCs that assign them do (every extension type RFC 9846 §4.3 lists, and seven more a ClientHello commonly carries), GREASE (RFC 8701) included, and say "unknown (n)" otherwise. Only the first handshake message of a record is looked at: a handshake message fragmented across records, or several coalesced in one, is not reassembled or split. A ClientHello larger than one segment, such as Chromium's with its X25519MLKEM768 key share, makes a strict walk raiseTruncatedHeaderErrorat its first segment andInvalidFieldErrorat the next, which begins inside the record; its SNI comes from reassembling the client's stream and decoding that, or, opt-in, from peeking its first segment withpeek_server_name()(below), andTLS.decode()has no lenient partial-hello mode. Under Encrypted Client Hello the SNI read is the outer ClientHello's. Only 443 is registered: 853, 465, 993, 995 and 8443 needdecode_as. DTLS and QUIC (UDP 443) are not decoded.peek_server_name(): the SNI host name from a ClientHello's first segment, opt-in (#285). A ClientHello larger than one TCP segment, such as Chromium's 1738-byte one with its X25519MLKEM768 key share, gives no SNI to a per-packet walk:TLS.decode()raisesTruncatedHeaderErrorat its first segment. The newnetprotocols.peek_server_name(data)(alsonetprotocols.layer7.peek_server_name) reads from a prefix instead:datastarts at a record header, as a segment's payload does, and may end anywhere, and the ClientHello is walked as far as the bytes go, the first record at most, reusing the strict parsers. It returns aTLSServerNamePeek, a frozen value withcompleteandserver_name(a name only withcomplete, and never empty), and one of three outcomes: found (complete, the name, once the whole server_name extension is present), absent (complete,None: the first record carries no host_name, because it is not a ClientHello, or the bytes show it names no host: no extensions block, the block walked to its end without server_name, or a list with no host_name) and not reached (notcomplete,None: the bytes, or the first record, ended first). Absent speaks for the first record only: a ChangeCipherSpec and then a ClientHello with a name in one segment, as TLS 1.3's middlebox compatibility mode sends after a HelloRetryRequest (RFC 9846 Appendix E.4), is absent, asTLS.server_nameisNonefor that first record; to look past whole records,TLS.decode()the first and peekdata[tls.header_len:]. Not reached is not "no SNI": reassemble the stream for certain. Under Encrypted Client Hello a found name is the outer ClientHello's, the client-facing server'spublic_name, as forTLS.server_name. A prefix that ends before the answer is known, inside the record header, the Random, a length, an extension header or the name, is not reached, and where a prefix ends never by itself causes a raise; bytes present that are malformed raise the strict path'sInvalidFieldError, the record guard's (content_type,legacy_version,length) or the ClientHello's (field="fragment"), with the sameoffset,expected,actualand message. A ClientHello fragmented across records is read to the first record's end, never joined to the next. A complete answer holds for every longer prefix and equalsTLS.decode(record).server_namewherever that answers; nothing is re-encoded, noTLSis built, and the work is bounded bylen(data). Measured: curl's, gnutls-cli's andopenssl s_client's ClientHellos fit one segment, so the answer is always complete; Chromium shuffles its extensions, and its server_name ends inside the first 1448 bytes for 54.42% of orders (54.45% and 54.40% over 100,000 permutations of each captured hello), found in the first captured connection's first segment and not reached in the second's.TLS.decode()'s strict contract is unchanged, and so is the boundary: no cryptography and no handshake beyond the ClientHello's fields.
- The encode benchmark compared unlike workloads, and so did the "faster than dpkt at re-encoding" claim built on it (CodeRabbit on #296).
scripts/benchmark_encode.pytimedbytes(Ethernet.decode(FRAME))for netprotocols, which re-encodes the 14-byte Ethernet header only, againstbytes(dpkt.ethernet.Ethernet(FRAME)), which serializes the whole Ethernet/IPv4/UDP frame (and fills a zero IPv4 checksum as it does). It now re-encodes the same whole frame in every library,bytes(decode_frame(FRAME))for netprotocols, from a frame all three decode fully in strict mode on ports none dispatches on, with valid checksums precomputed, and asserts before timing that each output equals the frame byte for byte. The README's "4.2× faster than dpkt at re-encoding" is now 1.3× on a whole frame (1.34×, median of three pinned runs); every earlier figure indocs/CLAIMS.md1.3, 5.3× at v1.3.0 through 4.15× for 2.8.0's first measurement, timed a header against a frame, and is labelled as not like for like there (on one machine: 4.14× as benchmarked, 1.39× on the whole frame, 1.17× on the Ethernet header alone).
- Every comparative number the README quotes was re-measured for this release (Rule 4 of
docs/CLAIMS.md), on the 394-frame corpus and the machine and method 2.7.0 used, againstdpkt 1.9.8andscapy 2.8.0: dpkt decodes the corpus 1.51× faster (from 1.37×; it stops at TCP on the new TLS frames, 2.04× there) and netprotocols is 3.3× ahead of scapy; encode is 1.34× ahead of dpkt on a whole Ethernet/IPv4/UDP frame, after the benchmark was corrected (see Fixed; the 4.15× this entry first quoted compared a header with a frame); a warm import takes 55.2 ms againstscapy.all's 235.3 ms (4.3×); the wheel is 285.1 KiB, 9.5× smaller than scapy's; and netprotocols decodes deeper than dpkt on 175 of 394 frames. TLS's dispatch on port 443 makes the strict walk reject 5tcp_https.pcapsegments that do not begin a record. Also re-checked: CLAIMS 1.7's ten-project CI audit (still none gates; pcapkit now runs a weekly benchmark that compares nothing), 3.1's import simulation withdpkt 1.9.8,pypacker 5.4andscapy 2.8.0pinned, and 4.1's dpkt dates; §7.1 counts all 21 protocols on #170's list as released. README's roadmap names Tier 5 as 2.8.0. - #170's competitor protocol survey, re-run against the current PyPI releases and recorded as a claim (part of #197). New
docs/CLAIMS.md§7.1 repeats the module-list survey #170 built its five tiers from, one row per item on its list, againstdpkt 1.9.8,scapy 2.8.0andpypacker 5.4(each the latest release on 2026-11-01, named with its upload date and sha256): all 21 decode onmaster, 15 of them in 2.6.0 and the six of Tiers 4 and 5 (NTP, TFTP, RADIUS, STUN, HSRP, TLS) merged but unreleased, so the claim isVERIFIEDformasterandGATED ON#174/#175 for a release. scapy 2.8.0 decodes all 21 (eight only afterload_contrib()orload_layer()), dpkt 1.9.8 19, one in part (no VXLAN or LLDP; TLS records with no server_name decoding) and pypacker 5.4 17, three in part (no IP-in-IP, since it dispatches protocol 41 but not 4, and no VXLAN, MPLS or CDP; an IPv6 AH header its extension-header walk sizes in 8-octet units rather than RFC 4302's (Payload Len + 2) × 4, which agree only at a Payload Len below AH's 12-octet fixed part, mis-framing every valid AH's ICV and everything after it, anLLCclass its Ethernet never reaches and whose non-SNAP path drops the SNAP field yet returns a header length of 8, not 3, reading every non-SNAP PDU, STP's included, 5 bytes late, and TLS with no server_name decoding), a partial cell counting toward the total and meaning one that lacks the feature the row's title names (TLS's server_name) or mis-frames the protocol's own header (pypacker's AH and non-SNAP LLC); how far a decoder goes beyond that, which message bodies, versions, formats or optional fields it covers, is not scored, since #170 counted modules, and dispatch is scored only in the IP-in-IP (#177, IP protocol 4) and LLC / SNAP (#188, the 802.3 Length) rows, whose issues are that dispatch. A "yes" is therefore a claim about a module, not its depth, and §7.1 names the depth gaps known and left unscored: dpkt's and pypacker's OSPF and PIM decode the common header only (no Hello, LSA header or Join/Prune), dpkt's VRRP is v2 over IPv4 only and pypacker's the 8-octet v2 header with its addresses undecoded (scapy has VRRPv3 and IPv6), their STUN has RFC 3489's generic attributes and no XOR-MAPPED-ADDRESS (scapy's contrib hasSTUNXorMappedAddress), all three decode a 1-octet LLC Control only where #188 asks for 1 or 2, and all three STPs one fixed 35-octet BPDU, with no Topology Change Notification short form or RSTP Version 1 Length; of the competitors only scapy has released since #170 opened, and none of 2.8.0's new modules is on the list. The newscripts/survey_protocols.pyreproduces the table: stdlib-only and static, it runs regular expressions over the unpacked releases' source files as text, imports and executes none of them, and prints the file and class behind every "yes" and "partial" and, behind every "no", a class or handler pattern that matches none of the package's files; a check whose file is missing fails rather than passes. It also prints the eleven protocols all three decode and netprotocols does not export (PPP, PPPoE, IEEE 802.11, Radiotap, Linux cooked capture, Cisco DTP, ATA over Ethernet, RTP, Diameter, SMB, Portmap), a list swept from dpkt's and pypacker's module lists and checked against scapy's rather than recalled, recorded as a survey and not a roadmap. A status audit of every claim for #101 relabels 1.1-1.6VERIFIED for 2.6.0andNEEDS RE-MEASUREMENTfor the next release, since their figures describe the 2.6.0 tree the README quotes them for, and labelsNEEDS RE-MEASUREMENT, without re-measuring, the two it found stale: 1.7, whose ten-project CI audit dates from 2026-09-04, and 3.1, whose simulation table names no dpkt or pypacker version; the README quotes both as published for 2.6.0 and is left as it is, and each is to be re-run before the next release's README quotes it. 4.1's count of dpkt's open issues, a lookup rather than a measurement, goes from 77 to 81 with the search that returns it; no other figure changed, and the README, which does not quote that count, is untouched.ARCHITECTURE.md's Layout map now names RADIUS among_tlv.py's callers and lists all five of_enums.py's enums (LLCSAPandARPHardwareTypewere missing); every module undersrc/netprotocols/was already in it, and no doc or source comment still calls a shipped protocol unimplemented. tests/fixtures/staging/is ignored and untracked, as the capture workspace it was meant to be..gitignore's "Application-specific" section held.logs/tests/fixtures/staging/, two entries merged by a missing newline, which matched nothing, so every capture PR committed a duplicate of its pcaps understaging/beside the copy folded into the corpus. The line is split into.logs/andtests/fixtures/staging/, and the 41 duplicate staging copies are untracked withgit rm --cached, which leaves them on disk only in the checkout that ran it: a clone that pulls this change deletes them. Nothing is lost, since each is byte-identical to a file still tracked, 40 at the same path undertests/fixtures/andstaging/http.pcapattests/fixtures/http/http.pcap, and every capture script recreatesstaging/when it runs. The sdist, which hatchling builds honouring.gitignore, no longer ships the 41 copies (itstests/fixtures/entries go from 98 to 57). No test or CI job read them: the corpus,tests/test_docs.py's scenario count and the fuzz seeds globtests/fixtures/*.pcapnon-recursively, andscripts/check_fixtures.py tests/fixturesstill reports 394 frames across 36 scenarios. Going forward, asCONTRIBUTING.mdnow says: capture intostaging/, validate withscripts/check_fixtures.py, then copy the validated pcap and any other files the capture script names intotests/fixtures/or the subdirectory it names, and commit only those.- A real TLS capture joins the corpus:
tls.pcap, 15 frames (394 across 36 scenarios), and the session it was cut from outside it.scripts/capture_fixtures_tls.shruns nginx 1.24 (OpenSSL 3.0) with a self-signed ECDSA P-256 certificate generated in a scratch directory (no key is committed) in one netns, and five clients in another, over a veth pair with offload off, each reaching it by host name through a per-netns/etc/hosts: headless Chromium 153 (BoringSSL), curl (OpenSSL 3.0), gnutls-cli 3.8,openssl s_client -noservernameand curl capped at TLS 1.2. The corpus keeps 15 segments of whole records: each client's ClientHello but Chromium's, which spans two segments, the server's TLS 1.3 flights (six records a segment), Chromium's ChangeCipherSpec and Finished, and every data segment of the TLS 1.2 connection, ChangeCipherSpec, the encrypted Finished and the close_notify Alert among them;tests/fixtures/tls/tls_session.pcapkeeps all 108 frames of the six connections. The script reassembles each connection withscripts/extract_http_streams.py'sextract()and asserts the connections, whole records on both sides, each ClientHello's SNI, Chromium's GREASE, X25519MLKEM768 key share, two segments and two extension orders, and every corpus frame's content types.scripts/check_fixtures.pynow checks TLS records on port 443, since TLS has no checksum beyond TCP's (tls-length,tls-empty,tls-ccs,tls-helloand, for the server_name,tls-sni), counts them (tls, one counter per content type,tls-client-hello,tls-server-name) and counts a segment that begins or ends inside a record astls-unchecked, which fails a file (tls-split) unless its name ends_session.pcap, so every corpus segment on port 443 that carries data must be whole records while the session capture keeps Chromium's split ClientHellos;tests/test_tls.pyfails each check on a tampered copy of a captured frame.tcp_https.pcap's seven IPv4 segments now each decode one application_data record, and its five IPv6 bare ACKs from port 443 raiseTruncatedHeaderErrorin a strict walk, as a bare ACK on BGP's port does;tests/test_corpus.pynames them and walks them lax. A ClientHello without its server_name and one whose extensions block is cut are derived from captured bytes intests/test_tls.py.TLSjoins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, seeds from every captured ClientHello, Chromium's two reassembled, and the constructed one, and properties that decode raises only for the guard's first failing reason, that records chain exactly when the next bytes begin like one, that the ClientHello accessors raise only on the fragment, and that built ClientHellos parse back), the truncation contract test, the corpus coverage set and the layout-map check.
TFTP: the Trivial File Transfer Protocol (RFC 1350), with option negotiation (RFC 2347-2349) (#192). UDP port 69 dispatches, best-effort like every port entry, to the newnetprotocols.TFTP(alsonetprotocols.layer7.TFTP), which decodes the 2-byteopcodeand keeps the message after it as rawbody, read on demand by opcode:filename,modeandoptionsfor an RRQ or WRQ,blockanddatafor DATA,blockfor ACK,error_code,error_nameanderror_messagefor ERROR, andoptionsfor an OACK (opcode 6, RFC 2347), eachNone(()foroptions) where the opcode does not carry it;opcode_namenames the opcode. Strings are zero-terminated rather than length-prefixed, so they are split withbytes.find, not the shared TLV walker, and read as ASCII with any other byte as a backslash escape. Options are(name, value)string pairs in wire order;option(name)matches a name in any case (RFC 2347), andblksize(RFC 2348),timeout,tsize(RFC 2349) andwindowsize(RFC 7440) read their value as a number, orNoneif it is absent, not decimal or over 20 digits (leading zeros aside; 20 hold any 64-bit size, andint()would raiseValueErrorpast 4,300). TFTP has no length field and the walk does not trim to UDP's (#235), so each opcode ends where its structure does and leaves the rest undecoded,bytes(TFTP.decode(x)) == x[:header_len]: an ACK after 4 bytes (an untagged Ethernet frame over IPv4 with no options pads it with 14 zeros), an ERROR at its message's zero byte, a request or an OACK after its last whole option pair (a zero byte where a name would start ends the options, so padding after whole pairs is left undecoded, and an option cut short is left undecoded with it). Without the UDP length (#235) a trailer holding a zero byte can still be read as option bytes: after a name with no value, the trailer's first zero byte ends that value (padding decodes(name, "")and gives up one byte), and after whole pairs an FCS holding a name, a zero byte, a value and a zero byte (12 00 34 00) reads as one more pair. DATA cannot, and itsdataruns to the end of the buffer, a trailer included.decode()raisesInvalidFieldErrorfor an opcode other than 1-6 (65,530 of 65,536 two-byte prefixes, so a wrong port guess is almost always rejected) andTruncatedHeaderErrorfor a mandatory field cut short: a block number or error code under 2 bytes, or a filename, mode or error message with no terminating zero byte. Dispatch reaches the request only. A client sends its RRQ or WRQ to port 69, but the server answers from an ephemeral port of its own, and the rest of the transfer runs between two ephemeral ports (RFC 1350 §4), which no port table can name: a stateless walk stops at UDP for every DATA, ACK, OACK and ERROR. A caller following the transfer takes the server's port from its first reply and walks withdecode_as={"udp.port": {port: TFTP}}, which covers both directions, or callsTFTP.decode()on the UDP payload.RADIUS: Remote Authentication Dial In User Service (RFC 2865, RFC 2866, #193). UDP ports 1812 (authentication) and 1813 (accounting) dispatch, best-effort like every port entry, to the newnetprotocols.RADIUS(alsonetprotocols.layer7.RADIUS), which decodes the 20-byte header intocode,identifier,lengthand the 16-byteauthenticator, kept raw, and keeps the attributes the Length covers as rawattributes, sobytes(RADIUS.decode(x)) == x[:header_len]. The Length decides the packet's extent: below 20 raisesInvalidFieldError(field="length",offset=2), past the bufferTruncatedHeaderError(RFC 2865 §3 discards a packet shorter than its Length), and bytes after it, padding by §3 or an FCS, are left undecoded, though since the walk does not yet bound a layer by UDP's length (#235), a Length that overstates the datagram takes trailing bytes such as an FCS as attributes instead of raising; RFC 2865's 4096-byte ceiling is not enforced, since RFC 7930 lifts it for TCP and TLS. A random datagram to either port is rejected about 99.6% of the time (281 of 65,536 Length values accepted for a 300-byte payload), by the Length alone; the Code is not checked, andcode_namenames the codes of RFC 2865, RFC 2866, RFC 5997 (Status-Server) and RFC 5176 (Dynamic Authorization), not every code IANA assigns.parsed_attributeswalks the attributes on demand with the shared_tlv.walk_kind_length_value(a Type byte and a Length byte that counts the two, no lone-byte types, no terminator) intoRADIUSAttribute(type, data), raisingInvalidFieldErrorfor a Length below 2 or one that runs past the packet, never fromdecode().RADIUSAttribute.type_namenames the attributes of RFC 2865 §5, RFC 2866 §5 and RFC 3579 §3, and RFC 2869's Event-Timestamp (55), Connect-Info (77), Acct-Interim-Interval (85) and NAS-Port-Id (87), and gives"unknown (n)"for any other;valuedecodes User-Name (1) as UTF-8 text, NAS-IP-Address (4) and Framed-IP-Address (8) asIPv4Addressand NAS-Port (5) as an integer, gives User-Password (2) and Vendor-Specific (26) as their raw bytes, and isNonefor every other type;RADIUS.user_name,nas_ip_address,nas_portandframed_ip_addressread the first of each. Nothing that needs the shared secret is computed or verified: the Request Authenticator of an Accounting-Request, Disconnect-Request or CoA-Request and the Response Authenticator of a reply, the Message-Authenticator (RFC 3579 §3.2), and the hiding of User-Password; vendor attributes inside Vendor-Specific are not decoded. The legacy ports 1645/1646 and RFC 5176's 3799 are not registered (decode_asreads them).STUN: Session Traversal Utilities for NAT (RFC 8489, and RFC 5389, which it obsoletes; #194). UDP and TCP port 3478 now dispatch, best-effort like every port entry, tonetprotocols.STUN(alsonetprotocols.layer7.STUN), which decodes the 20-byte header intomessage_type,magic_cookieandtransaction_idand keeps the attributes raw, padding included, asattributes, sobytes(STUN.decode(x)) == x[:header_len];lengthislen(attributes), not a field. The 14-bit Message Type stays one field, and accessors split the class and method interleaved in it (message_class,method,class_name,method_name,message_type_name, e.g. "Binding Success Response").decode()verifies the magic cookie (0x2112A442,STUN.MAGIC_COOKIE) and rejects a message without it withInvalidFieldError(field="magic_cookie"), so an RFC 3489 message, whose 16-byte transaction ID takes the cookie's place, is not decoded; it also rejects nonzero top two bits ("message_type", which also turns TURN ChannelData away) and a Message Length that is not a multiple of 4 ("length"), and raisesTruncatedHeaderErrorfor a Length past the buffer. Over random payloads to port 3478 every walk stopped.parsed_attributeswalks the attributes on demand asSTUNAttribute(type, value)through the shared TLV walker, which gains a privatealignparameter for STUN's 4-byte padding, and raisesInvalidFieldErroron a malformed list;STUNAttributenames IANA's attribute types (type_name), says which are comprehension-required, reads an address in the clear (address), and re-encodes zero-padded as RFC 8489 §14 sends it, while padding of any other value, which RFC 5389 §15 allowed, survives a decode-encode round trip. The other accessors never raise, reading the attributes up to the first malformed one:attribute(kind)(the first of duplicates),mapped_addressandxor_mapped_address(STUNAddress(family, port, address), the latter un-XORed with the cookie, and over IPv6 the cookie and transaction ID, leaving the wire bytes untouched),xor_address()for TURN's other XOR-encoded addresses,software,error_code(300-699,Nonefor a Class outside 3-6 or a Number above 99, which RFC 8489 §14.8 rules out) anderror_reason,unknown_attributes,message_integrity(the raw HMAC-SHA1, unverified: it needs the credential's key) andfingerprint. Over TCP, where messages follow one another with no framing but their Length (RFC 8489 §6.2.2), each message decodes as its own layer andSTUN.next_protocol()answersSTUNwhile the next 8 bytes begin like a message, as BGP does; as for BGP, a segment of more than 29 messages exceeds the defaultmax_depth, and a 1448-byte one can hold 72 bare 20-byte headers (a largermax_depthdecodes the rest, and so does walking on frompacket.consumedwithstart=STUNas many times as it takes: the 72 take three walks). TLS/DTLS (port 5349), RFC 6544 framing and ChannelData are not decoded.- STUN's FINGERPRINT in
compute/verify/Packet.with_checksums().compute(stun)is the IEEE CRC-32 (binascii.crc32) of the message up to its FINGERPRINT attribute, the header's Length already counting it, XORed with0x5354554E(RFC 8489 §14.7, RFC 5389 §15.5;ipandpayloadignored), and raisesInvalidFieldErrorunless the last attribute is a 4-byte FINGERPRINT.verify()accepts a message with no FINGERPRINT, as it does a GRE header without the C bit, and fails one whose FINGERPRINT is not last. No one field says whether a message has one, so it has none only when its attributes walk whole, none of them a FINGERPRINT, and its last 8 bytes do not begin like one: a corrupted Length earlier in the list, which would end the walk short of the FINGERPRINT or fold it into a longer value, fails rather than reading as a message without one.with_checksums()rewrites the attribute's value and leaves MESSAGE-INTEGRITY alone; it now carries a rebuilt layer's decode context acrossdataclasses.replace(), which resets it, so the first of two STUN messages in a TCP segment still names the second innext_protocol().compute()andverify()were restructured to stay at radon B (8) and A (5): the checksums that cover only the layer's own bytes (IPv4, IGMP, CDP, OSPF, STUN) share one helper, and the "carries no checksum" rules (UDP over IPv4 at 0, GRE without the C bit, OSPF under cryptographic authentication, STUN without FINGERPRINT) another. NTP: the Network Time Protocol, NTPv4 (RFC 5905) and NTPv3 (RFC 1305) (#191). UDP port 123 dispatches, best-effort like every port entry, to the newnetprotocols.NTP(alsonetprotocols.layer7.NTP), which decodes the 48-byte header (RFC 5905 §7.3) intoleap,version,mode,stratum,poll,precision,root_delay,root_dispersion,reference_idand the four timestamps,reference_timestamp,origin_timestamp,receive_timestampandtransmit_timestamp, each the raw wire value (Poll and Precision signed log2 seconds, Root Delay and Dispersion the 32 bits of a 16.16 fixed-point number, timestamps 32.32 seconds since 1900), and keeps everything after it as rawbody, sobytes(NTP.decode(x)) == x. Display properties convert alongside without replacing the raw fields:reference_time,origin_time,receive_timeandtransmit_timegive an aware UTCdatetime(the module'sntp_to_datetime()andntp_to_unix()convert any timestamp), reading a timestamp whose top bit is clear as era 1, from 2036-02-07T06:28:16Z, as RFC 4330 §3 does, and 0, which RFC 5905 §6 reserves for an unknown time, asNone;root_delay_seconds, signed below version 4 as RFC 1305 and RFC 2030 define it and unsigned for NTPv4 as RFC 5905's short format is (so0xffff0000is -1.0 s in NTPv3 and 65535.0 s in NTPv4),root_dispersion_seconds, unsigned (both assume NTPv2-4's meanings and do not apply to NTPv1, whose second and third words are other fields),poll_secondsandprecision_seconds;leap_name,mode_nameandstratum_name(RFC 5905 Figures 9-11);kiss_codefor a stratum 0 Kiss-o'-Death (§7.4); andreference_id_str, ASCII at stratum 0 and 1 and a dotted IPv4 address from stratum 2. NTP has no length field and the walk does not trim to UDP's (#235), so the accessors split the body without raising:extension_fields, NTPv4's RFC 7822 fields asNTPExtensionField(type, value)(type_namegives the names IANA's registry has since RFC 9748, the NTS types of RFC 8915 and 0x2005's UDP Checksum Complement, says "Private or Experimental Use" for the 0xF000-0xFFFF range RFC 9748 reserves, where chrony's 0xF323 falls, and "unknown" with the hex value otherwise), until what is left has a MAC's length;mac, anNTPMAC(key_id, digest)of 4 (a crypto-NAK, RFC 5905 §9.2), 20 (MD5 or AES-128-CMAC, RFC 8573) or 24 (SHA-1) bytes, or 12 below version 4 (RFC 1305's DES), never verified; andremainder, anything else, such as a field a snap length cut. A 4-byte Ethernet FCS after a plain message has a crypto-NAK's length and reads as one, which only the UDP length could prevent. Against a wrong port guess,decode()rejects a version outside 1-4 and then modes 6 and 7 (InvalidFieldError,field"version"or"mode"), which 62.5% of random datagrams fail; it judges the first byte before the length, so a message shorter than 48 bytes raisesTruncatedHeaderErroronly when its first byte passes, or when it is empty. Construction accepts them. Mode 6 and 7 control messages (RFC 9327's mode 6 fromntpq, ntpd's private mode 7 fromntpdc) have their own header and are deliberately not decoded, so a strict walk raisesInvalidFieldErroron that traffic, whatever its length; walk it withlax=True, which stops at UDP withstopped_byset. A typed way to take port 123 out of dispatch for one walk, and decoding mode 6, are planned follow-ups. NTPv1 (RFC 1059) shares the header only by position: it has no Mode field, so its messages decode as mode 0, reserved.HSRP: Cisco's Hot Standby Router Protocol, HSRPv1 (RFC 2281) (#195). UDP port 1985 dispatches, best-effort like every port entry, to the newnetprotocols.HSRP(alsonetprotocols.layer7.HSRP), which decodes the 20-byte message (RFC 2281 §5.1) intoversion,opcode,state,hellotime,holdtime,priority,group,reserved,auth_data(the 8 bytes of clear-text Authentication Data, raw) andvirtual_ip(dotted-decimal), sobytes(HSRP.decode(x)) == x[:20]; Hello, Coup and Resign share the layout and differ in the Op Code alone. Display properties:opcode_nameandstate_name(Initial, Learn, Listen, Speak, Standby, Active;"unknown (n)"for a value only construction can give),password(the Authentication Data with its NUL padding stripped,b"cisco"by default),auth_data_str(that text when printable, hex otherwise),is_default_authandvirtual_mac, the group's well-known00:00:0c:07:ac:XXaddress (§6.1). The message is always 20 bytes, so whatever follows it, an FCS or the MD5 Authentication TLV some Cisco releases append (not decoded), is left undecoded. Against a wrong port guess,decode()rejects a Version other than 0, an Op Code other than 0-2 and a State §5.1 does not list (InvalidFieldError, judged in that order before the length), which random bytes pass 18 times in 2^24; construction accepts them. The guard is also what keeps two other kinds of message on port 1985 from being misread as HSRPv1: HSRPv2, whose first byte is a TLV type, is rejected atversion, and Cisco's Op Code 3 interface-state Advertise atopcode. Neither is decoded, so a strict walk raises on them: walk withlax=True. Decoding HSRPv2 is a possible follow-up.
- Transport checksums and flow keys use the final destination behind an IPv6 Routing header (RFC 8200 §8.1, #236). The pseudo-header of a TCP, UDP, ICMPv6, VRRPv3 or PIM checksum over IPv6 used
ip.dst, which on a packet in flight behind a Routing header withsegments_left > 0is the next hop, socompute()gave the wrong value,verify()called a correct packet corrupt, andPacket.with_checksums()would write the wrong one;flow_key()keyed the two directions of a source-routed flow differently.checksum.compute(),checksum.verify()andflow.flow_key()take a new keyword-onlyrouting: IPv6Routing | None = None, andPacket.with_checksums()andPacket.flow_key()pass the lastIPv6Routingwithsegments_left > 0between the nearest IP header and the transport, since a receiver skips one with none left (RFC 8200 §4.4 for unrecognized types, and each type's own processing rules: RFC 2460 §4.4, RFC 6554 §4.2, RFC 8754 §4.3) and RFC 8200 §4.1 says each extension header "should occur at most once" (a Routing header before an inner IP header, as in a tunnel, does not apply to it). Withroutinggiven, IPv6 and segments left, the address is the newIPv6Routing.final_destination(dst): the last address of type 0 (RFC 2460 §4.4) and the Home Address of type 2 (RFC 6275 §6.4); for type 3 (RFC 6554 §3) the last entry, rebuilt from the firstCmprEoctets ofdstand the octets the header carries,Padexcluded; for type 4 (RFC 8754 §2) Segment List[0]. It returnsNonefor another routing type or data of the wrong shape, and the address staysip.dstthen; it staysip.dsttoo with no segments left, which the method itself does not check (it ignoressegments_left), and over IPv4. It never raises and works on a layer decoded from amemoryview. Callers that pass noroutingbehave as before.IPv6Routing.segmentsstill returnsNonefor types 3 and 4. - SCTP's zero-tail scan no longer copies the trailer (#257). The chunk walk behind
SCTP.decode()andSCTP.parsed_chunkschecks that what follows the last chunk is all zero bytes; onbytesinput it sliced the rest of the buffer first, so a direct decode of a packet with a long trailer allocated a copy of it. The scan now reads through amemoryview, as CDP's does, and peak memory stays flat whatever the trailer's length. Results are unchanged. Inside a walk the frame bounds the trailer, so this mattered only for a direct decode.
- Every comparative number the README quotes was re-measured for this release (Rule 4 of
docs/CLAIMS.md), on the 379-frame corpus Tier 4 grew from 293 (35 scenarios, from 30), againstdpkt 1.9.8andscapy 2.8.0, on a different machine from 2.6.0's (an Intel Core i7-1355U, CPython 3.12.12, every run pinned to one performance core), so only same-machine runs against the 2.6.0 tree attribute a change to the code. dpkt decodes the corpus 1.37× faster (1.35-1.43× over three runs; the README moves from 1.3× to 1.4×) and netprotocols stays 3.4× ahead of scapy. The rise comes from the new frames: dpkt 1.9.8 has TFTP, RADIUS, STUN, NTP and HSRP modules, but its UDP and TCP never dispatch on a port, so on Tier 4's 86 frames it stops at UDP (at TCP for STUN's two TCP segments) and reads 1.48× faster. On the 293 frames the 2.6.0 tree shares, alternating runs read their medians within 1% (lower in 4 of 6 pairs), so Tier 4 did not measurably slow them; the Tier 2 routing captures (1.63×, so "about three fifths" of netprotocols' time, from "two thirds") and 2.4.0's 140 frames (1.12×, from 1.14×) read the same on the 2.6.0 tree on this machine. Decode depth: deeper on 153 of 379 frames, from 94 of 293, the 59 new all Tier 4 frames dpkt leaves as raw UDP or TCP payload, which README now says. Encode is 4.10× ahead of dpkt (from 4.66×; Tier 4 did not touch the encode path, and the 2.6.0 tree reads 4.27-4.69× on this machine), import 56.7 ms with cached bytecode, as an installed package has it (eight more modules, about 5 ms against the 2.6.0 tree) againstscapy.all's 241.7 ms (4.3×, from 4.9×); cold, netprotocols' and the installed packages' modules compiled from source, 99.1 ms against 552.2 ms (5.6×), about 12-15 ms more than the 2.6.0 tree, and the wheel is 266.9 KiB, 10.1× smaller than scapy 2.8.0's 2.63 MiB. The benchmark baseline is not re-recorded (#251). 1.7's CI audit, 3.1's simulation and 4.1's dpkt last-commit date were not re-checked and are left for 2.8.0 (#175). - A crafted HSRP capture joins the corpus:
hsrp.pcap, 12 frames (379 across 35 scenarios). No open-source router speaks HSRP, soscripts/capture_fixtures_hsrp.shcrafts it with Yersinia 0.8.2, whose HSRP attack 0 sends one raw message per invocation with every field set from the command line, from one netns over a veth pair, and captures it in another: in group 1 (virtual IP 10.9.195.254, the default authentication datacisco) R1 and R2 contend in Speak, R1 becomes Standby and then Active and R2 Standby, R1 resigns, R2 becomes Active, and R3, at priority 200, preempts it with a Coup; in group 2 (virtual IP 10.9.195.253, the configured passwordspark) R4 is Active and R5 Standby — 10 Hellos, 1 Coup and 1 Resign, all with TTL 1, every IPv4 and UDP checksum verifying. Yersinia builds every byte of each frame and the script pins the source MAC addresses, so a re-capture is byte for byte the same but for its timestamps; the script asserts the frames one by one. The capture is this repository's own, under its MIT license.scripts/check_fixtures.pynow checks every HSRP message's fields, since HSRP has no checksum (hsrp-length,hsrp-port,hsrp-version,hsrp-op-code,hsrp-stateandhsrp-holdtime, and, as corpus conventions rather than RFC 2281 rules,hsrp-reservedandhsrp-auth-data), and counts them (hsrp,hsrp-hello,hsrp-coup,hsrp-resign);tests/test_hsrp.pyfails each check on a tampered copy of a captured frame. No router's state machine sent the capture, sotests/test_hsrp.pyalso builds, as constructed frames, an exchange modelling behaviour reported for Cisco routers (TTL 2 where RFC 2281 says 1, the group's virtual MAC address as the Active router's source, timers moving from 3 s / 10 s to 5 s / 15 s on becoming Active, a Coup from Listen preempting the Active router and the Resign it draws), and what neither holds: the Initial and Learn states, HSRPv2, an Op Code 3 Advertise, the MD5 Authentication TLV and trailers. Its unit tests and the fuzz seeds are built from bytes rather than cut from the capture.HSRPjoins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, and properties that decode raises only for the guard's first failing reason and then the length, that every accessor is total, and that trailing bytes stay out of the message), the contract tests (truncation, and trailers under strict and lax walks) and the corpus coverage set. - A real NTP capture joins the corpus:
ntp.pcap, 17 frames (367 across 34 scenarios, withradius.pcapandstun.pcap).scripts/capture_fixtures_ntp.shruns a chronyd 4.5 server (local stratum 8) in one netns and clients in another, over a veth pair, through eight scenarios — ntpdig (ntpsec) plain and with an MD5 and a SHA-1 symmetric key, chronyd as an NTPv3 client, with chrony's experimental extension field and with NTS, a chronyd symmetric active peer before and after it synchronizes, and a broadcast — and keeps a fixed, asserted selection of 17 frames, each request with the answer whose Origin Timestamp matches it. No daemon touches the system clock (-x,-Q).scripts/check_fixtures.pynow walks NTPv4 extension fields (ntp-extension-field) and verifies every NTP MAC with the published test keys (ntp-md5,ntp-sha1), failing on an unknown Key ID (ntp-unknown-key), an extension field Length RFC 7822 forbids (ntp-extension-field), a trailer that is neither a field nor a MAC (ntp-trailer) or a message shorter than its header (ntp-truncated), and counts NTP messages (ntp).NTPjoins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, and a property that decode and every accessor are total and that the extension fields, MAC and remainder tile the body), the contract tests (truncation, and trailers under strict and lax walks) and the corpus coverage set;tests/test_ntp.pyholds ntpdig's Transmit Timestamps against the pcap clock and verifies the four MACs. - A real STUN capture joins the corpus:
stun.pcap, 12 frames (350 across 33 scenarios, withtftp.pcapandradius.pcap), and an RFC 3489 one outside it.scripts/capture_fixtures_stun.shruns coturn 4.6.1'sturnserverin STUN-only mode in one netns and clients in another, over a veth pair with offload off:turnutils_stunclient's Binding Request and Success Response (XOR-MAPPED-ADDRESS, MAPPED-ADDRESS, RESPONSE-ORIGIN, SOFTWARE, FINGERPRINT) and its RFC 5780 request drawing error 420; a script-built request with an unknown comprehension-required attribute drawing 420 with UNKNOWN-ATTRIBUTES; two script-built requests in one TCP segment and their two responses in one segment back; and, against a server requiring the long-term credential mechanism, the 401 challenge and an authenticated exchange with MESSAGE-INTEGRITY both ways. Thestunclient's RFC 3489 exchange goes totests/fixtures/stun/stun_rfc3489.pcap, outside the corpus globs, sinceSTUNrejects it by design. The script asserts the selection message by message.scripts/check_fixtures.pynow verifies every STUN FINGERPRINT with its own bit-at-a-time CRC-32, and every MESSAGE-INTEGRITY with the test credential published intests/fixtures/MANIFEST.md, over UDP and over TCP segments on port 3478, failing a datagram the message does not fill, an unknown USERNAME and a MESSAGE-INTEGRITY-SHA256 it cannot compute. The kernel had no IPv6, so RFC 5769's published test vectors, IPv6 XOR-MAPPED-ADDRESS among them, cover it intests/test_stun.py.STUNjoins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, and a property that decode and every accessor are total and that the parsed attributes tile the raw ones), the truncation contract test, the corpus coverage set and the layout-map check. - A real RADIUS capture joins the corpus:
radius.pcap, 12 frames (338 across 32 scenarios).scripts/capture_fixtures_radius.shruns a FreeRADIUS 3.2.5 server (freeradius -Xon a scratch copy of the packaged configuration, never/etc/freeradiusitself) and radclient in two netns over a veth pair, and asserts the capture frame by frame: a PAP Access-Request answered by an Access-Accept, a wrong password by an Access-Reject, a CHAP Access-Request by an Access-Accept, an Accounting-Request Start and Stop each by an Accounting-Response, and a Status-Server (RFC 5997) by an Access-Accept, every authentication frame with a Message-Authenticator. The test secret and passwords are published in MANIFEST.md;scripts/check_fixtures.pynow verifies, with that secret, each Accounting-Request's Request Authenticator (radius-accounting-authenticator) and the Message-Authenticator of each Access-Request and Status-Server (radius-message-authenticator), checks the Length against the datagram (radius-length,radius-truncated) and that the attributes tile the packet (radius-attributes), and counts RADIUS packets (radius); a reply's authenticators need its request's, in another frame, sotests/test_radius.pypairs and verifies those, unhides each User-Password and checks the CHAP-Password.RADIUSjoins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, and a property that decode raises only for its Length and that the attribute walk tiles the attributes or raisesInvalidFieldError), the contract tests (truncation and a lying Length) and the corpus coverage set. - A real TFTP capture joins the corpus:
tftp.pcap, 33 frames (326 across 31 scenarios).scripts/capture_fixtures_tftp.shruns tftpd-hpa 5.2 (--secure --create) in one netns and the tftp-hpa 5.2 client and curl in another, over a veth pair, and captures six transfers whole, filtering by host rather than by port, so the ephemeral-port DATA and ACK flow is kept: a three-block RRQ ending in a short block, an RRQ ending in an empty block, a WRQ, ERROR codes 1 and 0, and curl's RRQ withtsize,blksizeandtimeout, answered by an OACK. The script asserts the composition frame by frame and checks that each file arrived intact;check_fixtures.pyverifies every UDP checksum without change.TFTPjoins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy over canonical messages of all six opcodes, and a property, seeded from the captured messages and from number options with digit runs pastint()'s 4,300-digit limit, that decode keeps a prefix that round-trips and that every accessor answers), the contract tests (truncation, a string without its zero byte, and padding, an FCS and a cut option after a request) and the corpus coverage set. scripts/check_fixtures.pyuses the final destination behind an IPv6 Routing header too (RFC 8200 §8.1, #259). The fixture checker, the corpus's independent checksum oracle, skipped Routing headers unread and built every IPv6 pseudo-header from the wire Destination Address, so a correct capture taken behind a route with segments left (SRv6, RPL) would have been rejected, and the checker disagreed with the library after #236. It now resolves the final destination with code of its own, sharing none withnetprotocols, by the same rules: types 0 and 2 the last (type 2: the only) address, type 3 the last entry completed with the firstCmprEoctets of the Destination Address, type 4 Segment List[0]; the last Routing header with segments left decides, and an unknown type or data of the wrong shape falls back to the wire address. Every corpus frame checks exactly as before. The pseudo-header of a transport-mode payload under ESP takes the final destination too, as the packet's own; a packet tunnelled inside does not, since the route is not its. New tests intests/test_checksum.pyrun the checker over the #236 vectors, each transport behind each type, ESP transport mode, several Routing headers and the fallbacks (alone, and after a Routing header that does resolve): each frame summed for the address the rules give passes, and the same frame summed for another fails, which for a resolved route is the wire address (the old rule) and for a fallback the address the route would have resolved to.- The nightly mutation run works again, on mutmut 3.8.1. It had two independent breaks. Dependabot's bump of
pytestto 9.2.0 (#261) removedItem._nodeid, which mutmut 3.8.0's pytest plugin read after every test, so the stats phase died on its first test withAttributeError: 'Function' object has no attribute '_nodeid'; mutmut 3.8.1 readsitem.nodeid,uv.locknow pins it, and thedevgroup's floor ismutmut>=3.8.1, since 3.8.0 cannot run with the lockedpytest. Behind that, the new checker tests intests/test_checksum.py(#263) loadscripts/check_fixtures.pyby a path relative to the test file, and mutmut runs the tests from amutants/copy that held noscripts/, so they failed withFileNotFoundError;[tool.mutmut]now listsscriptsinalso_copy(the directory: mutmut 3.8.1 copies a file entry without creating its parent directory). A local run of the workflow's command checked 2481 mutants and found no survivor beyond the two inscripts/mutmut_survivors.txt. - CodeQL no longer reports the RFC-mandated MD5 in
tests/andscripts/as weak hashing of sensitive data.py/weak-sensitive-data-hashingflagged five lines of the pending RADIUS work (#265), each computing the MD5 that RADIUS requires (authenticators, User-Password hiding, CHAP) over published test secrets, withusedforsecurity=False, to verify captured traffic, as the pending STUN work (#267) does for its long-term-credential key; the OSPF and RIP checks escaped only because their variables are namedkey. The CodeQL config cannot scope a query to paths (query-filtersdrops it everywhere,paths-ignoredrops paths from every query), socodeql.yml's analyze step now writes the SARIF without uploading it (upload: failure-only, the action's mode for post-processing), the newscripts/filter_codeql_sarif.py(stdlib only) removes that query's results whose primary location is undertests/orscripts/and logs each one it drops, andgithub/codeql-action/upload-sarif, at the same pinned commit, uploads the rest. The query still runs onsrc/, and every other query on all three. Neither step setscategory, so the analysis keeps the automation id the action derived before (.github/workflows/codeql.yml:analyze/, from the workflow, job and matrix; the CLI writes none without--sarif-category) and existing alerts stay tracked. The filter leaves every other result and every other field untouched, rewrites a file only when it drops something, and fails the job on malformed SARIF; it reads relative,./, percent-encoded,originalUriBaseIds-based andfile:URIs, and filters every*.sarifunder the output directory exactly asupload-sariffinds them (subdirectories included; symlinks, a directory named*.sarifand a file named just.sarifskipped), logging each by its path under the directory. If the filter or the upload fails, the job fails and no new analysis replaces the previous one (upload-sarifcan fail after uploading, while it waits for processing); unfiltered SARIF never goes up.tests/test_filter_codeql_sarif.pyruns it overtests/fixtures/codeql/python.sarif, CodeQL CLI 2.27.3 output unedited but for two scrubbed host details, and synthetic variations of it;tests/test_workflows.pypins the step order, theuploadvalue, the SARIF path the steps share, the lockstep pin, the absent category and the absentcontinue-on-error. Run locally on #265's tree with CLI 2.27.3 and the action's flags, the filter drops exactly the five alerts and nothing else.
MPLS: the MPLS label stack (RFC 3032 §2.1, #187). EtherTypes 0x8847 (EtherType.MPLS, "MPLS") and 0x8848 (EtherType.MPLS_UPSTREAM_ASSIGNED, "MPLS with upstream-assigned label": IANA's names; RFC 5332 §4 retired 0x8848's original "multicast" meaning) now dispatch tonetprotocols.MPLS(alsonetprotocols.layer2.MPLS), from Ethernet, VLAN tags and GRE alike, so MPLS in GRE (RFC 4023) needs no code of its own. OneMPLSlayer holds the whole stack, top first, aslabels, a tuple ofMPLSLabelentries (label,traffic_class— RFC 5462's name for RFC 3032's Exp field —bottom_of_stackandttl, withword,bytes(),is_special_purpose, andlabel_name, the base special-purpose labels named as IANA's registry names them);bottomis the last entry.decode()reads entries until the first with the S bit set, so the stack bounds itself andbytes(MPLS.decode(x)) == x[:header_len]; what follows, Ethernet padding and FCS included, is the labelled packet's. A stack whose S bit never comes raisesTruncatedHeaderError(field="labels",offsetwhere the missing entry would start), in time linear in the buffer, and a deep stack counts once againstmax_depth. Construction requires a non-empty stack with S set on the last entry alone, so every stack that can be built round-trips. MPLS names no payload protocol, sonext_protocol()follows a documented convention: a bottom label of 0 or 2 (IPv4 or IPv6 Explicit NULL) names IPv4 or IPv6, 13 (GAL) and 14 (OAM Alert) stop the walk, and otherwise the first nibble after the stack is read as an IP version, 4 or 6 (RFC 4928 §2), so a pseudowire control word or associated channel header (first nibble 0 or 1, RFC 4385) stops it. The class comes from theethertypetable at 0x0800 or 0x86DD, soregistryanddecode_asoverrides reach the labelled packet;payload_ethertypesays which the convention chose.next_protocol()is handed no bytes, sodecode()records the nibble on the instance outside its comparison and hash, asBGPrecords whether another message follows; a stack built rather than decoded answers from its bottom label alone. The guess fails, as RFC 4928 describes, on an Ethernet pseudowire sent without a control word whose inner destination MAC begins with nibble 4 or 6, which decodes as an IP header; the module docstring says how to walk such a payload explicitly. Since 0x8847 and 0x8848 are now built in, code that registered a different class at either on the default registry (as theregister()examples in 2.5.0'sregistry.py, README.md, ARCHITECTURE.md anddocs/CLAIMS.mddid), or on one built from it withRegistry.from_defaults()orderive(), now raisesRegistryConflictError; passoverride=Trueto replaceMPLS, ordecode_as={"ethertype": {0x8847: ..., 0x8848: ...}}(each key you used) to override it for one walk.LLDP: the Link Layer Discovery Protocol (IEEE 802.1AB), layer 2 (#186). EtherType 0x88CC (EtherType.LLDP, "LLDP") now dispatches tonetprotocols.LLDP(alsonetprotocols.layer2.LLDP) from Ethernet and from a VLAN tag, and the walk ends there. An LLDPDU is a run of TLVs, each a 16-bit header word (a 7-bit Type, a 9-bit Length) and Length bytes of value;LLDP.tlvskeeps every one, in wire order, as anLLDPTLV(type, value)withlengthandtype_name(Wireshark's names for types 0-8 and 127, "unknown (n)" for the reserved 9-126), through the End of LLDPDU TLV, sobytes(LLDP.decode(x)) == x[:header_len]holds by construction. The End TLV bounds the LLDPDU: Ethernet padding, an FCS or anything else after it is left undecoded. An LLDPDU that reaches the end of the buffer without one decodes too, since 802.1AB-2016 made the End TLV optional, as Wireshark's dissector notes (lldpd 1.0.18's receiver still discards one); without an End TLV a trailer is read as TLVs: two or more zero bytes read as an End TLV, and anything else as another TLV or a framing error.decodechecks framing only: a buffer shorter than one TLV header raisesTruncatedHeaderErroras any too-short header does (offset 0, nofield), a later TLV header cut short or a TLV whose Length runs past the buffer raises it withfield="tlvs"and the TLV's offset, and an End TLV with a nonzero Length raisesInvalidFieldError. The mandatory order is reported, not enforced:chassis_id(LLDPChassisID) andport_id(LLDPPortID), each asubtypeand the rawidwithsubtype_name, andttl(anint, its first two bytes) read the first, second and third TLV and areNonewhen that TLV is of another type, an ID's value is not 2 to 256 bytes or the TTL's is shorter than 2 bytes, so none raises;has_mandatory_tlvssays whether all three are there (any subtype passes),is_shutdownwhether the TTL is 0, andtlv(type)finds the first TLV of a type. Subtype numbers follow the IEEE 802.1 LLDP MIBs and the display names Wireshark's dissector. Every other TLV, organizationally specific ones included, keeps its value raw. The walk is local tolayer2/lldp.py;_tlv.walk_kind_length_value, which TCP, IPv4, IPv6 and PIM share, is unchanged. EtherType 0x88CC no longer serves the tests and README as the example of an unknown EtherType; 0x88B5, IEEE 802's Local Experimental EtherType 1, does.LLCandSNAP: IEEE 802.2 LLC and SNAP headers after an IEEE 802.3 Length (#188). An Ethernet or VLAN type/length field of 1500 or less is a frame Length (IEEE 802.3 Clause 3.2.6), andnext_protocol()now answersnetprotocols.LLC(alsonetprotocols.layer2) for it: DSAP, SSAP and a 1-octet (U-format) or 2-octet (I- and S-format) Control, stored with its first octet as the integer's low byte so the format bits are its two low bits. I-format and UI PDUs dispatch on the DSAP through the newllc.dsaptable (registry.TABLE_LLC_DSAP), at DSAP 0x42 only when the two octets after the Control are 0x0000, or fewer than two octets follow (next entry); other formats, such as XID and TEST, end the walk. Accessors:control_format,is_group,is_response,is_raw_ipx,dsap_name,ssap_name,dsap_enum. The newLLCSAPenum holds the IEEE Registration Authority's assigned LSAPs and the global DSAP, with display names.SNAP(OUI and PID, RFC 1042) is a built-inllc.dsapentry, at 0xAA, reached only when the SSAP is 0xAA too and the Control is UI;STP, at 0x42, is the other (next entry). Under OUI 00-00-00 (RFC 1042) or 00-00-F8 (IEEE 802.1H bridge-tunnel) the PID is an EtherType and dispatches throughethertype; under any other OUI it goes through the newllc.snaptable (registry.TABLE_LLC_SNAP), keyed(oui << 16) | pid(SNAP.snap_key). This departs from #188, which recommended reading every PID inethertype: RFC 9542 §3 makes the PID a number the OUI's owner assigns, so CDP (OUI 00-00-0C, PID 0x2000) is not EtherType 0x2000. A Novell raw 802.3 frame (0xFFFF where the SAPs would be: an IPX checksum) decodes as anLLClayer withis_raw_ipxset and ends the walk; that layer's other fields and accessors then read IPX bytes and are meaningless (the fixture's frame reads as an I-format Control 0x1E00, the IPX length). STP (DSAP 0x42) decodes asSTP(next entry), and CDP asCDP(the entry after it).STP: Spanning Tree BPDUs, IEEE 802.1D and 802.1w (RSTP) (#189). LLC DSAP 0x42 (LLCSAP.SPANNING_TREE) now dispatches, for a UI or I-format PDU, tonetprotocols.STP(alsonetprotocols.layer2.STP), the walk's last layer, unless the two octets after the Control are present and not 0x0000: GARP's PDUs, such as GVRP's, share the SAP with Protocol Identifier 0x0001 (IEEE P802.1aq/D1.5++ §14.5 NOTE 1 leaves other Protocol Identifiers to other protocols), and their walk ends atLLC, whatever classllc.dsapholds at 0x42.LLC.decode()records that check on the instance outside its comparison and hash, so equal LLC headers still compare and hash equal; a header built with the constructor ordataclasses.replace()has seen no bytes and dispatches. Fewer than two octets still reachSTP, which reports the truncation. One class decodes the three BPDU Types and branches on the type, as ICMP does: the Configuration BPDU (type 0x00, 35 octets, 802.1D-2004 §9.3.1), the RST BPDU (0x02, 36 octets, §9.3.3: the same fields and a Version 1 Length) and the Topology Change Notification (0x80, §9.3.2), which is the 4-octet prefix alone and decodes as the short form of the class, every field afterbpdu_typeNone. Fields:protocol_id,version,bpdu_type, thenflags,root_priority,root_mac,root_path_cost,bridge_priority,bridge_mac,port_id,message_age,max_age,hello_time,forward_delay(the timers raw, in 1/256 s) andversion_1_length(RST only). The flag accessors answerNonein a type that leaves their bit unused:topology_change(Configuration and RST),topology_change_ack(Configuration only), andproposal,port_role/port_role_name,learning,forwardingandagreement(RST only); the raw octet stays inflags. The two priority octets of a Bridge Identifier are kept whole (802.1D-1998 made all 16 bits a priority) and split as 802.1t does byroot_priority_component/root_system_id_extensionandbridge_priority_component/bridge_system_id_extension; alsoroot_id_str/bridge_id_str(Wireshark's priority/extension/MAC form),port_priority/port_number,*_secondsfor the four timers,bpdu_type_nameandversion_name. The flag bits, port role values and field layout follow the unapproved IEEE 802.1 draft "P802.1aq/D1.5++suggested changes, May 16, 2009" (aq-seaman-merged-bpdu-encoding-0509.pdf, whose Clause 14 merges 802.1D Clause 9 with 802.1Q-2005 Clause 14), except that its §14.4 o) mislabels octets 34-35 as Max Age: they carry Forward Delay, as in Wireshark'spacket-bpdu.cand Linux'sbr_stp_bpdu.c. The type and version names and port role names 1-3 are Wireshark's (packet-bpdu.c, fetched 2026-10-25); role 0, which Wireshark does not name, isUnknown, 802.1D-2004's name for it (802.1Q calls it Master; the draft's §14.2.9 NOTE).header_lenis exactly the type's length: Ethernet padding and an FCS never reach the decoder in a walk (the 802.3 Length bounds the PDU), a directdecode()leaves them undecoded, and the octets of a PDU longer than its BPDU, which a receiver ignores (§14.4 and §14.6 i)3) of that draft), stay after the layer. Cisco PVST+'s SSTP BPDUs, the ones that carry TLVs, travel in SNAP under OUI 00-00-0C, PID 0x010B, not at DSAP 0x42 (Wireshark parses their TLVs only there), and walk as far asSNAP; anllc.snapentry at(0x00000C << 16) | 0x010Bwould reachSTPfrom there. PVST+'s VLAN 1 BPDUs go untagged to the IEEE address, at DSAP 0x42, and decode asSTP(Cisco does not say they carry a TLV; Wireshark parses PVST+ TLVs only under PID 0x010B) (Cisco document 24063, "Troubleshoot Spanning Tree PVID- and Type-Inconsistencies"; the full URL is inlayer2/stp.py's module docstring). A Protocol Identifier other than 0 (on a directSTP.decode(); a walk from LLC DSAP 0x42 does not reach it) and a BPDU Type other than the three raiseInvalidFieldError(field="protocol_id", offset 0, orfield="bpdu_type", offset 3), since neither leaves a layout to read; a buffer shorter than its type needs raisesTruncatedHeaderError(field="bpdu_type"). The version, unused flag bits and a nonzero Version 1 Length are carried verbatim, and a type 0x02 BPDU is laid out as RST whatever its version. MSTP is out of scope: an MST BPDU (802.1s/802.1Q, version 3) decodes as its 36-octet RST prefix, and its Version 3 Length, MST configuration and MSTI messages are left undecoded after the layer, as a version 2 implementation reads them (§14.6 i), and §14.5 d) and e), of the draft). In a walk the 802.3 Length already ends the PDU, but kept raw in the layer they would need an end on a directdecode()too, where only the Version 3 Length could give one, and that field is unreliable on the wire (Wireshark'spacket-bpdu.cnotes a Cisco C3550 release that appears to send it in MSTI-message units, and MST BPDUs that carry a Version 3 Length of 0 and put the length in the format selector octet): read to the end of the buffer instead, they would take in padding and an FCS. In a walk a caller recovers them withframe[packet.consumed : 14 + packet[Ethernet].length](behind one VLAN tag,18 + packet[VLAN].length). The real BPDUs are the corpus's 802.1D ones; RST BPDUs are tested with constructed frames only, since neither the kernel bridge nor any installable package here speaks RSTP.CDP: the Cisco Discovery Protocol, versions 1 and 2 (#190). SNAP OUI 00-00-0C PID 0x2000 now dispatches throughllc.snaptonetprotocols.CDP(alsonetprotocols.layer2), which decodes the 4-byte header (version,ttl,checksum) and the TLVs after it asCDPTLV(type, value), each a 2-byte Type and a 2-byte Length that counts the 4-byte TLV header, kept raw in wire order withtype_namefrom Wireshark's packet-cdp.c (commit 31bf0857, fetched 2026-10-25), sobytes(CDP.decode(x)) == x[:header_len]. Any Version decodes, since the SNAP header says outright that CDP follows. Accessors read the first TLV of their type and returnNonewhen it is missing or malformed:device_id,port_id,software_version,platform(ASCII, a byte outside it as a backslash escape),capabilities(the 32-bit mask) andcapability_names, andaddressesandmanagement_addresses(type 22), lists ofCDPAddress(protocol type, protocol, address, withipfor NLPID 0xCC IPv4 and the 802.2 form of EtherType 0x86DD IPv6), plustlv(type). CDP has no PDU length: in a walk the 802.3 Length bounds it, so padding and an FCS stay out.decodestops early without raising only where every byte left is zero, so zero padding is left undecoded when it is called directly; otherwise a TLV Length below 4 raisesInvalidFieldErrorand 1-3 bytes left after the last TLV raiseTruncatedHeaderError, in a walk too (bothfield="tlvs", at the offset where the TLV would start), as does a TLV that runs past the buffer. Zeros after the last TLV but inside the 802.3 Length are part of the declared PDU, yet a walk leaves them undecoded without raising:consumedstopping short of the Length's end is the only structural signal,verify()(which sums the bytes decoded) fails on them only where the TLVs end at an odd offset on a nonzero byte and the sender summed the whole Length, andscripts/check_fixtures.pyrejects such a frame. Wireshark's packet-cdp.c differs: it stops at a Length below 4 whatever follows, and marks 1-3 bytes left malformed even when they are zero. A nonzero trailer that happens to read as whole TLVs (a 4-byte FCS ending in 0x0004) decodes as phantom TLVs; thereverify()is the check that the bytes decoded are the PDU the sender summed. Wireshark's Port ID length heuristic is not reproduced. The walk ends at CDP.- CDP checksums in
compute/verify/Packet.with_checksums(). The internet checksum of the whole PDU, checksum field zeroed, no pseudo-header (ipandpayloadignored), except that an odd final bytevis added as the low byte of a last word below 0x80 and as0xFF00 + v - 1from 0x80, as lldpd 1.0.18'sframe_checksum()and Wireshark's packet-cdp.c sum it;internet_checksum()alone gives the wrong value for an odd-length PDU whose final byte is not 0x00 (there the two coincide).with_checksums()fills it as it fills IPv4's. Ethernet.is_length/Ethernet.lengthandVLAN.is_length/VLAN.length: whether the rawethertypefield holds an 802.3 Length, and the Length orNone. The field itself is unchanged in type and meaning.
- Ethernet and VLAN dispatch branch on type versus length. A value of 0x0600 or more dispatches through
ethertypeexactly as before; 1500 or less answersLLC(it used to look the value up inethertype, which accepted a key there: registering one, such as 0x0026, a Configuration BPDU's Length, was the only way to decode STP; see the Behaviour change entry below); 1501-1535, which IEEE 802.3 leaves undefined, answersNone. GRE's Protocol Type and a SNAP PID are EtherTypes only and keep the plain lookup. No frame in the 2.5.0 corpus has a type/length value below 0x0600, and every one of them decodes exactly as before. decode_frame()ends every later layer's buffer at the end of the LLC PDU an 802.3 Length gives, so Ethernet zero padding and an FCS after a short PDU reach no decoder and stay pastpacket.consumed. A Length past the end of the frame bounds nothing (a frame a snap length cut decodes what was captured), a tighter bound is never widened by a later one, and a Length shorter than the 3-byte LLC header makesLLC.decode()raiseTruncatedHeaderError. It is the only enclosing length the walk honours; IPv4's, IPv6's and UDP's are not (#235). The hook is private (Protocol._BOUNDS_PAYLOAD,_payload_extent()) while #235 settles a public form.- Behaviour change: an
ethertypeentry at 1500 or less is no longer reached from Ethernet or VLAN. The table accepts any key, as in 2.5.0, but Ethernet and VLAN no longer look a type/length value of 1500 or less up there: they answerLLCfor it, and nothing for 1501-1535 (see the entry above). So a class registered at, say, 0x0026 to decode STP over raw Ethernet is no longer reached from an Ethernet frame. GRE still looks any value up inethertype, so such an entry still answers GRE Protocol Type 0x0026, as in 2.5.0, and the newSNAPlooks a PID under OUI 00-00-00 or 00-00-F8 up there too, so it now also answers an RFC 1042 or 802.1H SNAP PID of 0x0026. RFC 1701's "Current List of Protocol Types" assigns GRE three values below 0x0600, SNA 0x0004, OSI network layer 0x00FE and PUP 0x0200, and an entry at 0x00FE is reached from GRE Protocol Type 0x00FE exactly as before. This dispatch change is inherent to #188's type/length reading. To migrate a raw-Ethernet decoder, register it inllc.dsapunder its DSAP or, for a SNAP protocol, inllc.snapunder(oui << 16) | pid. STP needs no migration: the built-inSTPnow holds DSAP 0x42, the one key that covers what 2.5.0 needed one key per 802.3 Length for (0x0026 for a Configuration BPDU, 0x0007 for a Topology Change Notification, 0x0027 for an RST BPDU, and more for MST BPDUs, whose Length varies); a decoder of one's own goes there withoverride=True, or in a registry of its own (Registry.from_defaults().derive(...), ordecode_frame(decode_as=...)), and is handed, likeSTP, only a PDU whose first two octets are 0x0000, or that holds fewer than two, never GARP's. The decoder is handed different bytes: in 2.5.0 it got everything from the LLC header to the end of the frame, padding and FCS included, and fromllc.dsapit gets the PDU after the LLC header (fromllc.snap, after the SNAP header), ending where the 802.3 Length does, so a migrated decoder must parse from there. The two new tables refuse a key their field cannot carry,llc.dsapone outside 0-0xFF andllc.snapone outside 0 to 2**40 - 1, raising the newInvalidRegistryKeyError(aProtocolError, exported fromnetprotocolsandnetprotocols.registry) fromregister(),register_all(),Registry.derive()anddecode_frame(decode_as=...)(whateverlaxsays).register_all()is not atomic, for this error as for aRegistryConflictError: the keys before the one that raises stay registered. Every other table,ethertypeincluded, accepts any key, as before.
- Every comparative number the README quotes was re-measured for this release (Rule 4 of
docs/CLAIMS.md), on the same machine class as 2.5.0's figures but on the 293-frame corpus Tier 3 grew from 265 (30 scenarios, from 27), againstdpkt 1.9.8andscapy 2.8.0. The headline ratios held: dpkt decodes the corpus 1.33× faster (1.28-1.34× over three runs) and netprotocols stays 3.4× ahead of scapy. The README's sub-claim that the 140 frames of 2.4.0's corpus "are still within 10%" of dpkt no longer holds and is replaced: over sixteen alternating runs of a file-by-file harness, dpkt leads on them by a median 1.14× on this tree against 1.07× on 2.5.0's. Whether Tier 3's type-versus-length dispatch and payload bound cost the old frames anything is not resolved: netprotocols' median over the 265 frames both trees share is 3.3% lower than 2.5.0's (lower in 12 of 16 alternating pairs, with dpkt's own median flat), inside this machine's run-to-run spread of about ±8%, and it was not profiled (#250). On the new MPLS and LLC/SNAP captures the two libraries are level; dpkt does not decode LLDP, so it is about 5× faster on those six frames. Encode is 4.66× ahead of dpkt, import 89.8 ms (from 70.0 ms; the five new modules cost about 15 ms against the 2.5.0 tree run alternately on the same machine) againstscapy.all's 436.2 ms, and the wheel is 220.5 KiB, 12.2× smaller than scapy 2.8.0's 2.63 MiB. Decode depth against dpkt is 94 of 293 frames deeper; of the 15 new, 7 are frames dpkt leaves raw (the six LLDP frames and a VLAN-tagged 802.3 SNAP frame), and 8 are MPLS and SNAP frames on which netprotocols makes the label stack or the SNAP header a layer of its own where dpkt folds it intoEthernetorLLC; STP and CDP are decoded by dpkt too. dpkt cannot decode one frame, the 4-byte STP Topology Change Notification (NeedData), so--depthskips it and every comparison reports dpkt at 292/293.docs/CLAIMS.mdrecords each run, the per-file table, the A/B and the frame-by-frame depth breakdown. scripts/check_fixtures.pychecks RST BPDUs and a Configuration BPDU's flags (#189). Its independent_check_bpdunow knows the RST BPDU (type 0x02, 36 octets, a Protocol Version of 2 or more, which a receiver's validation requires) and counts each type (stp-config,stp-rst,stp-tcn). Its BPDU check covers only the DSAP 0x42 PDUs the library dispatches, UI (either P/F) and I-format; any other Control there (XID, TEST, S-format) is counted (llc-dsap-0x42-control-0xaf, say) and not checked. A UI or I-format PDU whose Protocol Identifier is not 0, such as GARP's, is counted (llc-dsap-0x42-protocol-0x0001) and not checked rather than failed as a malformed BPDU, and an I-format PDU's BPDU is read after its 2-octet Control, as the library reads it. It also holds each BPDU to what its sender must transmit, which a receiver ignores or tolerates: the Flags bits its type leaves unused 0 (six in a Configuration BPDU, bit 8 in an RST BPDU) and an RST BPDU's Version 1 Length 0. Thellc.pcapBPDUs now decode toSTP, and the corpus coverage test requires it; no frame is added, so the corpus counts are unchanged.- The three CDP frames of
llc.pcapnow decode toCDP: the corpus coverage set, the corpus checksum cases (tests/test_checksum.py, in the mutation audit's selection) and the fuzz suites (ALL_PROTOCOLS, a round-trip strategy, accessor and trailer properties) cover it. No frame was added.scripts/check_fixtures.pykeeps its own CDP check, which shares no code with the library. - An IEEE 802.3 LLC/SNAP capture joins the corpus:
llc.pcap, 14 frames (293 across 30 scenarios).scripts/capture_fixtures_llc.shruns two Linux bridges with STP on in two netns and lldpd 1.0.18 in its own UTS namespace, and captures on a bridge port: five kernel-built 802.1D BPDUs (both bridges' Configuration BPDUs, the root's with TC and with TC + TCA, a 21-byte TCN), CDPv1 and CDPv2 from lldpd (and a CDPv1 frame whose odd-length PDU ends in 0xA9: CDP's checksum adds a final byte from 0x80 as 0xFF00 plus the byte less 1, as lldpd'sframe_checksum()and Wireshark's packet-cdp.c do, and the frame shows it is not padded as RFC 1071 pads it and that the- 1matters; only a test,test_cdp_odd_byte_is_lldpds_form, tells that form from adding the byte less 0x100), and six frames the new stdlib-onlyscripts/llc_fixture_frames.pybuilds and sends throughAF_PACKET(RFC 1042 ARP padded to 60 bytes and ICMP-in-IPv4, 802.1H ARP, RFC 1042 ARP behind an 802.1Q tag, Novell raw 802.3 IPX, and a type/length value of 1501). It keeps the first frame of each kind and asserts the composition exactly.scripts/check_fixtures.pynow reads the type/length field as IEEE 802.3 does, after VLAN tags too, holds each Length against its frame (only zero padding may follow a PDU shorter than 46 bytes), checks the LLC Control width, SNAP framing, BPDU and raw IPX lengths, walks the CDP TLVs and verifies the CDP checksum over exactly the PDU, and checks an RFC 1042 or 802.1H payload as its EtherType, IPv4 and ICMP checksums included. - A real LLDP capture joins the corpus:
lldp.pcap, 6 frames (279 across 29 scenarios).scripts/capture_fixtures_lldp.shruns two lldpd 1.0.18 agents, LLDP only, in two netns over a veth pair, each configured from its own file before its first LLDPDU: A with its MAC address as Chassis ID, its interface name as Port ID and a 304-byte custom organizationally specific TLV (which needs the 9th Length bit), B with a locally assigned Chassis ID, its MAC address as Port ID and a TTL of 180. It then changes A's Port ID to a locally assigned value at run time, which makes lldpd send a shutdown LLDPDU for the old one, and stops both agents, which send one each. It keeps the first LLDPDU of each kind (sender, Port ID subtype, shutdown or not) and asserts the six exactly: their Chassis ID, Port ID, TTL and TLV type sequence.scripts/check_fixtures.pychecks LLDPDUs structurally, since LLDP has no checksum: the TLVs must walk to an empty End TLV with only zero bytes after it, the first three must be a well-formed Chassis ID, Port ID and 2-byte TTL that do not recur, and a shutdown LLDPDU must carry nothing else; its ARP and fallback arms move into a_check_non_iphelper so_check_l3does not grow.tests/test_lldp.pyholds the checker to failing tampered copies.LLDPjoins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, an accessor-safety property fed LLDP-shaped buffers, and a padding and trailer property), the truncation and lying-length contract tests and the corpus coverage set; a decode-cost test counts the bytes a 10,000-TLV LLDPDU's walk reads by slicing or copying it whole, and another, withtracemalloc, checks that decoding a 1,000-TLV LLDPDU followed by a megabyte after its End TLV, asbytesand as amemoryview, peaks under half a megabyte of allocation, which a copy of the rest of the buffer at any TLV, over a megabyte, would exceed. Neither bounds per-TLV quadratic work that leaves no large allocation behind, such as rebuilding the TLV list at every TLV. - A captured MPLS fixture joins the corpus:
mpls.pcap, 8 frames (273 across 28 scenarios). The capture host's kernel hasCONFIG_MPLS_ROUTINGoff, soscripts/capture_fixtures_mpls.shhas the kernel send two ICMP echo requests and two UDP datagrams over a veth pair between two netns, offload off, captures them inbound, and thenscripts/mpls_fixture_packets.py(stdlib only) wraps those datagrams in script-built Ethernet headers and label stacks and sends them through anAF_PACKETsocket: one label, two labels, three labels with distinct traffic classes, an Entropy Label Indicator and entropy label, IPv4 and IPv6 Explicit NULL bottom labels (the IPv6 datagram script-built, since the host has IPv6 disabled; the IPv4 Explicit NULL frame zero padded to 60 bytes), EtherType 0x8848 to a multicast MAC, and an Ethernet pseudowire with a control word. The script reads the capture back and fails unless every byte arrived as built, and the capture script fails unless the capture holds exactly those eight frames. A second tcpdump captures the same frames with a 20-byte snap length astests/fixtures/mpls/mpls_snaplen.pcap, outside the corpus globs likebgp/bgp_session.pcap, so truncation is tested on captured frames too: six stacks cut after their first entry, and two whole one-entry stacks whose IPv4 header is cut.scripts/check_fixtures.pywalks each label stack to its bottom entry in its own code and verifies the labelled packet's checksums, IPv4 or IPv6 by the same convention, and the Ethernet frame after the pseudowire's control word; its ARP branch moved into a_check_arphelper beside the new_check_mpls, so_check_l3dispatches the two through a table and stays at radon B.tests/test_mpls.pyholds the checker to failing a flipped byte in each frame's labelled packet. MPLS joins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, accessor-safety and trailer properties), the truncation and memoryview contract tests and the corpus coverage set. - The
register()examples no longer use MPLS's EtherType.registry.py, README.md, ARCHITECTURE.md anddocs/CLAIMS.md§5.5 registered a hypothetical class at 0x8847 as "a protocol this library does not implement", which now raisesRegistryConflictError; they, andtests/test_registry.py's stand-ins, use 0x88B5 ("IEEE Std 802 - Local Experimental Ethertype" in IANA's registry) and aTelemetryclass instead, andtests/test_docs.pyruns each document's example, and the three inregistry.py's docstrings, to check each registers on a free key. README's "Why NETProtocols" now names the corpus its figures were measured on, which this release's re-measurement (the first Development entry) makes the 293 frames the corpus holds at 2.6.0.
VRRPandVRRPv6: the Virtual Router Redundancy Protocol, VRRPv2 (RFC 3768) and VRRPv3 (RFC 5798) (#181). IP protocol 112 (IPProtocol.VRRP, "VRRP") now dispatches tonetprotocols.VRRPfrom IPv4 and to its subclassVRRPv6from IPv6 and its extension headers. One class decodes both versions and branches on the version nibble: the fixed fieldsversion,type,vrid,priority,count_ip_addrsandchecksum, the 16 bits between Count and Checksum kept raw asadver_wordand read through per-version accessors that returnNonewhere the version has no such field (auth_type/auth_type_nameandadver_intin seconds for VRRPv2;reservedandmax_adver_intin centiseconds for VRRPv3;advertisement_intervalin seconds for either), the virtualaddresses, and VRRPv2's 8 bytes ofauth_data(the null-padded password under Auth Type 1, keepalived'sauth_type PASS). The address width depends on the IP family, not on anything in the header, which is why the class comes as a pair:VRRPreads 4-byte addresses andVRRPv616-byte ones, andVRRPv6accepts VRRPv3 only, since RFC 3768 defines VRRPv2 for IPv4 alone. VRRP has no length field, but the version and count give its exact length, which isheader_len, so Ethernet padding and an FCS after the message are left undecoded andbytes(VRRP.decode(x)) == x[:header_len]. A version other than 2 or 3 raisesInvalidFieldError(field="version",offset=0), because the version decides the layout; an unknown type, a priority of 0 (a master resigning), a count of 0 and the reserved bits are carried verbatim. A count, or VRRPv2's authentication data, past the buffer raisesTruncatedHeaderError(field="count_ip_addrs"or"auth_data"). Construction also checkscount_ip_addrs == len(addresses), the authentication data's length against the version (8 bytes or none), and thattypefits its nibble. The walk ends at VRRP. Registering over protocol 112 inip.protoreaches IPv4 only, as for AH's 51;_defaults.FAMILY_SPECIFIC_NUMBERSnow names both.- VRRP checksums in
compute/verify/Packet.with_checksums(). The internet checksum of the whole message with the checksum field zeroed: alone for VRRPv2 (RFC 3768 §5.3.8,ipnot needed), behind the IP pseudo-header with protocol 112 for VRRPv3 over IPv4 and IPv6 (iprequired).payloadis ignored, as for IGMP. Over IPv6 that is RFC 5798 §5.2.8's rule; over IPv4, §5.2.8 cites only RFC 2460's pseudo-header, which is IPv6's, and the IPv4 one is what keepalived 2.2.8 sends by default. RFC 9568 §5.2.8, which obsoletes RFC 5798, leaves the pseudo-header out over IPv4, as keepalived'sv3_checksum_as_v2option does, andverify()returnsFalsefor such an advert. RIP: the Routing Information Protocol, versions 1 and 2 (RFC 1058, RFC 2453, #182). UDP port 520 dispatches, best-effort like every port entry, to the newnetprotocols.RIP(alsonetprotocols.layer7.RIP), which decodes the 4-byte header intocommand,versionandreserved(bytes 2-3: must be zero in RFC 1058 and RFC 2453, RFC 1388's Routing Domain) and keeps everything after it as rawbody, sobytes(RIP.decode(x)) == x.entriesparses the 20-byte entries on demand: a route is aRIPEntry(afi,route_tag,address,subnet_mask,next_hop,metric; RIPv1 zeroes the v2-only fields, which are kept verbatim either way), and an entry with AFI 0xFFFF is aRIPAuthentication(auth_type, the raw 16databytes, andpasswordfor type 2, orpacket_length,key_id,auth_data_lenandsequence_numberfor RFC 4822's type 3), never a route;routesandauthenticationselect them. RIP has no length field and the walk does not trim to UDP's (#235), so the entries end at the RFC 4822 authentication trailer, which the first entry's Packet Length locates when the bytes there start with the trailer's0xFFFF 0x0001(authentication_trailer, raw, to the end of the body: Auth Data Len does not size it, since BIRD declares 20 for a 16-byte MD5 digest and 32 for a 32-byte HMAC-SHA-256 one), or at the last whole entry, with anything shorter than an entry after it — an entry cut by a snap length, or an Ethernet FCS — inremainder; past the header neither decode nor any accessor raises. Against a wrong port guess,decode()rejects a version other than 1 or 2 and command 0 (InvalidFieldError), which 99.2% of random datagrams fail; construction accepts them. The other commands, TraceOn to Update Acknowledge (command_name, with IANA's names), and RIPv1 messages with nonzero must-be-zero fields decode. RIPng (RFC 2080, UDP 521, the IPv6 protocol) is not decoded; RIP itself has no IPv6 form.OSPF: OSPFv2 (RFC 2328), IP protocol 89 (#183). IPv4 protocol 89 (IPProtocol.OSPF, "OSPF") now dispatches tonetprotocols.OSPF(alsonetprotocols.layer3.OSPF), which decodes the 24-byte common header —version,type,packet_length,router_id,area_id,checksum,instance_idandau_type(one byte each: RFC 6549 §2 split RFC 2328's 16-bit AuType into an Instance ID and an 8-bit AuType), the raw 8-byteauthentication— and keeps the message as rawbody, sobytes(OSPF.decode(x)) == x[:header_len]by construction. One accessor per message type parses the body on demand and returnsNonefor the other types:hello(OSPFHello: network mask, hello and dead intervals, options, priority, DR, BDR and the neighbor list),database_description(OSPFDatabaseDescription: interface MTU, options, the I/M/MS flags, DD sequence number and itsOSPFLSAHeaders),ls_requests(OSPFLSRequests),lsas(a Link State Update'sOSPFLSAs, each a decoded 20-byteOSPFLSAHeaderand a rawbody) andls_acknowledgments(OSPFLSAHeaders). LSA bodies are not decoded: the Router, Network, Summary and AS-external (and other) LSA contents stay rawbytes, as follow-up work.decode()and the constructor check each known message's framing (whole neighbors, LSA headers and requests; an update's LSA count and lengths walking its body exactly), raisingInvalidFieldErrorwithfield="body"otherwise, so no accessor raises; a type outside 1-5 keeps its body as is. Packet Length bounds the packet: below 24 raisesInvalidFieldError, past the bufferTruncatedHeaderError. Under cryptographic authentication (AuType 2) the digest after the packet, Auth Data Len bytes, is kept inauth_trailerand counted inheader_len, withkey_id,auth_data_lenandcrypto_sequence_numberaccessors; AuType 3 (RFC 7474, extended sequence numbers) is framed the same way, its trailer the 64-bit sequence number and the digest, which Auth Data Len counts together, and the same accessors read its 32-bit Key ID and 64-bit sequence number; nothing else after the packet is consumed, so an RFC 5613 LLS block, Ethernet padding or an FCS is left after the OSPF layer. Records have__bytes__, so a packet can be built from them, and display helpers (type_name,au_type_name,options_str,flags_str,ls_type_name, hex strings). Only version 2 decodes: OSPFv3 (RFC 5340), which IPv6 carries under the same number, is not implemented, soip.proto.v6withholds protocol 89 (_defaults.IPV4_ONLY_NUMBERS) and an IPv6 packet with next header 89 still ends its walk at the IPv6 header;OSPF.decode()rejects version 3 withInvalidFieldError(field="version") for a caller who sends it there anyway. The registry gains the private mechanism for that: a withheld key owns no class, inheritance skips it as it skips an override,derive()copies it, and a registration made directly in the child table fills it.- OSPF checksums in
netprotocols.checksum(the new functions are also exported fromnetprotocols).compute(ospf)is the internet checksum of the packet with its checksum field zeroed and its Authentication field left out (RFC 2328 §D.4.1), no pseudo-header (ipandpayloadare ignored); under cryptographic authentication (AuType 2 or 3), which computes none (§D.4.3; RFC 7474 §5 keeps that for AuType 3),compute()raisesInvalidFieldError,verify()returnsTrue(the digest, which this library cannot check without the key, protects the packet) andPacket.with_checksums()leaves the field alone. Newfletcher_checksum(data, offset)computes the ISO 8473 Fletcher checksum field (RFC 905 Annex B), raisingValueErrorunless the 2-byte field atoffsetlies insidedata.lsa_checksum(lsa)generates anOSPFLSA's LS Checksum, over the LSA but its LS Age (RFC 2328 §12.1.7), andverify_lsa(lsa)checks it as RFC 905 B.4 does, by both running sums being zero, so a field stored with0x00where the generator writes0xff(equal modulo 255) verifies too, plus RFC 2328 §12.1.7's rule that the LS Checksum cannot be zero: a field of0x0000fails even where those sums are zero. - PIM-SM (#184):
netprotocols.PIM, layer 3, RFC 7761. IP protocol 103 (IPProtocol.PIM, "PIM") now dispatches from IPv4 and IPv6, extension headers included, to onePIMclass for both families, which decodes the 4-byte common header (version,type,reserved,checksum) and keeps the rest as rawbody, sobytes(PIM.decode(x)) == x[:header_len]holds by construction.PIM.messagedispatches ontype, through a parser table in the shape of IGMP's message types, to a typed message parsed on demand:PIMHello(type 0; its option TLVs asPIMHelloOption(type, value)withtype_name, plusholdtime,lan_prune_delay(PIMLANPruneDelay),dr_priority,generation_idandaddress_listread from them),PIMRegister(1; the B and N bits and the encapsulated packet, whichencapsulateddecodes in a lax walk from its IP header),PIMRegisterStop(2),PIMJoinPrune(3, and Graft and Graft-Ack, 6 and 7, which share its format;PIMGroupSets of joined and pruned sources) andPIMAssert(5). Bootstrap (4), Candidate-RP-Advertisement (8), State Refresh (9) and other types decode with their body raw, andmessageisNonefor them;type_namenames types 0-12 (DF Election, ECMP Redirect and PIM Flooding Mechanism, 10-12, from the IANA registry). Encoded-Unicast, Encoded-Group and Encoded-Source addresses (§4.9.1) arePIMEncodedUnicast,PIMEncodedGroup(withbidirectional,admin_scope) andPIMEncodedSource(withsparse,wildcard,rpt), sized by their own address family, so an IPv6-encoded message decodes whatever IP family carries it; only native IPv4 and IPv6 encodings are supported, and any other family or encoding (RFC 5384's join-attribute Encoded-Source included) makesmessageraiseInvalidFieldError. Every typed message, option and address has abytes(), so a message can be built from them. PIM has no length field, and the walk does not trim to the IP length, sodecodebounds the message by its own structure: Join/Prune, Graft, Graft-Ack, Register-Stop and Assert end where their counts and addresses say, leaving any trailer (Ethernet padding, an FCS) undecoded; a Hello's options are walked and a run of zero bytes where the next option would start is left undecoded as padding; a Register's data packet and the raw types' bodies run to the end of the buffer. Past the headerdecodenever raises: a body its parser cannot read (cut short, an unknown address family, a nonzero trailer after a Hello that does not walk) is kept whole, formessageto raise on. A version other than 2 raisesInvalidFieldError(field="version") fromdecodeand the constructor. - PIM checksums in
compute/verify/Packet.with_checksums().compute(pim, ip=...)is the internet checksum over the whole message, or over a Register's first 8 bytes (RFC 7761 §4.9.3), with the IPv6 pseudo-header (next header 103, the covered length) in front over IPv6 and none over IPv4;ipis required, since the family decides which.verify()also accepts a Register whose checksum covers the whole message, which §4.9.3 says should be accepted "for interoperability reasons";with_checksums()fills PIM layers like the transports, so it rewrites such a Register to the 8-byte form. BGP: BGP-4 messages (RFC 4271) over TCP port 179 (#185). TCP port 179 now dispatches, best-effort like every port entry, tonetprotocols.BGP(alsonetprotocols.layer7.BGP), one message per instance: the 19-byte common header asmarker,lengthandtype, and the body kept raw inbody, sobytes(BGP.decode(x)) == x[:header_len], whereheader_lenis the message's Length, not the buffer. Decode applies RFC 4271 §6.1's header checks — an all-ones Marker, a Type of 1-5 (OPEN, UPDATE, NOTIFICATION, KEEPALIVE, ROUTE-REFRESH) and that type's Length bounds (KEEPALIVE exactly 19, OPEN 29-4096, UPDATE and ROUTE-REFRESH from 23 and NOTIFICATION from 21, up to the 65535 of RFC 8654's extended messages) — and raisesTruncatedHeaderErrorfor a message the buffer cuts short. Accessors parse the body on demand and returnNonefor other types:version,my_as,hold_time,bgp_identifier,optional_parameters(BGPOptionalParameter, either the RFC 4271 encoding or RFC 9072's extended one, flagged byextended_optional_parametersand recorded on each parameter asextended_length, which sets the width of the Parameter Lengthbytes(parameter)writes and is part of its equality; Capabilities named, its value raw) for OPEN;withdrawn_routesandnlri(BGPPrefix, IPv4, bit lengths up to 32) andpath_attributes(BGPPathAttribute: flags, type code and rawdata, the Attribute Length one or two bytes by the Extended Length flag; ORIGIN, NEXT_HOP, MULTI_EXIT_DISC and LOCAL_PREF values decoded invalue, and every permanent type code in the IANA BGP Path Attributes registry named, its value kept raw) for UPDATE;error_code,error_subcode,error_data, their names as the IANA BGP Parameters registry (fetched 2026-10-25) assigns them (error codes 0-9 and the subcodes of every code with a subcode registry, RFC 4271 §4.5's "Unspecific" 0 for the codes without one), and an RFC 9003shutdown_communication(strict UTF-8,Nonewhen absent or invalid) for NOTIFICATION. A malformed body raisesInvalidFieldErrorfrom its accessor, not from decode. ROUTE-REFRESH's body stays raw. A TCP segment holding several messages decodes as oneBGPlayer each:next_protocol()answersBGPwhile another message begins in the same segment, whichdecode()records outside the instance's comparison and hash. A message the segment cuts raisesTruncatedHeaderError(lax mode keeps the messages before it), a segment that starts inside one fails the Marker check, and reassembly stays the caller's, as forHTTP. Each message being a layer, a segment of more than 29 messages exceeds the defaultmax_depth, so valid traffic can raiseMaxDepthExceededError(or, lax, stop short): a 1448-byte segment holds up to 76 KEEPALIVEs or 30 one-prefix UPDATEs, and GRO, TSO, loopback and jumbo-frame captures carry larger segments. The module docstring,walk.py, ARCHITECTURE.md anddocs/CLAIMS.md§5.7 document it and the two ways past it: a largermax_depth, or a second walk withdecode_frame(frame[packet.consumed:], start=BGP). Out of scope and left raw, as #185 asks: AS_PATH (its AS number width, 2 or 4 bytes, is negotiated in the OPENs), capability values, ADD-PATH path identifiers, ROUTE-REFRESH's fields and the MP_REACH/MP_UNREACH attributes that carry IPv6 routes. The capture host has no IPv6, so BGP over IPv6 is tested with constructed frames.
- Every comparative number the README quotes was re-measured for this release (Rule 4 of
docs/CLAIMS.md), on the same machine class as 2.4.0's figures but on the 265-frame corpus Tier 2 grew from 140, againstdpkt 1.9.8andscapy 2.8.0. The README's "within 15% of dpkt on decode" no longer holds and is replaced: dpkt decodes the corpus 1.30× faster (1.27-1.30× over three runs), while netprotocols stays 3.4× ahead of scapy. A file-by-file A/B against the 2.4.0 tree puts the gap in the five new routing captures, on which dpkt takes about two thirds of netprotocols' time, while the 140 frames 2.4.0 was measured on still read within 10% of dpkt on both trees, so it is the workload rather than a regression; why dpkt is faster on those protocols was not profiled. Encode is 4.62× ahead of dpkt, import 70.0 ms (from 55.0 ms, the five new modules) againstscapy.all's 396.9 ms, and the wheel is 176.5 KiB, 15.3× smaller than scapy 2.8.0's 2.63 MiB. Decode depth against dpkt is 79 of 265 frames deeper, the 40 new ones being the BGP and RIP frames, which dpkt leaves as raw bytes.docs/CLAIMS.mdrecords each run, the per-file table and the A/B, and renames claim 1.2 for the figure it now holds. - The decode benchmark baseline is re-recorded on the 265-frame corpus.
benchmarks/baseline.jsonwas recorded at 2.2.1 on the 97-frame corpus (6.5677 normalized); it now holds 2.5.0 on 265 frames, 5.4344 normalized (97,453 f/s, 30 repetitions, best of 9, CPython 3.12.3), viascripts/benchmark.py --update-baseline. The corpus--checkwalks grew with Tier 1 and Tier 2 captures that cost more per frame than the old ones, so normalized throughput fell with the workload: the same library code read -14.1% on master (03387af) and -17.1% (-16.5% on the re-measure) on the release PR, either side of the 15% gate on runner noise alone, and the file-by-file A/B of 2.4.0 against 2.5.0 indocs/CLAIMS.mdshows no regression beyond that harness's noise on the 140 frames 2.4.0 had. Re-anchoring accepts the drift since 2.2.1: the gate now guards against regressions relative to 2.5.0 on this corpus. - A real BGP capture joins the corpus:
bgp.pcap, 19 frames (265 across 27 scenarios), and its whole session goes intotests/fixtures/bgp/.scripts/capture_fixtures_bgp.shruns three BIRD 2.14 speakers in netns on one bridge, an eBGP and an iBGP session, with offload disabled, through OPENs, KEEPALIVEs, UPDATEs (five prefixes each with its own MED, 600 /24s that BIRD packs into a few UPDATEs, some longer than a segment), a withdrawal and a Cease NOTIFICATION with an RFC 9003 shutdown communication. It reassembles each direction to assert what was announced and withdrawn, prefix by prefix, and that the capture holds a segment of several whole messages, one of whole messages then a cut one, and one starting inside a message; it writes every frame tobgp/bgp_session.pcap(94 frames, outside the corpus globs) and the frames whose payload is whole messages tobgp.pcap.scripts/check_fixtures.pyneeded no change: it verifies the TCP checksums that cover the BGP payload. The corpus's deepest chain is now 10 layers (a segment of 7 UPDATEs);walk.pyanddocs/CLAIMS.md§5.7 say so.tests/test_fuzz.pygains BGP accessor-safety and built-UPDATE properties. - A real PIM-SM capture joins the corpus:
pim.pcap, 13 frames (246 across 26 scenarios).scripts/capture_fixtures_pim.shruns two FRR 8.4 routers (zebra + pimd) between a multicast source and an IGMPv3 receiver, four netns over three veth pairs, with static RPs on opposite routers for two groups so that a (,G) tree and a Register exchange both cross the captured link, then has the receiver leave and stops one pimd. It keeps the first frame of each of 13 kinds — Hellos with Holdtime, LAN Prune Delay, DR Priority, Generation ID and Address List options, a Holdtime-0 goodbye, a data Register and a Null-Register, a Register-Stop, and Join/Prune messages with joined and pruned (,G), (S,G) and (S,G,rpt) entries — and fails unless it saw all of them. FRR sums its Registers' checksums over the first 8 bytes.scripts/check_fixtures.pyverifies every PIM checksum (IPv4, and IPv6 with its pseudo-header), accepts either Register form, and checks the Register's encapsulated packet in turn, skipping only a Null-Register's zero dummy IPv4 header checksum, which RFC 7761 says a receiver must not check; an IPv6 Null-Register's dummy PIM header (version 0, after the dummy IPv6 header) is checked by its own checksum over the dummy header's source and group, as §4.9.3 asks, rather than as a PIM message;tests/test_pim.pyruns it on the frames and on tampered copies. The capture host has no IPv6, so PIM over IPv6 is covered by constructed frames whose pseudo-header checksums the test computes itself; Assert, Graft and the raw types are covered by constructed messages, and real frames are tested with zero padding and a 4-byte trailer appended. PIM joins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, an accessor-safety property and trailer properties), the truncation and damaged-payload contract tests, the corpus checksum cases and the corpus coverage set. _tlv.walk_kind_length_valuetakes awidth(default 1), the size of the kind and length fields, so PIM Hello options (2-byte type and length) walk through it. The floor and overrun message are now derived once per call, which takes the walker from radon C (13) to B (10); a seeded 3000-case comparison against a verbatim copy of the previous walker pins every byte-wide caller (TCP, IPv4, IPv6 options) to identical results and errors.checksum.compute()'s PIM arm is one call to a_pim_checksumhelper, beside the_pseudo_header_checksumhelper the ICMPv6, TCP and UDP arms already use, socompute()stays at radon B. The scoped mutation runs onnetprotocols._tlv.*andnetprotocols.checksum.*leave no survivor beyond the one already allowlisted.- A real OSPFv2 capture joins the corpus:
ospf.pcap, 54 frames (233 across 25 scenarios).scripts/capture_fixtures_ospf.shruns FRR 8.4'szebraandospfdin two netns over a veth pair and captures three adjacencies in turn, one per AuType (none, simple password, keyed MD5), each with every message type: Hellos, the Database Description exchange, Link State Requests, Link State Updates carrying router, network and AS-external LSAs, and Link State Acknowledgments. The script fails unless each adjacency holds exactly 6 Hellos, 5 Database Descriptions, 2 requests, 2 acknowledgments and six LSAs (two router LSAs from each router, A's network and AS-external LSAs) in 3 or 4 updates, and no frame carries data after its packet (FRR sent no LLS). The test password and MD5 key are published intests/fixtures/MANIFEST.md.scripts/check_fixtures.pyverifies, with its own implementations, every AuType 0/1 packet checksum, the AuType 1 password, every AuType 2 keyed-MD5 digest (and that its packet checksum is zero) and every LSA's Fletcher checksum, in RFC 905 B.4's verification form plus RFC 2328 §12.1.7's rule that it is never zero; it reads AuType from header byte 15, past RFC 6549's Instance ID.tests/test_ospf.pyloads the checker and holds it to failing a flipped body byte, LSA byte, password byte, digest byte, key ID and checksum, two swapped LSA bytes (which move only one Fletcher sum), a change that moves only the other, and an LS Checksum of0x0000whose sums are zero, and to passing a valid frame with a nonzero Instance ID. The kernel had no IPv6, so OSPFv3 over IPv6 is covered by a constructed frame, as are LLS blocks, padding and FCS trailers.OSPFjoins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy built from the message records, and an accessor-safety property that also feeds OSPF-shaped buffers), the truncation and lying-length contract tests, the corpus checksum cases and the corpus coverage set. The registry tests now holdip.protoandip.proto.v6to differing at the IPv6-only numbers, at 51, and at 89, which onlyip.protoholds. - A real RIP capture joins the corpus:
rip.pcap, 21 frames (179 across 24 scenarios).scripts/capture_fixtures_rip.shruns two BIRD 2.14 routers in two netns over a veth pair through five scenarios — RIPv1 broadcast, RIPv2 multicast, a plain-text password, keyed MD5 and HMAC-SHA-256 — and keeps a fixed, asserted selection of each: every router's first Request and first Response, and one whole-table periodic update with poisoned-reverse routes.scripts/check_fixtures.pynow verifies each RFC 4822 digest with the published test keys (rip-keyed-md5,rip-hmac-sha256), fails on a Key ID with no published key (rip-unknown-sa) or a missing trailer header (rip-trailer), and counts RIP datagrams (rip); its VXLAN peeling moves into_check_vxlan.RIPjoins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, and a property that decode and every accessor are total and that entries, trailer and remainder tile the body), the contract tests (truncation, a trailer and a cut entry under strict and lax walks) and the corpus coverage set. - A real VRRP capture joins the corpus:
vrrp.pcap, 18 frames (158 across 23 scenarios).scripts/capture_fixtures_vrrp.shruns keepalived 2.2.8 as two routers in two netns over a veth pair through four virtual routers: VRRPv2 withauth_type PASSand two addresses, failing over from A to B with a priority-0 advert from each; VRRPv2 without authentication; VRRPv3 with one address, failing over the same way; and VRRPv3 unicast with three addresses and a 0.5 s interval. A master advertises for as long as it runs, so the script drives each step by watching the capture, keeps each router's first two live adverts and its resignation per segment, and fails unless the kept frames are exactly those 18. keepalived builds each IPv4 header (IP_HDRINCL) and every VRRP byte; the kernel fills the IPv4 header checksum.scripts/check_fixtures.pyverifies every VRRP checksum independently (no pseudo-header for VRRPv2, the IPv4 or IPv6 one for VRRPv3), and fails a message whose length disagrees with its version and count or the IP payload, a version other than 2 or 3, and VRRPv2 over IPv6. veth does not pad, so Ethernet padding, a nonzero trailer and VRRPv3 over IPv6 (the capture host has no IPv6) are covered by constructed frames intests/test_vrrp.py, whose checksums it computes itself and also runs throughcheck_fixtures.py, as it does tampered copies of the capture.VRRPandVRRPv6join the fuzz suite (ALL_PROTOCOLS, round-trip strategies, an accessor property, a padding and trailer property), the truncation contract test, the corpus coverage set andtests/test_checksum.py;checksum.compute()'s UDP arm moves into a helper, as GRE's and SCTP's did, to keep its complexity where it was.
- IP-in-IP decodes through (#177). IP protocol 4 (IPv4 in IPv4, RFC 2003; IPv4 in IPv6, RFC 2473) and 41 (6in4, RFC 4213; IPv6 in IPv6, RFC 2473) now dispatch from the outer IP header straight to the inner
IPv4orIPv6, from either outer family, sodecode_framewalks a tunneled packet to its inner transport instead of stopping at the outer header. The encapsulation has no header of its own, so there is no new class, only twoip.protorows and twoIPProtocolmembers,IPIPandIPV6("IPv4 encapsulation", "IPv6 encapsulation"). A hostile run of nested protocol-4 headers is stopped bymax_depth, like any other long chain. ESP: IPsec Encapsulating Security Payload headers (RFC 4303) (#178). IP protocol 50 now dispatches from IPv4 and IPv6 tonetprotocols.ESP, which decodes the cleartext 8-byte prefix,spiandsequence_number(withspi_hex_strfor display), and keeps everything after it — payload, IV, padding, Pad Length, Next Header and ICV — as one opaqueciphertext: bytes, sobytes(ESP.decode(x)) == x; like an ICMPbody, it runs to the end of the frame, so on a datagram shorter than Ethernet's minimum it ends with the link-layer padding, not the ICV. There is no cryptography: without the Security Association's keys and algorithms nothing in the packet says where the ciphertext ends and the trailer begins, soESP.next_protocol()returnsNoneand a frame walk ends at ESP by design.IPProtocolgainsESP("ESP").AHandAHv6: the IPsec Authentication Header (RFC 4302) (#179). IP protocol 51 now dispatches tonetprotocols.AHfrom IPv4 and to its subclassAHv6from IPv6 and its extension headers. Both decode the fixed fields —next_header,payload_len,reserved,spi,sequence_number— and keep the ICV raw inicv, sized by Payload Len ((payload_len + 2) * 4 - 12bytes, any alignment padding included) and never verified.next_protocol()chains onward throughnext_header, so an AH-wrapped TCP segment keeps decoding intoTCP; the pair exists because the onward table must be the outer family's:AHreadsip.proto, so IPv4 → AH → 0 cannot conjure a Hop-by-Hop layer, andAHv6readsip.proto.v6, so IPv6 → AH → Destination Options (RFC 8200 §4.1) keeps decoding.isinstance(layer, AH),packet[AH]andcase AH(...)match either. A Payload Len below 1 raisesInvalidFieldError, one past the bufferTruncatedHeaderError, andAHv6also rejects a header that is not a multiple of 8 octets (an odd Payload Len), all withfield="payload_len".IPProtocolgainsAH("AH"). Registering over protocol 51 inip.protonow reaches IPv4 only:AHv6isip.proto.v6's own entry, which inheritance does not overwrite;_defaults.FAMILY_SPECIFIC_NUMBERSnames it.VXLAN: VXLAN tunnels decode through to the inner frame (RFC 7348, #180). UDP port 4789 dispatches to the newnetprotocols.VXLAN(alsonetprotocols.layer7.VXLAN), which decodes the 8-byte header intoflags,reserved1,vniandreserved2, in wire order, withbytes(VXLAN.decode(x)) == x.next_protocol()always returnsEthernet: the payload is a whole Ethernet frame, sodecode_framewalks on into the inner frame's VLAN tags, ARP, IPv4 or IPv6 through the existingethertypetable, and aregistryordecode_aspassed to the walk applies inside the tunnel too. The walker needed no change. RFC 7348 §5 requires the I flag (VXLAN.I_FLAG,0x08), and decoding a header without it raisesInvalidFieldError(field="flags",offset=0); that check is also what diagnoses about half of the non-VXLAN datagrams that happen to use port 4789, instead of decoding them as a tunnel around a garbage inner frame. Construction accepts a clear I flag, so such a header can be built to test how another stack drops it, andbytes()of it is the header with the I flag clear;decode()rejects it (ARCHITECTURE.md's round-trip guarantee now says it covers canonical headers, the ones decode produces given its context). The cost is on decode: a capture whose I flag is clear raises at the VXLAN header'sframe_offset(alax=Truewalk keeps only Ethernet, IP and UDP), and its inner frame, 8 bytes on, decodes with a seconddecode_frame(..., start=Ethernet)walk. The reserved bits are kept verbatim and never rejected, since the RFC says to ignore them on receipt and extensions such as Group Based Policy reuse them. Lookup tries the destination port first, so a datagram to 4789 dispatches to VXLAN whatever source port the sender's flow hash picked, even a registered one (and so does a DNS reply to a client whose ephemeral port is 4789, which dispatches to VXLAN, never to DNS). Only 4789 is registered: a capture from a Linux device created without adstport, which then uses Linux's pre-IANA 8472, needsdecode_as={"udp.port": {8472: VXLAN}}. A frame that nests VXLAN in itself is stopped bymax_depth, four layers per level.- SCTP (#176):
netprotocols.SCTP, layer 4, RFC 9260. IP protocol 132 (IPProtocol.SCTP, "SCTP") now dispatches from IPv4 and IPv6, extension headers included, toSCTP, which decodes the 12-byte common header (src_port,dst_port,verification_tag,checksum) and keeps the chunks as rawchunksbytes, padding included, sobytes(SCTP.decode(x)) == x[:header_len]holds by construction.parsed_chunkssplits them on demand into a flat tuple ofSCTPChunk(type, flags, value), which names the RFC 9260 chunk types (DATA, INIT, INIT ACK, SACK, HEARTBEAT, HEARTBEAT ACK, ABORT, SHUTDOWN, SHUTDOWN ACK, ERROR, COOKIE ECHO, COOKIE ACK, ECNE, CWR, SHUTDOWN COMPLETE) and the common extensions (AUTH, I-DATA, ASCONF, ASCONF-ACK, RE-CONFIG, PAD, FORWARD-TSN, I-FORWARD-TSN) viatype_name, falling back to"unknown (n)";flags_strnames the DATA/I-DATA I/U/B/E bits and the ABORT/SHUTDOWN COMPLETE T bit, andunrecognized_actionreads the type's two high bits.bytes(SCTPChunk(...))emits the padded wire form, so a packet can be built from a list of chunks. SCTP has no length field, the chain walk does not trim to the IP length, and CRC32c, unlike the internet checksum, changes when zero bytes are appended, sodecodewalks the chunk headers to find where the packet ends: a run of zero bytes where the next chunk would start is left undecoded as link-layer padding (a short Ethernet frame's). Past the 12-byte common headerdecodenever raises, likeICMPv4andIGMP: a remainder the walk cannot parse (a chunk cut by a snap length, an IP fragment or an ICMP error's quote; a nonzero trailer such as an Ethernet FCS) is kept verbatim inchunks, so the ports, verification tag and checksum survive in strict and lax walks and inICMPv4.embedded_chain(when the quote holds the whole 12-byte common header), andverify()returnsFalsefor the cut packet.parsed_chunksraises on such a remainder when it does not walk (a trailer that happens to walk parses as a phantom chunk, soverify()is the reliable signal):InvalidFieldErrorfor a chunk length below 4,TruncatedHeaderErrorfor a chunk that runs past the bytes, so a hostile length can neither loop nor over-read. A final chunk whose padding the buffer cuts short is accepted as is.flow_key()andPacket.flow_key()key SCTP on its ports like TCP and UDP. The chain ends at SCTP; payload-protocol dispatch is not implemented. netprotocols.crc32c(), and SCTP checksums incompute/verify/Packet.with_checksums(). The standard library has no CRC32c (zlib.crc32is the IEEE CRC-32), sochecksum.pygains a table-driven Castagnoli CRC, pinned to RFC 3720 Appendix B.4's vectors.compute(sctp)is the CRC32c of the whole packet with the checksum field zeroed and no pseudo-header (ipis ignored), returned byte-swapped: the CRC goes on the wire least significant byte first (RFC 9260 Appendix A), andSCTP.checksumreads its four bytes big-endian.with_checksums()fills SCTP layers like the other transports.
Packet.flow_key()keys a tunneled flow on the inner IP header. It used the first IPv4/IPv6 layer in the packet, which in a tunnel is the outer one: the key carried the tunnel endpoints' addresses and the tunnel's protocol number (4, 41, or 47 for GRE, which already reached this) instead of the conversation's. It now uses the IP header nearest before the transport layer, asPacket.with_checksums()already did, and returnsNonewhen no IP header precedes the transport.flow_key()takes the protocol number from the transport layer, not the IP header.FlowKey.protocolwas read fromIPv4.protocol/IPv6.next_header, which name whatever directly follows the IP header: an IPv6 flow behind a Hop-by-Hop, Routing or Destination Options header was keyed protocol 0, 43 or 60, and an AH-protected one 51, so neither matched the same conversation's unwrapped key. (A Routing header with segments left still keys on the IPv6 destination, which is the next segment rather than the final destination, so a source-routed flow's two directions can still differ.) It is now 6 forTCPand 17 forUDPwherever the segment sits, asFlowKey's docstring already promised;Packet.flow_key()andflow_key()share one transport-to-number table innetprotocols.flow.
- Every comparative number the README quotes was re-measured for this release (Rule 4 of
docs/CLAIMS.md), on the same machine class as 2.3.0's figures but on the 140-frame corpus Tier 1 grew from 97, againstdpkt 1.9.8andscapy 2.8.0: decode is at parity with dpkt (from 5.3% slower to 3.0% faster over three runs; the README keeps "within 15%") and 4.1× ahead of scapy, encode 4.18× ahead of dpkt, import 55.0 ms againstscapy.all's 428.0 ms, and the wheel is 124.4 KiB, 21.7× smaller than scapy 2.8.0's 2.63 MiB. Decode depth against dpkt is 39 of 140 frames deeper, the 12 new ones being the VXLAN frames and one SCTP frame.docs/CLAIMS.mdrecords each run and what moved, and corrects the 2.3.0 figures' scapy version:uv.lockalready pinned 2.8.0 when they were taken, so they most likely name 2.7.0 in error. - The nightly mutation gate no longer reports a new function's mutants as untested.
mutation.ymlrestoresmutants/from the previous night, and that directory holdsmutmut-stats.json, mutmut's map from each function to the tests that call it. mutmut 3.8 re-traces only tests it has never seen, so a function added since then and called only by existing tests (herechecksum.py's_gre_checksumand_sctp_checksum) mapped to no tests, and all 49 of their mutants failed the gate as "no tests". The workflow now deletes the map before each run, so mutmut traces its configured test selection in full; a local reproduction went from 49 "no tests" to 49 killed.tests/test_workflows.pypins the step. - A real SCTP association joins the corpus:
sctp.pcap, 16 frames (140 across 22 scenarios). The capture host's kernel has no SCTP, soscripts/capture_fixtures_sctp.shruns usrsctp's example client and echo server (libusrsctp-examples) in two netns over a veth pair, on raw IPv4: INIT through SHUTDOWN COMPLETE, with DATA, SACK and a HEARTBEAT exchange from each end, then one script-built packet with an unknown chunk type (63); the script fails unless the client completes the association and the capture holds those 16 frames, one chunk each. usrsctp builds those packets' IPv4 headers (IP_HDRINCL, the kernel filling length and checksum); the kernel builds the script-built packet's.scripts/check_fixtures.pyverifies every SCTP CRC32c with its own bit-at-a-time implementation, andtests/test_sctp.pycovers truncation, lying lengths, link-layer padding, nonzero chunk padding and IPv6 carriage with constructed packets. SCTP joins the fuzz suite (ALL_PROTOCOLS, a round-trip strategy, a chunk-accessor property), the truncation contract test, the corpus checksum cases and the corpus coverage set.registry.py's tworegister("ip.proto", 132, SCTP)examples, and the registry tests that registered stand-ins at 132, now use 253 (reserved for experimentation, RFC 3692), since 132 is built in and a different class there raisesRegistryConflictError. - An IPsec AH capture joins the corpus:
ah.pcap, 6 frames (124 across 21 scenarios).scripts/ipsec_fixture_packets.pynow also builds AH with HMAC-SHA-256-128 — transport mode over a TCP SYN, an ICMPv4 echo and UDP, tunnel mode over inner IPv4, and an AH-over-ESP bundle — computing each ICV over the IPv4 header's immutable fields, the AH header and the payload (RFC 4302 §3.3.3). Because the ICV covers the outer header, the script builds that header itself andscripts/capture_fixtures_ipsec.shsends whole datagrams withIP_HDRINCL; the post-capture comparison found them byte-identical on the wire. The new keys are published intests/fixtures/MANIFEST.md, andscripts/check_fixtures.pyverifies every AH ICV with them before the checksums, inner packet or ESP packet behind it, which it then requires to be readable, as it does ESP's; an AH frame on an unpublished SPI fails, as does one whose ICV the checker cannot compute (IPv4 header options, or an IPv6 outer header).esp.pcapis unchanged. IPv6-outer AH, with its 4 bytes of ICV padding, is covered by constructed frames intests/test_ah.py, andwith_checksums()is tested to recompute a transport checksum through AH from either family.AHandAHv6join the fuzz, round-trip, contract and corpus-coverage suites, and the registry tests now holdip.protoandip.proto.v6to differing only at the IPv6-only numbers and at 51. - An IPsec ESP capture joins the corpus:
esp.pcap, 6 frames (118 across 20 scenarios). The capture host's kernel has no xfrm ESP transform, so the new stdlib-onlyscripts/ipsec_fixture_packets.pybuilds genuine ESP — NULL encryption (RFC 2410), HMAC-SHA-256-128 integrity (RFC 4868), RFC 4303 padding and trailer — in transport mode (ICMPv4, UDP) and tunnel mode (inner IPv4), andscripts/capture_fixtures_ipsec.shsends it through a raw protocol-50 socket over a veth pair, so the kernel builds the outer IPv4 header; the script then checks that every byte it built arrived unchanged. The test keys are published intests/fixtures/MANIFEST.md, andscripts/check_fixtures.pyverifies every ESP ICV with them, then the padding and the inner packet's checksums. An ESP frame on an SPI with no published key fails the checker rather than being skipped, as does anything an ICV vouched for that it cannot read, at any depth below the ESP header (an unknown protocol or EtherType, a header too short to check, a fragment); and tunnel nesting past its depth bound (8 encapsulations) now fails instead of passing unchecked, whatever the chain ends in, for GRE and IP-in-IP as well as ESP; an IPv4 header with an invalid IHL now fails asipv4-ihlon every path, where it was checked on (or crashed the checker). IPv6-outer ESP is covered by constructed frames intests/test_esp.py, since the capture host has no IPv6.ESPjoins the fuzz, round-trip, contract and corpus-coverage suites. - A real VXLAN capture joins the corpus:
vxlan.pcap, 11 frames (112 across 19 scenarios).scripts/capture_fixtures_vxlan.shbuilds a kernel VXLAN tunnel on port 4789 between two netns over a veth underlay and captures ARP, ICMP echoes and one UDP datagram across two segments: VNI 1193046 (0x123456) withudpcsum, so the outer UDP checksum is real, and VNI 100 withnoudpcsum, so the outer checksum is zero.scripts/check_fixtures.pypeels VXLAN on destination port 4789 and verifies the inner frame's checksums.tests/test_checksum.pynow checks every transport in a frame against its nearest enclosing IP header, not just the first, so a VXLAN frame yields both its outer UDP and its inner transport, and holds zero UDP-over-IPv4 checksums apart as "not used" (they mustverify(); there is nothing to recompute). The corpus's deepest chain is now 7 layers, andwalk.py,docs/CLAIMS.mdand ARCHITECTURE.md say so. ARCHITECTURE.md no longer lists VXLAN among protocols this library does not implement. - A real IP-in-IP capture joins the corpus:
ipip.pcap, 4 frames (101 across 18 scenarios).scripts/capture_fixtures_ipip.shsends ICMP echoes through raw IP sockets opened for protocols 4 and 41 over a veth pair, so the kernel builds the outer header as a tunnel endpoint would; this works where theipip/sitdrivers are not built. The capture host had no IPv6, so the corpus holds IPv4 in IPv4 and IPv6 in IPv4; the script also captures the two IPv6-outer combinations on a kernel with IPv6, andtests/test_ipip.pycovers them with constructed frames.scripts/check_fixtures.pypeels IP-in-IP and verifies the inner checksums.tests/test_checksum.pynow pairs each transport with its nearest enclosing IP header rather than the first. The coverage figure indocs/CLAIMS.md§5.3 andpyproject.tomlis re-measured (2,682 statements, 1 missed). - README's Roadmap section now leads with the current roadmap, #170, instead of describing the completed #107 as if nothing had replaced it and promising that "new planned work will open fresh issues" — #170 had been open since 2026-09-09. It names #170's five tier themes without restating its tiers or target versions, which moved up one minor version when 2.3.0 shipped the HTTP codec outside them;
tests/test_docs.pynow checks the section leads with #170 and links none of the tier epics. - Fixed a concurrency-group deadlock that cancelled the 2.3.0 release run before any job could start.
ci.yml's concurrency group was keyed on${{ github.workflow }}, which inside aworkflow_callresolves to the caller's name ("Release"), not "CI" — so release.yml calling ci.yml on a tag push made both the top-level run and the nestedcijob claim the identical groupRelease-refs/tags/<tag>, and GitHub cancelled the run as a self-deadlock. The group now uses a literalciprefix instead.tests/test_workflows.pygains a guard: no workflow declaringworkflow_callmay key its own concurrency group ongithub.workflow.
HTTP: an HTTP/1.1 codec (RFC 9112, RFC 9110).HTTP.decode(data, *, request_method=None, closed=False)decodes one complete message from an already-reassembled buffer and leaves any pipelined bytes after it alone (header_lenis where it ends). The instance holdsheadandraw_bodyverbatim, sobytes(msg) == head + raw_bodywhatever odd bytes the sender used, and constructing one runs the same parse, also requiringheadto be exactly one head andraw_bodyexactly the body its framing delimits. Accessors cover the start line (method,target,http_version,status_code,reason_phrase),fields,header()/header_values()(ASCII case-insensitive, invalid names never match),framing(HTTPFraming),connection_disposition(HTTPDisposition:CONTINUE/CLOSE/TUNNEL),content(chunked framing removed),trailersandanomalies; none of them raises. Everything the grammar resolved rather than rejected is anHTTPAnomalywith its kind, field, first offset and count.request_methodis the decode context a response needs (HEAD, and CONNECT answered with a 2xx, change its framing) and is stored only when it does;closed=Truesays the buffer ends at connection close, which a close-delimited response needs. HTTP is not port-dispatched, and TCP reassembly remains the caller's. NewHTTPAnomalyKindmembers check a request's Host (RFC 9112 §3.2):HOST_MISSING(HTTP/1.1),HOST_DUPLICATE,HOST_INVALID(not RFC 3986uri-host [":" port]),HOST_AMBIGUOUS(a comma or percent-encoding) andHOST_TARGET_MISMATCH(differs from an absolute-form target's authority, compared case-insensitively without percent-decoding or default ports). An HTTP error'soffsetis relative to the start of the message, also when constructing;utils/exceptions.pydocuments that exception to the attribute-relative rule.
-
Real HTTP/1.1 captures,
tests/fixtures/http/.scripts/capture_fixtures_http.shruns Python'shttp.server(protocol_version = "HTTP/1.1") on one end of a veth pair and drives it from the other: curl for six connections (GET, HEAD, a conditional GET answered 304, POST, a chunked response with a trailer, a 404) and a raw socket for one pipelined connection, since curl no longer pipelines HTTP/1.1. The new stdlib-onlyscripts/extract_http_streams.pywrites each connection's request and response byte streams beside the 98-frame capture, outside the corpus's non-recursive*.pcapglob, so the corpus counts are unchanged.tests/test_http.pyreassembles the streams again throughdecode_frame, so the extractor and the codec must agree on the wire bytes, then decodes every message (no anomalies; HEAD and 304 framedNONE, the chunked trailer read, the pipelined stream split by the README's loop). The streams seedtests/fuzz/fuzz_http_decode.py: two minutes now reachcov: 388 ft: 1441from262/892unseeded. A new strategy generates HEAD and CONNECT-2xx responses for the context round-trip property, whichhttp_messages()never covered. -
HTTP documentation. README: a coverage row and a Decoding HTTP section (the pipelining loop,
request_method/closed, anomalies), with every example run against the captures bytests/test_docs.py. ARCHITECTURE.md: text framing in the decode contract, HTTP's offset convention, its property-based__match_args__, why it is absent from thetcp.porttable (decode_asdecodes 8 of the capture's 98 frames), the layout map and the cookbook. SECURITY.md: what is in scope forHTTPand what it cannot see by design.docs/CLAIMS.md§5.2–5.3 and thepyproject.tomlcoverage comment are re-measured (19 protocols; 2,676 statements, 1 missed). -
HTTPjoins the fuzzing and property suites.ALL_PROTOCOLS, a round-trip strategy (context-free messages), a mutated-message strategy feeding two new properties (accessors never raise; arbitraryhead/raw_body/request_methodeither fail to construct or round-trip exactly), a decode-path test that construction's re-parse never runs insidedecode(), the offset convention intests/test_diagnostics.py, and a new Atheris harness,tests/fuzz/fuzz_http_decode.py, run byfuzz.yml'satherisjob with its imports instrumented.tests/test_http.pydecodes the chunked responsetcp_http.pcapcarries across two TCP segments. -
HTTP/1.1 message grammar (
netprotocols.layer7.http). The byte-level parsers the coming HTTP codec builds on: head scan, request/status line, field lines, RFC 9110 list parsing, Transfer-Encoding, Content-Length, RFC 9112 §6.3 framing, chunked bodies with trailers, and connection disposition. Ambiguities real implementations disagree on — CL+TE, bare LF, obs-fold, whitespace before the colon, chunk-extension and chunk-line oddities — decode by the RFC's resolution and are reported as located, aggregated anomalies instead of raising; only an unrepresentable message raises. The module joins the nightly mutation audit ('netprotocols.layer7.http.x__*'). It passes that audit with no survivors: equivalent mutants were designed out (literals hoisted to module level, dead initial values removed, the CONNECT 2xx range checked once, the chunk-extension walker replaced by a module-level regex), every raise site is pinned to its exact message and structured fields, and anomalies are asserted as full records. Trailing whitespace after a chunk extension (5;a) is flaggedCHUNK_EXTENSION_INVALID, as RFC 9112 §7.1.1 allows none. -
The nightly mutation run can now fail on a surviving mutant.
mutmut run(3.8.0) exits 0 however many mutants survive, somutation.ymlwas green whatever it found. A new final step,scripts/check_mutmut_survivors.py, fails the job on any undetected mutant not accepted in the new triage recordscripts/mutmut_survivors.txt, on a stale entry there, and on a scoped file with no checked mutant at all; unknown mutmut statuses fail closed. The two accepted survivors and their reasoning moved into that record from apyproject.tomlcomment. -
Closed a mutation-testing gap the gate exposed. A third survivor —
_tlv.walk_kind_length_valuediscarding a caller'smin_option_lengthwhen the length byte counts its own header — was neither triaged nor killed, because no call site passes a floor above the structural 2. Two direct tests intests/test_tlv.pynow pin it. -
Mutation runs can no longer report false survivors from warm caches. mutmut 3 runs the clean suite in-process and then forks once per mutant, so a
functoolscache warmed by the original code (DNS's section parsers) could answer in the child and hide a mutant.tests/conftest.pynow clears every package-level cache before each test, discovering them rather than listing them. -
Hypothesis profiles load for every test selection. They were registered only when
tests/test_fuzz.pywas imported, which mutmut's test selection never does, so property tests under mutation ran randomized and under the default deadline. They now live intests/conftest.py. -
fuzz.ymlandmutation.ymlkey their concurrency groups on the triggering event, so the nightly cron can no longer cancel a manually dispatched run. CONTRIBUTING.md gains Mutation testing and Releasing sections, the latter making those manual runs a release prerequisite. -
New guards in
tests/test_workflows.py: every harness undertests/fuzz/must be run byfuzz.yml, the survivor gate must followmutmut runand read the full status listing, and both nightly concurrency groups must be event-keyed. -
pyproject.toml's mutmut comment now says that decorated functions are never mutated, so the@lru_cacheDNS section parsers sit outside the audit whatever the filters say. -
Tightened three DNS corpus assertions in
tests/test_dns.pyfrom substring/endswithchecks to exact equality, closing 3 open CodeQLpy/incomplete-url-substring-sanitizationalerts (#166).test_names_decompress_to_real_domainsasserted"example.com" in names/"accounts.youtube.com" in namesagainst asetdecoded from a fixed pcap corpus, andtest_answers_parse_to_real_recordsassertedcname.rdata_text.endswith("google.com")against the same corpus — not security-relevant trust checks, but exactly the substring/suffix pattern the rule flags regardless of what the value's actually validating. Both now compare against the known exact decoded values instead (names == {"example.com", "accounts.youtube.com"},rdata_text == "www3.l.google.com"), which removes the pattern CodeQL keys on and is strictly more precise than the checks it replaces. -
Consolidated six open Dependabot updates and grouped
github/codeql-actionso its sub-actions can no longer be bumped apart (#198, #199, #204, #205, #206, #207). Dependabot tracksgithub/codeql-action/init,/analyze, and/upload-sarifas three separate dependencies and opened one PR each;analyzerefuses a config file written by a differentinitrelease ("Loaded a configuration file for version '4.37.9', but running version '4.38.1'"), so #204 and #206 each failed CodeQL alone and neither could ever merge. All three now move to v4.38.1 together, alongsideastral-sh/setup-uv10.0.1 → 10.2.0,hypothesis6.167.1 → 6.168.0,ruff0.16.6 → 0.16.7, andmutmut3.7.0 → 3.8.0 (lockfile byte-identical to Dependabot's).dependabot.ymlgains acodeql-actiongroup for thegithub-actionsecosystem, andtests/test_workflows.pygainsTestCodeQLActionVersionLockstep, which fails the ordinary test job — naming the mismatched steps — whenevergithub/codeql-action/*steps across all workflows are pinned to more than one commit. -
The Atheris
decode_frameharness now gets coverage feedback.tests/fuzz/fuzz_decode_frame.pyimportednetprotocolsoutsideatheris.instrument_imports(), so libFuzzer saw no edges and the nightlyatherisjob was mutating random bytes blind: a two-minute local run executed 30.4M inputs with the corpus never leavingcorp: 1/1b. With the imports instrumented, the same two minutes grow it fromcov: 15tocov: 98 ft: 284 corp: 59/4925b, with no crash found. -
The Atheris
decode_frameharness now starts from the real-capture fixtures. Unseeded, two minutes of fuzzing plateaued at 98 edges: strict decoding rejects almost every mutated frame at the first header, so libFuzzer rarely got past Ethernet/IP. The harness now hands every frame intests/fixtures/*.pcap(92 unique of 97) to libFuzzer through-seed_inputs=, so the nightly job needs no change and never writes new inputs back among the seeds. Seeds are content-addressed files in a fixed temporary directory, because libFuzzer exits from C and no Python cleanup runs. The harness exits instead of fuzzing if it finds no frame, so a moved fixture directory can't silently put it back to fuzzing from nothing. The seeds alone start atcov: 115; the same two minutes now reachcov: 146 ft: 511 corp: 122/12556b, with no crash found. -
Every comparative number the README quotes was re-measured for this release (Rule 4 of
docs/CLAIMS.md), on a different machine from the 2.2.x figures (CPython 3.12.3, x86-64 Linux): decode is ~6% behind dpkt and 4.6× ahead of scapy, encode 4.53× ahead of dpkt, import 56.8 ms againstscapy.all's 487.0 ms (the HTTP codec costs about a millisecond of it), and the wheel is 106.1 KiB, 23.9× smaller than scapy's, afterlayer7/http.pyadded 16 KiB. Decode depth against dpkt is unchanged (27 of 97 frames deeper).docs/CLAIMS.mdrecords each run and what moved.
- Closed a decode-throughput regression against dpkt that nobody had
been watching tier over tier (#147). Re-measuring every held claim
after #107/#124 closed showed netprotocols had gone from 1.16× faster
than dpkt right after Tier 1 to ~11% slower after Tiers 2-4 — a
reversal none of the five tiers' own re-measurements had caught,
because none of them profiled, only re-measured before/after.
cProfileagainst the corpus decode loop found two causes, neither of them the tiers first suspected:bytes_to_ipv6(added by #99 for Pyodide portability, not one of the three tiers originally named) formatted its eight address words one f-string at a time through a generator, ~18% of total corpus decode time;decode_frame()'sPacketconstruction paid a redundantisinstancecheck, throughProtocol's ABC machinery, on a list already guaranteed to hold onlyProtocolinstances, ~7-8% ofdecode_frame()'s own time. Both fixed without changing observable behavior:bytes_to_ipv6now formats all eight words in one%-format call (verified byte-identical against glibc'sinet_ntopvia the existing hypothesis test, 2.1× faster in isolation);Packetgained an internal_from_decoded()fast-construction path, used only bydecode_frame()— the publicPacket(...)constructor still validates arbitrary arguments exactly as before. scripts/benchmark.pynow measuresdecode_frame(), the documented public chain-walking API, instead of a hand-rolled loop that predated it (#147). The benchmark'sdecode_netprotocols()kept its own copy of the pre-#88 walk loop, never updated whendecode_frame()shipped, so every decode-throughput figure this project has published — including every number indocs/CLAIMS.mdsection 1 before this release — described code the documented API's callers never actually ran.benchmarks/baseline.json, five tiers and this fix stale at a v1.3.0-era figure, was refreshed to match.
See docs/CLAIMS.md's "Re-measured after closing the
dpkt-throughput regression" section for the full profiling writeup,
before/after numbers under both the old and new benchmark
methodology, and updated 1.1/1.2/1.6 figures.
- Addressed CodeFactor's static-analysis findings on the tooling
scripts (#156).
scripts/pyodide/check_in_pyodide.pyextracted the built wheel into a hardcoded, predictable/tmp/netprotocols- wheelpath; it now usestempfile.mkdtemp(), verified against a real Pyodide runtime (node scripts/pyodide/run_in_pyodide.mjs) decoding the full corpus unchanged.scripts/check_fixtures.py's_check_l3— one 137-line function walking IPv4, IPv6, GRE tunneling, VLAN and every upper-layer checksum — is split into one small function per protocol; output is byte-identical on the full 97-frame fixture corpus before and after.scripts/benchmark.py's three broadexcept Exception: continueblocks are unchanged but now documented:dpktandscapyhave no shared "malformed frame" exception the way this project's ownProtocolErrordoes, so a bareexceptis the correct interop boundary, not a swallowed bug. The flagged duplication betweenbenchmark.pyandcheck_in_pyodide.py's minimal pcap readers — nearly byte-identicalread_pcap/corpus_framesfunctions — is now shared via a newscripts/_pcap.py. An initial pass left the duplication in place, reasoning both scripts' docstrings required each verification path to stand fully independent of the others; re-reading them shows that claim is narrower than stated — "standalone" there means not depending on netprotocols (the thing each script verifies), the same usageCONTRIBUTING.mdandcheck_fixtures.py's own docstring use, never independence from sibling scripts._pcap.pyis itself stdlib-only and does not import netprotocols, so it preserves the property the docstrings actually document. Verified against a real Pyodide runtime after the extraction: the corpus still decodes unchanged, andcheck_fixtures.py's own, materially differentread_pcap(it additionally validates linktype and length) is untouched, since it was never part of this duplication.
- Corrected six README.md claims an independent audit against the
live repo found stale or overstated, none of them accidental
regressions — each had simply drifted from what it once described.
Wheel size (85.6 KB / ~30× smaller than scapy) was measured against
the
2.0.0wheel, two releases behind; rebuilt fromHEAD, it's 88.3 KB / ~29× (docs/CLAIMS.md§1.5 corrected to match). The typing bullet's "107 of [scapy's] files" enable strict mypy checking was a rawwc -lover scapy's enabled-files list including blank lines and comments; filtered the way scapy's own tooling does, it's 89 (docs/CLAIMS.md§2.1 corrected, with the mismeasurement documented so it doesn't recur). The Pyodide/browser bullet credited "dpkt and pypacker import cleanly" to the real-Pyodide CI job; that job only ever imports netprotocols under Pyodide (confirmed by readingscripts/pyodide/check_in_pyodide.py) — the dpkt/pypacker rows come from a separatesys.meta_path-blocklist simulation under ordinary CPython, not from CI (docs/CLAIMS.md§3.1 reworded to say so explicitly). The CI-gating bullet's closing clause, "the rest have no performance benchmark at all," was contradicted by the very citation it points to —docs/CLAIMS.md§1.7 documents that scapy and PyTCP-net_proto do ship benchmark scripts, just not CI-wired; reworded to the claim the table actually supports (none of the ten gates on a regression). The Contributing section's "pytest,mypy, andruff check— all three are enforced by CI on Python 3.12-3.14" overstated the matrix: onlypytestruns on 3.12-3.14;mypyandruff checkeach run on 3.12 only. The Roadmap section's "everything through 2.2.0 has landed onmaster" didn't mention that a further, unreleased fix (#147) has since landed on top of 2.2.0 — added a clause naming it. A seventh finding — the Roadmap's claim that "only 2.0.0 was an actual PyPI release" — is contradicted by PyPI itself (2.2.0, and in fact five earlier minor/patch versions, are also published there); left unfixed pending a maintainer decision on whether 2.2.0's publication was intentional, since fixing the prose first would paper over a real process question. - Resolved the seventh finding above: 2.2.0's PyPI publication was confirmed intentional. The Roadmap section's "per the roadmap's own release policy, only 2.0.0 was an actual PyPI release" is now "the roadmap's original 'only at a major version bump' release policy wasn't actually held to: both 2.0.0 and 2.2.0 — a minor release — are on PyPI," and the roadmap table's 2.2.0 row gained the same released marker 2.0.0 already carried. Issue #107, the source both docs draw this from, updated its own stated policy line with a dated correction rather than silently rewriting history.
- A fresh independent audit for #101 found four more genuine drifts
and fixed them, none of them regressions — just the register falling
behind a codebase and a README that both kept moving.
docs/CLAIMS.md§5.3's statement count (1,935) had drifted from the live count of 2,091 as the codebase grew — the coverage percentage held steady only because the miss count never moved, masking it;pyproject.toml's own inline comment was still quoting an even older 1,441 and is now corrected too. §5.7's "79 tests" fortests/test_walk.pyundercounted the live 85: one test parametrized over the corpus's first 40 frames now collects its full 40 instances because the corpus has since grown past that slice, not because tests were added. §1.6 overstated its own claim about README.md, saying the decode-depth figure travels with the throughput figure "in the same sentence" there; they're adjacent bullets, not one sentence — corrected. README's Pyodide/browser bullet said outright that "pypacker was not tested", contradicted bydocs/CLAIMS.md§3.1's own simulation table two paragraphs away, which shows pypacker importing cleanly under the identical CPython-side check used for dpkt; reworded to say so, and to stop implying the scapy-import failure was observed directly inside the real Pyodide CI run rather than established by source citation plus that simulation. README's CI-gating bullet lumped PyTCP-net_proto in with three libraries whose benchmark code targets the library being compared;docs/CLAIMS.md§1.7's own citation notes PyTCP-net_proto's benchmark exercises its RX daemon instead — reworded to keep that distinction rather than flattening it. - Restored this file's own missing
## [2.2.0]version header. A prior documentation commit deleted it while inserting an adjacent bullet, which silently re-merged the entire tagged, PyPI-published 2.2.0 release back under## [Unreleased]— the section below is what agit showof thev2.2.0tag's own CHANGELOG.md actually contained at release time.
-
Typed accessors for every enum-backed field.
_enums.pydefinesEtherType,IPProtocol,ARPOperationandARPHardwareType, but until now no decoded field exposed them — only the*_namedisplay strings, and the enums themselves were used only for dispatch. Every field with a fixed wire vocabulary now has an*_enumcompanion alongside the existingintfield and its*_namestring, mirroring thesrc/src_addressprecedent 1.3.0 established for IP addresses:Ethernet.ethertype_enum,VLAN.ethertype_enum,GRE.protocol_enum,IPv4.protocol_enum,IPv6.next_header_enum(and the three IPv6 extension headers that share the field:IPv6HopByHopOptions,IPv6DestinationOptions,IPv6Routing,IPv6Fragment),ARP.oper_enum,ARP.ptype_enum,ARP.htype_name/ARP.htype_enum(new —ARPHardwareTypewas exported but referenced nowhere), andDHCP.htype_name/DHCP.htype_enum. Each returnsNone— never raises — for a wire value this library does not enumerate, sobytes(decode(x)) == xis unaffected for unrecognized values; the rawintfield stays canonical and round-trips regardless (#95). -
IPv4, TCP and DHCP curate a short
__match_args__by hand. Their full auto-generated positional form runs to 11-15 fields — unusable positionally, since nobody writes, or gets right, a fourteen-slot pattern.IPv4.__match_args__ == ('src', 'dst', 'protocol'),TCP.__match_args__ == ('src_port', 'dst_port', 'flags'),DHCP.__match_args__ == ('op', 'chaddr', 'yiaddr')— the two or three fields someone draftingcase IPv4(...)actually reaches for. Every other header (including the still-wideIPv6, at 8 fields) keeps the plain auto-generated tuple, and keyword patterns (case IPv4(protocol=6)) are unaffected either way and stay the documented default.__match_args__is part of the public API once documented, so the chosen order is pinned bytests/test_pattern_matching.pyrather than left free to drift. ARCHITECTURE.md anddocs/CLAIMS.mdare updated to describe this as a deliberate, tested exception rather than the "this library never hand-declares__match_args__" absolute they stated before (#94). -
DNS resource records expose typed RDATA, and every question, not just the first.
DNSResourceRecord.rdata_textdecoded A/AAAA/MX/ SOA/etc. into a display string only; a newrdata_valuefield adds the typed decoding alongside it (rdata_textis unchanged) —ipaddress.IPv4Address/IPv6Addressfor A/AAAA, the decompressed targetstrfor NS/CNAME/PTR, a newMXRecord(preference, exchange)for MX, a newSOARecord(mname, rname, serial, refresh, retry, expire, minimum)for SOA,list[str]of character-strings for TXT, andNone— never raises — for the types this library does not decode. Computed eagerly at parse time, likerdata_textalways has been: a name inside RDATA (a CNAME's target, for instance) can use DNS compression against the whole message, so decoding it needs the same message-wide contextrdata_textalready required, which a property computed lazily fromrdataalone could not resolve. Separately,DNS.questionsadds atuple[DNSQuestion, ...]walking every entry of the question section —question_name/question_type/question_classexposed only the first and are unchanged (#96). -
A typed
DHCPOption, alongsideDHCP.option_map.option_mapwas the only accessor in the library returning a baredict[int, bytes]rather than typed objects; it is unchanged (still returns exactly what it always did). A newparsed_optionsproperty wraps the same, already RFC-3396-concatenated, mapping into atuple[DHCPOption, ...], mirroringTCPOption/IPv4Option:code,data,code_name, and a decoded.valuefor the option codes this library understands — a singleipaddress.IPv4Addressfor Subnet Mask (1)/Requested IP Address (50)/Server Identifier (54), a tuple of one or more for Router (3)/Domain Name Server (6) (RFC 2132 permits repeating either), the integer seconds for IP Address Lease Time (51), the raw byte for Message Type (53).None— never raises — for codes this library does not decode and malformed option data (#96). -
IPv4Option.valuedecodes Record Route, Timestamp and Router Alert.IPv4Optionhadkind_nameand no.value— the three common kinds (RFC 791 §3.1, RFC 2113) were named but their contents left raw, unlikeTCPOption, which already decodes its values. Record Route (7) decodes to atuple[ipaddress.IPv4Address, ...]of the addresses recorded so far — the option's own pointer byte says how many of the address slots are actually filled, not the option's total length. Timestamp (68) decodes totuple[int, ...]of plain millisecond timestamps when its flag selects that shape, ortuple[tuple[ipaddress.IPv4Address, int], ...]of (address, timestamp) pairs when the flag says each entry carries one — the overflow counter and pointer are not decoded, readdataraw for those. Router Alert (148) decodes to the 2-byte value asint.None— never raises — for every other kind and for malformed data on one of these three (a bad pointer, an unrecognized Timestamp flag, a short buffer) (#96). -
IPv6Routing.segmentsandIPv6Option.valuefor Router Alert / Jumbo Payload.IPv6Routing.datawas entirely unparsed — no segment-list extraction for any routing type. RH0 (routing_type0, deprecated by RFC 5095 but still seen — RFC 2460 §4.4) and Mobile IPv6 (2, RFC 6275 §6.4) both store a 4-byte reserved field followed by one IPv6 address per segment;segmentsdecodes that into atuple[ipaddress.IPv6Address, ...]. RPL Source Routing (3, RFC 6554) is deliberately not decoded: RFC 6554 §3 elides a shared prefix from each intermediate address relative to the enclosing packet's destination address, context this one-extension-header accessor does not have —datastays available raw.Nonefor every other routing type and for malformed address data. Separately,IPv6Option.value(Hop-by-Hop / Destination Options TLVs) now decodes Router Alert (5, RFC 2711 §2.1) and Jumbo Payload (194, RFC 2675 §2) into typedints, the last of #96's four pieces (IPv6Option"likewise decode[d] no values");Nonefor every other type and malformed data, same contract throughout this tier (#96). -
CI proves the library runs under a real Pyodide (WebAssembly) runtime, not just that the modules
scapy/dpktneed are individually blocked. A newpyodidejob (.github/workflows/ci.yml) boots actual Pyodide under Node viascripts/pyodide/run_in_pyodide.mjs, installs the wheel this job just built, and decodes the entire real-capture fixture corpus with it — seescripts/pyodide/check_in_pyodide.py. That surfaced a genuine bug along the way:IPv6.decode()/bytes(IPv6(...))usedsocket.inet_ntop/inet_pton(AF_INET6, ...), and Pyodide's CPython build hasAF_INET6sockets disabled, so every IPv6 frame failed to decode there._base.py'sipv6_to_bytes/bytes_to_ipv6are now a pure-Python implementation (ipaddressfor parsing; a hand-rolled RFC 5952 canonicalizer, differentially verified against glibc'sinet_ntopacross 500,000+ random addresses plus both of its dotted-quad special cases, for formatting —str(ipaddress.IPv6Address)was tried first and rejected: it disagrees with glibc on IPv4-mapped addresses, and disagrees with itself between Python 3.11 and 3.12). IPv4 addressing is unaffected; behavior for every existing platform is unchanged, exception type included (#99). -
Nightly fuzzing with a moving seed.
tests/test_fuzz.py's"netprotocols"Hypothesis profile is deterministic on purpose (200 examples,derandomize=True) so a pull request is reproducible — but that also means every build since it was written has run the same 200 inputs. A new"nightly"profile (10,000 examples, a real random seed each run) runs the whole suite on a new schedule,.github/workflows/fuzz.yml(03:00 UTC daily, plus manual dispatch), kept out ofci.ymldeliberately —ci.ymlis reused byrelease.ymlviaworkflow_call, and aschedule:trigger there would fire the whole PR/release gate on a cron, not just this exploratory job..hypothesis/'s example database accumulates across nightly runs viaactions/cache(keyed by run id with a prefix restore-key, since a fixed key would restore forever but never actually save a new entry) and uploads as a workflow artifact on failure, so a counterexample is recoverable without repo write access; a failed scheduled run's own red build is the notification (GitHub already does this by default), so nothing here files an issue on top of it. Reproduce locally:HYPOTHESIS_PROFILE=nightly uv run pytest. Also adds a targeted strategy building well-formed TCP SYN options (MSS, window scale, SACK-Permitted, SACK, timestamps) — the real-capture corpus never caught a SYN, so unlike NOP/Timestamps these otherwise depend onmax_examplesalone stumbling into a well-formed TLV by chance (#98). -
A pcap/pcapng reader that takes bytes, not filenames. New
netprotocols.pcap:read_captures(buffer)auto-detects classic pcap vs. pcapng from its magic number and yieldsCapturedFrame(timestampin nanoseconds since the Unix epoch, normalized from whatever resolution the source recorded,datathe frame's raw bytes);read_pcap()/read_pcapng()are the same for a caller who already knows the format. pcapng support covers exactly the block types frames can come from — Section Header, Interface Description (read only for itsif_tsresoloption), Enhanced Packet, and Simple Packet (which the format gives no timestamp at all, hence0); every other block type is skipped wholesale. A malformed or truncated capture raises the newMalformedCaptureError(ProtocolErrorfamily, nolaxmode — a corrupt container is a different failure shape than a malformed header inside one already- extracted frame). Format detection is eager; producing frames is lazy (a generator), so a bad record downstream doesn't invalidate what already iterated cleanly, and a huge capture is never forced into a list of frames nobody asked for.tests/conftest.pydrops the private classic-pcap reader every test file reached for —pcap_frames()is now a thin adapter over the shippedread_pcap(), and~10test files were migrated onto it (a real migration, not a rename:tests/test_pcap.pykeeps its own independent reference reader, deliberately never importing the module it is cross-checking, the same "standalone, so a shared bug can't cancel itself out" precedent asscripts/benchmark.pyandscripts/check_fixtures.py).One design idea was tried and reverted on measurement: slicing each frame lazily out of a
memoryviewover the whole buffer, to keep large captures zero-copy. Measured across synthetic captures up to ~140MB, it was 0.91x-0.98x — never faster, sometimes slower — because a real capture is many small frames, and amemoryviewslice's own overhead is paid per frame; #88's identical finding for a single frame generalizes rather than being contradicted.docs/CLAIMS.md5.8 is corrected accordingly — it previously forward-referenced this issue with an unverified "1.8x" figure (#100).
- The comparative-claims embargo is lifted (#107, #124).
docs/CLAIMS.md1.7 gained a per-project table auditing ten comparable Python packet libraries' CI configurations (dpkt, scapy, pypacker, construct, pcapkit, dnspython, pyshark, nfstream, stackforge, PyTCP-net_proto) for an actual performance-regression gate — cited file:line or workflow, dated 2026-09-04; none of the ten gate on one, so the comparative form of 1.7's claim is now stated with that evidence (#124). Every section that previously carried aCOMPARATIVE — HELDbanner is re-measured against the current tree and published: decode throughput (1.1, 1.2), encoding throughput (1.3), import time (1.4), wheel size (1.5), decode depth (1.6), themypy --strictcomparison (2.1),match/caseexclusivity (2.2), the five-property combination (2.3), Pyodide/browser support (3.1), and the permissive-licence wedge (4.1). One finding moved against this project rather than for it and is reported as such: three tiers of added surface since Tier 1 (#87's dispatch rewrite, #88's chain walker, #91's structured errors chief among them) reversed decode throughput from 1.16× faster than dpkt back to roughly 11% slower — still within the 15% band claim 1.2 names, just no longer ahead. Two new reproduction scripts back claims that previously had none:scripts/benchmark_encode.py(1.3) andscripts/benchmark_import.py(1.4).README.mdgains a "Why NETProtocols" section drawing the now-published claims into the project's front door, in the tonedocs/CLAIMS.md4.2 sets for writing about competitors.
-
The round-trip property (
bytes(decode(x)) == x) is now Hypothesis-generated for all 18 protocols, not 4. It previously held only forEthernet,UDP,TCPandIPv6Fragment; the other 14 rested on a single example each.tests/strategies.pyadds one reusable strategy per protocol — reusable because a strategy that generates valid instances is useful for more than this one property — andtests/test_fuzz.py::TestGeneralizedRoundTripsasserts the property in one method, parametrized over all 14.The interdependent-field protocols the issue specifically flagged are generated as consistent combinations, never independently: IPv4 draws
ihlfirst and sizesoptionsto match; the three IPv6 extension headers drawhdr_ext_lenfirst and size their TLV bytes to match; GRE drawsflagsfirst and computesfields' length from the same_optional_len()the decoder itself uses, so the two can never silently disagree.The 14 single-example assertions already living in each protocol's own test file (
test_arp.py::test_round_tripand so on) are kept as regression anchors — a fixed example pinned to a real captured header catches a specific regression fast and readably, which a generated property does not replace.One adjacent gap closed while surveying this:
DHCPandGREwere missing fromtest_fuzz.py::ALL_PROTOCOLSentirely, so neither had ever been fuzzed with untrusted bytes for basic decode safety (any input either decodes or raises ProtocolError, never anything else). Both are now included.
-
match/casedissection is documented. It already worked on every decoded header, with zero code changes needed — a frozen dataclass auto-generates__match_args__, and every field with a fixed wire vocabulary is anIntEnum, so a value pattern binds the plainintthe decoder stored. None of that appeared anywhere:match packet.layers: case [_, IPv4(protocol=IPProtocol.TCP) as ip, TCP(flags_str=f), *_] \ if "SYN" in f and "ACK" not in f: print(f"connection attempt from {ip.src}")
README gains a first-screen example and a dedicated section; ARCHITECTURE.md explains the two mechanisms and the two ways a contributor can quietly break them (reordering a class's fields changes what a positional pattern binds to; degrading a fixed- vocabulary field from
IntEnumto a bareintmakes a value pattern stop matching without raising).tests/test_pattern_matching.pypins both mechanisms directly and runs the README's own example over the corpus, so a regression in either is caught rather than incidental. -
Structured diagnostics on every
ProtocolError. Every exception used to carry only a formatted string — the full attribute set on a raisedTruncatedHeaderErrorwasargs,add_note,with_traceback. A fuzzing harness, conformance suite, or protocol-validation tool that wanted to know where a parse failed had to regex the message. Every raise site insrc/now attaches:try: packet = decode_frame(frame) except ProtocolError as e: print(e.protocol, e.field, e.offset, e.frame_offset, e.expected, e.actual) # <class 'netprotocols.layer3.ip.IPv4'> ihl 0 14 >=5 0
protocol— the class that raised. Set on every single raise site.field— the attribute at fault, where one field is at fault.offset— byte offset of the problem, relative to thedecode()buffer for a fixed-header error, or to thefieldattribute (options,body,sections) for an on-demand parse — a TCP option error's offset is relative toheader.options, not the frame.Nonefor a__post_init__validation error, which sees field values, never the bytes they came from.frame_offset—offsetrebased to the whole captured frame.decode_frameis the only code holding the cursor needed to do this, so it's the only thing that sets it; a bareSomeClass.decode()call leaves itNone.expected/actual— added wherever there's a concrete pair to state beyond the message text.
All five default to
None, and no message string changed — every existingstr(err)andmatch=assertion holds. New public name:MaxDepthExceededErrorgains the same attributes as every otherProtocolErrorsubclass (it already existed as of thedecode_framework; this is the first release to give it structured context too). -
decode_frame(): the chain walker ships with the library. The README taught a hand-rolled eight-line loop, ARCHITECTURE.md showed it again, and the test suite kept its own copy — so the library's most-used function was the one function it did not provide. It does now, with the parts a copy-pasted loop never has:from netprotocols import decode_frame packet = decode_frame(frame) # Packet(Ethernet(...), IPv4(...), TCP(...)) frame[packet.consumed:] # whatever the chain did not decode
- An explicit starting layer.
decode_frame(buf, start=IPv4)walks a buffer that begins mid-stack — a tunnel payload, a packet quoted inside an ICMP error, a non-Ethernet link type. There was previously no way to ask for this. - Bounded depth.
max_depth(default 32) caps the chain and raises the newMaxDepthExceededError, rooted atProtocolErrorlike everything else. Every header already validated its own length, so a chain always terminated; the bound turns a crafted frame's very long walk into an immediate named error. The deepest chain in the 97-frame corpus is 5. - A lax mode that reports instead of raising.
lax=Trueends the walk on aProtocolErrorand returns the layers decoded so far, with the reason onpacket.stopped_by— what a capture tool needs when frame 4,000,001 is malformed. It relaxes the walk, never a decoder: every layer returned was decoded under the ordinary strict rules. - Per-call decoder overrides.
decode_as={"udp.port": {6969: DNS}}reads DNS on a nonstandard port for one call, without touching global state;registry=takes a prepared registry for bulk work.
Packetgainsstopped_by(why a walk ended early,Nonefor a packet you built) andconsumed(the bytes its headers occupy). Both default to the constructed-packet values, soPacket(eth, ip)is unchanged.On
memoryview: the walker slices what it is given and does not convert. Measured on the corpus, wrapping each frame in amemoryviewruns at 0.95x the plain-byteswalk — for one small frame the view costs more to build than the copy it saves — while amemoryviewover a large capture buffer keeps slices zero-copy. Converting internally would have been worse than either. - An explicit starting layer.
-
A public protocol registry: third parties can now extend the decode walk without editing library source. Dispatch was four hardcoded functions with dict literals inside them and no hook of any kind — a protocol this library does not implement (MPLS, VXLAN, a proprietary telemetry header) could only be added by forking. It is now five named tables owned by
netprotocols.registry, and registering against one is all it takes:from netprotocols.registry import register @register("ethertype", 0x8847) class MPLS(Protocol): ... register("ip.proto", 132, SCTP) # for a class you did not write
The tables are
ethertype,ip.proto,ip.proto.v6,udp.portandtcp.port, each named after the wire field it dispatches on.ip.proto.v6inheritsip.proto, which is how the IPv6-only gating generalises: the four extension headers are registered in the v6 table alone, so an IPv4 packet withprotocol=0still cannot conjure a Hop-by-Hop layer — and because inheritance is resolved at registration rather than at lookup, the gating costs nothing on the hot path. Dispatch behaviour is unchanged entry for entry.Registrations land in the process-wide
DEFAULTregistry;Registry.from_defaults()gives an isolated one for embedding or test isolation, andRegistry.derive()makes a copy-on-write child. Registering over an existing key raisesRegistryConflictErrorunlessoverride=Trueis passed, so two packages claiming the same port cannot silently resolve by import order; re-registering the same class to the same key is a no-op, since a decorator re-runs whenever its module does.New public names:
Registry,register,register_all,DEFAULT,RegistryConflictError,UnknownTableError.
next_protocol()accepts an optional registry. Threading a per-call registry through the walk needs the dispatch to be redirectable, andnext_protocol()read the process-wide tables directly. It now takesregistry=None, passed to the same dispatch helpers as before, so no table knowledge is duplicated and the default path stays a singledict.get. Measured in one process, the optional parameter costs +2.1 ns per dispatch — roughly 0.1% of a frame decode. Every existing zero-argument call is unaffected.- Port-based dispatch is a table lookup rather than a rebuild.
udp_app_classandtcp_app_classre-ran their deferred imports and rebuilt adictliteral on every call — they were outside the scope of the earlier dispatch-hoisting work, which named only the EtherType and IP-protocol functions. Both now read the registry's flat tables:udp.port303.1 → 46.0 ns (6.6x),tcp.port186.8 → 45.1 ns (4.1x), measured old and new shapes in one process.ethertypeloses its lazy-build guard (51.8 → 47.7 ns) andip.protois unchanged, having already been a table. Corpus throughput moves about 1% — only 28 of the 97 corpus frames reach a transport header and therefore do a port dispatch at all — which is below this machine's run-to-run noise; the per-call figures above are the measurement that resolves. - The layer modules no longer import each other's classes. The
built-in decoder map moved into
_defaults.py, which registers it once from__init__.pyafter every protocol class exists, so the function-body imports that kept the module graph acyclic are gone fromvlan.py,gre.py,tcp.py,udp.pyandipv6_ext.py; those dispatch helpers are now ordinary module-level imports. The tables are built at package import instead of on first dispatch, so the lazy-build branch is off the hot path entirely. - DNS section parsing happens once, and no longer re-serializes the
message to read it. Six helpers called
bytes(self)— a full re-serialization of the whole message — so a single.answersaccess rebuilt the message 14 times; andanswers,authoritiesandadditionalseach re-parsed all three sections, so reading all three parsed the message three times. The parsers are now module-level functions working directly from thesectionsbytes the instance already holds, in section-relative offsets (a compression pointer, which counts from the start of the message, is translated once), and the three accessors share a single parse cached on those immutable bytes. Measured here on a corpus response:.answers16.84 → 0.20 us, all three sections 52.08 → 0.54 us, and one uncached parse 17.03 → 12.17 us from dropping the re-serializations alone. Nothing is stored on the frozen instance — the cache is a bounded module-level memo keyed by value, so equal messages share a parse and records (frozen dataclasses) are shared rather than copied. The byte-exact round-trip is unchanged. A compression pointer that addresses the fixed header now raisesInvalidFieldErrorinstead of decoding header bytes as labels. No API change. - The decoder no longer re-validates the addresses it just
generated. Every header's
__post_init__ran the address validators, including for instances built bydecode()— so a MAC mechanically rendered from six bytes bybytes_to_mac()was immediately matched againstmac_regexto confirm what the conversion had already guaranteed.Ethernet,ARPandIPv4now build their decoded instance directly (object.__new__plusobject.__setattr__per field), skipping__init__and__post_init__on that path only. Measured here:Ethernet.decode2330 → 830 ns (2.8x),IPv4.decode4936 → 2596 ns (1.9x), a corpus walk 76,500 → 113,200 frames/sec (1.48x). Strictness on construction is unchanged — every public constructor still validates and still raises, which is now asserted alongside a test that the decode path runs no regex at all. The__post_init__checks bypassed this way are onesdecode()establishes itself (documented at each site and in_base.py). No API change. - Protocol dispatch is a table lookup, not a table construction.
_ethertype_class()and_ip_protocol_class()re-ran their deferred imports and rebuilt adictliteral on every call — once per layer per frame, the hottest path in the library. Both now populate a module-level table on first use (the imports stay deferred, so the layer modules remain acyclic) and reduce the call to a lookup. Measured here:_ip_protocol_class1439 → 104 ns (13.9x),_ethertype_class712 → 86 ns (8.3x), and a corpus walk 58,300 → 76,500 frames/sec (1.31x). The IPv6-only gating is unchanged: the IPv4 table simply omits those numbers, so an IPv4 packet withprotocol=0still cannot decode a Hop-by-Hop layer, now asserted at the table level as well as through the public API. No API change. bytes_to_macrenders addresses withbytes.hex(":")instead of a generator overformat(). The old form ran seven generator steps and sixformat()calls per address, twice per Ethernet frame, and showed up in a corpus profile as 88,200 generator calls. Measured 16–29× faster on the call depending on run. Output is byte-for-byte identical, andmemoryview.hextakes a separator too, so a decode-time view still works. No API change.
- BREAKING:
Packet.payloadis gone. It was always exactlybytes(self)— a redundant duplicate of__bytes__/bytes(packet), which already existed and is the unambiguous spelling — so it is deleted outright rather than deprecated. This is the breaking change behind the 2.0.0 major bump. Replacepacket.payloadwithbytes(packet).
-
Packetindexes by protocol type, not just position, and is hashable.packet[TCP]returns the firstTCPlayer in wire order (KeyErrorif there is none);packet.get(TCP)returnsNoneinstead of raising.packet[0]keeps indexing positionally —__getitem__branches on whether the key is anintor a type.Packet.__hash__mirrors exactly what__eq__already compares (layers, andstopped_by's type andstr(), not its identity —ProtocolErrorhas no custom__eq__), so aPacketis now usable as a dict key or set member. -
Canonical, direction-independent flow keys.
netprotocols.flowis a new small module (FlowKey,flow_key()) that folds a TCP/UDP segment and its enclosing IPv4/IPv6 header into a key that is identical for both directions of one conversation:from netprotocols import flow_key flow_key(tcp, ip=ipv4) == flow_key(reply_tcp, ip=reply_ipv4) # True
FlowKeyis aNamedTuple— canonicalizing the two directions is comparing the two(address, port)endpoint tuples and always emitting the lexicographically smaller one first, which a plain tuple already orders natively; every other frozen dataclass in this codebase models a wire format (decode()/__bytes__/_struct), and a derived key isn't one.Packet.flow_key()is the convenience form: it walksself.layersfor the first IPv4/IPv6 and TCP/UDP layers and delegates to the free function,Noneif either is missing. Reads whichever ofIPv4.protocol/IPv6.next_headerthe enclosing header actually has — the same semantic field, different attribute name. A transport layer with no ports (ICMP) returnsNonefrom both forms, rather than raising or inventing a port-slot convention for a message type that has none. -
ICMPv4/ICMPv6gainembedded_chain: an error message's embedded packet, already decoded.decode_frame(lax=True, start=...)already handled this — an RFC-792 error message quotes only the invoking IP header plus 8 bytes of what follows, never a full TCP/UDP header, so decoding it needs the lax path and notry/except, verified with zero new code before this landed.embedded_chainis the pre-wired convenience next to the existing rawembedded_packet, same shape as an accessor-plus-typed-view pair elsewhere in this codebase:icmp.embedded_chain # decode_frame(icmp.embedded_packet, lax=True, start=IPv4) # → Packet([IPv4(...)]), stopped_by=TruncatedHeaderError(...)
Nonefor the same casesembedded_packetdegrades to (non-error message types, an empty body); starts atIPv4for anICMPv4message,IPv6forICMPv6. The README documents the distinction the issue asked for:embedded_chain'slax=Trueis the right default here because the truncation is RFC-mandated, expected input — not a license to reach forlax=Trueon a complete frame that fails to decode, which is still a bug to raise on.
- The release workflow can no longer publish untested code. Pushing
a
v*tag ranuv buildanduv publishwith no dependency on the lint, typecheck or test jobs — and because the CI workflow triggers only on pushes and pull requests targetingmaster, a tag push ran no checks at all. A tag against broken code published to PyPI unchallenged, and a published version can only be yanked, never replaced.ci.ymlis now also a reusable workflow (workflow_call), andrelease.ymlinvokes it against the tagged commit with the publish job gated behind it, so the release gate and the pull-request gate are one definition and cannot drift apart.
- A mistagged release can no longer publish the wrong version.
release.ymlbuilt frompyproject.tomland never consulted the tag, so pushingv1.4.0while the project still read1.3.0would either fail at upload against an existing version or, if that version was never released, silently publish the wrong one. The QA ladder cannot catch this — every check passes, because the code is fine and only the tag is wrong. The release now reads the version back out of the built artifact and refuses to publish unless it matches the tag. - The README no longer advertises shipped work as upcoming. Its Roadmap section listed the eight decoder-depth items tracked by #67 — all of which shipped in 1.3.0, with #67 itself closed — so the front page presented finished work as planned and pointed readers at a closed issue. It now links the current roadmap (#107) and its five release-mapped epics instead of restating individual items, which is what went stale.
- ARCHITECTURE.md no longer misstates the corpus or the source
layout. It described "93 frames across 16 scenarios" long after the
corpus reached 97 across 17, and its layout map omitted
vlan.py,gre.pyanddhcp.py. The counts now live intests/fixtures/MANIFEST.mdand the README alone — ARCHITECTURE.md points at the MANIFEST rather than keeping a third copy, which is what drifted. - Layer sub-packages now export everything their layer defines.
from netprotocols.layer7 import DHCPfailed whilefrom netprotocols import DHCPworked, because each layer's own__init__carried a subset of what the top-level package re-exports.layer3was missingGRE,IPv4Option,IPv6Option,NDPOptionandIGMPv3GroupRecord;layer4was missingTCPOption;layer7exported onlyDNS, omittingDHCP,DNSOverTCPandDNSResourceRecord. Purely additive — no name changed meaning.
- Comparative claims are under embargo until the roadmap closes.
docs/CLAIMS.mdgains a standing rule and a per-claimCOMPARATIVE — HELDmarker: nothing mentioning scapy, dpkt or any other library reaches the README, release notes or package metadata until #107 is finished. The measurements keep being recorded — the register exists to hold evidence, not to publish it — and ship once, together, rather than in pieces that each need defending. The rationale is in the numbers: claim 1.2 went from "2.9x slower than dpkt" to "1.16x faster" inside a single tier. - Three differentiators found during Tier 1 are now tracked as claims
rather than living in pull-request descriptions: decode depth (1.6 —
the corpus walk reaches a deeper layer than dpkt on 27 of 97 frames,
reproducible with
scripts/benchmark.py --depth, which this change adds), the CI throughput gate (1.7), and strict construction on a decode path that pays nothing for it (5.4). The stale "we are ~86% of dpkt" line in "Claims we must not make" is corrected, and a rule added that a superiority claim must name its axis — scapy crafts, sends and covers thousands of protocols, so the codec axes are where the evidence is. - A reproducible decode benchmark, and a CI job that fails on a
regression.
scripts/benchmark.pywalks the 97-frame corpus and reports frames/sec;--comparetimesdpktandscapyon the same frames (both dev-only extras in a newbenchdependency group — the package still has zero runtime dependencies). Because absolute throughput is a property of the machine, every run also times a fixed calibration workload and reports a normalized figure, which is what--checkcompares againstbenchmarks/baseline.json. The CI job blocks at 15% below the baseline: measured, that is about four times the noise it must tolerate — the job's first run landed 3.7% from a baseline recorded on entirely different hardware, and run-to-run spread on one machine is ~2%, while the Tier 1 changes moved the number by 30-90% each. A failing check re-measures once before failing, so a runner that loses CPU to a neighbour does not block an unrelated pull request. Comparison output carries its own caveats — notably that the libraries are not asked for identical work, since dpkt leaves the DNS-over-TCP payload as raw bytes where this library decodes it — because a benchmark nobody can check is the problem #86 set out to fix, not the goal. tests/test_version.pyholdsnetprotocols.__version__against the version inpyproject.toml. The two were kept in step by hand and nothing checked them, so a bump that missed one would ship a package whose metadata and__version__disagree.tests/test_docs.pyholds documented facts against the fixtures: the MANIFEST's and README's frame/scenario counts must match the real corpus, ARCHITECTURE.md must not reintroduce a third copy of them, and the layout map must mention every shipped module. It also guards the README's Roadmap section against pointing back at the superseded #67 or re-listing work that has already shipped.tests/test_exports.pykeeps the layer and top-level export sets in agreement, deriving the expectation from each object's__module__rather than a hand-written list, so a protocol added to the top level but forgotten in its layer fails the suite.- Coverage is now enforced, not merely reported:
fail_under = 98in[tool.coverage.report]. The suite covers 99% of 1441 statements — the only misses arePacket.__repr__and its__eq__NotImplementedbranch — so the gate is set below the current figure to leave room for a legitimately unreachable branch, and well above the level at which the bar would stop meaning anything. tests/test_workflows.pyasserts the release gate stays wired: thatci.ymlremains callable, that some release job invokes it, thatpublishdepends on that job, and that every localuses: ./…reference resolves to a workflow declaringworkflow_call. The wiring is otherwise easy to remove silently — releases keep working while the gate quietly stops existing — and it cannot be verified by running it, since publishing is irreversible.docs/CLAIMS.mdrecords the positioning claims produced by the post-1.3.0 competitive analysis, each with its evidence, a reproduction path and a publication status —VERIFIED,GATED ON #nn, orNEEDS RE-MEASUREMENT. Several of the strongest claims are not true yet (decode throughput against dpkt is gated on the Tier 1 performance work; the browser claim is untested until a Pyodide CI job exists), so the register also lists what must not be said and why. Feeds the README as each roadmap tier lands; see #101 and the roadmap in #107.
- IEEE 802.1Q VLAN tags (
VLAN, 802.1Q-2018 §9.6 / 802.1ad QinQ): single and stacked (QinQ0x88A8, legacy double-tagged0x9100) tags decode as one layer per tag; the Tag Control Information word is split intopcp/dei/viddataclass fields validated in__post_init__(InvalidFieldError), with the packed 16-bit view kept as thetciproperty;VLANis registered in the property-based fuzz suite and theEtherTypedisplay names are covered by the enum completeness test. - IGMPv3 group records (
IGMPv3GroupRecord, RFC 3376 §4.2): a v3 Membership Report (type0x22) now parses its group-record array on demand.IGMP.group_recordsyields oneIGMPv3GroupRecordper record (record type + display name, multicast group, source-address list, raw auxiliary data) andIGMP.num_group_recordsreads the count; other message types returnNone. Parsing reads the raw body and never re-encodes, so the byte-exact round-trip is preserved, and a lying record/source count or a truncated record raisesInvalidFieldError(bounded — never hangs or over-reads). - IGMPv3 query fields (RFC 3376 §4.1): a v3 Membership Query (type
0x11) now exposes its fields past the group address — thes_flag(suppress router-side processing),qrv,qqic, andquery_source_addressesaccessors parse the raw body on demand. A v2 (8-byte) query and non-query types returnNone, and a source count that runs past the message raisesInvalidFieldError. - DHCP (
netprotocols.DHCP, RFC 2131/2132) — the fixed BOOTP header (op, xid, the client/your/server/gateway addresses, the 16-byte client hardware address, and the server-name / boot-file fields) decodes in full; the magic cookie and TLV options are kept raw and parsed on demand.option_mapwalks the options (concatenating a value split across appearances, RFC 3396) andmessage_type/message_type_nameread the DHCP message type (option 53). Dispatched from UDP by well-known port (67/68); terminal, with a byte-exact round-trip and the same bounded-parse contract as DNS (InvalidFieldErroron a missing cookie or an option that overruns the buffer). - GRE (
netprotocols.GRE, RFC 2784/2890) — Generic Routing Encapsulation, dispatched from IPv4/IPv6 protocol 47. The four-byte header (flags/version + protocol type) decodes with the optional checksum, key, and sequence-number fields that the flag bits announce kept raw and surfaced through accessors. The payload chains onward by theprotocol_typeEtherType, so a GRE-tunnelled IPv4/IPv6 packet keeps decoding; the round-trip stays byte-exact regardless of which optional fields are present. - GRE checksum arm (
netprotocols.checksum, RFC 2784 §2.5):compute/verifynow cover GRE — the internet checksum over the GRE header plus its payload with the checksum field zeroed and no pseudo-header.compute(gre, payload=...)requires the Checksum-Present bit (and its field) and raisesInvalidFieldErrorotherwise;verifyof a header whose Checksum-Present bit is clear returnsTrue— a frame cannot fail a checksum it does not carry — mirroring the UDP-over-IPv4 zero rule. - Richer address accessors (README roadmap): read-only
_addressproperties return stdlibipaddressobjects alongside the canonicalstrfields, for comparison, subnet membership, and arithmetic —IPv4.src_address/dst_addressandARP.spa_address/tpa_addressasipaddress.IPv4Address,IPv6.src_address/dst_addressasipaddress.IPv6Address, and the fourDHCPaddress fields asciaddr_address/yiaddr_address/siaddr_address/giaddr_address. Purely additive: thestrfields stay the round-tripping representation. MAC addresses staystr— the stdlib has no EUI type. - IPv4 options (
IPv4Option, RFC 791 §3.1): the options TLV list now parses on demand, mirroring the TCP-option work —IPv4.parsed_optionsyields oneIPv4Optionper option in wire order (kind +kind_name, rawdata). The common kinds are named: End of Option List and No-Operation (single-byte; EOL ends the parse, so padding after it is not returned), Record Route (7), Timestamp (68), and Router Alert (148, RFC 2113); unknown kinds keep their rawdatawith a numeric fallback name. Parsing reads the rawoptionsbytes and never re-encodes, so the byte-exact round-trip is preserved; an option length below the 2-byte minimum or one that runs past the options raisesInvalidFieldError(bounded — never hangs or over-reads). - DNS resource records (
DNSResourceRecord, RFC 1035 §4.1.3): the answer, authority, and additional sections parse on demand —DNS.answers/DNS.authorities/DNS.additionalsyield records (name, type +rtype_name, class, TTL, rawrdata, and a decodedrdata_text: IPv4/IPv6 for A/AAAA, the target name for CNAME/NS/PTR, and MX/TXT/SOA; hexadecimal otherwise). Parsing reads the raw sections and never re-encodes, so the byte-exact round-trip holds; a record or compressed name that runs past the message raisesInvalidFieldError. - TCP options (
TCPOption, RFC 9293 §3.1): the options TLV list now parses on demand —TCP.parsed_optionsyields oneTCPOptionper option in wire order (kind +kind_name, rawdata, and a decodedvaluewhere this library understands the kind: the segment size for MSS, the shift count for Window Scale, a(tsval, tsecr)pair for Timestamps, and(left_edge, right_edge)pairs for SACK; RFC 7323/2018). EOL and NOP are single-byte (EOL ends the parse); unknown kinds keep their rawdatawithvaluedegrading toNone. Parsing reads the rawoptionsbytes and never re-encodes, so the byte-exact round-trip is preserved, and an option length below the TLV minimum or one that runs past the options raisesInvalidFieldError(bounded — never hangs or over-reads). - ICMP message bodies (RFC 792 / RFC 4443):
ICMPv4/ICMPv6gain a rawbodyfield — the message data after the 8-byte header — so a decoded message is self-contained (likeIGMP/DNS),header_lenconsumes the whole IP payload, and the layer stays terminal with a byte-exact round-trip. Echo requests/replies (v4 types 8/0, v6 128/129) exposeidentifier/sequence_numbersplit fromrest, and the error messages (v4 Destination Unreachable / Redirect / Time Exceeded / Parameter Problem; v6 types 1-4) exposeembedded_packet— the invoking datagram, decodable asIPv4/IPv6. The accessors read on demand and degrade toNonefor other message types or an empty body, never raising. A decoded message now carries its body inbytes(layer), sochecksum.compute/verifyneed no separatepayloadfor it (passing one for a header-only object still works). - IPv6 Neighbor Discovery (
NDPOption, RFC 4861):ICMPv6now parses NDP messages on demand —ndp_target_addressreads the 16-byte target of a Neighbor Solicitation/Advertisement (135/136), andndp_optionswalks the option TLVs of Router Solicitation/Advertisement, Neighbor Solicitation/Advertisement, and Redirect at each message's own options offset. EachNDPOptioncarries itstype+type_nameand rawdata; a Source/Target Link-Layer Address option (1/2) reads back as a MAC string vialink_layer_address, and Prefix Information (3) / MTU (5) stay raw. Non-NDP message types returnNone. Option lengths count in 8-octet units: a zero length (which must not loop), a length past the message, or a body shorter than the message's fixed fields raises - IPv6 extension-header options (
IPv6Option, RFC 8200 §4.2): the Hop-by-Hop and Destination Options headers now parse their option TLVs on demand —parsed_optionsyields oneIPv6Optionper option in wire order, padding included (Pad1 is a lone type byte; everything else is type/length/data). Each option carries itstype+type_name(Pad1, PadN, Router Alert per RFC 2711, Jumbo Payload per RFC 2675; unknown types keep their numeric value) and rawdata, and exposes the action-on-unrecognized bits (the two high bits of the type) asunrecognized_action. Parsing reads the rawoptionsbytes and never re-encodes, so the byte-exact round-trip is preserved; a missing length byte or option data that runs past the header raisesInvalidFieldError(bounded — never hangs or over-reads). - DNS over TCP (
DNSOverTCP, RFC 1035 §4.2.2):TCP.next_protocol()now dispatches application protocols by well-known port (layer4._ports.tcp_app_class). DNS over TCP is length-prefixed, so port 53 chains through a 2-byteDNSOverTCPlength shim — a layer betweenTCPand theDNSmessage, like a VLAN tag between Ethernet and its payload — and the walk reaches the DNS message (records and all) at its true offset. Non-DNS ports still end the chain at TCP.
- The real-capture fixture corpus gained
vlan_icmp.pcap(802.1Q single tag VID 100 + 802.1ad QinQ S-VID 200 / C-VID 30, over ARP and ICMPv4), so theVLANlayer rides the corpus-wide invariants and the transport-checksum recompute like every other protocol. It is a direct tcpdump capture of real kernel-tagged frames — built over 802.1Q / 802.1ad vlan devices on a veth pair with VLAN and checksum offload disabled so the tags stay in-band in the saved bytes and the inner checksums are genuine kernel output; seetests/fixtures/MANIFEST.mdandscripts/capture_fixtures_vlan.sh. - The corpus gained real-capture
dhcp.pcap(a DHCP DORA exchange fromdnsmasq+dhclient) andgre.pcap(IPv4-in-GRE ICMPv4 echo over a plain and a keyed kernel tunnel), so theDHCPandGRElayers ride the corpus-wide invariants on genuine bytes.scripts/capture_fixtures_dhcp.shandscripts/capture_fixtures_gre.shproduce them, andscripts/check_fixtures.pynow peels a GRE header to verify the tunnelled inner IPv4/ICMP checksums. - The corpus gained real-capture
dns_tcp.pcap(an A and a TXT query + response fromdig +tcpagainstdnsmasqover a veth pair, offload disabled), so the TCP application dispatch and theDNSOverTCPlength shim (#57) ride the corpus-wide invariants and the TCP-checksum recompute on genuine bytes — every frame decodesEthernet→IPv4→TCP→DNSOverTCP→DNSwith the length prefix agreeing with the message it frames and a resolvable answer.scripts/capture_fixtures_dns_tcp.shproduces it; the corpus is now 97 frames across 17 scenarios. - Contributor documentation: a
CONTRIBUTING.md(dev setup, the QA ladder, the decode contract, the add-a-protocol enforcement points, and the fixture-capture workflow), a pull-request template, and bug-report / protocol-request issue templates under.github/. - README refresh: the Protocol coverage table gains the shipped
DHCPandGRErows, theDNSrow notes resource-record parsing and the DNS-over-TCP length shim, and theIGMProw notes the IGMPv3 report and query parsing. The Roadmap section now lists only the remaining items, linking the open decoder-depth issues (#59-#66, tracked by #67), and the stale corpus figure is corrected to 93 frames across 16 scenarios here and inARCHITECTURE.md.
- IGMP (
netprotocols.IGMP, RFC 1112/2236/3376) — IPv4 multicast group management, dispatched from IPv4 protocol 2. The common four-byte header (type, max-response code, checksum) is decoded; thegroup_addressaccessor reads the group for the message types that carry one, andnetprotocols.checksumgains an IGMP arm. v3 group-record parsing is a roadmap follow-up. - DNS (
netprotocols.DNS, RFC 1035) — the first application-layer protocol. The 12-byte header and flag bits are decoded; the four message sections are kept raw with on-demand, read-only accessors (question_name,question_type,question_class) that decompress names safely (bounded pointer-following; malformed or looping names raiseInvalidFieldError, never hang). Round-trip stays byte-exact. - Port-based dispatch on UDP:
UDP.next_protocol()reaches an application protocol by well-known port (netprotocols.layer4._ports,{53: DNS}for now), checked destination-then-source. Documented as best-effort — a mis-dispatch degrades to the malformed-frame path.
- IPv6 extension headers (RFC 8200 §4.3-4.6):
IPv6HopByHopOptions,IPv6Routing,IPv6Fragment,IPv6DestinationOptions. The decode chain now reaches ICMPv6/TCP/UDP behind them (MLD reports decode fully). Extension headers dispatch only inside an IPv6 chain, and a Fragment header chains onward only from the first fragment. - Checksums (
netprotocols.checksum):internet_checksum()(RFC 1071),compute()/verify()covering the IPv4 header checksum, ICMPv4, and TCP/UDP/ICMPv6 with IPv4/IPv6 pseudo-headers, andPacket.with_checksums()for filling a whole stack on encode. The UDP-only zero substitution is confined to the UDP arm. - Property-based fuzzing of the decode path (hypothesis, dev-only):
decode() raises nothing outside
ProtocolErrorfor any input; the chain walk never consumes past the frame; constrained round trips. IPProtocolgainsHOPOPT,IPV6_ROUTE,IPV6_FRAG,IPV6_DSTOPTSwith display names.
- The real-capture fixture corpus grew to 65 frames across 12 scenarios (MLD behind hop-by-hop, IPv6 fragment pairs); checksum tests recompute every verifiable corpus frame to its captured wire value.
IPv4.next_protocol()chained non-first fragments (fragment_offset > 0) into garbage upper-layer decodes — a slice from the middle of a fragmented payload has no header at its start. Discovered by the new real-capture fixture corpus on live fragmented traffic; the chain now ends at the IPv4 layer for those frames, as it already did for unknown protocols.
- A real-capture fixture corpus under
tests/fixtures/(56 frames, 10 scenarios, every checksum internally verified — see its MANIFEST.md) with corpus-wide invariant tests, plus the capture and validation scripts underscripts/.
Complete rewrite. The public API is new; see the README and ARCHITECTURE.md for the current usage.
- The parsing core moved from
ctypes.BigEndianStructuresubclasses to frozen, slotted dataclasses parsed withstruct.Struct. Decoded and constructed instances are now identical in type and compare equal field-by-field. next_protocol()(returning the class that decodes the payload, orNone) replaces the stringly-typedencapsulated_protochain. Protocol number registries are exposed asEtherType,IPProtocol, andARPOperationenums.header_lenis now an instance property: IPv4 honors IHL and TCP honors the data offset, and both expose their rawoptionsbytes.- Field names modernized (
ethertype,src_port,total_length,checksum, ...); display helpers are properties such asprotocol_name,flags_str, andchecksum_hex_str. - Packaging moved to PEP 621 (
hatchling+uv), src layout, Python 3.12+, MIT license,py.typed(mypy strict clean). - Validators are plain functions (
validate_mac_addr,validate_ipv4_addr) raising exceptions rooted atProtocolError.
TCP.header_lenwas hardcoded to 32 bytes; the base header is 20 and the real length follows the data offset.- Decoding ignored IPv4 IHL and TCP data offset, so headers carrying options were mis-sliced.
- Serialization returned a zeroed buffer (
Protocol.__str__);bytes(header)now re-emits the exact on-wire form, options included. Packetrejected instances of indirectProtocolsubclasses (e.g.IPv4,ICMPv4) due to validation against direct subclasses only; membership is now checked withisinstance.- Malformed input (truncated buffers, lying IHL/data-offset values) now
raises typed exceptions (
TruncatedHeaderError,InvalidFieldError) instead of arbitraryValueError/struct.errorleaks.
- The
Validatordescriptor infrastructure (it stored state on the descriptor itself — class-shared — and was never wired into any protocol class). - Poetry manifests and the
setup.py-era metadata.
Last release of the ctypes-based implementation, published to PyPI in
2022. The repository had drifted behind the published releases; the
0.8.0 sources were recovered from the PyPI sdist and committed (tagged
v0.8.0) before the 1.0.0 rewrite. Releases 0.4.4 through 0.8.0 exist
on PyPI only; their individual histories were not preserved.