-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection_ff.py
3413 lines (3032 loc) · 127 KB
/
connection_ff.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 binascii
import logging
import os
from collections import deque
from dataclasses import dataclass
from enum import Enum
from functools import partial
from typing import (
Any,
Callable,
Deque,
Dict,
FrozenSet,
List,
Optional,
Sequence,
Set,
Tuple,
)
from .. import tls
from ..buffer import (
UINT_VAR_MAX,
UINT_VAR_MAX_SIZE,
Buffer,
BufferReadError,
size_uint_var,
)
from . import events
from .configuration import SMALLEST_MAX_DATAGRAM_SIZE, QuicConfiguration
from .congestion.base import K_GRANULARITY
from .crypto import CryptoError, CryptoPair, KeyUnavailableError
from .logger import QuicLoggerTrace
from .packet import (
CONNECTION_ID_MAX_SIZE,
NON_ACK_ELICITING_FRAME_TYPES,
PACKET_TYPE_HANDSHAKE,
PACKET_TYPE_INITIAL,
PACKET_TYPE_ONE_RTT,
PACKET_TYPE_RETRY,
PACKET_TYPE_ZERO_RTT,
PROBING_FRAME_TYPES,
RETRY_INTEGRITY_TAG_SIZE,
STATELESS_RESET_TOKEN_SIZE,
QuicErrorCode,
QuicFrameType,
QuicProtocolVersion,
QuicStreamFrame,
QuicTransportParameters,
get_retry_integrity_tag,
get_spin_bit,
is_draft_version,
is_long_header,
pull_ack_frame,
pull_quic_header,
pull_quic_transport_parameters,
push_ack_frame,
push_quic_transport_parameters,
)
from .packet_builder import (
QuicDeliveryState,
QuicPacketBuilder,
QuicPacketBuilderStop,
)
from .recovery import QuicPacketRecovery, QuicPacketSpace
from .stream import FinalSizeError, QuicStream, StreamFinishedError
logger = logging.getLogger("quic")
CRYPTO_BUFFER_SIZE = 16384
EPOCH_SHORTCUTS = {
"I": tls.Epoch.INITIAL,
"H": tls.Epoch.HANDSHAKE,
"0": tls.Epoch.ZERO_RTT,
"1": tls.Epoch.ONE_RTT,
}
MAX_EARLY_DATA = 0xFFFFFFFF
SECRETS_LABELS = [
[
None,
"CLIENT_EARLY_TRAFFIC_SECRET",
"CLIENT_HANDSHAKE_TRAFFIC_SECRET",
"CLIENT_TRAFFIC_SECRET_0",
],
[
None,
None,
"SERVER_HANDSHAKE_TRAFFIC_SECRET",
"SERVER_TRAFFIC_SECRET_0",
],
]
STREAM_FLAGS = 0x07
STREAM_COUNT_MAX = 0x1000000000000000
UDP_HEADER_SIZE = 8
MAX_PENDING_RETIRES = 100
NetworkAddress = Any
# frame sizes
ACK_FRAME_CAPACITY = 64 # FIXME: this is arbitrary!
APPLICATION_CLOSE_FRAME_CAPACITY = 1 + 2 * UINT_VAR_MAX_SIZE # + reason length
CONNECTION_LIMIT_FRAME_CAPACITY = 1 + UINT_VAR_MAX_SIZE
HANDSHAKE_DONE_FRAME_CAPACITY = 1
MAX_STREAM_DATA_FRAME_CAPACITY = 1 + 2 * UINT_VAR_MAX_SIZE
NEW_CONNECTION_ID_FRAME_CAPACITY = (
1 + 2 * UINT_VAR_MAX_SIZE + 1 + CONNECTION_ID_MAX_SIZE + STATELESS_RESET_TOKEN_SIZE
)
PATH_CHALLENGE_FRAME_CAPACITY = 1 + 8
PATH_RESPONSE_FRAME_CAPACITY = 1 + 8
PING_FRAME_CAPACITY = 1
RESET_STREAM_FRAME_CAPACITY = 1 + 3 * UINT_VAR_MAX_SIZE
RETIRE_CONNECTION_ID_CAPACITY = 1 + UINT_VAR_MAX_SIZE
STOP_SENDING_FRAME_CAPACITY = 1 + 2 * UINT_VAR_MAX_SIZE
STREAMS_BLOCKED_CAPACITY = 1 + UINT_VAR_MAX_SIZE
TRANSPORT_CLOSE_FRAME_CAPACITY = 1 + 3 * UINT_VAR_MAX_SIZE # + reason length
def EPOCHS(shortcut: str) -> FrozenSet[tls.Epoch]:
return frozenset(EPOCH_SHORTCUTS[i] for i in shortcut)
def dump_cid(cid: bytes) -> str:
return binascii.hexlify(cid).decode("ascii")
def get_epoch(packet_type: int) -> tls.Epoch:
if packet_type == PACKET_TYPE_INITIAL:
return tls.Epoch.INITIAL
elif packet_type == PACKET_TYPE_ZERO_RTT:
return tls.Epoch.ZERO_RTT
elif packet_type == PACKET_TYPE_HANDSHAKE:
return tls.Epoch.HANDSHAKE
else:
return tls.Epoch.ONE_RTT
def get_transport_parameters_extension(version: int) -> tls.ExtensionType:
if is_draft_version(version):
return tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS_DRAFT
else:
return tls.ExtensionType.QUIC_TRANSPORT_PARAMETERS
def stream_is_client_initiated(stream_id: int) -> bool:
"""
Returns True if the stream is client initiated.
"""
return not (stream_id & 1)
def stream_is_unidirectional(stream_id: int) -> bool:
"""
Returns True if the stream is unidirectional.
"""
return bool(stream_id & 2)
class Limit:
def __init__(self, frame_type: int, name: str, value: int):
self.frame_type = frame_type
self.name = name
self.sent = value
self.used = 0
self.value = value
class QuicConnectionError(Exception):
def __init__(self, error_code: int, frame_type: int, reason_phrase: str):
self.error_code = error_code
self.frame_type = frame_type
self.reason_phrase = reason_phrase
def __str__(self) -> str:
s = "Error: %d, reason: %s" % (self.error_code, self.reason_phrase)
if self.frame_type is not None:
s += ", frame_type: %s" % self.frame_type
return s
class QuicConnectionAdapter(logging.LoggerAdapter):
def process(self, msg: str, kwargs: Any) -> Tuple[str, Any]:
return "[%s] %s" % (self.extra["id"], msg), kwargs
@dataclass
class QuicConnectionId:
cid: bytes
sequence_number: int
stateless_reset_token: bytes = b""
was_sent: bool = False
class QuicConnectionState(Enum):
FIRSTFLIGHT = 0
CONNECTED = 1
CLOSING = 2
DRAINING = 3
TERMINATED = 4
@dataclass
class QuicNetworkPath:
addr: NetworkAddress
bytes_received: int = 0
bytes_sent: int = 0
is_validated: bool = False
local_challenge: Optional[bytes] = None
remote_challenge: Optional[bytes] = None
def can_send(self, size: int) -> bool:
return self.is_validated or (self.bytes_sent + size) <= 3 * self.bytes_received
@dataclass
class QuicReceiveContext:
epoch: tls.Epoch
host_cid: bytes
network_path: QuicNetworkPath
quic_logger_frames: Optional[List[Any]]
time: float
QuicTokenHandler = Callable[[bytes], None]
END_STATES = frozenset(
[
QuicConnectionState.CLOSING,
QuicConnectionState.DRAINING,
QuicConnectionState.TERMINATED,
]
)
class QuicConnection:
"""
A QUIC connection.
The state machine is driven by three kinds of sources:
- the API user requesting data to be send out (see :meth:`connect`,
:meth:`reset_stream`, :meth:`send_ping`, :meth:`send_datagram_frame`
and :meth:`send_stream_data`)
- data being received from the network (see :meth:`receive_datagram`)
- a timer firing (see :meth:`handle_timer`)
:param configuration: The QUIC configuration to use.
"""
def __init__(
self,
*,
configuration: QuicConfiguration,
original_destination_connection_id: Optional[bytes] = None,
retry_source_connection_id: Optional[bytes] = None,
session_ticket_fetcher: Optional[tls.SessionTicketFetcher] = None,
session_ticket_handler: Optional[tls.SessionTicketHandler] = None,
token_handler: Optional[QuicTokenHandler] = None,
) -> None:
assert configuration.max_datagram_size >= SMALLEST_MAX_DATAGRAM_SIZE, (
"The smallest allowed maximum datagram size is "
f"{SMALLEST_MAX_DATAGRAM_SIZE} bytes"
)
if configuration.is_client:
assert (
original_destination_connection_id is None
), "Cannot set original_destination_connection_id for a client"
assert (
retry_source_connection_id is None
), "Cannot set retry_source_connection_id for a client"
else:
assert token_handler is None, "Cannot set `token_handler` for a server"
assert (
configuration.token == b""
), "Cannot set `configuration.token` for a server"
assert (
configuration.certificate is not None
), "SSL certificate is required for a server"
assert (
configuration.private_key is not None
), "SSL private key is required for a server"
assert (
original_destination_connection_id is not None
), "original_destination_connection_id is required for a server"
# configuration
self._configuration = configuration
self._is_client = configuration.is_client
self._ack_delay = K_GRANULARITY
self._close_at: Optional[float] = None
self._close_event: Optional[events.ConnectionTerminated] = None
self._connect_called = False
self._cryptos: Dict[tls.Epoch, CryptoPair] = {}
self._crypto_buffers: Dict[tls.Epoch, Buffer] = {}
self._crypto_retransmitted = False
self._crypto_streams: Dict[tls.Epoch, QuicStream] = {}
self._events: Deque[events.QuicEvent] = deque()
self._handshake_complete = False
self._handshake_confirmed = False
self._host_cids = [
QuicConnectionId(
cid=os.urandom(configuration.connection_id_length),
sequence_number=0,
stateless_reset_token=os.urandom(16) if not self._is_client else None,
was_sent=True,
)
]
self.host_cid = self._host_cids[0].cid
self._host_cid_seq = 1
self._local_ack_delay_exponent = 3
self._local_active_connection_id_limit = 8
self._local_initial_source_connection_id = self._host_cids[0].cid
self._local_max_data = Limit(
frame_type=QuicFrameType.MAX_DATA,
name="max_data",
value=configuration.max_data,
)
self._local_max_stream_data_bidi_local = configuration.max_stream_data
self._local_max_stream_data_bidi_remote = configuration.max_stream_data
self._local_max_stream_data_uni = configuration.max_stream_data
self._local_max_streams_bidi = Limit(
frame_type=QuicFrameType.MAX_STREAMS_BIDI,
name="max_streams_bidi",
value=128,
)
self._local_max_streams_uni = Limit(
frame_type=QuicFrameType.MAX_STREAMS_UNI, name="max_streams_uni", value=128
)
self._local_next_stream_id_bidi = 0 if self._is_client else 1
self._local_next_stream_id_uni = 2 if self._is_client else 3
self._loss_at: Optional[float] = None
self._max_datagram_size = configuration.max_datagram_size
self._network_paths: List[QuicNetworkPath] = []
self._pacing_at: Optional[float] = None
self._packet_number = 0
self._parameters_received = False
self._peer_cid = QuicConnectionId(
# cid=os.urandom(configuration.connection_id_length), sequence_number=None
cid=binascii.unhexlify("0011223344556677"), sequence_number=None # sending values in first flight
)
self._peer_cid_available: List[QuicConnectionId] = []
self._peer_cid_sequence_numbers: Set[int] = set([0])
self._peer_retire_prior_to = 0
self._peer_token = configuration.token
self._quic_logger: Optional[QuicLoggerTrace] = None
self._remote_ack_delay_exponent = 3
self._remote_active_connection_id_limit = 2
self._remote_initial_source_connection_id: Optional[bytes] = None
self._remote_max_idle_timeout: Optional[float] = None # seconds
self._remote_max_data = 0
self._remote_max_data_used = 0
self._remote_max_datagram_frame_size: Optional[int] = None
self._remote_max_stream_data_bidi_local = 0
self._remote_max_stream_data_bidi_remote = 0
self._remote_max_stream_data_uni = 0
self._remote_max_streams_bidi = 0
self._remote_max_streams_uni = 0
self._retry_count = 0
self._retry_source_connection_id = retry_source_connection_id
self._spaces: Dict[tls.Epoch, QuicPacketSpace] = {}
self._spin_bit = False
self._spin_highest_pn = 0
self._state = QuicConnectionState.FIRSTFLIGHT
self._streams: Dict[int, QuicStream] = {}
self._streams_queue: List[QuicStream] = []
self._streams_blocked_bidi: List[QuicStream] = []
self._streams_blocked_uni: List[QuicStream] = []
self._streams_finished: Set[int] = set()
self._version: Optional[int] = None
self._version_negotiation_count = 0
if self._is_client:
self._original_destination_connection_id = self._peer_cid.cid
else:
self._original_destination_connection_id = (
original_destination_connection_id
)
# logging
self._logger = QuicConnectionAdapter(
logger, {"id": dump_cid(self._original_destination_connection_id)}
)
if configuration.quic_logger:
self._quic_logger = configuration.quic_logger.start_trace(
is_client=configuration.is_client,
odcid=self._original_destination_connection_id,
)
# loss recovery
self._loss = QuicPacketRecovery(
congestion_control_algorithm=configuration.congestion_control_algorithm,
initial_rtt=configuration.initial_rtt,
max_datagram_size=self._max_datagram_size,
peer_completed_address_validation=not self._is_client,
quic_logger=self._quic_logger,
send_probe=self._send_probe,
logger=self._logger,
)
# things to send
self._close_pending = False
self._datagrams_pending: Deque[bytes] = deque()
self._handshake_done_pending = False
self._ping_pending: List[int] = []
self._probe_pending = False
self._retire_connection_ids: List[int] = []
self._streams_blocked_pending = False
# callbacks
self._session_ticket_fetcher = session_ticket_fetcher
self._session_ticket_handler = session_ticket_handler
self._token_handler = token_handler
# frame handlers
self.__frame_handlers = {
0x00: (self._handle_padding_frame, EPOCHS("IH01")),
0x01: (self._handle_ping_frame, EPOCHS("IH01")),
0x02: (self._handle_ack_frame, EPOCHS("IH1")),
0x03: (self._handle_ack_frame, EPOCHS("IH1")),
0x04: (self._handle_reset_stream_frame, EPOCHS("01")),
0x05: (self._handle_stop_sending_frame, EPOCHS("01")),
0x06: (self._handle_crypto_frame, EPOCHS("IH1")),
0x07: (self._handle_new_token_frame, EPOCHS("1")),
0x08: (self._handle_stream_frame, EPOCHS("01")),
0x09: (self._handle_stream_frame, EPOCHS("01")),
0x0A: (self._handle_stream_frame, EPOCHS("01")),
0x0B: (self._handle_stream_frame, EPOCHS("01")),
0x0C: (self._handle_stream_frame, EPOCHS("01")),
0x0D: (self._handle_stream_frame, EPOCHS("01")),
0x0E: (self._handle_stream_frame, EPOCHS("01")),
0x0F: (self._handle_stream_frame, EPOCHS("01")),
0x10: (self._handle_max_data_frame, EPOCHS("01")),
0x11: (self._handle_max_stream_data_frame, EPOCHS("01")),
0x12: (self._handle_max_streams_bidi_frame, EPOCHS("01")),
0x13: (self._handle_max_streams_uni_frame, EPOCHS("01")),
0x14: (self._handle_data_blocked_frame, EPOCHS("01")),
0x15: (self._handle_stream_data_blocked_frame, EPOCHS("01")),
0x16: (self._handle_streams_blocked_frame, EPOCHS("01")),
0x17: (self._handle_streams_blocked_frame, EPOCHS("01")),
0x18: (self._handle_new_connection_id_frame, EPOCHS("01")),
0x19: (self._handle_retire_connection_id_frame, EPOCHS("01")),
0x1A: (self._handle_path_challenge_frame, EPOCHS("01")),
0x1B: (self._handle_path_response_frame, EPOCHS("01")),
0x1C: (self._handle_connection_close_frame, EPOCHS("IH01")),
0x1D: (self._handle_connection_close_frame, EPOCHS("01")),
0x1E: (self._handle_handshake_done_frame, EPOCHS("1")),
0x30: (self._handle_datagram_frame, EPOCHS("01")),
0x31: (self._handle_datagram_frame, EPOCHS("01")),
}
@property
def configuration(self) -> QuicConfiguration:
return self._configuration
@property
def original_destination_connection_id(self) -> bytes:
print(self._original_destination_connection_id)
return self._original_destination_connection_id
def change_connection_id(self) -> None:
"""
Switch to the next available connection ID and retire
the previous one.
.. aioquic_transmit::
"""
if self._peer_cid_available:
# retire previous CID
self._retire_peer_cid(self._peer_cid)
# assign new CID
self._consume_peer_cid()
def close(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: Optional[int] = None,
reason_phrase: str = "",
) -> None:
"""
Close the connection.
.. aioquic_transmit::
:param error_code: An error code indicating why the connection is
being closed.
:param reason_phrase: A human-readable explanation of why the
connection is being closed.
"""
if self._close_event is None and self._state not in END_STATES:
self._close_event = events.ConnectionTerminated(
error_code=error_code,
frame_type=frame_type,
reason_phrase=reason_phrase,
)
self._close_pending = True
def connect(self, addr: NetworkAddress, now: float) -> None:
"""
Initiate the TLS handshake.
This method can only be called for clients and a single time.
.. aioquic_transmit::
:param addr: The network address of the remote peer.
:param now: The current time.
"""
assert (
self._is_client and not self._connect_called
), "connect() can only be called for clients and a single time"
self._connect_called = True
self._network_paths = [QuicNetworkPath(addr, is_validated=True)]
self._version = self._configuration.supported_versions[0]
self._connect(now=now)
def datagrams_to_send(self, now: float) -> List[Tuple[bytes, NetworkAddress]]:
"""
Return a list of `(data, addr)` tuples of datagrams which need to be
sent, and the network address to which they need to be sent.
After calling this method call :meth:`get_timer` to know when the next
timer needs to be set.
:param now: The current time.
"""
network_path = self._network_paths[0]
if self._state in END_STATES:
return []
# build datagrams
builder = QuicPacketBuilder(
host_cid=self.host_cid,
is_client=self._is_client,
max_datagram_size=self._max_datagram_size,
packet_number=self._packet_number,
peer_cid=self._peer_cid.cid,
peer_token=self._peer_token,
quic_logger=self._quic_logger,
spin_bit=self._spin_bit,
version=self._version,
)
if self._close_pending:
epoch_packet_types = []
if not self._handshake_confirmed:
epoch_packet_types += [
(tls.Epoch.INITIAL, PACKET_TYPE_INITIAL),
(tls.Epoch.HANDSHAKE, PACKET_TYPE_HANDSHAKE),
]
epoch_packet_types.append((tls.Epoch.ONE_RTT, PACKET_TYPE_ONE_RTT))
for epoch, packet_type in epoch_packet_types:
crypto = self._cryptos[epoch]
if crypto.send.is_valid():
builder.start_packet(packet_type, crypto)
self._write_connection_close_frame(
builder=builder,
epoch=epoch,
error_code=self._close_event.error_code,
frame_type=self._close_event.frame_type,
reason_phrase=self._close_event.reason_phrase,
)
self._logger.info(
"Connection close sent (code 0x%X, reason %s)",
self._close_event.error_code,
self._close_event.reason_phrase,
)
self._close_pending = False
self._close_begin(is_initiator=True, now=now)
else:
# congestion control
builder.max_flight_bytes = (
self._loss.congestion_window - self._loss.bytes_in_flight
)
if (
self._probe_pending
and builder.max_flight_bytes < self._max_datagram_size
):
builder.max_flight_bytes = self._max_datagram_size
# limit data on un-validated network paths
if not network_path.is_validated:
builder.max_total_bytes = (
network_path.bytes_received * 3 - network_path.bytes_sent
)
try:
if not self._handshake_confirmed:
for epoch in [tls.Epoch.INITIAL, tls.Epoch.HANDSHAKE]:
self._write_handshake(builder, epoch, now)
self._write_application(builder, network_path, now)
except QuicPacketBuilderStop:
pass
datagrams, packets = builder.flush()
if datagrams:
self._packet_number = builder.packet_number
# register packets
sent_handshake = False
for packet in packets:
packet.sent_time = now
self._loss.on_packet_sent(
packet=packet, space=self._spaces[packet.epoch]
)
if packet.epoch == tls.Epoch.HANDSHAKE:
sent_handshake = True
# log packet
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_sent",
data={
"frames": packet.quic_logger_frames,
"header": {
"packet_number": packet.packet_number,
"packet_type": self._quic_logger.packet_type(
packet.packet_type
),
"scid": (
dump_cid(self.host_cid)
if is_long_header(packet.packet_type)
else ""
),
"dcid": dump_cid(self._peer_cid.cid),
},
"raw": {"length": packet.sent_bytes},
},
)
# check if we can discard initial keys
if sent_handshake and self._is_client:
self._discard_epoch(tls.Epoch.INITIAL)
# return datagrams to send and the destination network address
ret = []
for datagram in datagrams:
payload_length = len(datagram)
network_path.bytes_sent += payload_length
ret.append((datagram, network_path.addr))
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="datagrams_sent",
data={
"count": 1,
"raw": [
{
"length": UDP_HEADER_SIZE + payload_length,
"payload_length": payload_length,
}
],
},
)
return ret
def get_next_available_stream_id(self, is_unidirectional=False) -> int:
"""
Return the stream ID for the next stream created by this endpoint.
"""
if is_unidirectional:
return self._local_next_stream_id_uni
else:
return self._local_next_stream_id_bidi
def get_timer(self) -> Optional[float]:
"""
Return the time at which the timer should fire or None if no timer is needed.
"""
timer_at = self._close_at
if self._state not in END_STATES:
# ack timer
for space in self._loss.spaces:
if space.ack_at is not None and space.ack_at < timer_at:
timer_at = space.ack_at
# loss detection timer
self._loss_at = self._loss.get_loss_detection_time()
if self._loss_at is not None and self._loss_at < timer_at:
timer_at = self._loss_at
# pacing timer
if self._pacing_at is not None and self._pacing_at < timer_at:
timer_at = self._pacing_at
return timer_at
def handle_timer(self, now: float) -> None:
"""
Handle the timer.
.. aioquic_transmit::
:param now: The current time.
"""
# end of closing period or idle timeout
if now >= self._close_at:
if self._close_event is None:
self._close_event = events.ConnectionTerminated(
error_code=QuicErrorCode.INTERNAL_ERROR,
frame_type=QuicFrameType.PADDING,
reason_phrase="Idle timeout",
)
self._close_end()
return
# loss detection timeout
if self._loss_at is not None and now >= self._loss_at:
self._logger.debug("Loss detection triggered")
self._loss.on_loss_detection_timeout(now=now)
def next_event(self) -> Optional[events.QuicEvent]:
"""
Retrieve the next event from the event buffer.
Returns `None` if there are no buffered events.
"""
try:
return self._events.popleft()
except IndexError:
return None
def _idle_timeout(self) -> float:
# RFC 9000 section 10.1
# Start with our local timeout.
idle_timeout = self._configuration.idle_timeout
if self._remote_max_idle_timeout is not None:
# Our peer has a preference too, so pick the smaller timeout.
idle_timeout = min(idle_timeout, self._remote_max_idle_timeout)
# But not too small!
return max(idle_timeout, 3 * self._loss.get_probe_timeout())
def receive_datagram(self, data: bytes, addr: NetworkAddress, now: float) -> None:
"""
Handle an incoming datagram.
.. aioquic_transmit::
:param data: The datagram which was received.
:param addr: The network address from which the datagram was received.
:param now: The current time.
"""
# stop handling packets when closing
if self._state in END_STATES:
return
# log datagram
if self._quic_logger is not None:
payload_length = len(data)
self._quic_logger.log_event(
category="transport",
event="datagrams_received",
data={
"count": 1,
"raw": [
{
"length": UDP_HEADER_SIZE + payload_length,
"payload_length": payload_length,
}
],
},
)
# for servers, arm the idle timeout on the first datagram
if self._close_at is None:
self._close_at = now + self._idle_timeout()
buf = Buffer(data=data)
while not buf.eof():
start_off = buf.tell()
try:
header = pull_quic_header(
buf, host_cid_length=self._configuration.connection_id_length
)
except ValueError:
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "header_parse_error",
"raw": {"length": buf.capacity - start_off},
},
)
return
# RFC 9000 section 14.1 requires servers to drop all initial packets
# contained in a datagram smaller than 1200 bytes.
if (
not self._is_client
and header.packet_type == PACKET_TYPE_INITIAL
and len(data) < SMALLEST_MAX_DATAGRAM_SIZE
):
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={
"trigger": "initial_packet_datagram_too_small",
"raw": {"length": buf.capacity - start_off},
},
)
return
# check destination CID matches
destination_cid_seq: Optional[int] = None
for connection_id in self._host_cids:
if header.destination_cid == connection_id.cid:
destination_cid_seq = connection_id.sequence_number
break
if (
self._is_client or header.packet_type == PACKET_TYPE_HANDSHAKE
) and destination_cid_seq is None:
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={"trigger": "unknown_connection_id"},
)
return
# check protocol version
if (
self._is_client
and self._state == QuicConnectionState.FIRSTFLIGHT
and header.version == QuicProtocolVersion.NEGOTIATION
and not self._version_negotiation_count
):
# version negotiation
versions = []
while not buf.eof():
versions.append(buf.pull_uint32())
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_received",
data={
"frames": [],
"header": {
"packet_type": "version_negotiation",
"scid": dump_cid(header.source_cid),
"dcid": dump_cid(header.destination_cid),
},
"raw": {"length": buf.tell() - start_off},
},
)
if self._version in versions:
self._logger.warning(
"Version negotiation packet contains %s" % self._version
)
return
common = [
x for x in self._configuration.supported_versions if x in versions
]
chosen_version = common[0] if common else None
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="version_information",
data={
"server_versions": versions,
"client_versions": self._configuration.supported_versions,
"chosen_version": chosen_version,
},
)
if chosen_version is None:
self._logger.error("Could not find a common protocol version")
self._close_event = events.ConnectionTerminated(
error_code=QuicErrorCode.INTERNAL_ERROR,
frame_type=QuicFrameType.PADDING,
reason_phrase="Could not find a common protocol version",
)
self._close_end()
return
self._packet_number = 0
self._version = QuicProtocolVersion(chosen_version)
self._version_negotiation_count += 1
self._logger.info("Retrying with %s", self._version)
self._connect(now=now)
return
elif (
header.version is not None
and header.version not in self._configuration.supported_versions
):
# unsupported version
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={"trigger": "unsupported_version"},
)
return
# handle retry packet
if header.packet_type == PACKET_TYPE_RETRY:
if (
self._is_client
and not self._retry_count
and header.destination_cid == self.host_cid
and header.integrity_tag
== get_retry_integrity_tag(
buf.data_slice(
start_off, buf.tell() - RETRY_INTEGRITY_TAG_SIZE
),
self._peer_cid.cid,
version=header.version,
)
):
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_received",
data={
"frames": [],
"header": {
"packet_type": "retry",
"scid": dump_cid(header.source_cid),
"dcid": dump_cid(header.destination_cid),
},
"raw": {"length": buf.tell() - start_off},
},
)
self._peer_cid.cid = header.source_cid
self._peer_token = header.token
self._retry_count += 1
self._retry_source_connection_id = header.source_cid
self._logger.info(
"Retrying with token (%d bytes)" % len(header.token)
)
self._connect(now=now)
else:
# unexpected or invalid retry packet
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={"trigger": "unexpected_packet"},
)
return
crypto_frame_required = False
network_path = self._find_network_path(addr)
# server initialization
if not self._is_client and self._state == QuicConnectionState.FIRSTFLIGHT:
assert (
header.packet_type == PACKET_TYPE_INITIAL
), "first packet must be INITIAL"
crypto_frame_required = True
self._network_paths = [network_path]
self._version = QuicProtocolVersion(header.version)
self._initialize(header.destination_cid)
# determine crypto and packet space
epoch = get_epoch(header.packet_type)
crypto = self._cryptos[epoch]
if epoch == tls.Epoch.ZERO_RTT:
space = self._spaces[tls.Epoch.ONE_RTT]
else:
space = self._spaces[epoch]
# decrypt packet
encrypted_off = buf.tell() - start_off
end_off = buf.tell() + header.rest_length
buf.seek(end_off)
try:
plain_header, plain_payload, packet_number = crypto.decrypt_packet(
data[start_off:end_off], encrypted_off, space.expected_packet_number
)
except KeyUnavailableError as exc:
self._logger.debug(exc)
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",
event="packet_dropped",
data={"trigger": "key_unavailable"},
)
# If a client receives HANDSHAKE or 1-RTT packets before it has
# handshake keys, it can assume that the server's INITIAL was lost.
if (
self._is_client
and epoch in (tls.Epoch.HANDSHAKE, tls.Epoch.ONE_RTT)
and not self._crypto_retransmitted
):
self._loss.reschedule_data(now=now)
self._crypto_retransmitted = True
continue
except CryptoError as exc:
self._logger.debug(exc)
if self._quic_logger is not None:
self._quic_logger.log_event(
category="transport",