/
rtcsctptransport.py
1781 lines (1499 loc) · 58.3 KB
/
rtcsctptransport.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import enum
import hmac
import logging
import math
import os
import time
from collections import deque
from struct import pack, unpack_from
from typing import Any, Callable, Deque, Dict, Iterator, List, Optional, Set, Tuple
import attr
from pyee import AsyncIOEventEmitter
from .exceptions import InvalidStateError
from .rtcdatachannel import RTCDataChannel, RTCDataChannelParameters
from .rtcdtlstransport import RTCDtlsTransport
from .utils import random32, uint16_add, uint16_gt, uint32_gt, uint32_gte
try:
from crc32c import crc32
except ImportError: # pragma: no cover
os.environ["CRC32C_SW_MODE"] = "1"
from crc32c import crc32
logger = logging.getLogger("sctp")
# local constants
COOKIE_LENGTH = 24
COOKIE_LIFETIME = 60
MAX_STREAMS = 65535
USERDATA_MAX_LENGTH = 1200
# protocol constants
SCTP_CAUSE_INVALID_STREAM = 0x0001
SCTP_CAUSE_STALE_COOKIE = 0x0003
SCTP_DATA_LAST_FRAG = 0x01
SCTP_DATA_FIRST_FRAG = 0x02
SCTP_DATA_UNORDERED = 0x04
SCTP_MAX_ASSOCIATION_RETRANS = 10
SCTP_MAX_BURST = 4
SCTP_MAX_INIT_RETRANS = 8
SCTP_RTO_ALPHA = 1 / 8
SCTP_RTO_BETA = 1 / 4
SCTP_RTO_INITIAL = 3.0
SCTP_RTO_MIN = 1
SCTP_RTO_MAX = 60
SCTP_TSN_MODULO = 2 ** 32
RECONFIG_MAX_STREAMS = 135
# parameters
SCTP_STATE_COOKIE = 0x0007
SCTP_STR_RESET_OUT_REQUEST = 0x000D
SCTP_STR_RESET_RESPONSE = 0x0010
SCTP_STR_RESET_ADD_OUT_STREAMS = 0x0011
SCTP_SUPPORTED_CHUNK_EXT = 0x8008
SCTP_PRSCTP_SUPPORTED = 0xC000
# data channel constants
DATA_CHANNEL_ACK = 2
DATA_CHANNEL_OPEN = 3
DATA_CHANNEL_RELIABLE = 0x00
DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT = 0x01
DATA_CHANNEL_PARTIAL_RELIABLE_TIMED = 0x02
DATA_CHANNEL_RELIABLE_UNORDERED = 0x80
DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED = 0x81
DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED = 0x82
WEBRTC_DCEP = 50
WEBRTC_STRING = 51
WEBRTC_BINARY = 53
WEBRTC_STRING_EMPTY = 56
WEBRTC_BINARY_EMPTY = 57
def chunk_type(chunk) -> str:
return chunk.__class__.__name__
def decode_params(body: bytes) -> List[Tuple[int, bytes]]:
params = []
pos = 0
while pos <= len(body) - 4:
param_type, param_length = unpack_from("!HH", body, pos)
params.append((param_type, body[pos + 4 : pos + param_length]))
pos += param_length + padl(param_length)
return params
def encode_params(params: List[Tuple[int, bytes]]) -> bytes:
body = b""
padding = b""
for param_type, param_value in params:
param_length = len(param_value) + 4
body += padding
body += pack("!HH", param_type, param_length) + param_value
padding = b"\x00" * padl(param_length)
return body
def padl(l: int) -> int:
m = l % 4
return 4 - m if m else 0
def tsn_minus_one(a: int) -> int:
return (a - 1) % SCTP_TSN_MODULO
def tsn_plus_one(a: int) -> int:
return (a + 1) % SCTP_TSN_MODULO
class Chunk:
type = -1
def __init__(self, flags: int = 0, body: bytes = b"") -> None:
self.flags = flags
self.body = body
def __bytes__(self) -> bytes:
body = self.body
data = pack("!BBH", self.type, self.flags, len(body) + 4) + body
data += b"\x00" * padl(len(body))
return data
def __repr__(self) -> str:
return "%s(flags=%d)" % (chunk_type(self), self.flags)
class BaseParamsChunk(Chunk):
def __init__(self, flags: int = 0, body: Optional[bytes] = None) -> None:
self.flags = flags
if body:
self.params = decode_params(body)
else:
self.params = []
@property
def body(self) -> bytes:
return encode_params(self.params)
class AbortChunk(BaseParamsChunk):
type = 6
class CookieAckChunk(Chunk):
type = 11
class CookieEchoChunk(Chunk):
type = 10
class DataChunk(Chunk):
type = 0
def __init__(self, flags: int = 0, body: Optional[bytes] = None) -> None:
self.flags = flags
if body:
(self.tsn, self.stream_id, self.stream_seq, self.protocol) = unpack_from(
"!LHHL", body
)
self.user_data = body[12:]
else:
self.tsn = 0
self.stream_id = 0
self.stream_seq = 0
self.protocol = 0
self.user_data = b""
def __bytes__(self) -> bytes:
length = 16 + len(self.user_data)
data = (
pack(
"!BBHLHHL",
self.type,
self.flags,
length,
self.tsn,
self.stream_id,
self.stream_seq,
self.protocol,
)
+ self.user_data
)
if length % 4:
data += b"\x00" * padl(length)
return data
def __repr__(self) -> str:
return "DataChunk(flags=%d, tsn=%d, stream_id=%d, stream_seq=%d)" % (
self.flags,
self.tsn,
self.stream_id,
self.stream_seq,
)
class ErrorChunk(BaseParamsChunk):
type = 9
class ForwardTsnChunk(Chunk):
type = 192
def __init__(self, flags: int = 0, body: Optional[bytes] = None) -> None:
self.flags = flags
self.streams = [] # type: List[Tuple[int, int]]
if body:
self.cumulative_tsn = unpack_from("!L", body, 0)[0]
pos = 4
while pos < len(body):
self.streams.append(unpack_from("!HH", body, pos))
pos += 4
else:
self.cumulative_tsn = 0
@property
def body(self) -> bytes:
body = pack("!L", self.cumulative_tsn)
for stream_id, stream_seq in self.streams:
body += pack("!HH", stream_id, stream_seq)
return body
def __repr__(self) -> str:
return "ForwardTsnChunk(cumulative_tsn=%d, streams=%s)" % (
self.cumulative_tsn,
self.streams,
)
class HeartbeatChunk(BaseParamsChunk):
type = 4
class HeartbeatAckChunk(BaseParamsChunk):
type = 5
class BaseInitChunk(Chunk):
def __init__(self, flags: int = 0, body: Optional[bytes] = None) -> None:
self.flags = flags
if body:
(
self.initiate_tag,
self.advertised_rwnd,
self.outbound_streams,
self.inbound_streams,
self.initial_tsn,
) = unpack_from("!LLHHL", body)
self.params = decode_params(body[16:])
else:
self.initiate_tag = 0
self.advertised_rwnd = 0
self.outbound_streams = 0
self.inbound_streams = 0
self.initial_tsn = 0
self.params = []
@property
def body(self) -> bytes:
body = pack(
"!LLHHL",
self.initiate_tag,
self.advertised_rwnd,
self.outbound_streams,
self.inbound_streams,
self.initial_tsn,
)
body += encode_params(self.params)
return body
class InitChunk(BaseInitChunk):
type = 1
class InitAckChunk(BaseInitChunk):
type = 2
class ReconfigChunk(BaseParamsChunk):
type = 130
class SackChunk(Chunk):
type = 3
def __init__(self, flags=0, body=None):
self.flags = flags
self.gaps = []
self.duplicates = []
if body:
(
self.cumulative_tsn,
self.advertised_rwnd,
nb_gaps,
nb_duplicates,
) = unpack_from("!LLHH", body)
pos = 12
for i in range(nb_gaps):
self.gaps.append(unpack_from("!HH", body, pos))
pos += 4
for i in range(nb_duplicates):
self.duplicates.append(unpack_from("!L", body, pos)[0])
pos += 4
else:
self.cumulative_tsn = 0
self.advertised_rwnd = 0
def __bytes__(self) -> bytes:
length = 16 + 4 * (len(self.gaps) + len(self.duplicates))
data = pack(
"!BBHLLHH",
self.type,
self.flags,
length,
self.cumulative_tsn,
self.advertised_rwnd,
len(self.gaps),
len(self.duplicates),
)
for gap in self.gaps:
data += pack("!HH", *gap)
for tsn in self.duplicates:
data += pack("!L", tsn)
return data
def __repr__(self) -> str:
return "SackChunk(flags=%d, advertised_rwnd=%d, cumulative_tsn=%d, gaps=%s)" % (
self.flags,
self.advertised_rwnd,
self.cumulative_tsn,
self.gaps,
)
class ShutdownChunk(Chunk):
type = 7
def __init__(self, flags=0, body=None):
self.flags = flags
if body:
self.cumulative_tsn = unpack_from("!L", body)[0]
else:
self.cumulative_tsn = 0
@property
def body(self) -> bytes:
return pack("!L", self.cumulative_tsn)
def __repr__(self) -> str:
return "ShutdownChunk(flags=%d, cumulative_tsn=%d)" % (
self.flags,
self.cumulative_tsn,
)
class ShutdownAckChunk(Chunk):
type = 8
class ShutdownCompleteChunk(Chunk):
type = 14
CHUNK_CLASSES = [
DataChunk,
InitChunk,
InitAckChunk,
SackChunk,
HeartbeatChunk,
HeartbeatAckChunk,
AbortChunk,
ShutdownChunk,
ShutdownAckChunk,
ErrorChunk,
CookieEchoChunk,
CookieAckChunk,
ShutdownCompleteChunk,
ReconfigChunk,
ForwardTsnChunk,
]
CHUNK_TYPES = dict((cls.type, cls) for cls in CHUNK_CLASSES)
def parse_packet(data: bytes) -> Tuple[int, int, int, List[Any]]:
length = len(data)
if length < 12:
raise ValueError("SCTP packet length is less than 12 bytes")
source_port, destination_port, verification_tag = unpack_from("!HHL", data)
# verify checksum
checksum = unpack_from("<L", data, 8)[0]
if checksum != crc32(data[0:8] + b"\x00\x00\x00\x00" + data[12:]):
raise ValueError("SCTP packet has invalid checksum")
chunks = []
pos = 12
while pos <= length - 4:
chunk_type, chunk_flags, chunk_length = unpack_from("!BBH", data, pos)
chunk_body = data[pos + 4 : pos + chunk_length]
chunk_cls = CHUNK_TYPES.get(chunk_type)
if chunk_cls:
chunks.append(chunk_cls(flags=chunk_flags, body=chunk_body))
pos += chunk_length + padl(chunk_length)
return source_port, destination_port, verification_tag, chunks
def serialize_packet(
source_port: int, destination_port: int, verification_tag: int, chunk: Chunk
) -> bytes:
header = pack("!HHL", source_port, destination_port, verification_tag)
data = bytes(chunk)
checksum = crc32(header + b"\x00\x00\x00\x00" + data)
return header + pack("<L", checksum) + data
# RFC 6525
@attr.s
class StreamResetOutgoingParam:
request_sequence = attr.ib()
response_sequence = attr.ib()
last_tsn = attr.ib()
streams = attr.ib(default=attr.Factory(list))
def __bytes__(self) -> bytes:
data = pack(
"!LLL", self.request_sequence, self.response_sequence, self.last_tsn
)
for stream in self.streams:
data += pack("!H", stream)
return data
@classmethod
def parse(cls, data):
request_sequence, response_sequence, last_tsn = unpack_from("!LLL", data)
streams = []
for pos in range(12, len(data), 2):
streams.append(unpack_from("!H", data, pos)[0])
return cls(
request_sequence=request_sequence,
response_sequence=response_sequence,
last_tsn=last_tsn,
streams=streams,
)
@attr.s
class StreamAddOutgoingParam:
request_sequence = attr.ib()
new_streams = attr.ib()
def __bytes__(self) -> bytes:
data = pack("!LHH", self.request_sequence, self.new_streams, 0)
return data
@classmethod
def parse(cls, data):
request_sequence, new_streams, reserved = unpack_from("!LHH", data)
return cls(request_sequence=request_sequence, new_streams=new_streams)
@attr.s
class StreamResetResponseParam:
response_sequence = attr.ib()
result = attr.ib()
def __bytes__(self) -> bytes:
return pack("!LL", self.response_sequence, self.result)
@classmethod
def parse(cls, data):
response_sequence, result = unpack_from("!LL", data)
return cls(response_sequence=response_sequence, result=result)
RECONFIG_PARAM_TYPES = {
13: StreamResetOutgoingParam,
16: StreamResetResponseParam,
17: StreamAddOutgoingParam,
}
class InboundStream:
def __init__(self) -> None:
self.reassembly = [] # type: List[DataChunk]
self.sequence_number = 0
def add_chunk(self, chunk: DataChunk) -> None:
if not self.reassembly or uint32_gt(chunk.tsn, self.reassembly[-1].tsn):
self.reassembly.append(chunk)
return
for i, rchunk in enumerate(self.reassembly):
# should never happen, the chunk should have been eliminated
# as a duplicate when _mark_received() is called
assert rchunk.tsn != chunk.tsn, "duplicate chunk in reassembly"
if uint32_gt(rchunk.tsn, chunk.tsn):
self.reassembly.insert(i, chunk)
break
def pop_messages(self) -> Iterator[Tuple[int, int, bytes]]:
pos = 0
start_pos = None
while pos < len(self.reassembly):
chunk = self.reassembly[pos]
if start_pos is None:
ordered = not (chunk.flags & SCTP_DATA_UNORDERED)
if not (chunk.flags & SCTP_DATA_FIRST_FRAG):
if ordered:
break
else:
pos += 1
continue
if ordered and uint16_gt(chunk.stream_seq, self.sequence_number):
break
expected_tsn = chunk.tsn
start_pos = pos
elif chunk.tsn != expected_tsn:
if ordered:
break
else:
start_pos = None
pos += 1
continue
if chunk.flags & SCTP_DATA_LAST_FRAG:
user_data = b"".join(
[c.user_data for c in self.reassembly[start_pos : pos + 1]]
)
self.reassembly = (
self.reassembly[:start_pos] + self.reassembly[pos + 1 :]
)
if ordered and chunk.stream_seq == self.sequence_number:
self.sequence_number = uint16_add(self.sequence_number, 1)
pos = start_pos
yield (chunk.stream_id, chunk.protocol, user_data)
else:
pos += 1
expected_tsn = tsn_plus_one(expected_tsn)
def prune_chunks(self, tsn: int) -> int:
"""
Prune chunks up to the given TSN.
"""
pos = -1
size = 0
for i, chunk in enumerate(self.reassembly):
if uint32_gte(tsn, chunk.tsn):
pos = i
size += len(chunk.user_data)
else:
break
self.reassembly = self.reassembly[pos + 1 :]
return size
@attr.s
class RTCSctpCapabilities:
"""
The :class:`RTCSctpCapabilities` dictionary provides information about the
capabilities of the :class:`RTCSctpTransport`.
"""
maxMessageSize = attr.ib()
"""
The maximum size of data that the implementation can send or
0 if the implementation can handle messages of any size.
"""
class RTCSctpTransport(AsyncIOEventEmitter):
"""
The :class:`RTCSctpTransport` interface includes information relating to
Stream Control Transmission Protocol (SCTP) transport.
:param transport: An :class:`RTCDtlsTransport`.
"""
def __init__(self, transport: RTCDtlsTransport, port: int = 5000) -> None:
if transport.state == "closed":
raise InvalidStateError
super().__init__()
self._association_state = self.State.CLOSED
self.__log_debug = lambda *args: None # type: Callable[..., None]
self.__started = False
self.__state = "new"
self.__transport = transport
self._loop = asyncio.get_event_loop()
self._hmac_key = os.urandom(16)
self._local_partial_reliability = True
self._local_port = port
self._local_verification_tag = random32()
self._remote_extensions = [] # type: List[int]
self._remote_partial_reliability = False
self._remote_port = None # type: Optional[int]
self._remote_verification_tag = 0
# inbound
self._advertised_rwnd = 1024 * 1024
self._inbound_streams = {} # type: Dict[int, InboundStream]
self._inbound_streams_count = 0
self._inbound_streams_max = MAX_STREAMS
self._last_received_tsn = None # type: Optional[int]
self._sack_duplicates = [] # type: List[int]
self._sack_misordered = set() # type: Set[int]
self._sack_needed = False
# outbound
self._cwnd = 3 * USERDATA_MAX_LENGTH
self._fast_recovery_exit = None
self._fast_recovery_transmit = False
self._forward_tsn_chunk = None # type: Optional[ForwardTsnChunk]
self._flight_size = 0
self._local_tsn = random32()
self._last_sacked_tsn = tsn_minus_one(self._local_tsn)
self._advanced_peer_ack_tsn = tsn_minus_one(self._local_tsn)
self._outbound_queue = deque() # type: Deque[DataChunk]
self._outbound_stream_seq = {} # type: Dict[int, int]
self._outbound_streams_count = MAX_STREAMS
self._partial_bytes_acked = 0
self._sent_queue = deque() # type: Deque[DataChunk]
# reconfiguration
self._reconfig_queue = [] # type: List[int]
self._reconfig_request = None
self._reconfig_request_seq = self._local_tsn
self._reconfig_response_seq = 0
# rtt calculation
self._srtt = None # type: Optional[float]
self._rttvar = None # type: Optional[float]
# timers
self._rto = SCTP_RTO_INITIAL
self._t1_chunk = None # type: Optional[Chunk]
self._t1_failures = 0
self._t1_handle = None # type: Optional[asyncio.TimerHandle]
self._t2_chunk = None # type: Optional[Chunk]
self._t2_failures = 0
self._t2_handle = None # type: Optional[asyncio.TimerHandle]
self._t3_handle = None # type: Optional[asyncio.TimerHandle]
# data channels
self._data_channel_id = None # type: Optional[int]
self._data_channel_queue = (
deque()
) # type: Deque[Tuple[RTCDataChannel, int, bytes]]
self._data_channels = {} # type: Dict[int, RTCDataChannel]
# FIXME: this is only used by RTCPeerConnection
self._bundled = False
self.mid = None # type: Optional[str]
@property
def is_server(self) -> bool:
return self.transport.transport.role != "controlling"
@property
def port(self) -> int:
"""
The local SCTP port number used for data channels.
"""
return self._local_port
@property
def state(self) -> str:
"""
The current state of the SCTP transport.
"""
return self.__state
@property
def transport(self):
"""
The :class:`RTCDtlsTransport` over which SCTP data is transmitted.
"""
return self.__transport
@classmethod
def getCapabilities(cls) -> RTCSctpCapabilities:
"""
Retrieve the capabilities of the transport.
:rtype: RTCSctpCapabilities
"""
return RTCSctpCapabilities(maxMessageSize=65536)
def setTransport(self, transport) -> None:
self.__transport = transport
async def start(self, remoteCaps: RTCSctpCapabilities, remotePort: int) -> None:
"""
Start the transport.
"""
if not self.__started:
self.__started = True
self.__state = "connecting"
self._remote_port = remotePort
# configure logging
if logger.isEnabledFor(logging.DEBUG):
prefix = self.is_server and "server " or "client "
self.__log_debug = lambda msg, *args: logger.debug(prefix + msg, *args)
# initialise local channel ID counter
# one side should be using even IDs, the other odd IDs
if self.is_server:
self._data_channel_id = 0
else:
self._data_channel_id = 1
self.__transport._register_data_receiver(self)
if not self.is_server:
await self._init()
async def stop(self) -> None:
"""
Stop the transport.
"""
if self._association_state != self.State.CLOSED:
await self._abort()
self.__transport._unregister_data_receiver(self)
self._set_state(self.State.CLOSED)
async def _abort(self) -> None:
"""
Abort the association.
"""
chunk = AbortChunk()
try:
await self._send_chunk(chunk)
except ConnectionError:
pass
async def _init(self) -> None:
"""
Initialize the association.
"""
chunk = InitChunk()
chunk.initiate_tag = self._local_verification_tag
chunk.advertised_rwnd = self._advertised_rwnd
chunk.outbound_streams = self._outbound_streams_count
chunk.inbound_streams = self._inbound_streams_max
chunk.initial_tsn = self._local_tsn
self._set_extensions(chunk.params)
await self._send_chunk(chunk)
# start T1 timer and enter COOKIE-WAIT state
self._t1_start(chunk)
self._set_state(self.State.COOKIE_WAIT)
def _flight_size_decrease(self, chunk: DataChunk) -> None:
self._flight_size = max(0, self._flight_size - chunk._book_size)
def _flight_size_increase(self, chunk: DataChunk) -> None:
self._flight_size += chunk._book_size
def _get_extensions(self, params: List[Tuple[int, bytes]]) -> None:
"""
Gets what extensions are supported by the remote party.
"""
for k, v in params:
if k == SCTP_PRSCTP_SUPPORTED:
self._remote_partial_reliability = True
elif k == SCTP_SUPPORTED_CHUNK_EXT:
self._remote_extensions = list(v)
def _set_extensions(self, params: List[Tuple[int, bytes]]) -> None:
"""
Sets what extensions are supported by the local party.
"""
extensions = []
if self._local_partial_reliability:
params.append((SCTP_PRSCTP_SUPPORTED, b""))
extensions.append(ForwardTsnChunk.type)
extensions.append(ReconfigChunk.type)
params.append((SCTP_SUPPORTED_CHUNK_EXT, bytes(extensions)))
def _get_inbound_stream(self, stream_id: int) -> InboundStream:
"""
Get or create the inbound stream with the specified ID.
"""
if stream_id not in self._inbound_streams:
self._inbound_streams[stream_id] = InboundStream()
return self._inbound_streams[stream_id]
def _get_timestamp(self) -> int:
return int(time.time())
async def _handle_data(self, data):
"""
Handle data received from the network.
"""
try:
_, _, verification_tag, chunks = parse_packet(data)
except ValueError:
return
# is this an init?
init_chunk = len([x for x in chunks if isinstance(x, InitChunk)])
if init_chunk:
assert len(chunks) == 1
expected_tag = 0
else:
expected_tag = self._local_verification_tag
# verify tag
if verification_tag != expected_tag:
self.__log_debug(
"Bad verification tag %d vs %d", verification_tag, expected_tag
)
return
# handle chunks
for chunk in chunks:
await self._receive_chunk(chunk)
# send SACK if needed
if self._sack_needed:
await self._send_sack()
def _maybe_abandon(self, chunk: DataChunk) -> bool:
"""
Determine if a chunk needs to be marked as abandoned.
If it does, it marks the chunk and any other chunk belong to the same
message as abandoned.
"""
if chunk._abandoned:
return True
abandon = (
chunk._max_retransmits is not None
and chunk._sent_count > chunk._max_retransmits
) or (chunk._expiry is not None and chunk._expiry < time.time())
if not abandon:
return False
chunk_pos = self._sent_queue.index(chunk)
for pos in range(chunk_pos, -1, -1):
ochunk = self._sent_queue[pos]
ochunk._abandoned = True
ochunk._retransmit = False
if ochunk.flags & SCTP_DATA_FIRST_FRAG:
break
for pos in range(chunk_pos, len(self._sent_queue)):
ochunk = self._sent_queue[pos]
ochunk._abandoned = True
ochunk._retransmit = False
if ochunk.flags & SCTP_DATA_LAST_FRAG:
break
return True
def _mark_received(self, tsn: int) -> bool:
"""
Mark an incoming data TSN as received.
"""
# it's a duplicate
if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered:
self._sack_duplicates.append(tsn)
return True
# consolidate misordered entries
self._sack_misordered.add(tsn)
for tsn in sorted(self._sack_misordered):
if tsn == tsn_plus_one(self._last_received_tsn):
self._last_received_tsn = tsn
else:
break
# filter out obsolete entries
def is_obsolete(x):
return uint32_gt(x, self._last_received_tsn)
self._sack_duplicates = list(filter(is_obsolete, self._sack_duplicates))
self._sack_misordered = set(filter(is_obsolete, self._sack_misordered))
return False
async def _receive(self, stream_id: int, pp_id: int, data: bytes) -> None:
"""
Receive data stream -> ULP.
"""
await self._data_channel_receive(stream_id, pp_id, data)
async def _receive_chunk(self, chunk):
"""
Handle an incoming chunk.
"""
self.__log_debug("< %s", chunk)
# common
if isinstance(chunk, DataChunk):
await self._receive_data_chunk(chunk)
elif isinstance(chunk, SackChunk):
await self._receive_sack_chunk(chunk)
elif isinstance(chunk, ForwardTsnChunk):
await self._receive_forward_tsn_chunk(chunk)
elif isinstance(chunk, HeartbeatChunk):
ack = HeartbeatAckChunk()
ack.params = chunk.params
await self._send_chunk(ack)
elif isinstance(chunk, AbortChunk):
self.__log_debug("x Association was aborted by remote party")
self._set_state(self.State.CLOSED)
elif isinstance(chunk, ShutdownChunk):
self._t2_cancel()
self._set_state(self.State.SHUTDOWN_RECEIVED)
ack = ShutdownAckChunk()
await self._send_chunk(ack)
self._t2_start(ack)
self._set_state(self.State.SHUTDOWN_ACK_SENT)
elif (
isinstance(chunk, ShutdownCompleteChunk)
and self._association_state == self.State.SHUTDOWN_ACK_SENT
):
self._t2_cancel()
self._set_state(self.State.CLOSED)
elif (
isinstance(chunk, ReconfigChunk)
and self._association_state == self.State.ESTABLISHED
):
for param in chunk.params:
cls = RECONFIG_PARAM_TYPES.get(param[0])
if cls:
await self._receive_reconfig_param(cls.parse(param[1]))
# server
elif isinstance(chunk, InitChunk) and self.is_server:
self._last_received_tsn = tsn_minus_one(chunk.initial_tsn)
self._reconfig_response_seq = tsn_minus_one(chunk.initial_tsn)
self._remote_verification_tag = chunk.initiate_tag
self._ssthresh = chunk.advertised_rwnd
self._get_extensions(chunk.params)
self.__log_debug(
"- Peer supports %d outbound streams, %d max inbound streams",
chunk.outbound_streams,
chunk.inbound_streams,
)
self._inbound_streams_count = min(
chunk.outbound_streams, self._inbound_streams_max
)
self._outbound_streams_count = min(
self._outbound_streams_count, chunk.inbound_streams
)
ack = InitAckChunk()
ack.initiate_tag = self._local_verification_tag
ack.advertised_rwnd = self._advertised_rwnd
ack.outbound_streams = self._outbound_streams_count
ack.inbound_streams = self._inbound_streams_max
ack.initial_tsn = self._local_tsn
self._set_extensions(ack.params)
# generate state cookie
cookie = pack("!L", self._get_timestamp())
cookie += hmac.new(self._hmac_key, cookie, "sha1").digest()
ack.params.append((SCTP_STATE_COOKIE, cookie))
await self._send_chunk(ack)
elif isinstance(chunk, CookieEchoChunk) and self.is_server:
# check state cookie MAC
cookie = chunk.body
if (
len(cookie) != COOKIE_LENGTH
or hmac.new(self._hmac_key, cookie[0:4], "sha1").digest() != cookie[4:]
):
self.__log_debug("x State cookie is invalid")
return
# check state cookie lifetime
now = self._get_timestamp()
stamp = unpack_from("!L", cookie)[0]
if stamp < now - COOKIE_LIFETIME or stamp > now:
self.__log_debug("x State cookie has expired")
error = ErrorChunk()
error.params.append((SCTP_CAUSE_STALE_COOKIE, b"\x00" * 8))
await self._send_chunk(error)
return