Skip to content

Commit 51eb712

Browse files
authored
fix(tcp)!: reserved bits, post-EOOL octets and the UTO granularity round-trip (#1211, #1218, #1219) (#1348)
- #1211: name the reserved bits of the header (octet 12, bits 4-6), the POC-SP Filler and the Quick-Start Resv./R bits in the schema, carry them in Flags.reserved, PartialOrderServiceProfile.reserved and QuickStartResponse.reserved/nonce_reserved, and write them back. - #1218: keep the octets after EOOL as TCP.padding and re-emit them while the options still end with EOOL, so the rebuilt Data Offset matches the parsed one; once the EOOL is edited out the padding is dropped and the Data Offset is recomputed. - #1219: store the G bit as UserTimeout.granularity and honour it in the maker while the value still fits in that unit, switching unit otherwise; the maker also takes an explicit granularity keyword, and the too-large error reports the actual value. Breaking: new required data-class fields, and the offset/profile/flags/nonce BitField dicts need a 'reserved' key. Existing tests that build those schemas and data by hand are updated to the new shape.
1 parent 0a32b2f commit 51eb712

10 files changed

Lines changed: 354 additions & 31 deletions

‎pcapkit/protocols/data/transport/tcp.py‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,12 @@ class Flags(Data):
6666
syn: 'bool'
6767
#: Last packet from sender.
6868
fin: 'bool'
69+
#: Reserved bits 4-6 of octet 12, between the Data Offset and ``NS``.
70+
reserved: 'int'
6971

7072
if TYPE_CHECKING:
7173
def __init__(self, ns: 'bool', cwr: 'bool', ece: 'bool', urg: 'bool', ack: 'bool',
72-
psh: 'bool', rst: 'bool', syn: 'bool', fin: 'bool') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
74+
psh: 'bool', rst: 'bool', syn: 'bool', fin: 'bool', reserved: 'int') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
7375

7476

7577
@info_final
@@ -98,6 +100,8 @@ class TCP(Protocol):
98100
if TYPE_CHECKING:
99101
#: TCP options.
100102
options: 'OrderedMultiDict[OptionNumber, Option]'
103+
#: Octets of the option area after the End of Option List option.
104+
padding: 'bytes'
101105
#: Connection control flags.
102106
connection: 'TCP_Flags'
103107

@@ -246,9 +250,11 @@ class PartialOrderServiceProfile(Option):
246250
start: 'bool'
247251
#: End flag.
248252
end: 'bool'
253+
#: Reserved bits (``Filler``).
254+
reserved: 'int'
249255

250256
if TYPE_CHECKING:
251-
def __init__(self, kind: 'OptionNumber', length: 'int', start: 'bool', end: 'bool') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
257+
def __init__(self, kind: 'OptionNumber', length: 'int', start: 'bool', end: 'bool', reserved: 'int') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
252258

253259

254260
@info_final
@@ -327,9 +333,13 @@ class QuickStartResponse(Option):
327333
ttl_diff: 'int'
328334
#: QS nonce.
329335
nonce: 'int'
336+
#: Reserved bits before the rate request (``Resv.``).
337+
reserved: 'int'
338+
#: Reserved bits after the QS nonce (``R``).
339+
nonce_reserved: 'int'
330340

331341
if TYPE_CHECKING:
332-
def __init__(self, kind: 'OptionNumber', length: 'int', req_rate: 'int', ttl_diff: 'int', nonce: 'int') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
342+
def __init__(self, kind: 'OptionNumber', length: 'int', req_rate: 'int', ttl_diff: 'int', nonce: 'int', reserved: 'int', nonce_reserved: 'int') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
333343

334344

335345
@info_final
@@ -338,9 +348,11 @@ class UserTimeout(Option):
338348

339349
#: User timeout.
340350
timeout: 'timedelta'
351+
#: Granularity (``G``): the timeout is in minutes if set, in seconds if not.
352+
granularity: 'bool'
341353

342354
if TYPE_CHECKING:
343-
def __init__(self, kind: 'OptionNumber', length: 'int', timeout: 'timedelta') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
355+
def __init__(self, kind: 'OptionNumber', length: 'int', timeout: 'timedelta', granularity: 'bool') -> 'None': ... # pylint: disable=unused-argument,super-init-not-called,multiple-statements,line-too-long,redefined-builtin
344356

345357

346358
@info_final

‎pcapkit/protocols/schema/transport/tcp.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ class OffsetFlag(TypedDict):
5454

5555
#: Data offset.
5656
offset: int
57+
#: Reserved bits.
58+
reserved: int
5759
#: ECN-nonce concealment protection.
5860
ns: int
5961

@@ -84,10 +86,14 @@ class POCProfile(TypedDict):
8486
start: int
8587
#: End flag.
8688
end: int
89+
#: Reserved bits (``Filler``).
90+
reserved: int
8791

8892
class QuickStartFlags(TypedDict):
8993
"""TCP quick start flags."""
9094

95+
#: Reserved bits.
96+
reserved: int
9197
#: Rate request.
9298
rate: int
9399

@@ -96,6 +102,8 @@ class QuickStartNonce(TypedDict):
96102

97103
#: Nonce.
98104
nonce: int
105+
#: Reserved bits (``R``).
106+
reserved: int
99107

100108
class TimeoutInfo(TypedDict):
101109
"""User timeout information."""
@@ -643,6 +651,7 @@ class PartialOrderServiceProfile(Option, code=Enum_Option.Partial_Order_Service_
643651
profile: 'POCProfile' = BitField(length=1, namespace={
644652
'start': (0, 1),
645653
'end': (1, 1),
654+
'reserved': (2, 6),
646655
})
647656

648657
if TYPE_CHECKING:
@@ -721,13 +730,15 @@ class QuickStartResponse(Option, code=Enum_Option.Quick_Start_Response):
721730

722731
#: Flags.
723732
flags: 'QuickStartFlags' = BitField(length=1, namespace={
733+
'reserved': (0, 4),
724734
'rate': (4, 4),
725735
})
726736
#: TTL difference.
727737
diff: 'int' = UInt8Field()
728738
#: QS nonce.
729739
nonce: 'QuickStartNonce' = BitField(length=4, namespace={
730740
'nonce': (0, 30),
741+
'reserved': (30, 2),
731742
})
732743

733744
if TYPE_CHECKING:
@@ -1176,6 +1187,7 @@ class TCP(Schema):
11761187
#: Data offset.
11771188
offset: 'OffsetFlag' = BitField(length=1, namespace={
11781189
'offset': (0, 4),
1190+
'reserved': (4, 3),
11791191
'ns': (7, 1),
11801192
})
11811193
#: TCP flags.

‎pcapkit/protocols/transport/tcp.py‎

Lines changed: 69 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
4 32 ``tcp.seq`` Sequence Number
2020
8 64 ``tcp.ack`` Acknowledgement Number (if ACK set)
2121
12 96 ``tcp.hdr_len`` Data Offset
22-
12 100 Reserved (must be ``\\x00``)
22+
12 100 ``tcp.flags.reserved`` Reserved (must be ``\\x00``)
2323
12 103 ``tcp.flags.ns`` ECN Concealment Protection (NS)
2424
13 104 ``tcp.flags.cwr`` Congestion Window Reduced (CWR)
2525
13 105 ``tcp.flags.ece`` ECN-Echo (ECE)
@@ -480,6 +480,7 @@ def read(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_TCP':
480480
rst=bool(schema.flags['rst']),
481481
syn=bool(schema.flags['syn']),
482482
fin=bool(schema.flags['fin']),
483+
reserved=schema.offset['reserved'],
483484
),
484485
window_size=schema.window,
485486
checksum=schema.checksum,
@@ -509,8 +510,13 @@ def read(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_TCP':
509510

510511
_optl = tcp.hdr_len - 20
511512
if _optl:
513+
# NOTE: the octets after an End of Option List option are kept as
514+
# read, so that :meth:`make` rebuilds the option area -- and the
515+
# Data Offset computed from it -- at its original length. A schema
516+
# built by hand rather than unpacked carries no ``padding``.
512517
tcp.__update__({
513518
'options': self._read_tcp_options(_optl),
519+
'padding': schema.get('padding', b''),
514520
})
515521

516522
return self._decode_next_layer(tcp, (tcp.srcport.port, tcp.dstport.port), length - tcp.hdr_len)
@@ -534,6 +540,8 @@ def make(self,
534540
urgent: 'int' = 0,
535541
options: 'Optional[list[Schema_Option | tuple[Enum_Option, dict[str, Any]] | bytes] | Option]' = None, # pylint: disable=line-too-long
536542
payload: 'bytes | ProtocolBase | Schema' = b'',
543+
padding: 'bytes' = b'',
544+
reserved: 'int' = 0,
537545
**kwargs: 'Any') -> 'Schema_TCP':
538546
"""Make (construct) packet data.
539547
@@ -556,6 +564,9 @@ def make(self,
556564
urgent: Urgent pointer.
557565
options: TCP options.
558566
payload: Payload of the packet.
567+
padding: Octets after the End of Option List option; dropped
568+
unless ``options`` end with one.
569+
reserved: Reserved bits 4-6 of octet 12.
559570
**kwargs: Arbitrary keyword arguments.
560571
561572
Returns:
@@ -603,7 +614,7 @@ def make(self,
603614
self._flags = _flag
604615

605616
if options is not None:
606-
options_value, total_length = self._make_tcp_options(options)
617+
options_value, total_length = self._make_tcp_options(options, padding)
607618
else:
608619
options_value, total_length = [], 0
609620

@@ -616,6 +627,7 @@ def make(self,
616627
ack=ack_no,
617628
offset={
618629
'offset': offset,
630+
'reserved': reserved,
619631
'ns': int(ns),
620632
},
621633
flags=flags,
@@ -705,6 +717,8 @@ def _make_data(cls, data: 'Data_TCP') -> 'dict[str, Any]': # type: ignore[overr
705717
'checksum': data.checksum,
706718
'urgent': data.urgent_pointer,
707719
'options': getattr(data, 'options', None),
720+
'padding': getattr(data, 'padding', b''),
721+
'reserved': data.flags.reserved,
708722
'payload': cls._make_payload(data),
709723
}
710724

@@ -1121,6 +1135,7 @@ def _read_mode_pocsp(self, schema: 'Schema_PartialOrderServiceProfile', *, optio
11211135
length=schema.length,
11221136
start=bool(schema.profile['start']),
11231137
end=bool(schema.profile['end']),
1138+
reserved=schema.profile['reserved'],
11241139
)
11251140
return data
11261141

@@ -1358,6 +1373,8 @@ def _read_mode_qs(self, schema: 'Schema_QuickStartResponse', *, options: 'Option
13581373
req_rate=40000 * (2 ** rate) / 1000 if rate > 0 else 0,
13591374
ttl_diff=schema.diff,
13601375
nonce=schema.nonce['nonce'],
1376+
reserved=schema.flags['reserved'],
1377+
nonce_reserved=schema.nonce['reserved'],
13611378
)
13621379
return data
13631380

@@ -1397,6 +1414,7 @@ def _read_mode_timeout(self, schema: 'Schema_UserTimeout', *, options: 'Option')
13971414
kind=schema.kind,
13981415
length=schema.length,
13991416
timeout=time,
1417+
granularity=bool(schema.info['granularity']),
14001418
)
14011419
return data
14021420

@@ -2056,21 +2074,25 @@ def _read_mode_fastopen(self, schema: 'Schema_FastOpenCookie', *, options: 'Opti
20562074
)
20572075
return data
20582076

2059-
def _make_tcp_options(self, options: 'list[Schema_Option | tuple[Enum_Option, dict[str, Any]] | bytes] | Option') -> 'tuple[list[Schema_Option | bytes], int]':
2077+
def _make_tcp_options(self, options: 'list[Schema_Option | tuple[Enum_Option, dict[str, Any]] | bytes] | Option',
2078+
padding: 'bytes' = b'') -> 'tuple[list[Schema_Option | bytes], int]':
20602079
"""Make options for TCP.
20612080
20622081
Args:
20632082
options: TCP options
2083+
padding: octets after the End of Option List option
20642084
20652085
Returns:
20662086
Tuple of options and total length of options.
20672087
20682088
Note:
20692089
The options are emitted in the given order, ``NOP`` and ``EOOL``
20702090
included, so that a parsed option list re-emits the same octets.
2071-
Padding is added only once, after the last option, when the list
2072-
does not end on a 32-bit boundary: zero octets if the list already
2073-
ends with ``EOOL``, otherwise ``NOP`` options followed by an ``EOOL``.
2091+
``padding`` follows them as given if they end with ``EOOL``, and is
2092+
dropped otherwise. Alignment is added only once, after that, when
2093+
the list does not end on a 32-bit boundary: zero octets if the list
2094+
already ends with ``EOOL``, otherwise ``NOP`` options followed by an
2095+
``EOOL``.
20742096
20752097
"""
20762098
total_length = 0
@@ -2117,6 +2139,13 @@ def _make_tcp_options(self, options: 'list[Schema_Option | tuple[Enum_Option, di
21172139
options_list.append(data)
21182140
total_length += data_len
21192141

2142+
# NOTE: ``padding`` belongs after an End of Option List option; with
2143+
# that gone -- e.g. options edited after parsing -- it is dropped, and
2144+
# the Data Offset is computed from the options alone.
2145+
if padding and code == Enum_Option.End_of_Option_List:
2146+
options_list.append(padding)
2147+
total_length += len(padding)
2148+
21202149
# force alignment to 32-bit boundary
21212150
if total_length % 4:
21222151
pad_len = 4 - (total_length % 4)
@@ -2388,6 +2417,7 @@ def _make_mode_poc(self, code: 'Enum_Option', opt: 'Optional[Data_PartialOrderCo
23882417
def _make_mode_pocsp(self, code: 'Enum_Option', opt: 'Optional[Data_PartialOrderServiceProfile]' = None, *,
23892418
start: 'bool' = False,
23902419
end: 'bool' = False,
2420+
reserved: 'int' = 0,
23912421
**kwargs: 'Any') -> 'Schema_PartialOrderServiceProfile':
23922422
"""Make TCP partial order connection service profile option.
23932423
@@ -2396,6 +2426,7 @@ def _make_mode_pocsp(self, code: 'Enum_Option', opt: 'Optional[Data_PartialOrder
23962426
opt: option data
23972427
start: start partial order connection
23982428
end: end partial order connection
2429+
reserved: reserved bits (``Filler``, 6 bits)
23992430
**kwargs: arbitrary keyword arguments
24002431
24012432
Returns:
@@ -2405,13 +2436,15 @@ def _make_mode_pocsp(self, code: 'Enum_Option', opt: 'Optional[Data_PartialOrder
24052436
if opt is not None:
24062437
start = opt.start
24072438
end = opt.end
2439+
reserved = opt.reserved
24082440

24092441
return Schema_PartialOrderServiceProfile(
24102442
kind=code,
24112443
length=3,
24122444
profile={
24132445
'start': start,
24142446
'end': end,
2447+
'reserved': reserved,
24152448
},
24162449
)
24172450

@@ -2572,6 +2605,8 @@ def _make_mode_qs(self, code: 'Enum_Option', opt: 'Optional[Data_QuickStartRespo
25722605
rate: 'int' = 0,
25732606
diff: 'timedelta | int' = 0,
25742607
nonce: 'int' = 0,
2608+
reserved: 'int' = 0,
2609+
nonce_reserved: 'int' = 0,
25752610
**kwargs: 'Any') -> 'Schema_QuickStartResponse':
25762611
"""Make TCP quick start response option.
25772612
@@ -2581,6 +2616,8 @@ def _make_mode_qs(self, code: 'Enum_Option', opt: 'Optional[Data_QuickStartRespo
25812616
rate: rate (in kbps)
25822617
diff: time to live (in seconds) difference
25832618
nonce: nonce value
2619+
reserved: reserved bits before the rate request (``Resv.``, 4 bits)
2620+
nonce_reserved: reserved bits after the nonce (``R``, 2 bits)
25842621
**kwargs: arbitrary keyword arguments
25852622
25862623
Returns:
@@ -2591,6 +2628,8 @@ def _make_mode_qs(self, code: 'Enum_Option', opt: 'Optional[Data_QuickStartRespo
25912628
rate = opt.req_rate
25922629
diff = opt.ttl_diff
25932630
nonce = opt.nonce
2631+
reserved = opt.reserved
2632+
nonce_reserved = opt.nonce_reserved
25942633

25952634
# :rfc:`4782` Section 3.1 encodes the rate as 40 kbps * 2 ** N, with
25962635
# N = 0 meaning a rate of zero; a response may report a lower rate than
@@ -2602,39 +2641,57 @@ def _make_mode_qs(self, code: 'Enum_Option', opt: 'Optional[Data_QuickStartRespo
26022641
kind=code,
26032642
length=8,
26042643
flags={
2644+
'reserved': reserved,
26052645
'rate': rate_val,
26062646
},
26072647
diff=diff_val,
26082648
nonce={
26092649
'nonce': nonce,
2650+
'reserved': nonce_reserved,
26102651
},
26112652
)
26122653

26132654
def _make_mode_timeout(self, code: 'Enum_Option', opt: 'Optional[Data_UserTimeout]' = None, *,
26142655
timeout: 'timedelta | int' = 0,
2656+
granularity: 'Optional[bool]' = None,
26152657
**kwargs: 'Any') -> 'Schema_UserTimeout':
26162658
"""Make TCP user timeout option.
26172659
26182660
Args:
26192661
code: option code
26202662
opt: option data
2621-
timeout: timeout value
2663+
timeout: timeout value (in seconds, if an :obj:`int`)
2664+
granularity: preferred unit, minutes (``G`` set) or seconds; it is
2665+
kept only while the value still fits in it -- seconds within 15
2666+
bits, minutes as a whole number of them. Otherwise, and if not
2667+
given, seconds are used when they fit in 15 bits, and minutes if
2668+
not.
26222669
**kwargs: arbitrary keyword arguments
26232670
26242671
Returns:
26252672
Constructed option schema.
26262673
2674+
Raises:
2675+
ProtocolError: If the timeout does not fit in 15 bits of minutes.
2676+
26272677
"""
26282678
if opt is not None:
2629-
timeout_val = math.floor(opt.timeout.total_seconds())
2679+
seconds = math.floor(opt.timeout.total_seconds())
2680+
granularity = opt.granularity
26302681
else:
2631-
timeout_val = timeout if isinstance(timeout, int) else math.floor(timeout.total_seconds())
2682+
seconds = timeout if isinstance(timeout, int) else math.floor(timeout.total_seconds())
26322683

2633-
granularity = timeout_val.bit_length() > 15
2634-
timeout_val = math.floor(timeout_val / 60) if granularity else timeout_val
2684+
# NOTE: a parsed (or requested) unit that the value no longer fits in --
2685+
# e.g. a parsed seconds option edited past 15 bits, or a minutes option
2686+
# edited to a value that is not a whole number of minutes -- falls back
2687+
# to the size-based choice, as when no unit is given at all.
2688+
fits_seconds = seconds.bit_length() <= 15
2689+
if granularity is None or (not granularity and not fits_seconds) or (granularity and seconds % 60):
2690+
granularity = not fits_seconds
2691+
timeout_val = math.floor(seconds / 60) if granularity else seconds
26352692

26362693
if timeout_val.bit_length() > 15:
2637-
raise ProtocolError(f'TCP: [OptNo {code}] timeout value too large: {timeout}')
2694+
raise ProtocolError(f'TCP: [OptNo {code}] timeout value too large: {seconds} seconds')
26382695

26392696
return Schema_UserTimeout(
26402697
kind=code,

0 commit comments

Comments
 (0)