Root Protocol

pcapkit.protocols.protocol contains Protocol only, which is an abstract base class for all protocol family, with pre-defined utility arguments and methods of specified protocols.

class pcapkit.protocols.protocol.Protocol(file=None, length=None, **kwargs)[source]

Bases: Generic[PT]

Abstract base class for all protocol family.

Parameters
  • *args (Any) – Arbitrary positional arguments.

  • **kwargs (Any) – Arbitrary keyword arguments.

Return type

Protocol[PT]

__init__(file: BinaryIO, length: Optional[int] = None, **kwargs: Any) None[source]
__init__(**kwargs: Any) None

Initialisation.

Parameters
__post_init__(file: BinaryIO, length: Optional[int] = None, **kwargs: Any) None[source]
__post_init__(**kwargs: Any) None

Post initialisation hook.

Parameters
  • file (Optional[BinaryIO]) – Source packet stream.

  • length (Optional[int]) – Length of packet data.

  • **kwargs (Any) – Arbitrary keyword arguments.

See also

For construction arguments, please refer to self.make.

Return type

None

__repr__()[source]

Returns representation of parsed protocol data.

Example

>>> protocol
<Frame alias='...' frame=(..., packet=b'...', sethernet=..., protocols='Ethernet:IPv6:Raw')>
Return type

str

__str__()[source]

Returns formatted hex representation of source data stream.

Example

>>> protocol
Frame(..., packet=b"...", sethernet=..., protocols='Ethernet:IPv6:Raw')
>>> print(protocol)
00 00 00 00 00 00 00 a6 87 f9 27 93 16 ee fe 80 00 00 00     ..........'........
00 00 00 1c cd 7c 77 ba c7 46 b7 87 00 0e aa 00 00 00 00     .....|w..F.........
fe 80 00 00 00 00 00 00 1c cd 7c 77 ba c7 46 b7 01 01 a4     ..........|w..F....
5e 60 d9 6b 97                                               ^`.k.
Return type

str

__iter__()[source]

Iterate through self._data.

Return type

BinaryIO

__getitem__(key)[source]

Subscription (getitem) support.

  • If key is a Protocol object, the method will fetch its indexes (id()).

  • Later, search the packet’s chain of protocols with the calculated key.

  • If no matches, then raises ProtocolNotFound.

Parameters

key (str | Protocol | Type[Protocol]) – Indexing key.

Returns

The sub-packet from the current packet of indexed protocol.

Raises

ProtocolNotFound – If key is not in the current packet.

Return type

Protocol

See also

The method calls self.expand_comp to handle the key and expand it for robust searching.

__contains__(name)[source]

Returns if certain protocol is in the instance.

Parameters

name (str | Protocol | Type[Protocol]) – Name to search

Return type

bool

See also

The method calls self.expand_comp to handle the name and expand it for robust searching.

abstract classmethod __index__()[source]

Numeral registry index of the protocol.

Return type

StdlibEnum | AenumEnum

__hash__()[source]

Return the hash value for self._data.

Return type

int

abstract property name: str

Name of current protocol.

Return type

str

property alias: str

Acronym of current protocol.

Return type

str

property info_name: str

Key name of the info dict.

Return type

str

property info: PT

Info dict of current instance.

Return type

TypeVar(PT, bound= Info)

property data: bytes

Binary packet data of current instance.

Return type

bytes

abstract property length: int

Header length of current protocol.

Return type

int

property payload: Protocol

Payload of current instance.

Return type

Protocol

property protocol: Optional[str]

Name of next layer protocol (if any).

Return type

Optional[str]

property protochain: ProtoChain

Protocol chain of current instance.

Return type

ProtoChain

property packet: Packet

DataType_Packet data of the protocol.

classmethod id()[source]

Index ID of the protocol.

By default, it returns the name of the protocol. In certain cases, the method may return multiple values.

Return type

tuple[str, …]

abstract read(length=None, **kwargs)[source]

Read (parse) packet data.

Parameters
  • length (Optional[int]) – Length of packet data.

  • **kwargs (Any) – Arbitrary keyword arguments.

Return type

TypeVar(PT, bound= Info)

Returns

Parsed packet data.

abstract make(**kwargs)[source]

Make (construct) packet data.

Parameters

**kwargs (Any) – Arbitrary keyword arguments.

Returns

Constructed packet data.

Return type

bytes

static decode(byte, *, encoding=None, errors='strict')[source]

Decode bytes into str.

Should decoding failed using encoding, the method will try again decoding the bytes as 'unicode_escape' with 'replace' for error handling.

See also

The method is a wrapping function for bytes.decode().

Parameters
  • byte (bytes) – Source bytestring.

  • encoding (Optional[str]) – The encoding with which to decode the bytes. If not provided, pcapkit will first try detecting its encoding using chardet. The fallback encoding would is UTF-8.

  • errors (Literal[‘strict’, ‘ignore’, ‘replace’]) – The error handling scheme to use for the handling of decoding errors. The default is 'strict' meaning that decoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error() that can handle UnicodeDecodeError.

Return type

str

Return type

str

Parameters
static unquote(url, *, encoding='utf-8', errors='replace')[source]

Unquote URLs into readable format.

Should decoding failed , the method will try again replacing '%' with '\x' then decoding the url as 'unicode_escape' with 'replace' for error handling.

See also

This method is a wrapper function for urllib.parse.unquote().

Parameters
  • url (str) – URL string.

  • encoding (str) – The encoding with which to decode the bytes.

  • errors (Literal[‘strict’, ‘ignore’, ‘replace’]) – The error handling scheme to use for the handling of decoding errors. The default is 'strict' meaning that decoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error() that can handle UnicodeDecodeError.

Return type

str

static expand_comp(value)[source]

Expand protocol class to protocol name.

The method is used to expand protocol class to protocol name, in the following manner:

  1. If value is a protocol instance, the method will return the protocol class, and the protocol names in upper case obtained from Protocol.id.

  2. If value is a protocol class, the method will return the protocol class itself, and the protocols names in upper case obtained from Protocol.id.

  3. If value is str, the method will attempt to search for the existing registered protocol class from pcapkit.protocols.__proto__ and follow step 2; otherwise, return the value itself.

Parameters

value (str | Protocol | Type[Protocol]) – Protocol class or name.

Return type

tuple

classmethod analyze(proto, payload, **kwargs)[source]

Analyse packet payload.

Parameters
  • proto (int) – Protocol registry number.

  • payload (bytes) – Packet payload.

  • **kwargs (Any) – Arbitrary keyword arguments.

Return type

Protocol

Returns

Parsed payload as a Protocol instance.

_read_protos(size)[source]

Read next layer protocol type.

  • If succeed, returns the enum of next layer protocol.

  • If fail, returns None.

Parameters

size (int) – buffer size

Return type

Optional[StdlibEnum | AenumEnum]

_read_fileng(*args, **kwargs)[source]

Read file buffer (self._file).

This method wraps the file.read call.

Parameters
  • *args (Any) – arbitrary positional arguments

  • **kwargs (Any) – arbitrary keyword arguments

Returns

Data read from file buffer.

Return type

bytes

_read_unpack(size=1, *, signed=False, lilendian=False, quiet=False)[source]

Read bytes and unpack for integers.

Parameters
  • size (int) – buffer size

  • signed (bool) – signed flag

  • lilendian (bool) – little-endian flag

  • quiet (bool) – quiet (no exception) flag

Return type

int

Returns

Unpacked data upon success

Raises

StructError – If unpack (struct.pack()) failed, and struct.error raised.

_read_binary(size=1)[source]

Read bytes and convert into binaries.

Parameters

size (int) – buffer size

Return type

str

Returns

Binary bits (0/1).

_read_packet(length: Optional[int] = None, *, header: None = None) bytes[source]
_read_packet(*, header: int, payload: Optional[int] = None, discard: Literal[True]) bytes
_read_packet(*, header: int, payload: Optional[int] = None, discard: Literal[False] = False) DataType_Packet

Read raw packet data.

Parameters
  • length – length of the packet

  • header – length of the packet header

  • payload – length of the packet payload

  • discard – flag if discard header data

  • If header omits, returns the whole packet data in bytes.

  • If discard is set as True, returns the packet body (in bytes) only.

  • Otherwise, returns the header and payload data as DataType_Packet object.

classmethod _make_pack(integer, *, size=1, signed=False, lilendian=False)[source]

Pack integers to bytes.

Parameters
  • integer (int) – integer to be packed

  • size (int) – buffer size

  • signed (bool) – signed flag

  • lilendian (bool) – little-endian flag

Return type

bytes

Returns

Packed data upon success.

Raises

StructError – If failed to pack the integer.

classmethod _make_index(name: int | StdlibEnum | AenumEnum, *, pack: Literal[False] = False) int[source]
classmethod _make_index(name: int | StdlibEnum | AenumEnum, *, pack: Literal[True], size: int = 4, signed: bool = False, lilendian: bool = False) bytes
classmethod _make_index(name: str, default: Optional[int] = None, *, namespace: Type[StdlibEnum] | Type[AenumEnum], pack: Literal[False] = False) int
classmethod _make_index(name: str, default: Optional[int] = None, *, namespace: Type[StdlibEnum] | Type[AenumEnum], pack: Literal[True], size: int = 4, signed: bool = False, lilendian: bool = False) bytes
classmethod _make_index(name: str, default: Optional[int] = None, *, namespace: dict[int, str], reversed: Literal[False] = False, pack: Literal[False] = False) int
classmethod _make_index(name: str, default: Optional[int] = None, *, namespace: dict[int, str], reversed: Literal[False] = False, pack: Literal[True], size: int = 4, signed: bool = False, lilendian: bool = False) bytes
classmethod _make_index(name: str, default: Optional[int] = None, *, namespace: dict[str, int], reversed: Literal[True], pack: Literal[False] = False) int
classmethod _make_index(name: str, default: Optional[int] = None, *, namespace: dict[str, int], reversed: Literal[True], pack: Literal[True], size: int = 4, signed: bool = False, lilendian: bool = False) bytes

Return first index of name from a dict or enumeration.

Parameters
  • name – item to be indexed

  • default – default value

  • namespace – namespace for item

  • reversed – if namespace is str -> int pairs

  • pack – if need struct.pack() to pack the result

  • size – buffer size

  • signed – signed flag

  • lilendian – little-endian flag

Returns

Index of name from a dict or enumeration. If pack is True, returns bytes; otherwise, returns int.

Raises

ProtocolNotImplemented – If name is NOT in namespace and default is None.

_decode_next_layer(dict_, proto, length=None)[source]

Decode next layer protocol.

Parameters
  • dict_ (TypeVar(PT, bound= Info)) – info buffer

  • proto (int) – next layer protocol index

  • length (Optional[int]) – valid (non-padding) length

Return type

TypeVar(PT, bound= Info)

Returns

Current protocol with next layer extracted.

_import_next_layer(proto, length=None)[source]

Import next layer extractor.

Parameters
  • proto (int) – next layer protocol index

  • length (Optional[int]) – valid (non-padding) length

Return type

Protocol

Returns

Instance of next layer.

__layer__: Optional[Literal['Link', 'Internet', 'Transport', 'Application']]
__proto__: DefaultDict[int, tuple[str, str]]

& self._import_next_layer. The values should be a tuple representing the module name and class name.

_info: PT

Parsed packet data.

_data: bytes

Raw packet data.

_file: BinaryIO

Source packet stream.

_next: Protocol
_seekset: int

File pointer.

Type

int

_exlayer: Optional[str]

Parse packet until such layer.

Type

str

_exproto: Optional[str | Protocol | Type[Protocol]]

Parse packet until such protocol.

Type

str

_sigterm

If terminate parsing next layer of protocol.

Type

bool

Data Structures

class pcapkit.protocols.data.protocol.Packet(header, payload)[source]

Bases: Info

Header and payload data.

Parameters
  • *args (VT) – Arbitrary positional arguments.

  • **kwargs (VT) – Arbitrary keyword arguments.

Return type

Info

header: bytes

packet header

payload: bytes

packet payload