2323from pcapkit .foundation .traceflow .data .data import FrameRecord
2424from pcapkit .foundation .traceflow .data .tcp import Packet as TF_TCP_Packet
2525from pcapkit .protocols .data .misc .pcap .frame import FrameInfo as Data_FrameInfo
26- from pcapkit .toolkit .pypcapfile import _default_accepts
26+ from pcapkit .toolkit .pypcapfile import (IPV4_EXTENSION_HEADERS , TCP_MIN_HEADER_LEN ,
27+ _default_accepts , _past_extension_headers )
2728from pcapkit .utilities .exceptions import ProtocolError , UnsupportedCall
2829
2930if TYPE_CHECKING :
@@ -462,6 +463,112 @@ def _ipv4_accepted(ipv4: 'IP') -> 'bool':
462463 return _default_accepts ('IPv4' , ipv4 .pack_hdr () + bytes (ipv4 .opts ))
463464
464465
466+ def _past_ipv4_extension_headers (packet : 'Packet' , ipv4 : 'IP' ) -> 'Optional[tuple[int, bytes]]' :
467+ """Step over the headers at the head of a DPKT IPv4 packet's payload that the default engine reads past.
468+
469+ Args:
470+ packet: DPKT packet ``ipv4`` is a layer of, whose octets
471+ :func:`_layer2bytes` slices.
472+ ipv4: DPKT IPv4 packet, whose protocol is one of the
473+ :data:`~pcapkit.toolkit.pypcapfile.IPV4_EXTENSION_HEADERS`.
474+
475+ Returns:
476+ The protocol number after the last of those headers and the octets from
477+ its header on, as far as the Total Length goes -- a Total Length of
478+ ``0``, which TCP segmentation offload leaves, runs to the end of the
479+ frame -- or :data:`None` if the default engine reads no upper-layer
480+ header there: ``ipv4`` is a later fragment, whose data is a slice of the
481+ datagram's payload (:rfc:`791#section-3.2`), or it leaves one of the
482+ headers undissected, which
483+ :func:`~pcapkit.toolkit.pypcapfile._past_extension_headers` decides by
484+ the default engine's own rules, up to
485+ :data:`~pcapkit.protocols.internet.internet.EXTENSION_HEADER_LIMIT`
486+ headers in a row (:issue:`1604`).
487+
488+ Note:
489+ The default engine dispatches an IPv4 packet's protocol through the
490+ registry IPv6 uses, so it reads an AH or IPv6 extension header there
491+ and what its Next Header names. `DPKT`_ decodes protocol 0 as IPv4 and
492+ an AH as :class:`dpkt.ah.AH`, and keeps the rest as octets, so the
493+ octets are read instead (:issue:`1606`).
494+
495+ .. _DPKT: https://dpkt.readthedocs.io
496+
497+ """
498+ if ipv4 .offset :
499+ return None
500+ wire , _ = _layer2bytes (packet , ipv4 )
501+ ihl = ipv4 .hl * 4
502+ return _past_extension_headers (ipv4 .p , wire [ihl :max (ipv4 .len , ihl )] if ipv4 .len else wire [ihl :])
503+
504+
505+ def _decode_tcp (segment : 'bytes' ) -> 'Optional[TCP]' :
506+ """Decode a TCP segment the default engine reads behind an AH or IPv6 extension header in IPv4.
507+
508+ Args:
509+ segment: Raw octets from the TCP header on, as far as the IPv4 packet
510+ carrying it goes (see :func:`_past_ipv4_extension_headers`).
511+
512+ Returns:
513+ The segment, with ``segment`` attached by :func:`attach_buffer` so that
514+ its header is the captured one; or :data:`None` if the default engine
515+ reads no TCP there: fewer than :data:`TCP_MIN_HEADER_LEN
516+ <pcapkit.toolkit.pypcapfile.TCP_MIN_HEADER_LEN>` octets, a Data Offset
517+ counting fewer or more than were captured, or options its TCP parser
518+ rejects (see :func:`~pcapkit.toolkit.pypcapfile._default_accepts`).
519+
520+ Note:
521+ Directly over IP, the default engine reads a TCP header its parser
522+ rejects out of the raw octets left behind
523+ (:func:`pcapkit.toolkit.pcap.tcp_segment`), but behind another header
524+ it does not, so the parser's answer stands here, as for the pypcapfile
525+ engine.
526+
527+ """
528+ import dpkt # isort:skip
529+
530+ hdr_len = (segment [12 ] >> 4 ) * 4 if len (segment ) >= TCP_MIN_HEADER_LEN else 0
531+ if hdr_len < TCP_MIN_HEADER_LEN or hdr_len > len (segment ):
532+ return None
533+ if hdr_len > TCP_MIN_HEADER_LEN and not _default_accepts ('TCP' , segment [:hdr_len ]):
534+ return None
535+ tcp = dpkt .tcp .TCP (segment )
536+ attach_buffer (tcp , segment )
537+ return tcp
538+
539+
540+ def _decode_ip (protocol : 'int' , data : 'bytes' ) -> 'Optional[IP | IP6]' :
541+ """Decode an IP packet the default engine reads behind an AH or IPv6 extension header in IPv4.
542+
543+ Args:
544+ protocol: The IP-in-IP protocol number, one of the :data:`IP_TUNNELS`.
545+ data: Raw octets from the IP header on, as far as the IPv4 packet
546+ carrying it goes (see :func:`_past_ipv4_extension_headers`).
547+
548+ Returns:
549+ The packet as `DPKT`_ decodes one in a tunnel, with ``data`` attached by
550+ :func:`attach_buffer`, so that :func:`_layer2bytes` slices its layers
551+ out of the captured octets; or :data:`None` if decoding it raises
552+ anything at all, as :class:`~pcapkit.foundation.engines.dpkt.DPKT` then
553+ keeps a frame raw. `DPKT`_ raises more than its own
554+ :exc:`~dpkt.dpkt.UnpackError`: dpkt 1.9.8 reads ``frag_off`` from
555+ whatever header follows an IPv6 Fragment header, so one followed by
556+ another extension header raises :exc:`AttributeError` (:issue:`1351`).
557+
558+ .. _DPKT: https://dpkt.readthedocs.io
559+
560+ """
561+ import dpkt # isort:skip
562+
563+ klass = dpkt .ip .IP if protocol == Enum_TransType .IPv4 else dpkt .ip6 .IP6
564+ try :
565+ ip = klass (data )
566+ except Exception : # as the DPKT engine does, for a whole frame
567+ return None
568+ attach_buffer (ip , data )
569+ return ip
570+
571+
465572def _tcp_carrier (packet : 'Packet' ) -> 'tuple[Optional[IP | IP6], Optional[TCP]]' :
466573 """Fetch the IP layer of a DPKT packet that carries its TCP segment, and the segment.
467574
@@ -476,14 +583,20 @@ def _tcp_carrier(packet: 'Packet') -> 'tuple[Optional[IP | IP6], Optional[TCP]]'
476583 rejects the header of an IPv4 packet on the way (see
477584 :func:`_ipv4_accepted`). A tunnel is a packet whose protocol, or for
478585 IPv6 the next header after its extension headers, is one of the
479- :data:`IP_TUNNELS`.
586+ :data:`IP_TUNNELS`. An IPv4 packet whose protocol names an AH or IPv6
587+ extension header carries what the default engine reads past them (see
588+ :func:`_past_ipv4_extension_headers`), a tunnel or a TCP segment, which
589+ are decoded from the captured octets (see :func:`_decode_ip` and
590+ :func:`_decode_tcp`).
480591
481592 Note:
482593 `DPKT`_ decodes an IPv4 or IPv6 packet inside another (:rfc:`2003`,
483594 :rfc:`2473`, :rfc:`4213`) as its ``data``. The TCP endpoints are the
484595 innermost packet's addresses, as for the default engine
485596 (:func:`pcapkit.toolkit.pcap.tcp_segment`); the outer ones are the
486- tunnel's (:issue:`1581`).
597+ tunnel's (:issue:`1581`). A segment found behind an extension header is
598+ no layer of ``packet``, so it carries its own octets, which
599+ :func:`_layer2bytes` then hands back (:issue:`1606`).
487600
488601 .. _DPKT: https://dpkt.readthedocs.io
489602
@@ -493,16 +606,28 @@ def _tcp_carrier(packet: 'Packet') -> 'tuple[Optional[IP | IP6], Optional[TCP]]'
493606 ip = _network (packet )
494607 if ip is None :
495608 return None , None
609+ root = packet # the packet ``ip`` is a layer of
496610 while True :
497- if isinstance (ip , dpkt .ip .IP ) and not _ipv4_accepted (ip ):
498- return None , None
611+ if isinstance (ip , dpkt .ip .IP ):
612+ if not _ipv4_accepted (ip ):
613+ return None , None
614+ if ip .p in IPV4_EXTENSION_HEADERS :
615+ upper = _past_ipv4_extension_headers (root , ip )
616+ if upper is not None and upper [0 ] == Enum_TransType .TCP :
617+ return ip , _decode_tcp (upper [1 ])
618+ if upper is None or upper [0 ] not in IP_TUNNELS or (inner := _decode_ip (* upper )) is None :
619+ return ip , None
620+ root = ip = inner
621+ continue
499622 if getattr (ip , 'p' , None ) not in IP_TUNNELS or not isinstance (ip .data , (dpkt .ip .IP , dpkt .ip6 .IP6 )):
500623 break
501624 ip = ip .data
502625
503626 tcp = getattr (ip , 'tcp' , None ) # type: Optional[TCP]
504627 if tcp is None and type (getattr (ip , 'data' , None )).__name__ == 'TCP' :
505628 tcp = cast ('TCP' , ip .data )
629+ if tcp is not None and root is not packet :
630+ attach_buffer (tcp , _layer2bytes (root , tcp )[0 ])
506631 return ip , tcp
507632
508633
@@ -542,12 +667,13 @@ def packet2chain(packet: 'Packet') -> 'str':
542667 packet: DPKT packet.
543668
544669 Returns:
545- Colon (``:``) separated list of protocol chain.
670+ Colon (``:``) separated list of protocol chain. It ends at the first
671+ payload that is no layer, as in :func:`packet2dict`, e.g. VRRP's ``''``.
546672
547673 """
548674 chain = [type (packet ).__name__ ]
549675 payload = packet .data
550- while not isinstance (payload , bytes ):
676+ while hasattr (payload , '__hdr_fields__' ):
551677 chain .append (type (payload ).__name__ )
552678 payload = payload .data
553679 return ':' .join (chain )
@@ -563,15 +689,21 @@ def packet2dict(packet: 'Packet', timestamp: 'float', *,
563689 data_link: Data link type.
564690
565691 Returns:
566- Dict[str, Any]: A :obj:`dict` mapping of packet data.
692+ Dict[str, Any]: A :obj:`dict` mapping of packet data. A layer's payload
693+ is mapped as a layer of its own only where it is one, i.e. has the
694+ header fields a :class:`dpkt.dpkt.Packet` has; any other is leaf data.
695+ `DPKT`_ leaves some undecoded payloads as a :obj:`str` rather than as
696+ :obj:`bytes`, e.g. ``''`` for VRRP's.
697+
698+ .. _DPKT: https://dpkt.readthedocs.io
567699
568700 """
569701 def wrapper (packet : 'Packet' ) -> 'dict[str, Any]' :
570702 dict_ = {} # type: dict[str, Any]
571703 for field in packet .__hdr_fields__ :
572704 dict_ [field ] = getattr (packet , field , None )
573705 payload = packet .data
574- if not isinstance (payload , bytes ):
706+ if hasattr (payload , '__hdr_fields__' ):
575707 dict_ [type (payload ).__name__ ] = wrapper (payload )
576708 return dict_
577709
0 commit comments