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:
ProtocolBase,Generic[_PT,_ST]Abstract base class for all protocol family.
- property info: _PT¶
Info dict of current instance.
- property payload: ProtocolBase¶
Payload of current instance.
- property protochain: ProtoChain¶
Protocol chain of current instance.
- property schema: _ST¶
Schema data of the protocol.
- classmethod id()¶
Index ID of the protocol.
- classmethod register(code, protocol)¶
Register a new protocol class.
Notes
The full qualified class name of the new protocol class should be as
{protocol.module}.{protocol.name}.- Parameters:
code (
int) – protocol codeprotocol (
Union[ModuleDescriptor,Type[ProtocolBase]]) – module descriptor or aProtocolsubclass
- Return type:
- classmethod analyze(proto, payload, **kwargs)¶
Analyse packet payload.
- Parameters:
- Return type:
- Returns:
Parsed payload as a
Protocolinstance.
- classmethod from_schema(schema)¶
Create protocol instance from schema.
- classmethod from_data(data)¶
Create protocol instance from data.
- abstract read(length=None, **kwargs)¶
Read (parse) packet data.
- abstract make(**kwargs)¶
Make (construct) packet data.
- unpack(length=None, **kwargs)¶
Unpack (parse) packet data.
- Parameters:
- Return type:
TypeVar(_PT, bound= Data)- Returns:
Parsed packet data.
Notes
We used a special keyword argument
__packet__to pass the global packet data to underlying methods. This is useful when the packet data is not available in the current instance.
- pack(**kwargs)¶
Pack (construct) packet data.
- Parameters:
**kwargs (
Any) – Arbitrary keyword arguments.- Return type:
- Returns:
Constructed packet data.
Notes
We used a special keyword argument
__packet__to pass the global packet data to underlying methods. This is useful when the packet data is not available in the current instance.
- static decode(byte, *, encoding=None, errors='strict')¶
-
Should decoding failed using
encoding, the method will try again decoding thebytesas'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 thebytes. If not provided,pcapkitwill first try detecting its encoding usingchardet. 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 aUnicodeDecodeError. Other possible values are'ignore'and'replace'as well as any other name registered withcodecs.register_error()that can handleUnicodeDecodeError.
- Return type:
- static unquote(url, *, encoding='utf-8', errors='replace')¶
Unquote URLs into readable format.
Should decoding failed , the method will try again replacing
'%'with'\x'then decoding theurlas'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 thebytes.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 aUnicodeDecodeError. Other possible values are'ignore'and'replace'as well as any other name registered withcodecs.register_error()that can handleUnicodeDecodeError.
- Return type:
- static expand_comp(value)¶
Expand protocol class to protocol name.
The method is used to expand protocol class to protocol name, in the following manner:
If
valueis a protocol instance, the method will return the protocol class, and the protocol names in upper case obtained fromProtocol.id.If
valueis a protocol class, the method will return the protocol class itself, and the protocols names in upper case obtained fromProtocol.id.If
valueisstr, the method will attempt to search for the existing registered protocol class frompcapkit.protocols.__proto__and follow step 2; otherwise, return the value itself.
- Parameters:
value (
Union[str,ProtocolBase,Type[ProtocolBase]]) – Protocol class or name.- Return type:
-
__layer__:
Optional[Literal['Link','Internet','Transport','Application']]¶ Layer of protocol, can be one of
Link,Internet,TransportandApplication. For example, the layer ofEthernetisLink. However, certain protocols are not in any layer, such asRaw, and thus its layer isNone.
-
__proto__:
DefaultDict[int,Union[ModuleDescriptor[ProtocolBase],Type[ProtocolBase]]]¶ Protocol index mapping for decoding next layer, c.f.
self._decode_next_layer&self._import_next_layer. The values should be a tuple representing the module name and class name, or aProtocolsubclass.
-
__schema__(dict_=None, **kwargs):
Type[TypeVar(_ST, bound= Schema)]¶ Protocol header schema definition.
- _read_packet(length=None, *, header=None, payload=None, discard=False)¶
Read raw packet data.
- Parameters:
- Return type:
- _get_payload()¶
Get payload from
self.__header__.- Return type:
- Returns:
Payload of
self.__header__asbytes.
See also
This is a wrapper function for
pcapkit.protocols.schema.schema.Schema.get_payload().
- classmethod _make_data(data)¶
Create key-value pairs from
datafor protocol construction.
- classmethod _make_index(name, default=None, *, namespace=None, reversed=False, pack=False, size=4, signed=False, lilendian=False)¶
Return first index of
namefrom adictor enumeration.- Parameters:
namespace (
Union[dict[str,int],dict[int,str],Type[IntEnum],Type[IntEnum],None]) – namespace for itemreversed (
bool) – if namespace isstr -> intpairspack (
bool) – if needstruct.pack()to pack the resultsize (
int) – buffer sizesigned (
bool) – signed flaglilendian (
bool) – little-endian flag
- Return type:
- Returns:
Index of
namefrom a dict or enumeration. IfpackisTrue, returnsbytes; otherwise, returnsint.- Raises:
ProtocolNotImplemented – If
nameis NOT innamespaceanddefaultisNone.
- classmethod _make_payload(data)¶
Create payload from
datafor protocol construction.This method uses
__next_type__and__next_name__to determine the payload type and name. If either of them isNone, aNoPayloadinstance will be returned. Otherwise, the payload will be constructed byProtocol.from_data.- Parameters:
data (
Data) – protocol data- Return type:
- Returns:
Payload for protocol construction.
- _decode_next_layer(dict_, proto, length=None, *, packet=None)¶
Decode next layer protocol.
- Parameters:
- Return type:
TypeVar(_PT, bound= Data)- Returns:
Current protocol with next layer extracted.
Notes
We added a new key
__next_type__todict_to store the next layer protocol type, and a new key__next_name__to store the next layer protocol name. These two keys will NOT be included whenInfo.to_dictis called.
- _import_next_layer(proto, length=None, *, packet=None)¶
Import next layer extractor.
- Parameters:
- Return type:
- Returns:
Instance of next layer.
-
__data__:
Type[TypeVar(_PT, bound= Data)] = <class 'pcapkit.protocols.data.misc.raw.Raw'>¶ Protocol packet data definition.
- __init__(file=None, length=None, **kwargs)¶
Initialisation.
- Parameters:
file (
Union[IO[bytes],bytes,None]) – Source packet stream._layer (
str) – Parse packet until_layer(self._exlayer)._protocol (
Union[str, Protocol, Type[Protocol]]) – Parse packet until_protocol(self._exproto).**kwargs (
Any) – Arbitrary keyword arguments.
- __post_init__(file=None, length=None, **kwargs)¶
Post initialisation hook.
- Parameters:
- Return type:
See also
For construction arguments, please refer to
self.make.
- classmethod __init_subclass__(schema=None, data=None, *args, **kwargs)[source]¶
Initialisation for subclasses.
- Parameters:
- Return type:
This method is called when a subclass of
Protocolis defined. It is used to set theself.__schema__attribute of the subclass.Notes
When
schemaand/ordatais not specified, the method will first try to find the corresponding class in theschemaanddatamodules respectively. If the class is not found, the defaultSchema_RawandData_Rawclasses will be used.This method also registers the subclass to the protocol registry, i.e.,
pcapkit.protocols.__proto__.See also
For more information on the registry, please refer to
pcapkit.foundation.registry.protocols.register_protocol().
- __repr__()¶
Returns representation of parsed protocol data. :rtype:
strExample
>>> protocol <Frame alias='...' frame=(..., packet=b'...', sethernet=..., protocols='Ethernet:IPv6:Raw')>
- __str__()¶
Returns formatted hex representation of source data stream. :rtype:
strExample
>>> 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.
- __getitem__(key)¶
Subscription (
getitem) support.If
keyis aProtocolobject, the method will fetch its indexes (self.id).Later, search the packet’s chain of protocols with the calculated
key.If no matches, then raises
ProtocolNotFound.
- Parameters:
- Return type:
- Returns:
The sub-packet from the current packet of indexed protocol.
- Raises:
ProtocolNotFound – If
keyis not in the current packet.
See also
The method calls
self.expand_compto handle thekeyand expand it for robust searching.
- __contains__(name)¶
Returns if certain protocol is in the instance.
See also
The method calls
self.expand_compto handle thenameand expand it for robust searching.
- abstract classmethod __index__()¶
Numeral registry index of the protocol.
- Return type:
IntEnum|IntEnum
-
_exproto:
Union[str,ProtocolBase,Type[ProtocolBase],None]¶ Parse packet until such protocol.
- Type:
Data Models¶
Internal Definitions¶
- class pcapkit.protocols.protocol.ProtocolBase(file=None, length=None, **kwargs)[source]¶
-
Abstract base class for all protocol family.
Note
This class is for internal use only. For customisation, please use
Protocolinstead.
- class pcapkit.protocols.protocol.ProtocolMeta(name, bases, namespace, /, **kwargs)[source]¶
Bases:
ABCMetaMeta class to add dynamic support to
Protocol.This meta class is used to generate necessary attributes for the
Protocolclass. It can be useful to reduce unnecessary registry calls and simplify the customisation process.
Type Variables¶
- pcapkit.protocols.protocol._PT: pcapkit.protocols.data.data.Data¶
- pcapkit.protocols.protocol._ST: pcapkit.protocols.schema.schema.Schema¶