-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathtcb.rs
More file actions
451 lines (400 loc) · 16.8 KB
/
tcb.rs
File metadata and controls
451 lines (400 loc) · 16.8 KB
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
use super::seqnum::SeqNum;
use etherparse::TcpHeader;
use std::collections::BTreeMap;
const MAX_UNACK: u32 = 1024 * 16; // 16KB
const READ_BUFFER_SIZE: usize = 1024 * 16; // 16KB
const MAX_COUNT_FOR_DUP_ACK: usize = 3; // Maximum number of duplicate ACKs before retransmission
/// Retransmission timeout
const RTO: std::time::Duration = std::time::Duration::from_secs(1);
/// Maximum count of retransmissions before dropping the packet
pub(crate) const MAX_RETRANSMIT_COUNT: usize = 3;
#[derive(Debug, PartialEq, Clone, Copy)]
pub(crate) enum TcpState {
// Init, /* Since we always act as a server, it starts from `Listen`, so we don't use states Init & SynSent. */
// SynSent,
Listen,
SynReceived,
Established,
FinWait1, // act as a client, actively send a farewell packet to the other side, followed with FinWait2, TimeWait, Closed
FinWait2,
TimeWait,
CloseWait, // act as a server, followed with LastAck, Closed
LastAck,
Closed,
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub(super) enum PacketType {
WindowUpdate,
Invalid,
RetransmissionRequest,
NewPacket,
Ack,
KeepAlive,
}
/// TCP Control Block
/// - `inflight_packets` is prerepresented bytes stream from upstream application,
/// which have been sent to the lower device but not yet acknowledged.
/// - `unordered_packets` is the bytes stream received from the lower device,
/// which can be acknowledged and extracted by `consume_unordered_packets` method
/// then can be read by upstream application via `Tcp::poll_read` method.
/// - `ordered_packets` is the list of contiguous packets ready to be read by the application.
#[derive(Debug, Clone)]
pub(crate) struct Tcb {
seq: SeqNum,
ack: SeqNum,
mtu: u16,
last_received_ack: SeqNum,
send_window: u16,
state: TcpState,
inflight_packets: BTreeMap<SeqNum, InflightPacket>,
unordered_packets: BTreeMap<SeqNum, Vec<u8>>,
ordered_packets: Vec<Vec<u8>>,
duplicate_ack_count: usize,
duplicate_ack_count_helper: SeqNum,
}
impl Tcb {
pub(super) fn new(ack: SeqNum, mtu: u16) -> Tcb {
#[cfg(debug_assertions)]
let seq = 100;
#[cfg(not(debug_assertions))]
let seq = rand::Rng::random::<u32>(&mut rand::rng());
Tcb {
seq: seq.into(),
ack,
mtu,
last_received_ack: seq.into(),
send_window: u16::MAX,
state: TcpState::Listen,
inflight_packets: BTreeMap::new(),
unordered_packets: BTreeMap::new(),
ordered_packets: Vec::new(),
duplicate_ack_count: 0,
duplicate_ack_count_helper: seq.into(),
}
}
pub fn calculate_payload_max_len(&self, ip_header_size: usize, tcp_header_size: usize) -> usize {
let send_window = self.get_send_window() as usize;
let mtu = self.get_mtu() as usize;
std::cmp::min(send_window, mtu.saturating_sub(ip_header_size + tcp_header_size))
}
pub fn update_duplicate_ack_count(&mut self, rcvd_ack: SeqNum) {
// If the received rcvd_ack is the same as duplicate_ack_count_helper and not all data has been acknowledged (rcvd_ack < self.seq), increment the count.
if rcvd_ack == self.duplicate_ack_count_helper && rcvd_ack < self.seq {
self.duplicate_ack_count = self.duplicate_ack_count.saturating_add(1);
} else {
self.duplicate_ack_count_helper = rcvd_ack;
self.duplicate_ack_count = 0; // reset duplicate ACK count
}
}
pub fn is_duplicate_ack_count_exceeded(&self) -> bool {
self.duplicate_ack_count >= MAX_COUNT_FOR_DUP_ACK
}
pub(super) fn add_unordered_packet(&mut self, seq: SeqNum, buf: Vec<u8>) {
if seq < self.ack {
#[rustfmt::skip]
log::warn!("{:?}: Received packet seq {seq} < self ack {}, len = {}", self.state, self.ack, buf.len());
return;
}
self.unordered_packets.insert(seq, buf);
}
pub(super) fn get_available_read_buffer_size(&self) -> usize {
let total_buffered = self.get_unordered_packets_total_len() + self.get_ordered_packets_total_len();
READ_BUFFER_SIZE.saturating_sub(total_buffered)
}
#[inline]
pub(crate) fn get_unordered_packets_total_len(&self) -> usize {
self.unordered_packets.values().map(|p| p.len()).sum()
}
#[inline]
pub(crate) fn get_ordered_packets_total_len(&self) -> usize {
self.ordered_packets.iter().map(|p| p.len()).sum()
}
pub(super) fn consume_unordered_packets(&mut self) {
while let Some(seq) = self.unordered_packets.keys().next().copied() {
if seq != self.ack {
break; // sequence number is not continuous, stop extracting
}
// remove and get the first packet
let payload = self.unordered_packets.remove(&seq).unwrap();
let payload_len = payload.len();
// Move the packet to ordered_packets
self.ordered_packets.push(payload);
self.ack += payload_len as u32;
}
}
pub(super) fn pop_ordered_packet(&mut self) -> Option<Vec<u8>> {
if self.ordered_packets.is_empty() {
None
} else {
Some(self.ordered_packets.remove(0))
}
}
pub(super) fn increase_seq(&mut self) {
self.seq += 1;
}
pub(super) fn get_seq(&self) -> SeqNum {
self.seq
}
pub(super) fn increase_ack(&mut self) {
self.ack += 1;
}
pub(super) fn get_ack(&self) -> SeqNum {
self.ack
}
pub(super) fn get_mtu(&self) -> u16 {
self.mtu
}
pub(super) fn get_last_received_ack(&self) -> SeqNum {
self.last_received_ack
}
pub(super) fn change_state(&mut self, state: TcpState) {
self.state = state;
}
pub(super) fn get_state(&self) -> TcpState {
self.state
}
pub(super) fn update_send_window(&mut self, window: u16) {
self.send_window = window;
}
pub(super) fn get_send_window(&self) -> u16 {
self.send_window
}
pub(super) fn get_recv_window(&self) -> u16 {
self.get_available_read_buffer_size().try_into().unwrap_or(u16::MAX)
}
// #[inline(always)]
// pub(super) fn buffer_size(&self, payload_len: u16) -> u16 {
// match MAX_UNACK - self.inflight_packets.len() as u32 {
// // b if b.saturating_sub(payload_len as u32 + 64) != 0 => payload_len,
// // b if b < 128 && b >= 4 => (b / 2) as u16,
// // b if b < 4 => b as u16,
// // b => (b - 64) as u16,
// b if b >= payload_len as u32 * 2 && b > 0 => payload_len,
// b if b < 4 => b as u16,
// b => (b / 2) as u16,
// }
// }
pub(super) fn check_pkt_type(&self, tcp_header: &TcpHeader, payload: &[u8]) -> PacketType {
let rcvd_ack = SeqNum(tcp_header.acknowledgment_number);
let rcvd_seq = SeqNum(tcp_header.sequence_number);
let rcvd_window = tcp_header.window_size;
let len = payload.len();
let res = if rcvd_ack > self.seq {
PacketType::Invalid
} else {
match rcvd_ack.cmp(&self.get_last_received_ack()) {
std::cmp::Ordering::Less => PacketType::Invalid,
std::cmp::Ordering::Equal => {
if self.ack - 1 == rcvd_seq && payload.len() <= 1 {
PacketType::KeepAlive
} else if !payload.is_empty() {
PacketType::NewPacket
} else if self.get_send_window() == rcvd_window && self.seq != rcvd_ack && self.is_duplicate_ack_count_exceeded() {
PacketType::RetransmissionRequest
} else {
PacketType::WindowUpdate
}
}
std::cmp::Ordering::Greater => {
if payload.is_empty() {
PacketType::Ack
} else {
PacketType::NewPacket
}
}
}
};
#[rustfmt::skip]
log::trace!("received {{ ack = {:08X?}, seq = {:08X?}, window = {rcvd_window} }}, self {{ ack = {:08X?}, seq = {:08X?}, send_window = {} }}, len = {len}, {res:?}", rcvd_ack.0, rcvd_seq.0, self.ack.0, self.seq.0, self.get_send_window());
res
}
pub(super) fn add_inflight_packet(&mut self, buf: Vec<u8>) -> std::io::Result<()> {
if buf.is_empty() {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "Empty payload"));
}
let buf_len = buf.len() as u32;
self.inflight_packets.insert(self.seq, InflightPacket::new(self.seq, buf));
self.seq += buf_len;
Ok(())
}
pub(super) fn update_last_received_ack(&mut self, ack: SeqNum) {
self.last_received_ack = ack;
}
pub(crate) fn update_inflight_packet_queue(&mut self, ack: SeqNum) {
match self.inflight_packets.first_key_value() {
None => return,
Some((&seq, _)) if ack < seq => return,
_ => {}
}
if let Some(seq) = self
.inflight_packets
.iter()
.find(|(_, p)| p.contains_seq_num(ack - 1))
.map(|(&s, _)| s)
{
let mut inflight_packet = self.inflight_packets.remove(&seq).unwrap();
let distance = ack.distance(inflight_packet.seq) as usize;
if distance < inflight_packet.payload.len() {
inflight_packet.payload.drain(0..distance);
inflight_packet.seq = ack;
self.inflight_packets.insert(ack, inflight_packet);
}
}
self.inflight_packets.retain(|_, p| ack < p.seq + p.payload.len() as u32);
}
pub(crate) fn find_inflight_packet(&self, seq: SeqNum) -> Option<&InflightPacket> {
self.inflight_packets.get(&seq)
}
#[must_use]
pub(crate) fn collect_timed_out_inflight_packets(&mut self) -> Vec<InflightPacket> {
let mut retransmit_list = Vec::new();
self.inflight_packets.retain(|_, packet| {
if packet.retransmit_count >= MAX_RETRANSMIT_COUNT {
log::warn!("Packet with seq {:?} reached max retransmit count, dropping packet", packet.seq);
return false; // remove this packet
}
if packet.is_timed_out() {
packet.retransmit_count += 1;
packet.retransmit_timeout *= 2; // increase timeout exponentially
packet.send_time = std::time::Instant::now();
retransmit_list.push(packet.clone());
}
true // keep the packet in the inflight_packets
});
retransmit_list
}
pub(crate) fn get_inflight_packets_total_len(&self) -> usize {
self.inflight_packets.values().map(|p| p.payload.len()).sum()
}
#[allow(dead_code)]
pub(crate) fn get_all_inflight_packets(&self) -> Vec<&InflightPacket> {
self.inflight_packets.values().collect::<Vec<_>>()
}
pub fn is_send_buffer_full(&self) -> bool {
// To respect the receiver's window (remote_window) size and avoid sending too many unacknowledged packets, which may cause packet loss
// Simplified version: min(cwnd, rwnd)
self.seq.distance(self.get_last_received_ack()) >= MAX_UNACK.min(self.get_send_window() as u32)
}
}
#[derive(Debug, Clone)]
pub struct InflightPacket {
pub seq: SeqNum,
pub payload: Vec<u8>,
pub send_time: std::time::Instant,
pub retransmit_count: usize,
pub retransmit_timeout: std::time::Duration, // current retransmission timeout
}
impl InflightPacket {
fn new(seq: SeqNum, payload: Vec<u8>) -> Self {
Self {
seq,
payload,
send_time: std::time::Instant::now(),
retransmit_count: 0,
retransmit_timeout: RTO,
}
}
pub(crate) fn contains_seq_num(&self, seq: SeqNum) -> bool {
self.seq <= seq && seq < self.seq + self.payload.len() as u32
}
pub(crate) fn is_timed_out(&self) -> bool {
self.send_time.elapsed() >= self.retransmit_timeout
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_in_flight_packet() {
let p = InflightPacket::new((u32::MAX - 1).into(), vec![10, 20, 30, 40, 50]);
assert!(p.contains_seq_num((u32::MAX - 1).into()));
assert!(p.contains_seq_num(u32::MAX.into()));
assert!(p.contains_seq_num(0.into()));
assert!(p.contains_seq_num(1.into()));
assert!(p.contains_seq_num(2.into()));
assert!(!p.contains_seq_num(3.into()));
}
#[test]
fn test_get_unordered_packets_with_max_bytes() {
let mut tcb = Tcb::new(SeqNum(1000), 1500);
// insert 3 consecutive packets
tcb.add_unordered_packet(SeqNum(1000), vec![1; 500]); // seq=1000, len=500
tcb.add_unordered_packet(SeqNum(1500), vec![2; 500]); // seq=1500, len=500
tcb.add_unordered_packet(SeqNum(2000), vec![3; 500]); // seq=2000, len=500
// test 1: consume contiguous packets
tcb.consume_unordered_packets();
assert_eq!(tcb.ack, SeqNum(2500)); // ack increased by 1500
assert_eq!(tcb.unordered_packets.len(), 0); // all packets consumed
assert_eq!(tcb.ordered_packets.len(), 3); // three packets in ordered list
// test 2: pop first ordered packet
let data = tcb.pop_ordered_packet().unwrap();
assert_eq!(data.len(), 500);
assert_eq!(data, vec![1; 500]);
assert_eq!(tcb.ordered_packets.len(), 2);
// test 3: pop second ordered packet
let data = tcb.pop_ordered_packet().unwrap();
assert_eq!(data.len(), 500);
assert_eq!(data, vec![2; 500]);
assert_eq!(tcb.ordered_packets.len(), 1);
// test 4: pop third ordered packet
let data = tcb.pop_ordered_packet().unwrap();
assert_eq!(data.len(), 500);
assert_eq!(data, vec![3; 500]);
assert_eq!(tcb.ordered_packets.len(), 0);
// test 5: no more data to extract
let data = tcb.pop_ordered_packet();
assert!(data.is_none());
}
#[test]
fn test_update_inflight_packet_queue() {
let mut tcb = Tcb::new(SeqNum(1000), 1500);
tcb.seq = SeqNum(100); // setting the initial seq
// insert 3 consecutive packets
tcb.add_inflight_packet(vec![1; 500]).unwrap(); // seq=100, len=500
tcb.add_inflight_packet(vec![2; 500]).unwrap(); // seq=600, len=500
tcb.add_inflight_packet(vec![3; 500]).unwrap(); // seq=1100, len=500
// test 1: confirm partial packets (ack=800)
tcb.update_inflight_packet_queue(SeqNum(800));
assert_eq!(tcb.inflight_packets.len(), 2); // remaining two packets
let first_packet = tcb.inflight_packets.first_key_value().unwrap().1;
assert_eq!(first_packet.seq, SeqNum(800)); // the remaining part of the first packet
assert_eq!(first_packet.payload.len(), 300); // remaining 300 bytes in the first packet
let second_packet = tcb.inflight_packets.last_key_value().unwrap().1;
assert_eq!(second_packet.seq, SeqNum(1100)); // no change in the second packet
// test 2: confirm all packets (ack=2000)
tcb.update_inflight_packet_queue(SeqNum(2000));
assert_eq!(tcb.inflight_packets.len(), 0); // all packets are acknowledged
}
#[test]
fn test_update_inflight_packet_queue_cumulative_ack() {
let mut tcb = Tcb::new(SeqNum(1000), 1500);
tcb.seq = SeqNum(1000);
// Insert 3 consecutive packets
tcb.add_inflight_packet(vec![1; 500]).unwrap(); // seq=1000, len=500
tcb.add_inflight_packet(vec![2; 500]).unwrap(); // seq=1500, len=500
tcb.add_inflight_packet(vec![3; 500]).unwrap(); // seq=2000, len=500
// Emulate cumulative ACK: ack=2500
tcb.update_inflight_packet_queue(SeqNum(2500));
assert_eq!(tcb.inflight_packets.len(), 0); // all packets should be removed
}
#[test]
fn test_retransmit_with_exponential_backoff() {
let mut tcb = Tcb::new(SeqNum(1000), 1500);
tcb.add_inflight_packet(vec![1; 500]).unwrap();
// Simulate retransmission timeouts
for i in 0..MAX_RETRANSMIT_COUNT {
// Simulate a timeout for the first packet
let timeout = tcb.inflight_packets.values().next().unwrap().retransmit_timeout + std::time::Duration::from_millis(100);
println!("timeout: {timeout:?}");
std::thread::sleep(timeout);
let packets = tcb.collect_timed_out_inflight_packets();
assert_eq!(packets.len(), 1);
let packet = &packets[0];
assert_eq!(packet.retransmit_count, i + 1);
assert!(packet.retransmit_timeout > RTO);
}
let packets = tcb.collect_timed_out_inflight_packets();
assert!(packets.is_empty());
assert!(tcb.inflight_packets.is_empty());
}
}