Source code for pcapkit.toolkit.pypcap

# -*- coding: utf-8 -*-
"""PyPCAP Tools
==================

.. module:: pcapkit.toolkit.pypcap

:mod:`pcapkit.toolkit.pypcap` contains the adapters for the `PyPCAP`_ engine.

.. important::

   `PyPCAP`_ is a thin :manpage:`libpcap(3)` binding: 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.pcap_ct`, the same adapter for `pcap-ct`_, which
   :class:`~pcapkit.foundation.engines.pcap_ct.PCAP_CT` drives. Each engine
   names its own adapter, so a change to one cannot alter the other.

"""
from typing import TYPE_CHECKING

from pcapkit.foundation.engines.pypcap import PyPCAP
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:`PyPCAP.__engine_name__
#: <pcapkit.foundation.engines.pypcap.PyPCAP.__engine_name__>` rather than
#: spelled out, so the engine cannot be renamed there and still be named the old
#: way here (:issue:`2304`).
_ENGINE = PyPCAP.__engine_name__

#: Explanatory suffix shared by every unsupported adapter below.
_NO_DISSECTION = ("'pypcap' 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 PyPCAP 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 `PyPCAP`_ 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 PyPCAP 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 `PyPCAP`_ 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 `PyPCAP`_ 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 `PyPCAP`_ 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 `PyPCAP`_ 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 `PyPCAP`_ provides no TCP layer to read. """ raise UnsupportedCall(f'{_ENGINE}: TCP flow tracing is not supported: {_NO_DISSECTION}')