Source code for pcapkit.toolkit.pcap_ct

# -*- coding: utf-8 -*-
"""pcap-ct Tools
===================

.. module:: pcapkit.toolkit.pcap_ct

:mod:`pcapkit.toolkit.pcap_ct` contains the adapters for the `pcap-ct`_ engine.

.. important::

   `pcap-ct`_ is a :mod:`ctypes` reimplementation of the `PyPCAP`_ interface
   over :manpage:`libpcap(3)`: it hands back the ``(timestamp, bytes)`` pair
   :c:func:`pcap_next_ex` produced and performs **no protocol dissection**, so
   there is no IP or TCP layer to reassemble or trace. The reassembly and flow
   tracing adapters raise :exc:`~pcapkit.utilities.exceptions.UnsupportedCall`
   rather than an :exc:`ImportError` that says nothing about why; dissecting
   the bytes with :mod:`pcapkit`'s own parsers would defeat the point of a
   third-party engine.

.. seealso::

   :mod:`pcapkit.toolkit.pypcap`, the same adapter for upstream `PyPCAP`_. The
   two distributions are independent projects sharing the |pcap|_ module name,
   and each engine names its own adapter, so a change to one cannot alter the
   other.

"""
from typing import TYPE_CHECKING

from pcapkit.foundation.engines.pcap_ct import PCAP_CT
from pcapkit.utilities.exceptions import UnsupportedCall

if TYPE_CHECKING:
    from ipaddress import IPv4Address, IPv6Address
    from typing import Any

    from pcapkit.const.reg.linktype import LinkType as Enum_LinkType
    from pcapkit.foundation.reassembly.ip.data import Packet as IP_Packet
    from pcapkit.foundation.reassembly.tcp.data import Packet as TCP_Packet
    from pcapkit.foundation.traceflow.tcp.data import Packet as TF_TCP_Packet

__all__ = [
    'packet2chain', 'packet2dict',
    'ipv4_reassembly', 'ipv6_reassembly', 'tcp_reassembly', 'tcp_traceflow',
]

#: Message prefix shared by every adapter below, read off
#: :attr:`PCAP_CT.__engine_name__
#: <pcapkit.foundation.engines.pcap_ct.PCAP_CT.__engine_name__>` rather than
#: spelled out, so the engine cannot be renamed there and still be named the old
#: way here (:issue:`2304`).
_ENGINE = PCAP_CT.__engine_name__

#: Explanatory suffix shared by every unsupported adapter below.
_NO_DISSECTION = ("'pcap-ct' is a libpcap binding and performs no protocol "
                  "dissection, so there is no protocol layer to read")


[docs] def packet2chain(packet: 'bytes', *, data_link: 'Enum_LinkType') -> 'str': """Fetch pcap-ct packet protocol chain. Args: packet: Raw packet bytes, as returned by ``pcap.pcap`` iteration. data_link: Data link type, from the capture handle. Returns: Colon (``:``) separated list of protocol chain. Note: As `pcap-ct`_ does not dissect the packet, the chain is only ever the link layer type followed by ``Raw``, e.g. ``ETHERNET:Raw``. """ return f'{data_link.name}:Raw'
[docs] def packet2dict(packet: 'bytes', timestamp: 'float', *, data_link: 'Enum_LinkType') -> 'dict[str, Any]': """Convert pcap-ct packet into :obj:`dict`. Args: packet: Raw packet bytes, as returned by ``pcap.pcap`` iteration. timestamp: Timestamp of packet, as returned by ``pcap.pcap`` iteration. data_link: Data link type, from the capture handle. Returns: A :obj:`dict` mapping of packet data. Note: The mapping carries the captured bytes verbatim rather than a decoded protocol tree, since `pcap-ct`_ does not decode anything. """ return { 'timestamp': timestamp, 'packet': packet, data_link.name: { 'raw_len': len(packet), 'raw': packet, }, }
[docs] def ipv4_reassembly(packet: 'bytes', timestamp: 'float', *, data_link: 'Enum_LinkType', count: 'int' = -1) -> 'IP_Packet[IPv4Address] | None': """Make data for IPv4 reassembly. Args: packet: Raw packet bytes. timestamp: Timestamp of the packet. data_link: Data link layer protocol (from the capture handle). count: Packet index. If not provided, defaults to ``-1``. Raises: UnsupportedCall: Always, as `pcap-ct`_ provides no IPv4 layer to read. .. versionchanged:: 1.7.0 Takes ``timestamp`` and ``data_link`` too, as the engine calls a registered reassembly adapter, so a 1.6.x call with ``packet`` alone fails. """ raise UnsupportedCall(f'{_ENGINE}: IPv4 reassembly is not supported: {_NO_DISSECTION}')
[docs] def ipv6_reassembly(packet: 'bytes', timestamp: 'float', *, data_link: 'Enum_LinkType', count: 'int' = -1) -> 'IP_Packet[IPv6Address] | None': """Make data for IPv6 reassembly. Args: packet: Raw packet bytes. timestamp: Timestamp of the packet. data_link: Data link layer protocol (from the capture handle). count: Packet index. If not provided, defaults to ``-1``. Raises: UnsupportedCall: Always, as `pcap-ct`_ provides no IPv6 layer to read. .. versionchanged:: 1.7.0 Takes ``timestamp`` and ``data_link`` too, as the engine calls a registered reassembly adapter, so a 1.6.x call with ``packet`` alone fails. """ raise UnsupportedCall(f'{_ENGINE}: IPv6 reassembly is not supported: {_NO_DISSECTION}')
[docs] def tcp_reassembly(packet: 'bytes', timestamp: 'float', *, data_link: 'Enum_LinkType', count: 'int' = -1) -> 'TCP_Packet | None': """Make data for TCP reassembly. Args: packet: Raw packet bytes. timestamp: Timestamp of the packet. data_link: Data link layer protocol (from the capture handle). count: Packet index. If not provided, defaults to ``-1``. Raises: UnsupportedCall: Always, as `pcap-ct`_ provides no TCP layer to read. .. versionchanged:: 1.7.0 Takes ``timestamp`` and ``data_link`` too, as the engine calls a registered reassembly adapter, so a 1.6.x call with ``packet`` alone fails. """ raise UnsupportedCall(f'{_ENGINE}: TCP reassembly is not supported: {_NO_DISSECTION}')
[docs] def tcp_traceflow(packet: 'bytes', timestamp: 'float', *, data_link: 'Enum_LinkType', count: 'int' = -1) -> 'TF_TCP_Packet | None': """Trace packet flow for TCP. Args: packet: Raw packet bytes. timestamp: Timestamp of the packet. data_link: Data link layer protocol (from the capture handle). count: Packet index. If not provided, defaults to ``-1``. Raises: UnsupportedCall: Always, as `pcap-ct`_ provides no TCP layer to read. """ raise UnsupportedCall(f'{_ENGINE}: TCP flow tracing is not supported: {_NO_DISSECTION}')