@@ -134,7 +134,11 @@ def _read_packet(self, buf: 'bytes', block_type: 'int',
134134 little: Whether the enclosing section is little-endian.
135135
136136 Returns:
137- Timestamp in seconds since the UNIX epoch, and the packet data.
137+ Timestamp in seconds since the UNIX epoch, and the packet data. The
138+ timestamp is a :class:`~pcapkit.toolkit.dpkt.Timestamp`: the
139+ :obj:`float` this reader always yielded, which also carries the exact
140+ value, the interface's resolution and the packet's original length,
141+ for the PCAP frame record of the packet (:issue:`1507`).
138142
139143 Raises:
140144 FormatError: If the section describes no interface of the ID the
@@ -143,6 +147,8 @@ def _read_packet(self, buf: 'bytes', block_type: 'int',
143147 """
144148 import dpkt # isort:skip
145149
150+ from pcapkit .toolkit .dpkt import Timestamp # isort:skip
151+
146152 if block_type == Enum_BlockType .Enhanced_Packet_Block :
147153 tag = 'EPB'
148154 pkt = (dpkt .pcapng .EnhancedPacketBlockLE (buf ) if little
@@ -168,7 +174,81 @@ def _read_packet(self, buf: 'bytes', block_type: 'int',
168174 timestamp = decimal .Decimal (ticks ) / resolution + offset
169175
170176 self ._linktype = interface .linktype
171- return float (timestamp ), pkt .pkt_data
177+ return (Timestamp (float (timestamp ), timestamp , resolution , pkt .pkt_len ), # pylint: disable=no-member
178+ pkt .pkt_data )
179+
180+
181+ def _pcap_reader () -> 'Type[PCAPReader]' :
182+ """A :class:`dpkt.pcap.Reader` that keeps each record's original length.
183+
184+ :class:`dpkt.pcap.Reader` parses every record header and then yields only
185+ ``(timestamp, octets)``, so the record's original length and the file's
186+ resolution are lost by the time a PCAP frame record of the packet is built
187+ (:issue:`1507`). This subclass yields the same timestamp, as a
188+ :class:`~pcapkit.toolkit.dpkt.Timestamp` or, for a nanosecond file, a
189+ :class:`~pcapkit.toolkit.dpkt.DecimalTimestamp`, which carries the two.
190+
191+ Built when called, so that importing this module does not import `DPKT`_,
192+ and so that it always subclasses the :class:`dpkt.pcap.Reader` of the moment.
193+
194+ Warns:
195+ DPKTWarning: If this `DPKT`_'s reader lacks the attributes the loop reads
196+ -- they are private, and ``dpkt`` is not pinned. The reader then runs
197+ unchanged, and a traced PCAP record's original length is its captured
198+ length.
199+
200+ Returns:
201+ The reader type.
202+
203+ .. _DPKT: https://dpkt.readthedocs.io
204+
205+ """
206+ import dpkt # isort:skip
207+
208+ from pcapkit .toolkit .dpkt import DecimalTimestamp , Timestamp # isort:skip
209+
210+ #: Attributes of :class:`dpkt.pcap.Reader` the loop below reads, as of dpkt 1.9.8.
211+ private = ('_Reader__f' , '_Reader__ph' , '_divisor' )
212+
213+ class _Reader (dpkt .pcap .Reader ): # type: ignore[name-defined,misc]
214+ def __init__ (self , fileobj : 'IO[bytes]' ) -> 'None' :
215+ super ().__init__ (fileobj )
216+ missing = [name for name in private if not hasattr (self , name )]
217+ #: Whether to read with :meth:`dpkt.pcap.Reader.__iter__` unchanged.
218+ self ._upstream = bool (missing )
219+ if missing :
220+ warn (f"dpkt { getattr (dpkt , '__version__' , '(unknown version)' )} : "
221+ f"'dpkt.pcap.Reader' has no { ', ' .join (repr (name ) for name in missing )} ; "
222+ "reading PCAP records without their original length, so a traced "
223+ 'PCAP record gives its captured length instead' , DPKTWarning ,
224+ stacklevel = stacklevel ())
225+
226+ # NOTE: the loop is :meth:`dpkt.pcap.Reader.__iter__`'s, over the stream
227+ # and the record header type that method reads them through. A generator,
228+ # so ``dpkt.pcap.Reader.__init__`` calling it runs none of it before
229+ # :attr:`_upstream` is set.
230+ def __iter__ (self ) -> 'Iterator[tuple[float, bytes]]' :
231+ if self ._upstream :
232+ yield from super ().__iter__ ()
233+ return
234+
235+ file , header = self ._Reader__f , self ._Reader__ph # pylint: disable=no-member
236+ nanosecond = isinstance (self ._divisor , decimal .Decimal )
237+ resolution = 1_000_000_000 if nanosecond else 1_000_000
238+ while True :
239+ buf = file .read (header .__hdr_len__ )
240+ if not buf :
241+ break
242+ hdr = header (buf )
243+ buf = file .read (hdr .caplen )
244+ value = hdr .tv_sec + (hdr .tv_usec / self ._divisor )
245+ if nanosecond :
246+ yield DecimalTimestamp (value , resolution , hdr .len ), buf
247+ else :
248+ exact = decimal .Decimal (hdr .tv_sec ) + decimal .Decimal (hdr .tv_usec ) / resolution
249+ yield Timestamp (value , exact , resolution , hdr .len ), buf
250+
251+ return _Reader
172252
173253
174254class DPKT (EngineBase ['DPKTPacket' ]):
@@ -276,7 +356,7 @@ def run(self) -> 'None':
276356
277357 if ext .magic_number in PCAP .MAGIC_NUMBER :
278358 logger .debug ('dpkt: reading %s as PCAP' , ext ._ifnm )
279- reader = dpkt . pcap . Reader (ext ._ifile )
359+ reader = _pcap_reader () (ext ._ifile )
280360 elif ext .magic_number in PCAPNG .MAGIC_NUMBER :
281361 logger .debug ('dpkt: reading %s as PCAP-NG' , ext ._ifnm )
282362 reader = PCAPNGReader (ext ._ifile )
0 commit comments