Base Fields¶
Removed in version 1.3.0: pcapkit.corekit.fields.field._Field, renamed
FieldBase with no alias left behind.
Removed in version 1.5.0: pcapkit.corekit.fields.field.NoValueType, now
pcapkit.corekit.sentinels.NoValueType (#911,
#1744), and pcapkit.corekit.fields.field.NoValue, now
pcapkit.corekit.sentinels.NO_VALUE (#937).
- class pcapkit.corekit.fields.field.Field[_T](length, default=NO_VALUE, callback=lambda *_: ...)[source]¶
Bases:
FieldBase[_T],Generic[_T]Base class for protocol fields.
- Parameters:
length (
int|Callable[[dict[str,Any]],int]) – Field size (in bytes); if a callable is given, it should return an integer value and accept the current packet as its only argument.default (
_T|NoValueType) – Field default value, if any.callback (
Callable[[Self,dict[str,Any]],None]) – Callback function to be called uponself.__call__.
- _length¶
- _length_callback¶
- class pcapkit.corekit.fields.field.FieldBase[_T](*args, **kwargs)[source]¶
-
Internal base class for protocol fields.
Important
A negative value of
lengthindicates that the field is variable-length (i.e., length unspecified) and thuspack()should be considerate of the template format and the actual value provided for packing.- Parameters:
- _default: _T | NoValueType = NO_VALUE¶
- property default: _T | NoValueType¶
Field default value.
- property length: int¶
Field size.
- Raises:
ProtocolError – If
templateresolves to a negative count (e.g.'-5s', from alengthcallback such aslambda pkt: pkt['__length__']resolving below zero once the buffer ran short of what the schema declared).struct.calcsize()cannot size such a template and raises a barestruct.error, uncatchable as a pcapkit-specific error; this re-raises it as the negative-length message below. See #805.ProtocolError – If
templateis otherwise malformed – anything elsestruct.calcsize()cannot size, such as a typo’d format character – rather than the negative-length message above, which would misreport the actual cause.struct.calcsize()raises the identical barestruct.errorfor both cases (measured:calcsize('-1s')andcalcsize('Xs')both raisebad char in struct format), so the two are told apart by_RE_NEGATIVE_LENGTH_TEMPLATEagainsttemplateitself – which is known already, without needing anythingstruct.calcsize()’s own error says – rather than by the error message. See #825.
Changed in version 1.5.0: Raises
ProtocolErrorwherestruct.calcsize()raised a barestruct.error(#805, #825).
- __call__(packet)[source]¶
Update field attributes.
- Parameters:
- Return type:
- Returns:
Updated field instance.
This method will return a new instance of
FieldBaseinstead of updating the current instance.
- __copy__()[source]¶
Return a shallow copy of the field.
Every field of every protocol is copied once per packet by
__call__(), which makes the genericcopy.copy()path – viaobject.__reduce_ex__()andcopy._reconstruct()– one of the costlier things an extraction would do. This does what that path would do, and only that: a new instance of the same class, its__dict__shallow-updated from this one.Note
Every
__call__inpcapkit.corekit.fieldscopies throughself.__copy__()– directly, or by way ofsuper().__call__– rather thancopy.copy(self).copy.copy()still has to find this method before it can call it –getattr(cls, '__copy__', None)– and that lookup alone was profiled at 55,846 calls (~1.7% of anextract()run) onexamples/captures/http.pcap, one per field per packet, all from this exact path. Calling__copy__directly is exactly whatcopy.copy()would have done once it found it, so a field is copied at the same points and to the same contents either way – only the redundant dispatch is skipped. See GitHub issue #730.- Return type:
- Returns:
A new field instance sharing this one’s attribute values.
- __set_name__(owner, name)[source]¶
Set field name and update field list (if applicable).
This method is to be called by the metaclass during class creation. It is used to set the field name and update the field list, i.e.,
Schema.__fields__mapping dictionary.
- unpack(buffer, packet)[source]¶
Unpack field value from
bytes.- Parameters:
- Return type:
_T- Returns:
Unpacked field value.
- Raises:
FieldValueError – If
bufferholds fewer octets thanlengthdeclares, and eitherlengthis pastMAX_ZERO_PAD_LENGTH, or the shortfall is pastMAX_ZERO_PAD_SHORTFALLand takes this parse’s total of such shortfalls past whatZERO_PAD_BUDGET_RATIOallows for the octets it has actually been given. A shortfall withinMAX_ZERO_PAD_SHORTFALLis always padded and never raises.
Changed in version 1.5.0: A short read is zero-filled on the tail, where its missing octets are, rather than on the head (#604).
Internal Definitions¶
- class pcapkit.corekit.fields.field.FieldMeta[_T](name, bases, namespace, /, **kwargs)[source]¶
-
Meta class to add dynamic support to
FieldBase.It defines nothing of its own, so a field class is built exactly as by
abc.ABCMeta.
- pcapkit.corekit.fields.field._RE_NEGATIVE_LENGTH_TEMPLATE¶
Matches a leading, optionally byte-order-prefixed negative count in a
FieldBase.template, e.g. the-1in'-1s'or in'>-1s'.Every template this package builds from a resolved field length is
f'{length}s'(seepcapkit.corekit.fields.strings,misc,collectionsand, before it gets byte-order-prefixed,numbers–NumberField.build_template’selsearm), so a negative resolved length always leaves that literal-immediately before the digits. WhatNumberFieldadds is a byte-order prefix – one of'@=<>!'– in front of that whole template (f'{endian}{struct_fmt}'), which is what a plain^-\d+misses: the prefix, not the minus sign, is what starts the string. The optional character class here accounts for exactly that one prefix position, so a negative count is recognised whether or not it was byte-order-prefixed, while still refusing anything else – a bare byte-order character with no minus sign after it ('>Xs'), or any other malformed template – which is what makes checking for it a reliable way to tell those cases apart from each other beforestruct.calcsize()is asked to size either one. See #825.- Type:
Pattern[str]