Skip to content

Commit 36db422

Browse files
authored
fix(corekit): IPv4InterfaceField keeps non-netmask masks; OrderedMultiDict deepcopy keeps order (#1346)
- IPv4InterfaceField.post_process read a hostmask-shaped mask (0.0.0.255) as a prefix length and packed a different netmask; a non-contiguous mask raised. A mask that is not a contiguous netmask now unpacks to an IPv4Interface subclass that keeps the four octets. Its str() is dotted, or 0xXXXXXXXX when the dotted form would read as a hostmask, and pre_process reads either form literally only when ip_interface rejects the string, so stdlib-legal strings keep their meaning and every wire mask survives str() and pack. Equality and ordering use the mask (#1294). - OrderedMultiDict.deepcopy rebuilds from items(multi=True) instead of the inherited, key-grouping to_dict(flat=False); the werkzeug port of MultiDict is left verbatim (#1295). Closes #1294 Closes #1295
1 parent ad1c030 commit 36db422

5 files changed

Lines changed: 485 additions & 29 deletions

File tree

‎pcapkit/corekit/fields/ipaddress.py‎

Lines changed: 214 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import abc
55
import contextlib
66
import ipaddress
7+
import re
78
from typing import TYPE_CHECKING, Generic, TypeVar, cast
89

910
from pcapkit.corekit.fields.field import NO_VALUE, Field
@@ -347,6 +348,191 @@ class _IPInterfaceField(_IPField[_IT]):
347348
"""
348349

349350

351+
class _RawMaskIPv4Interface(ipaddress.IPv4Interface):
352+
"""IPv4 interface whose mask is not a contiguous netmask.
353+
354+
Args:
355+
address: Dotted address and mask, as ``'a.b.c.d/m.m.m.m'`` or
356+
``'a.b.c.d/0xXXXXXXXX'``; either way the mask is read literally.
357+
358+
:class:`ipaddress.IPv4Interface` can only hold a prefix length, so it
359+
reads a hostmask-shaped mask such as ``0.0.0.255`` as ``/24`` and rejects
360+
a mask such as ``255.0.255.0``. This class keeps the mask octets as given
361+
in :attr:`netmask`, so :meth:`IPv4InterfaceField.pre_process` writes them
362+
back unchanged.
363+
364+
:func:`str`, :func:`repr` and :mod:`pickle` use the ``address/mask``
365+
form, which :meth:`IPv4InterfaceField.pre_process` packs back to the same
366+
octets. The mask is dotted, except when it is hostmask-shaped (ones, then
367+
zeros, read from the low bit): :func:`ipaddress.ip_interface` would read
368+
such a dotted mask as a hostmask, so it is written as eight hex digits
369+
instead, e.g. ``10.0.0.1/0x000000ff``. The stdlib rejects that hex form,
370+
so it never means anything else there.
371+
372+
Equality and ordering use the mask too. An instance sorts as the stdlib
373+
sorts ``address/32``, then by mask, so the order stays total when mixed
374+
with :class:`ipaddress.IPv4Interface` values.
375+
376+
Such a mask has no prefix length, so :attr:`network`, :attr:`with_prefixlen`
377+
and the prefix length all describe the address alone (``/32``); only
378+
:attr:`netmask`, :attr:`hostmask`, :attr:`with_netmask` and
379+
:attr:`with_hostmask` carry the mask. :attr:`with_netmask` is always
380+
dotted, so it is not the round-trip form; :func:`str` is.
381+
382+
"""
383+
384+
def __init__(self, address: 'str') -> 'None':
385+
addr, _, mask = address.partition('/')
386+
super().__init__(addr)
387+
self.netmask = _parse_literal_mask(mask)
388+
389+
@property
390+
def hostmask(self) -> 'IPv4Address':
391+
"""Bitwise inverse of :attr:`netmask`."""
392+
return ipaddress.IPv4Address(int(self.netmask) ^ 0xFFFFFFFF)
393+
394+
def __str__(self) -> 'str':
395+
if _is_hostmask(self.netmask):
396+
return f'{self.ip}/0x{int(self.netmask):08x}'
397+
return f'{self.ip}/{self.netmask}'
398+
399+
def __eq__(self, other: 'object') -> 'bool':
400+
if not isinstance(other, ipaddress.IPv4Interface):
401+
return NotImplemented
402+
return self.ip == other.ip and self.netmask == other.netmask
403+
404+
def __hash__(self) -> 'int':
405+
return hash((int(self.ip), int(self.netmask)))
406+
407+
def __lt__(self, other: 'Any') -> 'bool':
408+
if not isinstance(other, ipaddress.IPv4Interface):
409+
return ipaddress.IPv4Interface.__lt__(self, other)
410+
return _interface_order(self) < _interface_order(other)
411+
412+
def __le__(self, other: 'Any') -> 'bool':
413+
if not isinstance(other, ipaddress.IPv4Interface):
414+
return ipaddress.IPv4Interface.__le__(self, other)
415+
return _interface_order(self) <= _interface_order(other)
416+
417+
def __gt__(self, other: 'Any') -> 'bool':
418+
if not isinstance(other, ipaddress.IPv4Interface):
419+
return ipaddress.IPv4Interface.__gt__(self, other)
420+
return _interface_order(self) > _interface_order(other)
421+
422+
def __ge__(self, other: 'Any') -> 'bool':
423+
if not isinstance(other, ipaddress.IPv4Interface):
424+
return ipaddress.IPv4Interface.__ge__(self, other)
425+
return _interface_order(self) >= _interface_order(other)
426+
427+
428+
def _is_netmask(mask: 'IPv4Address') -> 'bool':
429+
"""Tell whether ``mask`` is a contiguous netmask (leading ones, then zeros).
430+
431+
Args:
432+
mask: Dotted mask.
433+
434+
Returns:
435+
:data:`True` for ``0.0.0.0`` through ``255.255.255.255`` with no gap
436+
in the ones, :data:`False` otherwise.
437+
438+
"""
439+
inverse = int(mask) ^ 0xFFFFFFFF
440+
return not inverse & (inverse + 1)
441+
442+
443+
def _is_hostmask(mask: 'IPv4Address') -> 'bool':
444+
"""Tell whether ``mask`` is hostmask-shaped (leading zeros, then ones).
445+
446+
Args:
447+
mask: Dotted mask.
448+
449+
Returns:
450+
:data:`True` when :func:`ipaddress.ip_interface` would accept the
451+
dotted ``mask`` as a hostmask, :data:`False` otherwise.
452+
453+
"""
454+
value = int(mask)
455+
return not value & (value + 1)
456+
457+
458+
#: Hex spelling of a literal mask, as :func:`str` writes a hostmask-shaped one.
459+
_HEX_MASK = re.compile(r'0[xX][0-9a-fA-F]{8}')
460+
461+
462+
def _parse_literal_mask(text: 'str') -> 'IPv4Address':
463+
"""Read a mask literally, from eight hex digits or a dotted quad.
464+
465+
Args:
466+
text: ``0xXXXXXXXX`` or ``m.m.m.m``.
467+
468+
Returns:
469+
The mask as given, never reinterpreted as a hostmask.
470+
471+
Raises:
472+
ValueError: If ``text`` is neither form.
473+
474+
"""
475+
if _HEX_MASK.fullmatch(text) is not None:
476+
return ipaddress.IPv4Address(int(text, 16))
477+
return ipaddress.IPv4Address(text)
478+
479+
480+
def _interface_from_mask(ip: 'IPv4Address', mask: 'IPv4Address') -> 'IPv4Interface':
481+
"""Build the interface for an address and a literal mask.
482+
483+
Args:
484+
ip: Interface address.
485+
mask: Mask, taken as given.
486+
487+
Returns:
488+
A stdlib :class:`~ipaddress.IPv4Interface` when ``mask`` is a
489+
contiguous netmask, otherwise a :class:`_RawMaskIPv4Interface`.
490+
491+
"""
492+
if _is_netmask(mask):
493+
return ipaddress.IPv4Interface(f'{ip}/{mask}')
494+
return _RawMaskIPv4Interface(f'{ip}/{mask}')
495+
496+
497+
def _literal_interface(value: 'str') -> 'Optional[IPv4Interface]':
498+
"""Read an ``address/mask`` string with the mask taken literally.
499+
500+
Args:
501+
value: Interface string that :func:`ipaddress.ip_interface` rejected.
502+
503+
Returns:
504+
The interface, or :obj:`None` if ``value`` is not an IPv4 address
505+
followed by a dotted or ``0xXXXXXXXX`` mask.
506+
507+
"""
508+
addr, sep, mask = value.partition('/')
509+
if not sep or ('.' not in mask and _HEX_MASK.fullmatch(mask) is None):
510+
return None
511+
try:
512+
return _interface_from_mask(ipaddress.IPv4Address(addr), _parse_literal_mask(mask))
513+
except ValueError:
514+
return None
515+
516+
517+
def _interface_order(value: 'IPv4Interface') -> 'tuple[int, int, int, int]':
518+
"""Sort key for an IPv4 interface, consistent with ``==``.
519+
520+
Args:
521+
value: IPv4 interface, either from the stdlib or a
522+
:class:`_RawMaskIPv4Interface`.
523+
524+
Returns:
525+
The stdlib order (network address, netmask, address), with a third
526+
element that is ``0`` for a stdlib interface and ``1 + mask`` for a
527+
:class:`_RawMaskIPv4Interface`, whose stdlib network is
528+
``address/32``.
529+
530+
"""
531+
if isinstance(value, _RawMaskIPv4Interface):
532+
return int(value.ip), 0xFFFFFFFF, 1 + int(value.netmask), int(value.ip)
533+
return int(value.network.network_address), int(value.network.netmask), 0, int(value.ip)
534+
535+
350536
class IPv4InterfaceField(_IPInterfaceField[ipaddress.IPv4Interface]):
351537
"""IPv4 interface value for protocol fields.
352538
@@ -383,14 +569,28 @@ def pre_process(self, value: 'IPv4Interface | bytes | int | str', packet: 'dict[
383569
:func:`_reject_bool`), is not a valid IP interface, or is the
384570
wrong IP version for this field.
385571
572+
Notes:
573+
A string means what :func:`ipaddress.ip_interface` says it
574+
means, so ``'10.0.0.1/0.0.0.255'`` is the hostmask spelling of
575+
``/24``. Only a string the stdlib rejects is read with its mask
576+
taken literally: a dotted mask that is neither a netmask nor a
577+
hostmask, such as ``'10.0.0.1/255.0.255.0'``, or eight hex
578+
digits, such as ``'10.0.0.1/0x000000ff'``. Those are the forms
579+
:func:`str` gives a :class:`_RawMaskIPv4Interface`.
580+
386581
"""
387582
_reject_bool(value, 'invalid IP interface')
388583

389584
if isinstance(value, ipaddress.IPv4Interface):
390585
val = value
391586
else:
392-
with _reraise_as_field_value_error('invalid IP interface'):
393-
parsed = ipaddress.ip_interface(value)
587+
try:
588+
parsed = ipaddress.ip_interface(value) # type: IPv4Interface | IPv6Interface
589+
except ValueError as error:
590+
literal = _literal_interface(value) if isinstance(value, str) else None
591+
if literal is None:
592+
raise FieldValueError(f'invalid IP interface: {error}') from error
593+
parsed = literal
394594
if not isinstance(parsed, ipaddress.IPv4Interface):
395595
raise FieldValueError(f'IP version mismatch: {parsed.version} != {self.version}')
396596
val = parsed
@@ -410,26 +610,29 @@ def post_process(self, value: 'bytes', packet: 'dict[str, Any]') -> 'IPv4Interfa
410610
Processed field value.
411611
412612
Raises:
413-
FieldValueError: If the trailing four octets are not a valid
414-
dotted netmask, or if the resulting interface is the wrong IP
415-
version for this field. The leading four octets cannot
416-
actually fail here -- they are always exactly 4 octets, fixed
417-
by this field's length, and any such octet string is a valid
418-
address -- but the conversion is still wrapped for
419-
consistency with the rest of this module.
613+
FieldValueError: If the resulting interface is the wrong IP
614+
version for this field. The eight octets cannot actually fail
615+
to convert here -- they are always exactly 8 octets, fixed by
616+
this field's length, any four octets are a valid address, and
617+
a mask that is not a netmask is kept as given -- but the
618+
conversion is still wrapped for consistency with the rest of
619+
this module.
420620
421621
Notes:
422622
The trailing four octets are a dotted netmask, as written by
423623
:meth:`pre_process` -- not a prefix length as in
424-
:meth:`IPv6InterfaceField.post_process`.
624+
:meth:`IPv6InterfaceField.post_process`. When they are not a
625+
contiguous netmask, the value is a :class:`_RawMaskIPv4Interface`
626+
that keeps them as given, rather than an interface the stdlib
627+
would reinterpret (``0.0.0.255`` as the hostmask of ``/24``).
425628
426629
"""
427630
with _reraise_as_field_value_error('invalid IPv4 address'):
428631
ip = ipaddress.IPv4Address(value[:4])
429632
mask = ipaddress.IPv4Address(value[4:])
430633

431634
with _reraise_as_field_value_error('invalid IPv4 interface'):
432-
val = ipaddress.ip_interface(f'{ip}/{mask}')
635+
val = _interface_from_mask(ip, mask)
433636
if not isinstance(val, ipaddress.IPv4Interface):
434637
raise FieldValueError(f'IP version mismatch: {val.version} != {self.version}')
435638
return val

‎pcapkit/corekit/multidict.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,18 @@ def __eq__(self, other: 'Any') -> 'bool':
497497

498498
__hash__ = None # type: ignore[assignment]
499499

500+
def deepcopy(self, memo: 'Optional[dict]' = None) -> 'OrderedMultiDict[_KT, _VT]':
501+
"""Return a deep copy of this object.
502+
503+
Notes:
504+
:meth:`MultiDict.deepcopy` rebuilds from :meth:`to_dict` with
505+
``flat=False``, which groups the values by key. This rebuilds from
506+
``items(multi=True)`` instead, so the copy keeps the insertion
507+
order of interleaved keys. :meth:`__deepcopy__` reaches it too.
508+
509+
"""
510+
return self.__class__(copy.deepcopy(list(self.items(multi=True)), memo=memo))
511+
500512
def __reduce_ex__(self, protocol: 'SupportsIndex') -> 'tuple[type, tuple[list[tuple[_KT, _VT]]]]':
501513
return type(self), (list(self.items(multi=True)),)
502514

‎tests/corekit/test_fields_ipaddress.py‎

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -606,30 +606,24 @@ def test_switch_backed_address_makers_reject_a_bool(self) -> None:
606606
locator_set=[{'ip': int(True)}]).pack().hex(),
607607
'00c1001800000400000000000000000000000000000000000000000100000000')
608608

609-
def test_ipv4_interface_post_process_rejects_a_non_contiguous_netmask(self) -> None:
610-
"""``IPv4InterfaceField.post_process`` builds
611-
``ipaddress.ip_interface(f'{ip}/{mask}')`` from wire bytes whose
612-
trailing four octets are meant to be a dotted netmask. Unlike the
613-
leading four octets (always exactly 4 octets, so always a valid
614-
address), those trailing octets are not guaranteed to form a
615-
*contiguous* netmask -- e.g. a capture with a malformed or corrupted
616-
IPv4 interface option can carry ``0.255.0.255``, which
617-
:func:`ipaddress.ip_interface` rejects with a bare
618-
:exc:`~ipaddress.NetmaskValueError`. This is reachable through
619-
:meth:`~pcapkit.corekit.fields.field.FieldBase.unpack` alone, with no
620-
malformed-length input required, and must raise :exc:`FieldValueError`
621-
instead.
609+
def test_ipv4_interface_post_process_keeps_a_non_contiguous_netmask(self) -> None:
610+
"""``IPv4InterfaceField.post_process`` reads wire bytes whose trailing
611+
four octets are meant to be a dotted netmask. Those octets are not
612+
guaranteed to form a *contiguous* netmask -- e.g. a capture with a
613+
malformed or corrupted IPv4 interface option can carry
614+
``0.255.0.255``, which :func:`ipaddress.ip_interface` rejects. The
615+
field keeps such a mask as given, so the value packs back to the same
616+
octets (c.f. :issue:`1294`).
622617
"""
623618
from pcapkit.corekit.fields.ipaddress import IPv4InterfaceField
624-
from pcapkit.utilities.exceptions import BaseError, FieldValueError
625619

626620
field = IPv4InterfaceField()
627621
raw = ipaddress.IPv4Address('1.2.3.4').packed + bytes([0, 255, 0, 255])
628622

629-
with self.assertRaises(FieldValueError) as context:
630-
field.unpack(raw, {})
631-
self.assertIsInstance(context.exception, BaseError)
632-
self.assertIn('0.255.0.255', str(context.exception))
623+
value = field.unpack(raw, {})
624+
self.assertIsInstance(value, ipaddress.IPv4Interface)
625+
self.assertEqual(value.netmask, ipaddress.IPv4Address('0.255.0.255'))
626+
self.assertEqual(field.pack(value, {}), raw)
633627

634628

635629
if __name__ == '__main__':

0 commit comments

Comments
 (0)