1#![allow(clippy::upper_case_acronyms)]
379#![warn(missing_docs)]
380#![cfg_attr(docsrs, feature(doc_cfg))]
381
382#[macro_use]
383extern crate log;
384
385use octets::BufferTooShortError;
386#[cfg(feature = "qlog")]
387use qlog::events::connectivity::ConnectivityEventType;
388#[cfg(feature = "qlog")]
389use qlog::events::connectivity::TransportOwner;
390#[cfg(feature = "qlog")]
391use qlog::events::quic::RecoveryEventType;
392#[cfg(feature = "qlog")]
393use qlog::events::quic::TransportEventType;
394#[cfg(feature = "qlog")]
395use qlog::events::DataRecipient;
396#[cfg(feature = "qlog")]
397use qlog::events::Event;
398#[cfg(feature = "qlog")]
399use qlog::events::EventData;
400#[cfg(feature = "qlog")]
401use qlog::events::EventImportance;
402#[cfg(feature = "qlog")]
403use qlog::events::EventType;
404#[cfg(feature = "qlog")]
405use qlog::events::RawInfo;
406use stream::StreamPriorityKey;
407
408use std::cmp;
409use std::convert::TryInto;
410use std::time;
411
412use std::sync::Arc;
413
414use std::net::SocketAddr;
415
416use std::str::FromStr;
417
418use std::collections::HashSet;
419use std::collections::VecDeque;
420use std::time::Duration;
421
422use smallvec::SmallVec;
423
424use crate::recovery::ReleaseDecision;
425
426pub const PROTOCOL_VERSION: u32 = PROTOCOL_VERSION_V1;
428
429const PROTOCOL_VERSION_V1: u32 = 0x0000_0001;
431
432pub const MAX_CONN_ID_LEN: usize = crate::packet::MAX_CID_LEN as usize;
434
435pub const MIN_CLIENT_INITIAL_LEN: usize = 1200;
437
438#[cfg(not(feature = "fuzzing"))]
439const PAYLOAD_MIN_LEN: usize = 4;
440
441#[cfg(feature = "fuzzing")]
442const PAYLOAD_MIN_LEN: usize = 20;
446
447const MIN_PROBING_SIZE: usize = 25;
449
450const MAX_AMPLIFICATION_FACTOR: usize = 3;
451
452const MAX_ACK_RANGES: usize = 68;
456
457const MAX_STREAM_ID: u64 = 1 << 60;
459
460const MAX_SEND_UDP_PAYLOAD_SIZE: usize = 1200;
462
463const DEFAULT_MAX_DGRAM_QUEUE_LEN: usize = 0;
465
466const DEFAULT_MAX_PATH_CHALLENGE_RX_QUEUE_LEN: usize = 3;
468
469const MAX_DGRAM_FRAME_SIZE: u64 = 65536;
472
473const PAYLOAD_LENGTH_LEN: usize = 2;
475
476const MAX_UNDECRYPTABLE_PACKETS: usize = 10;
478
479const RESERVED_VERSION_MASK: u32 = 0xfafafafa;
480
481const DEFAULT_CONNECTION_WINDOW: u64 = 48 * 1024;
483
484const MAX_CONNECTION_WINDOW: u64 = 24 * 1024 * 1024;
486
487const CONNECTION_WINDOW_FACTOR: f64 = 1.5;
490
491const MAX_PROBING_TIMEOUTS: usize = 3;
494
495const DEFAULT_INITIAL_CONGESTION_WINDOW_PACKETS: usize = 10;
497
498const MAX_CRYPTO_STREAM_OFFSET: u64 = 1 << 16;
500
501pub type Result<T> = std::result::Result<T, Error>;
508
509#[derive(Clone, Copy, Debug, PartialEq, Eq)]
511pub enum Error {
512 Done,
514
515 BufferTooShort,
517
518 UnknownVersion,
520
521 InvalidFrame,
524
525 InvalidPacket,
527
528 InvalidState,
531
532 InvalidStreamState(u64),
537
538 InvalidTransportParam,
540
541 CryptoFail,
543
544 TlsFail,
546
547 FlowControl,
549
550 StreamLimit,
552
553 StreamStopped(u64),
558
559 StreamReset(u64),
564
565 FinalSize,
567
568 CongestionControl,
570
571 IdLimit,
573
574 OutOfIdentifiers,
576
577 KeyUpdate,
579
580 CryptoBufferExceeded,
582}
583
584#[derive(Copy, Clone, Debug, Eq, PartialEq)]
588pub enum WireErrorCode {
589 NoError = 0x0,
592 InternalError = 0x1,
595 ConnectionRefused = 0x2,
597 FlowControlError = 0x3,
600 StreamLimitError = 0x4,
603 StreamStateError = 0x5,
606 FinalSizeError = 0x6,
613 FrameEncodingError = 0x7,
617 TransportParameterError = 0x8,
622 ConnectionIdLimitError = 0x9,
627 ProtocolViolation = 0xa,
630 InvalidToken = 0xb,
633 ApplicationError = 0xc,
636 CryptoBufferExceeded = 0xd,
638 KeyUpdateError = 0xe,
640 AeadLimitReached = 0xf,
643 NoViablePath = 0x10,
648}
649
650impl Error {
651 fn to_wire(self) -> u64 {
652 match self {
653 Error::Done => WireErrorCode::NoError as u64,
654 Error::InvalidFrame => WireErrorCode::FrameEncodingError as u64,
655 Error::InvalidStreamState(..) =>
656 WireErrorCode::StreamStateError as u64,
657 Error::InvalidTransportParam =>
658 WireErrorCode::TransportParameterError as u64,
659 Error::FlowControl => WireErrorCode::FlowControlError as u64,
660 Error::StreamLimit => WireErrorCode::StreamLimitError as u64,
661 Error::IdLimit => WireErrorCode::ConnectionIdLimitError as u64,
662 Error::FinalSize => WireErrorCode::FinalSizeError as u64,
663 Error::CryptoBufferExceeded =>
664 WireErrorCode::CryptoBufferExceeded as u64,
665 Error::KeyUpdate => WireErrorCode::KeyUpdateError as u64,
666 _ => WireErrorCode::ProtocolViolation as u64,
667 }
668 }
669
670 #[cfg(feature = "ffi")]
671 fn to_c(self) -> libc::ssize_t {
672 match self {
673 Error::Done => -1,
674 Error::BufferTooShort => -2,
675 Error::UnknownVersion => -3,
676 Error::InvalidFrame => -4,
677 Error::InvalidPacket => -5,
678 Error::InvalidState => -6,
679 Error::InvalidStreamState(_) => -7,
680 Error::InvalidTransportParam => -8,
681 Error::CryptoFail => -9,
682 Error::TlsFail => -10,
683 Error::FlowControl => -11,
684 Error::StreamLimit => -12,
685 Error::FinalSize => -13,
686 Error::CongestionControl => -14,
687 Error::StreamStopped { .. } => -15,
688 Error::StreamReset { .. } => -16,
689 Error::IdLimit => -17,
690 Error::OutOfIdentifiers => -18,
691 Error::KeyUpdate => -19,
692 Error::CryptoBufferExceeded => -20,
693 }
694 }
695}
696
697impl std::fmt::Display for Error {
698 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
699 write!(f, "{self:?}")
700 }
701}
702
703impl std::error::Error for Error {
704 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
705 None
706 }
707}
708
709impl std::convert::From<octets::BufferTooShortError> for Error {
710 fn from(_err: octets::BufferTooShortError) -> Self {
711 Error::BufferTooShort
712 }
713}
714
715#[derive(Clone, Copy, Debug, PartialEq, Eq)]
717pub struct RecvInfo {
718 pub from: SocketAddr,
720
721 pub to: SocketAddr,
723}
724
725#[derive(Clone, Copy, Debug, PartialEq, Eq)]
727pub struct SendInfo {
728 pub from: SocketAddr,
730
731 pub to: SocketAddr,
733
734 pub at: time::Instant,
740}
741
742#[derive(Clone, Debug, PartialEq, Eq)]
744pub struct ConnectionError {
745 pub is_app: bool,
747
748 pub error_code: u64,
750
751 pub reason: Vec<u8>,
753}
754
755#[repr(C)]
761#[derive(PartialEq, Eq)]
762pub enum Shutdown {
763 Read = 0,
765
766 Write = 1,
768}
769
770#[repr(C)]
772#[cfg(feature = "qlog")]
773#[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
774pub enum QlogLevel {
775 Core = 0,
777
778 Base = 1,
780
781 Extra = 2,
783}
784
785pub struct Config {
787 local_transport_params: TransportParams,
788
789 version: u32,
790
791 tls_ctx: tls::Context,
792
793 application_protos: Vec<Vec<u8>>,
794
795 grease: bool,
796
797 cc_algorithm: CongestionControlAlgorithm,
798 initial_congestion_window_packets: usize,
799
800 pmtud: bool,
801
802 hystart: bool,
803
804 pacing: bool,
805 max_pacing_rate: Option<u64>,
807
808 dgram_recv_max_queue_len: usize,
809 dgram_send_max_queue_len: usize,
810
811 path_challenge_recv_max_queue_len: usize,
812
813 max_send_udp_payload_size: usize,
814
815 max_connection_window: u64,
816 max_stream_window: u64,
817
818 max_amplification_factor: usize,
819
820 disable_dcid_reuse: bool,
821
822 track_unknown_transport_params: Option<usize>,
823}
824
825fn is_reserved_version(version: u32) -> bool {
827 version & RESERVED_VERSION_MASK == version
828}
829
830impl Config {
831 pub fn new(version: u32) -> Result<Config> {
840 Self::with_tls_ctx(version, tls::Context::new()?)
841 }
842
843 #[cfg(feature = "boringssl-boring-crate")]
851 #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
852 pub fn with_boring_ssl_ctx_builder(
853 version: u32, tls_ctx_builder: boring::ssl::SslContextBuilder,
854 ) -> Result<Config> {
855 Self::with_tls_ctx(version, tls::Context::from_boring(tls_ctx_builder))
856 }
857
858 fn with_tls_ctx(version: u32, tls_ctx: tls::Context) -> Result<Config> {
859 if !is_reserved_version(version) && !version_is_supported(version) {
860 return Err(Error::UnknownVersion);
861 }
862
863 Ok(Config {
864 local_transport_params: TransportParams::default(),
865 version,
866 tls_ctx,
867 application_protos: Vec::new(),
868 grease: true,
869 cc_algorithm: CongestionControlAlgorithm::CUBIC,
870 initial_congestion_window_packets:
871 DEFAULT_INITIAL_CONGESTION_WINDOW_PACKETS,
872 pmtud: false,
873 hystart: true,
874 pacing: true,
875 max_pacing_rate: None,
876
877 dgram_recv_max_queue_len: DEFAULT_MAX_DGRAM_QUEUE_LEN,
878 dgram_send_max_queue_len: DEFAULT_MAX_DGRAM_QUEUE_LEN,
879
880 path_challenge_recv_max_queue_len:
881 DEFAULT_MAX_PATH_CHALLENGE_RX_QUEUE_LEN,
882
883 max_send_udp_payload_size: MAX_SEND_UDP_PAYLOAD_SIZE,
884
885 max_connection_window: MAX_CONNECTION_WINDOW,
886 max_stream_window: stream::MAX_STREAM_WINDOW,
887
888 max_amplification_factor: MAX_AMPLIFICATION_FACTOR,
889
890 disable_dcid_reuse: false,
891
892 track_unknown_transport_params: None,
893 })
894 }
895
896 pub fn load_cert_chain_from_pem_file(&mut self, file: &str) -> Result<()> {
909 self.tls_ctx.use_certificate_chain_file(file)
910 }
911
912 pub fn load_priv_key_from_pem_file(&mut self, file: &str) -> Result<()> {
924 self.tls_ctx.use_privkey_file(file)
925 }
926
927 pub fn load_verify_locations_from_file(&mut self, file: &str) -> Result<()> {
940 self.tls_ctx.load_verify_locations_from_file(file)
941 }
942
943 pub fn load_verify_locations_from_directory(
956 &mut self, dir: &str,
957 ) -> Result<()> {
958 self.tls_ctx.load_verify_locations_from_directory(dir)
959 }
960
961 pub fn verify_peer(&mut self, verify: bool) {
974 self.tls_ctx.set_verify(verify);
975 }
976
977 pub fn discover_pmtu(&mut self, discover: bool) {
981 self.pmtud = discover;
982 }
983
984 pub fn grease(&mut self, grease: bool) {
988 self.grease = grease;
989 }
990
991 pub fn log_keys(&mut self) {
1000 self.tls_ctx.enable_keylog();
1001 }
1002
1003 pub fn set_ticket_key(&mut self, key: &[u8]) -> Result<()> {
1014 self.tls_ctx.set_ticket_key(key)
1015 }
1016
1017 pub fn enable_early_data(&mut self) {
1019 self.tls_ctx.set_early_data_enabled(true);
1020 }
1021
1022 pub fn set_application_protos(
1040 &mut self, protos_list: &[&[u8]],
1041 ) -> Result<()> {
1042 self.application_protos =
1043 protos_list.iter().map(|s| s.to_vec()).collect();
1044
1045 self.tls_ctx.set_alpn(protos_list)
1046 }
1047
1048 pub fn set_application_protos_wire_format(
1065 &mut self, protos: &[u8],
1066 ) -> Result<()> {
1067 let mut b = octets::Octets::with_slice(protos);
1068
1069 let mut protos_list = Vec::new();
1070
1071 while let Ok(proto) = b.get_bytes_with_u8_length() {
1072 protos_list.push(proto.buf());
1073 }
1074
1075 self.set_application_protos(&protos_list)
1076 }
1077
1078 pub fn set_max_amplification_factor(&mut self, v: usize) {
1082 self.max_amplification_factor = v;
1083 }
1084
1085 pub fn set_max_idle_timeout(&mut self, v: u64) {
1089 self.local_transport_params.max_idle_timeout = v;
1090 }
1091
1092 pub fn set_max_recv_udp_payload_size(&mut self, v: usize) {
1096 self.local_transport_params.max_udp_payload_size = v as u64;
1097 }
1098
1099 pub fn set_max_send_udp_payload_size(&mut self, v: usize) {
1103 self.max_send_udp_payload_size = cmp::max(v, MAX_SEND_UDP_PAYLOAD_SIZE);
1104 }
1105
1106 pub fn set_initial_max_data(&mut self, v: u64) {
1119 self.local_transport_params.initial_max_data = v;
1120 }
1121
1122 pub fn set_initial_max_stream_data_bidi_local(&mut self, v: u64) {
1136 self.local_transport_params
1137 .initial_max_stream_data_bidi_local = v;
1138 }
1139
1140 pub fn set_initial_max_stream_data_bidi_remote(&mut self, v: u64) {
1154 self.local_transport_params
1155 .initial_max_stream_data_bidi_remote = v;
1156 }
1157
1158 pub fn set_initial_max_stream_data_uni(&mut self, v: u64) {
1171 self.local_transport_params.initial_max_stream_data_uni = v;
1172 }
1173
1174 pub fn set_initial_max_streams_bidi(&mut self, v: u64) {
1192 self.local_transport_params.initial_max_streams_bidi = v;
1193 }
1194
1195 pub fn set_initial_max_streams_uni(&mut self, v: u64) {
1211 self.local_transport_params.initial_max_streams_uni = v;
1212 }
1213
1214 pub fn set_ack_delay_exponent(&mut self, v: u64) {
1218 self.local_transport_params.ack_delay_exponent = v;
1219 }
1220
1221 pub fn set_max_ack_delay(&mut self, v: u64) {
1225 self.local_transport_params.max_ack_delay = v;
1226 }
1227
1228 pub fn set_active_connection_id_limit(&mut self, v: u64) {
1232 if v >= 2 {
1233 self.local_transport_params.active_conn_id_limit = v;
1234 }
1235 }
1236
1237 pub fn set_disable_active_migration(&mut self, v: bool) {
1241 self.local_transport_params.disable_active_migration = v;
1242 }
1243
1244 pub fn set_cc_algorithm(&mut self, algo: CongestionControlAlgorithm) {
1248 self.cc_algorithm = algo;
1249 }
1250
1251 pub fn set_cc_algorithm_name(&mut self, name: &str) -> Result<()> {
1264 self.cc_algorithm = CongestionControlAlgorithm::from_str(name)?;
1265
1266 Ok(())
1267 }
1268
1269 pub fn set_initial_congestion_window_packets(&mut self, packets: usize) {
1273 self.initial_congestion_window_packets = packets;
1274 }
1275
1276 pub fn enable_hystart(&mut self, v: bool) {
1280 self.hystart = v;
1281 }
1282
1283 pub fn enable_pacing(&mut self, v: bool) {
1287 self.pacing = v;
1288 }
1289
1290 pub fn set_max_pacing_rate(&mut self, v: u64) {
1294 self.max_pacing_rate = Some(v);
1295 }
1296
1297 pub fn enable_dgram(
1304 &mut self, enabled: bool, recv_queue_len: usize, send_queue_len: usize,
1305 ) {
1306 self.local_transport_params.max_datagram_frame_size = if enabled {
1307 Some(MAX_DGRAM_FRAME_SIZE)
1308 } else {
1309 None
1310 };
1311 self.dgram_recv_max_queue_len = recv_queue_len;
1312 self.dgram_send_max_queue_len = send_queue_len;
1313 }
1314
1315 pub fn set_path_challenge_recv_max_queue_len(&mut self, queue_len: usize) {
1322 self.path_challenge_recv_max_queue_len = queue_len;
1323 }
1324
1325 pub fn set_max_connection_window(&mut self, v: u64) {
1329 self.max_connection_window = v;
1330 }
1331
1332 pub fn set_max_stream_window(&mut self, v: u64) {
1336 self.max_stream_window = v;
1337 }
1338
1339 pub fn set_stateless_reset_token(&mut self, v: Option<u128>) {
1346 self.local_transport_params.stateless_reset_token = v;
1347 }
1348
1349 pub fn set_disable_dcid_reuse(&mut self, v: bool) {
1360 self.disable_dcid_reuse = v;
1361 }
1362
1363 pub fn enable_track_unknown_transport_parameters(&mut self, size: usize) {
1372 self.track_unknown_transport_params = Some(size);
1373 }
1374}
1375
1376pub struct Connection {
1378 version: u32,
1380
1381 ids: cid::ConnectionIdentifiers,
1383
1384 trace_id: String,
1386
1387 pkt_num_spaces: [packet::PktNumSpace; packet::Epoch::count()],
1389
1390 next_pkt_num: u64,
1392
1393 peer_transport_params: TransportParams,
1395
1396 peer_transport_params_track_unknown: Option<usize>,
1399
1400 local_transport_params: TransportParams,
1402
1403 handshake: tls::Handshake,
1405
1406 session: Option<Vec<u8>>,
1411
1412 recovery_config: recovery::RecoveryConfig,
1414
1415 paths: path::PathMap,
1417
1418 path_challenge_recv_max_queue_len: usize,
1420
1421 path_challenge_rx_count: u64,
1423
1424 application_protos: Vec<Vec<u8>>,
1426
1427 recv_count: usize,
1429
1430 sent_count: usize,
1432
1433 lost_count: usize,
1435
1436 retrans_count: usize,
1438
1439 dgram_sent_count: usize,
1441
1442 dgram_recv_count: usize,
1444
1445 rx_data: u64,
1447
1448 flow_control: flowcontrol::FlowControl,
1450
1451 almost_full: bool,
1453
1454 tx_cap: usize,
1456
1457 tx_buffered: usize,
1459
1460 tx_data: u64,
1462
1463 max_tx_data: u64,
1465
1466 last_tx_data: u64,
1468
1469 stream_retrans_bytes: u64,
1472
1473 sent_bytes: u64,
1475
1476 recv_bytes: u64,
1478
1479 acked_bytes: u64,
1481
1482 lost_bytes: u64,
1484
1485 streams: stream::StreamMap,
1487
1488 odcid: Option<ConnectionId<'static>>,
1491
1492 rscid: Option<ConnectionId<'static>>,
1495
1496 token: Option<Vec<u8>>,
1498
1499 local_error: Option<ConnectionError>,
1502
1503 peer_error: Option<ConnectionError>,
1506
1507 blocked_limit: Option<u64>,
1509
1510 idle_timer: Option<time::Instant>,
1512
1513 draining_timer: Option<time::Instant>,
1515
1516 undecryptable_pkts: VecDeque<(Vec<u8>, RecvInfo)>,
1518
1519 alpn: Vec<u8>,
1521
1522 is_server: bool,
1524
1525 derived_initial_secrets: bool,
1527
1528 did_version_negotiation: bool,
1531
1532 did_retry: bool,
1534
1535 got_peer_conn_id: bool,
1537
1538 peer_verified_initial_address: bool,
1540
1541 parsed_peer_transport_params: bool,
1543
1544 handshake_completed: bool,
1546
1547 handshake_done_sent: bool,
1549
1550 handshake_done_acked: bool,
1552
1553 handshake_confirmed: bool,
1555
1556 key_phase: bool,
1558
1559 ack_eliciting_sent: bool,
1562
1563 closed: bool,
1565
1566 timed_out: bool,
1568
1569 grease: bool,
1571
1572 keylog: Option<Box<dyn std::io::Write + Send + Sync>>,
1574
1575 #[cfg(feature = "qlog")]
1576 qlog: QlogInfo,
1577
1578 dgram_recv_queue: dgram::DatagramQueue,
1580 dgram_send_queue: dgram::DatagramQueue,
1581
1582 emit_dgram: bool,
1584
1585 disable_dcid_reuse: bool,
1588
1589 reset_stream_local_count: u64,
1591
1592 stopped_stream_local_count: u64,
1594
1595 reset_stream_remote_count: u64,
1597
1598 stopped_stream_remote_count: u64,
1600
1601 max_amplification_factor: usize,
1603}
1604
1605#[inline]
1625pub fn accept(
1626 scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr,
1627 peer: SocketAddr, config: &mut Config,
1628) -> Result<Connection> {
1629 let conn = Connection::new(scid, odcid, local, peer, config, true)?;
1630
1631 Ok(conn)
1632}
1633
1634#[inline]
1653pub fn connect(
1654 server_name: Option<&str>, scid: &ConnectionId, local: SocketAddr,
1655 peer: SocketAddr, config: &mut Config,
1656) -> Result<Connection> {
1657 let mut conn = Connection::new(scid, None, local, peer, config, false)?;
1658
1659 if let Some(server_name) = server_name {
1660 conn.handshake.set_host_name(server_name)?;
1661 }
1662
1663 Ok(conn)
1664}
1665
1666#[inline]
1690pub fn negotiate_version(
1691 scid: &ConnectionId, dcid: &ConnectionId, out: &mut [u8],
1692) -> Result<usize> {
1693 packet::negotiate_version(scid, dcid, out)
1694}
1695
1696#[inline]
1756pub fn retry(
1757 scid: &ConnectionId, dcid: &ConnectionId, new_scid: &ConnectionId,
1758 token: &[u8], version: u32, out: &mut [u8],
1759) -> Result<usize> {
1760 packet::retry(scid, dcid, new_scid, token, version, out)
1761}
1762
1763#[inline]
1765pub fn version_is_supported(version: u32) -> bool {
1766 matches!(version, PROTOCOL_VERSION_V1)
1767}
1768
1769macro_rules! push_frame_to_pkt {
1775 ($out:expr, $frames:expr, $frame:expr, $left:expr) => {{
1776 if $frame.wire_len() <= $left {
1777 $left -= $frame.wire_len();
1778
1779 $frame.to_bytes(&mut $out)?;
1780
1781 $frames.push($frame);
1782
1783 true
1784 } else {
1785 false
1786 }
1787 }};
1788}
1789
1790macro_rules! qlog_with_type {
1794 ($ty:expr, $qlog:expr, $qlog_streamer_ref:ident, $body:block) => {{
1795 #[cfg(feature = "qlog")]
1796 {
1797 if EventImportance::from($ty).is_contained_in(&$qlog.level) {
1798 if let Some($qlog_streamer_ref) = &mut $qlog.streamer {
1799 $body
1800 }
1801 }
1802 }
1803 }};
1804}
1805
1806#[cfg(feature = "qlog")]
1807const QLOG_PARAMS_SET: EventType =
1808 EventType::TransportEventType(TransportEventType::ParametersSet);
1809
1810#[cfg(feature = "qlog")]
1811const QLOG_PACKET_RX: EventType =
1812 EventType::TransportEventType(TransportEventType::PacketReceived);
1813
1814#[cfg(feature = "qlog")]
1815const QLOG_PACKET_TX: EventType =
1816 EventType::TransportEventType(TransportEventType::PacketSent);
1817
1818#[cfg(feature = "qlog")]
1819const QLOG_DATA_MV: EventType =
1820 EventType::TransportEventType(TransportEventType::DataMoved);
1821
1822#[cfg(feature = "qlog")]
1823const QLOG_METRICS: EventType =
1824 EventType::RecoveryEventType(RecoveryEventType::MetricsUpdated);
1825
1826#[cfg(feature = "qlog")]
1827const QLOG_CONNECTION_CLOSED: EventType =
1828 EventType::ConnectivityEventType(ConnectivityEventType::ConnectionClosed);
1829
1830#[cfg(feature = "qlog")]
1831struct QlogInfo {
1832 streamer: Option<qlog::streamer::QlogStreamer>,
1833 logged_peer_params: bool,
1834 level: EventImportance,
1835}
1836
1837#[cfg(feature = "qlog")]
1838impl Default for QlogInfo {
1839 fn default() -> Self {
1840 QlogInfo {
1841 streamer: None,
1842 logged_peer_params: false,
1843 level: EventImportance::Base,
1844 }
1845 }
1846}
1847
1848impl Connection {
1849 fn new(
1850 scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr,
1851 peer: SocketAddr, config: &mut Config, is_server: bool,
1852 ) -> Result<Connection> {
1853 let tls = config.tls_ctx.new_handshake()?;
1854 Connection::with_tls(scid, odcid, local, peer, config, tls, is_server)
1855 }
1856
1857 fn with_tls(
1858 scid: &ConnectionId, odcid: Option<&ConnectionId>, local: SocketAddr,
1859 peer: SocketAddr, config: &Config, tls: tls::Handshake, is_server: bool,
1860 ) -> Result<Connection> {
1861 let max_rx_data = config.local_transport_params.initial_max_data;
1862
1863 let scid_as_hex: Vec<String> =
1864 scid.iter().map(|b| format!("{b:02x}")).collect();
1865
1866 let reset_token = if is_server {
1867 config.local_transport_params.stateless_reset_token
1868 } else {
1869 None
1870 };
1871
1872 let recovery_config = recovery::RecoveryConfig::from_config(config);
1873
1874 let mut path = path::Path::new(
1875 local,
1876 peer,
1877 &recovery_config,
1878 config.path_challenge_recv_max_queue_len,
1879 MIN_CLIENT_INITIAL_LEN,
1880 true,
1881 );
1882
1883 path.verified_peer_address = odcid.is_some();
1885 path.peer_verified_local_address = is_server;
1887
1888 let paths = path::PathMap::new(
1890 path,
1891 config.local_transport_params.active_conn_id_limit as usize,
1892 is_server,
1893 config.pmtud,
1894 config.max_send_udp_payload_size,
1895 );
1896
1897 let active_path_id = paths.get_active_path_id()?;
1898
1899 let ids = cid::ConnectionIdentifiers::new(
1900 config.local_transport_params.active_conn_id_limit as usize,
1901 scid,
1902 active_path_id,
1903 reset_token,
1904 );
1905
1906 let mut conn = Connection {
1907 version: config.version,
1908
1909 ids,
1910
1911 trace_id: scid_as_hex.join(""),
1912
1913 pkt_num_spaces: [
1914 packet::PktNumSpace::new(),
1915 packet::PktNumSpace::new(),
1916 packet::PktNumSpace::new(),
1917 ],
1918
1919 next_pkt_num: 0,
1920
1921 peer_transport_params: TransportParams::default(),
1922
1923 peer_transport_params_track_unknown: config
1924 .track_unknown_transport_params,
1925
1926 local_transport_params: config.local_transport_params.clone(),
1927
1928 handshake: tls,
1929
1930 session: None,
1931
1932 recovery_config,
1933
1934 paths,
1935 path_challenge_recv_max_queue_len: config
1936 .path_challenge_recv_max_queue_len,
1937 path_challenge_rx_count: 0,
1938
1939 application_protos: config.application_protos.clone(),
1940
1941 recv_count: 0,
1942 sent_count: 0,
1943 lost_count: 0,
1944 retrans_count: 0,
1945 dgram_sent_count: 0,
1946 dgram_recv_count: 0,
1947 sent_bytes: 0,
1948 recv_bytes: 0,
1949 acked_bytes: 0,
1950 lost_bytes: 0,
1951
1952 rx_data: 0,
1953 flow_control: flowcontrol::FlowControl::new(
1954 max_rx_data,
1955 cmp::min(max_rx_data / 2 * 3, DEFAULT_CONNECTION_WINDOW),
1956 config.max_connection_window,
1957 ),
1958 almost_full: false,
1959
1960 tx_cap: 0,
1961
1962 tx_buffered: 0,
1963
1964 tx_data: 0,
1965 max_tx_data: 0,
1966 last_tx_data: 0,
1967
1968 stream_retrans_bytes: 0,
1969
1970 streams: stream::StreamMap::new(
1971 config.local_transport_params.initial_max_streams_bidi,
1972 config.local_transport_params.initial_max_streams_uni,
1973 config.max_stream_window,
1974 ),
1975
1976 odcid: None,
1977
1978 rscid: None,
1979
1980 token: None,
1981
1982 local_error: None,
1983
1984 peer_error: None,
1985
1986 blocked_limit: None,
1987
1988 idle_timer: None,
1989
1990 draining_timer: None,
1991
1992 undecryptable_pkts: VecDeque::new(),
1993
1994 alpn: Vec::new(),
1995
1996 is_server,
1997
1998 derived_initial_secrets: false,
1999
2000 did_version_negotiation: false,
2001
2002 did_retry: false,
2003
2004 got_peer_conn_id: false,
2005
2006 peer_verified_initial_address: is_server,
2008
2009 parsed_peer_transport_params: false,
2010
2011 handshake_completed: false,
2012
2013 handshake_done_sent: false,
2014 handshake_done_acked: false,
2015
2016 handshake_confirmed: false,
2017
2018 key_phase: false,
2019
2020 ack_eliciting_sent: false,
2021
2022 closed: false,
2023
2024 timed_out: false,
2025
2026 grease: config.grease,
2027
2028 keylog: None,
2029
2030 #[cfg(feature = "qlog")]
2031 qlog: Default::default(),
2032
2033 dgram_recv_queue: dgram::DatagramQueue::new(
2034 config.dgram_recv_max_queue_len,
2035 ),
2036
2037 dgram_send_queue: dgram::DatagramQueue::new(
2038 config.dgram_send_max_queue_len,
2039 ),
2040
2041 emit_dgram: true,
2042
2043 disable_dcid_reuse: config.disable_dcid_reuse,
2044
2045 reset_stream_local_count: 0,
2046 stopped_stream_local_count: 0,
2047 reset_stream_remote_count: 0,
2048 stopped_stream_remote_count: 0,
2049
2050 max_amplification_factor: config.max_amplification_factor,
2051 };
2052
2053 if let Some(odcid) = odcid {
2054 conn.local_transport_params
2055 .original_destination_connection_id = Some(odcid.to_vec().into());
2056
2057 conn.local_transport_params.retry_source_connection_id =
2058 Some(conn.ids.get_scid(0)?.cid.to_vec().into());
2059
2060 conn.did_retry = true;
2061 }
2062
2063 conn.local_transport_params.initial_source_connection_id =
2064 Some(conn.ids.get_scid(0)?.cid.to_vec().into());
2065
2066 conn.handshake.init(is_server)?;
2067
2068 conn.handshake
2069 .use_legacy_codepoint(config.version != PROTOCOL_VERSION_V1);
2070
2071 conn.encode_transport_params()?;
2072
2073 if !is_server {
2076 let mut dcid = [0; 16];
2077 rand::rand_bytes(&mut dcid[..]);
2078
2079 let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2080 &dcid,
2081 conn.version,
2082 conn.is_server,
2083 false,
2084 )?;
2085
2086 let reset_token = conn.peer_transport_params.stateless_reset_token;
2087 conn.set_initial_dcid(
2088 dcid.to_vec().into(),
2089 reset_token,
2090 active_path_id,
2091 )?;
2092
2093 conn.pkt_num_spaces[packet::Epoch::Initial].crypto_open =
2094 Some(aead_open);
2095 conn.pkt_num_spaces[packet::Epoch::Initial].crypto_seal =
2096 Some(aead_seal);
2097
2098 conn.derived_initial_secrets = true;
2099 }
2100
2101 Ok(conn)
2102 }
2103
2104 #[inline]
2111 pub fn set_keylog(&mut self, writer: Box<dyn std::io::Write + Send + Sync>) {
2112 self.keylog = Some(writer);
2113 }
2114
2115 #[cfg(feature = "qlog")]
2125 #[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
2126 pub fn set_qlog(
2127 &mut self, writer: Box<dyn std::io::Write + Send + Sync>, title: String,
2128 description: String,
2129 ) {
2130 self.set_qlog_with_level(writer, title, description, QlogLevel::Base)
2131 }
2132
2133 #[cfg(feature = "qlog")]
2143 #[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
2144 pub fn set_qlog_with_level(
2145 &mut self, writer: Box<dyn std::io::Write + Send + Sync>, title: String,
2146 description: String, qlog_level: QlogLevel,
2147 ) {
2148 let vp = if self.is_server {
2149 qlog::VantagePointType::Server
2150 } else {
2151 qlog::VantagePointType::Client
2152 };
2153
2154 let level = match qlog_level {
2155 QlogLevel::Core => EventImportance::Core,
2156
2157 QlogLevel::Base => EventImportance::Base,
2158
2159 QlogLevel::Extra => EventImportance::Extra,
2160 };
2161
2162 self.qlog.level = level;
2163
2164 let trace = qlog::TraceSeq::new(
2165 qlog::VantagePoint {
2166 name: None,
2167 ty: vp,
2168 flow: None,
2169 },
2170 Some(title.to_string()),
2171 Some(description.to_string()),
2172 Some(qlog::Configuration {
2173 time_offset: Some(0.0),
2174 original_uris: None,
2175 }),
2176 None,
2177 );
2178
2179 let mut streamer = qlog::streamer::QlogStreamer::new(
2180 qlog::QLOG_VERSION.to_string(),
2181 Some(title),
2182 Some(description),
2183 None,
2184 time::Instant::now(),
2185 trace,
2186 self.qlog.level,
2187 writer,
2188 );
2189
2190 streamer.start_log().ok();
2191
2192 let ev_data = self
2193 .local_transport_params
2194 .to_qlog(TransportOwner::Local, self.handshake.cipher());
2195
2196 streamer.add_event(Event::with_time(0.0, ev_data)).ok();
2198
2199 self.qlog.streamer = Some(streamer);
2200 }
2201
2202 #[cfg(feature = "qlog")]
2204 #[cfg_attr(docsrs, doc(cfg(feature = "qlog")))]
2205 pub fn qlog_streamer(&mut self) -> Option<&mut qlog::streamer::QlogStreamer> {
2206 self.qlog.streamer.as_mut()
2207 }
2208
2209 #[inline]
2219 pub fn set_session(&mut self, session: &[u8]) -> Result<()> {
2220 let mut b = octets::Octets::with_slice(session);
2221
2222 let session_len = b.get_u64()? as usize;
2223 let session_bytes = b.get_bytes(session_len)?;
2224
2225 self.handshake.set_session(session_bytes.as_ref())?;
2226
2227 let raw_params_len = b.get_u64()? as usize;
2228 let raw_params_bytes = b.get_bytes(raw_params_len)?;
2229
2230 let peer_params = TransportParams::decode(
2231 raw_params_bytes.as_ref(),
2232 self.is_server,
2233 self.peer_transport_params_track_unknown,
2234 )?;
2235
2236 self.process_peer_transport_params(peer_params)?;
2237
2238 Ok(())
2239 }
2240
2241 pub fn set_max_idle_timeout(&mut self, v: u64) -> Result<()> {
2249 self.local_transport_params.max_idle_timeout = v;
2250
2251 self.encode_transport_params()
2252 }
2253
2254 #[cfg(feature = "boringssl-boring-crate")]
2264 #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2265 pub fn set_cc_algorithm_in_handshake(
2266 ssl: &mut boring::ssl::SslRef, algo: CongestionControlAlgorithm,
2267 ) -> Result<()> {
2268 let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2269
2270 ex_data.recovery_config.cc_algorithm = algo;
2271
2272 Ok(())
2273 }
2274
2275 #[cfg(feature = "boringssl-boring-crate")]
2285 #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2286 pub fn set_cc_algorithm_name_in_handshake(
2287 ssl: &mut boring::ssl::SslRef, name: &str,
2288 ) -> Result<()> {
2289 let cc_algo = CongestionControlAlgorithm::from_str(name)?;
2290 Self::set_cc_algorithm_in_handshake(ssl, cc_algo)
2291 }
2292
2293 #[cfg(feature = "boringssl-boring-crate")]
2303 #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2304 pub fn set_initial_congestion_window_packets_in_handshake(
2305 ssl: &mut boring::ssl::SslRef, packets: usize,
2306 ) -> Result<()> {
2307 let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2308
2309 ex_data.recovery_config.initial_congestion_window_packets = packets;
2310
2311 Ok(())
2312 }
2313
2314 #[cfg(feature = "boringssl-boring-crate")]
2324 #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2325 pub fn set_hystart_in_handshake(
2326 ssl: &mut boring::ssl::SslRef, v: bool,
2327 ) -> Result<()> {
2328 let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2329
2330 ex_data.recovery_config.hystart = v;
2331
2332 Ok(())
2333 }
2334
2335 #[cfg(feature = "boringssl-boring-crate")]
2345 #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2346 pub fn set_pacing_in_handshake(
2347 ssl: &mut boring::ssl::SslRef, v: bool,
2348 ) -> Result<()> {
2349 let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2350
2351 ex_data.recovery_config.pacing = v;
2352
2353 Ok(())
2354 }
2355
2356 #[cfg(feature = "boringssl-boring-crate")]
2366 #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2367 pub fn set_max_pacing_rate_in_handshake(
2368 ssl: &mut boring::ssl::SslRef, v: Option<u64>,
2369 ) -> Result<()> {
2370 let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2371
2372 ex_data.recovery_config.max_pacing_rate = v;
2373
2374 Ok(())
2375 }
2376
2377 #[cfg(feature = "boringssl-boring-crate")]
2387 #[cfg_attr(docsrs, doc(cfg(feature = "boringssl-boring-crate")))]
2388 pub fn set_max_send_udp_payload_size_in_handshake(
2389 ssl: &mut boring::ssl::SslRef, v: usize,
2390 ) -> Result<()> {
2391 let ex_data = tls::ExData::from_ssl_ref(ssl).ok_or(Error::TlsFail)?;
2392
2393 ex_data.recovery_config.max_send_udp_payload_size = v;
2394
2395 Ok(())
2396 }
2397
2398 pub fn recv(&mut self, buf: &mut [u8], info: RecvInfo) -> Result<usize> {
2441 let len = buf.len();
2442
2443 if len == 0 {
2444 return Err(Error::BufferTooShort);
2445 }
2446
2447 let recv_pid = self.paths.path_id_from_addrs(&(info.to, info.from));
2448
2449 if let Some(recv_pid) = recv_pid {
2450 let recv_path = self.paths.get_mut(recv_pid)?;
2451
2452 if self.is_server && !recv_path.verified_peer_address {
2464 recv_path.max_send_bytes += len * self.max_amplification_factor;
2465 }
2466 } else if !self.is_server {
2467 trace!(
2470 "{} client received packet from unknown address {:?}, dropping",
2471 self.trace_id,
2472 info,
2473 );
2474
2475 return Ok(len);
2476 }
2477
2478 let mut done = 0;
2479 let mut left = len;
2480
2481 while left > 0 {
2483 let read = match self.recv_single(
2484 &mut buf[len - left..len],
2485 &info,
2486 recv_pid,
2487 ) {
2488 Ok(v) => v,
2489
2490 Err(Error::Done) => {
2491 if self.is_stateless_reset(&buf[len - left..len]) {
2494 trace!("{} packet is a stateless reset", self.trace_id);
2495
2496 self.mark_closed();
2497 }
2498
2499 left
2500 },
2501
2502 Err(e) => {
2503 self.close(false, e.to_wire(), b"").ok();
2506 return Err(e);
2507 },
2508 };
2509
2510 done += read;
2511 left -= read;
2512 }
2513
2514 self.process_undecrypted_0rtt_packets()?;
2518
2519 Ok(done)
2520 }
2521
2522 fn process_undecrypted_0rtt_packets(&mut self) -> Result<()> {
2523 if self.pkt_num_spaces[packet::Epoch::Application]
2526 .crypto_0rtt_open
2527 .is_some()
2528 {
2529 while let Some((mut pkt, info)) = self.undecryptable_pkts.pop_front()
2530 {
2531 if let Err(e) = self.recv(&mut pkt, info) {
2532 self.undecryptable_pkts.clear();
2533
2534 return Err(e);
2535 }
2536 }
2537 }
2538 Ok(())
2539 }
2540
2541 fn is_stateless_reset(&self, buf: &[u8]) -> bool {
2543 let buf_len = buf.len();
2545 if buf_len < 21 {
2546 return false;
2547 }
2548
2549 match self.peer_transport_params.stateless_reset_token {
2552 Some(token) => {
2553 let token_len = 16;
2554
2555 crypto::verify_slices_are_equal(
2556 &token.to_be_bytes(),
2557 &buf[buf_len - token_len..buf_len],
2558 )
2559 .is_ok()
2560 },
2561
2562 None => false,
2563 }
2564 }
2565
2566 fn recv_single(
2581 &mut self, buf: &mut [u8], info: &RecvInfo, recv_pid: Option<usize>,
2582 ) -> Result<usize> {
2583 let now = time::Instant::now();
2584
2585 if buf.is_empty() {
2586 return Err(Error::Done);
2587 }
2588
2589 if self.is_closed() || self.is_draining() {
2590 return Err(Error::Done);
2591 }
2592
2593 let is_closing = self.local_error.is_some();
2594
2595 if is_closing {
2596 return Err(Error::Done);
2597 }
2598
2599 let buf_len = buf.len();
2600
2601 let mut b = octets::OctetsMut::with_slice(buf);
2602
2603 let mut hdr = Header::from_bytes(&mut b, self.source_id().len())
2604 .map_err(|e| {
2605 drop_pkt_on_err(
2606 e,
2607 self.recv_count,
2608 self.is_server,
2609 &self.trace_id,
2610 )
2611 })?;
2612
2613 if hdr.ty == packet::Type::VersionNegotiation {
2614 if self.is_server {
2616 return Err(Error::Done);
2617 }
2618
2619 if self.did_version_negotiation {
2621 return Err(Error::Done);
2622 }
2623
2624 if self.recv_count > 0 {
2627 return Err(Error::Done);
2628 }
2629
2630 if hdr.dcid != self.source_id() {
2631 return Err(Error::Done);
2632 }
2633
2634 if hdr.scid != self.destination_id() {
2635 return Err(Error::Done);
2636 }
2637
2638 trace!("{} rx pkt {:?}", self.trace_id, hdr);
2639
2640 let versions = hdr.versions.ok_or(Error::Done)?;
2641
2642 if versions.contains(&self.version) {
2645 return Err(Error::Done);
2646 }
2647
2648 let supported_versions =
2649 versions.iter().filter(|&&v| version_is_supported(v));
2650
2651 let mut found_version = false;
2652
2653 for &v in supported_versions {
2654 found_version = true;
2655
2656 if v == PROTOCOL_VERSION_V1 {
2658 self.version = v;
2659 break;
2660 }
2661
2662 self.version = cmp::max(self.version, v);
2663 }
2664
2665 if !found_version {
2666 return Err(Error::UnknownVersion);
2674 }
2675
2676 self.did_version_negotiation = true;
2677
2678 let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2680 &self.destination_id(),
2681 self.version,
2682 self.is_server,
2683 true,
2684 )?;
2685
2686 self.drop_epoch_state(packet::Epoch::Initial, now);
2688 self.got_peer_conn_id = false;
2689 self.handshake.clear()?;
2690
2691 self.pkt_num_spaces[packet::Epoch::Initial].crypto_open =
2692 Some(aead_open);
2693 self.pkt_num_spaces[packet::Epoch::Initial].crypto_seal =
2694 Some(aead_seal);
2695
2696 self.handshake
2697 .use_legacy_codepoint(self.version != PROTOCOL_VERSION_V1);
2698
2699 self.encode_transport_params()?;
2702
2703 return Err(Error::Done);
2704 }
2705
2706 if hdr.ty == packet::Type::Retry {
2707 if self.is_server {
2709 return Err(Error::Done);
2710 }
2711
2712 if self.did_retry {
2714 return Err(Error::Done);
2715 }
2716
2717 if packet::verify_retry_integrity(
2719 &b,
2720 &self.destination_id(),
2721 self.version,
2722 )
2723 .is_err()
2724 {
2725 return Err(Error::Done);
2726 }
2727
2728 trace!("{} rx pkt {:?}", self.trace_id, hdr);
2729
2730 self.token = hdr.token;
2731 self.did_retry = true;
2732
2733 self.odcid = Some(self.destination_id().into_owned());
2735
2736 self.set_initial_dcid(
2737 hdr.scid.clone(),
2738 None,
2739 self.paths.get_active_path_id()?,
2740 )?;
2741
2742 self.rscid = Some(self.destination_id().into_owned());
2743
2744 let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2746 &hdr.scid,
2747 self.version,
2748 self.is_server,
2749 true,
2750 )?;
2751
2752 self.drop_epoch_state(packet::Epoch::Initial, now);
2754 self.got_peer_conn_id = false;
2755 self.handshake.clear()?;
2756
2757 self.pkt_num_spaces[packet::Epoch::Initial].crypto_open =
2758 Some(aead_open);
2759 self.pkt_num_spaces[packet::Epoch::Initial].crypto_seal =
2760 Some(aead_seal);
2761
2762 return Err(Error::Done);
2763 }
2764
2765 if self.is_server && !self.did_version_negotiation {
2766 if !version_is_supported(hdr.version) {
2767 return Err(Error::UnknownVersion);
2768 }
2769
2770 self.version = hdr.version;
2771 self.did_version_negotiation = true;
2772
2773 self.handshake
2774 .use_legacy_codepoint(self.version != PROTOCOL_VERSION_V1);
2775
2776 self.encode_transport_params()?;
2779 }
2780
2781 if hdr.ty != packet::Type::Short && hdr.version != self.version {
2782 return Err(Error::Done);
2785 }
2786
2787 let payload_len = if hdr.ty == packet::Type::Short {
2790 b.cap()
2791 } else {
2792 b.get_varint().map_err(|e| {
2793 drop_pkt_on_err(
2794 e.into(),
2795 self.recv_count,
2796 self.is_server,
2797 &self.trace_id,
2798 )
2799 })? as usize
2800 };
2801
2802 if payload_len > b.cap() {
2805 return Err(drop_pkt_on_err(
2806 Error::InvalidPacket,
2807 self.recv_count,
2808 self.is_server,
2809 &self.trace_id,
2810 ));
2811 }
2812
2813 if !self.derived_initial_secrets {
2815 let (aead_open, aead_seal) = crypto::derive_initial_key_material(
2816 &hdr.dcid,
2817 self.version,
2818 self.is_server,
2819 false,
2820 )?;
2821
2822 self.pkt_num_spaces[packet::Epoch::Initial].crypto_open =
2823 Some(aead_open);
2824 self.pkt_num_spaces[packet::Epoch::Initial].crypto_seal =
2825 Some(aead_seal);
2826
2827 self.derived_initial_secrets = true;
2828 }
2829
2830 let epoch = hdr.ty.to_epoch()?;
2832
2833 let aead = if hdr.ty == packet::Type::ZeroRTT {
2835 self.pkt_num_spaces[epoch].crypto_0rtt_open.as_ref()
2837 } else {
2838 self.pkt_num_spaces[epoch].crypto_open.as_ref()
2840 };
2841
2842 let mut aead = match aead {
2844 Some(v) => v,
2845
2846 None => {
2847 if hdr.ty == packet::Type::ZeroRTT &&
2848 self.undecryptable_pkts.len() < MAX_UNDECRYPTABLE_PACKETS &&
2849 !self.is_established()
2850 {
2851 let pkt_len = b.off() + payload_len;
2857 let pkt = (b.buf()[..pkt_len]).to_vec();
2858
2859 self.undecryptable_pkts.push_back((pkt, *info));
2860 return Ok(pkt_len);
2861 }
2862
2863 let e = drop_pkt_on_err(
2864 Error::CryptoFail,
2865 self.recv_count,
2866 self.is_server,
2867 &self.trace_id,
2868 );
2869
2870 return Err(e);
2871 },
2872 };
2873
2874 let aead_tag_len = aead.alg().tag_len();
2875
2876 packet::decrypt_hdr(&mut b, &mut hdr, aead).map_err(|e| {
2877 drop_pkt_on_err(e, self.recv_count, self.is_server, &self.trace_id)
2878 })?;
2879
2880 let pn = packet::decode_pkt_num(
2881 self.pkt_num_spaces[epoch].largest_rx_pkt_num,
2882 hdr.pkt_num,
2883 hdr.pkt_num_len,
2884 );
2885
2886 let pn_len = hdr.pkt_num_len;
2887
2888 trace!(
2889 "{} rx pkt {:?} len={} pn={} {}",
2890 self.trace_id,
2891 hdr,
2892 payload_len,
2893 pn,
2894 AddrTupleFmt(info.from, info.to)
2895 );
2896
2897 #[cfg(feature = "qlog")]
2898 let mut qlog_frames = vec![];
2899
2900 let mut aead_next = None;
2902
2903 if self.handshake_confirmed &&
2904 hdr.ty != Type::ZeroRTT &&
2905 hdr.key_phase != self.key_phase
2906 {
2907 if let Some(key_update) = self.pkt_num_spaces[epoch]
2909 .key_update
2910 .as_ref()
2911 .and_then(|key_update| {
2912 (pn < key_update.pn_on_update).then_some(key_update)
2913 })
2914 {
2915 aead = &key_update.crypto_open;
2916 } else {
2917 trace!("{} peer-initiated key update", self.trace_id);
2918
2919 aead_next = Some((
2920 self.pkt_num_spaces[epoch]
2921 .crypto_open
2922 .as_ref()
2923 .unwrap()
2924 .derive_next_packet_key()?,
2925 self.pkt_num_spaces[epoch]
2926 .crypto_seal
2927 .as_ref()
2928 .unwrap()
2929 .derive_next_packet_key()?,
2930 ));
2931
2932 aead = &aead_next.as_ref().unwrap().0;
2935 }
2936 }
2937
2938 let mut payload = packet::decrypt_pkt(
2939 &mut b,
2940 pn,
2941 pn_len,
2942 payload_len,
2943 aead,
2944 )
2945 .map_err(|e| {
2946 drop_pkt_on_err(e, self.recv_count, self.is_server, &self.trace_id)
2947 })?;
2948
2949 if self.pkt_num_spaces[epoch].recv_pkt_num.contains(pn) {
2950 trace!("{} ignored duplicate packet {}", self.trace_id, pn);
2951 return Err(Error::Done);
2952 }
2953
2954 if payload.cap() == 0 {
2956 return Err(Error::InvalidPacket);
2957 }
2958
2959 let recv_pid = if hdr.ty == packet::Type::Short && self.got_peer_conn_id {
2962 let pkt_dcid = ConnectionId::from_ref(&hdr.dcid);
2963 self.get_or_create_recv_path_id(recv_pid, &pkt_dcid, buf_len, info)?
2964 } else {
2965 self.paths.get_active_path_id()?
2967 };
2968
2969 if let Some((open_next, seal_next)) = aead_next {
2972 if !self.pkt_num_spaces[epoch]
2973 .key_update
2974 .as_ref()
2975 .map_or(true, |prev| prev.update_acked)
2976 {
2977 return Err(Error::KeyUpdate);
2979 }
2980
2981 trace!("{} key update verified", self.trace_id);
2982
2983 let _ = self.pkt_num_spaces[epoch].crypto_seal.replace(seal_next);
2984
2985 let open_prev = self.pkt_num_spaces[epoch]
2986 .crypto_open
2987 .replace(open_next)
2988 .unwrap();
2989
2990 let recv_path = self.paths.get_mut(recv_pid)?;
2991
2992 self.pkt_num_spaces[epoch].key_update = Some(packet::KeyUpdate {
2993 crypto_open: open_prev,
2994 pn_on_update: pn,
2995 update_acked: false,
2996 timer: now + (recv_path.recovery.pto() * 3),
2997 });
2998
2999 self.key_phase = !self.key_phase;
3000
3001 qlog_with_type!(QLOG_PACKET_RX, self.qlog, q, {
3002 let trigger = Some(
3003 qlog::events::security::KeyUpdateOrRetiredTrigger::RemoteUpdate,
3004 );
3005
3006 let ev_data_client =
3007 EventData::KeyUpdated(qlog::events::security::KeyUpdated {
3008 key_type:
3009 qlog::events::security::KeyType::Client1RttSecret,
3010 trigger: trigger.clone(),
3011 ..Default::default()
3012 });
3013
3014 q.add_event_data_with_instant(ev_data_client, now).ok();
3015
3016 let ev_data_server =
3017 EventData::KeyUpdated(qlog::events::security::KeyUpdated {
3018 key_type:
3019 qlog::events::security::KeyType::Server1RttSecret,
3020 trigger,
3021 ..Default::default()
3022 });
3023
3024 q.add_event_data_with_instant(ev_data_server, now).ok();
3025 });
3026 }
3027
3028 if !self.is_server && !self.got_peer_conn_id {
3029 if self.odcid.is_none() {
3030 self.odcid = Some(self.destination_id().into_owned());
3031 }
3032
3033 self.set_initial_dcid(
3036 hdr.scid.clone(),
3037 self.peer_transport_params.stateless_reset_token,
3038 recv_pid,
3039 )?;
3040
3041 self.got_peer_conn_id = true;
3042 }
3043
3044 if self.is_server && !self.got_peer_conn_id {
3045 self.set_initial_dcid(hdr.scid.clone(), None, recv_pid)?;
3046
3047 if !self.did_retry {
3048 self.local_transport_params
3049 .original_destination_connection_id =
3050 Some(hdr.dcid.to_vec().into());
3051
3052 self.encode_transport_params()?;
3053 }
3054
3055 self.got_peer_conn_id = true;
3056 }
3057
3058 let mut ack_elicited = false;
3062
3063 let mut frame_processing_err = None;
3066
3067 let mut probing = true;
3070
3071 while payload.cap() > 0 {
3073 let frame = frame::Frame::from_bytes(&mut payload, hdr.ty)?;
3074
3075 qlog_with_type!(QLOG_PACKET_RX, self.qlog, _q, {
3076 qlog_frames.push(frame.to_qlog());
3077 });
3078
3079 if frame.ack_eliciting() {
3080 ack_elicited = true;
3081 }
3082
3083 if !frame.probing() {
3084 probing = false;
3085 }
3086
3087 if let Err(e) = self.process_frame(frame, &hdr, recv_pid, epoch, now)
3088 {
3089 frame_processing_err = Some(e);
3090 break;
3091 }
3092 }
3093
3094 qlog_with_type!(QLOG_PACKET_RX, self.qlog, q, {
3095 let packet_size = b.len();
3096
3097 let qlog_pkt_hdr = qlog::events::quic::PacketHeader::with_type(
3098 hdr.ty.to_qlog(),
3099 Some(pn),
3100 Some(hdr.version),
3101 Some(&hdr.scid),
3102 Some(&hdr.dcid),
3103 );
3104
3105 let qlog_raw_info = RawInfo {
3106 length: Some(packet_size as u64),
3107 payload_length: Some(payload_len as u64),
3108 data: None,
3109 };
3110
3111 let ev_data =
3112 EventData::PacketReceived(qlog::events::quic::PacketReceived {
3113 header: qlog_pkt_hdr,
3114 frames: Some(qlog_frames),
3115 raw: Some(qlog_raw_info),
3116 ..Default::default()
3117 });
3118
3119 q.add_event_data_with_instant(ev_data, now).ok();
3120 });
3121
3122 qlog_with_type!(QLOG_PACKET_RX, self.qlog, q, {
3123 let recv_path = self.paths.get_mut(recv_pid)?;
3124 if let Some(ev_data) = recv_path.recovery.maybe_qlog() {
3125 q.add_event_data_with_instant(ev_data, now).ok();
3126 }
3127 });
3128
3129 if let Some(e) = frame_processing_err {
3130 return Err(e);
3132 }
3133
3134 if self.is_established() {
3138 qlog_with_type!(QLOG_PARAMS_SET, self.qlog, q, {
3139 if !self.qlog.logged_peer_params {
3140 let ev_data = self
3141 .peer_transport_params
3142 .to_qlog(TransportOwner::Remote, self.handshake.cipher());
3143
3144 q.add_event_data_with_instant(ev_data, now).ok();
3145
3146 self.qlog.logged_peer_params = true;
3147 }
3148 });
3149 }
3150
3151 let mut pmtud_probe = false;
3153
3154 for (_, p) in self.paths.iter_mut() {
3157 for acked in p.recovery.get_acked_frames(epoch) {
3158 match acked {
3159 frame::Frame::Ping {
3160 mtu_probe: Some(mtu_probe),
3161 } => {
3162 let pmtud_next = p.pmtud.get_current();
3163 p.pmtud.set_current(cmp::max(pmtud_next, mtu_probe));
3164
3165 p.pmtud.should_probe(false);
3167 pmtud_probe = true;
3168
3169 trace!(
3170 "{} pmtud acked; pmtu size {:?}",
3171 self.trace_id,
3172 p.pmtud.get_current()
3173 );
3174 },
3175
3176 frame::Frame::ACK { ranges, .. } => {
3177 if let Some(largest_acked) = ranges.last() {
3181 self.pkt_num_spaces[epoch]
3182 .recv_pkt_need_ack
3183 .remove_until(largest_acked);
3184 }
3185 },
3186
3187 frame::Frame::CryptoHeader { offset, length } => {
3188 self.pkt_num_spaces[epoch]
3189 .crypto_stream
3190 .send
3191 .ack_and_drop(offset, length);
3192 },
3193
3194 frame::Frame::StreamHeader {
3195 stream_id,
3196 offset,
3197 length,
3198 ..
3199 } => {
3200 let stream = match self.streams.get_mut(stream_id) {
3201 Some(v) => v,
3202
3203 None => continue,
3204 };
3205
3206 stream.send.ack_and_drop(offset, length);
3207
3208 self.tx_buffered =
3209 self.tx_buffered.saturating_sub(length);
3210
3211 qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
3212 let ev_data = EventData::DataMoved(
3213 qlog::events::quic::DataMoved {
3214 stream_id: Some(stream_id),
3215 offset: Some(offset),
3216 length: Some(length as u64),
3217 from: Some(DataRecipient::Transport),
3218 to: Some(DataRecipient::Dropped),
3219 ..Default::default()
3220 },
3221 );
3222
3223 q.add_event_data_with_instant(ev_data, now).ok();
3224 });
3225
3226 if stream.is_complete() && !stream.is_readable() {
3230 let local = stream.local;
3231 self.streams.collect(stream_id, local);
3232 }
3233 },
3234
3235 frame::Frame::HandshakeDone => {
3236 self.handshake_done_sent = true;
3239
3240 self.handshake_done_acked = true;
3241 },
3242
3243 frame::Frame::ResetStream { stream_id, .. } => {
3244 let stream = match self.streams.get_mut(stream_id) {
3245 Some(v) => v,
3246
3247 None => continue,
3248 };
3249
3250 if stream.is_complete() && !stream.is_readable() {
3254 let local = stream.local;
3255 self.streams.collect(stream_id, local);
3256 }
3257 },
3258
3259 _ => (),
3260 }
3261 }
3262
3263 if pmtud_probe {
3265 trace!(
3266 "{} updating pmtu {:?}",
3267 p.pmtud.get_current(),
3268 self.trace_id
3269 );
3270
3271 qlog_with_type!(
3272 EventType::ConnectivityEventType(
3273 ConnectivityEventType::MtuUpdated
3274 ),
3275 self.qlog,
3276 q,
3277 {
3278 let pmtu_data = EventData::MtuUpdated(
3279 qlog::events::connectivity::MtuUpdated {
3280 old: Some(p.recovery.max_datagram_size() as u16),
3281 new: p.pmtud.get_current() as u16,
3282 done: Some(pmtud_probe),
3283 },
3284 );
3285
3286 q.add_event_data_with_instant(pmtu_data, now).ok();
3287 }
3288 );
3289
3290 p.recovery
3291 .pmtud_update_max_datagram_size(p.pmtud.get_current());
3292 }
3293 }
3294
3295 let no_dcid = self
3298 .paths
3299 .iter_mut()
3300 .filter(|(_, p)| p.active_dcid_seq.is_none());
3301
3302 for (pid, p) in no_dcid {
3303 if self.ids.zero_length_dcid() {
3304 p.active_dcid_seq = Some(0);
3305 continue;
3306 }
3307
3308 let dcid_seq = match self.ids.lowest_available_dcid_seq() {
3309 Some(seq) => seq,
3310 None => break,
3311 };
3312
3313 self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
3314
3315 p.active_dcid_seq = Some(dcid_seq);
3316 }
3317
3318 if self.pkt_num_spaces[epoch].recv_pkt_need_ack.last() < Some(pn) {
3321 self.pkt_num_spaces[epoch].largest_rx_pkt_time = now;
3322 }
3323
3324 self.pkt_num_spaces[epoch].recv_pkt_num.insert(pn);
3325
3326 self.pkt_num_spaces[epoch].recv_pkt_need_ack.push_item(pn);
3327
3328 self.pkt_num_spaces[epoch].ack_elicited =
3329 cmp::max(self.pkt_num_spaces[epoch].ack_elicited, ack_elicited);
3330
3331 self.pkt_num_spaces[epoch].largest_rx_pkt_num =
3332 cmp::max(self.pkt_num_spaces[epoch].largest_rx_pkt_num, pn);
3333
3334 if !probing {
3335 self.pkt_num_spaces[epoch].largest_rx_non_probing_pkt_num = cmp::max(
3336 self.pkt_num_spaces[epoch].largest_rx_non_probing_pkt_num,
3337 pn,
3338 );
3339
3340 let active_path_id = self.paths.get_active_path_id()?;
3342
3343 if self.is_server &&
3344 recv_pid != active_path_id &&
3345 self.pkt_num_spaces[epoch].largest_rx_non_probing_pkt_num == pn
3346 {
3347 self.on_peer_migrated(recv_pid, self.disable_dcid_reuse, now)?;
3348 }
3349 }
3350
3351 if let Some(idle_timeout) = self.idle_timeout() {
3352 self.idle_timer = Some(now + idle_timeout);
3353 }
3354
3355 self.update_tx_cap();
3357
3358 self.recv_count += 1;
3359 self.paths.get_mut(recv_pid)?.recv_count += 1;
3360
3361 let read = b.off() + aead_tag_len;
3362
3363 self.recv_bytes += read as u64;
3364 self.paths.get_mut(recv_pid)?.recv_bytes += read as u64;
3365
3366 if self.is_server && hdr.ty == packet::Type::Handshake {
3370 self.drop_epoch_state(packet::Epoch::Initial, now);
3371
3372 self.paths.get_mut(recv_pid)?.verified_peer_address = true;
3373 }
3374
3375 self.ack_eliciting_sent = false;
3376
3377 Ok(read)
3378 }
3379
3380 pub fn send(&mut self, out: &mut [u8]) -> Result<(usize, SendInfo)> {
3442 self.send_on_path(out, None, None)
3443 }
3444
3445 pub fn send_on_path(
3529 &mut self, out: &mut [u8], from: Option<SocketAddr>,
3530 to: Option<SocketAddr>,
3531 ) -> Result<(usize, SendInfo)> {
3532 if out.is_empty() {
3533 return Err(Error::BufferTooShort);
3534 }
3535
3536 if self.is_closed() || self.is_draining() {
3537 return Err(Error::Done);
3538 }
3539
3540 let now = time::Instant::now();
3541
3542 if self.local_error.is_none() {
3543 self.do_handshake(now)?;
3544 }
3545
3546 let _ = self.process_undecrypted_0rtt_packets();
3553
3554 if !self.derived_initial_secrets {
3557 return Err(Error::Done);
3558 }
3559
3560 let mut has_initial = false;
3561
3562 let mut done = 0;
3563
3564 let mut left = cmp::min(out.len(), self.max_send_udp_payload_size());
3567
3568 let send_pid = match (from, to) {
3569 (Some(f), Some(t)) => self
3570 .paths
3571 .path_id_from_addrs(&(f, t))
3572 .ok_or(Error::InvalidState)?,
3573
3574 _ => self.get_send_path_id(from, to)?,
3575 };
3576
3577 let send_path = self.paths.get_mut(send_pid)?;
3578
3579 if send_path.pmtud.get_probe_status() {
3581 let size = if self.handshake_confirmed || self.handshake_done_sent {
3582 send_path.pmtud.get_probe_size()
3583 } else {
3584 send_path.pmtud.get_current()
3585 };
3586
3587 send_path.recovery.pmtud_update_max_datagram_size(size);
3588
3589 left = cmp::min(out.len(), send_path.recovery.max_datagram_size());
3590 }
3591
3592 if !send_path.verified_peer_address && self.is_server {
3595 left = cmp::min(left, send_path.max_send_bytes);
3596 }
3597
3598 while left > 0 {
3600 let (ty, written) = match self.send_single(
3601 &mut out[done..done + left],
3602 send_pid,
3603 has_initial,
3604 now,
3605 ) {
3606 Ok(v) => v,
3607
3608 Err(Error::BufferTooShort) | Err(Error::Done) => break,
3609
3610 Err(e) => return Err(e),
3611 };
3612
3613 done += written;
3614 left -= written;
3615
3616 match ty {
3617 packet::Type::Initial => has_initial = true,
3618
3619 packet::Type::Short => break,
3621
3622 _ => (),
3623 };
3624
3625 if let Ok(epoch) = ty.to_epoch() {
3628 if self.paths.get_mut(send_pid)?.recovery.loss_probes(epoch) > 0 {
3629 break;
3630 }
3631 }
3632
3633 if !(from.is_some() && to.is_some()) &&
3635 self.get_send_path_id(from, to)? != send_pid
3636 {
3637 break;
3638 }
3639 }
3640
3641 if done == 0 {
3642 self.last_tx_data = self.tx_data;
3643
3644 return Err(Error::Done);
3645 }
3646
3647 #[cfg(not(feature = "fuzzing"))]
3649 if has_initial && left > 0 && done < MIN_CLIENT_INITIAL_LEN {
3650 let pad_len = cmp::min(left, MIN_CLIENT_INITIAL_LEN - done);
3651
3652 out[done..done + pad_len].fill(0);
3655
3656 done += pad_len;
3657 }
3658
3659 let send_path = self.paths.get(send_pid)?;
3660
3661 let info = SendInfo {
3662 from: send_path.local_addr(),
3663 to: send_path.peer_addr(),
3664
3665 at: send_path.recovery.get_packet_send_time(),
3666 };
3667
3668 Ok((done, info))
3669 }
3670
3671 fn send_single(
3672 &mut self, out: &mut [u8], send_pid: usize, has_initial: bool,
3673 now: time::Instant,
3674 ) -> Result<(packet::Type, usize)> {
3675 if out.is_empty() {
3676 return Err(Error::BufferTooShort);
3677 }
3678
3679 if self.is_draining() {
3680 return Err(Error::Done);
3681 }
3682
3683 let is_closing = self.local_error.is_some();
3684
3685 let out_len = out.len();
3686
3687 let mut b = octets::OctetsMut::with_slice(out);
3688
3689 let pkt_type = self.write_pkt_type(send_pid)?;
3690
3691 let max_dgram_len = if !self.dgram_send_queue.is_empty() {
3692 self.dgram_max_writable_len()
3693 } else {
3694 None
3695 };
3696
3697 let epoch = pkt_type.to_epoch()?;
3698 let pkt_space = &mut self.pkt_num_spaces[epoch];
3699
3700 for (_, p) in self.paths.iter_mut() {
3702 for lost in p.recovery.get_lost_frames(epoch) {
3703 match lost {
3704 frame::Frame::CryptoHeader { offset, length } => {
3705 pkt_space.crypto_stream.send.retransmit(offset, length);
3706
3707 self.stream_retrans_bytes += length as u64;
3708 p.stream_retrans_bytes += length as u64;
3709
3710 self.retrans_count += 1;
3711 p.retrans_count += 1;
3712 },
3713
3714 frame::Frame::StreamHeader {
3715 stream_id,
3716 offset,
3717 length,
3718 fin,
3719 } => {
3720 let stream = match self.streams.get_mut(stream_id) {
3721 Some(v) => v,
3722
3723 None => continue,
3724 };
3725
3726 let was_flushable = stream.is_flushable();
3727
3728 let empty_fin = length == 0 && fin;
3729
3730 stream.send.retransmit(offset, length);
3731
3732 if (stream.is_flushable() || empty_fin) && !was_flushable
3740 {
3741 let priority_key = Arc::clone(&stream.priority_key);
3742 self.streams.insert_flushable(&priority_key);
3743 }
3744
3745 self.stream_retrans_bytes += length as u64;
3746 p.stream_retrans_bytes += length as u64;
3747
3748 self.retrans_count += 1;
3749 p.retrans_count += 1;
3750 },
3751
3752 frame::Frame::ACK { .. } => {
3753 pkt_space.ack_elicited = true;
3754 },
3755
3756 frame::Frame::ResetStream {
3757 stream_id,
3758 error_code,
3759 final_size,
3760 } =>
3761 if self.streams.get(stream_id).is_some() {
3762 self.streams
3763 .insert_reset(stream_id, error_code, final_size);
3764 },
3765
3766 frame::Frame::HandshakeDone if !self.handshake_done_acked => {
3769 self.handshake_done_sent = false;
3770 },
3771
3772 frame::Frame::MaxStreamData { stream_id, .. } => {
3773 if self.streams.get(stream_id).is_some() {
3774 self.streams.insert_almost_full(stream_id);
3775 }
3776 },
3777
3778 frame::Frame::MaxData { .. } => {
3779 self.almost_full = true;
3780 },
3781
3782 frame::Frame::NewConnectionId { seq_num, .. } => {
3783 self.ids.mark_advertise_new_scid_seq(seq_num, true);
3784 },
3785
3786 frame::Frame::RetireConnectionId { seq_num } => {
3787 self.ids.mark_retire_dcid_seq(seq_num, true)?;
3788 },
3789
3790 frame::Frame::Ping { mtu_probe } if mtu_probe.is_some() => {
3791 p.pmtud.pmtu_probe_lost();
3792 },
3793
3794 _ => (),
3795 }
3796 }
3797 }
3798
3799 let is_app_limited = self.delivery_rate_check_if_app_limited();
3800 let n_paths = self.paths.len();
3801 let path = self.paths.get_mut(send_pid)?;
3802 let flow_control = &mut self.flow_control;
3803 let pkt_space = &mut self.pkt_num_spaces[epoch];
3804
3805 let mut left = if path.pmtud.is_enabled() {
3806 cmp::min(path.pmtud.get_current(), b.cap())
3808 } else {
3809 b.cap()
3810 };
3811
3812 let pn = self.next_pkt_num;
3813 let largest_acked_pkt =
3814 path.recovery.get_largest_acked_on_epoch(epoch).unwrap_or(0);
3815 let pn_len = packet::pkt_num_len(pn, largest_acked_pkt);
3816
3817 let crypto_overhead = pkt_space.crypto_overhead().ok_or(Error::Done)?;
3819
3820 let dcid_seq = path.active_dcid_seq.ok_or(Error::OutOfIdentifiers)?;
3821
3822 let dcid =
3823 ConnectionId::from_ref(self.ids.get_dcid(dcid_seq)?.cid.as_ref());
3824
3825 let scid = if let Some(scid_seq) = path.active_scid_seq {
3826 ConnectionId::from_ref(self.ids.get_scid(scid_seq)?.cid.as_ref())
3827 } else if pkt_type == packet::Type::Short {
3828 ConnectionId::default()
3829 } else {
3830 return Err(Error::InvalidState);
3831 };
3832
3833 let hdr = Header {
3834 ty: pkt_type,
3835
3836 version: self.version,
3837
3838 dcid,
3839 scid,
3840
3841 pkt_num: 0,
3842 pkt_num_len: pn_len,
3843
3844 token: if pkt_type == packet::Type::Initial {
3848 self.token.clone()
3849 } else {
3850 None
3851 },
3852
3853 versions: None,
3854 key_phase: self.key_phase,
3855 };
3856
3857 hdr.to_bytes(&mut b)?;
3858
3859 let hdr_trace = if log::max_level() == log::LevelFilter::Trace {
3860 Some(format!("{hdr:?}"))
3861 } else {
3862 None
3863 };
3864
3865 let hdr_ty = hdr.ty;
3866
3867 #[cfg(feature = "qlog")]
3868 let qlog_pkt_hdr = self.qlog.streamer.as_ref().map(|_q| {
3869 qlog::events::quic::PacketHeader::with_type(
3870 hdr.ty.to_qlog(),
3871 Some(pn),
3872 Some(hdr.version),
3873 Some(&hdr.scid),
3874 Some(&hdr.dcid),
3875 )
3876 });
3877
3878 let mut overhead = b.off() + pn_len + crypto_overhead;
3881
3882 if pkt_type != packet::Type::Short {
3885 overhead += PAYLOAD_LENGTH_LEN;
3886 }
3887
3888 match left.checked_sub(overhead) {
3890 Some(v) => left = v,
3891
3892 None => {
3893 path.recovery.update_app_limited(false);
3900 return Err(Error::Done);
3901 },
3902 }
3903
3904 if left < PAYLOAD_MIN_LEN {
3906 path.recovery.update_app_limited(false);
3907 return Err(Error::Done);
3908 }
3909
3910 let mut frames: SmallVec<[frame::Frame; 1]> = SmallVec::new();
3911
3912 let mut ack_eliciting = false;
3913 let mut in_flight = false;
3914 let mut pmtud_probe = false;
3916 let mut has_data = false;
3917
3918 let ack_elicit_required = path.recovery.should_elicit_ack(epoch);
3921
3922 let header_offset = b.off();
3923
3924 if pkt_type != packet::Type::Short {
3929 b.skip(PAYLOAD_LENGTH_LEN)?;
3930 }
3931
3932 packet::encode_pkt_num(pn, pn_len, &mut b)?;
3933
3934 let payload_offset = b.off();
3935
3936 let cwnd_available =
3937 path.recovery.cwnd_available().saturating_sub(overhead);
3938
3939 let left_before_packing_ack_frame = left;
3940
3941 if pkt_space.recv_pkt_need_ack.len() > 0 &&
3948 (pkt_space.ack_elicited || ack_elicit_required) &&
3949 (!is_closing ||
3950 (pkt_type == Type::Handshake &&
3951 self.local_error
3952 .as_ref()
3953 .is_some_and(|le| le.is_app))) &&
3954 path.active()
3955 {
3956 let ack_delay = pkt_space.largest_rx_pkt_time.elapsed();
3957
3958 let ack_delay = ack_delay.as_micros() as u64 /
3959 2_u64
3960 .pow(self.local_transport_params.ack_delay_exponent as u32);
3961
3962 let frame = frame::Frame::ACK {
3963 ack_delay,
3964 ranges: pkt_space.recv_pkt_need_ack.clone(),
3965 ecn_counts: None, };
3967
3968 if pkt_space.ack_elicited || frame.wire_len() < cwnd_available {
3973 if push_frame_to_pkt!(b, frames, frame, left) {
3977 pkt_space.ack_elicited = false;
3978 }
3979 }
3980 }
3981
3982 left = cmp::min(
3984 left,
3985 cwnd_available.saturating_sub(left_before_packing_ack_frame - left),
3987 );
3988
3989 let mut challenge_data = None;
3990
3991 let active_path = self.paths.get_active_mut()?;
3992
3993 if pkt_type == packet::Type::Short {
3994 let pmtu_probe = active_path.should_send_pmtu_probe(
4007 self.handshake_confirmed,
4008 self.handshake_done_sent,
4009 out_len,
4010 is_closing,
4011 frames.is_empty(),
4012 );
4013
4014 trace!("{} pmtud probe status {} hs_con={} hs_sent={} cwnd_avail={} out_len={} left={}", self.trace_id, pmtu_probe, self.handshake_confirmed, self.handshake_done_sent,
4015 active_path.recovery.cwnd_available(), out_len, left);
4016
4017 if pmtu_probe {
4018 trace!(
4019 "{} sending pmtud probe pmtu_probe={} next_size={} pmtu={}",
4020 self.trace_id,
4021 active_path.pmtud.get_probe_size(),
4022 active_path.pmtud.get_probe_status(),
4023 active_path.pmtud.get_current(),
4024 );
4025
4026 left = active_path.pmtud.get_probe_size();
4027
4028 match left.checked_sub(overhead) {
4029 Some(v) => left = v,
4030
4031 None => {
4032 active_path.recovery.update_app_limited(false);
4041 return Err(Error::Done);
4042 },
4043 }
4044
4045 let frame = frame::Frame::Padding {
4046 len: active_path.pmtud.get_probe_size() - overhead - 1,
4047 };
4048
4049 if push_frame_to_pkt!(b, frames, frame, left) {
4050 let frame = frame::Frame::Ping {
4051 mtu_probe: Some(active_path.pmtud.get_probe_size()),
4052 };
4053
4054 if push_frame_to_pkt!(b, frames, frame, left) {
4055 ack_eliciting = true;
4056 in_flight = true;
4057 }
4058 }
4059
4060 pmtud_probe = true;
4061 }
4062
4063 let path = self.paths.get_mut(send_pid)?;
4064 while let Some(challenge) = path.pop_received_challenge() {
4067 let frame = frame::Frame::PathResponse { data: challenge };
4068
4069 if push_frame_to_pkt!(b, frames, frame, left) {
4070 ack_eliciting = true;
4071 in_flight = true;
4072 } else {
4073 break;
4076 }
4077 }
4078
4079 if path.validation_requested() {
4081 let data = rand::rand_u64().to_be_bytes();
4083
4084 let frame = frame::Frame::PathChallenge { data };
4085
4086 if push_frame_to_pkt!(b, frames, frame, left) {
4087 challenge_data = Some(data);
4089
4090 ack_eliciting = true;
4091 in_flight = true;
4092 }
4093 }
4094
4095 if let Some(key_update) = pkt_space.key_update.as_mut() {
4096 key_update.update_acked = true;
4097 }
4098 }
4099
4100 let path = self.paths.get_mut(send_pid)?;
4101
4102 if pkt_type == packet::Type::Short && !is_closing {
4103 while let Some(seq_num) = self.ids.next_advertise_new_scid_seq() {
4105 let frame = self.ids.get_new_connection_id_frame_for(seq_num)?;
4106
4107 if push_frame_to_pkt!(b, frames, frame, left) {
4108 self.ids.mark_advertise_new_scid_seq(seq_num, false);
4109
4110 ack_eliciting = true;
4111 in_flight = true;
4112 } else {
4113 break;
4114 }
4115 }
4116 }
4117
4118 if pkt_type == packet::Type::Short && !is_closing && path.active() {
4119 if self.handshake_completed &&
4122 !self.handshake_done_sent &&
4123 self.is_server
4124 {
4125 let frame = frame::Frame::HandshakeDone;
4126
4127 if push_frame_to_pkt!(b, frames, frame, left) {
4128 self.handshake_done_sent = true;
4129
4130 ack_eliciting = true;
4131 in_flight = true;
4132 }
4133 }
4134
4135 if self.streams.should_update_max_streams_bidi() {
4137 let frame = frame::Frame::MaxStreamsBidi {
4138 max: self.streams.max_streams_bidi_next(),
4139 };
4140
4141 if push_frame_to_pkt!(b, frames, frame, left) {
4142 self.streams.update_max_streams_bidi();
4143
4144 ack_eliciting = true;
4145 in_flight = true;
4146 }
4147 }
4148
4149 if self.streams.should_update_max_streams_uni() {
4151 let frame = frame::Frame::MaxStreamsUni {
4152 max: self.streams.max_streams_uni_next(),
4153 };
4154
4155 if push_frame_to_pkt!(b, frames, frame, left) {
4156 self.streams.update_max_streams_uni();
4157
4158 ack_eliciting = true;
4159 in_flight = true;
4160 }
4161 }
4162
4163 if let Some(limit) = self.blocked_limit {
4165 let frame = frame::Frame::DataBlocked { limit };
4166
4167 if push_frame_to_pkt!(b, frames, frame, left) {
4168 self.blocked_limit = None;
4169
4170 ack_eliciting = true;
4171 in_flight = true;
4172 }
4173 }
4174
4175 for stream_id in self.streams.almost_full() {
4177 let stream = match self.streams.get_mut(stream_id) {
4178 Some(v) => v,
4179
4180 None => {
4181 self.streams.remove_almost_full(stream_id);
4184 continue;
4185 },
4186 };
4187
4188 stream.recv.autotune_window(now, path.recovery.rtt());
4190
4191 let frame = frame::Frame::MaxStreamData {
4192 stream_id,
4193 max: stream.recv.max_data_next(),
4194 };
4195
4196 if push_frame_to_pkt!(b, frames, frame, left) {
4197 let recv_win = stream.recv.window();
4198
4199 stream.recv.update_max_data(now);
4200
4201 self.streams.remove_almost_full(stream_id);
4202
4203 ack_eliciting = true;
4204 in_flight = true;
4205
4206 flow_control.ensure_window_lower_bound(
4209 (recv_win as f64 * CONNECTION_WINDOW_FACTOR) as u64,
4210 );
4211
4212 self.almost_full = true;
4215 }
4216 }
4217
4218 if self.almost_full &&
4220 flow_control.max_data() < flow_control.max_data_next()
4221 {
4222 flow_control.autotune_window(now, path.recovery.rtt());
4224
4225 let frame = frame::Frame::MaxData {
4226 max: flow_control.max_data_next(),
4227 };
4228
4229 if push_frame_to_pkt!(b, frames, frame, left) {
4230 self.almost_full = false;
4231
4232 flow_control.update_max_data(now);
4234
4235 ack_eliciting = true;
4236 in_flight = true;
4237 }
4238 }
4239
4240 for (stream_id, error_code) in self
4242 .streams
4243 .stopped()
4244 .map(|(&k, &v)| (k, v))
4245 .collect::<Vec<(u64, u64)>>()
4246 {
4247 let frame = frame::Frame::StopSending {
4248 stream_id,
4249 error_code,
4250 };
4251
4252 if push_frame_to_pkt!(b, frames, frame, left) {
4253 self.streams.remove_stopped(stream_id);
4254
4255 ack_eliciting = true;
4256 in_flight = true;
4257 }
4258 }
4259
4260 for (stream_id, (error_code, final_size)) in self
4262 .streams
4263 .reset()
4264 .map(|(&k, &v)| (k, v))
4265 .collect::<Vec<(u64, (u64, u64))>>()
4266 {
4267 let frame = frame::Frame::ResetStream {
4268 stream_id,
4269 error_code,
4270 final_size,
4271 };
4272
4273 if push_frame_to_pkt!(b, frames, frame, left) {
4274 self.streams.remove_reset(stream_id);
4275
4276 ack_eliciting = true;
4277 in_flight = true;
4278 }
4279 }
4280
4281 for (stream_id, limit) in self
4283 .streams
4284 .blocked()
4285 .map(|(&k, &v)| (k, v))
4286 .collect::<Vec<(u64, u64)>>()
4287 {
4288 let frame = frame::Frame::StreamDataBlocked { stream_id, limit };
4289
4290 if push_frame_to_pkt!(b, frames, frame, left) {
4291 self.streams.remove_blocked(stream_id);
4292
4293 ack_eliciting = true;
4294 in_flight = true;
4295 }
4296 }
4297
4298 while let Some(seq_num) = self.ids.next_retire_dcid_seq() {
4300 let dcid_seq = path.active_dcid_seq.ok_or(Error::InvalidState)?;
4304
4305 if seq_num == dcid_seq {
4306 continue;
4307 }
4308
4309 let frame = frame::Frame::RetireConnectionId { seq_num };
4310
4311 if push_frame_to_pkt!(b, frames, frame, left) {
4312 self.ids.mark_retire_dcid_seq(seq_num, false)?;
4313
4314 ack_eliciting = true;
4315 in_flight = true;
4316 } else {
4317 break;
4318 }
4319 }
4320 }
4321
4322 if path.active() || n_paths == 1 {
4325 if let Some(conn_err) = self.local_error.as_ref() {
4326 if conn_err.is_app {
4327 if pkt_type == packet::Type::Short {
4329 let frame = frame::Frame::ApplicationClose {
4330 error_code: conn_err.error_code,
4331 reason: conn_err.reason.clone(),
4332 };
4333
4334 if push_frame_to_pkt!(b, frames, frame, left) {
4335 let pto = path.recovery.pto();
4336 self.draining_timer = Some(now + (pto * 3));
4337
4338 ack_eliciting = true;
4339 in_flight = true;
4340 }
4341 }
4342 } else {
4343 let frame = frame::Frame::ConnectionClose {
4345 error_code: conn_err.error_code,
4346 frame_type: 0,
4347 reason: conn_err.reason.clone(),
4348 };
4349
4350 if push_frame_to_pkt!(b, frames, frame, left) {
4351 let pto = path.recovery.pto();
4352 self.draining_timer = Some(now + (pto * 3));
4353
4354 ack_eliciting = true;
4355 in_flight = true;
4356 }
4357 }
4358 }
4359 }
4360
4361 if pkt_space.crypto_stream.is_flushable() &&
4363 left > frame::MAX_CRYPTO_OVERHEAD &&
4364 !is_closing &&
4365 path.active()
4366 {
4367 let crypto_off = pkt_space.crypto_stream.send.off_front();
4368
4369 let hdr_off = b.off();
4383 let hdr_len = 1 + octets::varint_len(crypto_off) + 2; if let Some(max_len) = left.checked_sub(hdr_len) {
4388 let (mut crypto_hdr, mut crypto_payload) =
4389 b.split_at(hdr_off + hdr_len)?;
4390
4391 let (len, _) = pkt_space
4393 .crypto_stream
4394 .send
4395 .emit(&mut crypto_payload.as_mut()[..max_len])?;
4396
4397 crypto_hdr.skip(hdr_off)?;
4404
4405 frame::encode_crypto_header(
4406 crypto_off,
4407 len as u64,
4408 &mut crypto_hdr,
4409 )?;
4410
4411 b.skip(hdr_len + len)?;
4413
4414 let frame = frame::Frame::CryptoHeader {
4415 offset: crypto_off,
4416 length: len,
4417 };
4418
4419 if push_frame_to_pkt!(b, frames, frame, left) {
4420 ack_eliciting = true;
4421 in_flight = true;
4422 has_data = true;
4423 }
4424 }
4425 }
4426
4427 let mut dgram_emitted = false;
4433 let dgrams_to_emit = max_dgram_len.is_some();
4434 let stream_to_emit = self.streams.has_flushable();
4435
4436 let mut do_dgram = self.emit_dgram && dgrams_to_emit;
4437 let do_stream = !self.emit_dgram && stream_to_emit;
4438
4439 if !do_stream && dgrams_to_emit {
4440 do_dgram = true;
4441 }
4442
4443 if (pkt_type == packet::Type::Short || pkt_type == packet::Type::ZeroRTT) &&
4445 left > frame::MAX_DGRAM_OVERHEAD &&
4446 !is_closing &&
4447 path.active() &&
4448 do_dgram
4449 {
4450 if let Some(max_dgram_payload) = max_dgram_len {
4451 while let Some(len) = self.dgram_send_queue.peek_front_len() {
4452 let hdr_off = b.off();
4453 let hdr_len = 1 + 2; if (hdr_len + len) <= left {
4457 match self.dgram_send_queue.pop() {
4459 Some(data) => {
4460 let (mut dgram_hdr, mut dgram_payload) =
4477 b.split_at(hdr_off + hdr_len)?;
4478
4479 dgram_payload.as_mut()[..len]
4480 .copy_from_slice(&data);
4481
4482 dgram_hdr.skip(hdr_off)?;
4490
4491 frame::encode_dgram_header(
4492 len as u64,
4493 &mut dgram_hdr,
4494 )?;
4495
4496 b.skip(hdr_len + len)?;
4498
4499 let frame =
4500 frame::Frame::DatagramHeader { length: len };
4501
4502 if push_frame_to_pkt!(b, frames, frame, left) {
4503 ack_eliciting = true;
4504 in_flight = true;
4505 dgram_emitted = true;
4506 let _ =
4507 self.dgram_sent_count.saturating_add(1);
4508 let _ =
4509 path.dgram_sent_count.saturating_add(1);
4510 }
4511 },
4512
4513 None => continue,
4514 };
4515 } else if len > max_dgram_payload {
4516 self.dgram_send_queue.pop();
4518 } else {
4519 break;
4520 }
4521 }
4522 }
4523 }
4524
4525 if (pkt_type == packet::Type::Short || pkt_type == packet::Type::ZeroRTT) &&
4527 left > frame::MAX_STREAM_OVERHEAD &&
4528 !is_closing &&
4529 path.active() &&
4530 !dgram_emitted
4531 {
4532 while let Some(priority_key) = self.streams.peek_flushable() {
4533 let stream_id = priority_key.id;
4534 let stream = match self.streams.get_mut(stream_id) {
4535 Some(v) if !v.send.is_stopped() => v,
4540 _ => {
4541 self.streams.remove_flushable(&priority_key);
4542 continue;
4543 },
4544 };
4545
4546 let stream_off = stream.send.off_front();
4547
4548 let hdr_off = b.off();
4562 let hdr_len = 1 + octets::varint_len(stream_id) + octets::varint_len(stream_off) + 2; let max_len = match left.checked_sub(hdr_len) {
4568 Some(v) => v,
4569 None => {
4570 let priority_key = Arc::clone(&stream.priority_key);
4571 self.streams.remove_flushable(&priority_key);
4572
4573 continue;
4574 },
4575 };
4576
4577 let (mut stream_hdr, mut stream_payload) =
4578 b.split_at(hdr_off + hdr_len)?;
4579
4580 let (len, fin) =
4582 stream.send.emit(&mut stream_payload.as_mut()[..max_len])?;
4583
4584 stream_hdr.skip(hdr_off)?;
4591
4592 frame::encode_stream_header(
4593 stream_id,
4594 stream_off,
4595 len as u64,
4596 fin,
4597 &mut stream_hdr,
4598 )?;
4599
4600 b.skip(hdr_len + len)?;
4602
4603 let frame = frame::Frame::StreamHeader {
4604 stream_id,
4605 offset: stream_off,
4606 length: len,
4607 fin,
4608 };
4609
4610 if push_frame_to_pkt!(b, frames, frame, left) {
4611 ack_eliciting = true;
4612 in_flight = true;
4613 has_data = true;
4614 }
4615
4616 let priority_key = Arc::clone(&stream.priority_key);
4617 if !stream.is_flushable() {
4619 self.streams.remove_flushable(&priority_key);
4620 } else if stream.incremental {
4621 self.streams.remove_flushable(&priority_key);
4624 self.streams.insert_flushable(&priority_key);
4625 }
4626
4627 #[cfg(feature = "fuzzing")]
4628 if left > frame::MAX_STREAM_OVERHEAD {
4630 continue;
4631 }
4632
4633 break;
4634 }
4635 }
4636
4637 self.emit_dgram = !dgram_emitted;
4639
4640 if (ack_elicit_required || path.needs_ack_eliciting) &&
4646 !ack_eliciting &&
4647 left >= 1 &&
4648 !is_closing
4649 {
4650 let frame = frame::Frame::Ping { mtu_probe: None };
4651
4652 if push_frame_to_pkt!(b, frames, frame, left) {
4653 ack_eliciting = true;
4654 in_flight = true;
4655 }
4656 }
4657
4658 if ack_eliciting && !pmtud_probe {
4659 path.needs_ack_eliciting = false;
4660 path.recovery.ping_sent(epoch);
4661 }
4662
4663 if !has_data &&
4664 !dgram_emitted &&
4665 cwnd_available > frame::MAX_STREAM_OVERHEAD
4666 {
4667 path.recovery.on_app_limited();
4668 }
4669
4670 if frames.is_empty() {
4671 path.recovery.update_app_limited(false);
4674 return Err(Error::Done);
4675 }
4676
4677 if (has_initial || !path.validated()) &&
4686 pkt_type == packet::Type::Short &&
4687 left >= 1
4688 {
4689 let frame = frame::Frame::Padding { len: left };
4690
4691 if push_frame_to_pkt!(b, frames, frame, left) {
4692 in_flight = true;
4693 }
4694 }
4695
4696 if b.off() - payload_offset < PAYLOAD_MIN_LEN {
4698 let payload_len = b.off() - payload_offset;
4699
4700 let frame = frame::Frame::Padding {
4701 len: PAYLOAD_MIN_LEN - payload_len,
4702 };
4703
4704 #[allow(unused_assignments)]
4705 if push_frame_to_pkt!(b, frames, frame, left) {
4706 in_flight = true;
4707 }
4708 }
4709
4710 let payload_len = b.off() - payload_offset;
4711
4712 if pkt_type != packet::Type::Short {
4714 let len = pn_len + payload_len + crypto_overhead;
4715
4716 let (_, mut payload_with_len) = b.split_at(header_offset)?;
4717 payload_with_len
4718 .put_varint_with_len(len as u64, PAYLOAD_LENGTH_LEN)?;
4719 }
4720
4721 trace!(
4722 "{} tx pkt {} len={} pn={} {}",
4723 self.trace_id,
4724 hdr_trace.unwrap_or_default(),
4725 payload_len,
4726 pn,
4727 AddrTupleFmt(path.local_addr(), path.peer_addr())
4728 );
4729
4730 #[cfg(feature = "qlog")]
4731 let mut qlog_frames: SmallVec<
4732 [qlog::events::quic::QuicFrame; 1],
4733 > = SmallVec::with_capacity(frames.len());
4734
4735 for frame in &mut frames {
4736 trace!("{} tx frm {:?}", self.trace_id, frame);
4737
4738 qlog_with_type!(QLOG_PACKET_TX, self.qlog, _q, {
4739 qlog_frames.push(frame.to_qlog());
4740 });
4741 }
4742
4743 qlog_with_type!(QLOG_PACKET_TX, self.qlog, q, {
4744 if let Some(header) = qlog_pkt_hdr {
4745 let length = payload_len + payload_offset + crypto_overhead;
4750 let qlog_raw_info = RawInfo {
4751 length: Some(length as u64),
4752 payload_length: Some(payload_len as u64),
4753 data: None,
4754 };
4755
4756 let send_at_time =
4757 now.duration_since(q.start_time()).as_secs_f32() * 1000.0;
4758
4759 let ev_data =
4760 EventData::PacketSent(qlog::events::quic::PacketSent {
4761 header,
4762 frames: Some(qlog_frames),
4763 raw: Some(qlog_raw_info),
4764 send_at_time: Some(send_at_time),
4765 ..Default::default()
4766 });
4767
4768 q.add_event_data_with_instant(ev_data, now).ok();
4769 }
4770 });
4771
4772 let aead = match pkt_space.crypto_seal {
4773 Some(ref v) => v,
4774 None => return Err(Error::InvalidState),
4775 };
4776
4777 let written = packet::encrypt_pkt(
4778 &mut b,
4779 pn,
4780 pn_len,
4781 payload_len,
4782 payload_offset,
4783 None,
4784 aead,
4785 )?;
4786
4787 let sent_pkt_has_data = if path.recovery.gcongestion_enabled() {
4788 has_data || dgram_emitted
4789 } else {
4790 has_data
4791 };
4792
4793 let sent_pkt = recovery::Sent {
4794 pkt_num: pn,
4795 frames,
4796 time_sent: now,
4797 time_acked: None,
4798 time_lost: None,
4799 size: if ack_eliciting { written } else { 0 },
4800 ack_eliciting,
4801 in_flight,
4802 delivered: 0,
4803 delivered_time: now,
4804 first_sent_time: now,
4805 is_app_limited: false,
4806 tx_in_flight: 0,
4807 lost: 0,
4808 has_data: sent_pkt_has_data,
4809 pmtud: pmtud_probe,
4810 };
4811
4812 if in_flight && is_app_limited {
4813 path.recovery.delivery_rate_update_app_limited(true);
4814 }
4815
4816 self.next_pkt_num += 1;
4817
4818 let handshake_status = recovery::HandshakeStatus {
4819 has_handshake_keys: self.pkt_num_spaces[packet::Epoch::Handshake]
4820 .has_keys(),
4821 peer_verified_address: self.peer_verified_initial_address,
4822 completed: self.handshake_completed,
4823 };
4824
4825 path.recovery.on_packet_sent(
4826 sent_pkt,
4827 epoch,
4828 handshake_status,
4829 now,
4830 &self.trace_id,
4831 );
4832
4833 qlog_with_type!(QLOG_METRICS, self.qlog, q, {
4834 if let Some(ev_data) = path.recovery.maybe_qlog() {
4835 q.add_event_data_with_instant(ev_data, now).ok();
4836 }
4837 });
4838
4839 if let Some(data) = challenge_data {
4841 path.add_challenge_sent(data, written, now);
4842 }
4843
4844 self.sent_count += 1;
4845 self.sent_bytes += written as u64;
4846 path.sent_count += 1;
4847 path.sent_bytes += written as u64;
4848
4849 if self.dgram_send_queue.byte_size() > path.recovery.cwnd_available() {
4850 path.recovery.update_app_limited(false);
4851 }
4852
4853 path.max_send_bytes = path.max_send_bytes.saturating_sub(written);
4854
4855 if !self.is_server && hdr_ty == packet::Type::Handshake {
4857 self.drop_epoch_state(packet::Epoch::Initial, now);
4858 }
4859
4860 if ack_eliciting && !self.ack_eliciting_sent {
4863 if let Some(idle_timeout) = self.idle_timeout() {
4864 self.idle_timer = Some(now + idle_timeout);
4865 }
4866 }
4867
4868 if ack_eliciting {
4869 self.ack_eliciting_sent = true;
4870 }
4871
4872 let active_path = self.paths.get_active_mut()?;
4873 if active_path.pmtud.is_enabled() {
4874 active_path
4875 .recovery
4876 .pmtud_update_max_datagram_size(active_path.pmtud.get_current());
4877 }
4878
4879 Ok((pkt_type, written))
4880 }
4881
4882 #[inline]
4884 pub fn get_next_release_time(&self) -> Option<ReleaseDecision> {
4885 Some(
4886 self.paths
4887 .get_active()
4888 .ok()?
4889 .recovery
4890 .get_next_release_time(),
4891 )
4892 }
4893
4894 #[inline]
4896 pub fn gcongestion_enabled(&self) -> Option<bool> {
4897 Some(self.paths.get_active().ok()?.recovery.gcongestion_enabled())
4898 }
4899
4900 pub fn max_release_into_future(&self) -> time::Duration {
4903 self.paths
4904 .get_active()
4905 .map(|p| p.recovery.rtt().mul_f64(0.125))
4906 .unwrap_or(time::Duration::from_millis(1))
4907 .min(Duration::from_millis(5))
4908 }
4909
4910 #[inline]
4919 pub fn send_quantum(&self) -> usize {
4920 match self.paths.get_active() {
4921 Ok(p) => p.recovery.send_quantum(),
4922 _ => 0,
4923 }
4924 }
4925
4926 pub fn send_quantum_on_path(
4938 &self, local_addr: SocketAddr, peer_addr: SocketAddr,
4939 ) -> usize {
4940 self.paths
4941 .path_id_from_addrs(&(local_addr, peer_addr))
4942 .and_then(|pid| self.paths.get(pid).ok())
4943 .map(|path| path.recovery.send_quantum())
4944 .unwrap_or(0)
4945 }
4946
4947 pub fn stream_recv(
4978 &mut self, stream_id: u64, out: &mut [u8],
4979 ) -> Result<(usize, bool)> {
4980 if !stream::is_bidi(stream_id) &&
4982 stream::is_local(stream_id, self.is_server)
4983 {
4984 return Err(Error::InvalidStreamState(stream_id));
4985 }
4986
4987 let stream = self
4988 .streams
4989 .get_mut(stream_id)
4990 .ok_or(Error::InvalidStreamState(stream_id))?;
4991
4992 if !stream.is_readable() {
4993 return Err(Error::Done);
4994 }
4995
4996 let local = stream.local;
4997 let priority_key = Arc::clone(&stream.priority_key);
4998
4999 #[cfg(feature = "qlog")]
5000 let offset = stream.recv.off_front();
5001
5002 let (read, fin) = match stream.recv.emit(out) {
5003 Ok(v) => v,
5004
5005 Err(e) => {
5006 if stream.is_complete() {
5011 self.streams.collect(stream_id, local);
5012 }
5013
5014 self.streams.remove_readable(&priority_key);
5015 return Err(e);
5016 },
5017 };
5018
5019 self.flow_control.add_consumed(read as u64);
5020
5021 let readable = stream.is_readable();
5022
5023 let complete = stream.is_complete();
5024
5025 if stream.recv.almost_full() {
5026 self.streams.insert_almost_full(stream_id);
5027 }
5028
5029 if !readable {
5030 self.streams.remove_readable(&priority_key);
5031 }
5032
5033 if complete {
5034 self.streams.collect(stream_id, local);
5035 }
5036
5037 qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
5038 let ev_data = EventData::DataMoved(qlog::events::quic::DataMoved {
5039 stream_id: Some(stream_id),
5040 offset: Some(offset),
5041 length: Some(read as u64),
5042 from: Some(DataRecipient::Transport),
5043 to: Some(DataRecipient::Application),
5044 ..Default::default()
5045 });
5046
5047 let now = time::Instant::now();
5048 q.add_event_data_with_instant(ev_data, now).ok();
5049 });
5050
5051 if self.should_update_max_data() {
5052 self.almost_full = true;
5053 }
5054
5055 if priority_key.incremental && readable {
5056 self.streams.remove_readable(&priority_key);
5058 self.streams.insert_readable(&priority_key);
5059 }
5060
5061 Ok((read, fin))
5062 }
5063
5064 pub fn stream_send(
5112 &mut self, stream_id: u64, buf: &[u8], fin: bool,
5113 ) -> Result<usize> {
5114 if !stream::is_bidi(stream_id) &&
5116 !stream::is_local(stream_id, self.is_server)
5117 {
5118 return Err(Error::InvalidStreamState(stream_id));
5119 }
5120
5121 if self.max_tx_data - self.tx_data < buf.len() as u64 {
5127 self.blocked_limit = Some(self.max_tx_data);
5128 }
5129
5130 let cap = self.tx_cap;
5131
5132 let stream = self.get_or_create_stream(stream_id, true)?;
5134
5135 #[cfg(feature = "qlog")]
5136 let offset = stream.send.off_back();
5137
5138 let was_writable = stream.is_writable();
5139
5140 let was_flushable = stream.is_flushable();
5141
5142 let priority_key = Arc::clone(&stream.priority_key);
5143
5144 if cap == 0 && !buf.is_empty() {
5150 if was_writable {
5151 self.streams.insert_writable(&priority_key);
5158 }
5159
5160 return Err(Error::Done);
5161 }
5162
5163 let (buf, fin, blocked_by_cap) = if cap < buf.len() {
5164 (&buf[..cap], false, true)
5165 } else {
5166 (buf, fin, false)
5167 };
5168
5169 let sent = match stream.send.write(buf, fin) {
5170 Ok(v) => v,
5171
5172 Err(e) => {
5173 self.streams.remove_writable(&priority_key);
5174 return Err(e);
5175 },
5176 };
5177
5178 let incremental = stream.incremental;
5179 let priority_key = Arc::clone(&stream.priority_key);
5180
5181 let flushable = stream.is_flushable();
5182
5183 let writable = stream.is_writable();
5184
5185 let empty_fin = buf.is_empty() && fin;
5186
5187 if sent < buf.len() {
5188 let max_off = stream.send.max_off();
5189
5190 if stream.send.blocked_at() != Some(max_off) {
5191 stream.send.update_blocked_at(Some(max_off));
5192 self.streams.insert_blocked(stream_id, max_off);
5193 }
5194 } else {
5195 stream.send.update_blocked_at(None);
5196 self.streams.remove_blocked(stream_id);
5197 }
5198
5199 if (flushable || empty_fin) && !was_flushable {
5205 self.streams.insert_flushable(&priority_key);
5206 }
5207
5208 if !writable {
5209 self.streams.remove_writable(&priority_key);
5210 } else if was_writable && blocked_by_cap {
5211 self.streams.insert_writable(&priority_key);
5218 }
5219
5220 self.tx_cap -= sent;
5221
5222 self.tx_data += sent as u64;
5223
5224 self.tx_buffered += sent;
5225
5226 qlog_with_type!(QLOG_DATA_MV, self.qlog, q, {
5227 let ev_data = EventData::DataMoved(qlog::events::quic::DataMoved {
5228 stream_id: Some(stream_id),
5229 offset: Some(offset),
5230 length: Some(sent as u64),
5231 from: Some(DataRecipient::Application),
5232 to: Some(DataRecipient::Transport),
5233 ..Default::default()
5234 });
5235
5236 let now = time::Instant::now();
5237 q.add_event_data_with_instant(ev_data, now).ok();
5238 });
5239
5240 if sent == 0 && !buf.is_empty() {
5241 return Err(Error::Done);
5242 }
5243
5244 if incremental && writable {
5245 self.streams.remove_writable(&priority_key);
5247 self.streams.insert_writable(&priority_key);
5248 }
5249
5250 Ok(sent)
5251 }
5252
5253 pub fn stream_priority(
5262 &mut self, stream_id: u64, urgency: u8, incremental: bool,
5263 ) -> Result<()> {
5264 let stream = match self.get_or_create_stream(stream_id, true) {
5267 Ok(v) => v,
5268
5269 Err(Error::Done) => return Ok(()),
5270
5271 Err(e) => return Err(e),
5272 };
5273
5274 if stream.urgency == urgency && stream.incremental == incremental {
5275 return Ok(());
5276 }
5277
5278 stream.urgency = urgency;
5279 stream.incremental = incremental;
5280
5281 let new_priority_key = Arc::new(StreamPriorityKey {
5282 urgency: stream.urgency,
5283 incremental: stream.incremental,
5284 id: stream_id,
5285 ..Default::default()
5286 });
5287
5288 let old_priority_key =
5289 std::mem::replace(&mut stream.priority_key, new_priority_key.clone());
5290
5291 self.streams
5292 .update_priority(&old_priority_key, &new_priority_key);
5293
5294 Ok(())
5295 }
5296
5297 pub fn stream_shutdown(
5323 &mut self, stream_id: u64, direction: Shutdown, err: u64,
5324 ) -> Result<()> {
5325 if direction == Shutdown::Read &&
5327 stream::is_local(stream_id, self.is_server) &&
5328 !stream::is_bidi(stream_id)
5329 {
5330 return Err(Error::InvalidStreamState(stream_id));
5331 }
5332
5333 if direction == Shutdown::Write &&
5335 !stream::is_local(stream_id, self.is_server) &&
5336 !stream::is_bidi(stream_id)
5337 {
5338 return Err(Error::InvalidStreamState(stream_id));
5339 }
5340
5341 let stream = self.streams.get_mut(stream_id).ok_or(Error::Done)?;
5343
5344 let priority_key = Arc::clone(&stream.priority_key);
5345
5346 match direction {
5347 Shutdown::Read => {
5348 stream.recv.shutdown()?;
5349
5350 if !stream.recv.is_fin() {
5351 self.streams.insert_stopped(stream_id, err);
5352 }
5353
5354 self.streams.remove_readable(&priority_key);
5356
5357 self.stopped_stream_local_count =
5358 self.stopped_stream_local_count.saturating_add(1);
5359 },
5360
5361 Shutdown::Write => {
5362 let (final_size, unsent) = stream.send.shutdown()?;
5363
5364 self.tx_data = self.tx_data.saturating_sub(unsent);
5367
5368 self.tx_buffered =
5369 self.tx_buffered.saturating_sub(unsent as usize);
5370
5371 self.update_tx_cap();
5373
5374 self.streams.insert_reset(stream_id, err, final_size);
5375
5376 self.streams.remove_writable(&priority_key);
5378
5379 self.reset_stream_local_count =
5380 self.reset_stream_local_count.saturating_add(1);
5381 },
5382 }
5383
5384 Ok(())
5385 }
5386
5387 #[inline]
5400 pub fn stream_capacity(&self, stream_id: u64) -> Result<usize> {
5401 if let Some(stream) = self.streams.get(stream_id) {
5402 let cap = cmp::min(self.tx_cap, stream.send.cap()?);
5403 return Ok(cap);
5404 };
5405
5406 Err(Error::InvalidStreamState(stream_id))
5407 }
5408
5409 pub fn stream_readable_next(&mut self) -> Option<u64> {
5422 let priority_key = self.streams.readable.front().clone_pointer()?;
5423
5424 self.streams.remove_readable(&priority_key);
5425
5426 Some(priority_key.id)
5427 }
5428
5429 pub fn stream_readable(&self, stream_id: u64) -> bool {
5431 let stream = match self.streams.get(stream_id) {
5432 Some(v) => v,
5433
5434 None => return false,
5435 };
5436
5437 stream.is_readable()
5438 }
5439
5440 pub fn stream_writable_next(&mut self) -> Option<u64> {
5456 if self.tx_cap == 0 {
5459 return None;
5460 }
5461
5462 let mut cursor = self.streams.writable.front();
5463
5464 while let Some(priority_key) = cursor.clone_pointer() {
5465 if let Some(stream) = self.streams.get(priority_key.id) {
5466 let cap = match stream.send.cap() {
5467 Ok(v) => v,
5468
5469 Err(_) =>
5472 return {
5473 self.streams.remove_writable(&priority_key);
5474
5475 Some(priority_key.id)
5476 },
5477 };
5478
5479 if cmp::min(self.tx_cap, cap) >= stream.send_lowat {
5480 self.streams.remove_writable(&priority_key);
5481 return Some(priority_key.id);
5482 }
5483 }
5484
5485 cursor.move_next();
5486 }
5487
5488 None
5489 }
5490
5491 #[inline]
5514 pub fn stream_writable(
5515 &mut self, stream_id: u64, len: usize,
5516 ) -> Result<bool> {
5517 if self.stream_capacity(stream_id)? >= len {
5518 return Ok(true);
5519 }
5520
5521 let stream = match self.streams.get_mut(stream_id) {
5522 Some(v) => v,
5523
5524 None => return Err(Error::InvalidStreamState(stream_id)),
5525 };
5526
5527 stream.send_lowat = cmp::max(1, len);
5528
5529 let is_writable = stream.is_writable();
5530
5531 let priority_key = Arc::clone(&stream.priority_key);
5532
5533 if self.max_tx_data - self.tx_data < len as u64 {
5534 self.blocked_limit = Some(self.max_tx_data);
5535 }
5536
5537 if stream.send.cap()? < len {
5538 let max_off = stream.send.max_off();
5539 if stream.send.blocked_at() != Some(max_off) {
5540 stream.send.update_blocked_at(Some(max_off));
5541 self.streams.insert_blocked(stream_id, max_off);
5542 }
5543 } else if is_writable {
5544 self.streams.insert_writable(&priority_key);
5551 }
5552
5553 Ok(false)
5554 }
5555
5556 #[inline]
5565 pub fn stream_finished(&self, stream_id: u64) -> bool {
5566 let stream = match self.streams.get(stream_id) {
5567 Some(v) => v,
5568
5569 None => return true,
5570 };
5571
5572 stream.recv.is_fin()
5573 }
5574
5575 #[inline]
5581 pub fn peer_streams_left_bidi(&self) -> u64 {
5582 self.streams.peer_streams_left_bidi()
5583 }
5584
5585 #[inline]
5591 pub fn peer_streams_left_uni(&self) -> u64 {
5592 self.streams.peer_streams_left_uni()
5593 }
5594
5595 #[inline]
5622 pub fn readable(&self) -> StreamIter {
5623 self.streams.readable()
5624 }
5625
5626 #[inline]
5665 pub fn writable(&self) -> StreamIter {
5666 if self.tx_cap == 0 {
5669 return StreamIter::default();
5670 }
5671
5672 self.streams.writable()
5673 }
5674
5675 pub fn max_send_udp_payload_size(&self) -> usize {
5689 let max_datagram_size = self
5690 .paths
5691 .get_active()
5692 .ok()
5693 .map(|p| p.recovery.max_datagram_size());
5694
5695 if let Some(max_datagram_size) = max_datagram_size {
5696 if self.is_established() {
5697 return cmp::min(16383, max_datagram_size);
5700 }
5701 }
5702
5703 MIN_CLIENT_INITIAL_LEN
5706 }
5707
5708 pub fn send_ack_eliciting(&mut self) -> Result<()> {
5720 if self.is_closed() || self.is_draining() {
5721 return Ok(());
5722 }
5723 self.paths.get_active_mut()?.needs_ack_eliciting = true;
5724 Ok(())
5725 }
5726
5727 pub fn send_ack_eliciting_on_path(
5735 &mut self, local: SocketAddr, peer: SocketAddr,
5736 ) -> Result<()> {
5737 if self.is_closed() || self.is_draining() {
5738 return Ok(());
5739 }
5740 let path_id = self
5741 .paths
5742 .path_id_from_addrs(&(local, peer))
5743 .ok_or(Error::InvalidState)?;
5744 self.paths.get_mut(path_id)?.needs_ack_eliciting = true;
5745 Ok(())
5746 }
5747
5748 #[inline]
5777 pub fn dgram_recv(&mut self, buf: &mut [u8]) -> Result<usize> {
5778 match self.dgram_recv_queue.pop() {
5779 Some(d) => {
5780 if d.len() > buf.len() {
5781 return Err(Error::BufferTooShort);
5782 }
5783
5784 buf[..d.len()].copy_from_slice(&d);
5785 Ok(d.len())
5786 },
5787
5788 None => Err(Error::Done),
5789 }
5790 }
5791
5792 #[inline]
5799 pub fn dgram_recv_vec(&mut self) -> Result<Vec<u8>> {
5800 match self.dgram_recv_queue.pop() {
5801 Some(d) => Ok(d),
5802
5803 None => Err(Error::Done),
5804 }
5805 }
5806
5807 #[inline]
5821 pub fn dgram_recv_peek(&self, buf: &mut [u8], len: usize) -> Result<usize> {
5822 self.dgram_recv_queue.peek_front_bytes(buf, len)
5823 }
5824
5825 #[inline]
5827 pub fn dgram_recv_front_len(&self) -> Option<usize> {
5828 self.dgram_recv_queue.peek_front_len()
5829 }
5830
5831 #[inline]
5833 pub fn dgram_recv_queue_len(&self) -> usize {
5834 self.dgram_recv_queue.len()
5835 }
5836
5837 #[inline]
5839 pub fn dgram_recv_queue_byte_size(&self) -> usize {
5840 self.dgram_recv_queue.byte_size()
5841 }
5842
5843 #[inline]
5845 pub fn dgram_send_queue_len(&self) -> usize {
5846 self.dgram_send_queue.len()
5847 }
5848
5849 #[inline]
5851 pub fn dgram_send_queue_byte_size(&self) -> usize {
5852 self.dgram_send_queue.byte_size()
5853 }
5854
5855 #[inline]
5857 pub fn is_dgram_send_queue_full(&self) -> bool {
5858 self.dgram_send_queue.is_full()
5859 }
5860
5861 #[inline]
5863 pub fn is_dgram_recv_queue_full(&self) -> bool {
5864 self.dgram_recv_queue.is_full()
5865 }
5866
5867 pub fn dgram_send(&mut self, buf: &[u8]) -> Result<()> {
5900 let max_payload_len = match self.dgram_max_writable_len() {
5901 Some(v) => v,
5902
5903 None => return Err(Error::InvalidState),
5904 };
5905
5906 if buf.len() > max_payload_len {
5907 return Err(Error::BufferTooShort);
5908 }
5909
5910 self.dgram_send_queue.push(buf.to_vec())?;
5911
5912 let active_path = self.paths.get_active_mut()?;
5913
5914 if self.dgram_send_queue.byte_size() >
5915 active_path.recovery.cwnd_available()
5916 {
5917 active_path.recovery.update_app_limited(false);
5918 }
5919
5920 Ok(())
5921 }
5922
5923 pub fn dgram_send_vec(&mut self, buf: Vec<u8>) -> Result<()> {
5930 let max_payload_len = match self.dgram_max_writable_len() {
5931 Some(v) => v,
5932
5933 None => return Err(Error::InvalidState),
5934 };
5935
5936 if buf.len() > max_payload_len {
5937 return Err(Error::BufferTooShort);
5938 }
5939
5940 self.dgram_send_queue.push(buf)?;
5941
5942 let active_path = self.paths.get_active_mut()?;
5943
5944 if self.dgram_send_queue.byte_size() >
5945 active_path.recovery.cwnd_available()
5946 {
5947 active_path.recovery.update_app_limited(false);
5948 }
5949
5950 Ok(())
5951 }
5952
5953 #[inline]
5970 pub fn dgram_purge_outgoing<F: Fn(&[u8]) -> bool>(&mut self, f: F) {
5971 self.dgram_send_queue.purge(f);
5972 }
5973
5974 #[inline]
5997 pub fn dgram_max_writable_len(&self) -> Option<usize> {
5998 match self.peer_transport_params.max_datagram_frame_size {
5999 None => None,
6000 Some(peer_frame_len) => {
6001 let dcid = self.destination_id();
6002 let mut max_len = self.max_send_udp_payload_size();
6004 max_len = max_len.saturating_sub(1 + dcid.len());
6007 max_len = max_len.saturating_sub(packet::MAX_PKT_NUM_LEN);
6009 max_len = max_len.saturating_sub(
6011 self.pkt_num_spaces[packet::Epoch::Application]
6012 .crypto_overhead()?,
6013 );
6014 max_len = cmp::min(peer_frame_len as usize, max_len);
6016 max_len.checked_sub(1 + frame::MAX_DGRAM_OVERHEAD)
6019 },
6020 }
6021 }
6022
6023 fn dgram_enabled(&self) -> bool {
6024 self.local_transport_params
6025 .max_datagram_frame_size
6026 .is_some()
6027 }
6028
6029 pub fn timeout_instant(&self) -> Option<time::Instant> {
6037 if self.is_closed() {
6038 return None;
6039 }
6040
6041 if self.is_draining() {
6042 self.draining_timer
6046 } else {
6047 let path_timer = self
6052 .paths
6053 .iter()
6054 .filter_map(|(_, p)| p.recovery.loss_detection_timer())
6055 .min();
6056
6057 let key_update_timer = self.pkt_num_spaces
6058 [packet::Epoch::Application]
6059 .key_update
6060 .as_ref()
6061 .map(|key_update| key_update.timer);
6062
6063 let timers = [self.idle_timer, path_timer, key_update_timer];
6064
6065 timers.iter().filter_map(|&x| x).min()
6066 }
6067 }
6068
6069 pub fn timeout(&self) -> Option<time::Duration> {
6076 self.timeout_instant().map(|timeout| {
6077 let now = time::Instant::now();
6078
6079 if timeout <= now {
6080 time::Duration::ZERO
6081 } else {
6082 timeout.duration_since(now)
6083 }
6084 })
6085 }
6086
6087 pub fn on_timeout(&mut self) {
6091 let now = time::Instant::now();
6092
6093 if let Some(draining_timer) = self.draining_timer {
6094 if draining_timer <= now {
6095 trace!("{} draining timeout expired", self.trace_id);
6096
6097 self.mark_closed();
6098 }
6099
6100 return;
6104 }
6105
6106 if let Some(timer) = self.idle_timer {
6107 if timer <= now {
6108 trace!("{} idle timeout expired", self.trace_id);
6109
6110 self.mark_closed();
6111 self.timed_out = true;
6112 return;
6113 }
6114 }
6115
6116 if let Some(timer) = self.pkt_num_spaces[packet::Epoch::Application]
6117 .key_update
6118 .as_ref()
6119 .map(|key_update| key_update.timer)
6120 {
6121 if timer <= now {
6122 let _ = self.pkt_num_spaces[packet::Epoch::Application]
6124 .key_update
6125 .take();
6126 }
6127 }
6128
6129 let handshake_status = self.handshake_status();
6130
6131 for (_, p) in self.paths.iter_mut() {
6132 if let Some(timer) = p.recovery.loss_detection_timer() {
6133 if timer <= now {
6134 trace!("{} loss detection timeout expired", self.trace_id);
6135
6136 let (lost_packets, lost_bytes) = p.on_loss_detection_timeout(
6137 handshake_status,
6138 now,
6139 self.is_server,
6140 &self.trace_id,
6141 );
6142
6143 self.lost_count += lost_packets;
6144 self.lost_bytes += lost_bytes as u64;
6145
6146 qlog_with_type!(QLOG_METRICS, self.qlog, q, {
6147 if let Some(ev_data) = p.recovery.maybe_qlog() {
6148 q.add_event_data_with_instant(ev_data, now).ok();
6149 }
6150 });
6151 }
6152 }
6153 }
6154
6155 self.paths.notify_failed_validations();
6157
6158 if self.paths.get_active_path_id().is_err() {
6160 match self.paths.find_candidate_path() {
6161 Some(pid) => {
6162 if self.set_active_path(pid, now).is_err() {
6163 self.mark_closed();
6165 }
6166 },
6167
6168 None => {
6170 self.mark_closed();
6171 },
6172 }
6173 }
6174 }
6175
6176 pub fn probe_path(
6207 &mut self, local_addr: SocketAddr, peer_addr: SocketAddr,
6208 ) -> Result<u64> {
6209 let pid = match self.paths.path_id_from_addrs(&(local_addr, peer_addr)) {
6211 Some(pid) => pid,
6212 None => self.create_path_on_client(local_addr, peer_addr)?,
6213 };
6214
6215 let path = self.paths.get_mut(pid)?;
6216 path.request_validation();
6217
6218 path.active_dcid_seq.ok_or(Error::InvalidState)
6219 }
6220
6221 pub fn migrate_source(&mut self, local_addr: SocketAddr) -> Result<u64> {
6230 let peer_addr = self.paths.get_active()?.peer_addr();
6231 self.migrate(local_addr, peer_addr)
6232 }
6233
6234 pub fn migrate(
6249 &mut self, local_addr: SocketAddr, peer_addr: SocketAddr,
6250 ) -> Result<u64> {
6251 if self.is_server {
6252 return Err(Error::InvalidState);
6253 }
6254
6255 let (pid, dcid_seq) = if let Some(pid) =
6257 self.paths.path_id_from_addrs(&(local_addr, peer_addr))
6258 {
6259 let path = self.paths.get_mut(pid)?;
6260
6261 if path.active() {
6263 return path.active_dcid_seq.ok_or(Error::OutOfIdentifiers);
6264 }
6265
6266 if !self.ids.zero_length_scid() &&
6270 path.active_scid_seq.is_none() &&
6271 self.ids.available_scids() == 0
6272 {
6273 return Err(Error::OutOfIdentifiers);
6274 }
6275
6276 let dcid_seq = if let Some(dcid_seq) = path.active_dcid_seq {
6278 dcid_seq
6279 } else {
6280 let dcid_seq = self
6281 .ids
6282 .lowest_available_dcid_seq()
6283 .ok_or(Error::OutOfIdentifiers)?;
6284
6285 self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
6286 path.active_dcid_seq = Some(dcid_seq);
6287
6288 dcid_seq
6289 };
6290
6291 (pid, dcid_seq)
6292 } else {
6293 let pid = self.create_path_on_client(local_addr, peer_addr)?;
6294
6295 let dcid_seq = self
6296 .paths
6297 .get(pid)?
6298 .active_dcid_seq
6299 .ok_or(Error::InvalidState)?;
6300
6301 (pid, dcid_seq)
6302 };
6303
6304 self.set_active_path(pid, time::Instant::now())?;
6306
6307 Ok(dcid_seq)
6308 }
6309
6310 pub fn new_scid(
6343 &mut self, scid: &ConnectionId, reset_token: u128, retire_if_needed: bool,
6344 ) -> Result<u64> {
6345 self.ids.new_scid(
6346 scid.to_vec().into(),
6347 Some(reset_token),
6348 true,
6349 None,
6350 retire_if_needed,
6351 )
6352 }
6353
6354 pub fn active_scids(&self) -> usize {
6357 self.ids.active_source_cids()
6358 }
6359
6360 #[inline]
6372 pub fn scids_left(&self) -> usize {
6373 let max_active_source_cids = cmp::min(
6374 self.peer_transport_params.active_conn_id_limit,
6375 self.local_transport_params.active_conn_id_limit,
6376 ) as usize;
6377
6378 max_active_source_cids - self.active_scids()
6379 }
6380
6381 pub fn retire_dcid(&mut self, dcid_seq: u64) -> Result<()> {
6401 if self.ids.zero_length_dcid() {
6402 return Err(Error::InvalidState);
6403 }
6404
6405 let active_path_dcid_seq = self
6406 .paths
6407 .get_active()?
6408 .active_dcid_seq
6409 .ok_or(Error::InvalidState)?;
6410
6411 let active_path_id = self.paths.get_active_path_id()?;
6412
6413 if active_path_dcid_seq == dcid_seq &&
6414 self.ids.lowest_available_dcid_seq().is_none() &&
6415 !self
6416 .paths
6417 .iter()
6418 .any(|(pid, p)| pid != active_path_id && p.usable())
6419 {
6420 return Err(Error::OutOfIdentifiers);
6421 }
6422
6423 if let Some(pid) = self.ids.retire_dcid(dcid_seq)? {
6424 let path = self.paths.get_mut(pid)?;
6427 let dcid_seq = self.ids.lowest_available_dcid_seq();
6428
6429 if let Some(dcid_seq) = dcid_seq {
6430 self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
6431 }
6432
6433 path.active_dcid_seq = dcid_seq;
6434 }
6435
6436 Ok(())
6437 }
6438
6439 pub fn path_event_next(&mut self) -> Option<PathEvent> {
6451 self.paths.pop_event()
6452 }
6453
6454 pub fn retired_scids(&self) -> usize {
6456 self.ids.retired_source_cids()
6457 }
6458
6459 pub fn retired_scid_next(&mut self) -> Option<ConnectionId<'static>> {
6466 self.ids.pop_retired_scid()
6467 }
6468
6469 pub fn available_dcids(&self) -> usize {
6475 self.ids.available_dcids()
6476 }
6477
6478 #[inline]
6525 pub fn paths_iter(&self, from: SocketAddr) -> SocketAddrIter {
6526 SocketAddrIter {
6529 sockaddrs: self
6530 .paths
6531 .iter()
6532 .filter(|(_, p)| p.active_dcid_seq.is_some())
6533 .filter(|(_, p)| p.usable() || p.probing_required())
6534 .filter(|(_, p)| p.local_addr() == from)
6535 .map(|(_, p)| p.peer_addr())
6536 .collect(),
6537
6538 index: 0,
6539 }
6540 }
6541
6542 pub fn close(&mut self, app: bool, err: u64, reason: &[u8]) -> Result<()> {
6568 if self.is_closed() || self.is_draining() {
6569 return Err(Error::Done);
6570 }
6571
6572 if self.local_error.is_some() {
6573 return Err(Error::Done);
6574 }
6575
6576 let is_safe_to_send_app_data =
6577 self.is_established() || self.is_in_early_data();
6578
6579 if app && !is_safe_to_send_app_data {
6580 self.local_error = Some(ConnectionError {
6582 is_app: false,
6583 error_code: 0x0c,
6584 reason: vec![],
6585 });
6586 } else {
6587 self.local_error = Some(ConnectionError {
6588 is_app: app,
6589 error_code: err,
6590 reason: reason.to_vec(),
6591 });
6592 }
6593
6594 if self.recv_count == 0 {
6596 self.mark_closed();
6597 }
6598
6599 Ok(())
6600 }
6601
6602 #[inline]
6607 pub fn trace_id(&self) -> &str {
6608 &self.trace_id
6609 }
6610
6611 #[inline]
6615 pub fn application_proto(&self) -> &[u8] {
6616 self.alpn.as_ref()
6617 }
6618
6619 #[inline]
6621 pub fn server_name(&self) -> Option<&str> {
6622 self.handshake.server_name()
6623 }
6624
6625 #[inline]
6627 pub fn peer_cert(&self) -> Option<&[u8]> {
6628 self.handshake.peer_cert()
6629 }
6630
6631 #[inline]
6638 pub fn peer_cert_chain(&self) -> Option<Vec<&[u8]>> {
6639 self.handshake.peer_cert_chain()
6640 }
6641
6642 #[inline]
6649 pub fn session(&self) -> Option<&[u8]> {
6650 self.session.as_deref()
6651 }
6652
6653 #[inline]
6661 pub fn source_id(&self) -> ConnectionId {
6662 if let Ok(path) = self.paths.get_active() {
6663 if let Some(active_scid_seq) = path.active_scid_seq {
6664 if let Ok(e) = self.ids.get_scid(active_scid_seq) {
6665 return ConnectionId::from_ref(e.cid.as_ref());
6666 }
6667 }
6668 }
6669
6670 let e = self.ids.oldest_scid();
6671 ConnectionId::from_ref(e.cid.as_ref())
6672 }
6673
6674 #[inline]
6679 pub fn source_ids(&self) -> impl Iterator<Item = &ConnectionId> {
6680 self.ids.scids_iter()
6681 }
6682
6683 #[inline]
6688 pub fn destination_id(&self) -> ConnectionId {
6689 if let Ok(path) = self.paths.get_active() {
6690 if let Some(active_dcid_seq) = path.active_dcid_seq {
6691 if let Ok(e) = self.ids.get_dcid(active_dcid_seq) {
6692 return ConnectionId::from_ref(e.cid.as_ref());
6693 }
6694 }
6695 }
6696
6697 let e = self.ids.oldest_dcid();
6698 ConnectionId::from_ref(e.cid.as_ref())
6699 }
6700
6701 #[inline]
6703 pub fn is_established(&self) -> bool {
6704 self.handshake_completed
6705 }
6706
6707 #[inline]
6709 pub fn is_resumed(&self) -> bool {
6710 self.handshake.is_resumed()
6711 }
6712
6713 #[inline]
6716 pub fn is_in_early_data(&self) -> bool {
6717 self.handshake.is_in_early_data()
6718 }
6719
6720 #[inline]
6722 pub fn is_readable(&self) -> bool {
6723 self.streams.has_readable() || self.dgram_recv_front_len().is_some()
6724 }
6725
6726 pub fn is_path_validated(
6734 &self, from: SocketAddr, to: SocketAddr,
6735 ) -> Result<bool> {
6736 let pid = self
6737 .paths
6738 .path_id_from_addrs(&(from, to))
6739 .ok_or(Error::InvalidState)?;
6740
6741 Ok(self.paths.get(pid)?.validated())
6742 }
6743
6744 #[inline]
6760 pub fn is_draining(&self) -> bool {
6761 self.draining_timer.is_some()
6762 }
6763
6764 #[inline]
6768 pub fn is_closed(&self) -> bool {
6769 self.closed
6770 }
6771
6772 #[inline]
6774 pub fn is_timed_out(&self) -> bool {
6775 self.timed_out
6776 }
6777
6778 #[inline]
6785 pub fn peer_error(&self) -> Option<&ConnectionError> {
6786 self.peer_error.as_ref()
6787 }
6788
6789 #[inline]
6800 pub fn local_error(&self) -> Option<&ConnectionError> {
6801 self.local_error.as_ref()
6802 }
6803
6804 #[inline]
6806 pub fn stats(&self) -> Stats {
6807 Stats {
6808 recv: self.recv_count,
6809 sent: self.sent_count,
6810 lost: self.lost_count,
6811 retrans: self.retrans_count,
6812 sent_bytes: self.sent_bytes,
6813 recv_bytes: self.recv_bytes,
6814 acked_bytes: self.acked_bytes,
6815 lost_bytes: self.lost_bytes,
6816 stream_retrans_bytes: self.stream_retrans_bytes,
6817 dgram_recv: self.dgram_recv_count,
6818 dgram_sent: self.dgram_sent_count,
6819 paths_count: self.paths.len(),
6820 reset_stream_count_local: self.reset_stream_local_count,
6821 stopped_stream_count_local: self.stopped_stream_local_count,
6822 reset_stream_count_remote: self.reset_stream_remote_count,
6823 stopped_stream_count_remote: self.stopped_stream_remote_count,
6824 path_challenge_rx_count: self.path_challenge_rx_count,
6825 }
6826 }
6827
6828 pub fn peer_transport_params(&self) -> Option<&TransportParams> {
6831 if !self.parsed_peer_transport_params {
6832 return None;
6833 }
6834
6835 Some(&self.peer_transport_params)
6836 }
6837
6838 pub fn path_stats(&self) -> impl Iterator<Item = PathStats> + '_ {
6841 self.paths.iter().map(|(_, p)| p.stats())
6842 }
6843
6844 pub fn is_server(&self) -> bool {
6846 self.is_server
6847 }
6848
6849 fn encode_transport_params(&mut self) -> Result<()> {
6850 let mut raw_params = [0; 128];
6851
6852 let raw_params = TransportParams::encode(
6853 &self.local_transport_params,
6854 self.is_server,
6855 &mut raw_params,
6856 )?;
6857
6858 self.handshake.set_quic_transport_params(raw_params)?;
6859
6860 Ok(())
6861 }
6862
6863 fn parse_peer_transport_params(
6864 &mut self, peer_params: TransportParams,
6865 ) -> Result<()> {
6866 match &peer_params.initial_source_connection_id {
6868 Some(v) if v != &self.destination_id() =>
6869 return Err(Error::InvalidTransportParam),
6870
6871 Some(_) => (),
6872
6873 None => return Err(Error::InvalidTransportParam),
6876 }
6877
6878 if let Some(odcid) = &self.odcid {
6880 match &peer_params.original_destination_connection_id {
6881 Some(v) if v != odcid =>
6882 return Err(Error::InvalidTransportParam),
6883
6884 Some(_) => (),
6885
6886 None if !self.is_server =>
6889 return Err(Error::InvalidTransportParam),
6890
6891 None => (),
6892 }
6893 }
6894
6895 if let Some(rscid) = &self.rscid {
6897 match &peer_params.retry_source_connection_id {
6898 Some(v) if v != rscid =>
6899 return Err(Error::InvalidTransportParam),
6900
6901 Some(_) => (),
6902
6903 None => return Err(Error::InvalidTransportParam),
6906 }
6907 }
6908
6909 self.process_peer_transport_params(peer_params)?;
6910
6911 self.parsed_peer_transport_params = true;
6912
6913 Ok(())
6914 }
6915
6916 fn process_peer_transport_params(
6917 &mut self, peer_params: TransportParams,
6918 ) -> Result<()> {
6919 self.max_tx_data = peer_params.initial_max_data;
6920
6921 self.update_tx_cap();
6923
6924 self.streams
6925 .update_peer_max_streams_bidi(peer_params.initial_max_streams_bidi);
6926 self.streams
6927 .update_peer_max_streams_uni(peer_params.initial_max_streams_uni);
6928
6929 let max_ack_delay =
6930 time::Duration::from_millis(peer_params.max_ack_delay);
6931
6932 self.recovery_config.max_ack_delay = max_ack_delay;
6933
6934 let active_path = self.paths.get_active_mut()?;
6935
6936 active_path.recovery.update_max_ack_delay(max_ack_delay);
6937
6938 if active_path.pmtud.get_probe_status() {
6939 active_path.recovery.pmtud_update_max_datagram_size(
6940 active_path
6941 .pmtud
6942 .get_probe_size()
6943 .min(peer_params.max_udp_payload_size as usize),
6944 );
6945 } else {
6946 active_path.recovery.update_max_datagram_size(
6947 peer_params.max_udp_payload_size as usize,
6948 );
6949 }
6950
6951 self.ids
6953 .set_source_conn_id_limit(peer_params.active_conn_id_limit);
6954
6955 self.peer_transport_params = peer_params;
6956
6957 Ok(())
6958 }
6959
6960 fn do_handshake(&mut self, now: time::Instant) -> Result<()> {
6964 let mut ex_data = tls::ExData {
6965 application_protos: &self.application_protos,
6966
6967 pkt_num_spaces: &mut self.pkt_num_spaces,
6968
6969 session: &mut self.session,
6970
6971 local_error: &mut self.local_error,
6972
6973 keylog: self.keylog.as_mut(),
6974
6975 trace_id: &self.trace_id,
6976
6977 recovery_config: self.recovery_config,
6978
6979 is_server: self.is_server,
6980 };
6981
6982 if self.handshake_completed {
6983 return self.handshake.process_post_handshake(&mut ex_data);
6984 }
6985
6986 match self.handshake.do_handshake(&mut ex_data) {
6987 Ok(_) => (),
6988
6989 Err(Error::Done) => {
6990 if self.sent_count == 0 &&
6993 ex_data.recovery_config != self.recovery_config
6994 {
6995 if let Ok(path) = self.paths.get_active_mut() {
6996 self.recovery_config = ex_data.recovery_config;
6997 path.reinit_recovery(&self.recovery_config);
6998 }
6999 }
7000
7001 let raw_params = self.handshake.quic_transport_params();
7008
7009 if !self.parsed_peer_transport_params && !raw_params.is_empty() {
7010 let peer_params = TransportParams::decode(
7011 raw_params,
7012 self.is_server,
7013 self.peer_transport_params_track_unknown,
7014 )?;
7015
7016 self.parse_peer_transport_params(peer_params)?;
7017 }
7018
7019 return Ok(());
7020 },
7021
7022 Err(e) => return Err(e),
7023 };
7024
7025 self.handshake_completed = self.handshake.is_completed();
7026
7027 self.alpn = self.handshake.alpn_protocol().to_vec();
7028
7029 let raw_params = self.handshake.quic_transport_params();
7030
7031 if !self.parsed_peer_transport_params && !raw_params.is_empty() {
7032 let peer_params = TransportParams::decode(
7033 raw_params,
7034 self.is_server,
7035 self.peer_transport_params_track_unknown,
7036 )?;
7037
7038 self.parse_peer_transport_params(peer_params)?;
7039 }
7040
7041 if self.handshake_completed {
7042 if self.is_server {
7046 self.handshake_confirmed = true;
7047
7048 self.drop_epoch_state(packet::Epoch::Handshake, now);
7049 }
7050
7051 self.undecryptable_pkts.clear();
7054
7055 trace!("{} connection established: proto={:?} cipher={:?} curve={:?} sigalg={:?} resumed={} {:?}",
7056 &self.trace_id,
7057 std::str::from_utf8(self.application_proto()),
7058 self.handshake.cipher(),
7059 self.handshake.curve(),
7060 self.handshake.sigalg(),
7061 self.handshake.is_resumed(),
7062 self.peer_transport_params);
7063 }
7064
7065 Ok(())
7066 }
7067
7068 fn write_pkt_type(&self, send_pid: usize) -> Result<packet::Type> {
7070 if self
7073 .local_error
7074 .as_ref()
7075 .is_some_and(|conn_err| !conn_err.is_app)
7076 {
7077 let epoch = match self.handshake.write_level() {
7078 crypto::Level::Initial => packet::Epoch::Initial,
7079 crypto::Level::ZeroRTT => unreachable!(),
7080 crypto::Level::Handshake => packet::Epoch::Handshake,
7081 crypto::Level::OneRTT => packet::Epoch::Application,
7082 };
7083
7084 if !self.handshake_confirmed {
7085 match epoch {
7086 packet::Epoch::Application =>
7089 return Ok(packet::Type::Handshake),
7090
7091 packet::Epoch::Handshake
7094 if self.pkt_num_spaces[packet::Epoch::Initial]
7095 .has_keys() =>
7096 return Ok(packet::Type::Initial),
7097
7098 _ => (),
7099 };
7100 }
7101
7102 return Ok(packet::Type::from_epoch(epoch));
7103 }
7104
7105 for &epoch in packet::Epoch::epochs(
7106 packet::Epoch::Initial..=packet::Epoch::Application,
7107 ) {
7108 if self.pkt_num_spaces[epoch].crypto_seal.is_none() {
7110 continue;
7111 }
7112
7113 if self.pkt_num_spaces[epoch].ready() {
7115 return Ok(packet::Type::from_epoch(epoch));
7116 }
7117
7118 for (_, p) in self.paths.iter() {
7120 if p.recovery.has_lost_frames(epoch) {
7121 return Ok(packet::Type::from_epoch(epoch));
7122 }
7123
7124 if p.recovery.loss_probes(epoch) > 0 {
7126 return Ok(packet::Type::from_epoch(epoch));
7127 }
7128 }
7129 }
7130
7131 let send_path = self.paths.get(send_pid)?;
7134 if (self.is_established() || self.is_in_early_data()) &&
7135 (self.should_send_handshake_done() ||
7136 self.almost_full ||
7137 self.blocked_limit.is_some() ||
7138 self.dgram_send_queue.has_pending() ||
7139 self.local_error
7140 .as_ref()
7141 .is_some_and(|conn_err| conn_err.is_app) ||
7142 self.streams.should_update_max_streams_bidi() ||
7143 self.streams.should_update_max_streams_uni() ||
7144 self.streams.has_flushable() ||
7145 self.streams.has_almost_full() ||
7146 self.streams.has_blocked() ||
7147 self.streams.has_reset() ||
7148 self.streams.has_stopped() ||
7149 self.ids.has_new_scids() ||
7150 self.ids.has_retire_dcids() ||
7151 send_path.pmtud.get_probe_status() ||
7152 send_path.needs_ack_eliciting ||
7153 send_path.probing_required())
7154 {
7155 if !self.is_server && self.is_in_early_data() {
7157 return Ok(packet::Type::ZeroRTT);
7158 }
7159
7160 return Ok(packet::Type::Short);
7161 }
7162
7163 Err(Error::Done)
7164 }
7165
7166 fn get_or_create_stream(
7169 &mut self, id: u64, local: bool,
7170 ) -> Result<&mut stream::Stream> {
7171 self.streams.get_or_create(
7172 id,
7173 &self.local_transport_params,
7174 &self.peer_transport_params,
7175 local,
7176 self.is_server,
7177 )
7178 }
7179
7180 fn process_frame(
7182 &mut self, frame: frame::Frame, hdr: &packet::Header,
7183 recv_path_id: usize, epoch: packet::Epoch, now: time::Instant,
7184 ) -> Result<()> {
7185 trace!("{} rx frm {:?}", self.trace_id, frame);
7186
7187 match frame {
7188 frame::Frame::Padding { .. } => (),
7189
7190 frame::Frame::Ping { .. } => (),
7191
7192 frame::Frame::ACK {
7193 ranges, ack_delay, ..
7194 } => {
7195 let ack_delay = ack_delay
7196 .checked_mul(2_u64.pow(
7197 self.peer_transport_params.ack_delay_exponent as u32,
7198 ))
7199 .ok_or(Error::InvalidFrame)?;
7200
7201 if epoch == packet::Epoch::Handshake ||
7202 (epoch == packet::Epoch::Application &&
7203 self.is_established())
7204 {
7205 self.peer_verified_initial_address = true;
7206 }
7207
7208 let handshake_status = self.handshake_status();
7209
7210 let is_app_limited = self.delivery_rate_check_if_app_limited();
7211
7212 for (_, p) in self.paths.iter_mut() {
7213 if is_app_limited {
7214 p.recovery.delivery_rate_update_app_limited(true);
7215 }
7216
7217 let (lost_packets, lost_bytes, acked_bytes) =
7218 p.recovery.on_ack_received(
7219 &ranges,
7220 ack_delay,
7221 epoch,
7222 handshake_status,
7223 now,
7224 &self.trace_id,
7225 );
7226
7227 self.lost_count += lost_packets;
7228 self.lost_bytes += lost_bytes as u64;
7229 self.acked_bytes += acked_bytes as u64;
7230 }
7231 },
7232
7233 frame::Frame::ResetStream {
7234 stream_id,
7235 error_code,
7236 final_size,
7237 } => {
7238 if !stream::is_bidi(stream_id) &&
7240 stream::is_local(stream_id, self.is_server)
7241 {
7242 return Err(Error::InvalidStreamState(stream_id));
7243 }
7244
7245 let max_rx_data_left = self.max_rx_data() - self.rx_data;
7246
7247 let stream = match self.get_or_create_stream(stream_id, false) {
7258 Ok(v) => v,
7259
7260 Err(Error::Done) => return Ok(()),
7261
7262 Err(e) => return Err(e),
7263 };
7264
7265 let was_readable = stream.is_readable();
7266 let priority_key = Arc::clone(&stream.priority_key);
7267
7268 let max_off_delta =
7269 stream.recv.reset(error_code, final_size)? as u64;
7270
7271 if max_off_delta > max_rx_data_left {
7272 return Err(Error::FlowControl);
7273 }
7274
7275 if !was_readable && stream.is_readable() {
7276 self.streams.insert_readable(&priority_key);
7277 }
7278
7279 self.rx_data += max_off_delta;
7280
7281 self.reset_stream_remote_count =
7282 self.reset_stream_remote_count.saturating_add(1);
7283 },
7284
7285 frame::Frame::StopSending {
7286 stream_id,
7287 error_code,
7288 } => {
7289 if !stream::is_local(stream_id, self.is_server) &&
7291 !stream::is_bidi(stream_id)
7292 {
7293 return Err(Error::InvalidStreamState(stream_id));
7294 }
7295
7296 let stream = match self.get_or_create_stream(stream_id, false) {
7307 Ok(v) => v,
7308
7309 Err(Error::Done) => return Ok(()),
7310
7311 Err(e) => return Err(e),
7312 };
7313
7314 let was_writable = stream.is_writable();
7315
7316 let priority_key = Arc::clone(&stream.priority_key);
7317
7318 if let Ok((final_size, unsent)) = stream.send.stop(error_code) {
7320 self.tx_data = self.tx_data.saturating_sub(unsent);
7327
7328 self.tx_buffered =
7329 self.tx_buffered.saturating_sub(unsent as usize);
7330
7331 self.streams.insert_reset(stream_id, error_code, final_size);
7332
7333 if !was_writable {
7334 self.streams.insert_writable(&priority_key);
7335 }
7336
7337 self.stopped_stream_remote_count =
7338 self.stopped_stream_remote_count.saturating_add(1);
7339 self.reset_stream_local_count =
7340 self.reset_stream_local_count.saturating_add(1);
7341 }
7342 },
7343
7344 frame::Frame::Crypto { data } => {
7345 if data.max_off() >= MAX_CRYPTO_STREAM_OFFSET {
7346 return Err(Error::CryptoBufferExceeded);
7347 }
7348
7349 self.pkt_num_spaces[epoch].crypto_stream.recv.write(data)?;
7351
7352 let mut crypto_buf = [0; 512];
7355
7356 let level = crypto::Level::from_epoch(epoch);
7357
7358 let stream = &mut self.pkt_num_spaces[epoch].crypto_stream;
7359
7360 while let Ok((read, _)) = stream.recv.emit(&mut crypto_buf) {
7361 let recv_buf = &crypto_buf[..read];
7362 self.handshake.provide_data(level, recv_buf)?;
7363 }
7364
7365 self.do_handshake(now)?;
7366 },
7367
7368 frame::Frame::CryptoHeader { .. } => unreachable!(),
7369
7370 frame::Frame::NewToken { .. } =>
7372 if self.is_server {
7373 return Err(Error::InvalidPacket);
7374 },
7375
7376 frame::Frame::Stream { stream_id, data } => {
7377 if !stream::is_bidi(stream_id) &&
7379 stream::is_local(stream_id, self.is_server)
7380 {
7381 return Err(Error::InvalidStreamState(stream_id));
7382 }
7383
7384 let max_rx_data_left = self.max_rx_data() - self.rx_data;
7385
7386 let stream = match self.get_or_create_stream(stream_id, false) {
7397 Ok(v) => v,
7398
7399 Err(Error::Done) => return Ok(()),
7400
7401 Err(e) => return Err(e),
7402 };
7403
7404 let max_off_delta =
7406 data.max_off().saturating_sub(stream.recv.max_off());
7407
7408 if max_off_delta > max_rx_data_left {
7409 return Err(Error::FlowControl);
7410 }
7411
7412 let was_readable = stream.is_readable();
7413 let priority_key = Arc::clone(&stream.priority_key);
7414
7415 let was_draining = stream.recv.is_draining();
7416
7417 stream.recv.write(data)?;
7418
7419 if !was_readable && stream.is_readable() {
7420 self.streams.insert_readable(&priority_key);
7421 }
7422
7423 self.rx_data += max_off_delta;
7424
7425 if was_draining {
7426 self.flow_control.add_consumed(max_off_delta);
7431
7432 if self.should_update_max_data() {
7433 self.almost_full = true;
7434 }
7435 }
7436 },
7437
7438 frame::Frame::StreamHeader { .. } => unreachable!(),
7439
7440 frame::Frame::MaxData { max } => {
7441 self.max_tx_data = cmp::max(self.max_tx_data, max);
7442 },
7443
7444 frame::Frame::MaxStreamData { stream_id, max } => {
7445 if !stream::is_bidi(stream_id) &&
7447 !stream::is_local(stream_id, self.is_server)
7448 {
7449 return Err(Error::InvalidStreamState(stream_id));
7450 }
7451
7452 let stream = match self.get_or_create_stream(stream_id, false) {
7463 Ok(v) => v,
7464
7465 Err(Error::Done) => return Ok(()),
7466
7467 Err(e) => return Err(e),
7468 };
7469
7470 let was_flushable = stream.is_flushable();
7471
7472 stream.send.update_max_data(max);
7473
7474 let writable = stream.is_writable();
7475
7476 let priority_key = Arc::clone(&stream.priority_key);
7477
7478 if stream.is_flushable() && !was_flushable {
7481 let priority_key = Arc::clone(&stream.priority_key);
7482 self.streams.insert_flushable(&priority_key);
7483 }
7484
7485 if writable {
7486 self.streams.insert_writable(&priority_key);
7487 }
7488 },
7489
7490 frame::Frame::MaxStreamsBidi { max } => {
7491 if max > MAX_STREAM_ID {
7492 return Err(Error::InvalidFrame);
7493 }
7494
7495 self.streams.update_peer_max_streams_bidi(max);
7496 },
7497
7498 frame::Frame::MaxStreamsUni { max } => {
7499 if max > MAX_STREAM_ID {
7500 return Err(Error::InvalidFrame);
7501 }
7502
7503 self.streams.update_peer_max_streams_uni(max);
7504 },
7505
7506 frame::Frame::DataBlocked { .. } => (),
7507
7508 frame::Frame::StreamDataBlocked { .. } => (),
7509
7510 frame::Frame::StreamsBlockedBidi { limit } => {
7511 if limit > MAX_STREAM_ID {
7512 return Err(Error::InvalidFrame);
7513 }
7514 },
7515
7516 frame::Frame::StreamsBlockedUni { limit } => {
7517 if limit > MAX_STREAM_ID {
7518 return Err(Error::InvalidFrame);
7519 }
7520 },
7521
7522 frame::Frame::NewConnectionId {
7523 seq_num,
7524 retire_prior_to,
7525 conn_id,
7526 reset_token,
7527 } => {
7528 if self.ids.zero_length_dcid() {
7529 return Err(Error::InvalidState);
7530 }
7531
7532 let mut retired_path_ids = SmallVec::new();
7533
7534 let new_dcid_res = self.ids.new_dcid(
7537 conn_id.into(),
7538 seq_num,
7539 u128::from_be_bytes(reset_token),
7540 retire_prior_to,
7541 &mut retired_path_ids,
7542 );
7543
7544 for (dcid_seq, pid) in retired_path_ids {
7545 let path = self.paths.get_mut(pid)?;
7546
7547 if path.active_dcid_seq != Some(dcid_seq) {
7549 continue;
7550 }
7551
7552 if let Some(new_dcid_seq) =
7553 self.ids.lowest_available_dcid_seq()
7554 {
7555 path.active_dcid_seq = Some(new_dcid_seq);
7556
7557 self.ids.link_dcid_to_path_id(new_dcid_seq, pid)?;
7558
7559 trace!(
7560 "{} path ID {} changed DCID: old seq num {} new seq num {}",
7561 self.trace_id, pid, dcid_seq, new_dcid_seq,
7562 );
7563 } else {
7564 path.active_dcid_seq = None;
7566
7567 trace!(
7568 "{} path ID {} cannot be used; DCID seq num {} has been retired",
7569 self.trace_id, pid, dcid_seq,
7570 );
7571 }
7572 }
7573
7574 new_dcid_res?;
7576 },
7577
7578 frame::Frame::RetireConnectionId { seq_num } => {
7579 if self.ids.zero_length_scid() {
7580 return Err(Error::InvalidState);
7581 }
7582
7583 if let Some(pid) = self.ids.retire_scid(seq_num, &hdr.dcid)? {
7584 let path = self.paths.get_mut(pid)?;
7585
7586 if path.active_scid_seq == Some(seq_num) {
7588 path.active_scid_seq = None;
7592 }
7593 }
7594 },
7595
7596 frame::Frame::PathChallenge { data } => {
7597 self.path_challenge_rx_count += 1;
7598
7599 self.paths
7600 .get_mut(recv_path_id)?
7601 .on_challenge_received(data);
7602 },
7603
7604 frame::Frame::PathResponse { data } => {
7605 self.paths.on_response_received(data)?;
7606 },
7607
7608 frame::Frame::ConnectionClose {
7609 error_code, reason, ..
7610 } => {
7611 self.peer_error = Some(ConnectionError {
7612 is_app: false,
7613 error_code,
7614 reason,
7615 });
7616
7617 let path = self.paths.get_active()?;
7618 self.draining_timer = Some(now + (path.recovery.pto() * 3));
7619 },
7620
7621 frame::Frame::ApplicationClose { error_code, reason } => {
7622 self.peer_error = Some(ConnectionError {
7623 is_app: true,
7624 error_code,
7625 reason,
7626 });
7627
7628 let path = self.paths.get_active()?;
7629 self.draining_timer = Some(now + (path.recovery.pto() * 3));
7630 },
7631
7632 frame::Frame::HandshakeDone => {
7633 if self.is_server {
7634 return Err(Error::InvalidPacket);
7635 }
7636
7637 self.peer_verified_initial_address = true;
7638
7639 self.handshake_confirmed = true;
7640
7641 self.drop_epoch_state(packet::Epoch::Handshake, now);
7643 },
7644
7645 frame::Frame::Datagram { data } => {
7646 if !self.dgram_enabled() {
7651 return Err(Error::InvalidState);
7652 }
7653
7654 if self.dgram_recv_queue.is_full() {
7656 self.dgram_recv_queue.pop();
7657 }
7658
7659 self.dgram_recv_queue.push(data)?;
7660
7661 let _ = self.dgram_recv_count.saturating_add(1);
7662 let _ = self
7663 .paths
7664 .get_mut(recv_path_id)?
7665 .dgram_recv_count
7666 .saturating_add(1);
7667 },
7668
7669 frame::Frame::DatagramHeader { .. } => unreachable!(),
7670 }
7671
7672 Ok(())
7673 }
7674
7675 fn drop_epoch_state(&mut self, epoch: packet::Epoch, now: time::Instant) {
7677 if self.pkt_num_spaces[epoch].crypto_open.is_none() {
7678 return;
7679 }
7680
7681 self.pkt_num_spaces[epoch].crypto_open = None;
7682 self.pkt_num_spaces[epoch].crypto_seal = None;
7683 self.pkt_num_spaces[epoch].clear();
7684
7685 let handshake_status = self.handshake_status();
7686 for (_, p) in self.paths.iter_mut() {
7687 p.recovery
7688 .on_pkt_num_space_discarded(epoch, handshake_status, now);
7689 }
7690
7691 trace!("{} dropped epoch {} state", self.trace_id, epoch);
7692 }
7693
7694 fn should_update_max_data(&self) -> bool {
7699 self.flow_control.should_update_max_data()
7700 }
7701
7702 fn max_rx_data(&self) -> u64 {
7704 self.flow_control.max_data()
7705 }
7706
7707 fn should_send_handshake_done(&self) -> bool {
7709 self.is_established() && !self.handshake_done_sent && self.is_server
7710 }
7711
7712 fn idle_timeout(&mut self) -> Option<time::Duration> {
7716 if self.local_transport_params.max_idle_timeout == 0 &&
7720 self.peer_transport_params.max_idle_timeout == 0
7721 {
7722 return None;
7723 }
7724
7725 let idle_timeout = if self.local_transport_params.max_idle_timeout == 0 {
7728 self.peer_transport_params.max_idle_timeout
7729 } else if self.peer_transport_params.max_idle_timeout == 0 {
7730 self.local_transport_params.max_idle_timeout
7731 } else {
7732 cmp::min(
7733 self.local_transport_params.max_idle_timeout,
7734 self.peer_transport_params.max_idle_timeout,
7735 )
7736 };
7737
7738 let path_pto = match self.paths.get_active() {
7739 Ok(p) => p.recovery.pto(),
7740 Err(_) => time::Duration::ZERO,
7741 };
7742
7743 let idle_timeout = time::Duration::from_millis(idle_timeout);
7744 let idle_timeout = cmp::max(idle_timeout, 3 * path_pto);
7745
7746 Some(idle_timeout)
7747 }
7748
7749 fn handshake_status(&self) -> recovery::HandshakeStatus {
7751 recovery::HandshakeStatus {
7752 has_handshake_keys: self.pkt_num_spaces[packet::Epoch::Handshake]
7753 .has_keys(),
7754
7755 peer_verified_address: self.peer_verified_initial_address,
7756
7757 completed: self.is_established(),
7758 }
7759 }
7760
7761 fn update_tx_cap(&mut self) {
7763 let cwin_available = match self.paths.get_active() {
7764 Ok(p) => p.recovery.cwnd_available() as u64,
7765 Err(_) => 0,
7766 };
7767
7768 self.tx_cap =
7769 cmp::min(cwin_available, self.max_tx_data - self.tx_data) as usize;
7770 }
7771
7772 fn delivery_rate_check_if_app_limited(&self) -> bool {
7773 let cwin_available = self
7789 .paths
7790 .iter()
7791 .filter(|&(_, p)| p.active())
7792 .map(|(_, p)| p.recovery.cwnd_available())
7793 .sum();
7794
7795 ((self.tx_buffered + self.dgram_send_queue_byte_size()) < cwin_available) &&
7796 (self.tx_data.saturating_sub(self.last_tx_data)) <
7797 cwin_available as u64 &&
7798 cwin_available > 0
7799 }
7800
7801 fn set_initial_dcid(
7802 &mut self, cid: ConnectionId<'static>, reset_token: Option<u128>,
7803 path_id: usize,
7804 ) -> Result<()> {
7805 self.ids.set_initial_dcid(cid, reset_token, Some(path_id));
7806 self.paths.get_mut(path_id)?.active_dcid_seq = Some(0);
7807
7808 Ok(())
7809 }
7810
7811 fn get_or_create_recv_path_id(
7814 &mut self, recv_pid: Option<usize>, dcid: &ConnectionId, buf_len: usize,
7815 info: &RecvInfo,
7816 ) -> Result<usize> {
7817 let ids = &mut self.ids;
7818
7819 let (in_scid_seq, mut in_scid_pid) =
7820 ids.find_scid_seq(dcid).ok_or(Error::InvalidState)?;
7821
7822 if let Some(recv_pid) = recv_pid {
7823 let recv_path = self.paths.get_mut(recv_pid)?;
7825
7826 let cid_entry =
7827 recv_path.active_scid_seq.and_then(|v| ids.get_scid(v).ok());
7828
7829 if cid_entry.map(|e| &e.cid) != Some(dcid) {
7830 let incoming_cid_entry = ids.get_scid(in_scid_seq)?;
7831
7832 let prev_recv_pid =
7833 incoming_cid_entry.path_id.unwrap_or(recv_pid);
7834
7835 if prev_recv_pid != recv_pid {
7836 trace!(
7837 "{} peer reused CID {:?} from path {} on path {}",
7838 self.trace_id,
7839 dcid,
7840 prev_recv_pid,
7841 recv_pid
7842 );
7843
7844 }
7846
7847 trace!(
7848 "{} path ID {} now see SCID with seq num {}",
7849 self.trace_id,
7850 recv_pid,
7851 in_scid_seq
7852 );
7853
7854 recv_path.active_scid_seq = Some(in_scid_seq);
7855 ids.link_scid_to_path_id(in_scid_seq, recv_pid)?;
7856 }
7857
7858 return Ok(recv_pid);
7859 }
7860
7861 if ids.zero_length_scid() {
7866 in_scid_pid = None;
7867 }
7868
7869 if let Some(in_scid_pid) = in_scid_pid {
7870 let old_path = self.paths.get_mut(in_scid_pid)?;
7874 let old_local_addr = old_path.local_addr();
7875 let old_peer_addr = old_path.peer_addr();
7876
7877 trace!(
7878 "{} reused CID seq {} of ({},{}) (path {}) on ({},{})",
7879 self.trace_id,
7880 in_scid_seq,
7881 old_local_addr,
7882 old_peer_addr,
7883 in_scid_pid,
7884 info.to,
7885 info.from
7886 );
7887
7888 self.paths
7890 .notify_event(path::PathEvent::ReusedSourceConnectionId(
7891 in_scid_seq,
7892 (old_local_addr, old_peer_addr),
7893 (info.to, info.from),
7894 ));
7895 }
7896
7897 let mut path = path::Path::new(
7899 info.to,
7900 info.from,
7901 &self.recovery_config,
7902 self.path_challenge_recv_max_queue_len,
7903 MIN_CLIENT_INITIAL_LEN,
7904 false,
7905 );
7906
7907 path.max_send_bytes = buf_len * self.max_amplification_factor;
7908 path.active_scid_seq = Some(in_scid_seq);
7909
7910 path.request_validation();
7912
7913 let pid = self.paths.insert_path(path, self.is_server)?;
7914
7915 if in_scid_pid.is_none() {
7917 ids.link_scid_to_path_id(in_scid_seq, pid)?;
7918 }
7919
7920 Ok(pid)
7921 }
7922
7923 fn get_send_path_id(
7925 &self, from: Option<SocketAddr>, to: Option<SocketAddr>,
7926 ) -> Result<usize> {
7927 if self.is_established() {
7930 let mut probing = self
7931 .paths
7932 .iter()
7933 .filter(|(_, p)| from.is_none() || Some(p.local_addr()) == from)
7934 .filter(|(_, p)| to.is_none() || Some(p.peer_addr()) == to)
7935 .filter(|(_, p)| p.active_dcid_seq.is_some())
7936 .filter(|(_, p)| p.probing_required())
7937 .map(|(pid, _)| pid);
7938
7939 if let Some(pid) = probing.next() {
7940 return Ok(pid);
7941 }
7942 }
7943
7944 if let Some((pid, p)) = self.paths.get_active_with_pid() {
7945 if from.is_some() && Some(p.local_addr()) != from {
7946 return Err(Error::Done);
7947 }
7948
7949 if to.is_some() && Some(p.peer_addr()) != to {
7950 return Err(Error::Done);
7951 }
7952
7953 return Ok(pid);
7954 };
7955
7956 Err(Error::InvalidState)
7957 }
7958
7959 fn set_active_path(
7961 &mut self, path_id: usize, now: time::Instant,
7962 ) -> Result<()> {
7963 if let Ok(old_active_path) = self.paths.get_active_mut() {
7964 for &e in packet::Epoch::epochs(
7965 packet::Epoch::Initial..=packet::Epoch::Application,
7966 ) {
7967 let (lost_packets, lost_bytes) = old_active_path
7968 .recovery
7969 .on_path_change(e, now, &self.trace_id);
7970
7971 self.lost_count += lost_packets;
7972 self.lost_bytes += lost_bytes as u64;
7973 }
7974 }
7975
7976 self.paths.set_active_path(path_id)
7977 }
7978
7979 fn on_peer_migrated(
7981 &mut self, new_pid: usize, disable_dcid_reuse: bool, now: time::Instant,
7982 ) -> Result<()> {
7983 let active_path_id = self.paths.get_active_path_id()?;
7984
7985 if active_path_id == new_pid {
7986 return Ok(());
7987 }
7988
7989 self.set_active_path(new_pid, now)?;
7990
7991 let no_spare_dcid =
7992 self.paths.get_mut(new_pid)?.active_dcid_seq.is_none();
7993
7994 if no_spare_dcid && !disable_dcid_reuse {
7995 self.paths.get_mut(new_pid)?.active_dcid_seq =
7996 self.paths.get_mut(active_path_id)?.active_dcid_seq;
7997 }
7998
7999 Ok(())
8000 }
8001
8002 fn create_path_on_client(
8004 &mut self, local_addr: SocketAddr, peer_addr: SocketAddr,
8005 ) -> Result<usize> {
8006 if self.is_server {
8007 return Err(Error::InvalidState);
8008 }
8009
8010 if !self.ids.zero_length_scid() && self.ids.available_scids() == 0 {
8013 return Err(Error::OutOfIdentifiers);
8014 }
8015
8016 let dcid_seq = if self.ids.zero_length_dcid() {
8020 0
8021 } else {
8022 self.ids
8023 .lowest_available_dcid_seq()
8024 .ok_or(Error::OutOfIdentifiers)?
8025 };
8026
8027 let mut path = path::Path::new(
8028 local_addr,
8029 peer_addr,
8030 &self.recovery_config,
8031 self.path_challenge_recv_max_queue_len,
8032 MIN_CLIENT_INITIAL_LEN,
8033 false,
8034 );
8035 path.active_dcid_seq = Some(dcid_seq);
8036
8037 let pid = self
8038 .paths
8039 .insert_path(path, false)
8040 .map_err(|_| Error::OutOfIdentifiers)?;
8041 self.ids.link_dcid_to_path_id(dcid_seq, pid)?;
8042
8043 Ok(pid)
8044 }
8045
8046 fn mark_closed(&mut self) {
8048 #[cfg(feature = "qlog")]
8049 {
8050 let cc = match (self.is_established(), self.timed_out, &self.peer_error, &self.local_error) {
8051 (false, _, _, _) => qlog::events::connectivity::ConnectionClosed {
8052 owner: Some(TransportOwner::Local),
8053 connection_code: None,
8054 application_code: None,
8055 internal_code: None,
8056 reason: Some("Failed to establish connection".to_string()),
8057 trigger: Some(qlog::events::connectivity::ConnectionClosedTrigger::HandshakeTimeout)
8058 },
8059
8060 (true, true, _, _) => qlog::events::connectivity::ConnectionClosed {
8061 owner: Some(TransportOwner::Local),
8062 connection_code: None,
8063 application_code: None,
8064 internal_code: None,
8065 reason: Some("Idle timeout".to_string()),
8066 trigger: Some(qlog::events::connectivity::ConnectionClosedTrigger::IdleTimeout)
8067 },
8068
8069 (true, false, Some(peer_error), None) => {
8070 let (connection_code, application_code, trigger) = if peer_error.is_app {
8071 (None, Some(qlog::events::ApplicationErrorCode::Value(peer_error.error_code)), None)
8072 } else {
8073 let trigger = if peer_error.error_code == WireErrorCode::NoError as u64 {
8074 Some(qlog::events::connectivity::ConnectionClosedTrigger::Clean)
8075 } else {
8076 Some(qlog::events::connectivity::ConnectionClosedTrigger::Error)
8077 };
8078
8079 (Some(qlog::events::ConnectionErrorCode::Value(peer_error.error_code)), None, trigger)
8080 };
8081
8082 qlog::events::connectivity::ConnectionClosed {
8083 owner: Some(TransportOwner::Remote),
8084 connection_code,
8085 application_code,
8086 internal_code: None,
8087 reason: Some(String::from_utf8_lossy(&peer_error.reason).to_string()),
8088 trigger,
8089 }
8090 },
8091
8092 (true, false, None, Some(local_error)) => {
8093 let (connection_code, application_code, trigger) = if local_error.is_app {
8094 (None, Some(qlog::events::ApplicationErrorCode::Value(local_error.error_code)), None)
8095 } else {
8096 let trigger = if local_error.error_code == WireErrorCode::NoError as u64 {
8097 Some(qlog::events::connectivity::ConnectionClosedTrigger::Clean)
8098 } else {
8099 Some(qlog::events::connectivity::ConnectionClosedTrigger::Error)
8100 };
8101
8102 (Some(qlog::events::ConnectionErrorCode::Value(local_error.error_code)), None, trigger)
8103 };
8104
8105 qlog::events::connectivity::ConnectionClosed {
8106 owner: Some(TransportOwner::Local),
8107 connection_code,
8108 application_code,
8109 internal_code: None,
8110 reason: Some(String::from_utf8_lossy(&local_error.reason).to_string()),
8111 trigger,
8112 }
8113 },
8114
8115 _ => qlog::events::connectivity::ConnectionClosed {
8116 owner: None,
8117 connection_code: None,
8118 application_code: None,
8119 internal_code: None,
8120 reason: None,
8121 trigger: None,
8122 },
8123 };
8124
8125 qlog_with_type!(QLOG_CONNECTION_CLOSED, self.qlog, q, {
8126 let ev_data = qlog::events::EventData::ConnectionClosed(cc);
8127
8128 q.add_event_data_now(ev_data).ok();
8129 });
8130 self.qlog.streamer = None;
8131 }
8132 self.closed = true;
8133 }
8134}
8135
8136#[cfg(feature = "boringssl-boring-crate")]
8137impl AsMut<boring::ssl::SslRef> for Connection {
8138 fn as_mut(&mut self) -> &mut boring::ssl::SslRef {
8139 self.handshake.ssl_mut()
8140 }
8141}
8142
8143fn drop_pkt_on_err(
8162 e: Error, recv_count: usize, is_server: bool, trace_id: &str,
8163) -> Error {
8164 if is_server && recv_count == 0 {
8168 return e;
8169 }
8170
8171 trace!("{} dropped invalid packet", trace_id);
8172
8173 Error::Done
8176}
8177
8178struct AddrTupleFmt(SocketAddr, SocketAddr);
8179
8180impl std::fmt::Display for AddrTupleFmt {
8181 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
8182 let AddrTupleFmt(src, dst) = &self;
8183
8184 if src.ip().is_unspecified() || dst.ip().is_unspecified() {
8185 return Ok(());
8186 }
8187
8188 f.write_fmt(format_args!("src:{src} dst:{dst}"))
8189 }
8190}
8191
8192#[derive(Clone, Default)]
8198pub struct Stats {
8199 pub recv: usize,
8201
8202 pub sent: usize,
8204
8205 pub lost: usize,
8207
8208 pub retrans: usize,
8210
8211 pub sent_bytes: u64,
8213
8214 pub recv_bytes: u64,
8216
8217 pub acked_bytes: u64,
8219
8220 pub lost_bytes: u64,
8222
8223 pub stream_retrans_bytes: u64,
8225
8226 pub dgram_recv: usize,
8228
8229 pub dgram_sent: usize,
8231
8232 pub paths_count: usize,
8234
8235 pub reset_stream_count_local: u64,
8237
8238 pub stopped_stream_count_local: u64,
8240
8241 pub reset_stream_count_remote: u64,
8243
8244 pub stopped_stream_count_remote: u64,
8246
8247 pub path_challenge_rx_count: u64,
8249}
8250
8251impl std::fmt::Debug for Stats {
8252 #[inline]
8253 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
8254 write!(
8255 f,
8256 "recv={} sent={} lost={} retrans={}",
8257 self.recv, self.sent, self.lost, self.retrans,
8258 )?;
8259
8260 write!(
8261 f,
8262 " sent_bytes={} recv_bytes={} lost_bytes={}",
8263 self.sent_bytes, self.recv_bytes, self.lost_bytes,
8264 )?;
8265
8266 Ok(())
8267 }
8268}
8269
8270#[derive(Clone, Debug, PartialEq)]
8275pub struct UnknownTransportParameter<T> {
8276 pub id: u64,
8278
8279 pub value: T,
8281}
8282
8283impl<T> UnknownTransportParameter<T> {
8284 pub fn is_reserved(&self) -> bool {
8289 let n = (self.id - 27) / 31;
8290 self.id == 31 * n + 27
8291 }
8292}
8293
8294#[cfg(feature = "qlog")]
8295impl From<UnknownTransportParameter<Vec<u8>>>
8296 for qlog::events::quic::UnknownTransportParameter
8297{
8298 fn from(value: UnknownTransportParameter<Vec<u8>>) -> Self {
8299 Self {
8300 id: value.id,
8301 value: qlog::HexSlice::maybe_string(Some(value.value.as_slice()))
8302 .unwrap_or_default(),
8303 }
8304 }
8305}
8306
8307impl From<UnknownTransportParameter<&[u8]>>
8308 for UnknownTransportParameter<Vec<u8>>
8309{
8310 fn from(value: UnknownTransportParameter<&[u8]>) -> Self {
8315 Self {
8316 id: value.id,
8317 value: value.value.to_vec(),
8318 }
8319 }
8320}
8321
8322#[derive(Clone, Debug, PartialEq, Default)]
8324pub struct UnknownTransportParameters {
8325 pub capacity: usize,
8327 pub parameters: Vec<UnknownTransportParameter<Vec<u8>>>,
8329}
8330
8331impl UnknownTransportParameters {
8332 pub fn push(&mut self, new: UnknownTransportParameter<&[u8]>) -> Result<()> {
8335 let new_unknown_tp_size = new.value.len() + std::mem::size_of::<u64>();
8336 if new_unknown_tp_size < self.capacity {
8337 self.capacity -= new_unknown_tp_size;
8338 self.parameters.push(new.into());
8339 Ok(())
8340 } else {
8341 Err(BufferTooShortError.into())
8342 }
8343 }
8344}
8345
8346pub struct UnknownTransportParameterIterator<'a> {
8348 index: usize,
8349 parameters: &'a Vec<UnknownTransportParameter<Vec<u8>>>,
8350}
8351
8352impl<'a> IntoIterator for &'a UnknownTransportParameters {
8353 type IntoIter = UnknownTransportParameterIterator<'a>;
8354 type Item = &'a UnknownTransportParameter<Vec<u8>>;
8355
8356 fn into_iter(self) -> Self::IntoIter {
8357 UnknownTransportParameterIterator {
8358 index: 0,
8359 parameters: &self.parameters,
8360 }
8361 }
8362}
8363
8364impl<'a> Iterator for UnknownTransportParameterIterator<'a> {
8365 type Item = &'a UnknownTransportParameter<Vec<u8>>;
8366
8367 fn next(&mut self) -> Option<Self::Item> {
8368 let result = self.parameters.get(self.index);
8369 self.index += 1;
8370 result
8371 }
8372}
8373
8374#[derive(Clone, Debug, PartialEq)]
8376pub struct TransportParams {
8377 pub original_destination_connection_id: Option<ConnectionId<'static>>,
8379 pub max_idle_timeout: u64,
8381 pub stateless_reset_token: Option<u128>,
8383 pub max_udp_payload_size: u64,
8385 pub initial_max_data: u64,
8387 pub initial_max_stream_data_bidi_local: u64,
8389 pub initial_max_stream_data_bidi_remote: u64,
8391 pub initial_max_stream_data_uni: u64,
8393 pub initial_max_streams_bidi: u64,
8395 pub initial_max_streams_uni: u64,
8397 pub ack_delay_exponent: u64,
8399 pub max_ack_delay: u64,
8401 pub disable_active_migration: bool,
8403 pub active_conn_id_limit: u64,
8405 pub initial_source_connection_id: Option<ConnectionId<'static>>,
8408 pub retry_source_connection_id: Option<ConnectionId<'static>>,
8411 pub max_datagram_frame_size: Option<u64>,
8413 pub unknown_params: Option<UnknownTransportParameters>,
8415 }
8417
8418impl Default for TransportParams {
8419 fn default() -> TransportParams {
8420 TransportParams {
8421 original_destination_connection_id: None,
8422 max_idle_timeout: 0,
8423 stateless_reset_token: None,
8424 max_udp_payload_size: 65527,
8425 initial_max_data: 0,
8426 initial_max_stream_data_bidi_local: 0,
8427 initial_max_stream_data_bidi_remote: 0,
8428 initial_max_stream_data_uni: 0,
8429 initial_max_streams_bidi: 0,
8430 initial_max_streams_uni: 0,
8431 ack_delay_exponent: 3,
8432 max_ack_delay: 25,
8433 disable_active_migration: false,
8434 active_conn_id_limit: 2,
8435 initial_source_connection_id: None,
8436 retry_source_connection_id: None,
8437 max_datagram_frame_size: None,
8438 unknown_params: Default::default(),
8439 }
8440 }
8441}
8442
8443impl TransportParams {
8444 fn decode(
8445 buf: &[u8], is_server: bool, unknown_size: Option<usize>,
8446 ) -> Result<TransportParams> {
8447 let mut params = octets::Octets::with_slice(buf);
8448 let mut seen_params = HashSet::new();
8449
8450 let mut tp = TransportParams::default();
8451
8452 if let Some(unknown_transport_param_tracking_size) = unknown_size {
8453 tp.unknown_params = Some(UnknownTransportParameters {
8454 capacity: unknown_transport_param_tracking_size,
8455 parameters: vec![],
8456 });
8457 }
8458
8459 while params.cap() > 0 {
8460 let id = params.get_varint()?;
8461
8462 if seen_params.contains(&id) {
8463 return Err(Error::InvalidTransportParam);
8464 }
8465 seen_params.insert(id);
8466
8467 let mut val = params.get_bytes_with_varint_length()?;
8468
8469 match id {
8470 0x0000 => {
8471 if is_server {
8472 return Err(Error::InvalidTransportParam);
8473 }
8474
8475 tp.original_destination_connection_id =
8476 Some(val.to_vec().into());
8477 },
8478
8479 0x0001 => {
8480 tp.max_idle_timeout = val.get_varint()?;
8481 },
8482
8483 0x0002 => {
8484 if is_server {
8485 return Err(Error::InvalidTransportParam);
8486 }
8487
8488 tp.stateless_reset_token = Some(u128::from_be_bytes(
8489 val.get_bytes(16)?
8490 .to_vec()
8491 .try_into()
8492 .map_err(|_| Error::BufferTooShort)?,
8493 ));
8494 },
8495
8496 0x0003 => {
8497 tp.max_udp_payload_size = val.get_varint()?;
8498
8499 if tp.max_udp_payload_size < 1200 {
8500 return Err(Error::InvalidTransportParam);
8501 }
8502 },
8503
8504 0x0004 => {
8505 tp.initial_max_data = val.get_varint()?;
8506 },
8507
8508 0x0005 => {
8509 tp.initial_max_stream_data_bidi_local = val.get_varint()?;
8510 },
8511
8512 0x0006 => {
8513 tp.initial_max_stream_data_bidi_remote = val.get_varint()?;
8514 },
8515
8516 0x0007 => {
8517 tp.initial_max_stream_data_uni = val.get_varint()?;
8518 },
8519
8520 0x0008 => {
8521 let max = val.get_varint()?;
8522
8523 if max > MAX_STREAM_ID {
8524 return Err(Error::InvalidTransportParam);
8525 }
8526
8527 tp.initial_max_streams_bidi = max;
8528 },
8529
8530 0x0009 => {
8531 let max = val.get_varint()?;
8532
8533 if max > MAX_STREAM_ID {
8534 return Err(Error::InvalidTransportParam);
8535 }
8536
8537 tp.initial_max_streams_uni = max;
8538 },
8539
8540 0x000a => {
8541 let ack_delay_exponent = val.get_varint()?;
8542
8543 if ack_delay_exponent > 20 {
8544 return Err(Error::InvalidTransportParam);
8545 }
8546
8547 tp.ack_delay_exponent = ack_delay_exponent;
8548 },
8549
8550 0x000b => {
8551 let max_ack_delay = val.get_varint()?;
8552
8553 if max_ack_delay >= 2_u64.pow(14) {
8554 return Err(Error::InvalidTransportParam);
8555 }
8556
8557 tp.max_ack_delay = max_ack_delay;
8558 },
8559
8560 0x000c => {
8561 tp.disable_active_migration = true;
8562 },
8563
8564 0x000d => {
8565 if is_server {
8566 return Err(Error::InvalidTransportParam);
8567 }
8568
8569 },
8571
8572 0x000e => {
8573 let limit = val.get_varint()?;
8574
8575 if limit < 2 {
8576 return Err(Error::InvalidTransportParam);
8577 }
8578
8579 tp.active_conn_id_limit = limit;
8580 },
8581
8582 0x000f => {
8583 tp.initial_source_connection_id = Some(val.to_vec().into());
8584 },
8585
8586 0x00010 => {
8587 if is_server {
8588 return Err(Error::InvalidTransportParam);
8589 }
8590
8591 tp.retry_source_connection_id = Some(val.to_vec().into());
8592 },
8593
8594 0x0020 => {
8595 tp.max_datagram_frame_size = Some(val.get_varint()?);
8596 },
8597
8598 unknown_tp_id => {
8600 if let Some(unknown_params) = &mut tp.unknown_params {
8601 let _ = unknown_params.push(UnknownTransportParameter {
8604 id: unknown_tp_id,
8605 value: val.buf(),
8606 });
8607 }
8608 },
8609 }
8610 }
8611
8612 Ok(tp)
8613 }
8614
8615 fn encode_param(
8616 b: &mut octets::OctetsMut, ty: u64, len: usize,
8617 ) -> Result<()> {
8618 b.put_varint(ty)?;
8619 b.put_varint(len as u64)?;
8620
8621 Ok(())
8622 }
8623
8624 fn encode<'a>(
8625 tp: &TransportParams, is_server: bool, out: &'a mut [u8],
8626 ) -> Result<&'a mut [u8]> {
8627 let mut b = octets::OctetsMut::with_slice(out);
8628
8629 if is_server {
8630 if let Some(ref odcid) = tp.original_destination_connection_id {
8631 TransportParams::encode_param(&mut b, 0x0000, odcid.len())?;
8632 b.put_bytes(odcid)?;
8633 }
8634 };
8635
8636 if tp.max_idle_timeout != 0 {
8637 TransportParams::encode_param(
8638 &mut b,
8639 0x0001,
8640 octets::varint_len(tp.max_idle_timeout),
8641 )?;
8642 b.put_varint(tp.max_idle_timeout)?;
8643 }
8644
8645 if is_server {
8646 if let Some(ref token) = tp.stateless_reset_token {
8647 TransportParams::encode_param(&mut b, 0x0002, 16)?;
8648 b.put_bytes(&token.to_be_bytes())?;
8649 }
8650 }
8651
8652 if tp.max_udp_payload_size != 0 {
8653 TransportParams::encode_param(
8654 &mut b,
8655 0x0003,
8656 octets::varint_len(tp.max_udp_payload_size),
8657 )?;
8658 b.put_varint(tp.max_udp_payload_size)?;
8659 }
8660
8661 if tp.initial_max_data != 0 {
8662 TransportParams::encode_param(
8663 &mut b,
8664 0x0004,
8665 octets::varint_len(tp.initial_max_data),
8666 )?;
8667 b.put_varint(tp.initial_max_data)?;
8668 }
8669
8670 if tp.initial_max_stream_data_bidi_local != 0 {
8671 TransportParams::encode_param(
8672 &mut b,
8673 0x0005,
8674 octets::varint_len(tp.initial_max_stream_data_bidi_local),
8675 )?;
8676 b.put_varint(tp.initial_max_stream_data_bidi_local)?;
8677 }
8678
8679 if tp.initial_max_stream_data_bidi_remote != 0 {
8680 TransportParams::encode_param(
8681 &mut b,
8682 0x0006,
8683 octets::varint_len(tp.initial_max_stream_data_bidi_remote),
8684 )?;
8685 b.put_varint(tp.initial_max_stream_data_bidi_remote)?;
8686 }
8687
8688 if tp.initial_max_stream_data_uni != 0 {
8689 TransportParams::encode_param(
8690 &mut b,
8691 0x0007,
8692 octets::varint_len(tp.initial_max_stream_data_uni),
8693 )?;
8694 b.put_varint(tp.initial_max_stream_data_uni)?;
8695 }
8696
8697 if tp.initial_max_streams_bidi != 0 {
8698 TransportParams::encode_param(
8699 &mut b,
8700 0x0008,
8701 octets::varint_len(tp.initial_max_streams_bidi),
8702 )?;
8703 b.put_varint(tp.initial_max_streams_bidi)?;
8704 }
8705
8706 if tp.initial_max_streams_uni != 0 {
8707 TransportParams::encode_param(
8708 &mut b,
8709 0x0009,
8710 octets::varint_len(tp.initial_max_streams_uni),
8711 )?;
8712 b.put_varint(tp.initial_max_streams_uni)?;
8713 }
8714
8715 if tp.ack_delay_exponent != 0 {
8716 TransportParams::encode_param(
8717 &mut b,
8718 0x000a,
8719 octets::varint_len(tp.ack_delay_exponent),
8720 )?;
8721 b.put_varint(tp.ack_delay_exponent)?;
8722 }
8723
8724 if tp.max_ack_delay != 0 {
8725 TransportParams::encode_param(
8726 &mut b,
8727 0x000b,
8728 octets::varint_len(tp.max_ack_delay),
8729 )?;
8730 b.put_varint(tp.max_ack_delay)?;
8731 }
8732
8733 if tp.disable_active_migration {
8734 TransportParams::encode_param(&mut b, 0x000c, 0)?;
8735 }
8736
8737 if tp.active_conn_id_limit != 2 {
8740 TransportParams::encode_param(
8741 &mut b,
8742 0x000e,
8743 octets::varint_len(tp.active_conn_id_limit),
8744 )?;
8745 b.put_varint(tp.active_conn_id_limit)?;
8746 }
8747
8748 if let Some(scid) = &tp.initial_source_connection_id {
8749 TransportParams::encode_param(&mut b, 0x000f, scid.len())?;
8750 b.put_bytes(scid)?;
8751 }
8752
8753 if is_server {
8754 if let Some(scid) = &tp.retry_source_connection_id {
8755 TransportParams::encode_param(&mut b, 0x0010, scid.len())?;
8756 b.put_bytes(scid)?;
8757 }
8758 }
8759
8760 if let Some(max_datagram_frame_size) = tp.max_datagram_frame_size {
8761 TransportParams::encode_param(
8762 &mut b,
8763 0x0020,
8764 octets::varint_len(max_datagram_frame_size),
8765 )?;
8766 b.put_varint(max_datagram_frame_size)?;
8767 }
8768
8769 let out_len = b.off();
8770
8771 Ok(&mut out[..out_len])
8772 }
8773
8774 #[cfg(feature = "qlog")]
8776 pub fn to_qlog(
8777 &self, owner: TransportOwner, cipher: Option<crypto::Algorithm>,
8778 ) -> EventData {
8779 let original_destination_connection_id = qlog::HexSlice::maybe_string(
8780 self.original_destination_connection_id.as_ref(),
8781 );
8782
8783 let stateless_reset_token = qlog::HexSlice::maybe_string(
8784 self.stateless_reset_token.map(|s| s.to_be_bytes()).as_ref(),
8785 );
8786
8787 let tls_cipher: Option<String> = cipher.map(|f| format!("{f:?}"));
8788
8789 EventData::TransportParametersSet(
8790 qlog::events::quic::TransportParametersSet {
8791 owner: Some(owner),
8792 tls_cipher,
8793 original_destination_connection_id,
8794 stateless_reset_token,
8795 disable_active_migration: Some(self.disable_active_migration),
8796 max_idle_timeout: Some(self.max_idle_timeout),
8797 max_udp_payload_size: Some(self.max_udp_payload_size as u32),
8798 ack_delay_exponent: Some(self.ack_delay_exponent as u16),
8799 max_ack_delay: Some(self.max_ack_delay as u16),
8800 active_connection_id_limit: Some(
8801 self.active_conn_id_limit as u32,
8802 ),
8803
8804 initial_max_data: Some(self.initial_max_data),
8805 initial_max_stream_data_bidi_local: Some(
8806 self.initial_max_stream_data_bidi_local,
8807 ),
8808 initial_max_stream_data_bidi_remote: Some(
8809 self.initial_max_stream_data_bidi_remote,
8810 ),
8811 initial_max_stream_data_uni: Some(
8812 self.initial_max_stream_data_uni,
8813 ),
8814 initial_max_streams_bidi: Some(self.initial_max_streams_bidi),
8815 initial_max_streams_uni: Some(self.initial_max_streams_uni),
8816
8817 unknown_parameters: self
8818 .unknown_params
8819 .as_ref()
8820 .map(|unknown_params| {
8821 unknown_params
8822 .into_iter()
8823 .cloned()
8824 .map(
8825 Into::<
8826 qlog::events::quic::UnknownTransportParameter,
8827 >::into,
8828 )
8829 .collect()
8830 })
8831 .unwrap_or_default(),
8832
8833 ..Default::default()
8834 },
8835 )
8836 }
8837}
8838
8839#[doc(hidden)]
8840pub mod testing {
8841 use super::*;
8842
8843 pub struct Pipe {
8844 pub client: Connection,
8845 pub server: Connection,
8846 }
8847
8848 impl Pipe {
8849 pub fn new() -> Result<Pipe> {
8850 let mut config = Config::new(crate::PROTOCOL_VERSION)?;
8851 config.load_cert_chain_from_pem_file("examples/cert.crt")?;
8852 config.load_priv_key_from_pem_file("examples/cert.key")?;
8853 config.set_application_protos(&[b"proto1", b"proto2"])?;
8854 config.set_initial_max_data(30);
8855 config.set_initial_max_stream_data_bidi_local(15);
8856 config.set_initial_max_stream_data_bidi_remote(15);
8857 config.set_initial_max_stream_data_uni(10);
8858 config.set_initial_max_streams_bidi(3);
8859 config.set_initial_max_streams_uni(3);
8860 config.set_max_idle_timeout(180_000);
8861 config.verify_peer(false);
8862 config.set_ack_delay_exponent(8);
8863
8864 Pipe::with_config(&mut config)
8865 }
8866
8867 pub fn client_addr() -> SocketAddr {
8868 "127.0.0.1:1234".parse().unwrap()
8869 }
8870
8871 pub fn server_addr() -> SocketAddr {
8872 "127.0.0.1:4321".parse().unwrap()
8873 }
8874
8875 pub fn with_config(config: &mut Config) -> Result<Pipe> {
8876 let mut client_scid = [0; 16];
8877 rand::rand_bytes(&mut client_scid[..]);
8878 let client_scid = ConnectionId::from_ref(&client_scid);
8879 let client_addr = Pipe::client_addr();
8880
8881 let mut server_scid = [0; 16];
8882 rand::rand_bytes(&mut server_scid[..]);
8883 let server_scid = ConnectionId::from_ref(&server_scid);
8884 let server_addr = Pipe::server_addr();
8885
8886 Ok(Pipe {
8887 client: connect(
8888 Some("quic.tech"),
8889 &client_scid,
8890 client_addr,
8891 server_addr,
8892 config,
8893 )?,
8894 server: accept(
8895 &server_scid,
8896 None,
8897 server_addr,
8898 client_addr,
8899 config,
8900 )?,
8901 })
8902 }
8903
8904 pub fn with_config_and_scid_lengths(
8905 config: &mut Config, client_scid_len: usize, server_scid_len: usize,
8906 ) -> Result<Pipe> {
8907 let mut client_scid = vec![0; client_scid_len];
8908 rand::rand_bytes(&mut client_scid[..]);
8909 let client_scid = ConnectionId::from_ref(&client_scid);
8910 let client_addr = Pipe::client_addr();
8911
8912 let mut server_scid = vec![0; server_scid_len];
8913 rand::rand_bytes(&mut server_scid[..]);
8914 let server_scid = ConnectionId::from_ref(&server_scid);
8915 let server_addr = Pipe::server_addr();
8916
8917 Ok(Pipe {
8918 client: connect(
8919 Some("quic.tech"),
8920 &client_scid,
8921 client_addr,
8922 server_addr,
8923 config,
8924 )?,
8925 server: accept(
8926 &server_scid,
8927 None,
8928 server_addr,
8929 client_addr,
8930 config,
8931 )?,
8932 })
8933 }
8934
8935 pub fn with_client_config(client_config: &mut Config) -> Result<Pipe> {
8936 let mut client_scid = [0; 16];
8937 rand::rand_bytes(&mut client_scid[..]);
8938 let client_scid = ConnectionId::from_ref(&client_scid);
8939 let client_addr = Pipe::client_addr();
8940
8941 let mut server_scid = [0; 16];
8942 rand::rand_bytes(&mut server_scid[..]);
8943 let server_scid = ConnectionId::from_ref(&server_scid);
8944 let server_addr = Pipe::server_addr();
8945
8946 let mut config = Config::new(crate::PROTOCOL_VERSION)?;
8947 config.load_cert_chain_from_pem_file("examples/cert.crt")?;
8948 config.load_priv_key_from_pem_file("examples/cert.key")?;
8949 config.set_application_protos(&[b"proto1", b"proto2"])?;
8950 config.set_initial_max_data(30);
8951 config.set_initial_max_stream_data_bidi_local(15);
8952 config.set_initial_max_stream_data_bidi_remote(15);
8953 config.set_initial_max_streams_bidi(3);
8954 config.set_initial_max_streams_uni(3);
8955 config.set_ack_delay_exponent(8);
8956
8957 Ok(Pipe {
8958 client: connect(
8959 Some("quic.tech"),
8960 &client_scid,
8961 client_addr,
8962 server_addr,
8963 client_config,
8964 )?,
8965 server: accept(
8966 &server_scid,
8967 None,
8968 server_addr,
8969 client_addr,
8970 &mut config,
8971 )?,
8972 })
8973 }
8974
8975 pub fn with_server_config(server_config: &mut Config) -> Result<Pipe> {
8976 let mut client_scid = [0; 16];
8977 rand::rand_bytes(&mut client_scid[..]);
8978 let client_scid = ConnectionId::from_ref(&client_scid);
8979 let client_addr = Pipe::client_addr();
8980
8981 let mut server_scid = [0; 16];
8982 rand::rand_bytes(&mut server_scid[..]);
8983 let server_scid = ConnectionId::from_ref(&server_scid);
8984 let server_addr = Pipe::server_addr();
8985
8986 let mut config = Config::new(crate::PROTOCOL_VERSION)?;
8987 config.set_application_protos(&[b"proto1", b"proto2"])?;
8988 config.set_initial_max_data(30);
8989 config.set_initial_max_stream_data_bidi_local(15);
8990 config.set_initial_max_stream_data_bidi_remote(15);
8991 config.set_initial_max_streams_bidi(3);
8992 config.set_initial_max_streams_uni(3);
8993 config.set_ack_delay_exponent(8);
8994
8995 Ok(Pipe {
8996 client: connect(
8997 Some("quic.tech"),
8998 &client_scid,
8999 client_addr,
9000 server_addr,
9001 &mut config,
9002 )?,
9003 server: accept(
9004 &server_scid,
9005 None,
9006 server_addr,
9007 client_addr,
9008 server_config,
9009 )?,
9010 })
9011 }
9012
9013 pub fn with_client_and_server_config(
9014 client_config: &mut Config, server_config: &mut Config,
9015 ) -> Result<Pipe> {
9016 let mut client_scid = [0; 16];
9017 rand::rand_bytes(&mut client_scid[..]);
9018 let client_scid = ConnectionId::from_ref(&client_scid);
9019 let client_addr = Pipe::client_addr();
9020
9021 let mut server_scid = [0; 16];
9022 rand::rand_bytes(&mut server_scid[..]);
9023 let server_scid = ConnectionId::from_ref(&server_scid);
9024 let server_addr = Pipe::server_addr();
9025
9026 Ok(Pipe {
9027 client: connect(
9028 Some("quic.tech"),
9029 &client_scid,
9030 client_addr,
9031 server_addr,
9032 client_config,
9033 )?,
9034 server: accept(
9035 &server_scid,
9036 None,
9037 server_addr,
9038 client_addr,
9039 server_config,
9040 )?,
9041 })
9042 }
9043
9044 pub fn handshake(&mut self) -> Result<()> {
9045 while !self.client.is_established() || !self.server.is_established() {
9046 let flight = emit_flight(&mut self.client)?;
9047 process_flight(&mut self.server, flight)?;
9048
9049 let flight = emit_flight(&mut self.server)?;
9050 process_flight(&mut self.client, flight)?;
9051 }
9052
9053 Ok(())
9054 }
9055
9056 pub fn advance(&mut self) -> Result<()> {
9057 let mut client_done = false;
9058 let mut server_done = false;
9059
9060 while !client_done || !server_done {
9061 match emit_flight(&mut self.client) {
9062 Ok(flight) => process_flight(&mut self.server, flight)?,
9063
9064 Err(Error::Done) => client_done = true,
9065
9066 Err(e) => return Err(e),
9067 };
9068
9069 match emit_flight(&mut self.server) {
9070 Ok(flight) => process_flight(&mut self.client, flight)?,
9071
9072 Err(Error::Done) => server_done = true,
9073
9074 Err(e) => return Err(e),
9075 };
9076 }
9077
9078 Ok(())
9079 }
9080
9081 pub fn client_recv(&mut self, buf: &mut [u8]) -> Result<usize> {
9082 let server_path = &self.server.paths.get_active().unwrap();
9083 let info = RecvInfo {
9084 to: server_path.peer_addr(),
9085 from: server_path.local_addr(),
9086 };
9087
9088 self.client.recv(buf, info)
9089 }
9090
9091 pub fn server_recv(&mut self, buf: &mut [u8]) -> Result<usize> {
9092 let client_path = &self.client.paths.get_active().unwrap();
9093 let info = RecvInfo {
9094 to: client_path.peer_addr(),
9095 from: client_path.local_addr(),
9096 };
9097
9098 self.server.recv(buf, info)
9099 }
9100
9101 pub fn send_pkt_to_server(
9102 &mut self, pkt_type: packet::Type, frames: &[frame::Frame],
9103 buf: &mut [u8],
9104 ) -> Result<usize> {
9105 let written = encode_pkt(&mut self.client, pkt_type, frames, buf)?;
9106 recv_send(&mut self.server, buf, written)
9107 }
9108
9109 pub fn client_update_key(&mut self) -> Result<()> {
9110 let space =
9111 &mut self.client.pkt_num_spaces[packet::Epoch::Application];
9112
9113 let open_next = space
9114 .crypto_open
9115 .as_ref()
9116 .unwrap()
9117 .derive_next_packet_key()
9118 .unwrap();
9119
9120 let seal_next = space
9121 .crypto_seal
9122 .as_ref()
9123 .unwrap()
9124 .derive_next_packet_key()?;
9125
9126 let open_prev = space.crypto_open.replace(open_next);
9127 space.crypto_seal.replace(seal_next);
9128
9129 space.key_update = Some(packet::KeyUpdate {
9130 crypto_open: open_prev.unwrap(),
9131 pn_on_update: self.client.next_pkt_num,
9132 update_acked: true,
9133 timer: time::Instant::now(),
9134 });
9135
9136 self.client.key_phase = !self.client.key_phase;
9137
9138 Ok(())
9139 }
9140 }
9141
9142 pub fn recv_send(
9143 conn: &mut Connection, buf: &mut [u8], len: usize,
9144 ) -> Result<usize> {
9145 let active_path = conn.paths.get_active()?;
9146 let info = RecvInfo {
9147 to: active_path.local_addr(),
9148 from: active_path.peer_addr(),
9149 };
9150
9151 conn.recv(&mut buf[..len], info)?;
9152
9153 let mut off = 0;
9154
9155 match conn.send(&mut buf[off..]) {
9156 Ok((write, _)) => off += write,
9157
9158 Err(Error::Done) => (),
9159
9160 Err(e) => return Err(e),
9161 }
9162
9163 Ok(off)
9164 }
9165
9166 pub fn process_flight(
9167 conn: &mut Connection, flight: Vec<(Vec<u8>, SendInfo)>,
9168 ) -> Result<()> {
9169 for (mut pkt, si) in flight {
9170 let info = RecvInfo {
9171 to: si.to,
9172 from: si.from,
9173 };
9174
9175 conn.recv(&mut pkt, info)?;
9176 }
9177
9178 Ok(())
9179 }
9180
9181 pub fn emit_flight_with_max_buffer(
9182 conn: &mut Connection, out_size: usize, from: Option<SocketAddr>,
9183 to: Option<SocketAddr>,
9184 ) -> Result<Vec<(Vec<u8>, SendInfo)>> {
9185 let mut flight = Vec::new();
9186
9187 loop {
9188 let mut out = vec![0u8; out_size];
9189
9190 let info = match conn.send_on_path(&mut out, from, to) {
9191 Ok((written, info)) => {
9192 out.truncate(written);
9193 info
9194 },
9195
9196 Err(Error::Done) => break,
9197
9198 Err(e) => return Err(e),
9199 };
9200
9201 flight.push((out, info));
9202 }
9203
9204 if flight.is_empty() {
9205 return Err(Error::Done);
9206 }
9207
9208 Ok(flight)
9209 }
9210
9211 pub fn emit_flight_on_path(
9212 conn: &mut Connection, from: Option<SocketAddr>, to: Option<SocketAddr>,
9213 ) -> Result<Vec<(Vec<u8>, SendInfo)>> {
9214 emit_flight_with_max_buffer(conn, 65535, from, to)
9215 }
9216
9217 pub fn emit_flight(
9218 conn: &mut Connection,
9219 ) -> Result<Vec<(Vec<u8>, SendInfo)>> {
9220 emit_flight_on_path(conn, None, None)
9221 }
9222
9223 pub fn encode_pkt(
9224 conn: &mut Connection, pkt_type: packet::Type, frames: &[frame::Frame],
9225 buf: &mut [u8],
9226 ) -> Result<usize> {
9227 let mut b = octets::OctetsMut::with_slice(buf);
9228
9229 let epoch = pkt_type.to_epoch()?;
9230
9231 let space = &mut conn.pkt_num_spaces[epoch];
9232
9233 let pn = conn.next_pkt_num;
9234 let pn_len = 4;
9235
9236 let send_path = conn.paths.get_active()?;
9237 let active_dcid_seq = send_path
9238 .active_dcid_seq
9239 .as_ref()
9240 .ok_or(Error::InvalidState)?;
9241 let active_scid_seq = send_path
9242 .active_scid_seq
9243 .as_ref()
9244 .ok_or(Error::InvalidState)?;
9245
9246 let hdr = Header {
9247 ty: pkt_type,
9248 version: conn.version,
9249 dcid: ConnectionId::from_ref(
9250 conn.ids.get_dcid(*active_dcid_seq)?.cid.as_ref(),
9251 ),
9252 scid: ConnectionId::from_ref(
9253 conn.ids.get_scid(*active_scid_seq)?.cid.as_ref(),
9254 ),
9255 pkt_num: pn,
9256 pkt_num_len: pn_len,
9257 token: conn.token.clone(),
9258 versions: None,
9259 key_phase: conn.key_phase,
9260 };
9261
9262 hdr.to_bytes(&mut b)?;
9263
9264 let payload_len = frames.iter().fold(0, |acc, x| acc + x.wire_len());
9265
9266 if pkt_type != packet::Type::Short {
9267 let len = pn_len + payload_len + space.crypto_overhead().unwrap();
9268 b.put_varint(len as u64)?;
9269 }
9270
9271 b.put_u32(pn as u32)?;
9274
9275 let payload_offset = b.off();
9276
9277 for frame in frames {
9278 frame.to_bytes(&mut b)?;
9279 }
9280
9281 let aead = match space.crypto_seal {
9282 Some(ref v) => v,
9283 None => return Err(Error::InvalidState),
9284 };
9285
9286 let written = packet::encrypt_pkt(
9287 &mut b,
9288 pn,
9289 pn_len,
9290 payload_len,
9291 payload_offset,
9292 None,
9293 aead,
9294 )?;
9295
9296 conn.next_pkt_num += 1;
9297
9298 Ok(written)
9299 }
9300
9301 pub fn decode_pkt(
9302 conn: &mut Connection, buf: &mut [u8],
9303 ) -> Result<Vec<frame::Frame>> {
9304 let mut b = octets::OctetsMut::with_slice(buf);
9305
9306 let mut hdr = Header::from_bytes(&mut b, conn.source_id().len()).unwrap();
9307
9308 let epoch = hdr.ty.to_epoch()?;
9309
9310 let aead = conn.pkt_num_spaces[epoch].crypto_open.as_ref().unwrap();
9311
9312 let payload_len = b.cap();
9313
9314 packet::decrypt_hdr(&mut b, &mut hdr, aead).unwrap();
9315
9316 let pn = packet::decode_pkt_num(
9317 conn.pkt_num_spaces[epoch].largest_rx_pkt_num,
9318 hdr.pkt_num,
9319 hdr.pkt_num_len,
9320 );
9321
9322 let mut payload =
9323 packet::decrypt_pkt(&mut b, pn, hdr.pkt_num_len, payload_len, aead)
9324 .unwrap();
9325
9326 let mut frames = Vec::new();
9327
9328 while payload.cap() > 0 {
9329 let frame = frame::Frame::from_bytes(&mut payload, hdr.ty)?;
9330 frames.push(frame);
9331 }
9332
9333 Ok(frames)
9334 }
9335
9336 pub fn create_cid_and_reset_token(
9337 cid_len: usize,
9338 ) -> (ConnectionId<'static>, u128) {
9339 let mut cid = vec![0; cid_len];
9340 rand::rand_bytes(&mut cid[..]);
9341 let cid = ConnectionId::from_ref(&cid).into_owned();
9342
9343 let mut reset_token = [0; 16];
9344 rand::rand_bytes(&mut reset_token);
9345 let reset_token = u128::from_be_bytes(reset_token);
9346
9347 (cid, reset_token)
9348 }
9349}
9350
9351#[cfg(test)]
9352mod tests {
9353 use super::*;
9354
9355 #[test]
9356 fn transport_params() {
9357 let tp = TransportParams {
9359 original_destination_connection_id: None,
9360 max_idle_timeout: 30,
9361 stateless_reset_token: Some(u128::from_be_bytes([0xba; 16])),
9362 max_udp_payload_size: 23_421,
9363 initial_max_data: 424_645_563,
9364 initial_max_stream_data_bidi_local: 154_323_123,
9365 initial_max_stream_data_bidi_remote: 6_587_456,
9366 initial_max_stream_data_uni: 2_461_234,
9367 initial_max_streams_bidi: 12_231,
9368 initial_max_streams_uni: 18_473,
9369 ack_delay_exponent: 20,
9370 max_ack_delay: 2_u64.pow(14) - 1,
9371 disable_active_migration: true,
9372 active_conn_id_limit: 8,
9373 initial_source_connection_id: Some(b"woot woot".to_vec().into()),
9374 retry_source_connection_id: Some(b"retry".to_vec().into()),
9375 max_datagram_frame_size: Some(32),
9376 unknown_params: Default::default(),
9377 };
9378
9379 let mut raw_params = [42; 256];
9380 let raw_params =
9381 TransportParams::encode(&tp, true, &mut raw_params).unwrap();
9382 assert_eq!(raw_params.len(), 94);
9383
9384 let new_tp = TransportParams::decode(raw_params, false, None).unwrap();
9385
9386 assert_eq!(new_tp, tp);
9387
9388 let tp = TransportParams {
9390 original_destination_connection_id: None,
9391 max_idle_timeout: 30,
9392 stateless_reset_token: None,
9393 max_udp_payload_size: 23_421,
9394 initial_max_data: 424_645_563,
9395 initial_max_stream_data_bidi_local: 154_323_123,
9396 initial_max_stream_data_bidi_remote: 6_587_456,
9397 initial_max_stream_data_uni: 2_461_234,
9398 initial_max_streams_bidi: 12_231,
9399 initial_max_streams_uni: 18_473,
9400 ack_delay_exponent: 20,
9401 max_ack_delay: 2_u64.pow(14) - 1,
9402 disable_active_migration: true,
9403 active_conn_id_limit: 8,
9404 initial_source_connection_id: Some(b"woot woot".to_vec().into()),
9405 retry_source_connection_id: None,
9406 max_datagram_frame_size: Some(32),
9407 unknown_params: Default::default(),
9408 };
9409
9410 let mut raw_params = [42; 256];
9411 let raw_params =
9412 TransportParams::encode(&tp, false, &mut raw_params).unwrap();
9413 assert_eq!(raw_params.len(), 69);
9414
9415 let new_tp = TransportParams::decode(raw_params, true, None).unwrap();
9416
9417 assert_eq!(new_tp, tp);
9418 }
9419
9420 #[test]
9421 fn transport_params_forbid_duplicates() {
9422 let initial_source_connection_id = b"id";
9424 let initial_source_connection_id_raw = [
9425 15,
9426 initial_source_connection_id.len() as u8,
9427 initial_source_connection_id[0],
9428 initial_source_connection_id[1],
9429 ];
9430
9431 let tp = TransportParams::decode(
9433 initial_source_connection_id_raw.as_slice(),
9434 true,
9435 None,
9436 )
9437 .unwrap();
9438
9439 assert_eq!(
9440 tp.initial_source_connection_id,
9441 Some(initial_source_connection_id.to_vec().into())
9442 );
9443
9444 let mut raw_params = Vec::new();
9446 raw_params.append(&mut initial_source_connection_id_raw.to_vec());
9447 raw_params.append(&mut initial_source_connection_id_raw.to_vec());
9448
9449 assert_eq!(
9451 TransportParams::decode(raw_params.as_slice(), true, None),
9452 Err(Error::InvalidTransportParam)
9453 );
9454 }
9455
9456 #[test]
9457 fn transport_params_unknown_zero_space() {
9458 let mut unknown_params: UnknownTransportParameters =
9459 UnknownTransportParameters {
9460 capacity: 0,
9461 parameters: vec![],
9462 };
9463 let massive_unknown_param = UnknownTransportParameter::<&[u8]> {
9464 id: 5,
9465 value: &[0xau8; 280],
9466 };
9467 assert!(unknown_params.push(massive_unknown_param).is_err());
9468 assert!(unknown_params.capacity == 0);
9469 assert!(unknown_params.parameters.is_empty());
9470 }
9471
9472 #[test]
9473 fn transport_params_unknown_max_space_respected() {
9474 let mut unknown_params: UnknownTransportParameters =
9475 UnknownTransportParameters {
9476 capacity: 256,
9477 parameters: vec![],
9478 };
9479
9480 let massive_unknown_param = UnknownTransportParameter::<&[u8]> {
9481 id: 5,
9482 value: &[0xau8; 280],
9483 };
9484 let big_unknown_param = UnknownTransportParameter::<&[u8]> {
9485 id: 5,
9486 value: &[0xau8; 232],
9487 };
9488 let little_unknown_param = UnknownTransportParameter::<&[u8]> {
9489 id: 6,
9490 value: &[0xau8; 7],
9491 };
9492
9493 assert!(unknown_params.push(massive_unknown_param).is_err());
9494 assert!(unknown_params.capacity == 256);
9495 assert!(unknown_params.parameters.is_empty());
9496
9497 unknown_params.push(big_unknown_param).unwrap();
9498 assert!(unknown_params.capacity == 16);
9499 assert!(unknown_params.parameters.len() == 1);
9500
9501 unknown_params.push(little_unknown_param.clone()).unwrap();
9502 assert!(unknown_params.capacity == 1);
9503 assert!(unknown_params.parameters.len() == 2);
9504
9505 assert!(unknown_params.push(little_unknown_param).is_err());
9506
9507 let mut unknown_params_iter = unknown_params.into_iter();
9508
9509 let unknown_params_first = unknown_params_iter
9510 .next()
9511 .expect("Should have a 0th element.");
9512 assert!(
9513 unknown_params_first.id == 5 &&
9514 unknown_params_first.value == vec![0xau8; 232]
9515 );
9516
9517 let unknown_params_second = unknown_params_iter
9518 .next()
9519 .expect("Should have a 1th element.");
9520 assert!(
9521 unknown_params_second.id == 6 &&
9522 unknown_params_second.value == vec![0xau8; 7]
9523 );
9524 }
9525
9526 #[test]
9527 fn transport_params_unknown_is_reserved() {
9528 let reserved_unknown_param = UnknownTransportParameter::<&[u8]> {
9529 id: 31 * 17 + 27,
9530 value: &[0xau8; 280],
9531 };
9532 let not_reserved_unknown_param = UnknownTransportParameter::<&[u8]> {
9533 id: 32 * 17 + 27,
9534 value: &[0xau8; 280],
9535 };
9536
9537 assert!(reserved_unknown_param.is_reserved());
9538 assert!(!not_reserved_unknown_param.is_reserved());
9539 }
9540 #[test]
9541 fn unknown_version() {
9542 let mut config = Config::new(0xbabababa).unwrap();
9543 config
9544 .set_application_protos(&[b"proto1", b"proto2"])
9545 .unwrap();
9546 config.verify_peer(false);
9547
9548 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
9549 assert_eq!(pipe.handshake(), Err(Error::UnknownVersion));
9550 }
9551
9552 #[test]
9553 fn config_version_reserved() {
9554 Config::new(0xbabababa).unwrap();
9555 Config::new(0x1a2a3a4a).unwrap();
9556 }
9557
9558 #[test]
9559 fn config_version_invalid() {
9560 assert_eq!(
9561 Config::new(0xb1bababa).err().unwrap(),
9562 Error::UnknownVersion
9563 );
9564 }
9565
9566 #[test]
9567 fn version_negotiation() {
9568 let mut buf = [0; 65535];
9569
9570 let mut config = Config::new(0xbabababa).unwrap();
9571 config
9572 .set_application_protos(&[b"proto1", b"proto2"])
9573 .unwrap();
9574 config.verify_peer(false);
9575
9576 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
9577
9578 let (mut len, _) = pipe.client.send(&mut buf).unwrap();
9579
9580 let hdr = packet::Header::from_slice(&mut buf[..len], 0).unwrap();
9581 len = crate::negotiate_version(&hdr.scid, &hdr.dcid, &mut buf).unwrap();
9582
9583 assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
9584
9585 assert_eq!(pipe.handshake(), Ok(()));
9586
9587 assert_eq!(pipe.client.version, PROTOCOL_VERSION);
9588 assert_eq!(pipe.server.version, PROTOCOL_VERSION);
9589 }
9590
9591 #[test]
9592 fn verify_custom_root() {
9593 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
9594 config.verify_peer(true);
9595 config
9596 .load_verify_locations_from_file("examples/rootca.crt")
9597 .unwrap();
9598 config
9599 .set_application_protos(&[b"proto1", b"proto2"])
9600 .unwrap();
9601
9602 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
9603 assert_eq!(pipe.handshake(), Ok(()));
9604 }
9605
9606 #[cfg(not(feature = "openssl"))]
9609 #[test]
9610 fn verify_client_invalid() {
9611 let mut server_config = Config::new(crate::PROTOCOL_VERSION).unwrap();
9612 server_config
9613 .load_cert_chain_from_pem_file("examples/cert.crt")
9614 .unwrap();
9615 server_config
9616 .load_priv_key_from_pem_file("examples/cert.key")
9617 .unwrap();
9618 server_config
9619 .set_application_protos(&[b"proto1", b"proto2"])
9620 .unwrap();
9621 server_config.set_initial_max_data(30);
9622 server_config.set_initial_max_stream_data_bidi_local(15);
9623 server_config.set_initial_max_stream_data_bidi_remote(15);
9624 server_config.set_initial_max_streams_bidi(3);
9625
9626 server_config.verify_peer(true);
9629
9630 let mut client_config = Config::new(crate::PROTOCOL_VERSION).unwrap();
9631 client_config
9632 .load_cert_chain_from_pem_file("examples/cert.crt")
9633 .unwrap();
9634 client_config
9635 .load_priv_key_from_pem_file("examples/cert.key")
9636 .unwrap();
9637 client_config
9638 .set_application_protos(&[b"proto1", b"proto2"])
9639 .unwrap();
9640 client_config.set_initial_max_data(30);
9641 client_config.set_initial_max_stream_data_bidi_local(15);
9642 client_config.set_initial_max_stream_data_bidi_remote(15);
9643 client_config.set_initial_max_streams_bidi(3);
9644
9645 client_config
9648 .load_verify_locations_from_file("examples/rootca.crt")
9649 .unwrap();
9650 client_config.verify_peer(true);
9651
9652 let mut pipe = testing::Pipe::with_client_and_server_config(
9653 &mut client_config,
9654 &mut server_config,
9655 )
9656 .unwrap();
9657 assert_eq!(pipe.handshake(), Err(Error::TlsFail));
9658
9659 assert!(pipe.server.peer_cert().is_some());
9661 }
9662
9663 #[test]
9664 fn verify_client_anonymous() {
9665 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
9666 config
9667 .load_cert_chain_from_pem_file("examples/cert.crt")
9668 .unwrap();
9669 config
9670 .load_priv_key_from_pem_file("examples/cert.key")
9671 .unwrap();
9672 config
9673 .set_application_protos(&[b"proto1", b"proto2"])
9674 .unwrap();
9675 config.set_initial_max_data(30);
9676 config.set_initial_max_stream_data_bidi_local(15);
9677 config.set_initial_max_stream_data_bidi_remote(15);
9678 config.set_initial_max_streams_bidi(3);
9679
9680 config.verify_peer(true);
9682
9683 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
9684 assert_eq!(pipe.handshake(), Ok(()));
9685
9686 assert!(pipe.server.peer_cert().is_none());
9688 }
9689
9690 #[test]
9691 fn missing_initial_source_connection_id() {
9692 let mut buf = [0; 65535];
9693
9694 let mut pipe = testing::Pipe::new().unwrap();
9695
9696 pipe.client
9698 .local_transport_params
9699 .initial_source_connection_id = None;
9700 assert_eq!(pipe.client.encode_transport_params(), Ok(()));
9701
9702 let (len, _) = pipe.client.send(&mut buf).unwrap();
9704
9705 assert_eq!(
9707 pipe.server_recv(&mut buf[..len]),
9708 Err(Error::InvalidTransportParam)
9709 );
9710 }
9711
9712 #[test]
9713 fn invalid_initial_source_connection_id() {
9714 let mut buf = [0; 65535];
9715
9716 let mut pipe = testing::Pipe::new().unwrap();
9717
9718 pipe.client
9720 .local_transport_params
9721 .initial_source_connection_id = Some(b"bogus value".to_vec().into());
9722 assert_eq!(pipe.client.encode_transport_params(), Ok(()));
9723
9724 let (len, _) = pipe.client.send(&mut buf).unwrap();
9726
9727 assert_eq!(
9729 pipe.server_recv(&mut buf[..len]),
9730 Err(Error::InvalidTransportParam)
9731 );
9732 }
9733
9734 #[test]
9735 fn change_idle_timeout() {
9736 let mut config = Config::new(0x1).unwrap();
9737 config
9738 .set_application_protos(&[b"proto1", b"proto2"])
9739 .unwrap();
9740 config.set_max_idle_timeout(999999);
9741 config.verify_peer(false);
9742
9743 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
9744 assert_eq!(pipe.client.local_transport_params.max_idle_timeout, 999999);
9745 assert_eq!(pipe.client.peer_transport_params.max_idle_timeout, 0);
9746 assert_eq!(pipe.server.local_transport_params.max_idle_timeout, 0);
9747 assert_eq!(pipe.server.peer_transport_params.max_idle_timeout, 0);
9748
9749 pipe.client.set_max_idle_timeout(456000).unwrap();
9750 pipe.server.set_max_idle_timeout(234000).unwrap();
9751 assert_eq!(pipe.client.local_transport_params.max_idle_timeout, 456000);
9752 assert_eq!(pipe.client.peer_transport_params.max_idle_timeout, 0);
9753 assert_eq!(pipe.server.local_transport_params.max_idle_timeout, 234000);
9754 assert_eq!(pipe.server.peer_transport_params.max_idle_timeout, 0);
9755
9756 assert_eq!(pipe.handshake(), Ok(()));
9757
9758 assert_eq!(
9759 pipe.client.idle_timeout(),
9760 Some(time::Duration::from_millis(234000))
9761 );
9762 assert_eq!(
9763 pipe.server.idle_timeout(),
9764 Some(time::Duration::from_millis(234000))
9765 );
9766 }
9767
9768 #[test]
9769 fn handshake() {
9770 let mut pipe = testing::Pipe::new().unwrap();
9771 assert_eq!(pipe.handshake(), Ok(()));
9772
9773 assert_eq!(
9774 pipe.client.application_proto(),
9775 pipe.server.application_proto()
9776 );
9777
9778 assert_eq!(pipe.server.server_name(), Some("quic.tech"));
9779 }
9780
9781 #[test]
9782 fn handshake_done() {
9783 let mut pipe = testing::Pipe::new().unwrap();
9784
9785 pipe.server.handshake.set_options(0x0000_4000);
9788
9789 assert_eq!(pipe.handshake(), Ok(()));
9790
9791 assert!(pipe.server.handshake_done_sent);
9792 }
9793
9794 #[test]
9795 fn handshake_confirmation() {
9796 let mut pipe = testing::Pipe::new().unwrap();
9797
9798 let flight = testing::emit_flight(&mut pipe.client).unwrap();
9800 testing::process_flight(&mut pipe.server, flight).unwrap();
9801
9802 let flight = testing::emit_flight(&mut pipe.server).unwrap();
9804
9805 assert!(!pipe.client.is_established());
9806 assert!(!pipe.client.handshake_confirmed);
9807
9808 assert!(!pipe.server.is_established());
9809 assert!(!pipe.server.handshake_confirmed);
9810
9811 testing::process_flight(&mut pipe.client, flight).unwrap();
9812
9813 let flight = testing::emit_flight(&mut pipe.client).unwrap();
9815
9816 assert!(pipe.client.is_established());
9817 assert!(!pipe.client.handshake_confirmed);
9818
9819 assert!(!pipe.server.is_established());
9820 assert!(!pipe.server.handshake_confirmed);
9821
9822 testing::process_flight(&mut pipe.server, flight).unwrap();
9823
9824 let flight = testing::emit_flight(&mut pipe.server).unwrap();
9826
9827 assert!(pipe.client.is_established());
9828 assert!(!pipe.client.handshake_confirmed);
9829
9830 assert!(pipe.server.is_established());
9831 assert!(pipe.server.handshake_confirmed);
9832
9833 testing::process_flight(&mut pipe.client, flight).unwrap();
9834
9835 let flight = testing::emit_flight(&mut pipe.client).unwrap();
9837
9838 assert!(pipe.client.is_established());
9839 assert!(pipe.client.handshake_confirmed);
9840
9841 assert!(pipe.server.is_established());
9842 assert!(pipe.server.handshake_confirmed);
9843
9844 testing::process_flight(&mut pipe.server, flight).unwrap();
9845
9846 assert!(pipe.client.is_established());
9847 assert!(pipe.client.handshake_confirmed);
9848
9849 assert!(pipe.server.is_established());
9850 assert!(pipe.server.handshake_confirmed);
9851 }
9852
9853 #[test]
9854 fn handshake_resumption() {
9855 #[cfg(not(feature = "openssl"))]
9856 const SESSION_TICKET_KEY: [u8; 48] = [0xa; 48];
9857
9858 #[cfg(feature = "openssl")]
9862 const SESSION_TICKET_KEY: [u8; 80] = [0xa; 80];
9863
9864 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
9865
9866 config
9867 .load_cert_chain_from_pem_file("examples/cert.crt")
9868 .unwrap();
9869 config
9870 .load_priv_key_from_pem_file("examples/cert.key")
9871 .unwrap();
9872 config
9873 .set_application_protos(&[b"proto1", b"proto2"])
9874 .unwrap();
9875 config.set_initial_max_data(30);
9876 config.set_initial_max_stream_data_bidi_local(15);
9877 config.set_initial_max_stream_data_bidi_remote(15);
9878 config.set_initial_max_streams_bidi(3);
9879 config.set_ticket_key(&SESSION_TICKET_KEY).unwrap();
9880
9881 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
9883 assert_eq!(pipe.handshake(), Ok(()));
9884
9885 assert!(pipe.client.is_established());
9886 assert!(pipe.server.is_established());
9887
9888 assert!(!pipe.client.is_resumed());
9889 assert!(!pipe.server.is_resumed());
9890
9891 let session = pipe.client.session().unwrap();
9893
9894 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
9896 config
9897 .load_cert_chain_from_pem_file("examples/cert.crt")
9898 .unwrap();
9899 config
9900 .load_priv_key_from_pem_file("examples/cert.key")
9901 .unwrap();
9902 config
9903 .set_application_protos(&[b"proto1", b"proto2"])
9904 .unwrap();
9905 config.set_initial_max_data(30);
9906 config.set_initial_max_stream_data_bidi_local(15);
9907 config.set_initial_max_stream_data_bidi_remote(15);
9908 config.set_initial_max_streams_bidi(3);
9909 config.set_ticket_key(&SESSION_TICKET_KEY).unwrap();
9910
9911 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
9912
9913 assert_eq!(pipe.client.set_session(session), Ok(()));
9914 assert_eq!(pipe.handshake(), Ok(()));
9915
9916 assert!(pipe.client.is_established());
9917 assert!(pipe.server.is_established());
9918
9919 assert!(pipe.client.is_resumed());
9920 assert!(pipe.server.is_resumed());
9921 }
9922
9923 #[test]
9924 fn handshake_alpn_mismatch() {
9925 let mut buf = [0; 65535];
9926
9927 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
9928 config
9929 .set_application_protos(&[b"proto3\x06proto4"])
9930 .unwrap();
9931 config.verify_peer(false);
9932
9933 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
9934 assert_eq!(pipe.handshake(), Err(Error::TlsFail));
9935
9936 assert_eq!(pipe.client.application_proto(), b"");
9937 assert_eq!(pipe.server.application_proto(), b"");
9938
9939 let (len, _) = pipe.server.send(&mut buf).unwrap();
9941 assert_eq!(len, 1200);
9942
9943 assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
9944 assert_eq!(pipe.server.sent_count, 1);
9945 }
9946
9947 #[cfg(not(feature = "openssl"))] #[test]
9949 fn handshake_0rtt() {
9950 let mut buf = [0; 65535];
9951
9952 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
9953 config
9954 .load_cert_chain_from_pem_file("examples/cert.crt")
9955 .unwrap();
9956 config
9957 .load_priv_key_from_pem_file("examples/cert.key")
9958 .unwrap();
9959 config
9960 .set_application_protos(&[b"proto1", b"proto2"])
9961 .unwrap();
9962 config.set_initial_max_data(30);
9963 config.set_initial_max_stream_data_bidi_local(15);
9964 config.set_initial_max_stream_data_bidi_remote(15);
9965 config.set_initial_max_streams_bidi(3);
9966 config.enable_early_data();
9967 config.verify_peer(false);
9968
9969 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
9971 assert_eq!(pipe.handshake(), Ok(()));
9972
9973 let session = pipe.client.session().unwrap();
9975
9976 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
9978 assert_eq!(pipe.client.set_session(session), Ok(()));
9979
9980 let (len, _) = pipe.client.send(&mut buf).unwrap();
9982 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
9983
9984 let pkt_type = packet::Type::ZeroRTT;
9986
9987 let frames = [frame::Frame::Stream {
9988 stream_id: 4,
9989 data: stream::RangeBuf::from(b"aaaaa", 0, true),
9990 }];
9991
9992 assert_eq!(
9993 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
9994 Ok(1200)
9995 );
9996
9997 assert_eq!(pipe.server.undecryptable_pkts.len(), 0);
9998
9999 let mut r = pipe.server.readable();
10001 assert_eq!(r.next(), Some(4));
10002 assert_eq!(r.next(), None);
10003
10004 let mut b = [0; 15];
10005 assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
10006 assert_eq!(&b[..5], b"aaaaa");
10007 }
10008
10009 #[cfg(not(feature = "openssl"))] #[test]
10011 fn handshake_0rtt_reordered() {
10012 let mut buf = [0; 65535];
10013
10014 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
10015 config
10016 .load_cert_chain_from_pem_file("examples/cert.crt")
10017 .unwrap();
10018 config
10019 .load_priv_key_from_pem_file("examples/cert.key")
10020 .unwrap();
10021 config
10022 .set_application_protos(&[b"proto1", b"proto2"])
10023 .unwrap();
10024 config.set_initial_max_data(30);
10025 config.set_initial_max_stream_data_bidi_local(15);
10026 config.set_initial_max_stream_data_bidi_remote(15);
10027 config.set_initial_max_streams_bidi(3);
10028 config.enable_early_data();
10029 config.verify_peer(false);
10030
10031 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10033 assert_eq!(pipe.handshake(), Ok(()));
10034
10035 let session = pipe.client.session().unwrap();
10037
10038 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10040 assert_eq!(pipe.client.set_session(session), Ok(()));
10041
10042 let (len, _) = pipe.client.send(&mut buf).unwrap();
10044 let mut initial = buf[..len].to_vec();
10045
10046 let pkt_type = packet::Type::ZeroRTT;
10048
10049 let frames = [frame::Frame::Stream {
10050 stream_id: 4,
10051 data: stream::RangeBuf::from(b"aaaaa", 0, true),
10052 }];
10053
10054 let len =
10055 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
10056 .unwrap();
10057 let mut zrtt = buf[..len].to_vec();
10058
10059 assert_eq!(pipe.server_recv(&mut zrtt), Ok(zrtt.len()));
10061
10062 assert_eq!(pipe.server.undecryptable_pkts.len(), 1);
10063 assert_eq!(pipe.server.undecryptable_pkts[0].0.len(), zrtt.len());
10064
10065 let mut r = pipe.server.readable();
10066 assert_eq!(r.next(), None);
10067
10068 assert_eq!(pipe.server_recv(&mut initial), Ok(initial.len()));
10070
10071 let mut r = pipe.server.readable();
10073 assert_eq!(r.next(), Some(4));
10074 assert_eq!(r.next(), None);
10075
10076 let mut b = [0; 15];
10077 assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
10078 assert_eq!(&b[..5], b"aaaaa");
10079 }
10080
10081 #[cfg(not(feature = "openssl"))] #[test]
10083 fn handshake_0rtt_truncated() {
10084 let mut buf = [0; 65535];
10085
10086 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
10087 config
10088 .load_cert_chain_from_pem_file("examples/cert.crt")
10089 .unwrap();
10090 config
10091 .load_priv_key_from_pem_file("examples/cert.key")
10092 .unwrap();
10093 config
10094 .set_application_protos(&[b"proto1", b"proto2"])
10095 .unwrap();
10096 config.set_initial_max_data(30);
10097 config.set_initial_max_stream_data_bidi_local(15);
10098 config.set_initial_max_stream_data_bidi_remote(15);
10099 config.set_initial_max_streams_bidi(3);
10100 config.enable_early_data();
10101 config.verify_peer(false);
10102
10103 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10105 assert_eq!(pipe.handshake(), Ok(()));
10106
10107 let session = pipe.client.session().unwrap();
10109
10110 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10112 assert_eq!(pipe.client.set_session(session), Ok(()));
10113
10114 pipe.client.send(&mut buf).unwrap();
10116
10117 let pkt_type = packet::Type::ZeroRTT;
10119
10120 let frames = [frame::Frame::Stream {
10121 stream_id: 4,
10122 data: stream::RangeBuf::from(b"aaaaa", 0, true),
10123 }];
10124
10125 let len =
10126 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
10127 .unwrap();
10128
10129 let mut zrtt = buf[..len - 1].to_vec();
10131
10132 assert_eq!(pipe.server_recv(&mut zrtt), Err(Error::InvalidPacket));
10134
10135 assert_eq!(pipe.server.undecryptable_pkts.len(), 0);
10136
10137 assert!(pipe.server.is_closed());
10138 }
10139
10140 #[test]
10141 fn crypto_limit() {
10142 let mut buf = [0; 65535];
10143
10144 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
10145 config
10146 .load_cert_chain_from_pem_file("examples/cert.crt")
10147 .unwrap();
10148 config
10149 .load_priv_key_from_pem_file("examples/cert.key")
10150 .unwrap();
10151 config
10152 .set_application_protos(&[b"proto1", b"proto2"])
10153 .unwrap();
10154 config.set_initial_max_data(30);
10155 config.set_initial_max_stream_data_bidi_local(15);
10156 config.set_initial_max_stream_data_bidi_remote(15);
10157 config.set_initial_max_streams_bidi(3);
10158 config.enable_early_data();
10159 config.verify_peer(false);
10160
10161 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10163 assert_eq!(pipe.handshake(), Ok(()));
10164
10165 let frames = [frame::Frame::Crypto {
10168 data: stream::RangeBuf::from(b"a", MAX_CRYPTO_STREAM_OFFSET, false),
10169 }];
10170
10171 let pkt_type = packet::Type::Short;
10172
10173 let written =
10174 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
10175 .unwrap();
10176
10177 let active_path = pipe.server.paths.get_active().unwrap();
10178 let info = RecvInfo {
10179 to: active_path.local_addr(),
10180 from: active_path.peer_addr(),
10181 };
10182
10183 assert_eq!(
10184 pipe.server.recv(&mut buf[..written], info),
10185 Err(Error::CryptoBufferExceeded)
10186 );
10187
10188 let written = match pipe.server.send(&mut buf) {
10189 Ok((write, _)) => write,
10190
10191 Err(_) => unreachable!(),
10192 };
10193
10194 let frames =
10195 testing::decode_pkt(&mut pipe.client, &mut buf[..written]).unwrap();
10196 let mut iter = frames.iter();
10197
10198 assert_eq!(
10199 iter.next(),
10200 Some(&frame::Frame::ConnectionClose {
10201 error_code: 0x0d,
10202 frame_type: 0,
10203 reason: Vec::new(),
10204 })
10205 );
10206 }
10207
10208 #[test]
10209 fn limit_handshake_data() {
10210 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
10211 config
10212 .load_cert_chain_from_pem_file("examples/cert-big.crt")
10213 .unwrap();
10214 config
10215 .load_priv_key_from_pem_file("examples/cert.key")
10216 .unwrap();
10217 config
10218 .set_application_protos(&[b"proto1", b"proto2"])
10219 .unwrap();
10220
10221 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
10222
10223 let flight = testing::emit_flight(&mut pipe.client).unwrap();
10224 let client_sent = flight.iter().fold(0, |out, p| out + p.0.len());
10225 testing::process_flight(&mut pipe.server, flight).unwrap();
10226
10227 let flight = testing::emit_flight(&mut pipe.server).unwrap();
10228 let server_sent = flight.iter().fold(0, |out, p| out + p.0.len());
10229
10230 assert_eq!(server_sent, client_sent * MAX_AMPLIFICATION_FACTOR);
10231 }
10232
10233 #[test]
10234 fn custom_limit_handshake_data() {
10235 const CUSTOM_AMPLIFICATION_FACTOR: usize = 2;
10236
10237 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
10238 config
10239 .load_cert_chain_from_pem_file("examples/cert-big.crt")
10240 .unwrap();
10241 config
10242 .load_priv_key_from_pem_file("examples/cert.key")
10243 .unwrap();
10244 config
10245 .set_application_protos(&[b"proto1", b"proto2"])
10246 .unwrap();
10247 config.set_max_amplification_factor(CUSTOM_AMPLIFICATION_FACTOR);
10248
10249 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
10250
10251 let flight = testing::emit_flight(&mut pipe.client).unwrap();
10252 let client_sent = flight.iter().fold(0, |out, p| out + p.0.len());
10253 testing::process_flight(&mut pipe.server, flight).unwrap();
10254
10255 let flight = testing::emit_flight(&mut pipe.server).unwrap();
10256 let server_sent = flight.iter().fold(0, |out, p| out + p.0.len());
10257
10258 assert_eq!(server_sent, client_sent * CUSTOM_AMPLIFICATION_FACTOR);
10259 }
10260
10261 #[test]
10262 fn stream() {
10263 let mut pipe = testing::Pipe::new().unwrap();
10264 assert_eq!(pipe.handshake(), Ok(()));
10265
10266 assert_eq!(pipe.client.stream_send(4, b"hello, world", true), Ok(12));
10267 assert_eq!(pipe.advance(), Ok(()));
10268
10269 assert!(!pipe.server.stream_finished(4));
10270
10271 let mut r = pipe.server.readable();
10272 assert_eq!(r.next(), Some(4));
10273 assert_eq!(r.next(), None);
10274
10275 let mut b = [0; 15];
10276 assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((12, true)));
10277 assert_eq!(&b[..12], b"hello, world");
10278
10279 assert!(pipe.server.stream_finished(4));
10280 }
10281
10282 #[cfg(not(feature = "openssl"))] #[test]
10284 fn zero_rtt() {
10285 let mut buf = [0; 65535];
10286
10287 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
10288 config
10289 .load_cert_chain_from_pem_file("examples/cert.crt")
10290 .unwrap();
10291 config
10292 .load_priv_key_from_pem_file("examples/cert.key")
10293 .unwrap();
10294 config
10295 .set_application_protos(&[b"proto1", b"proto2"])
10296 .unwrap();
10297 config.set_initial_max_data(30);
10298 config.set_initial_max_stream_data_bidi_local(15);
10299 config.set_initial_max_stream_data_bidi_remote(15);
10300 config.set_initial_max_streams_bidi(3);
10301 config.enable_early_data();
10302 config.verify_peer(false);
10303
10304 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10306 assert_eq!(pipe.handshake(), Ok(()));
10307
10308 let session = pipe.client.session().unwrap();
10310
10311 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10313 assert_eq!(pipe.client.set_session(session), Ok(()));
10314
10315 let (len, _) = pipe.client.send(&mut buf).unwrap();
10317 let mut initial = buf[..len].to_vec();
10318
10319 assert!(pipe.client.is_in_early_data());
10320
10321 assert_eq!(pipe.client.stream_send(4, b"hello, world", true), Ok(12));
10323
10324 let (len, _) = pipe.client.send(&mut buf).unwrap();
10325 let mut zrtt = buf[..len].to_vec();
10326
10327 assert_eq!(pipe.server_recv(&mut initial), Ok(initial.len()));
10329 assert!(pipe.server.is_in_early_data());
10330
10331 assert_eq!(pipe.server_recv(&mut zrtt), Ok(zrtt.len()));
10332
10333 let mut r = pipe.server.readable();
10335 assert_eq!(r.next(), Some(4));
10336 assert_eq!(r.next(), None);
10337
10338 let mut b = [0; 15];
10339 assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((12, true)));
10340 assert_eq!(&b[..12], b"hello, world");
10341 }
10342
10343 #[test]
10344 fn stream_send_on_32bit_arch() {
10345 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
10346 config
10347 .load_cert_chain_from_pem_file("examples/cert.crt")
10348 .unwrap();
10349 config
10350 .load_priv_key_from_pem_file("examples/cert.key")
10351 .unwrap();
10352 config
10353 .set_application_protos(&[b"proto1", b"proto2"])
10354 .unwrap();
10355 config.set_initial_max_data(2_u64.pow(32) + 5);
10356 config.set_initial_max_stream_data_bidi_local(15);
10357 config.set_initial_max_stream_data_bidi_remote(15);
10358 config.set_initial_max_stream_data_uni(10);
10359 config.set_initial_max_streams_bidi(3);
10360 config.set_initial_max_streams_uni(0);
10361 config.verify_peer(false);
10362
10363 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
10364 assert_eq!(pipe.handshake(), Ok(()));
10365
10366 assert_eq!(pipe.client.stream_send(4, b"hello, world", true), Ok(12));
10369
10370 assert_eq!(pipe.advance(), Ok(()));
10371
10372 assert!(!pipe.server.stream_finished(4));
10373 }
10374
10375 #[test]
10376 fn empty_stream_frame() {
10377 let mut buf = [0; 65535];
10378
10379 let mut pipe = testing::Pipe::new().unwrap();
10380 assert_eq!(pipe.handshake(), Ok(()));
10381
10382 let frames = [frame::Frame::Stream {
10383 stream_id: 4,
10384 data: stream::RangeBuf::from(b"aaaaa", 0, false),
10385 }];
10386
10387 let pkt_type = packet::Type::Short;
10388 assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
10389
10390 let mut readable = pipe.server.readable();
10391 assert_eq!(readable.next(), Some(4));
10392
10393 assert_eq!(pipe.server.stream_recv(4, &mut buf), Ok((5, false)));
10394
10395 let frames = [frame::Frame::Stream {
10396 stream_id: 4,
10397 data: stream::RangeBuf::from(b"", 5, true),
10398 }];
10399
10400 let pkt_type = packet::Type::Short;
10401 assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
10402
10403 let mut readable = pipe.server.readable();
10404 assert_eq!(readable.next(), Some(4));
10405
10406 assert_eq!(pipe.server.stream_recv(4, &mut buf), Ok((0, true)));
10407
10408 let frames = [frame::Frame::Stream {
10409 stream_id: 4,
10410 data: stream::RangeBuf::from(b"", 15, true),
10411 }];
10412
10413 let pkt_type = packet::Type::Short;
10414 assert_eq!(
10415 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10416 Err(Error::FinalSize)
10417 );
10418 }
10419
10420 #[test]
10421 fn update_key_request() {
10422 let mut b = [0; 15];
10423
10424 let mut pipe = testing::Pipe::new().unwrap();
10425 assert_eq!(pipe.handshake(), Ok(()));
10426 assert_eq!(pipe.advance(), Ok(()));
10427
10428 assert_eq!(pipe.client_update_key(), Ok(()));
10430 assert_eq!(pipe.client.stream_send(4, b"hello", false), Ok(5));
10431 assert_eq!(pipe.advance(), Ok(()));
10432
10433 let mut r = pipe.server.readable();
10435 assert_eq!(r.next(), Some(4));
10436 assert_eq!(r.next(), None);
10437 assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, false)));
10438 assert_eq!(&b[..5], b"hello");
10439
10440 assert!(
10442 pipe.server.pkt_num_spaces[packet::Epoch::Application]
10443 .key_update
10444 .as_ref()
10445 .unwrap()
10446 .update_acked
10447 );
10448
10449 assert_eq!(pipe.server.stream_send(4, b"world", false), Ok(5));
10451 assert_eq!(pipe.advance(), Ok(()));
10452
10453 let mut r = pipe.client.readable();
10455 assert_eq!(r.next(), Some(4));
10456 assert_eq!(r.next(), None);
10457 assert_eq!(pipe.client.stream_recv(4, &mut b), Ok((5, false)));
10458 assert_eq!(&b[..5], b"world");
10459
10460 for _ in 0..10 {
10462 assert_eq!(pipe.server.stream_send(4, b"world", false), Ok(5));
10463 assert_eq!(pipe.advance(), Ok(()));
10464
10465 let mut r = pipe.client.readable();
10466 assert_eq!(r.next(), Some(4));
10467 assert_eq!(r.next(), None);
10468 assert_eq!(pipe.client.stream_recv(4, &mut b), Ok((5, false)));
10469 assert_eq!(&b[..5], b"world");
10470 }
10471 }
10472
10473 #[test]
10474 fn update_key_request_twice_error() {
10475 let mut buf = [0; 65535];
10476
10477 let mut pipe = testing::Pipe::new().unwrap();
10478 assert_eq!(pipe.handshake(), Ok(()));
10479 assert_eq!(pipe.advance(), Ok(()));
10480
10481 let frames = [frame::Frame::Stream {
10482 stream_id: 4,
10483 data: stream::RangeBuf::from(b"hello", 0, false),
10484 }];
10485
10486 assert_eq!(pipe.client_update_key(), Ok(()));
10488 let written = testing::encode_pkt(
10489 &mut pipe.client,
10490 packet::Type::Short,
10491 &frames,
10492 &mut buf,
10493 )
10494 .unwrap();
10495
10496 assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
10498
10499 assert_eq!(pipe.client_update_key(), Ok(()));
10502 let written = testing::encode_pkt(
10503 &mut pipe.client,
10504 packet::Type::Short,
10505 &frames,
10506 &mut buf,
10507 )
10508 .unwrap();
10509
10510 assert_eq!(pipe.server_recv(&mut buf[..written]), Err(Error::KeyUpdate));
10513 }
10514
10515 #[test]
10516 fn max_stream_data_receive_uni() {
10519 let mut buf = [0; 65535];
10520
10521 let mut pipe = testing::Pipe::new().unwrap();
10522 assert_eq!(pipe.handshake(), Ok(()));
10523
10524 assert_eq!(pipe.client.stream_send(2, b"hello", false), Ok(5));
10526 assert_eq!(pipe.advance(), Ok(()));
10527
10528 let frames = [frame::Frame::MaxStreamData {
10530 stream_id: 2,
10531 max: 1024,
10532 }];
10533
10534 let pkt_type = packet::Type::Short;
10535 assert_eq!(
10536 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10537 Err(Error::InvalidStreamState(2)),
10538 );
10539 }
10540
10541 #[test]
10542 fn empty_payload() {
10543 let mut buf = [0; 65535];
10544
10545 let mut pipe = testing::Pipe::new().unwrap();
10546 assert_eq!(pipe.handshake(), Ok(()));
10547
10548 let pkt_type = packet::Type::Short;
10550 assert_eq!(
10551 pipe.send_pkt_to_server(pkt_type, &[], &mut buf),
10552 Err(Error::InvalidPacket)
10553 );
10554 }
10555
10556 #[test]
10557 fn min_payload() {
10558 let mut buf = [0; 65535];
10559
10560 let mut pipe = testing::Pipe::new().unwrap();
10561
10562 let frames = [frame::Frame::Padding { len: 4 }];
10564
10565 let pkt_type = packet::Type::Initial;
10566 let written =
10567 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
10568 .unwrap();
10569 assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
10570
10571 let initial_path = pipe
10572 .server
10573 .paths
10574 .get_active()
10575 .expect("initial path not found");
10576
10577 assert_eq!(initial_path.max_send_bytes, 195);
10578
10579 pipe.server
10581 .paths
10582 .get_active_mut()
10583 .expect("no active path")
10584 .recovery
10585 .inc_loss_probes(packet::Epoch::Initial);
10586
10587 let initial_path = pipe
10588 .server
10589 .paths
10590 .get_active_mut()
10591 .expect("initial path not found");
10592
10593 initial_path.max_send_bytes = 60;
10595
10596 assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
10597 }
10598
10599 #[test]
10600 fn flow_control_limit() {
10601 let mut buf = [0; 65535];
10602
10603 let mut pipe = testing::Pipe::new().unwrap();
10604 assert_eq!(pipe.handshake(), Ok(()));
10605
10606 let frames = [
10607 frame::Frame::Stream {
10608 stream_id: 0,
10609 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
10610 },
10611 frame::Frame::Stream {
10612 stream_id: 4,
10613 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
10614 },
10615 frame::Frame::Stream {
10616 stream_id: 8,
10617 data: stream::RangeBuf::from(b"a", 0, false),
10618 },
10619 ];
10620
10621 let pkt_type = packet::Type::Short;
10622 assert_eq!(
10623 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10624 Err(Error::FlowControl),
10625 );
10626 }
10627
10628 #[test]
10629 fn flow_control_limit_dup() {
10630 let mut buf = [0; 65535];
10631
10632 let mut pipe = testing::Pipe::new().unwrap();
10633 assert_eq!(pipe.handshake(), Ok(()));
10634
10635 let frames = [
10636 frame::Frame::Stream {
10638 stream_id: 0,
10639 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaa", 0, false),
10640 },
10641 frame::Frame::Stream {
10643 stream_id: 0,
10644 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
10645 },
10646 frame::Frame::Stream {
10647 stream_id: 8,
10648 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
10649 },
10650 ];
10651
10652 let pkt_type = packet::Type::Short;
10653 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
10654 }
10655
10656 #[test]
10657 fn flow_control_update() {
10658 let mut buf = [0; 65535];
10659
10660 let mut pipe = testing::Pipe::new().unwrap();
10661 assert_eq!(pipe.handshake(), Ok(()));
10662
10663 let frames = [
10664 frame::Frame::Stream {
10665 stream_id: 0,
10666 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
10667 },
10668 frame::Frame::Stream {
10669 stream_id: 4,
10670 data: stream::RangeBuf::from(b"a", 0, false),
10671 },
10672 ];
10673
10674 let pkt_type = packet::Type::Short;
10675
10676 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
10677
10678 pipe.server.stream_recv(0, &mut buf).unwrap();
10679 pipe.server.stream_recv(4, &mut buf).unwrap();
10680
10681 let frames = [frame::Frame::Stream {
10682 stream_id: 4,
10683 data: stream::RangeBuf::from(b"a", 1, false),
10684 }];
10685
10686 let len = pipe
10687 .send_pkt_to_server(pkt_type, &frames, &mut buf)
10688 .unwrap();
10689
10690 assert!(len > 0);
10691
10692 let frames =
10693 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
10694 let mut iter = frames.iter();
10695
10696 iter.next().unwrap();
10698
10699 assert_eq!(
10700 iter.next(),
10701 Some(&frame::Frame::MaxStreamData {
10702 stream_id: 0,
10703 max: 30
10704 })
10705 );
10706 assert_eq!(iter.next(), Some(&frame::Frame::MaxData { max: 61 }));
10707 }
10708
10709 #[test]
10710 fn flow_control_drain() {
10713 let mut pipe = testing::Pipe::new().unwrap();
10714 assert_eq!(pipe.handshake(), Ok(()));
10715
10716 assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
10718 assert_eq!(pipe.advance(), Ok(()));
10719
10720 let mut r = pipe.server.readable();
10722 assert_eq!(r.next(), Some(4));
10723 assert_eq!(r.next(), None);
10724
10725 assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
10727 assert_eq!(pipe.client.stream_send(4, b"aaaaa", true), Ok(5));
10728
10729 assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
10730 assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
10731 assert_eq!(pipe.client.stream_send(8, b"aaaaa", true), Ok(5));
10732
10733 assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Read, 42), Ok(()));
10735
10736 let mut r = pipe.server.readable();
10737 assert_eq!(r.next(), None);
10738
10739 assert_eq!(pipe.advance(), Ok(()));
10741 }
10742
10743 #[test]
10744 fn stream_flow_control_limit_bidi() {
10745 let mut buf = [0; 65535];
10746
10747 let mut pipe = testing::Pipe::new().unwrap();
10748 assert_eq!(pipe.handshake(), Ok(()));
10749
10750 let frames = [frame::Frame::Stream {
10751 stream_id: 4,
10752 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaaa", 0, true),
10753 }];
10754
10755 let pkt_type = packet::Type::Short;
10756 assert_eq!(
10757 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10758 Err(Error::FlowControl),
10759 );
10760 }
10761
10762 #[test]
10763 fn stream_flow_control_limit_uni() {
10764 let mut buf = [0; 65535];
10765
10766 let mut pipe = testing::Pipe::new().unwrap();
10767 assert_eq!(pipe.handshake(), Ok(()));
10768
10769 let frames = [frame::Frame::Stream {
10770 stream_id: 2,
10771 data: stream::RangeBuf::from(b"aaaaaaaaaaa", 0, true),
10772 }];
10773
10774 let pkt_type = packet::Type::Short;
10775 assert_eq!(
10776 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10777 Err(Error::FlowControl),
10778 );
10779 }
10780
10781 #[test]
10782 fn stream_flow_control_update() {
10783 let mut buf = [0; 65535];
10784
10785 let mut pipe = testing::Pipe::new().unwrap();
10786 assert_eq!(pipe.handshake(), Ok(()));
10787
10788 let frames = [frame::Frame::Stream {
10789 stream_id: 4,
10790 data: stream::RangeBuf::from(b"aaaaaaaaa", 0, false),
10791 }];
10792
10793 let pkt_type = packet::Type::Short;
10794
10795 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
10796
10797 pipe.server.stream_recv(4, &mut buf).unwrap();
10798
10799 let frames = [frame::Frame::Stream {
10800 stream_id: 4,
10801 data: stream::RangeBuf::from(b"a", 9, false),
10802 }];
10803
10804 let len = pipe
10805 .send_pkt_to_server(pkt_type, &frames, &mut buf)
10806 .unwrap();
10807
10808 assert!(len > 0);
10809
10810 let frames =
10811 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
10812 let mut iter = frames.iter();
10813
10814 iter.next().unwrap();
10816
10817 assert_eq!(
10818 iter.next(),
10819 Some(&frame::Frame::MaxStreamData {
10820 stream_id: 4,
10821 max: 24,
10822 })
10823 );
10824 }
10825
10826 #[test]
10827 fn stream_left_bidi() {
10828 let mut buf = [0; 65535];
10829
10830 let mut pipe = testing::Pipe::new().unwrap();
10831 assert_eq!(pipe.handshake(), Ok(()));
10832
10833 assert_eq!(3, pipe.client.peer_streams_left_bidi());
10834 assert_eq!(3, pipe.server.peer_streams_left_bidi());
10835
10836 pipe.server.stream_send(1, b"a", false).ok();
10837 assert_eq!(2, pipe.server.peer_streams_left_bidi());
10838 pipe.server.stream_send(5, b"a", false).ok();
10839 assert_eq!(1, pipe.server.peer_streams_left_bidi());
10840
10841 pipe.server.stream_send(9, b"a", false).ok();
10842 assert_eq!(0, pipe.server.peer_streams_left_bidi());
10843
10844 let frames = [frame::Frame::MaxStreamsBidi { max: MAX_STREAM_ID }];
10845
10846 let pkt_type = packet::Type::Short;
10847 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
10848
10849 assert_eq!(MAX_STREAM_ID - 3, pipe.server.peer_streams_left_bidi());
10850 }
10851
10852 #[test]
10853 fn stream_left_uni() {
10854 let mut buf = [0; 65535];
10855
10856 let mut pipe = testing::Pipe::new().unwrap();
10857 assert_eq!(pipe.handshake(), Ok(()));
10858
10859 assert_eq!(3, pipe.client.peer_streams_left_uni());
10860 assert_eq!(3, pipe.server.peer_streams_left_uni());
10861
10862 pipe.server.stream_send(3, b"a", false).ok();
10863 assert_eq!(2, pipe.server.peer_streams_left_uni());
10864 pipe.server.stream_send(7, b"a", false).ok();
10865 assert_eq!(1, pipe.server.peer_streams_left_uni());
10866
10867 pipe.server.stream_send(11, b"a", false).ok();
10868 assert_eq!(0, pipe.server.peer_streams_left_uni());
10869
10870 let frames = [frame::Frame::MaxStreamsUni { max: MAX_STREAM_ID }];
10871
10872 let pkt_type = packet::Type::Short;
10873 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
10874
10875 assert_eq!(MAX_STREAM_ID - 3, pipe.server.peer_streams_left_uni());
10876 }
10877
10878 #[test]
10879 fn stream_limit_bidi() {
10880 let mut buf = [0; 65535];
10881
10882 let mut pipe = testing::Pipe::new().unwrap();
10883 assert_eq!(pipe.handshake(), Ok(()));
10884
10885 let frames = [
10886 frame::Frame::Stream {
10887 stream_id: 4,
10888 data: stream::RangeBuf::from(b"a", 0, false),
10889 },
10890 frame::Frame::Stream {
10891 stream_id: 8,
10892 data: stream::RangeBuf::from(b"a", 0, false),
10893 },
10894 frame::Frame::Stream {
10895 stream_id: 12,
10896 data: stream::RangeBuf::from(b"a", 0, false),
10897 },
10898 frame::Frame::Stream {
10899 stream_id: 16,
10900 data: stream::RangeBuf::from(b"a", 0, false),
10901 },
10902 frame::Frame::Stream {
10903 stream_id: 20,
10904 data: stream::RangeBuf::from(b"a", 0, false),
10905 },
10906 frame::Frame::Stream {
10907 stream_id: 24,
10908 data: stream::RangeBuf::from(b"a", 0, false),
10909 },
10910 frame::Frame::Stream {
10911 stream_id: 28,
10912 data: stream::RangeBuf::from(b"a", 0, false),
10913 },
10914 ];
10915
10916 let pkt_type = packet::Type::Short;
10917 assert_eq!(
10918 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10919 Err(Error::StreamLimit),
10920 );
10921 }
10922
10923 #[test]
10924 fn stream_limit_max_bidi() {
10925 let mut buf = [0; 65535];
10926
10927 let mut pipe = testing::Pipe::new().unwrap();
10928 assert_eq!(pipe.handshake(), Ok(()));
10929
10930 let frames = [frame::Frame::MaxStreamsBidi { max: MAX_STREAM_ID }];
10931
10932 let pkt_type = packet::Type::Short;
10933 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
10934
10935 let frames = [frame::Frame::MaxStreamsBidi {
10936 max: MAX_STREAM_ID + 1,
10937 }];
10938
10939 let pkt_type = packet::Type::Short;
10940 assert_eq!(
10941 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10942 Err(Error::InvalidFrame),
10943 );
10944 }
10945
10946 #[test]
10947 fn stream_limit_uni() {
10948 let mut buf = [0; 65535];
10949
10950 let mut pipe = testing::Pipe::new().unwrap();
10951 assert_eq!(pipe.handshake(), Ok(()));
10952
10953 let frames = [
10954 frame::Frame::Stream {
10955 stream_id: 2,
10956 data: stream::RangeBuf::from(b"a", 0, false),
10957 },
10958 frame::Frame::Stream {
10959 stream_id: 6,
10960 data: stream::RangeBuf::from(b"a", 0, false),
10961 },
10962 frame::Frame::Stream {
10963 stream_id: 10,
10964 data: stream::RangeBuf::from(b"a", 0, false),
10965 },
10966 frame::Frame::Stream {
10967 stream_id: 14,
10968 data: stream::RangeBuf::from(b"a", 0, false),
10969 },
10970 frame::Frame::Stream {
10971 stream_id: 18,
10972 data: stream::RangeBuf::from(b"a", 0, false),
10973 },
10974 frame::Frame::Stream {
10975 stream_id: 22,
10976 data: stream::RangeBuf::from(b"a", 0, false),
10977 },
10978 frame::Frame::Stream {
10979 stream_id: 26,
10980 data: stream::RangeBuf::from(b"a", 0, false),
10981 },
10982 ];
10983
10984 let pkt_type = packet::Type::Short;
10985 assert_eq!(
10986 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
10987 Err(Error::StreamLimit),
10988 );
10989 }
10990
10991 #[test]
10992 fn stream_limit_max_uni() {
10993 let mut buf = [0; 65535];
10994
10995 let mut pipe = testing::Pipe::new().unwrap();
10996 assert_eq!(pipe.handshake(), Ok(()));
10997
10998 let frames = [frame::Frame::MaxStreamsUni { max: MAX_STREAM_ID }];
10999
11000 let pkt_type = packet::Type::Short;
11001 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
11002
11003 let frames = [frame::Frame::MaxStreamsUni {
11004 max: MAX_STREAM_ID + 1,
11005 }];
11006
11007 let pkt_type = packet::Type::Short;
11008 assert_eq!(
11009 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
11010 Err(Error::InvalidFrame),
11011 );
11012 }
11013
11014 #[test]
11015 fn stream_left_reset_bidi() {
11016 let mut buf = [0; 65535];
11017
11018 let mut pipe = testing::Pipe::new().unwrap();
11019 assert_eq!(pipe.handshake(), Ok(()));
11020
11021 assert_eq!(3, pipe.client.peer_streams_left_bidi());
11022 assert_eq!(3, pipe.server.peer_streams_left_bidi());
11023
11024 pipe.client.stream_send(0, b"a", false).ok();
11025 assert_eq!(2, pipe.client.peer_streams_left_bidi());
11026 pipe.client.stream_send(4, b"a", false).ok();
11027 assert_eq!(1, pipe.client.peer_streams_left_bidi());
11028 pipe.client.stream_send(8, b"a", false).ok();
11029 assert_eq!(0, pipe.client.peer_streams_left_bidi());
11030
11031 pipe.client
11033 .stream_shutdown(0, Shutdown::Write, 1001)
11034 .unwrap();
11035 pipe.advance().unwrap();
11036
11037 assert_eq!(0, pipe.client.peer_streams_left_bidi());
11038 let mut r = pipe.server.readable();
11039 assert_eq!(Some(0), r.next());
11040 assert_eq!(Some(4), r.next());
11041 assert_eq!(Some(8), r.next());
11042 assert_eq!(None, r.next());
11043
11044 assert_eq!(
11045 pipe.server.stream_recv(0, &mut buf),
11046 Err(Error::StreamReset(1001))
11047 );
11048
11049 let mut r = pipe.server.readable();
11050 assert_eq!(Some(4), r.next());
11051 assert_eq!(Some(8), r.next());
11052 assert_eq!(None, r.next());
11053
11054 pipe.server
11056 .stream_shutdown(0, Shutdown::Write, 1001)
11057 .unwrap();
11058 pipe.advance().unwrap();
11059
11060 assert_eq!(1, pipe.client.peer_streams_left_bidi());
11061
11062 pipe.client
11064 .stream_shutdown(4, Shutdown::Write, 1001)
11065 .unwrap();
11066 pipe.client
11067 .stream_shutdown(8, Shutdown::Write, 1001)
11068 .unwrap();
11069 pipe.advance().unwrap();
11070
11071 let mut r = pipe.server.readable();
11072 assert_eq!(Some(4), r.next());
11073 assert_eq!(Some(8), r.next());
11074 assert_eq!(None, r.next());
11075
11076 assert_eq!(
11077 pipe.server.stream_recv(4, &mut buf),
11078 Err(Error::StreamReset(1001))
11079 );
11080
11081 assert_eq!(
11082 pipe.server.stream_recv(8, &mut buf),
11083 Err(Error::StreamReset(1001))
11084 );
11085
11086 let mut r = pipe.server.readable();
11087 assert_eq!(None, r.next());
11088
11089 pipe.server
11090 .stream_shutdown(4, Shutdown::Write, 1001)
11091 .unwrap();
11092 pipe.server
11093 .stream_shutdown(8, Shutdown::Write, 1001)
11094 .unwrap();
11095 pipe.advance().unwrap();
11096
11097 assert_eq!(3, pipe.client.peer_streams_left_bidi());
11098 }
11099
11100 #[test]
11101 fn stream_reset_counts() {
11102 let mut pipe = testing::Pipe::new().unwrap();
11103 assert_eq!(pipe.handshake(), Ok(()));
11104
11105 pipe.client.stream_send(0, b"a", false).ok();
11106 pipe.client.stream_send(2, b"a", false).ok();
11107 pipe.client.stream_send(4, b"a", false).ok();
11108 pipe.client.stream_send(8, b"a", false).ok();
11109 pipe.advance().unwrap();
11110
11111 let stats = pipe.client.stats();
11112 assert_eq!(stats.reset_stream_count_local, 0);
11113
11114 pipe.client
11116 .stream_shutdown(0, Shutdown::Write, 1001)
11117 .unwrap();
11118 pipe.advance().unwrap();
11119
11120 let stats = pipe.client.stats();
11121 assert_eq!(stats.reset_stream_count_local, 1);
11122 assert_eq!(stats.reset_stream_count_remote, 0);
11123 let stats = pipe.server.stats();
11124 assert_eq!(stats.reset_stream_count_local, 0);
11125 assert_eq!(stats.reset_stream_count_remote, 1);
11126
11127 pipe.server
11129 .stream_shutdown(0, Shutdown::Write, 1001)
11130 .unwrap();
11131 pipe.advance().unwrap();
11132
11133 let stats = pipe.client.stats();
11134 assert_eq!(stats.reset_stream_count_local, 1);
11135 assert_eq!(stats.reset_stream_count_remote, 1);
11136 let stats = pipe.server.stats();
11137 assert_eq!(stats.reset_stream_count_local, 1);
11138 assert_eq!(stats.reset_stream_count_remote, 1);
11139
11140 pipe.client
11142 .stream_shutdown(2, Shutdown::Write, 1001)
11143 .unwrap();
11144 pipe.client
11145 .stream_shutdown(4, Shutdown::Write, 1001)
11146 .unwrap();
11147 pipe.client
11148 .stream_shutdown(8, Shutdown::Write, 1001)
11149 .unwrap();
11150 pipe.advance().unwrap();
11151
11152 pipe.server
11153 .stream_shutdown(4, Shutdown::Write, 1001)
11154 .unwrap();
11155 pipe.server
11156 .stream_shutdown(8, Shutdown::Write, 1001)
11157 .unwrap();
11158 pipe.advance().unwrap();
11159
11160 let stats = pipe.client.stats();
11161 assert_eq!(stats.reset_stream_count_local, 4);
11162 assert_eq!(stats.reset_stream_count_remote, 3);
11163 let stats = pipe.server.stats();
11164 assert_eq!(stats.reset_stream_count_local, 3);
11165 assert_eq!(stats.reset_stream_count_remote, 4);
11166 }
11167
11168 #[test]
11169 fn stream_stop_counts() {
11170 let mut pipe = testing::Pipe::new().unwrap();
11171 assert_eq!(pipe.handshake(), Ok(()));
11172
11173 pipe.client.stream_send(0, b"a", false).ok();
11174 pipe.client.stream_send(2, b"a", false).ok();
11175 pipe.client.stream_send(4, b"a", false).ok();
11176 pipe.client.stream_send(8, b"a", false).ok();
11177 pipe.advance().unwrap();
11178
11179 let stats = pipe.client.stats();
11180 assert_eq!(stats.reset_stream_count_local, 0);
11181
11182 pipe.server
11184 .stream_shutdown(0, Shutdown::Read, 1001)
11185 .unwrap();
11186 pipe.advance().unwrap();
11187
11188 let stats = pipe.client.stats();
11189 assert_eq!(stats.stopped_stream_count_local, 0);
11190 assert_eq!(stats.stopped_stream_count_remote, 1);
11191 assert_eq!(stats.reset_stream_count_local, 1);
11192 assert_eq!(stats.reset_stream_count_remote, 0);
11193
11194 let stats = pipe.server.stats();
11195 assert_eq!(stats.stopped_stream_count_local, 1);
11196 assert_eq!(stats.stopped_stream_count_remote, 0);
11197 assert_eq!(stats.reset_stream_count_local, 0);
11198 assert_eq!(stats.reset_stream_count_remote, 1);
11199
11200 pipe.server
11202 .stream_shutdown(2, Shutdown::Read, 1001)
11203 .unwrap();
11204 pipe.server
11205 .stream_shutdown(4, Shutdown::Read, 1001)
11206 .unwrap();
11207 pipe.server
11208 .stream_shutdown(8, Shutdown::Read, 1001)
11209 .unwrap();
11210 pipe.advance().unwrap();
11211
11212 let stats = pipe.client.stats();
11213 assert_eq!(stats.stopped_stream_count_local, 0);
11214 assert_eq!(stats.stopped_stream_count_remote, 4);
11215 assert_eq!(stats.reset_stream_count_local, 4);
11216 assert_eq!(stats.reset_stream_count_remote, 0);
11217
11218 let stats = pipe.server.stats();
11219 assert_eq!(stats.stopped_stream_count_local, 4);
11220 assert_eq!(stats.stopped_stream_count_remote, 0);
11221 assert_eq!(stats.reset_stream_count_local, 0);
11222 assert_eq!(stats.reset_stream_count_remote, 4);
11223 }
11224
11225 #[test]
11226 fn streams_blocked_max_bidi() {
11227 let mut buf = [0; 65535];
11228
11229 let mut pipe = testing::Pipe::new().unwrap();
11230 assert_eq!(pipe.handshake(), Ok(()));
11231
11232 let frames = [frame::Frame::StreamsBlockedBidi {
11233 limit: MAX_STREAM_ID,
11234 }];
11235
11236 let pkt_type = packet::Type::Short;
11237 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
11238
11239 let frames = [frame::Frame::StreamsBlockedBidi {
11240 limit: MAX_STREAM_ID + 1,
11241 }];
11242
11243 let pkt_type = packet::Type::Short;
11244 assert_eq!(
11245 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
11246 Err(Error::InvalidFrame),
11247 );
11248 }
11249
11250 #[test]
11251 fn streams_blocked_max_uni() {
11252 let mut buf = [0; 65535];
11253
11254 let mut pipe = testing::Pipe::new().unwrap();
11255 assert_eq!(pipe.handshake(), Ok(()));
11256
11257 let frames = [frame::Frame::StreamsBlockedUni {
11258 limit: MAX_STREAM_ID,
11259 }];
11260
11261 let pkt_type = packet::Type::Short;
11262 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
11263
11264 let frames = [frame::Frame::StreamsBlockedUni {
11265 limit: MAX_STREAM_ID + 1,
11266 }];
11267
11268 let pkt_type = packet::Type::Short;
11269 assert_eq!(
11270 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
11271 Err(Error::InvalidFrame),
11272 );
11273 }
11274
11275 #[test]
11276 fn stream_data_overlap() {
11277 let mut buf = [0; 65535];
11278
11279 let mut pipe = testing::Pipe::new().unwrap();
11280 assert_eq!(pipe.handshake(), Ok(()));
11281
11282 let frames = [
11283 frame::Frame::Stream {
11284 stream_id: 0,
11285 data: stream::RangeBuf::from(b"aaaaa", 0, false),
11286 },
11287 frame::Frame::Stream {
11288 stream_id: 0,
11289 data: stream::RangeBuf::from(b"bbbbb", 3, false),
11290 },
11291 frame::Frame::Stream {
11292 stream_id: 0,
11293 data: stream::RangeBuf::from(b"ccccc", 6, false),
11294 },
11295 ];
11296
11297 let pkt_type = packet::Type::Short;
11298 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
11299
11300 let mut b = [0; 15];
11301 assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((11, false)));
11302 assert_eq!(&b[..11], b"aaaaabbbccc");
11303 }
11304
11305 #[test]
11306 fn stream_data_overlap_with_reordering() {
11307 let mut buf = [0; 65535];
11308
11309 let mut pipe = testing::Pipe::new().unwrap();
11310 assert_eq!(pipe.handshake(), Ok(()));
11311
11312 let frames = [
11313 frame::Frame::Stream {
11314 stream_id: 0,
11315 data: stream::RangeBuf::from(b"aaaaa", 0, false),
11316 },
11317 frame::Frame::Stream {
11318 stream_id: 0,
11319 data: stream::RangeBuf::from(b"ccccc", 6, false),
11320 },
11321 frame::Frame::Stream {
11322 stream_id: 0,
11323 data: stream::RangeBuf::from(b"bbbbb", 3, false),
11324 },
11325 ];
11326
11327 let pkt_type = packet::Type::Short;
11328 assert!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf).is_ok());
11329
11330 let mut b = [0; 15];
11331 assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((11, false)));
11332 assert_eq!(&b[..11], b"aaaaabccccc");
11333 }
11334
11335 #[test]
11336 fn reset_stream_data_recvd() {
11339 let mut b = [0; 15];
11340 let mut buf = [0; 65535];
11341
11342 let mut pipe = testing::Pipe::new().unwrap();
11343 assert_eq!(pipe.handshake(), Ok(()));
11344
11345 assert_eq!(pipe.client.stream_send(0, b"hello", false), Ok(5));
11347 assert_eq!(pipe.advance(), Ok(()));
11348
11349 let mut r = pipe.server.readable();
11351 assert_eq!(r.next(), Some(0));
11352 assert_eq!(r.next(), None);
11353
11354 assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((5, false)));
11355 assert!(!pipe.server.stream_finished(0));
11356
11357 let mut r = pipe.server.readable();
11358 assert_eq!(r.next(), None);
11359
11360 assert_eq!(pipe.server.stream_send(0, b"", true), Ok(0));
11361 assert_eq!(pipe.advance(), Ok(()));
11362
11363 let mut r = pipe.client.readable();
11364 assert_eq!(r.next(), Some(0));
11365 assert_eq!(r.next(), None);
11366
11367 assert_eq!(pipe.client.stream_recv(0, &mut b), Ok((0, true)));
11368 assert!(pipe.client.stream_finished(0));
11369
11370 let frames = [frame::Frame::ResetStream {
11372 stream_id: 0,
11373 error_code: 42,
11374 final_size: 5,
11375 }];
11376
11377 let pkt_type = packet::Type::Short;
11378 assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
11379
11380 let mut r = pipe.server.readable();
11382 assert_eq!(r.next(), Some(0));
11383 assert_eq!(r.next(), None);
11384
11385 assert_eq!(
11386 pipe.server.stream_recv(0, &mut b),
11387 Err(Error::StreamReset(42))
11388 );
11389
11390 assert!(pipe.server.stream_finished(0));
11391
11392 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf)
11394 .unwrap();
11395
11396 let mut r = pipe.server.readable();
11397 assert_eq!(r.next(), None);
11398 }
11399
11400 #[test]
11401 fn reset_stream_data_not_recvd() {
11404 let mut b = [0; 15];
11405 let mut buf = [0; 65535];
11406
11407 let mut pipe = testing::Pipe::new().unwrap();
11408 assert_eq!(pipe.handshake(), Ok(()));
11409
11410 assert_eq!(pipe.client.stream_send(0, b"h", false), Ok(1));
11412 assert_eq!(pipe.advance(), Ok(()));
11413
11414 let mut r = pipe.server.readable();
11416 assert_eq!(r.next(), Some(0));
11417 assert_eq!(r.next(), None);
11418
11419 assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((1, false)));
11420 assert!(!pipe.server.stream_finished(0));
11421
11422 let mut r = pipe.server.readable();
11423 assert_eq!(r.next(), None);
11424
11425 assert_eq!(pipe.server.stream_send(0, b"", true), Ok(0));
11426 assert_eq!(pipe.advance(), Ok(()));
11427
11428 let mut r = pipe.client.readable();
11429 assert_eq!(r.next(), Some(0));
11430 assert_eq!(r.next(), None);
11431
11432 assert_eq!(pipe.client.stream_recv(0, &mut b), Ok((0, true)));
11433 assert!(pipe.client.stream_finished(0));
11434
11435 let frames = [frame::Frame::ResetStream {
11437 stream_id: 0,
11438 error_code: 42,
11439 final_size: 5,
11440 }];
11441
11442 let pkt_type = packet::Type::Short;
11443 assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
11444
11445 let mut r = pipe.server.readable();
11447 assert_eq!(r.next(), Some(0));
11448 assert_eq!(r.next(), None);
11449
11450 assert_eq!(
11451 pipe.server.stream_recv(0, &mut b),
11452 Err(Error::StreamReset(42))
11453 );
11454
11455 assert!(pipe.server.stream_finished(0));
11456
11457 assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
11459
11460 let mut r = pipe.server.readable();
11461 assert_eq!(r.next(), None);
11462 }
11463
11464 #[test]
11465 fn reset_stream_flow_control() {
11468 let mut buf = [0; 65535];
11469
11470 let mut pipe = testing::Pipe::new().unwrap();
11471 assert_eq!(pipe.handshake(), Ok(()));
11472
11473 let frames = [
11474 frame::Frame::Stream {
11475 stream_id: 0,
11476 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
11477 },
11478 frame::Frame::Stream {
11479 stream_id: 4,
11480 data: stream::RangeBuf::from(b"a", 0, false),
11481 },
11482 frame::Frame::ResetStream {
11483 stream_id: 4,
11484 error_code: 0,
11485 final_size: 15,
11486 },
11487 frame::Frame::Stream {
11488 stream_id: 8,
11489 data: stream::RangeBuf::from(b"a", 0, false),
11490 },
11491 ];
11492
11493 let pkt_type = packet::Type::Short;
11494 assert_eq!(
11495 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
11496 Err(Error::FlowControl),
11497 );
11498 }
11499
11500 #[test]
11501 fn reset_stream_flow_control_stream() {
11504 let mut buf = [0; 65535];
11505
11506 let mut pipe = testing::Pipe::new().unwrap();
11507 assert_eq!(pipe.handshake(), Ok(()));
11508
11509 let frames = [
11510 frame::Frame::Stream {
11511 stream_id: 4,
11512 data: stream::RangeBuf::from(b"a", 0, false),
11513 },
11514 frame::Frame::ResetStream {
11515 stream_id: 4,
11516 error_code: 0,
11517 final_size: 16, },
11519 ];
11520
11521 let pkt_type = packet::Type::Short;
11522 assert_eq!(
11523 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf),
11524 Err(Error::FlowControl),
11525 );
11526 }
11527
11528 #[test]
11529 fn path_challenge() {
11530 let mut buf = [0; 65535];
11531
11532 let mut pipe = testing::Pipe::new().unwrap();
11533 assert_eq!(pipe.handshake(), Ok(()));
11534
11535 let frames = [frame::Frame::PathChallenge { data: [0xba; 8] }];
11536
11537 let pkt_type = packet::Type::Short;
11538
11539 let len = pipe
11540 .send_pkt_to_server(pkt_type, &frames, &mut buf)
11541 .unwrap();
11542
11543 assert!(len > 0);
11544
11545 let frames =
11546 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
11547 let mut iter = frames.iter();
11548
11549 iter.next().unwrap();
11551
11552 assert_eq!(
11553 iter.next(),
11554 Some(&frame::Frame::PathResponse { data: [0xba; 8] })
11555 );
11556 }
11557
11558 #[cfg(not(feature = "openssl"))] #[test]
11560 fn early_1rtt_packet() {
11563 let mut buf = [0; 65535];
11564
11565 let mut pipe = testing::Pipe::new().unwrap();
11566
11567 let flight = testing::emit_flight(&mut pipe.client).unwrap();
11569 testing::process_flight(&mut pipe.server, flight).unwrap();
11570
11571 let flight = testing::emit_flight(&mut pipe.server).unwrap();
11573 testing::process_flight(&mut pipe.client, flight).unwrap();
11574
11575 let flight = testing::emit_flight(&mut pipe.client).unwrap();
11577
11578 let delayed = flight;
11581
11582 testing::emit_flight(&mut pipe.server).ok();
11583
11584 assert!(pipe.client.is_established());
11585
11586 let frames = [frame::Frame::Stream {
11588 stream_id: 0,
11589 data: stream::RangeBuf::from(b"hello, world", 0, true),
11590 }];
11591
11592 let pkt_type = packet::Type::Short;
11593 let written =
11594 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
11595 .unwrap();
11596
11597 assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
11598
11599 let frames = [frame::Frame::Stream {
11601 stream_id: 4,
11602 data: stream::RangeBuf::from(b"hello, world", 0, true),
11603 }];
11604
11605 let written =
11606 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
11607 .unwrap();
11608
11609 assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
11610
11611 assert!(!pipe.server.is_established());
11612
11613 assert_eq!(
11618 pipe.server.pkt_num_spaces[packet::Epoch::Application]
11619 .largest_rx_pkt_num,
11620 0
11621 );
11622
11623 testing::process_flight(&mut pipe.server, delayed).unwrap();
11625
11626 assert!(pipe.server.is_established());
11627
11628 assert_eq!(
11629 pipe.server.pkt_num_spaces[packet::Epoch::Application]
11630 .largest_rx_pkt_num,
11631 0
11632 );
11633 }
11634
11635 #[test]
11636 fn stop_sending() {
11637 let mut b = [0; 15];
11638
11639 let mut buf = [0; 65535];
11640
11641 let mut pipe = testing::Pipe::new().unwrap();
11642 assert_eq!(pipe.handshake(), Ok(()));
11643
11644 assert_eq!(pipe.client.stream_send(0, b"hello", true), Ok(5));
11646 assert_eq!(pipe.advance(), Ok(()));
11647
11648 let mut r = pipe.server.readable();
11650 assert_eq!(r.next(), Some(0));
11651 assert_eq!(r.next(), None);
11652
11653 assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((5, true)));
11654 assert!(pipe.server.stream_finished(0));
11655
11656 let mut r = pipe.server.readable();
11657 assert_eq!(r.next(), None);
11658
11659 let mut r = pipe.server.writable();
11661 assert_eq!(r.next(), Some(0));
11662 assert_eq!(r.next(), None);
11663
11664 while pipe.server.stream_send(0, b"world", false) != Err(Error::Done) {
11665 assert_eq!(pipe.advance(), Ok(()));
11666 }
11667
11668 let mut r = pipe.server.writable();
11669 assert_eq!(r.next(), None);
11670
11671 let frames = [frame::Frame::StopSending {
11673 stream_id: 0,
11674 error_code: 42,
11675 }];
11676
11677 let pkt_type = packet::Type::Short;
11678 let len = pipe
11679 .send_pkt_to_server(pkt_type, &frames, &mut buf)
11680 .unwrap();
11681
11682 let frames =
11684 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
11685
11686 let mut iter = frames.iter();
11687
11688 iter.next();
11690
11691 assert_eq!(
11692 iter.next(),
11693 Some(&frame::Frame::ResetStream {
11694 stream_id: 0,
11695 error_code: 42,
11696 final_size: 15,
11697 })
11698 );
11699
11700 let mut r = pipe.server.writable();
11702 assert_eq!(r.next(), Some(0));
11703 assert_eq!(r.next(), None);
11704
11705 assert_eq!(
11706 pipe.server.stream_send(0, b"world", true),
11707 Err(Error::StreamStopped(42)),
11708 );
11709
11710 assert_eq!(pipe.server.streams.len(), 1);
11711
11712 let mut ranges = ranges::RangeSet::default();
11714 ranges.insert(pipe.server.next_pkt_num - 5..pipe.server.next_pkt_num);
11715
11716 let frames = [frame::Frame::ACK {
11717 ack_delay: 15,
11718 ranges,
11719 ecn_counts: None,
11720 }];
11721
11722 assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(0));
11723
11724 assert_eq!(pipe.server.streams.len(), 0);
11726
11727 let frames = [frame::Frame::StopSending {
11729 stream_id: 0,
11730 error_code: 42,
11731 }];
11732
11733 let len = pipe
11734 .send_pkt_to_server(pkt_type, &frames, &mut buf)
11735 .unwrap();
11736
11737 let frames =
11738 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
11739
11740 assert_eq!(frames.len(), 1);
11741
11742 match frames.first() {
11743 Some(frame::Frame::ACK { .. }) => (),
11744
11745 f => panic!("expected ACK frame, got {:?}", f),
11746 };
11747
11748 let mut r = pipe.server.writable();
11749 assert_eq!(r.next(), None);
11750 }
11751
11752 #[test]
11753 fn stop_sending_fin() {
11754 let mut b = [0; 15];
11755
11756 let mut buf = [0; 65535];
11757
11758 let mut pipe = testing::Pipe::new().unwrap();
11759 assert_eq!(pipe.handshake(), Ok(()));
11760
11761 assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
11763 assert_eq!(pipe.advance(), Ok(()));
11764
11765 let mut r = pipe.server.readable();
11767 assert_eq!(r.next(), Some(4));
11768 assert_eq!(r.next(), None);
11769
11770 assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
11771 assert!(pipe.server.stream_finished(4));
11772
11773 let mut r = pipe.server.readable();
11774 assert_eq!(r.next(), None);
11775
11776 let mut r = pipe.server.writable();
11778 assert_eq!(r.next(), Some(4));
11779 assert_eq!(r.next(), None);
11780
11781 assert_eq!(pipe.server.stream_send(4, b"world", false), Ok(5));
11782 assert_eq!(pipe.advance(), Ok(()));
11783
11784 assert_eq!(pipe.server.stream_send(4, b"world", true), Ok(5));
11786
11787 let frames = [frame::Frame::StopSending {
11789 stream_id: 4,
11790 error_code: 42,
11791 }];
11792
11793 let pkt_type = packet::Type::Short;
11794 let len = pipe
11795 .send_pkt_to_server(pkt_type, &frames, &mut buf)
11796 .unwrap();
11797
11798 let frames =
11800 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
11801
11802 let mut iter = frames.iter();
11803
11804 iter.next();
11806
11807 assert_eq!(
11808 iter.next(),
11809 Some(&frame::Frame::ResetStream {
11810 stream_id: 4,
11811 error_code: 42,
11812 final_size: 5,
11813 })
11814 );
11815
11816 assert_eq!(iter.next(), None);
11818 }
11819
11820 #[test]
11821 fn stop_sending_unsent_tx_cap() {
11823 let mut buf = [0; 65535];
11824
11825 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
11826 config
11827 .load_cert_chain_from_pem_file("examples/cert.crt")
11828 .unwrap();
11829 config
11830 .load_priv_key_from_pem_file("examples/cert.key")
11831 .unwrap();
11832 config
11833 .set_application_protos(&[b"proto1", b"proto2"])
11834 .unwrap();
11835 config.set_initial_max_data(15);
11836 config.set_initial_max_stream_data_bidi_local(30);
11837 config.set_initial_max_stream_data_bidi_remote(30);
11838 config.set_initial_max_stream_data_uni(30);
11839 config.set_initial_max_streams_bidi(3);
11840 config.set_initial_max_streams_uni(0);
11841 config.verify_peer(false);
11842
11843 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
11844 assert_eq!(pipe.handshake(), Ok(()));
11845
11846 assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
11848 assert_eq!(pipe.advance(), Ok(()));
11849
11850 let mut r = pipe.server.readable();
11851 assert_eq!(r.next(), Some(4));
11852 assert_eq!(r.next(), None);
11853
11854 let mut b = [0; 15];
11855 assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
11856
11857 assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
11859 assert_eq!(pipe.advance(), Ok(()));
11860
11861 assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
11863 assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
11864 assert_eq!(
11865 pipe.server.stream_send(4, b"hello", false),
11866 Err(Error::Done)
11867 );
11868
11869 let frames = [frame::Frame::StopSending {
11871 stream_id: 4,
11872 error_code: 42,
11873 }];
11874
11875 let pkt_type = packet::Type::Short;
11876 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf)
11877 .unwrap();
11878
11879 assert_eq!(pipe.client.stream_send(8, b"hello", true), Ok(5));
11881 assert_eq!(pipe.advance(), Ok(()));
11882
11883 assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
11884 assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
11885 assert_eq!(
11886 pipe.server.stream_send(8, b"hello", false),
11887 Err(Error::Done)
11888 );
11889 assert_eq!(pipe.advance(), Ok(()));
11890 }
11891
11892 #[test]
11893 fn stream_shutdown_read() {
11894 let mut buf = [0; 65535];
11895
11896 let mut pipe = testing::Pipe::new().unwrap();
11897 assert_eq!(pipe.handshake(), Ok(()));
11898
11899 assert_eq!(pipe.client.stream_send(4, b"hello, world", false), Ok(12));
11901 assert_eq!(pipe.advance(), Ok(()));
11902
11903 let mut r = pipe.server.readable();
11904 assert_eq!(r.next(), Some(4));
11905 assert_eq!(r.next(), None);
11906
11907 assert_eq!(pipe.client.streams.len(), 1);
11908 assert_eq!(pipe.server.streams.len(), 1);
11909
11910 assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Read, 42), Ok(()));
11912
11913 let mut r = pipe.server.readable();
11914 assert_eq!(r.next(), None);
11915
11916 let (len, _) = pipe.server.send(&mut buf).unwrap();
11917
11918 let mut dummy = buf[..len].to_vec();
11919
11920 let frames =
11921 testing::decode_pkt(&mut pipe.client, &mut dummy[..len]).unwrap();
11922 let mut iter = frames.iter();
11923
11924 assert_eq!(
11925 iter.next(),
11926 Some(&frame::Frame::StopSending {
11927 stream_id: 4,
11928 error_code: 42,
11929 })
11930 );
11931
11932 assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
11933
11934 assert_eq!(pipe.advance(), Ok(()));
11935
11936 let mut r = pipe.client.writable();
11938 assert_eq!(r.next(), Some(4));
11939 assert_eq!(r.next(), None);
11940
11941 assert_eq!(
11942 pipe.client.stream_send(4, b"bye", false),
11943 Err(Error::StreamStopped(42))
11944 );
11945
11946 assert_eq!(pipe.server.stream_send(4, b"hello, world", true), Ok(12));
11949 assert_eq!(pipe.advance(), Ok(()));
11950
11951 let mut r = pipe.client.readable();
11953 assert_eq!(r.next(), Some(4));
11954 assert_eq!(r.next(), None);
11955
11956 assert_eq!(pipe.client.stream_recv(4, &mut buf), Ok((12, true)));
11957
11958 assert_eq!(pipe.client.streams.len(), 0);
11960 assert_eq!(pipe.server.streams.len(), 0);
11961
11962 assert_eq!(
11963 pipe.server.stream_shutdown(4, Shutdown::Read, 0),
11964 Err(Error::Done)
11965 );
11966 }
11967
11968 #[test]
11969 fn stream_shutdown_read_after_fin() {
11970 let mut buf = [0; 65535];
11971
11972 let mut pipe = testing::Pipe::new().unwrap();
11973 assert_eq!(pipe.handshake(), Ok(()));
11974
11975 assert_eq!(pipe.client.stream_send(4, b"hello, world", true), Ok(12));
11977 assert_eq!(pipe.advance(), Ok(()));
11978
11979 let mut r = pipe.server.readable();
11980 assert_eq!(r.next(), Some(4));
11981 assert_eq!(r.next(), None);
11982
11983 assert_eq!(pipe.client.streams.len(), 1);
11984 assert_eq!(pipe.server.streams.len(), 1);
11985
11986 assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Read, 42), Ok(()));
11988
11989 let mut r = pipe.server.readable();
11990 assert_eq!(r.next(), None);
11991
11992 assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
11994
11995 assert_eq!(pipe.advance(), Ok(()));
11996
11997 assert_eq!(pipe.server.stream_send(4, b"hello, world", true), Ok(12));
12000 assert_eq!(pipe.advance(), Ok(()));
12001
12002 let mut r = pipe.client.readable();
12004 assert_eq!(r.next(), Some(4));
12005 assert_eq!(r.next(), None);
12006
12007 assert_eq!(pipe.client.stream_recv(4, &mut buf), Ok((12, true)));
12008
12009 assert_eq!(pipe.client.streams.len(), 0);
12011 assert_eq!(pipe.server.streams.len(), 0);
12012
12013 assert_eq!(
12014 pipe.server.stream_shutdown(4, Shutdown::Read, 0),
12015 Err(Error::Done)
12016 );
12017 }
12018
12019 #[test]
12020 fn stream_shutdown_read_update_max_data() {
12021 let mut buf = [0; 65535];
12022
12023 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
12024 config
12025 .load_cert_chain_from_pem_file("examples/cert.crt")
12026 .unwrap();
12027 config
12028 .load_priv_key_from_pem_file("examples/cert.key")
12029 .unwrap();
12030 config
12031 .set_application_protos(&[b"proto1", b"proto2"])
12032 .unwrap();
12033 config.set_initial_max_data(30);
12034 config.set_initial_max_stream_data_bidi_local(10000);
12035 config.set_initial_max_stream_data_bidi_remote(10000);
12036 config.set_initial_max_streams_bidi(10);
12037 config.verify_peer(false);
12038
12039 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12040 assert_eq!(pipe.handshake(), Ok(()));
12041
12042 assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
12043 assert_eq!(pipe.advance(), Ok(()));
12044
12045 assert_eq!(pipe.server.stream_recv(0, &mut buf), Ok((1, false)));
12046 assert_eq!(pipe.server.stream_shutdown(0, Shutdown::Read, 123), Ok(()));
12047
12048 assert_eq!(pipe.server.rx_data, 1);
12049 assert_eq!(pipe.client.tx_data, 1);
12050 assert_eq!(pipe.client.max_tx_data, 30);
12051
12052 assert_eq!(
12053 pipe.client
12054 .stream_send(0, &buf[..pipe.client.tx_cap], false),
12055 Ok(29)
12056 );
12057 assert_eq!(pipe.advance(), Ok(()));
12058
12059 assert!(!pipe.server.stream_readable(0)); assert_eq!(pipe.client.tx_data, 30);
12064 assert_eq!(pipe.server.rx_data, 30);
12065 assert_eq!(pipe.client.tx_cap, 45);
12066 }
12067
12068 #[test]
12069 fn stream_shutdown_uni() {
12070 let mut pipe = testing::Pipe::new().unwrap();
12071 assert_eq!(pipe.handshake(), Ok(()));
12072
12073 assert_eq!(pipe.client.stream_send(2, b"hello, world", false), Ok(10));
12075 assert_eq!(pipe.server.stream_send(3, b"hello, world", false), Ok(10));
12076 assert_eq!(pipe.advance(), Ok(()));
12077
12078 assert_eq!(pipe.client.stream_shutdown(2, Shutdown::Write, 42), Ok(()));
12080 assert_eq!(
12081 pipe.client.stream_shutdown(2, Shutdown::Read, 42),
12082 Err(Error::InvalidStreamState(2))
12083 );
12084
12085 assert_eq!(
12086 pipe.client.stream_shutdown(3, Shutdown::Write, 42),
12087 Err(Error::InvalidStreamState(3))
12088 );
12089 assert_eq!(pipe.client.stream_shutdown(3, Shutdown::Read, 42), Ok(()));
12090 }
12091
12092 #[test]
12093 fn stream_shutdown_write() {
12094 let mut buf = [0; 65535];
12095
12096 let mut pipe = testing::Pipe::new().unwrap();
12097 assert_eq!(pipe.handshake(), Ok(()));
12098
12099 assert_eq!(pipe.client.stream_send(4, b"hello, world", false), Ok(12));
12101 assert_eq!(pipe.advance(), Ok(()));
12102
12103 let mut r = pipe.server.readable();
12104 assert_eq!(r.next(), Some(4));
12105 assert_eq!(r.next(), None);
12106
12107 let mut r = pipe.server.writable();
12108 assert_eq!(r.next(), Some(4));
12109 assert_eq!(r.next(), None);
12110
12111 assert_eq!(pipe.client.streams.len(), 1);
12112 assert_eq!(pipe.server.streams.len(), 1);
12113
12114 assert_eq!(pipe.server.stream_send(4, b"goodbye, world", false), Ok(14));
12116 assert_eq!(pipe.advance(), Ok(()));
12117
12118 assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Write, 42), Ok(()));
12120
12121 let mut r = pipe.server.writable();
12122 assert_eq!(r.next(), None);
12123
12124 let (len, _) = pipe.server.send(&mut buf).unwrap();
12125
12126 let mut dummy = buf[..len].to_vec();
12127
12128 let frames =
12129 testing::decode_pkt(&mut pipe.client, &mut dummy[..len]).unwrap();
12130 let mut iter = frames.iter();
12131
12132 assert_eq!(
12133 iter.next(),
12134 Some(&frame::Frame::ResetStream {
12135 stream_id: 4,
12136 error_code: 42,
12137 final_size: 14,
12138 })
12139 );
12140
12141 assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
12142
12143 assert_eq!(pipe.advance(), Ok(()));
12144
12145 assert_eq!(
12147 pipe.server.stream_send(4, b"bye", false),
12148 Err(Error::FinalSize)
12149 );
12150
12151 assert_eq!(pipe.client.stream_send(4, b"bye", true), Ok(3));
12153 assert_eq!(pipe.advance(), Ok(()));
12154
12155 let mut r = pipe.server.readable();
12157 assert_eq!(r.next(), Some(4));
12158 assert_eq!(r.next(), None);
12159
12160 assert_eq!(pipe.server.stream_recv(4, &mut buf), Ok((15, true)));
12161
12162 let mut r = pipe.client.readable();
12164 assert_eq!(r.next(), Some(4));
12165 assert_eq!(r.next(), None);
12166
12167 assert_eq!(
12168 pipe.client.stream_recv(4, &mut buf),
12169 Err(Error::StreamReset(42))
12170 );
12171
12172 assert_eq!(pipe.client.streams.len(), 0);
12174 assert_eq!(pipe.server.streams.len(), 0);
12175
12176 assert_eq!(
12177 pipe.server.stream_shutdown(4, Shutdown::Write, 0),
12178 Err(Error::Done)
12179 );
12180 }
12181
12182 #[test]
12183 fn stream_shutdown_write_unsent_tx_cap() {
12185 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
12186 config
12187 .load_cert_chain_from_pem_file("examples/cert.crt")
12188 .unwrap();
12189 config
12190 .load_priv_key_from_pem_file("examples/cert.key")
12191 .unwrap();
12192 config
12193 .set_application_protos(&[b"proto1", b"proto2"])
12194 .unwrap();
12195 config.set_initial_max_data(15);
12196 config.set_initial_max_stream_data_bidi_local(30);
12197 config.set_initial_max_stream_data_bidi_remote(30);
12198 config.set_initial_max_stream_data_uni(30);
12199 config.set_initial_max_streams_bidi(3);
12200 config.set_initial_max_streams_uni(0);
12201 config.verify_peer(false);
12202
12203 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12204 assert_eq!(pipe.handshake(), Ok(()));
12205
12206 assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
12208 assert_eq!(pipe.advance(), Ok(()));
12209
12210 let mut r = pipe.server.readable();
12211 assert_eq!(r.next(), Some(4));
12212 assert_eq!(r.next(), None);
12213
12214 let mut b = [0; 15];
12215 assert_eq!(pipe.server.stream_recv(4, &mut b), Ok((5, true)));
12216
12217 assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
12219 assert_eq!(pipe.advance(), Ok(()));
12220
12221 assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
12223 assert_eq!(pipe.server.stream_send(4, b"hello", false), Ok(5));
12224 assert_eq!(
12225 pipe.server.stream_send(4, b"hello", false),
12226 Err(Error::Done)
12227 );
12228
12229 assert!(!pipe.client.should_update_max_data());
12231
12232 assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Write, 42), Ok(()));
12234 assert_eq!(pipe.advance(), Ok(()));
12235
12236 assert_eq!(pipe.client.stream_send(8, b"hello", true), Ok(5));
12238 assert_eq!(pipe.advance(), Ok(()));
12239
12240 assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
12241 assert_eq!(pipe.server.stream_send(8, b"hello", false), Ok(5));
12242 assert_eq!(
12243 pipe.server.stream_send(8, b"hello", false),
12244 Err(Error::Done)
12245 );
12246 assert_eq!(pipe.advance(), Ok(()));
12247 }
12248
12249 #[test]
12250 fn stream_round_robin() {
12253 let mut buf = [0; 65535];
12254
12255 let mut pipe = testing::Pipe::new().unwrap();
12256 assert_eq!(pipe.handshake(), Ok(()));
12257
12258 assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
12259 assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
12260 assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
12261
12262 let (len, _) = pipe.client.send(&mut buf).unwrap();
12263
12264 let frames =
12265 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
12266
12267 let mut iter = frames.iter();
12268
12269 iter.next();
12271
12272 assert_eq!(
12273 iter.next(),
12274 Some(&frame::Frame::Stream {
12275 stream_id: 8,
12276 data: stream::RangeBuf::from(b"aaaaa", 0, false),
12277 })
12278 );
12279
12280 let (len, _) = pipe.client.send(&mut buf).unwrap();
12281
12282 let frames =
12283 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
12284
12285 assert_eq!(
12286 frames.first(),
12287 Some(&frame::Frame::Stream {
12288 stream_id: 0,
12289 data: stream::RangeBuf::from(b"aaaaa", 0, false),
12290 })
12291 );
12292
12293 let (len, _) = pipe.client.send(&mut buf).unwrap();
12294
12295 let frames =
12296 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
12297
12298 assert_eq!(
12299 frames.first(),
12300 Some(&frame::Frame::Stream {
12301 stream_id: 4,
12302 data: stream::RangeBuf::from(b"aaaaa", 0, false),
12303 })
12304 );
12305 }
12306
12307 #[test]
12308 fn stream_readable() {
12310 let mut pipe = testing::Pipe::new().unwrap();
12311 assert_eq!(pipe.handshake(), Ok(()));
12312
12313 let mut r = pipe.client.readable();
12315 assert_eq!(r.next(), None);
12316
12317 assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
12318
12319 let mut r = pipe.client.readable();
12320 assert_eq!(r.next(), None);
12321
12322 let mut r = pipe.server.readable();
12323 assert_eq!(r.next(), None);
12324
12325 assert_eq!(pipe.advance(), Ok(()));
12326
12327 let mut r = pipe.server.readable();
12329 assert_eq!(r.next(), Some(0));
12330 assert_eq!(r.next(), None);
12331
12332 assert_eq!(
12333 pipe.server.stream_send(0, b"aaaaaaaaaaaaaaa", false),
12334 Ok(15)
12335 );
12336 assert_eq!(pipe.advance(), Ok(()));
12337
12338 let mut r = pipe.client.readable();
12339 assert_eq!(r.next(), Some(0));
12340 assert_eq!(r.next(), None);
12341
12342 let mut b = [0; 15];
12344 pipe.client.stream_recv(0, &mut b).unwrap();
12345 assert_eq!(pipe.advance(), Ok(()));
12346
12347 let mut r = pipe.client.readable();
12348 assert_eq!(r.next(), None);
12349
12350 let mut r = pipe.server.readable();
12352 assert_eq!(r.next(), Some(0));
12353 assert_eq!(r.next(), None);
12354
12355 assert_eq!(pipe.server.stream_shutdown(0, Shutdown::Read, 0), Ok(()));
12356
12357 let mut r = pipe.server.readable();
12358 assert_eq!(r.next(), None);
12359
12360 assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
12362 assert_eq!(pipe.advance(), Ok(()));
12363
12364 assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
12365 assert_eq!(pipe.advance(), Ok(()));
12366
12367 let mut r = pipe.server.readable();
12368 assert_eq!(r.len(), 2);
12369
12370 assert!(r.next().is_some());
12371 assert!(r.next().is_some());
12372 assert!(r.next().is_none());
12373
12374 assert_eq!(r.len(), 0);
12375 }
12376
12377 #[test]
12378 fn stream_writable() {
12380 let mut pipe = testing::Pipe::new().unwrap();
12381 assert_eq!(pipe.handshake(), Ok(()));
12382
12383 let mut w = pipe.client.writable();
12385 assert_eq!(w.next(), None);
12386
12387 assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
12388
12389 let mut w = pipe.client.writable();
12391 assert_eq!(w.next(), Some(0));
12392 assert_eq!(w.next(), None);
12393
12394 assert_eq!(pipe.advance(), Ok(()));
12395
12396 let mut w = pipe.server.writable();
12398 assert_eq!(w.next(), Some(0));
12399 assert_eq!(w.next(), None);
12400
12401 assert_eq!(
12402 pipe.server.stream_send(0, b"aaaaaaaaaaaaaaa", false),
12403 Ok(15)
12404 );
12405
12406 let mut w = pipe.server.writable();
12408 assert_eq!(w.next(), None);
12409
12410 assert_eq!(pipe.advance(), Ok(()));
12411
12412 let mut b = [0; 15];
12414 pipe.client.stream_recv(0, &mut b).unwrap();
12415 assert_eq!(pipe.advance(), Ok(()));
12416
12417 let mut w = pipe.server.writable();
12419 assert_eq!(w.next(), Some(0));
12420 assert_eq!(w.next(), None);
12421
12422 assert_eq!(pipe.server.stream_shutdown(0, Shutdown::Write, 0), Ok(()));
12424
12425 let mut w = pipe.server.writable();
12426 assert_eq!(w.next(), None);
12427
12428 assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
12430 assert_eq!(pipe.advance(), Ok(()));
12431
12432 assert_eq!(pipe.client.stream_send(8, b"aaaaa", false), Ok(5));
12433 assert_eq!(pipe.advance(), Ok(()));
12434
12435 let mut w = pipe.server.writable();
12436 assert_eq!(w.len(), 2);
12437
12438 assert!(w.next().is_some());
12439 assert!(w.next().is_some());
12440 assert!(w.next().is_none());
12441
12442 assert_eq!(w.len(), 0);
12443
12444 assert_eq!(pipe.server.stream_send(8, b"aaaaa", true), Ok(5));
12446
12447 let mut w = pipe.server.writable();
12448 assert_eq!(w.next(), Some(4));
12449 assert_eq!(w.next(), None);
12450 }
12451
12452 #[test]
12453 fn stream_writable_blocked() {
12454 let mut config = crate::Config::new(crate::PROTOCOL_VERSION).unwrap();
12455 config
12456 .load_cert_chain_from_pem_file("examples/cert.crt")
12457 .unwrap();
12458 config
12459 .load_priv_key_from_pem_file("examples/cert.key")
12460 .unwrap();
12461 config.set_application_protos(&[b"h3"]).unwrap();
12462 config.set_initial_max_data(70);
12463 config.set_initial_max_stream_data_bidi_local(150000);
12464 config.set_initial_max_stream_data_bidi_remote(150000);
12465 config.set_initial_max_stream_data_uni(150000);
12466 config.set_initial_max_streams_bidi(100);
12467 config.set_initial_max_streams_uni(5);
12468 config.verify_peer(false);
12469
12470 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12471 assert_eq!(pipe.handshake(), Ok(()));
12472
12473 let send_buf = [0; 35];
12475 assert_eq!(pipe.client.stream_send(0, &send_buf, false), Ok(35));
12476
12477 assert_eq!(pipe.client.stream_writable_next(), Some(0));
12479 assert_eq!(pipe.client.stream_writable_next(), None);
12480
12481 let send_buf = [0; 36];
12484 assert_eq!(pipe.client.stream_send(0, &send_buf, false), Ok(35));
12485
12486 assert_eq!(pipe.client.stream_writable_next(), None);
12487
12488 assert_eq!(pipe.client.tx_cap, 0);
12489
12490 assert_eq!(pipe.advance(), Ok(()));
12491
12492 let mut b = [0; 70];
12493 pipe.server.stream_recv(0, &mut b).unwrap();
12494
12495 assert_eq!(pipe.advance(), Ok(()));
12496
12497 assert_ne!(pipe.client.tx_cap, 0);
12500
12501 assert_eq!(pipe.client.stream_writable_next(), Some(0));
12502 assert_eq!(pipe.client.stream_writable_next(), None);
12503 }
12504
12505 #[test]
12506 fn flow_control_limit_send() {
12509 let mut pipe = testing::Pipe::new().unwrap();
12510 assert_eq!(pipe.handshake(), Ok(()));
12511
12512 assert_eq!(
12513 pipe.client.stream_send(0, b"aaaaaaaaaaaaaaa", false),
12514 Ok(15)
12515 );
12516 assert_eq!(pipe.advance(), Ok(()));
12517 assert_eq!(
12518 pipe.client.stream_send(4, b"aaaaaaaaaaaaaaa", false),
12519 Ok(15)
12520 );
12521 assert_eq!(pipe.advance(), Ok(()));
12522 assert_eq!(pipe.client.stream_send(8, b"a", false), Err(Error::Done));
12523 assert_eq!(pipe.advance(), Ok(()));
12524
12525 let mut r = pipe.server.readable();
12526 assert!(r.next().is_some());
12527 assert!(r.next().is_some());
12528 assert!(r.next().is_none());
12529 }
12530
12531 #[test]
12532 fn invalid_initial_server() {
12535 let mut buf = [0; 65535];
12536 let mut pipe = testing::Pipe::new().unwrap();
12537
12538 let frames = [frame::Frame::Padding { len: 10 }];
12539
12540 let written = testing::encode_pkt(
12541 &mut pipe.client,
12542 packet::Type::Initial,
12543 &frames,
12544 &mut buf,
12545 )
12546 .unwrap();
12547
12548 buf[written - 1] = !buf[written - 1];
12552
12553 assert_eq!(pipe.server.timeout(), None);
12554
12555 assert_eq!(
12556 pipe.server_recv(&mut buf[..written]),
12557 Err(Error::CryptoFail)
12558 );
12559
12560 assert!(pipe.server.is_closed());
12561 }
12562
12563 #[test]
12564 fn invalid_initial_client() {
12567 let mut buf = [0; 65535];
12568 let mut pipe = testing::Pipe::new().unwrap();
12569
12570 let (len, _) = pipe.client.send(&mut buf).unwrap();
12572
12573 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(1200));
12575
12576 let frames = [frame::Frame::Padding { len: 10 }];
12577
12578 let written = testing::encode_pkt(
12579 &mut pipe.server,
12580 packet::Type::Initial,
12581 &frames,
12582 &mut buf,
12583 )
12584 .unwrap();
12585
12586 buf[written - 1] = !buf[written - 1];
12590
12591 assert_eq!(pipe.client_recv(&mut buf[..written]), Ok(71));
12593
12594 assert!(!pipe.client.is_closed());
12596
12597 assert!(pipe.client.idle_timer.is_some());
12599 }
12600
12601 #[test]
12602 fn invalid_initial_payload() {
12605 let mut buf = [0; 65535];
12606 let mut pipe = testing::Pipe::new().unwrap();
12607
12608 let mut b = octets::OctetsMut::with_slice(&mut buf);
12609
12610 let epoch = packet::Type::Initial.to_epoch().unwrap();
12611
12612 let pn = 0;
12613 let pn_len = packet::pkt_num_len(pn, 0);
12614
12615 let dcid = pipe.client.destination_id();
12616 let scid = pipe.client.source_id();
12617
12618 let hdr = Header {
12619 ty: packet::Type::Initial,
12620 version: pipe.client.version,
12621 dcid: ConnectionId::from_ref(&dcid),
12622 scid: ConnectionId::from_ref(&scid),
12623 pkt_num: 0,
12624 pkt_num_len: pn_len,
12625 token: pipe.client.token.clone(),
12626 versions: None,
12627 key_phase: false,
12628 };
12629
12630 hdr.to_bytes(&mut b).unwrap();
12631
12632 let payload_len = 4096;
12634
12635 let len = pn_len + payload_len;
12636 b.put_varint(len as u64).unwrap();
12637
12638 packet::encode_pkt_num(pn, pn_len, &mut b).unwrap();
12639
12640 let payload_offset = b.off();
12641
12642 let frames = [frame::Frame::Padding { len: 10 }];
12643
12644 for frame in &frames {
12645 frame.to_bytes(&mut b).unwrap();
12646 }
12647
12648 let space = &mut pipe.client.pkt_num_spaces[epoch];
12649
12650 let payload_len = frames.iter().fold(0, |acc, x| acc + x.wire_len());
12652
12653 let aead = space.crypto_seal.as_ref().unwrap();
12654
12655 let written = packet::encrypt_pkt(
12656 &mut b,
12657 pn,
12658 pn_len,
12659 payload_len,
12660 payload_offset,
12661 None,
12662 aead,
12663 )
12664 .unwrap();
12665
12666 assert_eq!(pipe.server.timeout(), None);
12667
12668 assert_eq!(
12669 pipe.server_recv(&mut buf[..written]),
12670 Err(Error::InvalidPacket)
12671 );
12672
12673 assert!(pipe.server.is_closed());
12674 }
12675
12676 #[test]
12677 fn invalid_packet() {
12679 let mut buf = [0; 65535];
12680
12681 let mut pipe = testing::Pipe::new().unwrap();
12682 assert_eq!(pipe.handshake(), Ok(()));
12683
12684 let frames = [frame::Frame::Padding { len: 10 }];
12685
12686 let written = testing::encode_pkt(
12687 &mut pipe.client,
12688 packet::Type::Short,
12689 &frames,
12690 &mut buf,
12691 )
12692 .unwrap();
12693
12694 buf[written - 1] = !buf[written - 1];
12698
12699 assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
12700
12701 buf[0] = 255;
12703
12704 assert_eq!(pipe.server_recv(&mut buf[..written]), Ok(written));
12705 }
12706
12707 #[test]
12708 fn recv_empty_buffer() {
12709 let mut buf = [0; 65535];
12710
12711 let mut pipe = testing::Pipe::new().unwrap();
12712 assert_eq!(pipe.handshake(), Ok(()));
12713
12714 assert_eq!(pipe.server_recv(&mut buf[..0]), Err(Error::BufferTooShort));
12715 }
12716
12717 #[test]
12718 fn stop_sending_before_flushed_packets() {
12719 let mut b = [0; 15];
12720
12721 let mut buf = [0; 65535];
12722
12723 let mut pipe = testing::Pipe::new().unwrap();
12724 assert_eq!(pipe.handshake(), Ok(()));
12725
12726 assert_eq!(pipe.client.stream_send(0, b"hello", true), Ok(5));
12728 assert_eq!(pipe.advance(), Ok(()));
12729
12730 let mut r = pipe.server.readable();
12732 assert_eq!(r.next(), Some(0));
12733 assert_eq!(r.next(), None);
12734
12735 assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((5, true)));
12736 assert!(pipe.server.stream_finished(0));
12737
12738 let mut r = pipe.server.readable();
12739 assert_eq!(r.next(), None);
12740
12741 let mut r = pipe.server.writable();
12743 assert_eq!(r.next(), Some(0));
12744 assert_eq!(r.next(), None);
12745
12746 while pipe.server.stream_send(0, b"world", false) != Err(Error::Done) {}
12747
12748 let mut r = pipe.server.writable();
12749 assert_eq!(r.next(), None);
12750
12751 let frames = [frame::Frame::StopSending {
12753 stream_id: 0,
12754 error_code: 42,
12755 }];
12756
12757 let pkt_type = packet::Type::Short;
12758 let len = pipe
12759 .send_pkt_to_server(pkt_type, &frames, &mut buf)
12760 .unwrap();
12761
12762 let frames =
12764 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
12765
12766 let mut iter = frames.iter();
12767
12768 iter.next();
12770
12771 assert_eq!(
12772 iter.next(),
12773 Some(&frame::Frame::ResetStream {
12774 stream_id: 0,
12775 error_code: 42,
12776 final_size: 0,
12777 })
12778 );
12779
12780 let mut r = pipe.server.writable();
12782 assert_eq!(r.next(), Some(0));
12783 assert_eq!(r.next(), None);
12784
12785 assert_eq!(
12786 pipe.server.stream_send(0, b"world", true),
12787 Err(Error::StreamStopped(42)),
12788 );
12789
12790 assert_eq!(pipe.server.streams.len(), 1);
12791
12792 let mut ranges = ranges::RangeSet::default();
12794 ranges.insert(0..6);
12795
12796 let frames = [frame::Frame::ACK {
12797 ack_delay: 15,
12798 ranges,
12799 ecn_counts: None,
12800 }];
12801
12802 assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(0));
12803
12804 assert_eq!(pipe.server.streams.len(), 0);
12806 }
12807
12808 #[test]
12809 fn reset_before_flushed_packets() {
12810 let mut b = [0; 15];
12811
12812 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
12813 config
12814 .load_cert_chain_from_pem_file("examples/cert.crt")
12815 .unwrap();
12816 config
12817 .load_priv_key_from_pem_file("examples/cert.key")
12818 .unwrap();
12819 config
12820 .set_application_protos(&[b"proto1", b"proto2"])
12821 .unwrap();
12822 config.set_initial_max_data(30);
12823 config.set_initial_max_stream_data_bidi_local(5);
12824 config.set_initial_max_stream_data_bidi_remote(15);
12825 config.set_initial_max_streams_bidi(3);
12826 config.verify_peer(false);
12827
12828 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12829 assert_eq!(pipe.handshake(), Ok(()));
12830
12831 assert_eq!(pipe.client.stream_send(0, b"hello", true), Ok(5));
12833 assert_eq!(pipe.advance(), Ok(()));
12834
12835 let mut r = pipe.server.readable();
12837 assert_eq!(r.next(), Some(0));
12838 assert_eq!(r.next(), None);
12839
12840 assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((5, true)));
12841 assert!(pipe.server.stream_finished(0));
12842
12843 let mut r = pipe.server.readable();
12844 assert_eq!(r.next(), None);
12845
12846 let mut r = pipe.server.writable();
12848 assert_eq!(r.next(), Some(0));
12849 assert_eq!(r.next(), None);
12850
12851 assert_eq!(pipe.server.stream_send(0, b"helloworld", false), Ok(5));
12852 assert_eq!(pipe.advance(), Ok(()));
12853
12854 assert_eq!(pipe.client.stream_recv(0, &mut b), Ok((5, false)));
12856 assert_eq!(pipe.advance(), Ok(()));
12857
12858 assert_eq!(pipe.server.stream_send(0, b"world", false), Ok(5));
12861 pipe.server.stream_shutdown(0, Shutdown::Write, 42).unwrap();
12862 assert_eq!(pipe.advance(), Ok(()));
12863
12864 assert_eq!(pipe.server.streams.len(), 0);
12866 }
12867
12868 #[test]
12869 fn stream_limit_update_bidi() {
12871 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
12872 config
12873 .load_cert_chain_from_pem_file("examples/cert.crt")
12874 .unwrap();
12875 config
12876 .load_priv_key_from_pem_file("examples/cert.key")
12877 .unwrap();
12878 config
12879 .set_application_protos(&[b"proto1", b"proto2"])
12880 .unwrap();
12881 config.set_initial_max_data(30);
12882 config.set_initial_max_stream_data_bidi_local(15);
12883 config.set_initial_max_stream_data_bidi_remote(15);
12884 config.set_initial_max_stream_data_uni(10);
12885 config.set_initial_max_streams_bidi(3);
12886 config.set_initial_max_streams_uni(0);
12887 config.verify_peer(false);
12888
12889 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12890 assert_eq!(pipe.handshake(), Ok(()));
12891
12892 assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
12894 assert_eq!(pipe.advance(), Ok(()));
12895
12896 assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
12897 assert_eq!(pipe.advance(), Ok(()));
12898
12899 assert_eq!(pipe.client.stream_send(4, b"b", true), Ok(1));
12900 assert_eq!(pipe.advance(), Ok(()));
12901
12902 assert_eq!(pipe.client.stream_send(0, b"b", true), Ok(1));
12903 assert_eq!(pipe.advance(), Ok(()));
12904
12905 let mut b = [0; 15];
12907 pipe.server.stream_recv(0, &mut b).unwrap();
12908 pipe.server.stream_recv(4, &mut b).unwrap();
12909 assert_eq!(pipe.advance(), Ok(()));
12910
12911 assert_eq!(pipe.server.stream_send(0, b"a", false), Ok(1));
12913 assert_eq!(pipe.advance(), Ok(()));
12914
12915 assert_eq!(pipe.server.stream_send(4, b"a", false), Ok(1));
12916 assert_eq!(pipe.advance(), Ok(()));
12917
12918 assert_eq!(pipe.server.stream_send(4, b"b", true), Ok(1));
12919 assert_eq!(pipe.advance(), Ok(()));
12920
12921 assert_eq!(pipe.server.stream_send(0, b"b", true), Ok(1));
12922
12923 assert_eq!(pipe.advance(), Ok(()));
12925
12926 assert_eq!(pipe.client.stream_send(8, b"a", false), Ok(1));
12928 assert_eq!(pipe.advance(), Ok(()));
12929
12930 assert_eq!(pipe.client.stream_send(12, b"a", false), Ok(1));
12931 assert_eq!(pipe.advance(), Ok(()));
12932
12933 assert_eq!(pipe.client.stream_send(16, b"a", false), Ok(1));
12934 assert_eq!(pipe.advance(), Ok(()));
12935
12936 assert_eq!(
12937 pipe.client.stream_send(20, b"a", false),
12938 Err(Error::StreamLimit)
12939 );
12940
12941 assert_eq!(pipe.server.readable().len(), 3);
12942 }
12943
12944 #[test]
12945 fn stream_limit_update_uni() {
12947 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
12948 config
12949 .load_cert_chain_from_pem_file("examples/cert.crt")
12950 .unwrap();
12951 config
12952 .load_priv_key_from_pem_file("examples/cert.key")
12953 .unwrap();
12954 config
12955 .set_application_protos(&[b"proto1", b"proto2"])
12956 .unwrap();
12957 config.set_initial_max_data(30);
12958 config.set_initial_max_stream_data_bidi_local(15);
12959 config.set_initial_max_stream_data_bidi_remote(15);
12960 config.set_initial_max_stream_data_uni(10);
12961 config.set_initial_max_streams_bidi(0);
12962 config.set_initial_max_streams_uni(3);
12963 config.verify_peer(false);
12964
12965 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
12966 assert_eq!(pipe.handshake(), Ok(()));
12967
12968 assert_eq!(pipe.client.stream_send(2, b"a", false), Ok(1));
12970 assert_eq!(pipe.advance(), Ok(()));
12971
12972 assert_eq!(pipe.client.stream_send(6, b"a", false), Ok(1));
12973 assert_eq!(pipe.advance(), Ok(()));
12974
12975 assert_eq!(pipe.client.stream_send(6, b"b", true), Ok(1));
12976 assert_eq!(pipe.advance(), Ok(()));
12977
12978 assert_eq!(pipe.client.stream_send(2, b"b", true), Ok(1));
12979 assert_eq!(pipe.advance(), Ok(()));
12980
12981 let mut b = [0; 15];
12983 pipe.server.stream_recv(2, &mut b).unwrap();
12984 pipe.server.stream_recv(6, &mut b).unwrap();
12985
12986 assert_eq!(pipe.advance(), Ok(()));
12988
12989 assert_eq!(pipe.client.stream_send(10, b"a", false), Ok(1));
12991 assert_eq!(pipe.advance(), Ok(()));
12992
12993 assert_eq!(pipe.client.stream_send(14, b"a", false), Ok(1));
12994 assert_eq!(pipe.advance(), Ok(()));
12995
12996 assert_eq!(pipe.client.stream_send(18, b"a", false), Ok(1));
12997 assert_eq!(pipe.advance(), Ok(()));
12998
12999 assert_eq!(
13000 pipe.client.stream_send(22, b"a", false),
13001 Err(Error::StreamLimit)
13002 );
13003
13004 assert_eq!(pipe.server.readable().len(), 3);
13005 }
13006
13007 #[test]
13008 fn stream_zero_length_fin() {
13012 let mut pipe = testing::Pipe::new().unwrap();
13013 assert_eq!(pipe.handshake(), Ok(()));
13014
13015 assert_eq!(
13016 pipe.client.stream_send(0, b"aaaaaaaaaaaaaaa", false),
13017 Ok(15)
13018 );
13019 assert_eq!(pipe.advance(), Ok(()));
13020
13021 let mut r = pipe.server.readable();
13022 assert_eq!(r.next(), Some(0));
13023 assert!(r.next().is_none());
13024
13025 let mut b = [0; 15];
13026 pipe.server.stream_recv(0, &mut b).unwrap();
13027 assert_eq!(pipe.advance(), Ok(()));
13028
13029 assert_eq!(pipe.client.stream_send(0, b"", true), Ok(0));
13031 assert_eq!(pipe.advance(), Ok(()));
13032
13033 let mut r = pipe.server.readable();
13035 assert_eq!(r.next(), Some(0));
13036 assert!(r.next().is_none());
13037
13038 let mut b = [0; 15];
13039 pipe.server.stream_recv(0, &mut b).unwrap();
13040 assert_eq!(pipe.advance(), Ok(()));
13041
13042 assert_eq!(pipe.client.stream_send(0, b"", true), Ok(0));
13044 assert_eq!(pipe.advance(), Ok(()));
13045
13046 let mut r = pipe.server.readable();
13049 assert_eq!(r.next(), None);
13050 }
13051
13052 #[test]
13053 fn stream_zero_length_fin_deferred_collection() {
13057 let mut pipe = testing::Pipe::new().unwrap();
13058 assert_eq!(pipe.handshake(), Ok(()));
13059
13060 assert_eq!(
13061 pipe.client.stream_send(0, b"aaaaaaaaaaaaaaa", false),
13062 Ok(15)
13063 );
13064 assert_eq!(pipe.advance(), Ok(()));
13065
13066 let mut r = pipe.server.readable();
13067 assert_eq!(r.next(), Some(0));
13068 assert!(r.next().is_none());
13069
13070 let mut b = [0; 15];
13071 pipe.server.stream_recv(0, &mut b).unwrap();
13072 assert_eq!(pipe.advance(), Ok(()));
13073
13074 assert_eq!(pipe.client.stream_send(0, b"", true), Ok(0));
13076 assert_eq!(pipe.advance(), Ok(()));
13077
13078 assert_eq!(pipe.server.stream_send(0, b"", true), Ok(0));
13080 assert_eq!(pipe.advance(), Ok(()));
13081
13082 let mut r = pipe.server.readable();
13084 assert_eq!(r.next(), Some(0));
13085 assert!(r.next().is_none());
13086
13087 let mut b = [0; 15];
13088 pipe.server.stream_recv(0, &mut b).unwrap();
13089 assert_eq!(pipe.advance(), Ok(()));
13090
13091 assert_eq!(pipe.client.stream_send(0, b"", true), Ok(0));
13093 assert_eq!(pipe.advance(), Ok(()));
13094
13095 let mut r = pipe.server.readable();
13098 assert_eq!(r.next(), None);
13099
13100 let mut r = pipe.client.readable();
13102 assert_eq!(r.next(), Some(0));
13103
13104 pipe.client.stream_recv(0, &mut b).unwrap();
13105 assert_eq!(pipe.advance(), Ok(()));
13106
13107 let mut r = pipe.client.readable();
13109 assert_eq!(r.next(), None);
13110 }
13111
13112 #[test]
13113 fn stream_zero_length_non_fin() {
13116 let mut pipe = testing::Pipe::new().unwrap();
13117 assert_eq!(pipe.handshake(), Ok(()));
13118
13119 assert_eq!(pipe.client.stream_send(0, b"", false), Ok(0));
13120
13121 assert_eq!(pipe.client.streams.len(), 1);
13123 assert_eq!(pipe.advance(), Ok(()));
13124
13125 let mut r = pipe.server.readable();
13128 assert!(r.next().is_none());
13129 }
13130
13131 #[test]
13132 fn collect_streams() {
13134 let mut buf = [0; 65535];
13135
13136 let mut pipe = testing::Pipe::new().unwrap();
13137 assert_eq!(pipe.handshake(), Ok(()));
13138
13139 assert_eq!(pipe.client.streams.len(), 0);
13140 assert_eq!(pipe.server.streams.len(), 0);
13141
13142 assert_eq!(pipe.client.stream_send(0, b"aaaaa", true), Ok(5));
13143 assert_eq!(pipe.advance(), Ok(()));
13144
13145 assert!(!pipe.client.stream_finished(0));
13146 assert!(!pipe.server.stream_finished(0));
13147
13148 assert_eq!(pipe.client.streams.len(), 1);
13149 assert_eq!(pipe.server.streams.len(), 1);
13150
13151 let mut b = [0; 5];
13152 pipe.server.stream_recv(0, &mut b).unwrap();
13153 assert_eq!(pipe.advance(), Ok(()));
13154
13155 assert_eq!(pipe.server.stream_send(0, b"aaaaa", true), Ok(5));
13156 assert_eq!(pipe.advance(), Ok(()));
13157
13158 assert!(!pipe.client.stream_finished(0));
13159 assert!(pipe.server.stream_finished(0));
13160
13161 assert_eq!(pipe.client.streams.len(), 1);
13162 assert_eq!(pipe.server.streams.len(), 0);
13163
13164 let mut b = [0; 5];
13165 pipe.client.stream_recv(0, &mut b).unwrap();
13166 assert_eq!(pipe.advance(), Ok(()));
13167
13168 assert_eq!(pipe.client.streams.len(), 0);
13169 assert_eq!(pipe.server.streams.len(), 0);
13170
13171 assert!(pipe.client.stream_finished(0));
13172 assert!(pipe.server.stream_finished(0));
13173
13174 assert_eq!(pipe.client.stream_send(0, b"", true), Err(Error::Done));
13175
13176 let frames = [frame::Frame::Stream {
13177 stream_id: 0,
13178 data: stream::RangeBuf::from(b"aa", 0, false),
13179 }];
13180
13181 let pkt_type = packet::Type::Short;
13182 assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(39));
13183 }
13184
13185 #[test]
13186 fn config_set_cc_algorithm_name() {
13187 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13188
13189 assert_eq!(config.set_cc_algorithm_name("reno"), Ok(()));
13190
13191 assert_eq!(
13193 config.set_cc_algorithm_name("???"),
13194 Err(Error::CongestionControl)
13195 );
13196 }
13197
13198 #[test]
13199 fn peer_cert() {
13200 let mut pipe = testing::Pipe::new().unwrap();
13201 assert_eq!(pipe.handshake(), Ok(()));
13202
13203 match pipe.client.peer_cert() {
13204 Some(c) => assert_eq!(c.len(), 753),
13205
13206 None => panic!("missing server certificate"),
13207 }
13208 }
13209
13210 #[test]
13211 fn peer_cert_chain() {
13212 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13213 config
13214 .load_cert_chain_from_pem_file("examples/cert-big.crt")
13215 .unwrap();
13216 config
13217 .load_priv_key_from_pem_file("examples/cert.key")
13218 .unwrap();
13219 config
13220 .set_application_protos(&[b"proto1", b"proto2"])
13221 .unwrap();
13222
13223 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
13224 assert_eq!(pipe.handshake(), Ok(()));
13225
13226 match pipe.client.peer_cert_chain() {
13227 Some(c) => assert_eq!(c.len(), 5),
13228
13229 None => panic!("missing server certificate chain"),
13230 }
13231 }
13232
13233 #[test]
13234 fn retry() {
13235 let mut buf = [0; 65535];
13236
13237 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13238 config
13239 .load_cert_chain_from_pem_file("examples/cert.crt")
13240 .unwrap();
13241 config
13242 .load_priv_key_from_pem_file("examples/cert.key")
13243 .unwrap();
13244 config
13245 .set_application_protos(&[b"proto1", b"proto2"])
13246 .unwrap();
13247
13248 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
13249
13250 let (mut len, _) = pipe.client.send(&mut buf).unwrap();
13252
13253 let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
13255
13256 let odcid = hdr.dcid.clone();
13257
13258 let mut scid = [0; MAX_CONN_ID_LEN];
13259 rand::rand_bytes(&mut scid[..]);
13260 let scid = ConnectionId::from_ref(&scid);
13261
13262 let token = b"quiche test retry token";
13263
13264 len = packet::retry(
13265 &hdr.scid,
13266 &hdr.dcid,
13267 &scid,
13268 token,
13269 hdr.version,
13270 &mut buf,
13271 )
13272 .unwrap();
13273
13274 assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
13276
13277 let (len, send_info) = pipe.client.send(&mut buf).unwrap();
13278
13279 let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
13280 assert_eq!(&hdr.token.unwrap(), token);
13281
13282 pipe.server = accept(
13284 &scid,
13285 Some(&odcid),
13286 testing::Pipe::server_addr(),
13287 send_info.from,
13288 &mut config,
13289 )
13290 .unwrap();
13291 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13292
13293 assert_eq!(pipe.advance(), Ok(()));
13294
13295 assert!(pipe.client.is_established());
13296 assert!(pipe.server.is_established());
13297 }
13298
13299 #[test]
13300 fn retry_with_pto() {
13301 let mut buf = [0; 65535];
13302
13303 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13304 config
13305 .load_cert_chain_from_pem_file("examples/cert.crt")
13306 .unwrap();
13307 config
13308 .load_priv_key_from_pem_file("examples/cert.key")
13309 .unwrap();
13310 config
13311 .set_application_protos(&[b"proto1", b"proto2"])
13312 .unwrap();
13313
13314 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
13315
13316 let (mut len, _) = pipe.client.send(&mut buf).unwrap();
13318
13319 let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
13321
13322 let odcid = hdr.dcid.clone();
13323
13324 let mut scid = [0; MAX_CONN_ID_LEN];
13325 rand::rand_bytes(&mut scid[..]);
13326 let scid = ConnectionId::from_ref(&scid);
13327
13328 let token = b"quiche test retry token";
13329
13330 len = packet::retry(
13331 &hdr.scid,
13332 &hdr.dcid,
13333 &scid,
13334 token,
13335 hdr.version,
13336 &mut buf,
13337 )
13338 .unwrap();
13339
13340 assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
13342
13343 let (len, send_info) = pipe.client.send(&mut buf).unwrap();
13344
13345 let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
13346 assert_eq!(&hdr.token.unwrap(), token);
13347
13348 pipe.server = accept(
13350 &scid,
13351 Some(&odcid),
13352 testing::Pipe::server_addr(),
13353 send_info.from,
13354 &mut config,
13355 )
13356 .unwrap();
13357 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13358
13359 let timer = pipe.client.timeout().unwrap();
13361 std::thread::sleep(timer + time::Duration::from_millis(1));
13362 pipe.client.on_timeout();
13363
13364 assert_eq!(pipe.advance(), Ok(()));
13365
13366 assert!(pipe.client.is_established());
13367 assert!(pipe.server.is_established());
13368 }
13369
13370 #[test]
13371 fn missing_retry_source_connection_id() {
13372 let mut buf = [0; 65535];
13373
13374 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13375 config
13376 .load_cert_chain_from_pem_file("examples/cert.crt")
13377 .unwrap();
13378 config
13379 .load_priv_key_from_pem_file("examples/cert.key")
13380 .unwrap();
13381 config
13382 .set_application_protos(&[b"proto1", b"proto2"])
13383 .unwrap();
13384
13385 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
13386
13387 let (mut len, _) = pipe.client.send(&mut buf).unwrap();
13389
13390 let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
13392
13393 let mut scid = [0; MAX_CONN_ID_LEN];
13394 rand::rand_bytes(&mut scid[..]);
13395 let scid = ConnectionId::from_ref(&scid);
13396
13397 let token = b"quiche test retry token";
13398
13399 len = packet::retry(
13400 &hdr.scid,
13401 &hdr.dcid,
13402 &scid,
13403 token,
13404 hdr.version,
13405 &mut buf,
13406 )
13407 .unwrap();
13408
13409 assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
13411
13412 let (len, _) = pipe.client.send(&mut buf).unwrap();
13413
13414 let from = "127.0.0.1:1234".parse().unwrap();
13417 pipe.server =
13418 accept(&scid, None, testing::Pipe::server_addr(), from, &mut config)
13419 .unwrap();
13420 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13421
13422 let flight = testing::emit_flight(&mut pipe.server).unwrap();
13423
13424 assert_eq!(
13425 testing::process_flight(&mut pipe.client, flight),
13426 Err(Error::InvalidTransportParam)
13427 );
13428 }
13429
13430 #[test]
13431 fn invalid_retry_source_connection_id() {
13432 let mut buf = [0; 65535];
13433
13434 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13435 config
13436 .load_cert_chain_from_pem_file("examples/cert.crt")
13437 .unwrap();
13438 config
13439 .load_priv_key_from_pem_file("examples/cert.key")
13440 .unwrap();
13441 config
13442 .set_application_protos(&[b"proto1", b"proto2"])
13443 .unwrap();
13444
13445 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
13446
13447 let (mut len, _) = pipe.client.send(&mut buf).unwrap();
13449
13450 let hdr = Header::from_slice(&mut buf[..len], MAX_CONN_ID_LEN).unwrap();
13452
13453 let mut scid = [0; MAX_CONN_ID_LEN];
13454 rand::rand_bytes(&mut scid[..]);
13455 let scid = ConnectionId::from_ref(&scid);
13456
13457 let token = b"quiche test retry token";
13458
13459 len = packet::retry(
13460 &hdr.scid,
13461 &hdr.dcid,
13462 &scid,
13463 token,
13464 hdr.version,
13465 &mut buf,
13466 )
13467 .unwrap();
13468
13469 assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
13471
13472 let (len, _) = pipe.client.send(&mut buf).unwrap();
13473
13474 let from = "127.0.0.1:1234".parse().unwrap();
13477 let odcid = ConnectionId::from_ref(b"bogus value");
13478 pipe.server = accept(
13479 &scid,
13480 Some(&odcid),
13481 testing::Pipe::server_addr(),
13482 from,
13483 &mut config,
13484 )
13485 .unwrap();
13486 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
13487
13488 let flight = testing::emit_flight(&mut pipe.server).unwrap();
13489
13490 assert_eq!(
13491 testing::process_flight(&mut pipe.client, flight),
13492 Err(Error::InvalidTransportParam)
13493 );
13494 }
13495
13496 #[test]
13497 fn zero_length_new_token() {
13499 let mut buf = [0; 65535];
13500
13501 let mut pipe = testing::Pipe::new().unwrap();
13502 assert_eq!(pipe.handshake(), Ok(()));
13503
13504 let frames = vec![frame::Frame::NewToken { token: vec![] }];
13505
13506 let pkt_type = packet::Type::Short;
13507
13508 let written =
13509 testing::encode_pkt(&mut pipe.server, pkt_type, &frames, &mut buf)
13510 .unwrap();
13511
13512 assert_eq!(
13513 pipe.client_recv(&mut buf[..written]),
13514 Err(Error::InvalidFrame)
13515 );
13516 }
13517
13518 #[test]
13519 fn client_sent_new_token() {
13521 let mut buf = [0; 65535];
13522
13523 let mut pipe = testing::Pipe::new().unwrap();
13524 assert_eq!(pipe.handshake(), Ok(()));
13525
13526 let frames = vec![frame::Frame::NewToken {
13527 token: vec![1, 2, 3],
13528 }];
13529
13530 let pkt_type = packet::Type::Short;
13531
13532 let written =
13533 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
13534 .unwrap();
13535
13536 assert_eq!(
13537 pipe.server_recv(&mut buf[..written]),
13538 Err(Error::InvalidPacket)
13539 );
13540 }
13541
13542 fn check_send(_: &mut impl Send) {}
13543
13544 #[test]
13545 fn config_must_be_send() {
13546 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13547 check_send(&mut config);
13548 }
13549
13550 #[test]
13551 fn connection_must_be_send() {
13552 let mut pipe = testing::Pipe::new().unwrap();
13553 check_send(&mut pipe.client);
13554 }
13555
13556 fn check_sync(_: &mut impl Sync) {}
13557
13558 #[test]
13559 fn config_must_be_sync() {
13560 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
13561 check_sync(&mut config);
13562 }
13563
13564 #[test]
13565 fn connection_must_be_sync() {
13566 let mut pipe = testing::Pipe::new().unwrap();
13567 check_sync(&mut pipe.client);
13568 }
13569
13570 #[test]
13571 fn data_blocked() {
13572 let mut buf = [0; 65535];
13573
13574 let mut pipe = testing::Pipe::new().unwrap();
13575 assert_eq!(pipe.handshake(), Ok(()));
13576
13577 assert_eq!(pipe.client.stream_send(0, b"aaaaaaaaaa", false), Ok(10));
13578 assert_eq!(pipe.client.blocked_limit, None);
13579 assert_eq!(pipe.advance(), Ok(()));
13580
13581 assert_eq!(pipe.client.stream_send(4, b"aaaaaaaaaa", false), Ok(10));
13582 assert_eq!(pipe.client.blocked_limit, None);
13583 assert_eq!(pipe.advance(), Ok(()));
13584
13585 assert_eq!(pipe.client.stream_send(8, b"aaaaaaaaaaa", false), Ok(10));
13586 assert_eq!(pipe.client.blocked_limit, Some(30));
13587
13588 let (len, _) = pipe.client.send(&mut buf).unwrap();
13589 assert_eq!(pipe.client.blocked_limit, None);
13590
13591 let frames =
13592 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
13593
13594 let mut iter = frames.iter();
13595
13596 assert_eq!(iter.next(), Some(&frame::Frame::DataBlocked { limit: 30 }));
13597
13598 assert_eq!(
13599 iter.next(),
13600 Some(&frame::Frame::Stream {
13601 stream_id: 8,
13602 data: stream::RangeBuf::from(b"aaaaaaaaaa", 0, false),
13603 })
13604 );
13605
13606 assert_eq!(iter.next(), None);
13607 }
13608
13609 #[test]
13610 fn stream_data_blocked() {
13611 let mut buf = [0; 65535];
13612
13613 let mut pipe = testing::Pipe::new().unwrap();
13614 assert_eq!(pipe.handshake(), Ok(()));
13615
13616 assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
13617 assert_eq!(pipe.client.streams.blocked().len(), 0);
13618
13619 assert_eq!(pipe.client.stream_send(0, b"aaaaa", false), Ok(5));
13620 assert_eq!(pipe.client.streams.blocked().len(), 0);
13621
13622 assert_eq!(pipe.client.stream_send(0, b"aaaaaa", false), Ok(5));
13623 assert_eq!(pipe.client.streams.blocked().len(), 1);
13624
13625 let (len, _) = pipe.client.send(&mut buf).unwrap();
13626 assert_eq!(pipe.client.streams.blocked().len(), 0);
13627
13628 let frames =
13629 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
13630
13631 let mut iter = frames.iter();
13632
13633 iter.next();
13635
13636 assert_eq!(
13637 iter.next(),
13638 Some(&frame::Frame::StreamDataBlocked {
13639 stream_id: 0,
13640 limit: 15,
13641 })
13642 );
13643
13644 assert_eq!(
13645 iter.next(),
13646 Some(&frame::Frame::Stream {
13647 stream_id: 0,
13648 data: stream::RangeBuf::from(b"aaaaaaaaaaaaaaa", 0, false),
13649 })
13650 );
13651
13652 assert_eq!(iter.next(), None);
13653
13654 assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
13657
13658 let (len, _) = pipe.client.send(&mut buf).unwrap();
13659 assert_eq!(pipe.client.streams.blocked().len(), 0);
13660
13661 let frames =
13662 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
13663
13664 let mut iter = frames.iter();
13665
13666 assert_eq!(
13667 iter.next(),
13668 Some(&frame::Frame::Stream {
13669 stream_id: 4,
13670 data: stream::RangeBuf::from(b"a", 0, false),
13671 })
13672 );
13673
13674 assert_eq!(iter.next(), None);
13675
13676 assert_eq!(
13679 pipe.client.stream_send(0, b"aaaaaa", false),
13680 Err(Error::Done)
13681 );
13682 assert_eq!(pipe.client.streams.blocked().len(), 0);
13683 assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
13684 }
13685
13686 #[test]
13687 fn stream_data_blocked_unblocked_flow_control() {
13688 let mut buf = [0; 65535];
13689 let mut pipe = testing::Pipe::new().unwrap();
13690 assert_eq!(pipe.handshake(), Ok(()));
13691
13692 assert_eq!(
13693 pipe.client.stream_send(0, b"aaaaaaaaaaaaaaah", false),
13694 Ok(15)
13695 );
13696 assert_eq!(pipe.client.streams.blocked().len(), 1);
13697 assert_eq!(pipe.advance(), Ok(()));
13698 assert_eq!(pipe.client.streams.blocked().len(), 0);
13699
13700 assert_eq!(pipe.client.stream_send(0, b"h", false), Err(Error::Done));
13703 assert_eq!(pipe.client.streams.blocked().len(), 0);
13704
13705 assert_eq!(pipe.client.stream_send(0, b"h", false), Err(Error::Done));
13708 assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
13709
13710 assert_eq!(pipe.client.stream_send(0, b"h", false), Err(Error::Done));
13711 assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
13712
13713 assert_eq!(pipe.client.stream_send(0, b"h", false), Err(Error::Done));
13714 assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
13715
13716 let mut r = pipe.server.readable();
13718 assert_eq!(r.next(), Some(0));
13719 assert_eq!(r.next(), None);
13720
13721 let mut b = [0; 10];
13722 assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((10, false)));
13723 assert_eq!(&b[..10], b"aaaaaaaaaa");
13724 assert_eq!(pipe.advance(), Ok(()));
13725
13726 assert_eq!(pipe.client.stream_send(0, b"hhhhhhhhhh!", false), Ok(10));
13727 assert_eq!(pipe.client.streams.blocked().len(), 1);
13728
13729 let (len, _) = pipe.client.send(&mut buf).unwrap();
13730 assert_eq!(pipe.client.streams.blocked().len(), 0);
13731
13732 let frames =
13733 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
13734
13735 let mut iter = frames.iter();
13736
13737 assert_eq!(
13738 iter.next(),
13739 Some(&frame::Frame::StreamDataBlocked {
13740 stream_id: 0,
13741 limit: 25,
13742 })
13743 );
13744
13745 assert_eq!(pipe.client.stream_send(0, b"!", false), Err(Error::Done));
13748 assert_eq!(pipe.client.streams.blocked().len(), 0);
13749 assert_eq!(pipe.client.send(&mut buf), Err(Error::Done));
13750 }
13751
13752 #[test]
13753 fn app_limited_true() {
13754 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13755 config
13756 .set_application_protos(&[b"proto1", b"proto2"])
13757 .unwrap();
13758 config.set_initial_max_data(50000);
13759 config.set_initial_max_stream_data_bidi_local(50000);
13760 config.set_initial_max_stream_data_bidi_remote(50000);
13761 config.set_max_recv_udp_payload_size(1200);
13762 config.verify_peer(false);
13763
13764 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
13765 assert_eq!(pipe.handshake(), Ok(()));
13766
13767 assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
13769 assert_eq!(pipe.advance(), Ok(()));
13770
13771 let mut b = [0; 15];
13773 pipe.server.stream_recv(0, &mut b).unwrap();
13774 assert_eq!(pipe.advance(), Ok(()));
13775
13776 let send_buf = [0; 10000];
13778 assert_eq!(pipe.server.stream_send(0, &send_buf, false), Ok(10000));
13779 assert_eq!(pipe.advance(), Ok(()));
13780
13781 assert!(pipe
13783 .server
13784 .paths
13785 .get_active()
13786 .expect("no active")
13787 .recovery
13788 .app_limited());
13789 }
13790
13791 #[test]
13792 fn app_limited_false() {
13793 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13794 config
13795 .set_application_protos(&[b"proto1", b"proto2"])
13796 .unwrap();
13797 config.set_initial_max_data(50000);
13798 config.set_initial_max_stream_data_bidi_local(50000);
13799 config.set_initial_max_stream_data_bidi_remote(50000);
13800 config.set_max_recv_udp_payload_size(1200);
13801 config.verify_peer(false);
13802
13803 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
13804 assert_eq!(pipe.handshake(), Ok(()));
13805
13806 assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
13808 assert_eq!(pipe.advance(), Ok(()));
13809
13810 let mut b = [0; 15];
13812 pipe.server.stream_recv(0, &mut b).unwrap();
13813 assert_eq!(pipe.advance(), Ok(()));
13814
13815 let send_buf1 = [0; 20000];
13817 assert_eq!(pipe.server.stream_send(0, &send_buf1, false), Ok(12000));
13818
13819 testing::emit_flight(&mut pipe.server).ok();
13820
13821 assert!(!pipe
13824 .server
13825 .paths
13826 .get_active()
13827 .expect("no active")
13828 .recovery
13829 .app_limited());
13830 }
13831
13832 #[test]
13833 fn sends_ack_only_pkt_when_full_cwnd_and_ack_elicited() {
13834 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13835 config
13836 .load_cert_chain_from_pem_file("examples/cert.crt")
13837 .unwrap();
13838 config
13839 .load_priv_key_from_pem_file("examples/cert.key")
13840 .unwrap();
13841 config
13842 .set_application_protos(&[b"proto1", b"proto2"])
13843 .unwrap();
13844 config.set_initial_max_data(50000);
13845 config.set_initial_max_stream_data_bidi_local(50000);
13846 config.set_initial_max_stream_data_bidi_remote(50000);
13847 config.set_initial_max_streams_bidi(3);
13848 config.set_initial_max_streams_uni(3);
13849 config.set_max_recv_udp_payload_size(1200);
13850 config.verify_peer(false);
13851
13852 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
13853 assert_eq!(pipe.handshake(), Ok(()));
13854
13855 let send_buf1 = [0; 20000];
13858 assert_eq!(pipe.client.stream_send(0, &send_buf1, false), Ok(12000));
13859
13860 testing::emit_flight(&mut pipe.client).ok();
13861
13862 assert_eq!(
13864 pipe.server.stream_send(1, &send_buf1[..500], false),
13865 Ok(500)
13866 );
13867
13868 testing::process_flight(
13869 &mut pipe.client,
13870 testing::emit_flight(&mut pipe.server).unwrap(),
13871 )
13872 .unwrap();
13873
13874 let mut buf = [0; 2000];
13875
13876 let ret = pipe.client.send(&mut buf);
13877
13878 assert_eq!(pipe.client.tx_cap, 0);
13879
13880 assert!(matches!(ret, Ok((_, _))), "the client should at least send one packet to acknowledge the newly received data");
13881
13882 let (sent, _) = ret.unwrap();
13883
13884 assert_ne!(sent, 0, "the client should at least send a pure ACK packet");
13885
13886 let frames =
13887 testing::decode_pkt(&mut pipe.server, &mut buf[..sent]).unwrap();
13888 assert_eq!(1, frames.len());
13889 assert!(
13890 matches!(frames[0], frame::Frame::ACK { .. }),
13891 "the packet sent by the client must be an ACK only packet"
13892 );
13893 }
13894
13895 #[test]
13898 fn sends_ack_only_pkt_when_full_cwnd_and_ack_elicited_despite_max_unacknowledging(
13899 ) {
13900 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13901 config
13902 .load_cert_chain_from_pem_file("examples/cert.crt")
13903 .unwrap();
13904 config
13905 .load_priv_key_from_pem_file("examples/cert.key")
13906 .unwrap();
13907 config
13908 .set_application_protos(&[b"proto1", b"proto2"])
13909 .unwrap();
13910 config.set_initial_max_data(50000);
13911 config.set_initial_max_stream_data_bidi_local(50000);
13912 config.set_initial_max_stream_data_bidi_remote(50000);
13913 config.set_initial_max_streams_bidi(3);
13914 config.set_initial_max_streams_uni(3);
13915 config.set_max_recv_udp_payload_size(1200);
13916 config.verify_peer(false);
13917
13918 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
13919 assert_eq!(pipe.handshake(), Ok(()));
13920
13921 let send_buf1 = [0; 20000];
13924 assert_eq!(pipe.client.stream_send(0, &send_buf1, false), Ok(12000));
13925
13926 testing::emit_flight(&mut pipe.client).ok();
13927
13928 let mut buf = [0; 2000];
13930 for _ in 0..recovery::MAX_OUTSTANDING_NON_ACK_ELICITING {
13931 let written = testing::encode_pkt(
13932 &mut pipe.server,
13933 packet::Type::Short,
13934 &[frame::Frame::Ping { mtu_probe: None }],
13935 &mut buf,
13936 )
13937 .unwrap();
13938
13939 pipe.client_recv(&mut buf[..written])
13940 .expect("client recv ping");
13941
13942 let ret = pipe.client.send(&mut buf);
13944
13945 assert!(matches!(ret, Ok((_, _))), "the client should at least send one packet to acknowledge the newly received data");
13946
13947 let (sent, _) = ret.unwrap();
13948
13949 assert_ne!(
13950 sent, 0,
13951 "the client should at least send a pure ACK packet"
13952 );
13953
13954 let frames =
13955 testing::decode_pkt(&mut pipe.server, &mut buf[..sent]).unwrap();
13956
13957 assert_eq!(1, frames.len());
13958
13959 assert!(
13960 matches!(frames[0], frame::Frame::ACK { .. }),
13961 "the packet sent by the client must be an ACK only packet"
13962 );
13963 }
13964
13965 assert_eq!(
13968 pipe.client.send(&mut buf),
13969 Err(Error::Done),
13970 "nothing for client to send after ACK-only packet"
13971 );
13972 }
13973
13974 #[test]
13975 fn app_limited_false_no_frame() {
13976 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
13977 config
13978 .set_application_protos(&[b"proto1", b"proto2"])
13979 .unwrap();
13980 config.set_initial_max_data(50000);
13981 config.set_initial_max_stream_data_bidi_local(50000);
13982 config.set_initial_max_stream_data_bidi_remote(50000);
13983 config.set_max_recv_udp_payload_size(1405);
13984 config.verify_peer(false);
13985
13986 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
13987 assert_eq!(pipe.handshake(), Ok(()));
13988
13989 assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
13991 assert_eq!(pipe.advance(), Ok(()));
13992
13993 let mut b = [0; 15];
13995 pipe.server.stream_recv(0, &mut b).unwrap();
13996 assert_eq!(pipe.advance(), Ok(()));
13997
13998 let send_buf1 = [0; 20000];
14000 assert_eq!(pipe.server.stream_send(0, &send_buf1, false), Ok(12000));
14001
14002 testing::emit_flight(&mut pipe.server).ok();
14003
14004 assert!(!pipe
14007 .server
14008 .paths
14009 .get_active()
14010 .expect("no active")
14011 .recovery
14012 .app_limited());
14013 }
14014
14015 #[test]
14016 fn app_limited_false_no_header() {
14017 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
14018 config
14019 .set_application_protos(&[b"proto1", b"proto2"])
14020 .unwrap();
14021 config.set_initial_max_data(50000);
14022 config.set_initial_max_stream_data_bidi_local(50000);
14023 config.set_initial_max_stream_data_bidi_remote(50000);
14024 config.set_max_recv_udp_payload_size(1406);
14025 config.verify_peer(false);
14026
14027 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
14028 assert_eq!(pipe.handshake(), Ok(()));
14029
14030 assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
14032 assert_eq!(pipe.advance(), Ok(()));
14033
14034 let mut b = [0; 15];
14036 pipe.server.stream_recv(0, &mut b).unwrap();
14037 assert_eq!(pipe.advance(), Ok(()));
14038
14039 let send_buf1 = [0; 20000];
14041 assert_eq!(pipe.server.stream_send(0, &send_buf1, false), Ok(12000));
14042
14043 testing::emit_flight(&mut pipe.server).ok();
14044
14045 assert!(!pipe
14048 .server
14049 .paths
14050 .get_active()
14051 .expect("no active")
14052 .recovery
14053 .app_limited());
14054 }
14055
14056 #[test]
14057 fn app_limited_not_changed_on_no_new_frames() {
14058 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
14059 config
14060 .set_application_protos(&[b"proto1", b"proto2"])
14061 .unwrap();
14062 config.set_initial_max_data(50000);
14063 config.set_initial_max_stream_data_bidi_local(50000);
14064 config.set_initial_max_stream_data_bidi_remote(50000);
14065 config.set_max_recv_udp_payload_size(1200);
14066 config.verify_peer(false);
14067
14068 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
14069 assert_eq!(pipe.handshake(), Ok(()));
14070
14071 assert_eq!(pipe.client.stream_send(0, b"a", true), Ok(1));
14073 assert_eq!(pipe.advance(), Ok(()));
14074
14075 let mut b = [0; 15];
14077 pipe.server.stream_recv(0, &mut b).unwrap();
14078 assert_eq!(pipe.advance(), Ok(()));
14079
14080 assert!(pipe
14083 .client
14084 .paths
14085 .get_active()
14086 .expect("no active")
14087 .recovery
14088 .app_limited());
14089
14090 assert_eq!(testing::emit_flight(&mut pipe.client), Err(Error::Done));
14092
14093 assert!(pipe
14095 .client
14096 .paths
14097 .get_active()
14098 .expect("no active")
14099 .recovery
14100 .app_limited());
14101 }
14102
14103 #[test]
14104 fn limit_ack_ranges() {
14105 let mut buf = [0; 65535];
14106
14107 let mut pipe = testing::Pipe::new().unwrap();
14108 assert_eq!(pipe.handshake(), Ok(()));
14109
14110 let epoch = packet::Epoch::Application;
14111
14112 assert_eq!(pipe.server.pkt_num_spaces[epoch].recv_pkt_need_ack.len(), 0);
14113
14114 let frames = [
14115 frame::Frame::Ping { mtu_probe: None },
14116 frame::Frame::Padding { len: 3 },
14117 ];
14118
14119 let pkt_type = packet::Type::Short;
14120
14121 let mut last_packet_sent = 0;
14122
14123 for _ in 0..512 {
14124 let recv_count = pipe.server.recv_count;
14125
14126 last_packet_sent = pipe.client.next_pkt_num;
14127
14128 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf)
14129 .unwrap();
14130
14131 assert_eq!(pipe.server.recv_count, recv_count + 1);
14132
14133 pipe.client.next_pkt_num += 1;
14135 }
14136
14137 assert_eq!(
14138 pipe.server.pkt_num_spaces[epoch].recv_pkt_need_ack.len(),
14139 MAX_ACK_RANGES
14140 );
14141
14142 assert_eq!(
14143 pipe.server.pkt_num_spaces[epoch].recv_pkt_need_ack.first(),
14144 Some(last_packet_sent - ((MAX_ACK_RANGES as u64) - 1) * 2)
14145 );
14146
14147 assert_eq!(
14148 pipe.server.pkt_num_spaces[epoch].recv_pkt_need_ack.last(),
14149 Some(last_packet_sent)
14150 );
14151 }
14152
14153 #[test]
14154 fn stream_priority() {
14156 const MAX_TEST_PACKET_SIZE: usize = 540;
14158
14159 let mut buf = [0; 65535];
14160
14161 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14162 config
14163 .load_cert_chain_from_pem_file("examples/cert.crt")
14164 .unwrap();
14165 config
14166 .load_priv_key_from_pem_file("examples/cert.key")
14167 .unwrap();
14168 config
14169 .set_application_protos(&[b"proto1", b"proto2"])
14170 .unwrap();
14171 config.set_initial_max_data(1_000_000);
14172 config.set_initial_max_stream_data_bidi_local(1_000_000);
14173 config.set_initial_max_stream_data_bidi_remote(1_000_000);
14174 config.set_initial_max_stream_data_uni(0);
14175 config.set_initial_max_streams_bidi(100);
14176 config.set_initial_max_streams_uni(0);
14177 config.verify_peer(false);
14178
14179 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14180 assert_eq!(pipe.handshake(), Ok(()));
14181
14182 assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
14183 assert_eq!(pipe.advance(), Ok(()));
14184
14185 assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
14186 assert_eq!(pipe.advance(), Ok(()));
14187
14188 assert_eq!(pipe.client.stream_send(8, b"a", false), Ok(1));
14189 assert_eq!(pipe.advance(), Ok(()));
14190
14191 assert_eq!(pipe.client.stream_send(12, b"a", false), Ok(1));
14192 assert_eq!(pipe.advance(), Ok(()));
14193
14194 assert_eq!(pipe.client.stream_send(16, b"a", false), Ok(1));
14195 assert_eq!(pipe.advance(), Ok(()));
14196
14197 assert_eq!(pipe.client.stream_send(20, b"a", false), Ok(1));
14198 assert_eq!(pipe.advance(), Ok(()));
14199
14200 let mut b = [0; 1];
14201
14202 let out = [b'b'; 500];
14203
14204 pipe.server.stream_recv(0, &mut b).unwrap();
14211 assert_eq!(pipe.server.stream_priority(0, 255, true), Ok(()));
14212 pipe.server.stream_send(0, &out, false).unwrap();
14213 pipe.server.stream_send(0, &out, false).unwrap();
14214 pipe.server.stream_send(0, &out, false).unwrap();
14215
14216 pipe.server.stream_recv(12, &mut b).unwrap();
14217 assert_eq!(pipe.server.stream_priority(12, 42, true), Ok(()));
14218 pipe.server.stream_send(12, &out, false).unwrap();
14219 pipe.server.stream_send(12, &out, false).unwrap();
14220 pipe.server.stream_send(12, &out, false).unwrap();
14221
14222 pipe.server.stream_recv(16, &mut b).unwrap();
14223 assert_eq!(pipe.server.stream_priority(16, 10, false), Ok(()));
14224 pipe.server.stream_send(16, &out, false).unwrap();
14225 pipe.server.stream_send(16, &out, false).unwrap();
14226 pipe.server.stream_send(16, &out, false).unwrap();
14227
14228 pipe.server.stream_recv(4, &mut b).unwrap();
14229 assert_eq!(pipe.server.stream_priority(4, 42, true), Ok(()));
14230 pipe.server.stream_send(4, &out, false).unwrap();
14231 pipe.server.stream_send(4, &out, false).unwrap();
14232 pipe.server.stream_send(4, &out, false).unwrap();
14233
14234 pipe.server.stream_recv(8, &mut b).unwrap();
14235 assert_eq!(pipe.server.stream_priority(8, 10, false), Ok(()));
14236 pipe.server.stream_send(8, &out, false).unwrap();
14237 pipe.server.stream_send(8, &out, false).unwrap();
14238 pipe.server.stream_send(8, &out, false).unwrap();
14239
14240 pipe.server.stream_recv(20, &mut b).unwrap();
14241 assert_eq!(pipe.server.stream_priority(20, 42, false), Ok(()));
14242 pipe.server.stream_send(20, &out, false).unwrap();
14243 pipe.server.stream_send(20, &out, false).unwrap();
14244 pipe.server.stream_send(20, &out, false).unwrap();
14245
14246 let mut off = 0;
14248
14249 for _ in 1..=3 {
14250 let (len, _) =
14251 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14252
14253 let frames =
14254 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14255 let stream = frames.first().unwrap();
14256
14257 assert_eq!(stream, &frame::Frame::Stream {
14258 stream_id: 8,
14259 data: stream::RangeBuf::from(&out, off, false),
14260 });
14261
14262 off = match stream {
14263 frame::Frame::Stream { data, .. } => data.max_off(),
14264
14265 _ => unreachable!(),
14266 };
14267 }
14268
14269 let mut off = 0;
14271
14272 for _ in 1..=3 {
14273 let (len, _) =
14274 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14275
14276 let frames =
14277 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14278 let stream = frames.first().unwrap();
14279
14280 assert_eq!(stream, &frame::Frame::Stream {
14281 stream_id: 16,
14282 data: stream::RangeBuf::from(&out, off, false),
14283 });
14284
14285 off = match stream {
14286 frame::Frame::Stream { data, .. } => data.max_off(),
14287
14288 _ => unreachable!(),
14289 };
14290 }
14291
14292 let mut off = 0;
14294
14295 for _ in 1..=3 {
14296 let (len, _) =
14297 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14298
14299 let frames =
14300 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14301 let stream = frames.first().unwrap();
14302
14303 assert_eq!(stream, &frame::Frame::Stream {
14304 stream_id: 20,
14305 data: stream::RangeBuf::from(&out, off, false),
14306 });
14307
14308 off = match stream {
14309 frame::Frame::Stream { data, .. } => data.max_off(),
14310
14311 _ => unreachable!(),
14312 };
14313 }
14314
14315 let mut off = 0;
14317
14318 for _ in 1..=3 {
14319 let (len, _) =
14320 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14321
14322 let frames =
14323 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14324
14325 assert_eq!(
14326 frames.first(),
14327 Some(&frame::Frame::Stream {
14328 stream_id: 12,
14329 data: stream::RangeBuf::from(&out, off, false),
14330 })
14331 );
14332
14333 let (len, _) =
14334 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14335
14336 let frames =
14337 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14338
14339 let stream = frames.first().unwrap();
14340
14341 assert_eq!(stream, &frame::Frame::Stream {
14342 stream_id: 4,
14343 data: stream::RangeBuf::from(&out, off, false),
14344 });
14345
14346 off = match stream {
14347 frame::Frame::Stream { data, .. } => data.max_off(),
14348
14349 _ => unreachable!(),
14350 };
14351 }
14352
14353 let mut off = 0;
14355
14356 for _ in 1..=3 {
14357 let (len, _) =
14358 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14359
14360 let frames =
14361 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14362 let stream = frames.first().unwrap();
14363
14364 assert_eq!(stream, &frame::Frame::Stream {
14365 stream_id: 0,
14366 data: stream::RangeBuf::from(&out, off, false),
14367 });
14368
14369 off = match stream {
14370 frame::Frame::Stream { data, .. } => data.max_off(),
14371
14372 _ => unreachable!(),
14373 };
14374 }
14375
14376 assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
14377 }
14378
14379 #[test]
14380 fn stream_reprioritize() {
14382 let mut buf = [0; 65535];
14383
14384 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14385 config
14386 .load_cert_chain_from_pem_file("examples/cert.crt")
14387 .unwrap();
14388 config
14389 .load_priv_key_from_pem_file("examples/cert.key")
14390 .unwrap();
14391 config
14392 .set_application_protos(&[b"proto1", b"proto2"])
14393 .unwrap();
14394 config.set_initial_max_data(30);
14395 config.set_initial_max_stream_data_bidi_local(15);
14396 config.set_initial_max_stream_data_bidi_remote(15);
14397 config.set_initial_max_stream_data_uni(0);
14398 config.set_initial_max_streams_bidi(5);
14399 config.set_initial_max_streams_uni(0);
14400 config.verify_peer(false);
14401
14402 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14403 assert_eq!(pipe.handshake(), Ok(()));
14404
14405 assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
14406 assert_eq!(pipe.advance(), Ok(()));
14407
14408 assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
14409 assert_eq!(pipe.advance(), Ok(()));
14410
14411 assert_eq!(pipe.client.stream_send(8, b"a", false), Ok(1));
14412 assert_eq!(pipe.advance(), Ok(()));
14413
14414 assert_eq!(pipe.client.stream_send(12, b"a", false), Ok(1));
14415 assert_eq!(pipe.advance(), Ok(()));
14416
14417 let mut b = [0; 1];
14418
14419 pipe.server.stream_recv(0, &mut b).unwrap();
14420 assert_eq!(pipe.server.stream_priority(0, 255, true), Ok(()));
14421 pipe.server.stream_send(0, b"b", false).unwrap();
14422
14423 pipe.server.stream_recv(12, &mut b).unwrap();
14424 assert_eq!(pipe.server.stream_priority(12, 42, true), Ok(()));
14425 pipe.server.stream_send(12, b"b", false).unwrap();
14426
14427 pipe.server.stream_recv(8, &mut b).unwrap();
14428 assert_eq!(pipe.server.stream_priority(8, 10, true), Ok(()));
14429 pipe.server.stream_send(8, b"b", false).unwrap();
14430
14431 pipe.server.stream_recv(4, &mut b).unwrap();
14432 assert_eq!(pipe.server.stream_priority(4, 42, true), Ok(()));
14433 pipe.server.stream_send(4, b"b", false).unwrap();
14434
14435 assert_eq!(pipe.server.stream_priority(0, 20, true), Ok(()));
14437
14438 let (len, _) = pipe.server.send(&mut buf).unwrap();
14440
14441 let frames =
14442 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14443
14444 assert_eq!(
14445 frames.first(),
14446 Some(&frame::Frame::Stream {
14447 stream_id: 8,
14448 data: stream::RangeBuf::from(b"b", 0, false),
14449 })
14450 );
14451
14452 let (len, _) = pipe.server.send(&mut buf).unwrap();
14454
14455 let frames =
14456 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14457
14458 assert_eq!(
14459 frames.first(),
14460 Some(&frame::Frame::Stream {
14461 stream_id: 0,
14462 data: stream::RangeBuf::from(b"b", 0, false),
14463 })
14464 );
14465
14466 let (len, _) = pipe.server.send(&mut buf).unwrap();
14468
14469 let frames =
14470 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14471
14472 assert_eq!(
14473 frames.first(),
14474 Some(&frame::Frame::Stream {
14475 stream_id: 12,
14476 data: stream::RangeBuf::from(b"b", 0, false),
14477 })
14478 );
14479
14480 let (len, _) = pipe.server.send(&mut buf).unwrap();
14481
14482 let frames =
14483 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14484
14485 assert_eq!(
14486 frames.first(),
14487 Some(&frame::Frame::Stream {
14488 stream_id: 4,
14489 data: stream::RangeBuf::from(b"b", 0, false),
14490 })
14491 );
14492
14493 assert_eq!(pipe.server.send(&mut buf), Err(Error::Done));
14494 }
14495
14496 #[test]
14497 fn stream_datagram_priority() {
14499 const MAX_TEST_PACKET_SIZE: usize = 540;
14501
14502 let mut buf = [0; 65535];
14503
14504 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14505 config
14506 .load_cert_chain_from_pem_file("examples/cert.crt")
14507 .unwrap();
14508 config
14509 .load_priv_key_from_pem_file("examples/cert.key")
14510 .unwrap();
14511 config
14512 .set_application_protos(&[b"proto1", b"proto2"])
14513 .unwrap();
14514 config.set_initial_max_data(1_000_000);
14515 config.set_initial_max_stream_data_bidi_local(1_000_000);
14516 config.set_initial_max_stream_data_bidi_remote(1_000_000);
14517 config.set_initial_max_stream_data_uni(0);
14518 config.set_initial_max_streams_bidi(100);
14519 config.set_initial_max_streams_uni(0);
14520 config.enable_dgram(true, 10, 10);
14521 config.verify_peer(false);
14522
14523 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14524 assert_eq!(pipe.handshake(), Ok(()));
14525
14526 assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
14527 assert_eq!(pipe.advance(), Ok(()));
14528
14529 assert_eq!(pipe.client.stream_send(4, b"a", false), Ok(1));
14530 assert_eq!(pipe.advance(), Ok(()));
14531
14532 let mut b = [0; 1];
14533
14534 let out = [b'b'; 500];
14535
14536 pipe.server.stream_recv(0, &mut b).unwrap();
14543 assert_eq!(pipe.server.stream_priority(0, 255, true), Ok(()));
14544 pipe.server.stream_send(0, &out, false).unwrap();
14545 pipe.server.stream_send(0, &out, false).unwrap();
14546 pipe.server.stream_send(0, &out, false).unwrap();
14547
14548 assert_eq!(pipe.server.stream_priority(4, 255, true), Ok(()));
14549 pipe.server.stream_send(4, &out, false).unwrap();
14550 pipe.server.stream_send(4, &out, false).unwrap();
14551 pipe.server.stream_send(4, &out, false).unwrap();
14552
14553 for _ in 1..=6 {
14554 assert_eq!(pipe.server.dgram_send(&out), Ok(()));
14555 }
14556
14557 let mut off_0 = 0;
14558 let mut off_4 = 0;
14559
14560 for _ in 1..=3 {
14561 let (len, _) =
14563 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14564
14565 let frames =
14566 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14567 let mut frame_iter = frames.iter();
14568
14569 assert_eq!(frame_iter.next().unwrap(), &frame::Frame::Datagram {
14570 data: out.into()
14571 });
14572 assert_eq!(frame_iter.next(), None);
14573
14574 let (len, _) =
14576 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14577
14578 let frames =
14579 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14580 let mut frame_iter = frames.iter();
14581 let stream = frame_iter.next().unwrap();
14582
14583 assert_eq!(stream, &frame::Frame::Stream {
14584 stream_id: 0,
14585 data: stream::RangeBuf::from(&out, off_0, false),
14586 });
14587
14588 off_0 = match stream {
14589 frame::Frame::Stream { data, .. } => data.max_off(),
14590
14591 _ => unreachable!(),
14592 };
14593 assert_eq!(frame_iter.next(), None);
14594
14595 let (len, _) =
14597 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14598
14599 let frames =
14600 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14601 let mut frame_iter = frames.iter();
14602
14603 assert_eq!(frame_iter.next().unwrap(), &frame::Frame::Datagram {
14604 data: out.into()
14605 });
14606 assert_eq!(frame_iter.next(), None);
14607
14608 let (len, _) =
14610 pipe.server.send(&mut buf[..MAX_TEST_PACKET_SIZE]).unwrap();
14611
14612 let frames =
14613 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
14614 let mut frame_iter = frames.iter();
14615 let stream = frame_iter.next().unwrap();
14616
14617 assert_eq!(stream, &frame::Frame::Stream {
14618 stream_id: 4,
14619 data: stream::RangeBuf::from(&out, off_4, false),
14620 });
14621
14622 off_4 = match stream {
14623 frame::Frame::Stream { data, .. } => data.max_off(),
14624
14625 _ => unreachable!(),
14626 };
14627 assert_eq!(frame_iter.next(), None);
14628 }
14629 }
14630
14631 #[test]
14632 fn early_retransmit() {
14634 let mut buf = [0; 65535];
14635
14636 let mut pipe = testing::Pipe::new().unwrap();
14637 assert_eq!(pipe.handshake(), Ok(()));
14638
14639 assert_eq!(pipe.client.stream_send(0, b"a", false), Ok(1));
14641 assert_eq!(pipe.advance(), Ok(()));
14642
14643 assert_eq!(pipe.client.stream_send(4, b"b", false), Ok(1));
14645 assert!(pipe.client.send(&mut buf).is_ok());
14646
14647 let timer = pipe.client.timeout().unwrap();
14649 std::thread::sleep(timer + time::Duration::from_millis(1));
14650
14651 pipe.client.on_timeout();
14652
14653 let epoch = packet::Epoch::Application;
14654 assert_eq!(
14655 pipe.client
14656 .paths
14657 .get_active()
14658 .expect("no active")
14659 .recovery
14660 .loss_probes(epoch),
14661 1,
14662 );
14663
14664 let (len, _) = pipe.client.send(&mut buf).unwrap();
14666 assert_eq!(
14667 pipe.client
14668 .paths
14669 .get_active()
14670 .expect("no active")
14671 .recovery
14672 .loss_probes(epoch),
14673 0,
14674 );
14675
14676 let frames =
14677 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
14678
14679 let mut iter = frames.iter();
14680
14681 iter.next();
14683
14684 assert_eq!(
14685 iter.next(),
14686 Some(&frame::Frame::Stream {
14687 stream_id: 4,
14688 data: stream::RangeBuf::from(b"b", 0, false),
14689 })
14690 );
14691 assert_eq!(pipe.client.stats().retrans, 1);
14692 }
14693
14694 #[test]
14695 fn dont_coalesce_probes() {
14697 let mut buf = [0; 65535];
14698
14699 let mut pipe = testing::Pipe::new().unwrap();
14700
14701 let (len, _) = pipe.client.send(&mut buf).unwrap();
14703 assert_eq!(len, 1200);
14704
14705 let timer = pipe.client.timeout().unwrap();
14707 std::thread::sleep(timer + time::Duration::from_millis(1));
14708
14709 pipe.client.on_timeout();
14710
14711 let epoch = packet::Epoch::Initial;
14712 assert_eq!(
14713 pipe.client
14714 .paths
14715 .get_active()
14716 .expect("no active")
14717 .recovery
14718 .loss_probes(epoch),
14719 1,
14720 );
14721
14722 let (len, _) = pipe.client.send(&mut buf).unwrap();
14724 assert_eq!(len, 1200);
14725 assert_eq!(
14726 pipe.client
14727 .paths
14728 .get_active()
14729 .expect("no active")
14730 .recovery
14731 .loss_probes(epoch),
14732 0,
14733 );
14734
14735 let timer = pipe.client.timeout().unwrap();
14737 std::thread::sleep(timer + time::Duration::from_millis(1));
14738
14739 pipe.client.on_timeout();
14740
14741 assert_eq!(
14742 pipe.client
14743 .paths
14744 .get_active()
14745 .expect("no active")
14746 .recovery
14747 .loss_probes(epoch),
14748 2,
14749 );
14750
14751 let (len, _) = pipe.client.send(&mut buf).unwrap();
14753 assert_eq!(len, 1200);
14754 assert_eq!(
14755 pipe.client
14756 .paths
14757 .get_active()
14758 .expect("no active")
14759 .recovery
14760 .loss_probes(epoch),
14761 1,
14762 );
14763
14764 let (len, _) = pipe.client.send(&mut buf).unwrap();
14766 assert_eq!(len, 1200);
14767 assert_eq!(
14768 pipe.client
14769 .paths
14770 .get_active()
14771 .expect("no active")
14772 .recovery
14773 .loss_probes(epoch),
14774 0,
14775 );
14776 }
14777
14778 #[test]
14779 fn coalesce_padding_short() {
14780 let mut buf = [0; 65535];
14781
14782 let mut pipe = testing::Pipe::new().unwrap();
14783
14784 let (len, _) = pipe.client.send(&mut buf).unwrap();
14786 assert_eq!(len, MIN_CLIENT_INITIAL_LEN);
14787 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
14788
14789 let (len, _) = pipe.server.send(&mut buf).unwrap();
14791 assert_eq!(len, MIN_CLIENT_INITIAL_LEN);
14792 assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
14793
14794 let (len, _) = pipe.server.send(&mut buf).unwrap();
14795 assert_eq!(pipe.client_recv(&mut buf[..len]), Ok(len));
14796
14797 assert!(pipe.client.is_established());
14799 assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
14800
14801 let (len, _) = pipe.client.send(&mut buf).unwrap();
14803 assert_eq!(len, MIN_CLIENT_INITIAL_LEN);
14804 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
14805
14806 assert_eq!(pipe.client.sent_count, pipe.server.recv_count);
14808 assert_eq!(pipe.server.sent_count, pipe.client.recv_count);
14809 }
14810
14811 #[test]
14812 fn handshake_anti_deadlock() {
14814 let mut buf = [0; 65535];
14815
14816 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
14817 config
14818 .load_cert_chain_from_pem_file("examples/cert-big.crt")
14819 .unwrap();
14820 config
14821 .load_priv_key_from_pem_file("examples/cert.key")
14822 .unwrap();
14823 config
14824 .set_application_protos(&[b"proto1", b"proto2"])
14825 .unwrap();
14826
14827 let mut pipe = testing::Pipe::with_server_config(&mut config).unwrap();
14828
14829 assert!(!pipe.client.handshake_status().has_handshake_keys);
14830 assert!(!pipe.client.handshake_status().peer_verified_address);
14831 assert!(!pipe.server.handshake_status().has_handshake_keys);
14832 assert!(pipe.server.handshake_status().peer_verified_address);
14833
14834 let (len, _) = pipe.client.send(&mut buf).unwrap();
14836 assert_eq!(len, 1200);
14837
14838 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
14841 let flight = testing::emit_flight(&mut pipe.server).unwrap();
14842
14843 assert!(!pipe.client.handshake_status().has_handshake_keys);
14844 assert!(!pipe.client.handshake_status().peer_verified_address);
14845 assert!(pipe.server.handshake_status().has_handshake_keys);
14846 assert!(pipe.server.handshake_status().peer_verified_address);
14847
14848 testing::process_flight(&mut pipe.client, flight).unwrap();
14851 testing::emit_flight(&mut pipe.client).unwrap();
14852
14853 assert!(pipe.client.handshake_status().has_handshake_keys);
14854 assert!(!pipe.client.handshake_status().peer_verified_address);
14855 assert!(pipe.server.handshake_status().has_handshake_keys);
14856 assert!(pipe.server.handshake_status().peer_verified_address);
14857
14858 assert!(pipe.client.timeout().is_some());
14860 }
14861
14862 #[test]
14863 fn handshake_packet_type_corruption() {
14866 let mut buf = [0; 65535];
14867
14868 let mut pipe = testing::Pipe::new().unwrap();
14869
14870 let (len, _) = pipe.client.send(&mut buf).unwrap();
14872 assert_eq!(len, 1200);
14873
14874 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
14876
14877 let flight = testing::emit_flight(&mut pipe.server).unwrap();
14878 testing::process_flight(&mut pipe.client, flight).unwrap();
14879
14880 let active_pid =
14882 pipe.client.paths.get_active_path_id().expect("no active");
14883 let (ty, len) = pipe
14884 .client
14885 .send_single(&mut buf, active_pid, false, time::Instant::now())
14886 .unwrap();
14887 assert_eq!(ty, Type::Initial);
14888
14889 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
14890
14891 let (ty, len) = pipe
14893 .client
14894 .send_single(&mut buf, active_pid, false, time::Instant::now())
14895 .unwrap();
14896 assert_eq!(ty, Type::Handshake);
14897
14898 buf[0] &= !(0x20);
14900
14901 let hdr = Header::from_slice(&mut buf[..len], 0).unwrap();
14902 assert_eq!(hdr.ty, Type::Initial);
14903
14904 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
14906 }
14907
14908 #[test]
14909 fn dgram_send_fails_invalidstate() {
14910 let mut pipe = testing::Pipe::new().unwrap();
14911 assert_eq!(pipe.handshake(), Ok(()));
14912
14913 assert_eq!(
14914 pipe.client.dgram_send(b"hello, world"),
14915 Err(Error::InvalidState)
14916 );
14917 }
14918
14919 #[test]
14920 fn dgram_send_app_limited() {
14921 let mut buf = [0; 65535];
14922 let send_buf = [0xcf; 1000];
14923
14924 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14925 config
14926 .load_cert_chain_from_pem_file("examples/cert.crt")
14927 .unwrap();
14928 config
14929 .load_priv_key_from_pem_file("examples/cert.key")
14930 .unwrap();
14931 config
14932 .set_application_protos(&[b"proto1", b"proto2"])
14933 .unwrap();
14934 config.set_initial_max_data(30);
14935 config.set_initial_max_stream_data_bidi_local(15);
14936 config.set_initial_max_stream_data_bidi_remote(15);
14937 config.set_initial_max_stream_data_uni(10);
14938 config.set_initial_max_streams_bidi(3);
14939 config.set_initial_max_streams_uni(3);
14940 config.enable_dgram(true, 1000, 1000);
14941 config.set_max_recv_udp_payload_size(1200);
14942 config.verify_peer(false);
14943
14944 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
14945 assert_eq!(pipe.handshake(), Ok(()));
14946
14947 for _ in 0..1000 {
14948 assert_eq!(pipe.client.dgram_send(&send_buf), Ok(()));
14949 }
14950
14951 assert!(!pipe
14952 .client
14953 .paths
14954 .get_active()
14955 .expect("no active")
14956 .recovery
14957 .app_limited());
14958 assert_eq!(pipe.client.dgram_send_queue.byte_size(), 1_000_000);
14959
14960 let (len, _) = pipe.client.send(&mut buf).unwrap();
14961
14962 assert_ne!(pipe.client.dgram_send_queue.byte_size(), 0);
14963 assert_ne!(pipe.client.dgram_send_queue.byte_size(), 1_000_000);
14964 assert!(!pipe
14965 .client
14966 .paths
14967 .get_active()
14968 .expect("no active")
14969 .recovery
14970 .app_limited());
14971
14972 assert_eq!(pipe.server_recv(&mut buf[..len]), Ok(len));
14973
14974 let flight = testing::emit_flight(&mut pipe.client).unwrap();
14975 testing::process_flight(&mut pipe.server, flight).unwrap();
14976
14977 let flight = testing::emit_flight(&mut pipe.server).unwrap();
14978 testing::process_flight(&mut pipe.client, flight).unwrap();
14979
14980 assert_ne!(pipe.client.dgram_send_queue.byte_size(), 0);
14981 assert_ne!(pipe.client.dgram_send_queue.byte_size(), 1_000_000);
14982
14983 assert!(!pipe
14984 .client
14985 .paths
14986 .get_active()
14987 .expect("no active")
14988 .recovery
14989 .app_limited());
14990 }
14991
14992 #[test]
14993 fn dgram_single_datagram() {
14994 let mut buf = [0; 65535];
14995
14996 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
14997 config
14998 .load_cert_chain_from_pem_file("examples/cert.crt")
14999 .unwrap();
15000 config
15001 .load_priv_key_from_pem_file("examples/cert.key")
15002 .unwrap();
15003 config
15004 .set_application_protos(&[b"proto1", b"proto2"])
15005 .unwrap();
15006 config.set_initial_max_data(30);
15007 config.set_initial_max_stream_data_bidi_local(15);
15008 config.set_initial_max_stream_data_bidi_remote(15);
15009 config.set_initial_max_stream_data_uni(10);
15010 config.set_initial_max_streams_bidi(3);
15011 config.set_initial_max_streams_uni(3);
15012 config.enable_dgram(true, 10, 10);
15013 config.verify_peer(false);
15014
15015 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
15016 assert_eq!(pipe.handshake(), Ok(()));
15017
15018 assert_eq!(pipe.client.dgram_send(b"hello, world"), Ok(()));
15019
15020 assert_eq!(pipe.advance(), Ok(()));
15021
15022 let result1 = pipe.server.dgram_recv(&mut buf);
15023 assert_eq!(result1, Ok(12));
15024
15025 let result2 = pipe.server.dgram_recv(&mut buf);
15026 assert_eq!(result2, Err(Error::Done));
15027 }
15028
15029 #[test]
15030 fn dgram_multiple_datagrams() {
15031 let mut buf = [0; 65535];
15032
15033 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15034 config
15035 .load_cert_chain_from_pem_file("examples/cert.crt")
15036 .unwrap();
15037 config
15038 .load_priv_key_from_pem_file("examples/cert.key")
15039 .unwrap();
15040 config
15041 .set_application_protos(&[b"proto1", b"proto2"])
15042 .unwrap();
15043 config.set_initial_max_data(30);
15044 config.set_initial_max_stream_data_bidi_local(15);
15045 config.set_initial_max_stream_data_bidi_remote(15);
15046 config.set_initial_max_stream_data_uni(10);
15047 config.set_initial_max_streams_bidi(3);
15048 config.set_initial_max_streams_uni(3);
15049 config.enable_dgram(true, 2, 3);
15050 config.verify_peer(false);
15051
15052 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
15053 assert_eq!(pipe.handshake(), Ok(()));
15054
15055 assert_eq!(pipe.client.dgram_send_queue_len(), 0);
15056 assert_eq!(pipe.client.dgram_send_queue_byte_size(), 0);
15057
15058 assert_eq!(pipe.client.dgram_send(b"hello, world"), Ok(()));
15059 assert_eq!(pipe.client.dgram_send(b"ciao, mondo"), Ok(()));
15060 assert_eq!(pipe.client.dgram_send(b"hola, mundo"), Ok(()));
15061 assert!(pipe.client.is_dgram_send_queue_full());
15062
15063 assert_eq!(pipe.client.dgram_send_queue_byte_size(), 34);
15064
15065 pipe.client
15066 .dgram_purge_outgoing(|d: &[u8]| -> bool { d[0] == b'c' });
15067
15068 assert_eq!(pipe.client.dgram_send_queue_len(), 2);
15069 assert_eq!(pipe.client.dgram_send_queue_byte_size(), 23);
15070 assert!(!pipe.client.is_dgram_send_queue_full());
15071
15072 assert_eq!(pipe.server.dgram_recv_queue_len(), 0);
15074
15075 assert_eq!(pipe.advance(), Ok(()));
15076
15077 assert_eq!(pipe.client.dgram_send_queue_len(), 0);
15079 assert_eq!(pipe.client.dgram_send_queue_byte_size(), 0);
15080
15081 assert_eq!(pipe.server.dgram_recv_queue_len(), 2);
15082 assert_eq!(pipe.server.dgram_recv_queue_byte_size(), 23);
15083 assert!(pipe.server.is_dgram_recv_queue_full());
15084
15085 let result1 = pipe.server.dgram_recv(&mut buf);
15086 assert_eq!(result1, Ok(12));
15087 assert_eq!(buf[0], b'h');
15088 assert_eq!(buf[1], b'e');
15089 assert!(!pipe.server.is_dgram_recv_queue_full());
15090
15091 let result2 = pipe.server.dgram_recv(&mut buf);
15092 assert_eq!(result2, Ok(11));
15093 assert_eq!(buf[0], b'h');
15094 assert_eq!(buf[1], b'o');
15095
15096 let result3 = pipe.server.dgram_recv(&mut buf);
15097 assert_eq!(result3, Err(Error::Done));
15098
15099 assert_eq!(pipe.server.dgram_recv_queue_len(), 0);
15100 assert_eq!(pipe.server.dgram_recv_queue_byte_size(), 0);
15101 }
15102
15103 #[test]
15104 fn dgram_send_queue_overflow() {
15105 let mut buf = [0; 65535];
15106
15107 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15108 config
15109 .load_cert_chain_from_pem_file("examples/cert.crt")
15110 .unwrap();
15111 config
15112 .load_priv_key_from_pem_file("examples/cert.key")
15113 .unwrap();
15114 config
15115 .set_application_protos(&[b"proto1", b"proto2"])
15116 .unwrap();
15117 config.set_initial_max_data(30);
15118 config.set_initial_max_stream_data_bidi_local(15);
15119 config.set_initial_max_stream_data_bidi_remote(15);
15120 config.set_initial_max_stream_data_uni(10);
15121 config.set_initial_max_streams_bidi(3);
15122 config.set_initial_max_streams_uni(3);
15123 config.enable_dgram(true, 10, 2);
15124 config.verify_peer(false);
15125
15126 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
15127 assert_eq!(pipe.handshake(), Ok(()));
15128
15129 assert_eq!(pipe.client.dgram_send(b"hello, world"), Ok(()));
15130 assert_eq!(pipe.client.dgram_send(b"ciao, mondo"), Ok(()));
15131 assert_eq!(pipe.client.dgram_send(b"hola, mundo"), Err(Error::Done));
15132
15133 assert_eq!(pipe.advance(), Ok(()));
15134
15135 let result1 = pipe.server.dgram_recv(&mut buf);
15136 assert_eq!(result1, Ok(12));
15137 assert_eq!(buf[0], b'h');
15138 assert_eq!(buf[1], b'e');
15139
15140 let result2 = pipe.server.dgram_recv(&mut buf);
15141 assert_eq!(result2, Ok(11));
15142 assert_eq!(buf[0], b'c');
15143 assert_eq!(buf[1], b'i');
15144
15145 let result3 = pipe.server.dgram_recv(&mut buf);
15146 assert_eq!(result3, Err(Error::Done));
15147 }
15148
15149 #[test]
15150 fn dgram_recv_queue_overflow() {
15151 let mut buf = [0; 65535];
15152
15153 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15154 config
15155 .load_cert_chain_from_pem_file("examples/cert.crt")
15156 .unwrap();
15157 config
15158 .load_priv_key_from_pem_file("examples/cert.key")
15159 .unwrap();
15160 config
15161 .set_application_protos(&[b"proto1", b"proto2"])
15162 .unwrap();
15163 config.set_initial_max_data(30);
15164 config.set_initial_max_stream_data_bidi_local(15);
15165 config.set_initial_max_stream_data_bidi_remote(15);
15166 config.set_initial_max_stream_data_uni(10);
15167 config.set_initial_max_streams_bidi(3);
15168 config.set_initial_max_streams_uni(3);
15169 config.enable_dgram(true, 2, 10);
15170 config.set_max_recv_udp_payload_size(1200);
15171 config.verify_peer(false);
15172
15173 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
15174 assert_eq!(pipe.handshake(), Ok(()));
15175
15176 assert_eq!(pipe.client.dgram_send(b"hello, world"), Ok(()));
15177 assert_eq!(pipe.client.dgram_send(b"ciao, mondo"), Ok(()));
15178 assert_eq!(pipe.client.dgram_send(b"hola, mundo"), Ok(()));
15179
15180 assert_eq!(pipe.advance(), Ok(()));
15181
15182 let result1 = pipe.server.dgram_recv(&mut buf);
15183 assert_eq!(result1, Ok(11));
15184 assert_eq!(buf[0], b'c');
15185 assert_eq!(buf[1], b'i');
15186
15187 let result2 = pipe.server.dgram_recv(&mut buf);
15188 assert_eq!(result2, Ok(11));
15189 assert_eq!(buf[0], b'h');
15190 assert_eq!(buf[1], b'o');
15191
15192 let result3 = pipe.server.dgram_recv(&mut buf);
15193 assert_eq!(result3, Err(Error::Done));
15194 }
15195
15196 #[test]
15197 fn dgram_send_max_size() {
15198 let mut buf = [0; MAX_DGRAM_FRAME_SIZE as usize];
15199
15200 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15201 config
15202 .load_cert_chain_from_pem_file("examples/cert.crt")
15203 .unwrap();
15204 config
15205 .load_priv_key_from_pem_file("examples/cert.key")
15206 .unwrap();
15207 config
15208 .set_application_protos(&[b"proto1", b"proto2"])
15209 .unwrap();
15210 config.set_initial_max_data(30);
15211 config.set_initial_max_stream_data_bidi_local(15);
15212 config.set_initial_max_stream_data_bidi_remote(15);
15213 config.set_initial_max_stream_data_uni(10);
15214 config.set_initial_max_streams_bidi(3);
15215 config.set_initial_max_streams_uni(3);
15216 config.enable_dgram(true, 10, 10);
15217 config.set_max_recv_udp_payload_size(1452);
15218 config.verify_peer(false);
15219
15220 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
15221
15222 assert_eq!(pipe.client.dgram_max_writable_len(), None);
15224
15225 assert_eq!(pipe.handshake(), Ok(()));
15226
15227 let max_dgram_size = pipe.client.dgram_max_writable_len().unwrap();
15228
15229 assert_eq!(max_dgram_size, 1160);
15232
15233 let dgram_packet: Vec<u8> = vec![42; max_dgram_size];
15234
15235 assert_eq!(pipe.client.dgram_send(&dgram_packet), Ok(()));
15236
15237 assert_eq!(pipe.advance(), Ok(()));
15238
15239 let result1 = pipe.server.dgram_recv(&mut buf);
15240 assert_eq!(result1, Ok(max_dgram_size));
15241
15242 let result2 = pipe.server.dgram_recv(&mut buf);
15243 assert_eq!(result2, Err(Error::Done));
15244 }
15245
15246 #[test]
15247 fn is_readable() {
15249 let mut buf = [0; 65535];
15250
15251 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15252 config
15253 .load_cert_chain_from_pem_file("examples/cert.crt")
15254 .unwrap();
15255 config
15256 .load_priv_key_from_pem_file("examples/cert.key")
15257 .unwrap();
15258 config
15259 .set_application_protos(&[b"proto1", b"proto2"])
15260 .unwrap();
15261 config.set_initial_max_data(30);
15262 config.set_initial_max_stream_data_bidi_local(15);
15263 config.set_initial_max_stream_data_bidi_remote(15);
15264 config.set_initial_max_stream_data_uni(10);
15265 config.set_initial_max_streams_bidi(3);
15266 config.set_initial_max_streams_uni(3);
15267 config.enable_dgram(true, 10, 10);
15268 config.set_max_recv_udp_payload_size(1452);
15269 config.verify_peer(false);
15270
15271 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
15272 assert_eq!(pipe.handshake(), Ok(()));
15273
15274 assert!(!pipe.client.is_readable());
15276 assert!(!pipe.server.is_readable());
15277
15278 assert_eq!(pipe.client.stream_send(4, b"aaaaa", false), Ok(5));
15279 assert_eq!(pipe.advance(), Ok(()));
15280
15281 assert!(!pipe.client.is_readable());
15283 assert!(pipe.server.is_readable());
15284
15285 assert_eq!(
15286 pipe.server.stream_send(4, b"aaaaaaaaaaaaaaa", false),
15287 Ok(15)
15288 );
15289 assert_eq!(pipe.advance(), Ok(()));
15290
15291 assert!(pipe.client.is_readable());
15293 assert!(pipe.server.is_readable());
15294
15295 let mut b = [0; 15];
15297 pipe.client.stream_recv(4, &mut b).unwrap();
15298 assert_eq!(pipe.advance(), Ok(()));
15299
15300 assert!(!pipe.client.is_readable());
15301 assert!(pipe.server.is_readable());
15302
15303 assert_eq!(pipe.server.stream_shutdown(4, Shutdown::Read, 0), Ok(()));
15305 assert!(!pipe.server.is_readable());
15306
15307 assert_eq!(pipe.client.dgram_send(b"dddddddddddddd"), Ok(()));
15309 assert_eq!(pipe.advance(), Ok(()));
15310
15311 assert!(!pipe.client.is_readable());
15312 assert!(pipe.server.is_readable());
15313
15314 assert_eq!(pipe.server.dgram_send(b"dddddddddddddd"), Ok(()));
15316 assert_eq!(pipe.advance(), Ok(()));
15317
15318 assert!(pipe.client.is_readable());
15319 assert!(pipe.server.is_readable());
15320
15321 let r = pipe.server.dgram_recv(&mut buf);
15323 assert_eq!(r, Ok(14));
15324 assert!(!pipe.server.is_readable());
15325
15326 let r = pipe.client.dgram_recv(&mut buf);
15327 assert_eq!(r, Ok(14));
15328 assert!(!pipe.client.is_readable());
15329 }
15330
15331 #[test]
15332 fn close() {
15333 let mut buf = [0; 65535];
15334
15335 let mut pipe = testing::Pipe::new().unwrap();
15336 assert_eq!(pipe.handshake(), Ok(()));
15337
15338 assert_eq!(pipe.client.close(false, 0x1234, b"hello?"), Ok(()));
15339
15340 assert_eq!(
15341 pipe.client.close(false, 0x4321, b"hello?"),
15342 Err(Error::Done)
15343 );
15344
15345 let (len, _) = pipe.client.send(&mut buf).unwrap();
15346
15347 let frames =
15348 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
15349
15350 assert_eq!(
15351 frames.first(),
15352 Some(&frame::Frame::ConnectionClose {
15353 error_code: 0x1234,
15354 frame_type: 0,
15355 reason: b"hello?".to_vec(),
15356 })
15357 );
15358 }
15359
15360 #[test]
15361 fn app_close_by_client() {
15362 let mut buf = [0; 65535];
15363
15364 let mut pipe = testing::Pipe::new().unwrap();
15365 assert_eq!(pipe.handshake(), Ok(()));
15366
15367 assert_eq!(pipe.client.close(true, 0x1234, b"hello!"), Ok(()));
15368
15369 assert_eq!(pipe.client.close(true, 0x4321, b"hello!"), Err(Error::Done));
15370
15371 let (len, _) = pipe.client.send(&mut buf).unwrap();
15372
15373 let frames =
15374 testing::decode_pkt(&mut pipe.server, &mut buf[..len]).unwrap();
15375
15376 assert_eq!(
15377 frames.first(),
15378 Some(&frame::Frame::ApplicationClose {
15379 error_code: 0x1234,
15380 reason: b"hello!".to_vec(),
15381 })
15382 );
15383 }
15384
15385 #[cfg(not(feature = "openssl"))]
15388 #[test]
15389 fn app_close_by_server_during_handshake_private_key_failure() {
15390 let mut pipe = testing::Pipe::new().unwrap();
15391 pipe.server.handshake.set_failing_private_key_method();
15392
15393 let flight = testing::emit_flight(&mut pipe.client).unwrap();
15395 assert_eq!(
15396 testing::process_flight(&mut pipe.server, flight),
15397 Err(Error::TlsFail)
15398 );
15399
15400 let flight = testing::emit_flight(&mut pipe.server).unwrap();
15401
15402 assert!(!pipe.server.is_established());
15404 assert!(!pipe.client.is_established());
15405
15406 assert_eq!(
15408 pipe.server.close(true, 123, b"fail whale"),
15409 Err(Error::Done)
15410 );
15411
15412 testing::process_flight(&mut pipe.client, flight).unwrap();
15413
15414 assert_eq!(
15416 pipe.client.close(true, 123, b"fail whale"),
15417 Err(Error::Done)
15418 );
15419
15420 assert!(!pipe.server.is_established());
15423 assert!(!pipe.client.is_established());
15424
15425 assert_eq!(pipe.advance(), Ok(()));
15426
15427 assert_eq!(
15428 pipe.server.local_error(),
15429 Some(&ConnectionError {
15430 is_app: false,
15431 error_code: 0x01,
15432 reason: vec![],
15433 })
15434 );
15435 assert_eq!(
15436 pipe.client.peer_error(),
15437 Some(&ConnectionError {
15438 is_app: false,
15439 error_code: 0x01,
15440 reason: vec![],
15441 })
15442 );
15443 }
15444
15445 #[test]
15446 fn app_close_by_server_during_handshake_not_established() {
15447 let mut pipe = testing::Pipe::new().unwrap();
15448
15449 let flight = testing::emit_flight(&mut pipe.client).unwrap();
15451 testing::process_flight(&mut pipe.server, flight).unwrap();
15452
15453 let flight = testing::emit_flight(&mut pipe.server).unwrap();
15454
15455 assert!(!pipe.client.is_established() && !pipe.server.is_established());
15457
15458 pipe.server.close(true, 123, b"fail whale").unwrap();
15460
15461 testing::process_flight(&mut pipe.client, flight).unwrap();
15462
15463 assert!(pipe.client.is_established());
15465
15466 pipe.client.stream_send(0, b"badauthtoken", true).unwrap();
15468
15469 let flight = testing::emit_flight(&mut pipe.client).unwrap();
15470 testing::process_flight(&mut pipe.server, flight).unwrap();
15471
15472 assert!(!pipe.server.is_established());
15474
15475 assert_eq!(pipe.advance(), Ok(()));
15476
15477 assert_eq!(
15478 pipe.server.local_error(),
15479 Some(&ConnectionError {
15480 is_app: false,
15481 error_code: 0x0c,
15482 reason: vec![],
15483 })
15484 );
15485 assert_eq!(
15486 pipe.client.peer_error(),
15487 Some(&ConnectionError {
15488 is_app: false,
15489 error_code: 0x0c,
15490 reason: vec![],
15491 })
15492 );
15493 }
15494
15495 #[test]
15496 fn app_close_by_server_during_handshake_established() {
15497 let mut pipe = testing::Pipe::new().unwrap();
15498
15499 let flight = testing::emit_flight(&mut pipe.client).unwrap();
15501 testing::process_flight(&mut pipe.server, flight).unwrap();
15502
15503 let flight = testing::emit_flight(&mut pipe.server).unwrap();
15504
15505 assert!(!pipe.client.is_established() && !pipe.server.is_established());
15507
15508 testing::process_flight(&mut pipe.client, flight).unwrap();
15509
15510 assert!(pipe.client.is_established());
15512
15513 pipe.client.stream_send(0, b"badauthtoken", true).unwrap();
15515
15516 let flight = testing::emit_flight(&mut pipe.client).unwrap();
15517 testing::process_flight(&mut pipe.server, flight).unwrap();
15518
15519 assert!(pipe.server.is_established());
15522
15523 pipe.server
15525 .close(true, 123, b"Invalid authentication")
15526 .unwrap();
15527
15528 assert_eq!(pipe.advance(), Ok(()));
15530
15531 assert_eq!(
15532 pipe.server.local_error(),
15533 Some(&ConnectionError {
15534 is_app: true,
15535 error_code: 123,
15536 reason: b"Invalid authentication".to_vec()
15537 })
15538 );
15539 assert_eq!(
15540 pipe.client.peer_error(),
15541 Some(&ConnectionError {
15542 is_app: true,
15543 error_code: 123,
15544 reason: b"Invalid authentication".to_vec()
15545 })
15546 );
15547 }
15548
15549 #[test]
15550 fn transport_close_by_client_during_handshake_established() {
15551 let mut pipe = testing::Pipe::new().unwrap();
15552
15553 let flight = testing::emit_flight(&mut pipe.client).unwrap();
15555 testing::process_flight(&mut pipe.server, flight).unwrap();
15556
15557 let flight = testing::emit_flight(&mut pipe.server).unwrap();
15558
15559 assert!(!pipe.client.is_established() && !pipe.server.is_established());
15561
15562 testing::process_flight(&mut pipe.client, flight).unwrap();
15563
15564 assert!(pipe.client.is_established());
15566
15567 pipe.client.close(false, 123, b"connection close").unwrap();
15569
15570 let flight = testing::emit_flight(&mut pipe.client).unwrap();
15571 testing::process_flight(&mut pipe.server, flight).unwrap();
15572
15573 assert_eq!(
15574 pipe.server.peer_error(),
15575 Some(&ConnectionError {
15576 is_app: false,
15577 error_code: 123,
15578 reason: b"connection close".to_vec()
15579 })
15580 );
15581 assert_eq!(
15582 pipe.client.local_error(),
15583 Some(&ConnectionError {
15584 is_app: false,
15585 error_code: 123,
15586 reason: b"connection close".to_vec()
15587 })
15588 );
15589 }
15590
15591 #[test]
15592 fn peer_error() {
15593 let mut pipe = testing::Pipe::new().unwrap();
15594 assert_eq!(pipe.handshake(), Ok(()));
15595
15596 assert_eq!(pipe.server.close(false, 0x1234, b"hello?"), Ok(()));
15597 assert_eq!(pipe.advance(), Ok(()));
15598
15599 assert_eq!(
15600 pipe.client.peer_error(),
15601 Some(&ConnectionError {
15602 is_app: false,
15603 error_code: 0x1234u64,
15604 reason: b"hello?".to_vec()
15605 })
15606 );
15607 }
15608
15609 #[test]
15610 fn app_peer_error() {
15611 let mut pipe = testing::Pipe::new().unwrap();
15612 assert_eq!(pipe.handshake(), Ok(()));
15613
15614 assert_eq!(pipe.server.close(true, 0x1234, b"hello!"), Ok(()));
15615 assert_eq!(pipe.advance(), Ok(()));
15616
15617 assert_eq!(
15618 pipe.client.peer_error(),
15619 Some(&ConnectionError {
15620 is_app: true,
15621 error_code: 0x1234u64,
15622 reason: b"hello!".to_vec()
15623 })
15624 );
15625 }
15626
15627 #[test]
15628 fn local_error() {
15629 let mut pipe = testing::Pipe::new().unwrap();
15630 assert_eq!(pipe.handshake(), Ok(()));
15631
15632 assert_eq!(pipe.server.local_error(), None);
15633
15634 assert_eq!(pipe.server.close(true, 0x1234, b"hello!"), Ok(()));
15635
15636 assert_eq!(
15637 pipe.server.local_error(),
15638 Some(&ConnectionError {
15639 is_app: true,
15640 error_code: 0x1234u64,
15641 reason: b"hello!".to_vec()
15642 })
15643 );
15644 }
15645
15646 #[test]
15647 fn update_max_datagram_size() {
15648 let mut client_scid = [0; 16];
15649 rand::rand_bytes(&mut client_scid[..]);
15650 let client_scid = ConnectionId::from_ref(&client_scid);
15651 let client_addr = "127.0.0.1:1234".parse().unwrap();
15652
15653 let mut server_scid = [0; 16];
15654 rand::rand_bytes(&mut server_scid[..]);
15655 let server_scid = ConnectionId::from_ref(&server_scid);
15656 let server_addr = "127.0.0.1:4321".parse().unwrap();
15657
15658 let mut client_config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15659 client_config
15660 .set_application_protos(&[b"proto1", b"proto2"])
15661 .unwrap();
15662 client_config.set_max_recv_udp_payload_size(1200);
15663
15664 let mut server_config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15665 server_config
15666 .load_cert_chain_from_pem_file("examples/cert.crt")
15667 .unwrap();
15668 server_config
15669 .load_priv_key_from_pem_file("examples/cert.key")
15670 .unwrap();
15671 server_config
15672 .set_application_protos(&[b"proto1", b"proto2"])
15673 .unwrap();
15674 server_config.verify_peer(false);
15675 server_config
15676 .set_application_protos(&[b"proto1", b"proto2"])
15677 .unwrap();
15678 server_config.set_max_send_udp_payload_size(1500);
15680
15681 let mut pipe = testing::Pipe {
15682 client: connect(
15683 Some("quic.tech"),
15684 &client_scid,
15685 client_addr,
15686 server_addr,
15687 &mut client_config,
15688 )
15689 .unwrap(),
15690 server: accept(
15691 &server_scid,
15692 None,
15693 server_addr,
15694 client_addr,
15695 &mut server_config,
15696 )
15697 .unwrap(),
15698 };
15699
15700 assert_eq!(
15702 pipe.server
15703 .paths
15704 .get_active()
15705 .expect("no active")
15706 .recovery
15707 .max_datagram_size(),
15708 1500,
15709 );
15710
15711 assert_eq!(pipe.handshake(), Ok(()));
15712
15713 assert_eq!(
15716 pipe.server
15717 .paths
15718 .get_active()
15719 .expect("no active")
15720 .recovery
15721 .max_datagram_size(),
15722 1200,
15723 );
15724 assert_eq!(
15725 pipe.server
15726 .paths
15727 .get_active()
15728 .expect("no active")
15729 .recovery
15730 .cwnd(),
15731 12000,
15732 );
15733 }
15734
15735 #[test]
15736 fn send_capacity() {
15739 let mut buf = [0; 65535];
15740
15741 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15742 config
15743 .load_cert_chain_from_pem_file("examples/cert.crt")
15744 .unwrap();
15745 config
15746 .load_priv_key_from_pem_file("examples/cert.key")
15747 .unwrap();
15748 config
15749 .set_application_protos(&[b"proto1", b"proto2"])
15750 .unwrap();
15751 config.set_initial_max_data(100000);
15752 config.set_initial_max_stream_data_bidi_local(10000);
15753 config.set_initial_max_stream_data_bidi_remote(10000);
15754 config.set_initial_max_streams_bidi(10);
15755 config.verify_peer(false);
15756
15757 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
15758 assert_eq!(pipe.handshake(), Ok(()));
15759
15760 assert_eq!(pipe.client.stream_send(0, b"hello!", true), Ok(6));
15761 assert_eq!(pipe.advance(), Ok(()));
15762
15763 assert_eq!(pipe.client.stream_send(4, b"hello!", true), Ok(6));
15764 assert_eq!(pipe.advance(), Ok(()));
15765
15766 assert_eq!(pipe.client.stream_send(8, b"hello!", true), Ok(6));
15767 assert_eq!(pipe.advance(), Ok(()));
15768
15769 assert_eq!(pipe.client.stream_send(12, b"hello!", true), Ok(6));
15770 assert_eq!(pipe.advance(), Ok(()));
15771
15772 let mut r = pipe.server.readable().collect::<Vec<u64>>();
15773 assert_eq!(r.len(), 4);
15774
15775 r.sort();
15776
15777 assert_eq!(r, [0, 4, 8, 12]);
15778
15779 assert_eq!(pipe.server.stream_recv(0, &mut buf), Ok((6, true)));
15780 assert_eq!(pipe.server.stream_recv(4, &mut buf), Ok((6, true)));
15781 assert_eq!(pipe.server.stream_recv(8, &mut buf), Ok((6, true)));
15782 assert_eq!(pipe.server.stream_recv(12, &mut buf), Ok((6, true)));
15783
15784 assert_eq!(pipe.server.tx_cap, 12000);
15785
15786 assert_eq!(pipe.server.stream_send(0, &buf[..5000], false), Ok(5000));
15787 assert_eq!(pipe.server.stream_send(4, &buf[..5000], false), Ok(5000));
15788 assert_eq!(pipe.server.stream_send(8, &buf[..5000], false), Ok(2000));
15789
15790 assert_eq!(
15792 pipe.server.stream_send(12, &buf[..5000], false),
15793 Err(Error::Done)
15794 );
15795 assert_eq!(pipe.server.tx_cap, 0);
15796
15797 assert_eq!(pipe.advance(), Ok(()));
15798 }
15799
15800 #[cfg(feature = "boringssl-boring-crate")]
15801 #[test]
15802 fn user_provided_boring_ctx() -> Result<()> {
15803 let mut server_tls_ctx_builder =
15805 boring::ssl::SslContextBuilder::new(boring::ssl::SslMethod::tls())
15806 .unwrap();
15807 server_tls_ctx_builder
15808 .set_certificate_chain_file("examples/cert.crt")
15809 .unwrap();
15810 server_tls_ctx_builder
15811 .set_private_key_file(
15812 "examples/cert.key",
15813 boring::ssl::SslFiletype::PEM,
15814 )
15815 .unwrap();
15816
15817 let mut server_config = Config::with_boring_ssl_ctx_builder(
15818 crate::PROTOCOL_VERSION,
15819 server_tls_ctx_builder,
15820 )?;
15821 let mut client_config = Config::new(crate::PROTOCOL_VERSION)?;
15822 client_config.load_cert_chain_from_pem_file("examples/cert.crt")?;
15823 client_config.load_priv_key_from_pem_file("examples/cert.key")?;
15824
15825 for config in [&mut client_config, &mut server_config] {
15826 config.set_application_protos(&[b"proto1", b"proto2"])?;
15827 config.set_initial_max_data(30);
15828 config.set_initial_max_stream_data_bidi_local(15);
15829 config.set_initial_max_stream_data_bidi_remote(15);
15830 config.set_initial_max_stream_data_uni(10);
15831 config.set_initial_max_streams_bidi(3);
15832 config.set_initial_max_streams_uni(3);
15833 config.set_max_idle_timeout(180_000);
15834 config.verify_peer(false);
15835 config.set_ack_delay_exponent(8);
15836 }
15837
15838 let mut pipe = testing::Pipe::with_client_and_server_config(
15839 &mut client_config,
15840 &mut server_config,
15841 )?;
15842
15843 assert_eq!(pipe.handshake(), Ok(()));
15844
15845 Ok(())
15846 }
15847
15848 #[cfg(feature = "boringssl-boring-crate")]
15849 #[test]
15850 fn in_handshake_config() -> Result<()> {
15851 let mut buf = [0; 65535];
15852
15853 const CUSTOM_INITIAL_CONGESTION_WINDOW_PACKETS: usize = 30;
15854
15855 let mut server_tls_ctx_builder =
15857 boring::ssl::SslContextBuilder::new(boring::ssl::SslMethod::tls())
15858 .unwrap();
15859 server_tls_ctx_builder
15860 .set_certificate_chain_file("examples/cert.crt")
15861 .unwrap();
15862 server_tls_ctx_builder
15863 .set_private_key_file(
15864 "examples/cert.key",
15865 boring::ssl::SslFiletype::PEM,
15866 )
15867 .unwrap();
15868 server_tls_ctx_builder.set_select_certificate_callback(|mut hello| {
15869 Connection::set_initial_congestion_window_packets_in_handshake(
15870 hello.ssl_mut(),
15871 CUSTOM_INITIAL_CONGESTION_WINDOW_PACKETS,
15872 )
15873 .unwrap();
15874
15875 Ok(())
15876 });
15877
15878 let mut server_config = Config::with_boring_ssl_ctx_builder(
15879 crate::PROTOCOL_VERSION,
15880 server_tls_ctx_builder,
15881 )?;
15882
15883 let mut client_config = Config::new(crate::PROTOCOL_VERSION)?;
15884 client_config.load_cert_chain_from_pem_file("examples/cert.crt")?;
15885 client_config.load_priv_key_from_pem_file("examples/cert.key")?;
15886
15887 for config in [&mut client_config, &mut server_config] {
15888 config.set_application_protos(&[b"proto1", b"proto2"])?;
15889 config.set_initial_max_data(1000000);
15890 config.set_initial_max_stream_data_bidi_local(15);
15891 config.set_initial_max_stream_data_bidi_remote(15);
15892 config.set_initial_max_stream_data_uni(10);
15893 config.set_initial_max_streams_bidi(3);
15894 config.set_initial_max_streams_uni(3);
15895 config.set_max_idle_timeout(180_000);
15896 config.verify_peer(false);
15897 config.set_ack_delay_exponent(8);
15898 }
15899
15900 let mut pipe = testing::Pipe::with_client_and_server_config(
15901 &mut client_config,
15902 &mut server_config,
15903 )?;
15904
15905 let (len, _) = pipe.client.send(&mut buf).unwrap();
15907
15908 assert_eq!(pipe.server.tx_cap, 0);
15909
15910 pipe.server_recv(&mut buf[..len]).unwrap();
15912
15913 assert_eq!(
15914 pipe.server.tx_cap,
15915 CUSTOM_INITIAL_CONGESTION_WINDOW_PACKETS * 1200
15916 );
15917
15918 let (len, _) = pipe.server.send(&mut buf).unwrap();
15920 pipe.client_recv(&mut buf[..len]).unwrap();
15921
15922 assert_eq!(pipe.handshake(), Ok(()));
15923
15924 Ok(())
15925 }
15926
15927 #[test]
15928 fn last_tx_data_larger_than_tx_data() {
15930 let mut config = Config::new(PROTOCOL_VERSION).unwrap();
15931 config
15932 .set_application_protos(&[b"proto1", b"proto2"])
15933 .unwrap();
15934 config.set_initial_max_data(12000);
15935 config.set_initial_max_stream_data_bidi_local(20000);
15936 config.set_initial_max_stream_data_bidi_remote(20000);
15937 config.set_max_recv_udp_payload_size(1200);
15938 config.verify_peer(false);
15939
15940 let mut pipe = testing::Pipe::with_client_config(&mut config).unwrap();
15941 assert_eq!(pipe.handshake(), Ok(()));
15942
15943 assert_eq!(pipe.client.stream_send(4, b"a", true), Ok(1));
15945 assert_eq!(pipe.client.stream_send(8, b"b", true), Ok(1));
15946 assert_eq!(pipe.advance(), Ok(()));
15947
15948 let mut b = [0; 15];
15950 pipe.server.stream_recv(4, &mut b).unwrap();
15951
15952 let buf = [0; 10000];
15954 assert_eq!(pipe.server.stream_send(4, &buf, false), Ok(10000));
15955
15956 testing::emit_flight(&mut pipe.server).unwrap();
15957
15958 let mut buf = [0; 1200];
15960 assert_eq!(pipe.server.stream_send(4, &buf, false), Ok(1200));
15961 assert_eq!(pipe.server.stream_send(8, &buf, false), Ok(800));
15962 assert_eq!(pipe.server.stream_send(4, &buf, false), Err(Error::Done));
15963
15964 let timer = pipe.server.timeout().unwrap();
15966 std::thread::sleep(timer + time::Duration::from_millis(1));
15967
15968 pipe.server.on_timeout();
15969
15970 let (len, _) = pipe.server.send(&mut buf).unwrap();
15973 assert_eq!(len, 1200);
15974
15975 let frames = [frame::Frame::StopSending {
15979 stream_id: 4,
15980 error_code: 42,
15981 }];
15982
15983 let pkt_type = packet::Type::Short;
15984 pipe.send_pkt_to_server(pkt_type, &frames, &mut buf)
15985 .unwrap();
15986 }
15987
15988 #[test]
15991 fn send_connection_ids() {
15992 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
15993 config
15994 .load_cert_chain_from_pem_file("examples/cert.crt")
15995 .unwrap();
15996 config
15997 .load_priv_key_from_pem_file("examples/cert.key")
15998 .unwrap();
15999 config
16000 .set_application_protos(&[b"proto1", b"proto2"])
16001 .unwrap();
16002 config.verify_peer(false);
16003 config.set_active_connection_id_limit(3);
16004
16005 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
16006 assert_eq!(pipe.handshake(), Ok(()));
16007
16008 assert_eq!(pipe.client.path_event_next(), None);
16010 assert_eq!(pipe.server.path_event_next(), None);
16011 assert_eq!(pipe.client.scids_left(), 2);
16012
16013 let (scid, reset_token) = testing::create_cid_and_reset_token(16);
16014 assert_eq!(pipe.client.new_scid(&scid, reset_token, false), Ok(1));
16015
16016 assert_eq!(pipe.advance(), Ok(()));
16018
16019 assert_eq!(pipe.server.available_dcids(), 1);
16021 assert_eq!(pipe.server.path_event_next(), None);
16022 assert_eq!(pipe.client.path_event_next(), None);
16023 assert_eq!(pipe.client.scids_left(), 1);
16024
16025 let (scid, reset_token) = testing::create_cid_and_reset_token(16);
16027 assert_eq!(pipe.client.new_scid(&scid, reset_token, false), Ok(2));
16028
16029 assert_eq!(pipe.advance(), Ok(()));
16031
16032 assert_eq!(pipe.server.available_dcids(), 2);
16034 assert_eq!(pipe.server.path_event_next(), None);
16035 assert_eq!(pipe.client.path_event_next(), None);
16036 assert_eq!(pipe.client.scids_left(), 0);
16037
16038 let (scid, reset_token) = testing::create_cid_and_reset_token(16);
16041 assert_eq!(
16042 pipe.client.new_scid(&scid, reset_token, false),
16043 Err(Error::IdLimit),
16044 );
16045 }
16046
16047 #[test]
16048 fn connection_id_zero() {
16050 let mut buf = [0; 65535];
16051
16052 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16053 config
16054 .load_cert_chain_from_pem_file("examples/cert.crt")
16055 .unwrap();
16056 config
16057 .load_priv_key_from_pem_file("examples/cert.key")
16058 .unwrap();
16059 config
16060 .set_application_protos(&[b"proto1", b"proto2"])
16061 .unwrap();
16062 config.verify_peer(false);
16063 config.set_active_connection_id_limit(2);
16064
16065 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
16066 assert_eq!(pipe.handshake(), Ok(()));
16067
16068 let mut frames = Vec::new();
16069
16070 let (scid, reset_token) = testing::create_cid_and_reset_token(0);
16072
16073 frames.push(frame::Frame::NewConnectionId {
16074 seq_num: 1,
16075 retire_prior_to: 0,
16076 conn_id: scid.to_vec(),
16077 reset_token: reset_token.to_be_bytes(),
16078 });
16079
16080 let pkt_type = packet::Type::Short;
16081
16082 let written =
16083 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
16084 .unwrap();
16085
16086 let active_path = pipe.server.paths.get_active().unwrap();
16087 let info = RecvInfo {
16088 to: active_path.local_addr(),
16089 from: active_path.peer_addr(),
16090 };
16091
16092 assert_eq!(
16093 pipe.server.recv(&mut buf[..written], info),
16094 Err(Error::InvalidFrame)
16095 );
16096
16097 let written = match pipe.server.send(&mut buf) {
16098 Ok((write, _)) => write,
16099
16100 Err(_) => unreachable!(),
16101 };
16102
16103 let frames =
16104 testing::decode_pkt(&mut pipe.client, &mut buf[..written]).unwrap();
16105 let mut iter = frames.iter();
16106
16107 assert_eq!(
16108 iter.next(),
16109 Some(&frame::Frame::ConnectionClose {
16110 error_code: 0x7,
16111 frame_type: 0,
16112 reason: Vec::new(),
16113 })
16114 );
16115 }
16116
16117 #[test]
16118 fn connection_id_invalid_max_len() {
16120 let mut buf = [0; 65535];
16121
16122 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16123 config
16124 .load_cert_chain_from_pem_file("examples/cert.crt")
16125 .unwrap();
16126 config
16127 .load_priv_key_from_pem_file("examples/cert.key")
16128 .unwrap();
16129 config
16130 .set_application_protos(&[b"proto1", b"proto2"])
16131 .unwrap();
16132 config.verify_peer(false);
16133 config.set_active_connection_id_limit(2);
16134
16135 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
16136 assert_eq!(pipe.handshake(), Ok(()));
16137
16138 let mut frames = Vec::new();
16139
16140 let (scid, reset_token) =
16142 testing::create_cid_and_reset_token(MAX_CONN_ID_LEN + 1);
16143
16144 frames.push(frame::Frame::NewConnectionId {
16145 seq_num: 1,
16146 retire_prior_to: 0,
16147 conn_id: scid.to_vec(),
16148 reset_token: reset_token.to_be_bytes(),
16149 });
16150
16151 let pkt_type = packet::Type::Short;
16152
16153 let written =
16154 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
16155 .unwrap();
16156
16157 let active_path = pipe.server.paths.get_active().unwrap();
16158 let info = RecvInfo {
16159 to: active_path.local_addr(),
16160 from: active_path.peer_addr(),
16161 };
16162
16163 assert_eq!(
16164 pipe.server.recv(&mut buf[..written], info),
16165 Err(Error::InvalidFrame)
16166 );
16167
16168 let written = match pipe.server.send(&mut buf) {
16169 Ok((write, _)) => write,
16170
16171 Err(_) => unreachable!(),
16172 };
16173
16174 let frames =
16175 testing::decode_pkt(&mut pipe.client, &mut buf[..written]).unwrap();
16176 let mut iter = frames.iter();
16177
16178 assert_eq!(
16179 iter.next(),
16180 Some(&frame::Frame::ConnectionClose {
16181 error_code: 0x7,
16182 frame_type: 0,
16183 reason: Vec::new(),
16184 })
16185 );
16186 }
16187
16188 #[test]
16189 fn connection_id_handling() {
16192 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16193 config
16194 .load_cert_chain_from_pem_file("examples/cert.crt")
16195 .unwrap();
16196 config
16197 .load_priv_key_from_pem_file("examples/cert.key")
16198 .unwrap();
16199 config
16200 .set_application_protos(&[b"proto1", b"proto2"])
16201 .unwrap();
16202 config.verify_peer(false);
16203 config.set_active_connection_id_limit(2);
16204
16205 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
16206 assert_eq!(pipe.handshake(), Ok(()));
16207
16208 assert_eq!(pipe.client.path_event_next(), None);
16210 assert_eq!(pipe.server.path_event_next(), None);
16211 assert_eq!(pipe.client.scids_left(), 1);
16212
16213 let scid = pipe.client.source_id().into_owned();
16214
16215 let (scid_1, reset_token_1) = testing::create_cid_and_reset_token(16);
16216 assert_eq!(pipe.client.new_scid(&scid_1, reset_token_1, false), Ok(1));
16217
16218 assert_eq!(pipe.advance(), Ok(()));
16220
16221 assert_eq!(pipe.server.available_dcids(), 1);
16223 assert_eq!(pipe.server.path_event_next(), None);
16224 assert_eq!(pipe.client.path_event_next(), None);
16225 assert_eq!(pipe.client.scids_left(), 0);
16226
16227 let (scid_2, reset_token_2) = testing::create_cid_and_reset_token(16);
16233 assert_eq!(pipe.client.new_scid(&scid_2, reset_token_2, true), Ok(2));
16234
16235 assert_eq!(pipe.advance(), Ok(()));
16237
16238 assert_eq!(pipe.server.available_dcids(), 1);
16240 assert_eq!(pipe.server.path_event_next(), None);
16241
16242 assert_eq!(pipe.client.retired_scid_next(), Some(scid));
16244 assert_eq!(pipe.client.retired_scid_next(), None);
16245
16246 assert_eq!(pipe.client.path_event_next(), None);
16247 assert_eq!(pipe.client.scids_left(), 0);
16248
16249 assert_eq!(pipe.server.destination_id(), scid_1);
16252
16253 assert_eq!(pipe.server.retire_dcid(0), Err(Error::InvalidState));
16256 assert_eq!(pipe.server.retire_dcid(3), Err(Error::InvalidState));
16257
16258 assert_eq!(pipe.server.retire_dcid(1), Ok(()));
16260
16261 assert_eq!(pipe.advance(), Ok(()));
16263
16264 assert_eq!(pipe.server.path_event_next(), None);
16265 assert_eq!(pipe.client.retired_scid_next(), Some(scid_1));
16266 assert_eq!(pipe.client.retired_scid_next(), None);
16267
16268 assert_eq!(pipe.server.destination_id(), scid_2);
16269 assert_eq!(pipe.server.available_dcids(), 0);
16270
16271 assert_eq!(pipe.server.retire_dcid(2), Err(Error::OutOfIdentifiers));
16273 }
16274
16275 #[test]
16276 fn lost_connection_id_frames() {
16277 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16278 config
16279 .load_cert_chain_from_pem_file("examples/cert.crt")
16280 .unwrap();
16281 config
16282 .load_priv_key_from_pem_file("examples/cert.key")
16283 .unwrap();
16284 config
16285 .set_application_protos(&[b"proto1", b"proto2"])
16286 .unwrap();
16287 config.verify_peer(false);
16288 config.set_active_connection_id_limit(2);
16289
16290 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
16291 assert_eq!(pipe.handshake(), Ok(()));
16292
16293 let scid = pipe.client.source_id().into_owned();
16294
16295 let (scid_1, reset_token_1) = testing::create_cid_and_reset_token(16);
16296 assert_eq!(pipe.client.new_scid(&scid_1, reset_token_1, false), Ok(1));
16297
16298 testing::emit_flight(&mut pipe.client).unwrap();
16300
16301 let timer = pipe.client.timeout().unwrap();
16303 std::thread::sleep(timer + time::Duration::from_millis(1));
16304
16305 pipe.client.on_timeout();
16306
16307 assert_eq!(pipe.advance(), Ok(()));
16309
16310 assert_eq!(pipe.server.available_dcids(), 1);
16312
16313 assert_eq!(pipe.server.retire_dcid(0), Ok(()));
16315
16316 testing::emit_flight(&mut pipe.server).unwrap();
16318
16319 let timer = pipe.server.timeout().unwrap();
16321 std::thread::sleep(timer + time::Duration::from_millis(1));
16322
16323 pipe.server.on_timeout();
16324
16325 assert_eq!(pipe.advance(), Ok(()));
16327
16328 assert_eq!(pipe.client.retired_scid_next(), Some(scid));
16329 assert_eq!(pipe.client.retired_scid_next(), None);
16330 }
16331
16332 #[test]
16333 fn sending_duplicate_scids() {
16334 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16335 config
16336 .load_cert_chain_from_pem_file("examples/cert.crt")
16337 .unwrap();
16338 config
16339 .load_priv_key_from_pem_file("examples/cert.key")
16340 .unwrap();
16341 config
16342 .set_application_protos(&[b"proto1", b"proto2"])
16343 .unwrap();
16344 config.verify_peer(false);
16345 config.set_active_connection_id_limit(3);
16346
16347 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
16348 assert_eq!(pipe.handshake(), Ok(()));
16349
16350 let (scid_1, reset_token_1) = testing::create_cid_and_reset_token(16);
16351 assert_eq!(pipe.client.new_scid(&scid_1, reset_token_1, false), Ok(1));
16352 assert_eq!(pipe.advance(), Ok(()));
16353
16354 let reset_token_2 = reset_token_1.wrapping_add(1);
16357 assert_eq!(
16358 pipe.client.new_scid(&scid_1, reset_token_2, false),
16359 Err(Error::InvalidState),
16360 );
16361
16362 assert_eq!(pipe.client.new_scid(&scid_1, reset_token_1, false), Ok(1));
16365 assert!(!pipe.client.ids.has_new_scids());
16366
16367 assert_eq!(pipe.server.retire_dcid(1), Ok(()));
16369 assert_eq!(pipe.advance(), Ok(()));
16370
16371 assert_eq!(pipe.client.new_scid(&scid_1, reset_token_1, false), Ok(2));
16374 }
16375
16376 #[test]
16377 fn connection_id_retire_limit() {
16379 let mut buf = [0; 65535];
16380
16381 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16382 config
16383 .load_cert_chain_from_pem_file("examples/cert.crt")
16384 .unwrap();
16385 config
16386 .load_priv_key_from_pem_file("examples/cert.key")
16387 .unwrap();
16388 config
16389 .set_application_protos(&[b"proto1", b"proto2"])
16390 .unwrap();
16391 config.verify_peer(false);
16392 config.set_active_connection_id_limit(2);
16393
16394 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
16395 assert_eq!(pipe.handshake(), Ok(()));
16396
16397 assert_eq!(pipe.client.path_event_next(), None);
16399 assert_eq!(pipe.server.path_event_next(), None);
16400 assert_eq!(pipe.client.scids_left(), 1);
16401
16402 let (scid_1, reset_token_1) = testing::create_cid_and_reset_token(16);
16403 assert_eq!(pipe.client.new_scid(&scid_1, reset_token_1, false), Ok(1));
16404
16405 assert_eq!(pipe.advance(), Ok(()));
16407
16408 assert_eq!(pipe.server.available_dcids(), 1);
16410 assert_eq!(pipe.server.path_event_next(), None);
16411 assert_eq!(pipe.client.path_event_next(), None);
16412 assert_eq!(pipe.client.scids_left(), 0);
16413
16414 let mut frames = Vec::new();
16415
16416 for i in 2..=7 {
16418 let (scid, reset_token) = testing::create_cid_and_reset_token(16);
16419
16420 frames.push(frame::Frame::NewConnectionId {
16421 seq_num: i,
16422 retire_prior_to: i,
16423 conn_id: scid.to_vec(),
16424 reset_token: reset_token.to_be_bytes(),
16425 });
16426 }
16427
16428 let pkt_type = packet::Type::Short;
16429
16430 let written =
16431 testing::encode_pkt(&mut pipe.client, pkt_type, &frames, &mut buf)
16432 .unwrap();
16433
16434 let active_path = pipe.server.paths.get_active().unwrap();
16435 let info = RecvInfo {
16436 to: active_path.local_addr(),
16437 from: active_path.peer_addr(),
16438 };
16439
16440 assert_eq!(
16441 pipe.server.recv(&mut buf[..written], info),
16442 Err(Error::IdLimit)
16443 );
16444
16445 let written = match pipe.server.send(&mut buf) {
16446 Ok((write, _)) => write,
16447
16448 Err(_) => unreachable!(),
16449 };
16450
16451 let frames =
16452 testing::decode_pkt(&mut pipe.client, &mut buf[..written]).unwrap();
16453 let mut iter = frames.iter();
16454
16455 assert_eq!(
16456 iter.next(),
16457 Some(&frame::Frame::ConnectionClose {
16458 error_code: 0x9,
16459 frame_type: 0,
16460 reason: Vec::new(),
16461 })
16462 );
16463 }
16464
16465 fn pipe_with_exchanged_cids(
16467 config: &mut Config, client_scid_len: usize, server_scid_len: usize,
16468 additional_cids: usize,
16469 ) -> testing::Pipe {
16470 let mut pipe = testing::Pipe::with_config_and_scid_lengths(
16471 config,
16472 client_scid_len,
16473 server_scid_len,
16474 )
16475 .unwrap();
16476 assert_eq!(pipe.handshake(), Ok(()));
16477
16478 let mut c_cids = Vec::new();
16479 let mut c_reset_tokens = Vec::new();
16480 let mut s_cids = Vec::new();
16481 let mut s_reset_tokens = Vec::new();
16482
16483 for i in 0..additional_cids {
16484 if client_scid_len > 0 {
16485 let (c_cid, c_reset_token) =
16486 testing::create_cid_and_reset_token(client_scid_len);
16487 c_cids.push(c_cid);
16488 c_reset_tokens.push(c_reset_token);
16489
16490 assert_eq!(
16491 pipe.client.new_scid(&c_cids[i], c_reset_tokens[i], true),
16492 Ok(i as u64 + 1)
16493 );
16494 }
16495
16496 if server_scid_len > 0 {
16497 let (s_cid, s_reset_token) =
16498 testing::create_cid_and_reset_token(server_scid_len);
16499 s_cids.push(s_cid);
16500 s_reset_tokens.push(s_reset_token);
16501 assert_eq!(
16502 pipe.server.new_scid(&s_cids[i], s_reset_tokens[i], true),
16503 Ok(i as u64 + 1)
16504 );
16505 }
16506 }
16507
16508 assert_eq!(pipe.advance(), Ok(()));
16510
16511 if client_scid_len > 0 {
16512 assert_eq!(pipe.server.available_dcids(), additional_cids);
16513 }
16514
16515 if server_scid_len > 0 {
16516 assert_eq!(pipe.client.available_dcids(), additional_cids);
16517 }
16518
16519 assert_eq!(pipe.server.path_event_next(), None);
16520 assert_eq!(pipe.client.path_event_next(), None);
16521
16522 pipe
16523 }
16524
16525 #[test]
16526 fn path_validation() {
16527 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16528 config
16529 .load_cert_chain_from_pem_file("examples/cert.crt")
16530 .unwrap();
16531 config
16532 .load_priv_key_from_pem_file("examples/cert.key")
16533 .unwrap();
16534 config
16535 .set_application_protos(&[b"proto1", b"proto2"])
16536 .unwrap();
16537 config.verify_peer(false);
16538 config.set_active_connection_id_limit(2);
16539
16540 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
16541 assert_eq!(pipe.handshake(), Ok(()));
16542
16543 let server_addr = testing::Pipe::server_addr();
16544 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
16545
16546 assert_eq!(
16548 pipe.client.probe_path(client_addr_2, server_addr),
16549 Err(Error::OutOfIdentifiers)
16550 );
16551
16552 let (c_cid, c_reset_token) = testing::create_cid_and_reset_token(16);
16553
16554 assert_eq!(pipe.client.new_scid(&c_cid, c_reset_token, true), Ok(1));
16555
16556 let (s_cid, s_reset_token) = testing::create_cid_and_reset_token(16);
16557 assert_eq!(pipe.server.new_scid(&s_cid, s_reset_token, true), Ok(1));
16558
16559 assert_eq!(
16561 pipe.client.probe_path(client_addr_2, server_addr),
16562 Err(Error::OutOfIdentifiers)
16563 );
16564
16565 assert_eq!(pipe.advance(), Ok(()));
16567
16568 assert_eq!(pipe.server.available_dcids(), 1);
16569 assert_eq!(pipe.server.path_event_next(), None);
16570 assert_eq!(pipe.client.available_dcids(), 1);
16571 assert_eq!(pipe.client.path_event_next(), None);
16572
16573 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
16575
16576 assert_eq!(
16578 pipe.server.probe_path(server_addr, client_addr_2),
16579 Err(Error::InvalidState),
16580 );
16581
16582 assert_eq!(pipe.advance(), Ok(()));
16583
16584 assert_eq!(
16586 pipe.client.path_event_next(),
16587 Some(PathEvent::Validated(client_addr_2, server_addr)),
16588 );
16589 assert_eq!(pipe.client.path_event_next(), None);
16590
16591 assert_eq!(
16593 pipe.server.path_event_next(),
16594 Some(PathEvent::New(server_addr, client_addr_2)),
16595 );
16596 assert_eq!(
16597 pipe.server.path_event_next(),
16598 Some(PathEvent::Validated(server_addr, client_addr_2)),
16599 );
16600 assert_eq!(pipe.server.path_event_next(), None);
16601
16602 assert_eq!(pipe.server.probe_path(server_addr, client_addr_2), Ok(1));
16604
16605 assert_eq!(pipe.client.path_event_next(), None);
16607 assert_eq!(pipe.server.path_event_next(), None);
16608 }
16609
16610 #[test]
16611 fn losing_probing_packets() {
16612 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16613 config
16614 .load_cert_chain_from_pem_file("examples/cert.crt")
16615 .unwrap();
16616 config
16617 .load_priv_key_from_pem_file("examples/cert.key")
16618 .unwrap();
16619 config
16620 .set_application_protos(&[b"proto1", b"proto2"])
16621 .unwrap();
16622 config.verify_peer(false);
16623 config.set_active_connection_id_limit(2);
16624
16625 let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
16626
16627 let server_addr = testing::Pipe::server_addr();
16628 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
16629 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
16630
16631 testing::emit_flight(&mut pipe.client).unwrap();
16633
16634 let probed_pid = pipe
16637 .client
16638 .paths
16639 .path_id_from_addrs(&(client_addr_2, server_addr))
16640 .unwrap();
16641 let probe_instant = pipe
16642 .client
16643 .paths
16644 .get(probed_pid)
16645 .unwrap()
16646 .recovery
16647 .loss_detection_timer()
16648 .unwrap();
16649 let timer = probe_instant.duration_since(time::Instant::now());
16650 std::thread::sleep(timer + time::Duration::from_millis(1));
16651
16652 pipe.client.on_timeout();
16653
16654 assert_eq!(pipe.advance(), Ok(()));
16655
16656 assert_eq!(
16658 pipe.client.path_event_next(),
16659 Some(PathEvent::Validated(client_addr_2, server_addr))
16660 );
16661 assert_eq!(pipe.client.path_event_next(), None);
16662
16663 assert_eq!(
16664 pipe.server.path_event_next(),
16665 Some(PathEvent::New(server_addr, client_addr_2))
16666 );
16667 assert_eq!(
16669 pipe.server.path_event_next(),
16670 Some(PathEvent::Validated(server_addr, client_addr_2))
16671 );
16672 assert_eq!(pipe.server.path_event_next(), None);
16673 }
16674
16675 #[test]
16676 fn failed_path_validation() {
16677 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16678 config
16679 .load_cert_chain_from_pem_file("examples/cert.crt")
16680 .unwrap();
16681 config
16682 .load_priv_key_from_pem_file("examples/cert.key")
16683 .unwrap();
16684 config
16685 .set_application_protos(&[b"proto1", b"proto2"])
16686 .unwrap();
16687 config.verify_peer(false);
16688 config.set_active_connection_id_limit(2);
16689
16690 let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
16691
16692 let server_addr = testing::Pipe::server_addr();
16693 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
16694 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
16695
16696 for _ in 0..MAX_PROBING_TIMEOUTS {
16697 testing::emit_flight(&mut pipe.client).unwrap();
16699
16700 let probed_pid = pipe
16703 .client
16704 .paths
16705 .path_id_from_addrs(&(client_addr_2, server_addr))
16706 .unwrap();
16707 let probe_instant = pipe
16708 .client
16709 .paths
16710 .get(probed_pid)
16711 .unwrap()
16712 .recovery
16713 .loss_detection_timer()
16714 .unwrap();
16715 let timer = probe_instant.duration_since(time::Instant::now());
16716 std::thread::sleep(timer + time::Duration::from_millis(1));
16717
16718 pipe.client.on_timeout();
16719 }
16720
16721 assert_eq!(
16722 pipe.client.path_event_next(),
16723 Some(PathEvent::FailedValidation(client_addr_2, server_addr)),
16724 );
16725 }
16726
16727 #[test]
16728 fn client_discard_unknown_address() {
16729 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16730 config
16731 .load_cert_chain_from_pem_file("examples/cert.crt")
16732 .unwrap();
16733 config
16734 .load_priv_key_from_pem_file("examples/cert.key")
16735 .unwrap();
16736 config
16737 .set_application_protos(&[b"proto1", b"proto2"])
16738 .unwrap();
16739 config.verify_peer(false);
16740 config.set_initial_max_data(30);
16741 config.set_initial_max_stream_data_uni(10);
16742 config.set_initial_max_streams_uni(3);
16743
16744 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
16745 assert_eq!(pipe.handshake(), Ok(()));
16746
16747 assert_eq!(pipe.server.stream_send(3, b"a", true), Ok(1));
16749
16750 let mut flight =
16751 testing::emit_flight(&mut pipe.server).expect("no packet");
16752 flight
16754 .iter_mut()
16755 .for_each(|(_, si)| si.from = "127.0.0.1:9292".parse().unwrap());
16756 assert_eq!(testing::process_flight(&mut pipe.client, flight), Ok(()));
16757 assert_eq!(pipe.client.paths.len(), 1);
16758 }
16759
16760 #[test]
16761 fn path_validation_limited_mtu() {
16762 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16763 config
16764 .load_cert_chain_from_pem_file("examples/cert.crt")
16765 .unwrap();
16766 config
16767 .load_priv_key_from_pem_file("examples/cert.key")
16768 .unwrap();
16769 config
16770 .set_application_protos(&[b"proto1", b"proto2"])
16771 .unwrap();
16772 config.verify_peer(false);
16773 config.set_active_connection_id_limit(2);
16774
16775 let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
16776
16777 let server_addr = testing::Pipe::server_addr();
16778 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
16779 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
16780 testing::process_flight(
16782 &mut pipe.server,
16783 testing::emit_flight_with_max_buffer(
16784 &mut pipe.client,
16785 1199,
16786 None,
16787 None,
16788 )
16789 .expect("no packet"),
16790 )
16791 .expect("error when processing client packets");
16792 testing::process_flight(
16793 &mut pipe.client,
16794 testing::emit_flight(&mut pipe.server).expect("no packet"),
16795 )
16796 .expect("error when processing client packets");
16797 let probed_pid = pipe
16798 .client
16799 .paths
16800 .path_id_from_addrs(&(client_addr_2, server_addr))
16801 .unwrap();
16802 assert!(!pipe.client.paths.get(probed_pid).unwrap().validated(),);
16803 assert_eq!(pipe.client.path_event_next(), None);
16804 assert_eq!(pipe.advance(), Ok(()));
16806 assert!(pipe.client.paths.get(probed_pid).unwrap().validated());
16807 assert_eq!(
16808 pipe.client.path_event_next(),
16809 Some(PathEvent::Validated(client_addr_2, server_addr))
16810 );
16811 }
16812
16813 #[test]
16814 fn path_probing_dos() {
16815 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16816 config
16817 .load_cert_chain_from_pem_file("examples/cert.crt")
16818 .unwrap();
16819 config
16820 .load_priv_key_from_pem_file("examples/cert.key")
16821 .unwrap();
16822 config
16823 .set_application_protos(&[b"proto1", b"proto2"])
16824 .unwrap();
16825 config.verify_peer(false);
16826 config.set_active_connection_id_limit(2);
16827
16828 let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
16829
16830 let server_addr = testing::Pipe::server_addr();
16831 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
16832 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
16833
16834 assert_eq!(pipe.advance(), Ok(()));
16835
16836 assert_eq!(
16838 pipe.client.path_event_next(),
16839 Some(PathEvent::Validated(client_addr_2, server_addr))
16840 );
16841 assert_eq!(pipe.client.path_event_next(), None);
16842
16843 assert_eq!(
16845 pipe.server.path_event_next(),
16846 Some(PathEvent::New(server_addr, client_addr_2))
16847 );
16848 assert_eq!(
16849 pipe.server.path_event_next(),
16850 Some(PathEvent::Validated(server_addr, client_addr_2))
16851 );
16852 assert_eq!(pipe.server.path_event_next(), None);
16853
16854 assert_eq!(pipe.server.paths.len(), 2);
16855
16856 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
16859 let client_addr_3 = "127.0.0.1:9012".parse().unwrap();
16860 let mut flight =
16861 testing::emit_flight(&mut pipe.client).expect("no generated packet");
16862 flight
16863 .iter_mut()
16864 .for_each(|(_, si)| si.from = client_addr_3);
16865 testing::process_flight(&mut pipe.server, flight)
16866 .expect("failed to process");
16867 assert_eq!(pipe.server.paths.len(), 2);
16868 assert_eq!(
16869 pipe.server.path_event_next(),
16870 Some(PathEvent::ReusedSourceConnectionId(
16871 1,
16872 (server_addr, client_addr_2),
16873 (server_addr, client_addr_3)
16874 ))
16875 );
16876 assert_eq!(pipe.server.path_event_next(), None);
16877 }
16878
16879 #[test]
16880 fn retiring_active_path_dcid() {
16881 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16882 config
16883 .load_cert_chain_from_pem_file("examples/cert.crt")
16884 .unwrap();
16885 config
16886 .load_priv_key_from_pem_file("examples/cert.key")
16887 .unwrap();
16888 config
16889 .set_application_protos(&[b"proto1", b"proto2"])
16890 .unwrap();
16891 config.verify_peer(false);
16892 config.set_active_connection_id_limit(2);
16893
16894 let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
16895 let server_addr = testing::Pipe::server_addr();
16896 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
16897 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
16898
16899 assert_eq!(pipe.client.retire_dcid(0), Err(Error::OutOfIdentifiers));
16900 }
16901
16902 #[test]
16903 fn send_on_path_test() {
16904 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
16905 config
16906 .load_cert_chain_from_pem_file("examples/cert.crt")
16907 .unwrap();
16908 config
16909 .load_priv_key_from_pem_file("examples/cert.key")
16910 .unwrap();
16911 config
16912 .set_application_protos(&[b"proto1", b"proto2"])
16913 .unwrap();
16914 config.verify_peer(false);
16915 config.set_initial_max_data(100000);
16916 config.set_initial_max_stream_data_bidi_local(100000);
16917 config.set_initial_max_stream_data_bidi_remote(100000);
16918 config.set_initial_max_streams_bidi(2);
16919 config.set_active_connection_id_limit(4);
16920
16921 let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 3);
16922
16923 let server_addr = testing::Pipe::server_addr();
16924 let client_addr = testing::Pipe::client_addr();
16925 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
16926 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
16927
16928 let mut buf = [0; 65535];
16929 assert_eq!(
16931 pipe.client.send_on_path(
16932 &mut buf,
16933 Some(client_addr),
16934 Some(server_addr)
16935 ),
16936 Err(Error::Done)
16937 );
16938
16939 let (sent, si) = pipe
16941 .client
16942 .send_on_path(&mut buf, Some(client_addr_2), Some(server_addr))
16943 .expect("No error");
16944 assert_eq!(sent, MIN_CLIENT_INITIAL_LEN);
16945 assert_eq!(si.from, client_addr_2);
16946 assert_eq!(si.to, server_addr);
16947
16948 let ri = RecvInfo {
16949 to: si.to,
16950 from: si.from,
16951 };
16952 assert_eq!(pipe.server.recv(&mut buf[..sent], ri), Ok(sent));
16953
16954 let stats = pipe.server.stats();
16955 assert_eq!(stats.path_challenge_rx_count, 1);
16956
16957 let client_addr_3 = "127.0.0.1:9012".parse().unwrap();
16959 let server_addr_2 = "127.0.0.1:9876".parse().unwrap();
16960 assert_eq!(
16961 pipe.client.send_on_path(
16962 &mut buf,
16963 Some(client_addr_3),
16964 Some(server_addr)
16965 ),
16966 Err(Error::InvalidState)
16967 );
16968 assert_eq!(
16969 pipe.client.send_on_path(
16970 &mut buf,
16971 Some(client_addr),
16972 Some(server_addr_2)
16973 ),
16974 Err(Error::InvalidState)
16975 );
16976
16977 assert_eq!(pipe.client.probe_path(client_addr, server_addr_2), Ok(2));
16979 assert_eq!(pipe.client.probe_path(client_addr_3, server_addr), Ok(3));
16980 assert_eq!(pipe.client.stream_send(0, &buf[..1201], true), Ok(1201));
16982
16983 let (sent, si) = pipe
16985 .client
16986 .send_on_path(&mut buf, Some(client_addr), None)
16987 .expect("No error");
16988 assert_eq!(sent, MIN_CLIENT_INITIAL_LEN);
16989 assert_eq!(si.from, client_addr);
16990 assert_eq!(si.to, server_addr_2);
16991
16992 let ri = RecvInfo {
16993 to: si.to,
16994 from: si.from,
16995 };
16996 assert_eq!(pipe.server.recv(&mut buf[..sent], ri), Ok(sent));
16997
16998 let stats = pipe.server.stats();
16999 assert_eq!(stats.path_challenge_rx_count, 2);
17000
17001 let (sent, si) = pipe
17003 .client
17004 .send_on_path(&mut buf, Some(client_addr), None)
17005 .expect("No error");
17006 assert_eq!(si.from, client_addr);
17007 assert_eq!(si.to, server_addr);
17008
17009 let ri = RecvInfo {
17010 to: si.to,
17011 from: si.from,
17012 };
17013 assert_eq!(pipe.server.recv(&mut buf[..sent], ri), Ok(sent));
17014
17015 let stats = pipe.server.stats();
17016 assert_eq!(stats.path_challenge_rx_count, 2);
17017
17018 let (sent, si) = pipe
17020 .client
17021 .send_on_path(&mut buf, None, Some(server_addr))
17022 .expect("No error");
17023 assert_eq!(sent, MIN_CLIENT_INITIAL_LEN);
17024 assert_eq!(si.from, client_addr_3);
17025 assert_eq!(si.to, server_addr);
17026
17027 let ri = RecvInfo {
17028 to: si.to,
17029 from: si.from,
17030 };
17031 assert_eq!(pipe.server.recv(&mut buf[..sent], ri), Ok(sent));
17032
17033 let stats = pipe.server.stats();
17034 assert_eq!(stats.path_challenge_rx_count, 3);
17035
17036 let (sent, si) = pipe
17038 .client
17039 .send_on_path(&mut buf, None, Some(server_addr))
17040 .expect("No error");
17041 assert_eq!(si.from, client_addr);
17042 assert_eq!(si.to, server_addr);
17043
17044 let ri = RecvInfo {
17045 to: si.to,
17046 from: si.from,
17047 };
17048 assert_eq!(pipe.server.recv(&mut buf[..sent], ri), Ok(sent));
17049
17050 assert_eq!(
17052 pipe.client.send_on_path(&mut buf, Some(client_addr), None),
17053 Err(Error::Done)
17054 );
17055 assert_eq!(
17056 pipe.client.send_on_path(&mut buf, None, Some(server_addr)),
17057 Err(Error::Done)
17058 );
17059
17060 assert_eq!(pipe.advance(), Ok(()));
17061
17062 let mut v1 = pipe.client.paths_iter(client_addr).collect::<Vec<_>>();
17063 let mut v2 = vec![server_addr, server_addr_2];
17064
17065 v1.sort();
17066 v2.sort();
17067
17068 assert_eq!(v1, v2);
17069
17070 let mut v1 = pipe.client.paths_iter(client_addr_2).collect::<Vec<_>>();
17071 let mut v2 = vec![server_addr];
17072
17073 v1.sort();
17074 v2.sort();
17075
17076 assert_eq!(v1, v2);
17077
17078 let mut v1 = pipe.client.paths_iter(client_addr_3).collect::<Vec<_>>();
17079 let mut v2 = vec![server_addr];
17080
17081 v1.sort();
17082 v2.sort();
17083
17084 assert_eq!(v1, v2);
17085
17086 let stats = pipe.server.stats();
17087 assert_eq!(stats.path_challenge_rx_count, 3);
17088 }
17089
17090 #[test]
17091 fn connection_migration() {
17092 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
17093 config
17094 .load_cert_chain_from_pem_file("examples/cert.crt")
17095 .unwrap();
17096 config
17097 .load_priv_key_from_pem_file("examples/cert.key")
17098 .unwrap();
17099 config
17100 .set_application_protos(&[b"proto1", b"proto2"])
17101 .unwrap();
17102 config.verify_peer(false);
17103 config.set_active_connection_id_limit(3);
17104 config.set_initial_max_data(30);
17105 config.set_initial_max_stream_data_bidi_local(15);
17106 config.set_initial_max_stream_data_bidi_remote(15);
17107 config.set_initial_max_stream_data_uni(10);
17108 config.set_initial_max_streams_bidi(3);
17109
17110 let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 2);
17111
17112 let server_addr = testing::Pipe::server_addr();
17113 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
17114 let client_addr_3 = "127.0.0.1:9012".parse().unwrap();
17115 let client_addr_4 = "127.0.0.1:8908".parse().unwrap();
17116
17117 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
17120 assert_eq!(pipe.advance(), Ok(()));
17121 assert_eq!(
17122 pipe.client.path_event_next(),
17123 Some(PathEvent::Validated(client_addr_2, server_addr))
17124 );
17125 assert_eq!(pipe.client.path_event_next(), None);
17126 assert_eq!(
17127 pipe.server.path_event_next(),
17128 Some(PathEvent::New(server_addr, client_addr_2))
17129 );
17130 assert_eq!(
17131 pipe.server.path_event_next(),
17132 Some(PathEvent::Validated(server_addr, client_addr_2))
17133 );
17134 assert_eq!(
17135 pipe.client.is_path_validated(client_addr_2, server_addr),
17136 Ok(true)
17137 );
17138 assert_eq!(
17139 pipe.server.is_path_validated(server_addr, client_addr_2),
17140 Ok(true)
17141 );
17142 assert_eq!(
17144 pipe.server.migrate(server_addr, client_addr_2),
17145 Err(Error::InvalidState)
17146 );
17147 assert_eq!(pipe.client.migrate(client_addr_2, server_addr), Ok(1));
17148 assert_eq!(pipe.client.stream_send(0, b"data", true), Ok(4));
17149 assert_eq!(pipe.advance(), Ok(()));
17150 assert_eq!(
17151 pipe.client
17152 .paths
17153 .get_active()
17154 .expect("no active")
17155 .local_addr(),
17156 client_addr_2
17157 );
17158 assert_eq!(
17159 pipe.client
17160 .paths
17161 .get_active()
17162 .expect("no active")
17163 .peer_addr(),
17164 server_addr
17165 );
17166 assert_eq!(
17167 pipe.server.path_event_next(),
17168 Some(PathEvent::PeerMigrated(server_addr, client_addr_2))
17169 );
17170 assert_eq!(pipe.server.path_event_next(), None);
17171 assert_eq!(
17172 pipe.server
17173 .paths
17174 .get_active()
17175 .expect("no active")
17176 .local_addr(),
17177 server_addr
17178 );
17179 assert_eq!(
17180 pipe.server
17181 .paths
17182 .get_active()
17183 .expect("no active")
17184 .peer_addr(),
17185 client_addr_2
17186 );
17187
17188 assert_eq!(pipe.client.migrate(client_addr_3, server_addr), Ok(2));
17191 assert_eq!(pipe.client.stream_send(4, b"data", true), Ok(4));
17192 assert_eq!(pipe.advance(), Ok(()));
17193 assert_eq!(
17194 pipe.client
17195 .paths
17196 .get_active()
17197 .expect("no active")
17198 .local_addr(),
17199 client_addr_3
17200 );
17201 assert_eq!(
17202 pipe.client
17203 .paths
17204 .get_active()
17205 .expect("no active")
17206 .peer_addr(),
17207 server_addr
17208 );
17209 assert_eq!(
17210 pipe.server.path_event_next(),
17211 Some(PathEvent::New(server_addr, client_addr_3))
17212 );
17213 assert_eq!(
17214 pipe.server.path_event_next(),
17215 Some(PathEvent::Validated(server_addr, client_addr_3))
17216 );
17217 assert_eq!(
17218 pipe.server.path_event_next(),
17219 Some(PathEvent::PeerMigrated(server_addr, client_addr_3))
17220 );
17221 assert_eq!(pipe.server.path_event_next(), None);
17222 assert_eq!(
17223 pipe.server
17224 .paths
17225 .get_active()
17226 .expect("no active")
17227 .local_addr(),
17228 server_addr
17229 );
17230 assert_eq!(
17231 pipe.server
17232 .paths
17233 .get_active()
17234 .expect("no active")
17235 .peer_addr(),
17236 client_addr_3
17237 );
17238
17239 assert_eq!(pipe.client.migrate(client_addr_3, server_addr), Ok(2));
17242 assert_eq!(pipe.client.stream_send(8, b"data", true), Ok(4));
17243 assert_eq!(pipe.advance(), Ok(()));
17244 assert_eq!(pipe.client.path_event_next(), None);
17245 assert_eq!(
17246 pipe.client
17247 .paths
17248 .get_active()
17249 .expect("no active")
17250 .local_addr(),
17251 client_addr_3
17252 );
17253 assert_eq!(
17254 pipe.client
17255 .paths
17256 .get_active()
17257 .expect("no active")
17258 .peer_addr(),
17259 server_addr
17260 );
17261 assert_eq!(pipe.server.path_event_next(), None);
17262 assert_eq!(
17263 pipe.server
17264 .paths
17265 .get_active()
17266 .expect("no active")
17267 .local_addr(),
17268 server_addr
17269 );
17270 assert_eq!(
17271 pipe.server
17272 .paths
17273 .get_active()
17274 .expect("no active")
17275 .peer_addr(),
17276 client_addr_3
17277 );
17278
17279 assert_eq!(
17282 pipe.client.migrate(client_addr_4, server_addr),
17283 Err(Error::OutOfIdentifiers)
17284 );
17285 assert_eq!(
17286 pipe.client
17287 .paths
17288 .get_active()
17289 .expect("no active")
17290 .local_addr(),
17291 client_addr_3
17292 );
17293 assert_eq!(
17294 pipe.client
17295 .paths
17296 .get_active()
17297 .expect("no active")
17298 .peer_addr(),
17299 server_addr
17300 );
17301 }
17302
17303 #[test]
17304 fn connection_migration_zero_length_cid() {
17305 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
17306 config
17307 .load_cert_chain_from_pem_file("examples/cert.crt")
17308 .unwrap();
17309 config
17310 .load_priv_key_from_pem_file("examples/cert.key")
17311 .unwrap();
17312 config
17313 .set_application_protos(&[b"proto1", b"proto2"])
17314 .unwrap();
17315 config.verify_peer(false);
17316 config.set_active_connection_id_limit(2);
17317 config.set_initial_max_data(30);
17318 config.set_initial_max_stream_data_bidi_local(15);
17319 config.set_initial_max_stream_data_bidi_remote(15);
17320 config.set_initial_max_stream_data_uni(10);
17321 config.set_initial_max_streams_bidi(3);
17322
17323 let mut pipe = pipe_with_exchanged_cids(&mut config, 0, 16, 1);
17324
17325 let server_addr = testing::Pipe::server_addr();
17326 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
17327
17328 assert_eq!(pipe.client.migrate(client_addr_2, server_addr), Ok(1));
17331 assert_eq!(pipe.client.stream_send(4, b"data", true), Ok(4));
17332 assert_eq!(pipe.advance(), Ok(()));
17333 assert_eq!(
17334 pipe.client
17335 .paths
17336 .get_active()
17337 .expect("no active")
17338 .local_addr(),
17339 client_addr_2
17340 );
17341 assert_eq!(
17342 pipe.client
17343 .paths
17344 .get_active()
17345 .expect("no active")
17346 .peer_addr(),
17347 server_addr
17348 );
17349 assert_eq!(
17350 pipe.server.path_event_next(),
17351 Some(PathEvent::New(server_addr, client_addr_2))
17352 );
17353 assert_eq!(
17354 pipe.server.path_event_next(),
17355 Some(PathEvent::Validated(server_addr, client_addr_2))
17356 );
17357 assert_eq!(
17358 pipe.server.path_event_next(),
17359 Some(PathEvent::PeerMigrated(server_addr, client_addr_2))
17360 );
17361 assert_eq!(pipe.server.path_event_next(), None);
17362 assert_eq!(
17363 pipe.server
17364 .paths
17365 .get_active()
17366 .expect("no active")
17367 .local_addr(),
17368 server_addr
17369 );
17370 assert_eq!(
17371 pipe.server
17372 .paths
17373 .get_active()
17374 .expect("no active")
17375 .peer_addr(),
17376 client_addr_2
17377 );
17378 }
17379
17380 #[test]
17381 fn connection_migration_reordered_non_probing() {
17382 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
17383 config
17384 .load_cert_chain_from_pem_file("examples/cert.crt")
17385 .unwrap();
17386 config
17387 .load_priv_key_from_pem_file("examples/cert.key")
17388 .unwrap();
17389 config
17390 .set_application_protos(&[b"proto1", b"proto2"])
17391 .unwrap();
17392 config.verify_peer(false);
17393 config.set_active_connection_id_limit(2);
17394 config.set_initial_max_data(30);
17395 config.set_initial_max_stream_data_bidi_local(15);
17396 config.set_initial_max_stream_data_bidi_remote(15);
17397 config.set_initial_max_stream_data_uni(10);
17398 config.set_initial_max_streams_bidi(3);
17399
17400 let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
17401
17402 let client_addr = testing::Pipe::client_addr();
17403 let server_addr = testing::Pipe::server_addr();
17404 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
17405
17406 assert_eq!(pipe.client.probe_path(client_addr_2, server_addr), Ok(1));
17407 assert_eq!(pipe.advance(), Ok(()));
17408 assert_eq!(
17409 pipe.client.path_event_next(),
17410 Some(PathEvent::Validated(client_addr_2, server_addr))
17411 );
17412 assert_eq!(pipe.client.path_event_next(), None);
17413 assert_eq!(
17414 pipe.server.path_event_next(),
17415 Some(PathEvent::New(server_addr, client_addr_2))
17416 );
17417 assert_eq!(
17418 pipe.server.path_event_next(),
17419 Some(PathEvent::Validated(server_addr, client_addr_2))
17420 );
17421 assert_eq!(pipe.server.path_event_next(), None);
17422
17423 assert_eq!(pipe.client.stream_send(0, b"data", true), Ok(4));
17425 let mut first = testing::emit_flight(&mut pipe.client).unwrap();
17426 first.iter_mut().for_each(|(_, si)| si.from = client_addr_2);
17427 assert_eq!(pipe.client.stream_send(4, b"data", true), Ok(4));
17429 let second = testing::emit_flight(&mut pipe.client).unwrap();
17430 assert_eq!(testing::process_flight(&mut pipe.server, second), Ok(()));
17432 assert_eq!(testing::process_flight(&mut pipe.server, first), Ok(()));
17433
17434 assert_eq!(pipe.server.path_event_next(), None);
17437 assert_eq!(
17438 pipe.server
17439 .paths
17440 .get_active()
17441 .expect("no active")
17442 .peer_addr(),
17443 client_addr
17444 );
17445 }
17446
17447 #[test]
17448 fn resilience_against_migration_attack() {
17449 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
17450 config
17451 .load_cert_chain_from_pem_file("examples/cert.crt")
17452 .unwrap();
17453 config
17454 .load_priv_key_from_pem_file("examples/cert.key")
17455 .unwrap();
17456 config
17457 .set_application_protos(&[b"proto1", b"proto2"])
17458 .unwrap();
17459 config.verify_peer(false);
17460 config.set_active_connection_id_limit(3);
17461 config.set_initial_max_data(100000);
17462 config.set_initial_max_stream_data_bidi_local(100000);
17463 config.set_initial_max_stream_data_bidi_remote(100000);
17464 config.set_initial_max_streams_bidi(2);
17465
17466 let mut pipe = pipe_with_exchanged_cids(&mut config, 16, 16, 1);
17467
17468 let client_addr = testing::Pipe::client_addr();
17469 let server_addr = testing::Pipe::server_addr();
17470 let spoofed_client_addr = "127.0.0.1:6666".parse().unwrap();
17471
17472 const DATA_BYTES: usize = 24000;
17473 let buf = [42; DATA_BYTES];
17474 let mut recv_buf = [0; DATA_BYTES];
17475 assert_eq!(pipe.server.stream_send(1, &buf, true), Ok(12000));
17476 assert_eq!(
17477 testing::process_flight(
17478 &mut pipe.client,
17479 testing::emit_flight(&mut pipe.server).unwrap()
17480 ),
17481 Ok(())
17482 );
17483 let (rcv_data_1, _) = pipe.client.stream_recv(1, &mut recv_buf).unwrap();
17484
17485 let mut faked_addr_flight =
17487 testing::emit_flight(&mut pipe.client).unwrap();
17488 faked_addr_flight
17489 .iter_mut()
17490 .for_each(|(_, si)| si.from = spoofed_client_addr);
17491 assert_eq!(
17492 testing::process_flight(&mut pipe.server, faked_addr_flight),
17493 Ok(())
17494 );
17495 assert_eq!(pipe.server.stream_send(1, &buf[12000..], true), Ok(12000));
17496 assert_eq!(
17497 pipe.server.path_event_next(),
17498 Some(PathEvent::ReusedSourceConnectionId(
17499 0,
17500 (server_addr, client_addr),
17501 (server_addr, spoofed_client_addr)
17502 ))
17503 );
17504 assert_eq!(
17505 pipe.server.path_event_next(),
17506 Some(PathEvent::New(server_addr, spoofed_client_addr))
17507 );
17508
17509 assert_eq!(
17510 pipe.server.is_path_validated(server_addr, client_addr),
17511 Ok(true)
17512 );
17513 assert_eq!(
17514 pipe.server
17515 .is_path_validated(server_addr, spoofed_client_addr),
17516 Ok(false)
17517 );
17518
17519 testing::emit_flight(&mut pipe.server).unwrap();
17521
17522 let probed_pid = pipe
17525 .server
17526 .paths
17527 .path_id_from_addrs(&(server_addr, spoofed_client_addr))
17528 .unwrap();
17529 let probe_instant = pipe
17530 .server
17531 .paths
17532 .get(probed_pid)
17533 .unwrap()
17534 .recovery
17535 .loss_detection_timer()
17536 .unwrap();
17537 let timer = probe_instant.duration_since(time::Instant::now());
17538 std::thread::sleep(timer + time::Duration::from_millis(1));
17539
17540 pipe.server.on_timeout();
17541
17542 assert_eq!(
17545 pipe.server.path_event_next(),
17546 Some(PathEvent::FailedValidation(
17547 server_addr,
17548 spoofed_client_addr
17549 ))
17550 );
17551
17552 assert_eq!(
17553 pipe.server.is_path_validated(server_addr, client_addr),
17554 Ok(true)
17555 );
17556 assert_eq!(
17557 pipe.server
17558 .is_path_validated(server_addr, spoofed_client_addr),
17559 Ok(false)
17560 );
17561
17562 let server_active_path = pipe.server.paths.get_active().unwrap();
17563 assert_eq!(server_active_path.local_addr(), server_addr);
17564 assert_eq!(server_active_path.peer_addr(), client_addr);
17565 assert_eq!(pipe.advance(), Ok(()));
17566 let (rcv_data_2, fin) =
17567 pipe.client.stream_recv(1, &mut recv_buf).unwrap();
17568 assert!(fin);
17569 assert_eq!(rcv_data_1 + rcv_data_2, DATA_BYTES);
17570 }
17571
17572 #[test]
17573 fn consecutive_non_ack_eliciting() {
17574 let mut buf = [0; 65535];
17575
17576 let mut pipe = testing::Pipe::new().unwrap();
17577 assert_eq!(pipe.handshake(), Ok(()));
17578
17579 let frames = [frame::Frame::Ping { mtu_probe: None }];
17582 let pkt_type = packet::Type::Short;
17583 for _ in 0..24 {
17584 let len = pipe
17585 .send_pkt_to_server(pkt_type, &frames, &mut buf)
17586 .unwrap();
17587 assert!(len > 0);
17588
17589 let frames =
17590 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
17591 assert!(
17592 frames
17593 .iter()
17594 .all(|frame| matches!(frame, frame::Frame::ACK { .. })),
17595 "ACK only"
17596 );
17597 }
17598
17599 let len = pipe
17601 .send_pkt_to_server(pkt_type, &frames, &mut buf)
17602 .unwrap();
17603 assert!(len > 0);
17604
17605 let frames =
17606 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
17607 assert!(
17608 frames
17609 .iter()
17610 .any(|frame| matches!(frame, frame::Frame::Ping {
17611 mtu_probe: None
17612 })),
17613 "found a PING"
17614 );
17615 }
17616
17617 #[test]
17618 fn send_ack_eliciting_causes_ping() {
17619 let mut pipe = testing::Pipe::new().unwrap();
17621 assert_eq!(pipe.handshake(), Ok(()));
17622
17623 pipe.server.send_ack_eliciting().unwrap();
17625
17626 let mut buf = [0; 1500];
17628 let (len, _) = pipe.server.send(&mut buf).unwrap();
17629
17630 let frames =
17631 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
17632 let mut iter = frames.iter();
17633
17634 assert_eq!(iter.next(), Some(&frame::Frame::Ping { mtu_probe: None }));
17635 }
17636
17637 #[test]
17638 fn send_ack_eliciting_no_ping() {
17639 let mut pipe = testing::Pipe::new().unwrap();
17641 assert_eq!(pipe.handshake(), Ok(()));
17642
17643 pipe.server.send_ack_eliciting().unwrap();
17645
17646 assert_eq!(pipe.server.stream_send(1, b"a", false), Ok(1));
17649
17650 let mut buf = [0; 1500];
17652 let (len, _) = pipe.server.send(&mut buf).unwrap();
17653
17654 let frames =
17655 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
17656 let mut iter = frames.iter();
17657
17658 assert!(matches!(
17659 iter.next(),
17660 Some(&frame::Frame::Stream {
17661 stream_id: 1,
17662 data: _
17663 })
17664 ));
17665 assert!(iter.next().is_none());
17666 }
17667
17668 #[test]
17671 fn stop_sending_stream_send_after_reset_stream_ack() {
17672 let mut b = [0; 15];
17673
17674 let mut buf = [0; 65535];
17675
17676 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
17677 config
17678 .load_cert_chain_from_pem_file("examples/cert.crt")
17679 .unwrap();
17680 config
17681 .load_priv_key_from_pem_file("examples/cert.key")
17682 .unwrap();
17683 config
17684 .set_application_protos(&[b"proto1", b"proto2"])
17685 .unwrap();
17686 config.set_initial_max_data(999999999);
17687 config.set_initial_max_stream_data_bidi_local(30);
17688 config.set_initial_max_stream_data_bidi_remote(30);
17689 config.set_initial_max_stream_data_uni(30);
17690 config.set_initial_max_streams_bidi(1000);
17691 config.set_initial_max_streams_uni(0);
17692 config.verify_peer(false);
17693
17694 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
17695 assert_eq!(pipe.handshake(), Ok(()));
17696
17697 assert_eq!(pipe.server.streams.len(), 0);
17698 assert_eq!(pipe.server.readable().len(), 0);
17699 assert_eq!(pipe.server.writable().len(), 0);
17700
17701 assert_eq!(pipe.client.stream_send(0, b"hello", true), Ok(5));
17703 assert_eq!(pipe.client.stream_send(4, b"hello", true), Ok(5));
17704 assert_eq!(pipe.client.stream_send(8, b"hello", true), Ok(5));
17705 assert_eq!(pipe.client.stream_send(12, b"hello", true), Ok(5));
17706 assert_eq!(pipe.client.stream_send(16, b"hello", true), Ok(5));
17707 assert_eq!(pipe.client.stream_send(20, b"hello", true), Ok(5));
17708 assert_eq!(pipe.client.stream_send(24, b"hello", true), Ok(5));
17709 assert_eq!(pipe.client.stream_send(28, b"hello", true), Ok(5));
17710 assert_eq!(pipe.client.stream_send(32, b"hello", true), Ok(5));
17711 assert_eq!(pipe.client.stream_send(36, b"hello", true), Ok(5));
17712 assert_eq!(pipe.advance(), Ok(()));
17713
17714 let mut r = pipe.server.readable();
17716 assert_eq!(r.len(), 10);
17717 assert_eq!(r.next(), Some(0));
17718 assert_eq!(r.next(), Some(4));
17719 assert_eq!(r.next(), Some(8));
17720 assert_eq!(r.next(), Some(12));
17721 assert_eq!(r.next(), Some(16));
17722 assert_eq!(r.next(), Some(20));
17723 assert_eq!(r.next(), Some(24));
17724 assert_eq!(r.next(), Some(28));
17725 assert_eq!(r.next(), Some(32));
17726 assert_eq!(r.next(), Some(36));
17727
17728 assert_eq!(r.next(), None);
17729
17730 let mut w = pipe.server.writable();
17731 assert_eq!(w.len(), 10);
17732 assert_eq!(w.next(), Some(0));
17733 assert_eq!(w.next(), Some(4));
17734 assert_eq!(w.next(), Some(8));
17735 assert_eq!(w.next(), Some(12));
17736 assert_eq!(w.next(), Some(16));
17737 assert_eq!(w.next(), Some(20));
17738 assert_eq!(w.next(), Some(24));
17739 assert_eq!(w.next(), Some(28));
17740 assert_eq!(w.next(), Some(32));
17741 assert_eq!(w.next(), Some(36));
17742 assert_eq!(w.next(), None);
17743
17744 assert_eq!(pipe.server.stream_recv(0, &mut b), Ok((5, true)));
17746 assert!(pipe.server.stream_finished(0));
17747
17748 assert_eq!(pipe.server.readable().len(), 9);
17749 assert_eq!(pipe.server.writable().len(), 10);
17750
17751 assert_eq!(pipe.server.stream_writable(0, 0), Ok(true));
17752
17753 while pipe.server.stream_send(0, b"world", false) != Err(Error::Done) {
17755 assert_eq!(pipe.advance(), Ok(()));
17756 }
17757
17758 assert_eq!(pipe.server.writable().len(), 9);
17759 assert_eq!(pipe.server.stream_writable(0, 0), Ok(true));
17760
17761 let frames = [frame::Frame::StopSending {
17763 stream_id: 0,
17764 error_code: 42,
17765 }];
17766
17767 let pkt_type = packet::Type::Short;
17768 let len = pipe
17769 .send_pkt_to_server(pkt_type, &frames, &mut buf)
17770 .unwrap();
17771
17772 let frames =
17774 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
17775
17776 let mut iter = frames.iter();
17777
17778 iter.next();
17780
17781 assert_eq!(
17782 iter.next(),
17783 Some(&frame::Frame::ResetStream {
17784 stream_id: 0,
17785 error_code: 42,
17786 final_size: 30,
17787 })
17788 );
17789
17790 let mut w = pipe.server.writable();
17793 assert_eq!(w.len(), 10);
17794
17795 assert!(w.any(|s| s == 0));
17796 assert_eq!(
17797 pipe.server.stream_writable(0, 1),
17798 Err(Error::StreamStopped(42))
17799 );
17800
17801 assert_eq!(pipe.server.writable().len(), 10);
17802 assert_eq!(pipe.server.streams.len(), 10);
17803
17804 let mut ranges = ranges::RangeSet::default();
17806 ranges.insert(0..12);
17807
17808 let frames = [frame::Frame::ACK {
17809 ack_delay: 15,
17810 ranges,
17811 ecn_counts: None,
17812 }];
17813
17814 assert_eq!(pipe.send_pkt_to_server(pkt_type, &frames, &mut buf), Ok(0));
17815
17816 assert_eq!(pipe.server.streams.len(), 9);
17818
17819 let frames = [frame::Frame::StopSending {
17821 stream_id: 0,
17822 error_code: 42,
17823 }];
17824
17825 let len = pipe
17826 .send_pkt_to_server(pkt_type, &frames, &mut buf)
17827 .unwrap();
17828
17829 let frames =
17830 testing::decode_pkt(&mut pipe.client, &mut buf[..len]).unwrap();
17831
17832 assert_eq!(frames.len(), 1);
17833
17834 match frames.first() {
17835 Some(frame::Frame::ACK { .. }) => (),
17836
17837 f => panic!("expected ACK frame, got {:?}", f),
17838 };
17839
17840 assert_eq!(pipe.server.streams.len(), 9);
17841
17842 let mut w = pipe.server.writable();
17844 assert_eq!(w.len(), 9);
17845 assert!(!w.any(|s| s == 0));
17846
17847 assert_eq!(pipe.server.stream_send(0, b"world", true), Err(Error::Done),);
17850
17851 let mut w = pipe.server.writable();
17853 assert_eq!(w.len(), 9);
17854 assert!(!w.any(|s| s == 0));
17855 }
17856
17857 #[test]
17858 fn challenge_no_cids() {
17859 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
17860 config
17861 .load_cert_chain_from_pem_file("examples/cert.crt")
17862 .unwrap();
17863 config
17864 .load_priv_key_from_pem_file("examples/cert.key")
17865 .unwrap();
17866 config
17867 .set_application_protos(&[b"proto1", b"proto2"])
17868 .unwrap();
17869 config.verify_peer(false);
17870 config.set_active_connection_id_limit(4);
17871 config.set_initial_max_data(30);
17872 config.set_initial_max_stream_data_bidi_local(15);
17873 config.set_initial_max_stream_data_bidi_remote(15);
17874 config.set_initial_max_stream_data_uni(10);
17875 config.set_initial_max_streams_bidi(3);
17876
17877 let mut pipe =
17878 testing::Pipe::with_config_and_scid_lengths(&mut config, 16, 16)
17879 .unwrap();
17880 assert_eq!(pipe.handshake(), Ok(()));
17881
17882 let mut server_cids = Vec::new();
17884 for _ in 0..2 {
17885 let (cid, reset_token) = testing::create_cid_and_reset_token(16);
17886 pipe.server
17887 .new_scid(&cid, reset_token, true)
17888 .expect("server issue cid");
17889 server_cids.push(cid);
17890 }
17891 assert_eq!(pipe.advance(), Ok(()));
17892
17893 let server_addr = testing::Pipe::server_addr();
17894 let client_addr_2 = "127.0.0.1:5678".parse().unwrap();
17895
17896 let frames = [frame::Frame::PathChallenge {
17898 data: [0, 1, 2, 3, 4, 5, 6, 7],
17899 }];
17900 let mut pkt_buf = [0u8; 1500];
17901 let mut b = octets::OctetsMut::with_slice(&mut pkt_buf);
17902 let epoch = packet::Type::Short.to_epoch().unwrap();
17903 let space = &mut pipe.client.pkt_num_spaces[epoch];
17904 let pn = pipe.client.next_pkt_num;
17905 let pn_len = 4;
17906
17907 let hdr = Header {
17908 ty: packet::Type::Short,
17909 version: pipe.client.version,
17910 dcid: server_cids[0].clone(),
17911 scid: ConnectionId::from_ref(&[5, 4, 3, 2, 1]),
17912 pkt_num: 0,
17913 pkt_num_len: pn_len,
17914 token: pipe.client.token.clone(),
17915 versions: None,
17916 key_phase: pipe.client.key_phase,
17917 };
17918 hdr.to_bytes(&mut b).expect("encode header");
17919 let payload_len = frames.iter().fold(0, |acc, x| acc + x.wire_len());
17920 b.put_u32(pn as u32).expect("put pn");
17921
17922 let payload_offset = b.off();
17923
17924 for frame in frames {
17925 frame.to_bytes(&mut b).expect("encode frames");
17926 }
17927
17928 let aead = space.crypto_seal.as_ref().expect("crypto seal");
17929
17930 let written = packet::encrypt_pkt(
17931 &mut b,
17932 pn,
17933 pn_len,
17934 payload_len,
17935 payload_offset,
17936 None,
17937 aead,
17938 )
17939 .expect("packet encrypt");
17940 pipe.client.next_pkt_num += 1;
17941
17942 pipe.server
17943 .recv(&mut pkt_buf[..written], RecvInfo {
17944 to: server_addr,
17945 from: client_addr_2,
17946 })
17947 .expect("server receive path challenge");
17948
17949 assert!(!pipe
17951 .server
17952 .paths_iter(server_addr)
17953 .any(|path| path == client_addr_2));
17954 }
17955
17956 #[test]
17957 fn successful_probe_pmtud() {
17958 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
17959 config
17960 .load_cert_chain_from_pem_file("examples/cert.crt")
17961 .unwrap();
17962 config
17963 .load_priv_key_from_pem_file("examples/cert.key")
17964 .unwrap();
17965 config
17966 .set_application_protos(&[b"proto1", b"proto2"])
17967 .unwrap();
17968 config.verify_peer(false);
17969 config.set_initial_max_data(100000);
17970 config.set_initial_max_stream_data_bidi_local(100000);
17971 config.set_initial_max_stream_data_bidi_remote(100000);
17972 config.set_initial_max_streams_bidi(2);
17973 config.set_active_connection_id_limit(4);
17974 config.set_max_send_udp_payload_size(1350);
17975 config.set_max_recv_udp_payload_size(1350);
17976 config.discover_pmtu(true);
17977
17978 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
17980 assert_eq!(pipe.handshake(), Ok(()));
17981
17982 let server_addr = testing::Pipe::server_addr();
17983 let client_addr = testing::Pipe::client_addr();
17984 let pid_1 = pipe
17985 .server
17986 .paths
17987 .path_id_from_addrs(&(server_addr, client_addr))
17988 .expect("no such path");
17989
17990 let pmtu_param = &mut pipe.server.paths.get_mut(pid_1).unwrap().pmtud;
17992 assert!(pmtu_param.get_probe_status());
17993 assert_eq!(pmtu_param.get_probe_size(), 1350);
17994 assert_eq!(pipe.advance(), Ok(()));
17995
17996 for (_, p) in pipe.server.paths.iter_mut() {
17997 assert_eq!(p.pmtud.get_current(), 1350);
17998 assert!(!p.pmtud.get_probe_status());
17999 }
18000 }
18001
18002 #[test]
18003 fn pmtud_probe_loss() {
18004 let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
18005 config
18006 .load_cert_chain_from_pem_file("examples/cert.crt")
18007 .unwrap();
18008 config
18009 .load_priv_key_from_pem_file("examples/cert.key")
18010 .unwrap();
18011 config
18012 .set_application_protos(&[b"proto1", b"proto2"])
18013 .unwrap();
18014 config.verify_peer(false);
18015 config.set_initial_max_data(100000);
18016 config.set_initial_max_stream_data_bidi_local(100000);
18017 config.set_initial_max_stream_data_bidi_remote(100000);
18018 config.set_initial_max_streams_bidi(2);
18019 config.set_active_connection_id_limit(4);
18020 config.set_max_send_udp_payload_size(1350);
18021 config.set_max_recv_udp_payload_size(1250);
18022 config.discover_pmtu(true);
18023
18024 let mut pipe = testing::Pipe::with_config(&mut config).unwrap();
18026 assert_eq!(pipe.handshake(), Ok(()));
18027
18028 let server_addr = testing::Pipe::server_addr();
18029 let client_addr = testing::Pipe::client_addr();
18030 let pid_1 = pipe
18031 .server
18032 .paths
18033 .path_id_from_addrs(&(server_addr, client_addr))
18034 .expect("no such path");
18035
18036 let pmtu_param = &mut pipe.server.paths.get_mut(pid_1).unwrap().pmtud;
18038 assert!(pmtu_param.get_probe_status());
18039 assert_eq!(pmtu_param.get_probe_size(), 1350);
18040 std::thread::sleep(
18041 pipe.server.paths.get_mut(pid_1).unwrap().recovery.rtt() +
18042 time::Duration::from_millis(1),
18043 );
18044
18045 let active_server_path = pipe.server.paths.get_active_mut().unwrap();
18046 let pmtu_param = &mut active_server_path.pmtud;
18047
18048 assert_eq!(pmtu_param.get_current(), 1200);
18050
18051 assert!(pmtu_param.get_probe_status());
18053 }
18054}
18055
18056pub use crate::packet::ConnectionId;
18057pub use crate::packet::Header;
18058pub use crate::packet::Type;
18059
18060pub use crate::path::PathEvent;
18061pub use crate::path::PathStats;
18062pub use crate::path::SocketAddrIter;
18063
18064pub use crate::recovery::CongestionControlAlgorithm;
18065use crate::recovery::RecoveryOps;
18066
18067pub use crate::stream::StreamIter;
18068
18069mod cid;
18070mod crypto;
18071mod dgram;
18072#[cfg(feature = "ffi")]
18073mod ffi;
18074mod flowcontrol;
18075mod frame;
18076pub mod h3;
18077mod minmax;
18078mod packet;
18079mod path;
18080mod pmtud;
18081mod rand;
18082mod ranges;
18083mod recovery;
18084mod stream;
18085mod tls;