-
Notifications
You must be signed in to change notification settings - Fork 446
/
Copy pathtcp.rs
7901 lines (7248 loc) · 255 KB
/
tcp.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Heads up! Before working on this file you should read, at least, RFC 793 and
// the parts of RFC 1122 that discuss TCP, as well as RFC 7323 for some of the TCP options.
// Consult RFC 7414 when implementing a new feature.
use core::fmt::Display;
#[cfg(feature = "async")]
use core::task::Waker;
use core::{cmp, fmt, mem};
#[cfg(feature = "async")]
use crate::socket::WakerRegistration;
use crate::socket::{Context, PollAt};
use crate::storage::{Assembler, RingBuffer};
use crate::time::{Duration, Instant};
use crate::wire::{
IpAddress, IpEndpoint, IpListenEndpoint, IpProtocol, IpRepr, TcpControl, TcpRepr, TcpSeqNumber,
TcpTimestampGenerator, TcpTimestampRepr, TCP_HEADER_LEN,
};
mod congestion;
macro_rules! tcp_trace {
($($arg:expr),*) => (net_log!(trace, $($arg),*));
}
/// Error returned by [`Socket::listen`]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ListenError {
InvalidState,
Unaddressable,
}
impl Display for ListenError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ListenError::InvalidState => write!(f, "invalid state"),
ListenError::Unaddressable => write!(f, "unaddressable destination"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ListenError {}
/// Error returned by [`Socket::connect`]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ConnectError {
InvalidState,
Unaddressable,
}
impl Display for ConnectError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ConnectError::InvalidState => write!(f, "invalid state"),
ConnectError::Unaddressable => write!(f, "unaddressable destination"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for ConnectError {}
/// Error returned by [`Socket::send`]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum SendError {
InvalidState,
}
impl Display for SendError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SendError::InvalidState => write!(f, "invalid state"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for SendError {}
/// Error returned by [`Socket::recv`]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum RecvError {
InvalidState,
Finished,
}
impl Display for RecvError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RecvError::InvalidState => write!(f, "invalid state"),
RecvError::Finished => write!(f, "operation finished"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for RecvError {}
/// A TCP socket ring buffer.
pub type SocketBuffer<'a> = RingBuffer<'a, u8>;
/// The state of a TCP socket, according to [RFC 793].
///
/// [RFC 793]: https://tools.ietf.org/html/rfc793
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum State {
Closed,
Listen,
SynSent,
SynReceived,
Established,
FinWait1,
FinWait2,
CloseWait,
Closing,
LastAck,
TimeWait,
}
impl fmt::Display for State {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
State::Closed => write!(f, "CLOSED"),
State::Listen => write!(f, "LISTEN"),
State::SynSent => write!(f, "SYN-SENT"),
State::SynReceived => write!(f, "SYN-RECEIVED"),
State::Established => write!(f, "ESTABLISHED"),
State::FinWait1 => write!(f, "FIN-WAIT-1"),
State::FinWait2 => write!(f, "FIN-WAIT-2"),
State::CloseWait => write!(f, "CLOSE-WAIT"),
State::Closing => write!(f, "CLOSING"),
State::LastAck => write!(f, "LAST-ACK"),
State::TimeWait => write!(f, "TIME-WAIT"),
}
}
}
// Conservative initial RTT estimate.
const RTTE_INITIAL_RTT: u32 = 300;
const RTTE_INITIAL_DEV: u32 = 100;
// Minimum "safety margin" for the RTO that kicks in when the
// variance gets very low.
const RTTE_MIN_MARGIN: u32 = 5;
const RTTE_MIN_RTO: u32 = 10;
const RTTE_MAX_RTO: u32 = 10000;
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
struct RttEstimator {
// Using u32 instead of Duration to save space (Duration is i64)
rtt: u32,
deviation: u32,
timestamp: Option<(Instant, TcpSeqNumber)>,
max_seq_sent: Option<TcpSeqNumber>,
rto_count: u8,
}
impl Default for RttEstimator {
fn default() -> Self {
Self {
rtt: RTTE_INITIAL_RTT,
deviation: RTTE_INITIAL_DEV,
timestamp: None,
max_seq_sent: None,
rto_count: 0,
}
}
}
impl RttEstimator {
fn retransmission_timeout(&self) -> Duration {
let margin = RTTE_MIN_MARGIN.max(self.deviation * 4);
let ms = (self.rtt + margin).clamp(RTTE_MIN_RTO, RTTE_MAX_RTO);
Duration::from_millis(ms as u64)
}
fn sample(&mut self, new_rtt: u32) {
// "Congestion Avoidance and Control", Van Jacobson, Michael J. Karels, 1988
self.rtt = (self.rtt * 7 + new_rtt + 7) / 8;
let diff = (self.rtt as i32 - new_rtt as i32).unsigned_abs();
self.deviation = (self.deviation * 3 + diff + 3) / 4;
self.rto_count = 0;
let rto = self.retransmission_timeout().total_millis();
tcp_trace!(
"rtte: sample={:?} rtt={:?} dev={:?} rto={:?}",
new_rtt,
self.rtt,
self.deviation,
rto
);
}
fn on_send(&mut self, timestamp: Instant, seq: TcpSeqNumber) {
if self
.max_seq_sent
.map(|max_seq_sent| seq > max_seq_sent)
.unwrap_or(true)
{
self.max_seq_sent = Some(seq);
if self.timestamp.is_none() {
self.timestamp = Some((timestamp, seq));
tcp_trace!("rtte: sampling at seq={:?}", seq);
}
}
}
fn on_ack(&mut self, timestamp: Instant, seq: TcpSeqNumber) {
if let Some((sent_timestamp, sent_seq)) = self.timestamp {
if seq >= sent_seq {
self.sample((timestamp - sent_timestamp).total_millis() as u32);
self.timestamp = None;
}
}
}
fn on_retransmit(&mut self) {
if self.timestamp.is_some() {
tcp_trace!("rtte: abort sampling due to retransmit");
}
self.timestamp = None;
self.rto_count = self.rto_count.saturating_add(1);
if self.rto_count >= 3 {
// This happens in 2 scenarios:
// - The RTT is higher than the initial estimate
// - The network conditions change, suddenly making the RTT much higher
// In these cases, the estimator can get stuck, because it can't sample because
// all packets sent would incur a retransmit. To avoid this, force an estimate
// increase if we see 3 consecutive retransmissions without any successful sample.
self.rto_count = 0;
self.rtt = RTTE_MAX_RTO.min(self.rtt * 2);
let rto = self.retransmission_timeout().total_millis();
tcp_trace!(
"rtte: too many retransmissions, increasing: rtt={:?} dev={:?} rto={:?}",
self.rtt,
self.deviation,
rto
);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
enum Timer {
Idle {
keep_alive_at: Option<Instant>,
},
Retransmit {
expires_at: Instant,
delay: Duration,
},
FastRetransmit,
Close {
expires_at: Instant,
},
}
const ACK_DELAY_DEFAULT: Duration = Duration::from_millis(10);
const CLOSE_DELAY: Duration = Duration::from_millis(10_000);
impl Timer {
fn new() -> Timer {
Timer::Idle {
keep_alive_at: None,
}
}
fn should_keep_alive(&self, timestamp: Instant) -> bool {
match *self {
Timer::Idle {
keep_alive_at: Some(keep_alive_at),
} if timestamp >= keep_alive_at => true,
_ => false,
}
}
fn should_retransmit(&self, timestamp: Instant) -> Option<Duration> {
match *self {
Timer::Retransmit { expires_at, delay } if timestamp >= expires_at => {
Some(timestamp - expires_at + delay)
}
Timer::FastRetransmit => Some(Duration::from_millis(0)),
_ => None,
}
}
fn should_close(&self, timestamp: Instant) -> bool {
match *self {
Timer::Close { expires_at } if timestamp >= expires_at => true,
_ => false,
}
}
fn poll_at(&self) -> PollAt {
match *self {
Timer::Idle {
keep_alive_at: Some(keep_alive_at),
} => PollAt::Time(keep_alive_at),
Timer::Idle {
keep_alive_at: None,
} => PollAt::Ingress,
Timer::Retransmit { expires_at, .. } => PollAt::Time(expires_at),
Timer::FastRetransmit => PollAt::Now,
Timer::Close { expires_at } => PollAt::Time(expires_at),
}
}
fn set_for_idle(&mut self, timestamp: Instant, interval: Option<Duration>) {
*self = Timer::Idle {
keep_alive_at: interval.map(|interval| timestamp + interval),
}
}
fn set_keep_alive(&mut self) {
if let Timer::Idle { keep_alive_at } = self {
if keep_alive_at.is_none() {
*keep_alive_at = Some(Instant::from_millis(0))
}
}
}
fn rewind_keep_alive(&mut self, timestamp: Instant, interval: Option<Duration>) {
if let Timer::Idle { keep_alive_at } = self {
*keep_alive_at = interval.map(|interval| timestamp + interval)
}
}
fn set_for_retransmit(&mut self, timestamp: Instant, delay: Duration) {
match *self {
Timer::Idle { .. } | Timer::FastRetransmit { .. } => {
*self = Timer::Retransmit {
expires_at: timestamp + delay,
delay,
}
}
Timer::Retransmit { expires_at, delay } if timestamp >= expires_at => {
*self = Timer::Retransmit {
expires_at: timestamp + delay,
delay: delay * 2,
}
}
Timer::Retransmit { .. } => (),
Timer::Close { .. } => (),
}
}
fn set_for_fast_retransmit(&mut self) {
*self = Timer::FastRetransmit
}
fn set_for_close(&mut self, timestamp: Instant) {
*self = Timer::Close {
expires_at: timestamp + CLOSE_DELAY,
}
}
fn is_retransmit(&self) -> bool {
match *self {
Timer::Retransmit { .. } | Timer::FastRetransmit => true,
_ => false,
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum AckDelayTimer {
Idle,
Waiting(Instant),
Immediate,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
struct Tuple {
local: IpEndpoint,
remote: IpEndpoint,
}
impl Display for Tuple {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.local, self.remote)
}
}
/// A congestion control algorithm.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum CongestionControl {
None,
#[cfg(feature = "socket-tcp-reno")]
Reno,
#[cfg(feature = "socket-tcp-cubic")]
Cubic,
}
/// A Transmission Control Protocol socket.
///
/// A TCP socket may passively listen for connections or actively connect to another endpoint.
/// Note that, for listening sockets, there is no "backlog"; to be able to simultaneously
/// accept several connections, as many sockets must be allocated, or any new connection
/// attempts will be reset.
#[derive(Debug)]
pub struct Socket<'a> {
state: State,
timer: Timer,
rtte: RttEstimator,
assembler: Assembler,
rx_buffer: SocketBuffer<'a>,
rx_fin_received: bool,
tx_buffer: SocketBuffer<'a>,
/// Interval after which, if no inbound packets are received, the connection is aborted.
timeout: Option<Duration>,
/// Interval at which keep-alive packets will be sent.
keep_alive: Option<Duration>,
/// The time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
hop_limit: Option<u8>,
/// Address passed to listen(). Listen address is set when listen() is called and
/// used every time the socket is reset back to the LISTEN state.
listen_endpoint: IpListenEndpoint,
/// Current 4-tuple (local and remote endpoints).
tuple: Option<Tuple>,
/// The sequence number corresponding to the beginning of the transmit buffer.
/// I.e. an ACK(local_seq_no+n) packet removes n bytes from the transmit buffer.
local_seq_no: TcpSeqNumber,
/// The sequence number corresponding to the beginning of the receive buffer.
/// I.e. userspace reading n bytes adds n to remote_seq_no.
remote_seq_no: TcpSeqNumber,
/// The last sequence number sent.
/// I.e. in an idle socket, local_seq_no+tx_buffer.len().
remote_last_seq: TcpSeqNumber,
/// The last acknowledgement number sent.
/// I.e. in an idle socket, remote_seq_no+rx_buffer.len().
remote_last_ack: Option<TcpSeqNumber>,
/// The last window length sent.
remote_last_win: u16,
/// The sending window scaling factor advertised to remotes which support RFC 1323.
/// It is zero if the window <= 64KiB and/or the remote does not support it.
remote_win_shift: u8,
/// The remote window size, relative to local_seq_no
/// I.e. we're allowed to send octets until local_seq_no+remote_win_len
remote_win_len: usize,
/// The receive window scaling factor for remotes which support RFC 1323, None if unsupported.
remote_win_scale: Option<u8>,
/// Whether or not the remote supports selective ACK as described in RFC 2018.
remote_has_sack: bool,
/// The maximum number of data octets that the remote side may receive.
remote_mss: usize,
/// The timestamp of the last packet received.
remote_last_ts: Option<Instant>,
/// The sequence number of the last packet received, used for sACK
local_rx_last_seq: Option<TcpSeqNumber>,
/// The ACK number of the last packet received.
local_rx_last_ack: Option<TcpSeqNumber>,
/// The number of packets received directly after
/// each other which have the same ACK number.
local_rx_dup_acks: u8,
/// Duration for Delayed ACK. If None no ACKs will be delayed.
ack_delay: Option<Duration>,
/// Delayed ack timer. If set, packets containing exclusively
/// ACK or window updates (ie, no data) won't be sent until expiry.
ack_delay_timer: AckDelayTimer,
/// Used for rate-limiting: No more challenge ACKs will be sent until this instant.
challenge_ack_timer: Instant,
/// Nagle's Algorithm enabled.
nagle: bool,
/// The congestion control algorithm.
congestion_controller: congestion::AnyController,
/// tsval generator - if some, tcp timestamp is enabled
tsval_generator: Option<TcpTimestampGenerator>,
/// 0 if not seen or timestamp not enabled
last_remote_tsval: u32,
#[cfg(feature = "async")]
rx_waker: WakerRegistration,
#[cfg(feature = "async")]
tx_waker: WakerRegistration,
}
const DEFAULT_MSS: usize = 536;
impl<'a> Socket<'a> {
#[allow(unused_comparisons)] // small usize platforms always pass rx_capacity check
/// Create a socket using the given buffers.
pub fn new<T>(rx_buffer: T, tx_buffer: T) -> Socket<'a>
where
T: Into<SocketBuffer<'a>>,
{
let (rx_buffer, tx_buffer) = (rx_buffer.into(), tx_buffer.into());
let rx_capacity = rx_buffer.capacity();
// From RFC 1323:
// [...] the above constraints imply that 2 * the max window size must be less
// than 2**31 [...] Thus, the shift count must be limited to 14 (which allows
// windows of 2**30 = 1 Gbyte).
if rx_capacity > (1 << 30) {
panic!("receiving buffer too large, cannot exceed 1 GiB")
}
let rx_cap_log2 = mem::size_of::<usize>() * 8 - rx_capacity.leading_zeros() as usize;
Socket {
state: State::Closed,
timer: Timer::new(),
rtte: RttEstimator::default(),
assembler: Assembler::new(),
tx_buffer,
rx_buffer,
rx_fin_received: false,
timeout: None,
keep_alive: None,
hop_limit: None,
listen_endpoint: IpListenEndpoint::default(),
tuple: None,
local_seq_no: TcpSeqNumber::default(),
remote_seq_no: TcpSeqNumber::default(),
remote_last_seq: TcpSeqNumber::default(),
remote_last_ack: None,
remote_last_win: 0,
remote_win_len: 0,
remote_win_shift: rx_cap_log2.saturating_sub(16) as u8,
remote_win_scale: None,
remote_has_sack: false,
remote_mss: DEFAULT_MSS,
remote_last_ts: None,
local_rx_last_ack: None,
local_rx_last_seq: None,
local_rx_dup_acks: 0,
ack_delay: Some(ACK_DELAY_DEFAULT),
ack_delay_timer: AckDelayTimer::Idle,
challenge_ack_timer: Instant::from_secs(0),
nagle: true,
tsval_generator: None,
last_remote_tsval: 0,
congestion_controller: congestion::AnyController::new(),
#[cfg(feature = "async")]
rx_waker: WakerRegistration::new(),
#[cfg(feature = "async")]
tx_waker: WakerRegistration::new(),
}
}
/// Enable or disable TCP Timestamp.
pub fn set_tsval_generator(&mut self, generator: Option<TcpTimestampGenerator>) {
self.tsval_generator = generator;
}
/// Return whether TCP Timestamp is enabled.
pub fn timestamp_enabled(&self) -> bool {
self.tsval_generator.is_some()
}
/// Set an algorithm for congestion control.
///
/// `CongestionControl::None` indicates that no congestion control is applied.
/// Options `CongestionControl::Cubic` and `CongestionControl::Reno` are also available.
/// To use Reno and Cubic, please enable the `socket-tcp-reno` and `socket-tcp-cubic` features
/// in the `smoltcp` crate, respectively.
///
/// `CongestionControl::Reno` is a classic congestion control algorithm valued for its simplicity.
/// Despite having a lower algorithmic complexity than `Cubic`,
/// it is less efficient in terms of bandwidth usage.
///
/// `CongestionControl::Cubic` represents a modern congestion control algorithm designed to
/// be more efficient and fair compared to `CongestionControl::Reno`.
/// It is the default choice for Linux, Windows, and macOS.
/// `CongestionControl::Cubic` relies on double precision (`f64`) floating point operations, which may cause issues in some contexts:
/// * Small embedded processors (such as Cortex-M0, Cortex-M1, and Cortex-M3) do not have an FPU, and floating point operations consume significant amounts of CPU time and Flash space.
/// * Interrupt handlers should almost always avoid floating-point operations.
/// * Kernel-mode code on desktop processors usually avoids FPU operations to reduce the penalty of saving and restoring FPU registers.
/// In all these cases, `CongestionControl::Reno` is a better choice of congestion control algorithm.
pub fn set_congestion_control(&mut self, congestion_control: CongestionControl) {
use congestion::*;
self.congestion_controller = match congestion_control {
CongestionControl::None => AnyController::None(no_control::NoControl),
#[cfg(feature = "socket-tcp-reno")]
CongestionControl::Reno => AnyController::Reno(reno::Reno::new()),
#[cfg(feature = "socket-tcp-cubic")]
CongestionControl::Cubic => AnyController::Cubic(cubic::Cubic::new()),
}
}
/// Return the current congestion control algorithm.
pub fn congestion_control(&self) -> CongestionControl {
use congestion::*;
match self.congestion_controller {
AnyController::None(_) => CongestionControl::None,
#[cfg(feature = "socket-tcp-reno")]
AnyController::Reno(_) => CongestionControl::Reno,
#[cfg(feature = "socket-tcp-cubic")]
AnyController::Cubic(_) => CongestionControl::Cubic,
}
}
/// Register a waker for receive operations.
///
/// The waker is woken on state changes that might affect the return value
/// of `recv` method calls, such as receiving data, or the socket closing.
///
/// Notes:
///
/// - Only one waker can be registered at a time. If another waker was previously registered,
/// it is overwritten and will no longer be woken.
/// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
/// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `recv` has
/// necessarily changed.
#[cfg(feature = "async")]
pub fn register_recv_waker(&mut self, waker: &Waker) {
self.rx_waker.register(waker)
}
/// Register a waker for send operations.
///
/// The waker is woken on state changes that might affect the return value
/// of `send` method calls, such as space becoming available in the transmit
/// buffer, or the socket closing.
///
/// Notes:
///
/// - Only one waker can be registered at a time. If another waker was previously registered,
/// it is overwritten and will no longer be woken.
/// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
/// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `send` has
/// necessarily changed.
#[cfg(feature = "async")]
pub fn register_send_waker(&mut self, waker: &Waker) {
self.tx_waker.register(waker)
}
/// Return the timeout duration.
///
/// See also the [set_timeout](#method.set_timeout) method.
pub fn timeout(&self) -> Option<Duration> {
self.timeout
}
/// Return the ACK delay duration.
///
/// See also the [set_ack_delay](#method.set_ack_delay) method.
pub fn ack_delay(&self) -> Option<Duration> {
self.ack_delay
}
/// Return whether Nagle's Algorithm is enabled.
///
/// See also the [set_nagle_enabled](#method.set_nagle_enabled) method.
pub fn nagle_enabled(&self) -> bool {
self.nagle
}
/// Return the current window field value, including scaling according to RFC 1323.
///
/// Used in internal calculations as well as packet generation.
#[inline]
fn scaled_window(&self) -> u16 {
cmp::min(
self.rx_buffer.window() >> self.remote_win_shift as usize,
(1 << 16) - 1,
) as u16
}
/// Return the last window field value, including scaling according to RFC 1323.
///
/// Used in internal calculations as well as packet generation.
///
/// Unlike `remote_last_win`, we take into account new packets received (but not acknowledged)
/// since the last window update and adjust the window length accordingly. This ensures a fair
/// comparison between the last window length and the new window length we're going to
/// advertise.
#[inline]
fn last_scaled_window(&self) -> Option<u16> {
let last_ack = self.remote_last_ack?;
let next_ack = self.remote_seq_no + self.rx_buffer.len();
let last_win = (self.remote_last_win as usize) << self.remote_win_shift;
let last_win_adjusted = last_ack + last_win - next_ack;
Some(cmp::min(last_win_adjusted >> self.remote_win_shift, (1 << 16) - 1) as u16)
}
/// Set the timeout duration.
///
/// A socket with a timeout duration set will abort the connection if either of the following
/// occurs:
///
/// * After a [connect](#method.connect) call, the remote endpoint does not respond within
/// the specified duration;
/// * After establishing a connection, there is data in the transmit buffer and the remote
/// endpoint exceeds the specified duration between any two packets it sends;
/// * After enabling [keep-alive](#method.set_keep_alive), the remote endpoint exceeds
/// the specified duration between any two packets it sends.
pub fn set_timeout(&mut self, duration: Option<Duration>) {
self.timeout = duration
}
/// Set the ACK delay duration.
///
/// By default, the ACK delay is set to 10ms.
pub fn set_ack_delay(&mut self, duration: Option<Duration>) {
self.ack_delay = duration
}
/// Enable or disable Nagle's Algorithm.
///
/// Also known as "tinygram prevention". By default, it is enabled.
/// Disabling it is equivalent to Linux's TCP_NODELAY flag.
///
/// When enabled, Nagle's Algorithm prevents sending segments smaller than MSS if
/// there is data in flight (sent but not acknowledged). In other words, it ensures
/// at most only one segment smaller than MSS is in flight at a time.
///
/// It ensures better network utilization by preventing sending many very small packets,
/// at the cost of increased latency in some situations, particularly when the remote peer
/// has ACK delay enabled.
pub fn set_nagle_enabled(&mut self, enabled: bool) {
self.nagle = enabled
}
/// Return the keep-alive interval.
///
/// See also the [set_keep_alive](#method.set_keep_alive) method.
pub fn keep_alive(&self) -> Option<Duration> {
self.keep_alive
}
/// Set the keep-alive interval.
///
/// An idle socket with a keep-alive interval set will transmit a "keep-alive ACK" packet
/// every time it receives no communication during that interval. As a result, three things
/// may happen:
///
/// * The remote endpoint is fine and answers with an ACK packet.
/// * The remote endpoint has rebooted and answers with an RST packet.
/// * The remote endpoint has crashed and does not answer.
///
/// The keep-alive functionality together with the timeout functionality allows to react
/// to these error conditions.
pub fn set_keep_alive(&mut self, interval: Option<Duration>) {
self.keep_alive = interval;
if self.keep_alive.is_some() {
// If the connection is idle and we've just set the option, it would not take effect
// until the next packet, unless we wind up the timer explicitly.
self.timer.set_keep_alive();
}
}
/// Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
///
/// See also the [set_hop_limit](#method.set_hop_limit) method
pub fn hop_limit(&self) -> Option<u8> {
self.hop_limit
}
/// Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
///
/// A socket without an explicitly set hop limit value uses the default [IANA recommended]
/// value (64).
///
/// # Panics
///
/// This function panics if a hop limit value of 0 is given. See [RFC 1122 § 3.2.1.7].
///
/// [IANA recommended]: https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml
/// [RFC 1122 § 3.2.1.7]: https://tools.ietf.org/html/rfc1122#section-3.2.1.7
pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
// A host MUST NOT send a datagram with a hop limit value of 0
if let Some(0) = hop_limit {
panic!("the time-to-live value of a packet must not be zero")
}
self.hop_limit = hop_limit
}
/// Return the local endpoint, or None if not connected.
#[inline]
pub fn local_endpoint(&self) -> Option<IpEndpoint> {
Some(self.tuple?.local)
}
/// Return the remote endpoint, or None if not connected.
#[inline]
pub fn remote_endpoint(&self) -> Option<IpEndpoint> {
Some(self.tuple?.remote)
}
/// Return the connection state, in terms of the TCP state machine.
#[inline]
pub fn state(&self) -> State {
self.state
}
fn reset(&mut self) {
let rx_cap_log2 =
mem::size_of::<usize>() * 8 - self.rx_buffer.capacity().leading_zeros() as usize;
self.state = State::Closed;
self.timer = Timer::new();
self.rtte = RttEstimator::default();
self.assembler = Assembler::new();
self.tx_buffer.clear();
self.rx_buffer.clear();
self.rx_fin_received = false;
self.listen_endpoint = IpListenEndpoint::default();
self.tuple = None;
self.local_seq_no = TcpSeqNumber::default();
self.remote_seq_no = TcpSeqNumber::default();
self.remote_last_seq = TcpSeqNumber::default();
self.remote_last_ack = None;
self.remote_last_win = 0;
self.remote_win_len = 0;
self.remote_win_scale = None;
self.remote_win_shift = rx_cap_log2.saturating_sub(16) as u8;
self.remote_mss = DEFAULT_MSS;
self.remote_last_ts = None;
self.ack_delay_timer = AckDelayTimer::Idle;
self.challenge_ack_timer = Instant::from_secs(0);
#[cfg(feature = "async")]
{
self.rx_waker.wake();
self.tx_waker.wake();
}
}
/// Start listening on the given endpoint.
///
/// This function returns `Err(Error::InvalidState)` if the socket was already open
/// (see [is_open](#method.is_open)), and `Err(Error::Unaddressable)`
/// if the port in the given endpoint is zero.
pub fn listen<T>(&mut self, local_endpoint: T) -> Result<(), ListenError>
where
T: Into<IpListenEndpoint>,
{
let local_endpoint = local_endpoint.into();
if local_endpoint.port == 0 {
return Err(ListenError::Unaddressable);
}
if self.is_open() {
// If we were already listening to same endpoint there is nothing to do; exit early.
//
// In the past listening on an socket that was already listening was an error,
// however this makes writing an acceptor loop with multiple sockets impossible.
// Without this early exit, if you tried to listen on a socket that's already listening you'll
// immediately get an error. The only way around this is to abort the socket first
// before listening again, but this means that incoming connections can actually
// get aborted between the abort() and the next listen().
if matches!(self.state, State::Listen) && self.listen_endpoint == local_endpoint {
return Ok(());
} else {
return Err(ListenError::InvalidState);
}
}
self.reset();
self.listen_endpoint = local_endpoint;
self.tuple = None;
self.set_state(State::Listen);
Ok(())
}
/// Connect to a given endpoint.
///
/// The local port must be provided explicitly. Assuming `fn get_ephemeral_port() -> u16`
/// allocates a port between 49152 and 65535, a connection may be established as follows:
///
/// ```no_run
/// # #[cfg(all(
/// # feature = "medium-ethernet",
/// # feature = "proto-ipv4",
/// # ))]
/// # {
/// # use smoltcp::socket::tcp::{Socket, SocketBuffer};
/// # use smoltcp::iface::Interface;
/// # use smoltcp::wire::IpAddress;
/// #
/// # fn get_ephemeral_port() -> u16 {
/// # 49152
/// # }
/// #
/// # let mut socket = Socket::new(
/// # SocketBuffer::new(vec![0; 1200]),
/// # SocketBuffer::new(vec![0; 1200])
/// # );
/// #
/// # let mut iface: Interface = todo!();
/// #
/// socket.connect(
/// iface.context(),
/// (IpAddress::v4(10, 0, 0, 1), 80),
/// get_ephemeral_port()
/// ).unwrap();
/// # }
/// ```
///
/// The local address may optionally be provided.
///
/// This function returns an error if the socket was open; see [is_open](#method.is_open).
/// It also returns an error if the local or remote port is zero, or if the remote address
/// is unspecified.
pub fn connect<T, U>(
&mut self,
cx: &mut Context,
remote_endpoint: T,
local_endpoint: U,
) -> Result<(), ConnectError>
where
T: Into<IpEndpoint>,
U: Into<IpListenEndpoint>,
{
let remote_endpoint: IpEndpoint = remote_endpoint.into();
let local_endpoint: IpListenEndpoint = local_endpoint.into();
if self.is_open() {
return Err(ConnectError::InvalidState);
}
if remote_endpoint.port == 0 || remote_endpoint.addr.is_unspecified() {
return Err(ConnectError::Unaddressable);
}
if local_endpoint.port == 0 {
return Err(ConnectError::Unaddressable);
}
// If local address is not provided, choose it automatically.
let local_endpoint = IpEndpoint {
addr: match local_endpoint.addr {
Some(addr) => {
if addr.is_unspecified() {
return Err(ConnectError::Unaddressable);
}
addr
}
None => cx
.get_source_address(&remote_endpoint.addr)
.ok_or(ConnectError::Unaddressable)?,
},
port: local_endpoint.port,
};
if local_endpoint.addr.version() != remote_endpoint.addr.version() {
return Err(ConnectError::Unaddressable);
}
self.reset();
self.tuple = Some(Tuple {
local: local_endpoint,
remote: remote_endpoint,
});
self.set_state(State::SynSent);
let seq = Self::random_seq_no(cx);
self.local_seq_no = seq;
self.remote_last_seq = seq;
Ok(())
}
#[cfg(test)]
fn random_seq_no(_cx: &mut Context) -> TcpSeqNumber {
TcpSeqNumber(10000)
}
#[cfg(not(test))]
fn random_seq_no(cx: &mut Context) -> TcpSeqNumber {
TcpSeqNumber(cx.rand().rand_u32() as i32)
}
/// Close the transmit half of the full-duplex connection.
///
/// Note that there is no corresponding function for the receive half of the full-duplex
/// connection; only the remote end can close it. If you no longer wish to receive any
/// data and would like to reuse the socket right away, use [abort](#method.abort).
pub fn close(&mut self) {
match self.state {
// In the LISTEN state there is no established connection.
State::Listen => self.set_state(State::Closed),
// In the SYN-SENT state the remote endpoint is not yet synchronized and, upon
// receiving an RST, will abort the connection.