Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion pcapkit/dumpkit/pcap.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,22 +125,29 @@ def __call__(self, value: 'Data_Frame', name: 'Optional[str]' = None) -> 'PCAPIO
# Utilities.
##########################################################################

def _dump_header(self, *, protocol: 'Enum_LinkType | StdlibIntEnum | AenumIntEnum | str | int', # pylint: disable=arguments-differ
def _dump_header(self, *, protocol: 'Enum_LinkType | StdlibIntEnum | AenumIntEnum | str | int', # pylint: disable=arguments-differ,too-many-arguments
byteorder: 'Literal["big", "little"]' = sys.byteorder, nanosecond: 'bool' = False,
thiszone: 'int' = 0, sigfigs: 'int' = 0, snaplen: 'int' = 0x40_000,
**kwargs: 'Any') -> 'None': # pylint: disable=unused-argument
"""Initially dump file heads and tails.

Args:
protocol: data link type
byteorder: header byte order
nanosecond: nanosecond-resolution file flag
thiszone: GMT to local correction
sigfigs: accuracy of timestamps
snaplen: max length of captured packets, in octets
**kwargs: arbitrary keyword arguments

"""
header = Header(
network=protocol,
byteorder=byteorder,
nanosecond=nanosecond,
thiszone=thiszone,
sigfigs=sigfigs,
snaplen=snaplen,
)
packet = header.data
with open(self._file, 'wb') as file:
Expand Down
4 changes: 3 additions & 1 deletion pcapkit/foundation/engines/pcap.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@ def run(self) -> 'None':
if ext._flag_q:
return

ext._open_output(protocol=self._dlink, byteorder=self._gbhdr.byteorder, nanosecond=self._nnsec)
ext._open_output(protocol=self._dlink, byteorder=self._gbhdr.byteorder,
nanosecond=self._nnsec, thiszone=self._gbhdr.info.thiszone,
sigfigs=self._gbhdr.info.sigfigs, snaplen=self._gbhdr.info.snaplen)
if ext._flag_f:
ofile = ext._ofile(f'{ext._ofnm}/Global Header.{ext._fext}')
else:
Expand Down
3 changes: 2 additions & 1 deletion pcapkit/foundation/extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -895,7 +895,8 @@ def _open_output(self, **kwargs: 'Any') -> 'None':

The engines call this at their global-header step, passing the header's
link type, byte order and timestamp resolution as ``protocol``,
``byteorder`` and ``nanosecond``: :class:`~pcapkit.dumpkit.pcap.PCAPIO`
``byteorder`` and ``nanosecond``, and the PCAP engine also its
``thiszone``, ``sigfigs`` and ``snaplen``: :class:`~pcapkit.dumpkit.pcap.PCAPIO`
writes its own global header from them, and the other writers ignore
them. :meth:`run` calls it again, without arguments, after the engine
has started, for the engines that have no such step. Only the first
Expand Down
5 changes: 3 additions & 2 deletions tests/foundation/engines/test_runtime_engines.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def __init__(self, file) -> None:
self.protocol = LinkType.ETHERNET
self.byteorder = 'little'
self.nanosecond = True
self.info = FakeInfo(header='global')
self.info = FakeInfo(header='global', thiszone=-3600, sigfigs=1, snaplen=65535)

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

quiet, sink = make_extractor(_flag_q=True)
engine = PCAP(quiet)
Expand Down
74 changes: 74 additions & 0 deletions tests/foundation/test_pcap_output_header_fields_unit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
"""Regression tests for #1165: ``format='pcap'`` keeps ``thiszone``, ``sigfigs``
and ``snaplen``.

The PCAP engine passes all three from the input's global header to
:meth:`~pcapkit.foundation.extraction.Extractor._open_output`, so
:class:`~pcapkit.dumpkit.pcap.PCAPIO` writes them back instead of the
:class:`~pcapkit.protocols.misc.pcap.header.Header` defaults.

"""
from __future__ import annotations

import os
import struct
import tempfile
import unittest
import warnings

from pcapkit.interface import extract
from tests._support import sample_path

#: Values that differ from every :class:`~pcapkit.protocols.misc.pcap.header.Header`
#: default (``0``, ``0`` and ``262144``).
THISZONE, SIGFIGS, SNAPLEN = -3600, 7, 1514


def _extract(fin: str, fout: str, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return extract(fin=fin, fout=fout, nofile=False, format='pcap', **kwargs)


def _read(path: str) -> bytes:
with open(path, 'rb') as file:
return file.read()


def _with_header_fields(data: bytes) -> bytes:
"""Rewrite bytes 8--20 of a PCAP file in the byte order of its magic number."""
endian = '<' if data[:4] in (b'\xd4\xc3\xb2\xa1', b'\x4d\x3c\xb2\xa1') else '>'
return data[:8] + struct.pack(f'{endian}iII', THISZONE, SIGFIGS, SNAPLEN) + data[20:]


class PCAPOutputHeaderFieldsTests(unittest.TestCase):

def setUp(self) -> None:
self.tmp = tempfile.TemporaryDirectory() # pylint: disable=consider-using-with
self.addCleanup(self.tmp.cleanup)
self.input = os.path.join(self.tmp.name, 'in.pcap')
with open(self.input, 'wb') as file:
file.write(_with_header_fields(_read(sample_path('in.pcap'))))

def test_whole_capture_round_trips_byte_identically(self) -> None:
extractor = _extract(self.input, os.path.join(self.tmp.name, 'out'))
self.assertEqual(_read(extractor.output), _read(self.input))

def test_split_mode_headers_carry_the_fields(self) -> None:
extractor = _extract(self.input, os.path.join(self.tmp.name, 'split'), files=True)
header = _read(self.input)[:24]
self.assertEqual(_read(os.path.join(extractor.output, 'Global Header.pcap')), header)
self.assertGreater(extractor.length, 0)
for num in range(1, extractor.length + 1):
self.assertEqual(_read(os.path.join(extractor.output, f'Frame {num}.pcap'))[:24], header)

def test_zero_frame_capture(self) -> None:
empty = os.path.join(self.tmp.name, 'empty.pcap')
with open(empty, 'wb') as file:
file.write(_read(self.input)[:24])
extractor = _extract(empty, os.path.join(self.tmp.name, 'empty-out'))
self.assertEqual(_read(extractor.output), _read(empty))


if __name__ == '__main__':
unittest.main()
Loading