44import abc
55import contextlib
66import ipaddress
7+ import re
78from typing import TYPE_CHECKING , Generic , TypeVar , cast
89
910from 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+
350536class 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
0 commit comments