Skip to content

Commit 91bd80e

Browse files
authored
fix(dumpkit): pcap output drops the input's snaplen, thiszone and sigfigs (#1165) (#1168)
The PCAP engine now passes the input global header's thiszone, sigfigs and snaplen to Extractor._open_output, and PCAPIO._dump_header writes them instead of the Header defaults (snaplen 262144). The engine unit test that pinned the old _open_output arguments is updated.
1 parent 1b0862e commit 91bd80e

5 files changed

Lines changed: 90 additions & 5 deletions

File tree

‎pcapkit/dumpkit/pcap.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,22 +125,29 @@ def __call__(self, value: 'Data_Frame', name: 'Optional[str]' = None) -> 'PCAPIO
125125
# Utilities.
126126
##########################################################################
127127

128-
def _dump_header(self, *, protocol: 'Enum_LinkType | StdlibIntEnum | AenumIntEnum | str | int', # pylint: disable=arguments-differ
128+
def _dump_header(self, *, protocol: 'Enum_LinkType | StdlibIntEnum | AenumIntEnum | str | int', # pylint: disable=arguments-differ,too-many-arguments
129129
byteorder: 'Literal["big", "little"]' = sys.byteorder, nanosecond: 'bool' = False,
130+
thiszone: 'int' = 0, sigfigs: 'int' = 0, snaplen: 'int' = 0x40_000,
130131
**kwargs: 'Any') -> 'None': # pylint: disable=unused-argument
131132
"""Initially dump file heads and tails.
132133
133134
Args:
134135
protocol: data link type
135136
byteorder: header byte order
136137
nanosecond: nanosecond-resolution file flag
138+
thiszone: GMT to local correction
139+
sigfigs: accuracy of timestamps
140+
snaplen: max length of captured packets, in octets
137141
**kwargs: arbitrary keyword arguments
138142
139143
"""
140144
header = Header(
141145
network=protocol,
142146
byteorder=byteorder,
143147
nanosecond=nanosecond,
148+
thiszone=thiszone,
149+
sigfigs=sigfigs,
150+
snaplen=snaplen,
144151
)
145152
packet = header.data
146153
with open(self._file, 'wb') as file:

‎pcapkit/foundation/engines/pcap.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,9 @@ def run(self) -> 'None':
124124
if ext._flag_q:
125125
return
126126

127-
ext._open_output(protocol=self._dlink, byteorder=self._gbhdr.byteorder, nanosecond=self._nnsec)
127+
ext._open_output(protocol=self._dlink, byteorder=self._gbhdr.byteorder,
128+
nanosecond=self._nnsec, thiszone=self._gbhdr.info.thiszone,
129+
sigfigs=self._gbhdr.info.sigfigs, snaplen=self._gbhdr.info.snaplen)
128130
if ext._flag_f:
129131
ofile = ext._ofile(f'{ext._ofnm}/Global Header.{ext._fext}')
130132
else:

‎pcapkit/foundation/extraction.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -895,7 +895,8 @@ def _open_output(self, **kwargs: 'Any') -> 'None':
895895
896896
The engines call this at their global-header step, passing the header's
897897
link type, byte order and timestamp resolution as ``protocol``,
898-
``byteorder`` and ``nanosecond``: :class:`~pcapkit.dumpkit.pcap.PCAPIO`
898+
``byteorder`` and ``nanosecond``, and the PCAP engine also its
899+
``thiszone``, ``sigfigs`` and ``snaplen``: :class:`~pcapkit.dumpkit.pcap.PCAPIO`
899900
writes its own global header from them, and the other writers ignore
900901
them. :meth:`run` calls it again, without arguments, after the engine
901902
has started, for the engines that have no such step. Only the first

‎tests/foundation/engines/test_runtime_engines.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def __init__(self, file) -> None:
9898
self.protocol = LinkType.ETHERNET
9999
self.byteorder = 'little'
100100
self.nanosecond = True
101-
self.info = FakeInfo(header='global')
101+
self.info = FakeInfo(header='global', thiszone=-3600, sigfigs=1, snaplen=65535)
102102

103103
for flag_f in (True, False):
104104
with self.subTest(flag_f=flag_f):
@@ -113,7 +113,8 @@ def __init__(self, file) -> None:
113113
self.assertEqual(extractor._offmt, 'unit')
114114
self.assertEqual(sink.records[-1][1], 'Global Header')
115115
extractor._open_output.assert_called_once_with(
116-
protocol=LinkType.ETHERNET, byteorder='little', nanosecond=True)
116+
protocol=LinkType.ETHERNET, byteorder='little', nanosecond=True,
117+
thiszone=-3600, sigfigs=1, snaplen=65535)
117118

118119
quiet, sink = make_extractor(_flag_q=True)
119120
engine = PCAP(quiet)
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# -*- coding: utf-8 -*-
2+
"""Regression tests for #1165: ``format='pcap'`` keeps ``thiszone``, ``sigfigs``
3+
and ``snaplen``.
4+
5+
The PCAP engine passes all three from the input's global header to
6+
:meth:`~pcapkit.foundation.extraction.Extractor._open_output`, so
7+
:class:`~pcapkit.dumpkit.pcap.PCAPIO` writes them back instead of the
8+
:class:`~pcapkit.protocols.misc.pcap.header.Header` defaults.
9+
10+
"""
11+
from __future__ import annotations
12+
13+
import os
14+
import struct
15+
import tempfile
16+
import unittest
17+
import warnings
18+
19+
from pcapkit.interface import extract
20+
from tests._support import sample_path
21+
22+
#: Values that differ from every :class:`~pcapkit.protocols.misc.pcap.header.Header`
23+
#: default (``0``, ``0`` and ``262144``).
24+
THISZONE, SIGFIGS, SNAPLEN = -3600, 7, 1514
25+
26+
27+
def _extract(fin: str, fout: str, **kwargs):
28+
with warnings.catch_warnings():
29+
warnings.simplefilter('ignore')
30+
return extract(fin=fin, fout=fout, nofile=False, format='pcap', **kwargs)
31+
32+
33+
def _read(path: str) -> bytes:
34+
with open(path, 'rb') as file:
35+
return file.read()
36+
37+
38+
def _with_header_fields(data: bytes) -> bytes:
39+
"""Rewrite bytes 8--20 of a PCAP file in the byte order of its magic number."""
40+
endian = '<' if data[:4] in (b'\xd4\xc3\xb2\xa1', b'\x4d\x3c\xb2\xa1') else '>'
41+
return data[:8] + struct.pack(f'{endian}iII', THISZONE, SIGFIGS, SNAPLEN) + data[20:]
42+
43+
44+
class PCAPOutputHeaderFieldsTests(unittest.TestCase):
45+
46+
def setUp(self) -> None:
47+
self.tmp = tempfile.TemporaryDirectory() # pylint: disable=consider-using-with
48+
self.addCleanup(self.tmp.cleanup)
49+
self.input = os.path.join(self.tmp.name, 'in.pcap')
50+
with open(self.input, 'wb') as file:
51+
file.write(_with_header_fields(_read(sample_path('in.pcap'))))
52+
53+
def test_whole_capture_round_trips_byte_identically(self) -> None:
54+
extractor = _extract(self.input, os.path.join(self.tmp.name, 'out'))
55+
self.assertEqual(_read(extractor.output), _read(self.input))
56+
57+
def test_split_mode_headers_carry_the_fields(self) -> None:
58+
extractor = _extract(self.input, os.path.join(self.tmp.name, 'split'), files=True)
59+
header = _read(self.input)[:24]
60+
self.assertEqual(_read(os.path.join(extractor.output, 'Global Header.pcap')), header)
61+
self.assertGreater(extractor.length, 0)
62+
for num in range(1, extractor.length + 1):
63+
self.assertEqual(_read(os.path.join(extractor.output, f'Frame {num}.pcap'))[:24], header)
64+
65+
def test_zero_frame_capture(self) -> None:
66+
empty = os.path.join(self.tmp.name, 'empty.pcap')
67+
with open(empty, 'wb') as file:
68+
file.write(_read(self.input)[:24])
69+
extractor = _extract(empty, os.path.join(self.tmp.name, 'empty-out'))
70+
self.assertEqual(_read(extractor.output), _read(empty))
71+
72+
73+
if __name__ == '__main__':
74+
unittest.main()

0 commit comments

Comments
 (0)