-
Notifications
You must be signed in to change notification settings - Fork 444
/
Copy pathtcp.rs
4598 lines (4214 loc) · 166 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. Consult RFC 7414 when implementing
// a new feature.
use core::{cmp, fmt, mem};
use {Error, Result};
use phy::DeviceCapabilities;
use time::{Duration, Instant};
use socket::{Socket, SocketMeta, SocketHandle, PollAt};
use storage::{Assembler, RingBuffer};
use wire::{IpProtocol, IpRepr, IpAddress, IpEndpoint, TcpSeqNumber, TcpRepr, TcpControl};
/// 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)]
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")
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Timer {
Idle {
keep_alive_at: Option<Instant>,
},
Retransmit {
expires_at: Instant,
delay: Duration
},
FastRetransmit,
Close {
expires_at: Instant
}
}
const RETRANSMIT_DELAY: Duration = Duration { millis: 100 };
const CLOSE_DELAY: Duration = Duration { millis: 10_000 };
impl Default for Timer {
fn default() -> Timer {
Timer::Idle { keep_alive_at: None }
}
}
impl Timer {
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) {
match *self {
Timer::Idle { ref mut keep_alive_at }
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>) {
match self {
&mut Timer::Idle { ref mut keep_alive_at } => {
*keep_alive_at = interval.map(|interval| timestamp + interval)
}
_ => ()
}
}
fn set_for_retransmit(&mut self, timestamp: Instant) {
match *self {
Timer::Idle { .. } | Timer::FastRetransmit { .. } => {
*self = Timer::Retransmit {
expires_at: timestamp + RETRANSMIT_DELAY,
delay: RETRANSMIT_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,
}
}
}
/// 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 TcpSocket<'a> {
pub(crate) meta: SocketMeta,
state: State,
timer: Timer,
assembler: Assembler,
rx_buffer: SocketBuffer<'a>,
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_address: IpAddress,
/// Current local endpoint. This is used for both filtering the incoming packets and
/// setting the source address. When listening or initiating connection on/from
/// an unspecified address, this field is updated with the chosen source address before
/// any packets are sent.
local_endpoint: IpEndpoint,
/// Current remote endpoint. This is used for both filtering the incoming packets and
/// setting the destination address. If the remote endpoint is unspecified, it means that
/// aborting the connection will not send an RST, and, in TIME-WAIT state, will not
/// send an ACK.
remote_endpoint: IpEndpoint,
/// 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 speculative remote window size.
/// I.e. the actual remote window size minus the count of in-flight octets.
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 recived, used for sACK
local_rx_last_seq: Option<TcpSeqNumber>,
/// The ACK number of the last packet recived.
local_rx_last_ack: Option<TcpSeqNumber>,
/// The number of packets recived directly after
/// each other which have the same ACK number.
local_rx_dup_acks: u8,
}
const DEFAULT_MSS: usize = 536;
impl<'a> TcpSocket<'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) -> TcpSocket<'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;
TcpSocket {
meta: SocketMeta::default(),
state: State::Closed,
timer: Timer::default(),
assembler: Assembler::new(rx_buffer.capacity()),
tx_buffer: tx_buffer,
rx_buffer: rx_buffer,
timeout: None,
keep_alive: None,
hop_limit: None,
listen_address: IpAddress::default(),
local_endpoint: IpEndpoint::default(),
remote_endpoint: IpEndpoint::default(),
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,
}
}
/// Return the socket handle.
#[inline]
pub fn handle(&self) -> SocketHandle {
self.meta.handle
}
/// Return the timeout duration.
///
/// See also the [set_timeout](#method.set_timeout) method.
pub fn timeout(&self) -> Option<Duration> {
self.timeout
}
/// 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
}
/// 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
}
/// 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 "challenge 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.
#[inline]
pub fn local_endpoint(&self) -> IpEndpoint {
self.local_endpoint
}
/// Return the remote endpoint.
#[inline]
pub fn remote_endpoint(&self) -> IpEndpoint {
self.remote_endpoint
}
/// 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::default();
self.assembler = Assembler::new(self.rx_buffer.capacity());
self.tx_buffer.clear();
self.rx_buffer.clear();
self.keep_alive = None;
self.timeout = None;
self.hop_limit = None;
self.listen_address = IpAddress::default();
self.local_endpoint = IpEndpoint::default();
self.remote_endpoint = IpEndpoint::default();
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;
}
/// Start listening on the given endpoint.
///
/// This function returns `Err(Error::Illegal)` 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<()>
where T: Into<IpEndpoint> {
let local_endpoint = local_endpoint.into();
if local_endpoint.port == 0 { return Err(Error::Unaddressable) }
if self.is_open() { return Err(Error::Illegal) }
self.reset();
self.listen_address = local_endpoint.addr;
self.local_endpoint = local_endpoint;
self.remote_endpoint = IpEndpoint::default();
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:
///
/// ```rust,ignore
/// socket.connect((IpAddress::v4(10, 0, 0, 1), 80), get_ephemeral_port())
/// ```
///
/// 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, remote_endpoint: T, local_endpoint: U) -> Result<()>
where T: Into<IpEndpoint>, U: Into<IpEndpoint> {
let remote_endpoint = remote_endpoint.into();
let local_endpoint = local_endpoint.into();
if self.is_open() { return Err(Error::Illegal) }
if !remote_endpoint.is_specified() { return Err(Error::Unaddressable) }
if local_endpoint.port == 0 { return Err(Error::Unaddressable) }
// If local address is not provided, use an unspecified address but a specified protocol.
// This lets us lower IpRepr later to determine IP header size and calculate MSS,
// but without committing to a specific address right away.
let local_addr = match remote_endpoint.addr {
IpAddress::Unspecified => return Err(Error::Unaddressable),
_ => remote_endpoint.addr.to_unspecified(),
};
let local_endpoint = IpEndpoint { addr: local_addr, ..local_endpoint };
// Carry over the local sequence number.
let local_seq_no = self.local_seq_no;
self.reset();
self.local_endpoint = local_endpoint;
self.remote_endpoint = remote_endpoint;
self.local_seq_no = local_seq_no;
self.remote_last_seq = local_seq_no;
self.set_state(State::SynSent);
Ok(())
}
/// 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.
State::SynSent =>
self.set_state(State::Closed),
// In the SYN-RECEIVED, ESTABLISHED and CLOSE-WAIT states the transmit half
// of the connection is open, and needs to be explicitly closed with a FIN.
State::SynReceived | State::Established =>
self.set_state(State::FinWait1),
State::CloseWait =>
self.set_state(State::LastAck),
// In the FIN-WAIT-1, FIN-WAIT-2, CLOSING, LAST-ACK, TIME-WAIT and CLOSED states,
// the transmit half of the connection is already closed, and no further
// action is needed.
State::FinWait1 | State::FinWait2 | State::Closing |
State::TimeWait | State::LastAck | State::Closed => ()
}
}
/// Aborts the connection, if any.
///
/// This function instantly closes the socket. One reset packet will be sent to the remote
/// endpoint.
///
/// In terms of the TCP state machine, the socket may be in any state and is moved to
/// the `CLOSED` state.
pub fn abort(&mut self) {
self.set_state(State::Closed);
}
/// Return whether the socket is passively listening for incoming connections.
///
/// In terms of the TCP state machine, the socket must be in the `LISTEN` state.
#[inline]
pub fn is_listening(&self) -> bool {
match self.state {
State::Listen => true,
_ => false
}
}
/// Return whether the socket is open.
///
/// This function returns true if the socket will process incoming or dispatch outgoing
/// packets. Note that this does not mean that it is possible to send or receive data through
/// the socket; for that, use [can_send](#method.can_send) or [can_recv](#method.can_recv).
///
/// In terms of the TCP state machine, the socket must not be in the `CLOSED`
/// or `TIME-WAIT` states.
#[inline]
pub fn is_open(&self) -> bool {
match self.state {
State::Closed => false,
State::TimeWait => false,
_ => true
}
}
/// Return whether a connection is active.
///
/// This function returns true if the socket is actively exchanging packets with
/// a remote endpoint. Note that this does not mean that it is possible to send or receive
/// data through the socket; for that, use [can_send](#method.can_send) or
/// [can_recv](#method.can_recv).
///
/// If a connection is established, [abort](#method.close) will send a reset to
/// the remote endpoint.
///
/// In terms of the TCP state machine, the socket must be in the `CLOSED`, `TIME-WAIT`,
/// or `LISTEN` state.
#[inline]
pub fn is_active(&self) -> bool {
match self.state {
State::Closed => false,
State::TimeWait => false,
State::Listen => false,
_ => true
}
}
/// Return whether the transmit half of the full-duplex connection is open.
///
/// This function returns true if it's possible to send data and have it arrive
/// to the remote endpoint. However, it does not make any guarantees about the state
/// of the transmit buffer, and even if it returns true, [send](#method.send) may
/// not be able to enqueue any octets.
///
/// In terms of the TCP state machine, the socket must be in the `ESTABLISHED` or
/// `CLOSE-WAIT` state.
#[inline]
pub fn may_send(&self) -> bool {
match self.state {
State::Established => true,
// In CLOSE-WAIT, the remote endpoint has closed our receive half of the connection
// but we still can transmit indefinitely.
State::CloseWait => true,
_ => false
}
}
/// Return whether the receive half of the full-duplex connection is open.
///
/// This function returns true if it's possible to receive data from the remote endpoint.
/// It will return true while there is data in the receive buffer, and if there isn't,
/// as long as the remote endpoint has not closed the connection.
///
/// In terms of the TCP state machine, the socket must be in the `ESTABLISHED`,
/// `FIN-WAIT-1`, or `FIN-WAIT-2` state, or have data in the receive buffer instead.
#[inline]
pub fn may_recv(&self) -> bool {
match self.state {
State::Established => true,
// In FIN-WAIT-1/2, we have closed our transmit half of the connection but
// we still can receive indefinitely.
State::FinWait1 | State::FinWait2 => true,
// If we have something in the receive buffer, we can receive that.
_ if self.rx_buffer.len() > 0 => true,
_ => false
}
}
/// Check whether the transmit half of the full-duplex connection is open
/// (see [may_send](#method.may_send), and the transmit buffer is not full.
#[inline]
pub fn can_send(&self) -> bool {
if !self.may_send() { return false }
!self.tx_buffer.is_full()
}
/// Return the maximum number of bytes inside the recv buffer.
#[inline]
pub fn recv_capacity(&self) -> usize {
self.rx_buffer.capacity()
}
/// Return the maximum number of bytes inside the transmit buffer.
#[inline]
pub fn send_capacity(&self) -> usize {
self.tx_buffer.capacity()
}
/// Check whether the receive half of the full-duplex connection buffer is open
/// (see [may_recv](#method.may_recv), and the receive buffer is not empty.
#[inline]
pub fn can_recv(&self) -> bool {
if !self.may_recv() { return false }
!self.rx_buffer.is_empty()
}
fn send_impl<'b, F, R>(&'b mut self, f: F) -> Result<R>
where F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R) {
if !self.may_send() { return Err(Error::Illegal) }
// The connection might have been idle for a long time, and so remote_last_ts
// would be far in the past. Unless we clear it here, we'll abort the connection
// down over in dispatch() by erroneously detecting it as timed out.
if self.tx_buffer.is_empty() { self.remote_last_ts = None }
let _old_length = self.tx_buffer.len();
let (size, result) = f(&mut self.tx_buffer);
if size > 0 {
#[cfg(any(test, feature = "verbose"))]
net_trace!("{}:{}:{}: tx buffer: enqueueing {} octets (now {})",
self.meta.handle, self.local_endpoint, self.remote_endpoint,
size, _old_length + size);
}
Ok(result)
}
/// Call `f` with the largest contiguous slice of octets in the transmit buffer,
/// and enqueue the amount of elements returned by `f`.
///
/// This function returns `Err(Error::Illegal) if the transmit half of
/// the connection is not open; see [may_send](#method.may_send).
pub fn send<'b, F, R>(&'b mut self, f: F) -> Result<R>
where F: FnOnce(&'b mut [u8]) -> (usize, R) {
self.send_impl(|tx_buffer| {
tx_buffer.enqueue_many_with(f)
})
}
/// Enqueue a sequence of octets to be sent, and fill it from a slice.
///
/// This function returns the amount of octets actually enqueued, which is limited
/// by the amount of free space in the transmit buffer; down to zero.
///
/// See also [send](#method.send).
pub fn send_slice(&mut self, data: &[u8]) -> Result<usize> {
self.send_impl(|tx_buffer| {
let size = tx_buffer.enqueue_slice(data);
(size, size)
})
}
fn recv_impl<'b, F, R>(&'b mut self, f: F) -> Result<R>
where F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R) {
// We may have received some data inside the initial SYN, but until the connection
// is fully open we must not dequeue any data, as it may be overwritten by e.g.
// another (stale) SYN. (We do not support TCP Fast Open.)
if !self.may_recv() { return Err(Error::Illegal) }
let _old_length = self.rx_buffer.len();
let (size, result) = f(&mut self.rx_buffer);
self.remote_seq_no += size;
if size > 0 {
#[cfg(any(test, feature = "verbose"))]
net_trace!("{}:{}:{}: rx buffer: dequeueing {} octets (now {})",
self.meta.handle, self.local_endpoint, self.remote_endpoint,
size, _old_length - size);
}
Ok(result)
}
/// Call `f` with the largest contiguous slice of octets in the receive buffer,
/// and dequeue the amount of elements returned by `f`.
///
/// This function returns `Err(Error::Illegal)` if the receive half of
/// the connection is not open; see [may_recv](#method.may_recv).
pub fn recv<'b, F, R>(&'b mut self, f: F) -> Result<R>
where F: FnOnce(&'b mut [u8]) -> (usize, R) {
self.recv_impl(|rx_buffer| {
rx_buffer.dequeue_many_with(f)
})
}
/// Dequeue a sequence of received octets, and fill a slice from it.
///
/// This function returns the amount of octets actually dequeued, which is limited
/// by the amount of occupied space in the receive buffer; down to zero.
///
/// See also [recv](#method.recv).
pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize> {
self.recv_impl(|rx_buffer| {
let size = rx_buffer.dequeue_slice(data);
(size, size)
})
}
/// Peek at a sequence of received octets without removing them from
/// the receive buffer, and return a pointer to it.
///
/// This function otherwise behaves identically to [recv](#method.recv).
pub fn peek(&mut self, size: usize) -> Result<&[u8]> {
// See recv() above.
if !self.may_recv() { return Err(Error::Illegal) }
let buffer = self.rx_buffer.get_allocated(0, size);
if buffer.len() > 0 {
#[cfg(any(test, feature = "verbose"))]
net_trace!("{}:{}:{}: rx buffer: peeking at {} octets",
self.meta.handle, self.local_endpoint, self.remote_endpoint,
buffer.len());
}
Ok(buffer)
}
/// Peek at a sequence of received octets without removing them from
/// the receive buffer, and fill a slice from it.
///
/// This function otherwise behaves identically to [recv_slice](#method.recv_slice).
pub fn peek_slice(&mut self, data: &mut [u8]) -> Result<usize> {
let buffer = self.peek(data.len())?;
let data = &mut data[..buffer.len()];
data.copy_from_slice(buffer);
Ok(buffer.len())
}
/// Return the amount of octets queued in the transmit buffer.
///
/// Note that the Berkeley sockets interface does not have an equivalent of this API.
pub fn send_queue(&self) -> usize {
self.tx_buffer.len()
}
/// Return the amount of octets queued in the receive buffer. This value can be larger than
/// the slice read by the next `recv` or `peek` call because it includes all queued octets,
/// and not only the octets that may be returned as a contiguous slice.
///
/// Note that the Berkeley sockets interface does not have an equivalent of this API.
pub fn recv_queue(&self) -> usize {
self.rx_buffer.len()
}
fn set_state(&mut self, state: State) {
if self.state != state {
if self.remote_endpoint.addr.is_unspecified() {
net_trace!("{}:{}: state={}=>{}",
self.meta.handle, self.local_endpoint,
self.state, state);
} else {
net_trace!("{}:{}:{}: state={}=>{}",
self.meta.handle, self.local_endpoint, self.remote_endpoint,
self.state, state);
}
}
self.state = state
}
pub(crate) fn reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
let reply_repr = TcpRepr {
src_port: repr.dst_port,
dst_port: repr.src_port,
control: TcpControl::None,
seq_number: TcpSeqNumber(0),
ack_number: None,
window_len: 0,
window_scale: None,
max_seg_size: None,
sack_permitted: false,
sack_ranges: [None, None, None],
payload: &[]
};
let ip_reply_repr = IpRepr::Unspecified {
src_addr: ip_repr.dst_addr(),
dst_addr: ip_repr.src_addr(),
protocol: IpProtocol::Tcp,
payload_len: reply_repr.buffer_len(),
hop_limit: 64
};
(ip_reply_repr, reply_repr)
}
pub(crate) fn rst_reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
debug_assert!(repr.control != TcpControl::Rst);
let (ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
// See https://www.snellman.net/blog/archive/2016-02-01-tcp-rst/ for explanation
// of why we sometimes send an RST and sometimes an RST|ACK
reply_repr.control = TcpControl::Rst;
reply_repr.seq_number = repr.ack_number.unwrap_or_default();
if repr.control == TcpControl::Syn {
reply_repr.ack_number = Some(repr.seq_number + repr.segment_len());
}
(ip_reply_repr, reply_repr)
}
fn ack_reply(&mut self, ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
let (mut ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
// From RFC 793:
// [...] an empty acknowledgment segment containing the current send-sequence number
// and an acknowledgment indicating the next sequence number expected
// to be received.
reply_repr.seq_number = self.remote_last_seq;
reply_repr.ack_number = self.remote_last_ack;
// From RFC 1323:
// The window field [...] of every outgoing segment, with the exception of SYN
// segments, is right-shifted by [advertised scale value] bits[...]
reply_repr.window_len = self.scaled_window();
self.remote_last_win = reply_repr.window_len;
// If the remote supports selective acknowledgement, add the option to the outgoing
// segment.
if self.remote_has_sack {
net_debug!("sending sACK option with current assembler ranges");
// RFC 2018: The first SACK block (i.e., the one immediately following the kind and
// length fields in the option) MUST specify the contiguous block of data containing
// the segment which triggered this ACK, unless that segment advanced the
// Acknowledgment Number field in the header.
reply_repr.sack_ranges[0] = None;
if let Some(last_seg_seq) = self.local_rx_last_seq.map(|s| s.0 as u32) {
reply_repr.sack_ranges[0] = self.assembler.iter_data(
reply_repr.ack_number.map(|s| s.0 as usize).unwrap_or(0))
.map(|(left, right)| (left as u32, right as u32))
.skip_while(|(left, right)| *left > last_seg_seq || *right < last_seg_seq)
.next();
}
if reply_repr.sack_ranges[0].is_none() {
// The matching segment was removed from the assembler, meaning the acknowledgement
// number has advanced, or there was no previous sACK.
//
// While the RFC says we SHOULD keep a list of reported sACK ranges, and iterate
// through those, that is currently infeasable. Instead, we offer the range with
// the lowest sequence number (if one exists) to hint at what segments would
// most quickly advance the acknowledgement number.
reply_repr.sack_ranges[0] = self.assembler.iter_data(
reply_repr.ack_number.map(|s| s.0 as usize).unwrap_or(0))
.map(|(left, right)| (left as u32, right as u32))
.next();
}
}
// Since the sACK option may have changed the length of the payload, update that.
ip_reply_repr.set_payload_len(reply_repr.buffer_len());
(ip_reply_repr, reply_repr)
}
pub(crate) fn accepts(&self, ip_repr: &IpRepr, repr: &TcpRepr) -> bool {
if self.state == State::Closed { return false }
// If we're still listening for SYNs and the packet has an ACK, it cannot
// be destined to this socket, but another one may well listen on the same
// local endpoint.
if self.state == State::Listen && repr.ack_number.is_some() { return false }
// Reject packets with a wrong destination.
if self.local_endpoint.port != repr.dst_port { return false }
if !self.local_endpoint.addr.is_unspecified() &&
self.local_endpoint.addr != ip_repr.dst_addr() { return false }
// Reject packets from a source to which we aren't connected.
if self.remote_endpoint.port != 0 &&
self.remote_endpoint.port != repr.src_port { return false }
if !self.remote_endpoint.addr.is_unspecified() &&
self.remote_endpoint.addr != ip_repr.src_addr() { return false }
true
}
pub(crate) fn process(&mut self, timestamp: Instant, ip_repr: &IpRepr, repr: &TcpRepr) ->
Result<Option<(IpRepr, TcpRepr<'static>)>> {
debug_assert!(self.accepts(ip_repr, repr));
// Consider how much the sequence number space differs from the transmit buffer space.
let (sent_syn, sent_fin) = match self.state {
// In SYN-SENT or SYN-RECEIVED, we've just sent a SYN.
State::SynSent | State::SynReceived => (true, false),
// In FIN-WAIT-1, LAST-ACK, or CLOSING, we've just sent a FIN.
State::FinWait1 | State::LastAck | State::Closing => (false, true),
// In all other states we've already got acknowledgemetns for
// all of the control flags we sent.
_ => (false, false)
};
let control_len = (sent_syn as usize) + (sent_fin as usize);
// Reject unacceptable acknowledgements.
match (self.state, repr) {
// An RST received in response to initial SYN is acceptable if it acknowledges
// the initial SYN.
(State::SynSent, &TcpRepr {
control: TcpControl::Rst, ack_number: None, ..
}) => {
net_debug!("{}:{}:{}: unacceptable RST (expecting RST|ACK) \
in response to initial SYN",
self.meta.handle, self.local_endpoint, self.remote_endpoint);
return Err(Error::Dropped)
}
(State::SynSent, &TcpRepr {
control: TcpControl::Rst, ack_number: Some(ack_number), ..
}) => {
if ack_number != self.local_seq_no + 1 {
net_debug!("{}:{}:{}: unacceptable RST|ACK in response to initial SYN",
self.meta.handle, self.local_endpoint, self.remote_endpoint);
return Err(Error::Dropped)
}
}
// Any other RST need only have a valid sequence number.
(_, &TcpRepr { control: TcpControl::Rst, .. }) => (),
// The initial SYN cannot contain an acknowledgement.
(State::Listen, &TcpRepr { ack_number: None, .. }) => (),
// This case is handled above.
(State::Listen, &TcpRepr { ack_number: Some(_), .. }) => unreachable!(),
// Every packet after the initial SYN must be an acknowledgement.
(_, &TcpRepr { ack_number: None, .. }) => {
net_debug!("{}:{}:{}: expecting an ACK",
self.meta.handle, self.local_endpoint, self.remote_endpoint);
return Err(Error::Dropped)
}
// Every acknowledgement must be for transmitted but unacknowledged data.
(_, &TcpRepr { ack_number: Some(ack_number), .. }) => {
let unacknowledged = self.tx_buffer.len() + control_len;
if ack_number < self.local_seq_no {
net_debug!("{}:{}:{}: duplicate ACK ({} not in {}...{})",
self.meta.handle, self.local_endpoint, self.remote_endpoint,
ack_number, self.local_seq_no, self.local_seq_no + unacknowledged);
return Err(Error::Dropped)
}
if ack_number > self.local_seq_no + unacknowledged {
net_debug!("{}:{}:{}: unacceptable ACK ({} not in {}...{})",
self.meta.handle, self.local_endpoint, self.remote_endpoint,
ack_number, self.local_seq_no, self.local_seq_no + unacknowledged);
return Ok(Some(self.ack_reply(ip_repr, &repr)))
}
}
}
let window_start = self.remote_seq_no + self.rx_buffer.len();
let window_end = self.remote_seq_no + self.rx_buffer.capacity();
let segment_start = repr.seq_number;