-
Notifications
You must be signed in to change notification settings - Fork 124
/
mod.rs
3291 lines (3023 loc) · 123 KB
/
mod.rs
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
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// The class implementing a QUIC connection.
use std::{
cell::RefCell,
cmp::{max, min},
fmt::{self, Debug},
iter, mem,
net::{IpAddr, SocketAddr},
ops::RangeInclusive,
rc::{Rc, Weak},
time::{Duration, Instant},
};
use neqo_common::{
event::Provider as EventProvider, hex, hex_snip_middle, hrtime, qdebug, qerror, qinfo,
qlog::NeqoQlog, qtrace, qwarn, Datagram, Decoder, Encoder, IpTos, Role,
};
use neqo_crypto::{
agent::CertificateInfo, Agent, AntiReplay, AuthenticationStatus, Cipher, Client, Group,
HandshakeState, PrivateKey, PublicKey, ResumptionToken, SecretAgentInfo, SecretAgentPreInfo,
Server, ZeroRttChecker,
};
use smallvec::SmallVec;
use crate::{
addr_valid::{AddressValidation, NewTokenState},
cid::{
ConnectionId, ConnectionIdEntry, ConnectionIdGenerator, ConnectionIdManager,
ConnectionIdRef, ConnectionIdStore, LOCAL_ACTIVE_CID_LIMIT,
},
crypto::{Crypto, CryptoDxState, CryptoSpace},
events::{ConnectionEvent, ConnectionEvents, OutgoingDatagramOutcome},
frame::{
CloseError, Frame, FrameType, FRAME_TYPE_CONNECTION_CLOSE_APPLICATION,
FRAME_TYPE_CONNECTION_CLOSE_TRANSPORT,
},
packet::{DecryptedPacket, PacketBuilder, PacketNumber, PacketType, PublicPacket},
path::{Path, PathRef, Paths},
qlog,
quic_datagrams::{DatagramTracking, QuicDatagrams},
recovery::{LossRecovery, RecoveryToken, SendProfile},
recv_stream::RecvStreamStats,
rtt::GRANULARITY,
send_stream::SendStream,
stats::{Stats, StatsCell},
stream_id::StreamType,
streams::{SendOrder, Streams},
tparams::{
self, TransportParameter, TransportParameterId, TransportParameters,
TransportParametersHandler,
},
tracking::{AckTracker, PacketNumberSpace, SentPacket},
version::{Version, WireVersion},
AppError, ConnectionError, Error, Res, StreamId,
};
mod dump;
mod idle;
pub mod params;
mod saved;
mod state;
#[cfg(test)]
pub mod test_internal;
use dump::dump_packet;
use idle::IdleTimeout;
pub use params::ConnectionParameters;
use params::PreferredAddressConfig;
#[cfg(test)]
pub use params::ACK_RATIO_SCALE;
use saved::SavedDatagrams;
use state::StateSignaling;
pub use state::{ClosingFrame, State};
pub use crate::send_stream::{RetransmissionPriority, SendStreamStats, TransmissionPriority};
/// The number of Initial packets that the client will send in response
/// to receiving an undecryptable packet during the early part of the
/// handshake. This is a hack, but a useful one.
const EXTRA_INITIALS: usize = 4;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ZeroRttState {
Init,
Sending,
AcceptedClient,
AcceptedServer,
Rejected,
}
#[derive(Clone, Debug, PartialEq, Eq)]
/// Type returned from `process()` and `process_output()`. Users are required to
/// call these repeatedly until `Callback` or `None` is returned.
pub enum Output {
/// Connection requires no action.
None,
/// Connection requires the datagram be sent.
Datagram(Datagram),
/// Connection requires `process_input()` be called when the `Duration`
/// elapses.
Callback(Duration),
}
impl Output {
/// Convert into an `Option<Datagram>`.
#[must_use]
pub fn dgram(self) -> Option<Datagram> {
match self {
Self::Datagram(dg) => Some(dg),
_ => None,
}
}
/// Get a reference to the Datagram, if any.
#[must_use]
pub fn as_dgram_ref(&self) -> Option<&Datagram> {
match self {
Self::Datagram(dg) => Some(dg),
_ => None,
}
}
/// Ask how long the caller should wait before calling back.
#[must_use]
pub fn callback(&self) -> Duration {
match self {
Self::Callback(t) => *t,
_ => Duration::new(0, 0),
}
}
}
/// Used by inner functions like `Connection::output`.
enum SendOption {
/// Yes, please send this datagram.
Yes(Datagram),
/// Don't send. If this was blocked on the pacer (the arg is true).
No(bool),
}
impl Default for SendOption {
fn default() -> Self {
Self::No(false)
}
}
/// Used by `Connection::preprocess` to determine what to do
/// with an packet before attempting to remove protection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PreprocessResult {
/// End processing and return successfully.
End,
/// Stop processing this datagram and move on to the next.
Next,
/// Continue and process this packet.
Continue,
}
/// `AddressValidationInfo` holds information relevant to either
/// responding to address validation (`NewToken`, `Retry`) or generating
/// tokens for address validation (`Server`).
enum AddressValidationInfo {
None,
// We are a client and have information from `NEW_TOKEN`.
NewToken(Vec<u8>),
// We are a client and have received a `Retry` packet.
Retry {
token: Vec<u8>,
retry_source_cid: ConnectionId,
},
// We are a server and can generate tokens.
Server(Weak<RefCell<AddressValidation>>),
}
impl AddressValidationInfo {
pub fn token(&self) -> &[u8] {
match self {
Self::NewToken(token) | Self::Retry { token, .. } => token,
_ => &[],
}
}
pub fn generate_new_token(
&mut self,
peer_address: SocketAddr,
now: Instant,
) -> Option<Vec<u8>> {
match self {
Self::Server(ref w) => {
if let Some(validation) = w.upgrade() {
validation
.borrow()
.generate_new_token(peer_address, now)
.ok()
} else {
None
}
}
Self::None => None,
_ => unreachable!("called a server function on a client"),
}
}
}
/// A QUIC Connection
///
/// First, create a new connection using `new_client()` or `new_server()`.
///
/// For the life of the connection, handle activity in the following manner:
/// 1. Perform operations using the `stream_*()` methods.
/// 1. Call `process_input()` when a datagram is received or the timer
/// expires. Obtain information on connection state changes by checking
/// `events()`.
/// 1. Having completed handling current activity, repeatedly call
/// `process_output()` for packets to send, until it returns `Output::Callback`
/// or `Output::None`.
///
/// After the connection is closed (either by calling `close()` or by the
/// remote) continue processing until `state()` returns `Closed`.
pub struct Connection {
role: Role,
version: Version,
state: State,
tps: Rc<RefCell<TransportParametersHandler>>,
/// What we are doing with 0-RTT.
zero_rtt_state: ZeroRttState,
/// All of the network paths that we are aware of.
paths: Paths,
/// This object will generate connection IDs for the connection.
cid_manager: ConnectionIdManager,
address_validation: AddressValidationInfo,
/// The connection IDs that were provided by the peer.
connection_ids: ConnectionIdStore<[u8; 16]>,
/// The source connection ID that this endpoint uses for the handshake.
/// Since we need to communicate this to our peer in tparams, setting this
/// value is part of constructing the struct.
local_initial_source_cid: ConnectionId,
/// The source connection ID from the first packet from the other end.
/// This is checked against the peer's transport parameters.
remote_initial_source_cid: Option<ConnectionId>,
/// The destination connection ID from the first packet from the client.
/// This is checked by the client against the server's transport parameters.
original_destination_cid: Option<ConnectionId>,
/// We sometimes save a datagram against the possibility that keys will later
/// become available. This avoids reporting packets as dropped during the handshake
/// when they are either just reordered or we haven't been able to install keys yet.
/// In particular, this occurs when asynchronous certificate validation happens.
saved_datagrams: SavedDatagrams,
/// Some packets were received, but not tracked.
received_untracked: bool,
/// This is responsible for the `QuicDatagrams`' handling:
/// <https://datatracker.ietf.org/doc/html/draft-ietf-quic-datagram>
quic_datagrams: QuicDatagrams,
pub(crate) crypto: Crypto,
pub(crate) acks: AckTracker,
idle_timeout: IdleTimeout,
streams: Streams,
state_signaling: StateSignaling,
loss_recovery: LossRecovery,
events: ConnectionEvents,
new_token: NewTokenState,
stats: StatsCell,
qlog: NeqoQlog,
/// A session ticket was received without `NEW_TOKEN`,
/// this is when that turns into an event without `NEW_TOKEN`.
release_resumption_token_timer: Option<Instant>,
conn_params: ConnectionParameters,
hrtime: hrtime::Handle,
/// For testing purposes it is sometimes necessary to inject frames that wouldn't
/// otherwise be sent, just to see how a connection handles them. Inserting them
/// into packets proper mean that the frames follow the entire processing path.
#[cfg(test)]
pub test_frame_writer: Option<Box<dyn test_internal::FrameWriter>>,
}
impl Debug for Connection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{:?} Connection: {:?} {:?}",
self.role,
self.state,
self.paths.primary_fallible()
)
}
}
impl Connection {
/// A long default for timer resolution, so that we don't tax the
/// system too hard when we don't need to.
const LOOSE_TIMER_RESOLUTION: Duration = Duration::from_millis(50);
/// Create a new QUIC connection with Client role.
/// # Errors
/// When NSS fails and an agent cannot be created.
pub fn new_client(
server_name: impl Into<String>,
protocols: &[impl AsRef<str>],
cid_generator: Rc<RefCell<dyn ConnectionIdGenerator>>,
local_addr: SocketAddr,
remote_addr: SocketAddr,
conn_params: ConnectionParameters,
now: Instant,
) -> Res<Self> {
let dcid = ConnectionId::generate_initial();
let mut c = Self::new(
Role::Client,
Agent::from(Client::new(server_name.into(), conn_params.is_greasing())?),
cid_generator,
protocols,
conn_params,
)?;
c.crypto.states.init(
c.conn_params.get_versions().compatible(),
Role::Client,
&dcid,
);
c.original_destination_cid = Some(dcid);
let path = Path::temporary(
local_addr,
remote_addr,
c.conn_params.get_cc_algorithm(),
c.conn_params.pacing_enabled(),
NeqoQlog::default(),
now,
);
c.setup_handshake_path(&Rc::new(RefCell::new(path)), now);
Ok(c)
}
/// Create a new QUIC connection with Server role.
/// # Errors
/// When NSS fails and an agent cannot be created.
pub fn new_server(
certs: &[impl AsRef<str>],
protocols: &[impl AsRef<str>],
cid_generator: Rc<RefCell<dyn ConnectionIdGenerator>>,
conn_params: ConnectionParameters,
) -> Res<Self> {
Self::new(
Role::Server,
Agent::from(Server::new(certs)?),
cid_generator,
protocols,
conn_params,
)
}
fn new<P: AsRef<str>>(
role: Role,
agent: Agent,
cid_generator: Rc<RefCell<dyn ConnectionIdGenerator>>,
protocols: &[P],
conn_params: ConnectionParameters,
) -> Res<Self> {
// Setup the local connection ID.
let local_initial_source_cid = cid_generator
.borrow_mut()
.generate_cid()
.ok_or(Error::ConnectionIdsExhausted)?;
let mut cid_manager =
ConnectionIdManager::new(cid_generator, local_initial_source_cid.clone());
let mut tps = conn_params.create_transport_parameter(role, &mut cid_manager)?;
tps.local.set_bytes(
tparams::INITIAL_SOURCE_CONNECTION_ID,
local_initial_source_cid.to_vec(),
);
let tphandler = Rc::new(RefCell::new(tps));
let crypto = Crypto::new(
conn_params.get_versions().initial(),
agent,
protocols.iter().map(P::as_ref).map(String::from).collect(),
Rc::clone(&tphandler),
)?;
let stats = StatsCell::default();
let events = ConnectionEvents::default();
let quic_datagrams = QuicDatagrams::new(
conn_params.get_datagram_size(),
conn_params.get_outgoing_datagram_queue(),
conn_params.get_incoming_datagram_queue(),
events.clone(),
);
let c = Self {
role,
version: conn_params.get_versions().initial(),
state: State::Init,
paths: Paths::default(),
cid_manager,
tps: tphandler.clone(),
zero_rtt_state: ZeroRttState::Init,
address_validation: AddressValidationInfo::None,
local_initial_source_cid,
remote_initial_source_cid: None,
original_destination_cid: None,
saved_datagrams: SavedDatagrams::default(),
received_untracked: false,
crypto,
acks: AckTracker::default(),
idle_timeout: IdleTimeout::new(conn_params.get_idle_timeout()),
streams: Streams::new(tphandler, role, events.clone()),
connection_ids: ConnectionIdStore::default(),
state_signaling: StateSignaling::Idle,
loss_recovery: LossRecovery::new(stats.clone(), conn_params.get_fast_pto()),
events,
new_token: NewTokenState::new(role),
stats,
qlog: NeqoQlog::disabled(),
release_resumption_token_timer: None,
conn_params,
hrtime: hrtime::Time::get(Self::LOOSE_TIMER_RESOLUTION),
quic_datagrams,
#[cfg(test)]
test_frame_writer: None,
};
c.stats.borrow_mut().init(format!("{c}"));
Ok(c)
}
/// # Errors
/// When the operation fails.
pub fn server_enable_0rtt(
&mut self,
anti_replay: &AntiReplay,
zero_rtt_checker: impl ZeroRttChecker + 'static,
) -> Res<()> {
self.crypto
.server_enable_0rtt(self.tps.clone(), anti_replay, zero_rtt_checker)
}
/// # Errors
/// When the operation fails.
pub fn server_enable_ech(
&mut self,
config: u8,
public_name: &str,
sk: &PrivateKey,
pk: &PublicKey,
) -> Res<()> {
self.crypto.server_enable_ech(config, public_name, sk, pk)
}
/// Get the active ECH configuration, which is empty if ECH is disabled.
#[must_use]
pub fn ech_config(&self) -> &[u8] {
self.crypto.ech_config()
}
/// # Errors
/// When the operation fails.
pub fn client_enable_ech(&mut self, ech_config_list: impl AsRef<[u8]>) -> Res<()> {
self.crypto.client_enable_ech(ech_config_list)
}
/// Set or clear the qlog for this connection.
pub fn set_qlog(&mut self, qlog: NeqoQlog) {
self.loss_recovery.set_qlog(qlog.clone());
self.paths.set_qlog(qlog.clone());
self.qlog = qlog;
}
/// Get the qlog (if any) for this connection.
pub fn qlog_mut(&mut self) -> &mut NeqoQlog {
&mut self.qlog
}
/// Get the original destination connection id for this connection. This
/// will always be present for `Role::Client` but not if `Role::Server` is in
/// `State::Init`.
#[must_use]
pub fn odcid(&self) -> Option<&ConnectionId> {
self.original_destination_cid.as_ref()
}
/// Set a local transport parameter, possibly overriding a default value.
/// This only sets transport parameters without dealing with other aspects of
/// setting the value.
///
/// # Errors
/// When the transport parameter is invalid.
/// # Panics
/// This panics if the transport parameter is known to this crate.
pub fn set_local_tparam(&self, tp: TransportParameterId, value: TransportParameter) -> Res<()> {
#[cfg(not(test))]
{
assert!(!tparams::INTERNAL_TRANSPORT_PARAMETERS.contains(&tp));
}
if *self.state() == State::Init {
self.tps.borrow_mut().local.set(tp, value);
Ok(())
} else {
qerror!("Current state: {:?}", self.state());
qerror!("Cannot set local tparam when not in an initial connection state.");
Err(Error::ConnectionState)
}
}
/// `odcid` is their original choice for our CID, which we get from the Retry token.
/// `remote_cid` is the value from the Source Connection ID field of an incoming packet: what
/// the peer wants us to use now. `retry_cid` is what we asked them to use when we sent the
/// Retry.
pub(crate) fn set_retry_cids(
&mut self,
odcid: &ConnectionId,
remote_cid: ConnectionId,
retry_cid: &ConnectionId,
) {
debug_assert_eq!(self.role, Role::Server);
qtrace!(
[self],
"Retry CIDs: odcid={} remote={} retry={}",
odcid,
remote_cid,
retry_cid
);
// We advertise "our" choices in transport parameters.
let local_tps = &mut self.tps.borrow_mut().local;
local_tps.set_bytes(tparams::ORIGINAL_DESTINATION_CONNECTION_ID, odcid.to_vec());
local_tps.set_bytes(tparams::RETRY_SOURCE_CONNECTION_ID, retry_cid.to_vec());
// ...and save their choices for later validation.
self.remote_initial_source_cid = Some(remote_cid);
}
fn retry_sent(&self) -> bool {
self.tps
.borrow()
.local
.get_bytes(tparams::RETRY_SOURCE_CONNECTION_ID)
.is_some()
}
/// Set ALPN preferences. Strings that appear earlier in the list are given
/// higher preference.
/// # Errors
/// When the operation fails, which is usually due to bad inputs or bad connection state.
pub fn set_alpn(&mut self, protocols: &[impl AsRef<str>]) -> Res<()> {
self.crypto.tls.set_alpn(protocols)?;
Ok(())
}
/// Enable a set of ciphers.
/// # Errors
/// When the operation fails, which is usually due to bad inputs or bad connection state.
pub fn set_ciphers(&mut self, ciphers: &[Cipher]) -> Res<()> {
if self.state != State::Init {
qerror!([self], "Cannot enable ciphers in state {:?}", self.state);
return Err(Error::ConnectionState);
}
self.crypto.tls.set_ciphers(ciphers)?;
Ok(())
}
/// Enable a set of key exchange groups.
/// # Errors
/// When the operation fails, which is usually due to bad inputs or bad connection state.
pub fn set_groups(&mut self, groups: &[Group]) -> Res<()> {
if self.state != State::Init {
qerror!([self], "Cannot enable groups in state {:?}", self.state);
return Err(Error::ConnectionState);
}
self.crypto.tls.set_groups(groups)?;
Ok(())
}
/// Set the number of additional key shares to send in the client hello.
/// # Errors
/// When the operation fails, which is usually due to bad inputs or bad connection state.
pub fn send_additional_key_shares(&mut self, count: usize) -> Res<()> {
if self.state != State::Init {
qerror!([self], "Cannot enable groups in state {:?}", self.state);
return Err(Error::ConnectionState);
}
self.crypto.tls.send_additional_key_shares(count)?;
Ok(())
}
fn make_resumption_token(&mut self) -> ResumptionToken {
debug_assert_eq!(self.role, Role::Client);
debug_assert!(self.crypto.has_resumption_token());
let rtt = self.paths.primary().borrow().rtt().estimate();
self.crypto
.create_resumption_token(
self.new_token.take_token(),
self.tps
.borrow()
.remote
.as_ref()
.expect("should have transport parameters"),
self.version,
u64::try_from(rtt.as_millis()).unwrap_or(0),
)
.unwrap()
}
/// Get the simplest PTO calculation for all those cases where we need
/// a value of this approximate order. Don't use this for loss recovery,
/// only use it where a more precise value is not important.
fn pto(&self) -> Duration {
self.paths
.primary()
.borrow()
.rtt()
.pto(PacketNumberSpace::ApplicationData)
}
fn create_resumption_token(&mut self, now: Instant) {
if self.role == Role::Server || self.state < State::Connected {
return;
}
qtrace!(
[self],
"Maybe create resumption token: {} {}",
self.crypto.has_resumption_token(),
self.new_token.has_token()
);
while self.crypto.has_resumption_token() && self.new_token.has_token() {
let token = self.make_resumption_token();
self.events.client_resumption_token(token);
}
// If we have a resumption ticket check or set a timer.
if self.crypto.has_resumption_token() {
let arm = if let Some(expiration_time) = self.release_resumption_token_timer {
if expiration_time <= now {
let token = self.make_resumption_token();
self.events.client_resumption_token(token);
self.release_resumption_token_timer = None;
// This means that we release one session ticket every 3 PTOs
// if no NEW_TOKEN frame is received.
self.crypto.has_resumption_token()
} else {
false
}
} else {
true
};
if arm {
self.release_resumption_token_timer = Some(now + 3 * self.pto());
}
}
}
/// The correct way to obtain a resumption token is to wait for the
/// `ConnectionEvent::ResumptionToken` event. To emit the event we are waiting for a
/// resumption token and a `NEW_TOKEN` frame to arrive. Some servers don't send `NEW_TOKEN`
/// frames and in this case, we wait for 3xPTO before emitting an event. This is especially a
/// problem for short-lived connections, where the connection is closed before any events are
/// released. This function retrieves the token, without waiting for a `NEW_TOKEN` frame to
/// arrive.
///
/// # Panics
///
/// If this is called on a server.
pub fn take_resumption_token(&mut self, now: Instant) -> Option<ResumptionToken> {
assert_eq!(self.role, Role::Client);
if self.crypto.has_resumption_token() {
let token = self.make_resumption_token();
if self.crypto.has_resumption_token() {
self.release_resumption_token_timer = Some(now + 3 * self.pto());
}
Some(token)
} else {
None
}
}
/// Enable resumption, using a token previously provided.
/// This can only be called once and only on the client.
/// After calling the function, it should be possible to attempt 0-RTT
/// if the token supports that.
/// # Errors
/// When the operation fails, which is usually due to bad inputs or bad connection state.
pub fn enable_resumption(&mut self, now: Instant, token: impl AsRef<[u8]>) -> Res<()> {
if self.state != State::Init {
qerror!([self], "set token in state {:?}", self.state);
return Err(Error::ConnectionState);
}
if self.role == Role::Server {
return Err(Error::ConnectionState);
}
qinfo!(
[self],
"resumption token {}",
hex_snip_middle(token.as_ref())
);
let mut dec = Decoder::from(token.as_ref());
let version = Version::try_from(u32::try_from(
dec.decode_uint(4).ok_or(Error::InvalidResumptionToken)?,
)?)?;
qtrace!([self], " version {:?}", version);
if !self.conn_params.get_versions().all().contains(&version) {
return Err(Error::DisabledVersion);
}
let rtt = Duration::from_millis(dec.decode_varint().ok_or(Error::InvalidResumptionToken)?);
qtrace!([self], " RTT {:?}", rtt);
let tp_slice = dec.decode_vvec().ok_or(Error::InvalidResumptionToken)?;
qtrace!([self], " transport parameters {}", hex(tp_slice));
let mut dec_tp = Decoder::from(tp_slice);
let tp =
TransportParameters::decode(&mut dec_tp).map_err(|_| Error::InvalidResumptionToken)?;
let init_token = dec.decode_vvec().ok_or(Error::InvalidResumptionToken)?;
qtrace!([self], " Initial token {}", hex(init_token));
let tok = dec.decode_remainder();
qtrace!([self], " TLS token {}", hex(tok));
match self.crypto.tls {
Agent::Client(ref mut c) => {
let res = c.enable_resumption(tok);
if let Err(e) = res {
self.absorb_error::<Error>(now, Err(Error::from(e)));
return Ok(());
}
}
Agent::Server(_) => return Err(Error::WrongRole),
}
self.version = version;
self.conn_params.get_versions_mut().set_initial(version);
self.tps.borrow_mut().set_version(version);
self.tps.borrow_mut().remote_0rtt = Some(tp);
if !init_token.is_empty() {
self.address_validation = AddressValidationInfo::NewToken(init_token.to_vec());
}
self.paths.primary().borrow_mut().rtt_mut().set_initial(rtt);
self.set_initial_limits();
// Start up TLS, which has the effect of setting up all the necessary
// state for 0-RTT. This only stages the CRYPTO frames.
let res = self.client_start(now);
self.absorb_error(now, res);
Ok(())
}
pub(crate) fn set_validation(&mut self, validation: &Rc<RefCell<AddressValidation>>) {
qtrace!([self], "Enabling NEW_TOKEN");
assert_eq!(self.role, Role::Server);
self.address_validation = AddressValidationInfo::Server(Rc::downgrade(validation));
}
/// Send a TLS session ticket AND a `NEW_TOKEN` frame (if possible).
/// # Errors
/// When the operation fails, which is usually due to bad inputs or bad connection state.
pub fn send_ticket(&mut self, now: Instant, extra: &[u8]) -> Res<()> {
if self.role == Role::Client {
return Err(Error::WrongRole);
}
let tps = &self.tps;
if let Agent::Server(ref mut s) = self.crypto.tls {
let mut enc = Encoder::default();
enc.encode_vvec_with(|enc_inner| {
tps.borrow().local.encode(enc_inner);
});
enc.encode(extra);
let records = s.send_ticket(now, enc.as_ref())?;
qdebug!([self], "send session ticket {}", hex(&enc));
self.crypto.buffer_records(records)?;
} else {
unreachable!();
}
// If we are able, also send a NEW_TOKEN frame.
// This should be recording all remote addresses that are valid,
// but there are just 0 or 1 in the current implementation.
if let Some(path) = self.paths.primary_fallible() {
if let Some(token) = self
.address_validation
.generate_new_token(path.borrow().remote_address(), now)
{
self.new_token.send_new_token(token);
}
Ok(())
} else {
Err(Error::NotConnected)
}
}
#[must_use]
pub fn tls_info(&self) -> Option<&SecretAgentInfo> {
self.crypto.tls.info()
}
/// # Errors
/// When there is no information to obtain.
pub fn tls_preinfo(&self) -> Res<SecretAgentPreInfo> {
Ok(self.crypto.tls.preinfo()?)
}
/// Get the peer's certificate chain and other info.
#[must_use]
pub fn peer_certificate(&self) -> Option<CertificateInfo> {
self.crypto.tls.peer_certificate()
}
/// Call by application when the peer cert has been verified.
///
/// This panics if there is no active peer. It's OK to call this
/// when authentication isn't needed, that will likely only cause
/// the connection to fail. However, if no packets have been
/// exchanged, it's not OK.
pub fn authenticated(&mut self, status: AuthenticationStatus, now: Instant) {
qdebug!([self], "Authenticated {:?}", status);
self.crypto.tls.authenticated(status);
let res = self.handshake(now, self.version, PacketNumberSpace::Handshake, None);
self.absorb_error(now, res);
self.process_saved(now);
}
/// Get the role of the connection.
#[must_use]
pub fn role(&self) -> Role {
self.role
}
/// Get the state of the connection.
#[must_use]
pub fn state(&self) -> &State {
&self.state
}
/// The QUIC version in use.
#[must_use]
pub fn version(&self) -> Version {
self.version
}
/// Get the 0-RTT state of the connection.
#[must_use]
pub fn zero_rtt_state(&self) -> ZeroRttState {
self.zero_rtt_state
}
/// Get a snapshot of collected statistics.
#[must_use]
pub fn stats(&self) -> Stats {
let mut v = self.stats.borrow().clone();
if let Some(p) = self.paths.primary_fallible() {
let p = p.borrow();
v.rtt = p.rtt().estimate();
v.rttvar = p.rtt().rttvar();
}
v
}
// This function wraps a call to another function and sets the connection state
// properly if that call fails.
fn capture_error<T>(
&mut self,
path: Option<PathRef>,
now: Instant,
frame_type: FrameType,
res: Res<T>,
) -> Res<T> {
if let Err(v) = &res {
#[cfg(debug_assertions)]
let msg = format!("{v:?}");
#[cfg(not(debug_assertions))]
let msg = "";
let error = ConnectionError::Transport(v.clone());
match &self.state {
State::Closing { error: err, .. }
| State::Draining { error: err, .. }
| State::Closed(err) => {
qwarn!([self], "Closing again after error {:?}", err);
}
State::Init => {
// We have not even sent anything just close the connection without sending any
// error. This may happen when client_start fails.
self.set_state(State::Closed(error));
}
State::WaitInitial => {
// We don't have any state yet, so don't bother with
// the closing state, just send one CONNECTION_CLOSE.
if let Some(path) = path.or_else(|| self.paths.primary_fallible()) {
self.state_signaling
.close(path, error.clone(), frame_type, msg);
}
self.set_state(State::Closed(error));
}
_ => {
if let Some(path) = path.or_else(|| self.paths.primary_fallible()) {
self.state_signaling
.close(path, error.clone(), frame_type, msg);
if matches!(v, Error::KeysExhausted) {
self.set_state(State::Closed(error));
} else {
self.set_state(State::Closing {
error,
timeout: self.get_closing_period_time(now),
});
}
} else {
self.set_state(State::Closed(error));
}
}
}
}
res
}
/// For use with `process_input()`. Errors there can be ignored, but this
/// needs to ensure that the state is updated.
fn absorb_error<T>(&mut self, now: Instant, res: Res<T>) -> Option<T> {
self.capture_error(None, now, 0, res).ok()
}
fn process_timer(&mut self, now: Instant) {
match &self.state {
// Only the client runs timers while waiting for Initial packets.
State::WaitInitial => debug_assert_eq!(self.role, Role::Client),
// If Closing or Draining, check if it is time to move to Closed.
State::Closing { error, timeout } | State::Draining { error, timeout } => {
if *timeout <= now {
let st = State::Closed(error.clone());
self.set_state(st);
qinfo!("Closing timer expired");
return;
}
}
State::Closed(_) => {
qdebug!("Timer fired while closed");
return;
}
_ => (),
}
let pto = self.pto();
if self.idle_timeout.expired(now, pto) {
qinfo!([self], "idle timeout expired");
self.set_state(State::Closed(ConnectionError::Transport(
Error::IdleTimeout,
)));
return;
}
self.streams.cleanup_closed_streams();
let res = self.crypto.states.check_key_update(now);
self.absorb_error(now, res);
let lost = self.loss_recovery.timeout(&self.paths.primary(), now);
self.handle_lost_packets(&lost);
qlog::packets_lost(&mut self.qlog, &lost);
if self.release_resumption_token_timer.is_some() {
self.create_resumption_token(now);
}
if !self.paths.process_timeout(now, pto) {
qinfo!([self], "last available path failed");
self.absorb_error::<Error>(now, Err(Error::NoAvailablePath));
}
}
/// Process new input datagrams on the connection.
pub fn process_input(&mut self, d: &Datagram, now: Instant) {
self.process_multiple_input(iter::once(d), now);
}
/// Process new input datagrams on the connection.
pub fn process_multiple_input<'a, I>(&mut self, dgrams: I, now: Instant)
where
I: IntoIterator<Item = &'a Datagram>,
I::IntoIter: ExactSizeIterator,
{
let dgrams = dgrams.into_iter();
if dgrams.len() == 0 {
return;
}
for d in dgrams {
self.input(d, now, now);
}
self.process_saved(now);
self.streams.cleanup_closed_streams();
}