-
Notifications
You must be signed in to change notification settings - Fork 120
/
passive_open.rs
366 lines (340 loc) · 11.2 KB
/
passive_open.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
use super::{
constants::FALLBACK_MSS,
established::ControlBlock,
isn_generator::IsnGenerator,
};
use crate::{
inetstack::protocols::{
arp::ArpPeer,
ethernet2::{
EtherType2,
Ethernet2Header,
},
ip::IpProtocol,
ipv4::Ipv4Header,
tcp::{
established::{
congestion_control,
congestion_control::CongestionControl,
},
segment::{
TcpHeader,
TcpOptions2,
TcpSegment,
},
SeqNumber,
},
},
runtime::{
fail::Fail,
network::{
config::TcpConfig,
types::MacAddress,
NetworkRuntime,
},
queue::BackgroundTask,
timer::TimerRc,
},
scheduler::{
Scheduler,
TaskHandle,
},
};
use ::libc::{
EBADMSG,
ECONNREFUSED,
ETIMEDOUT,
};
use ::std::{
cell::RefCell,
collections::{
HashMap,
HashSet,
VecDeque,
},
convert::TryInto,
future::Future,
net::SocketAddrV4,
rc::Rc,
task::{
Context,
Poll,
Waker,
},
time::Duration,
};
struct InflightAccept {
local_isn: SeqNumber,
remote_isn: SeqNumber,
header_window_size: u16,
remote_window_scale: Option<u8>,
mss: usize,
#[allow(unused)]
handle: TaskHandle,
}
struct ReadySockets<const N: usize> {
ready: VecDeque<Result<ControlBlock<N>, Fail>>,
endpoints: HashSet<SocketAddrV4>,
waker: Option<Waker>,
}
impl<const N: usize> ReadySockets<N> {
fn push_ok(&mut self, cb: ControlBlock<N>) {
assert!(self.endpoints.insert(cb.get_remote()));
self.ready.push_back(Ok(cb));
if let Some(w) = self.waker.take() {
w.wake()
}
}
fn push_err(&mut self, err: Fail) {
self.ready.push_back(Err(err));
if let Some(w) = self.waker.take() {
w.wake()
}
}
fn poll(&mut self, ctx: &mut Context) -> Poll<Result<ControlBlock<N>, Fail>> {
let r = match self.ready.pop_front() {
Some(r) => r,
None => {
self.waker.replace(ctx.waker().clone());
return Poll::Pending;
},
};
if let Ok(ref cb) = r {
assert!(self.endpoints.remove(&cb.get_remote()));
}
Poll::Ready(r)
}
fn len(&self) -> usize {
self.ready.len()
}
}
pub struct PassiveSocket<const N: usize> {
inflight: HashMap<SocketAddrV4, InflightAccept>,
ready: Rc<RefCell<ReadySockets<N>>>,
max_backlog: usize,
isn_generator: IsnGenerator,
local: SocketAddrV4,
rt: Rc<dyn NetworkRuntime<N>>,
scheduler: Scheduler,
clock: TimerRc,
tcp_config: TcpConfig,
local_link_addr: MacAddress,
arp: ArpPeer<N>,
}
impl<const N: usize> PassiveSocket<N> {
pub fn new(
local: SocketAddrV4,
max_backlog: usize,
rt: Rc<dyn NetworkRuntime<N>>,
scheduler: Scheduler,
clock: TimerRc,
tcp_config: TcpConfig,
local_link_addr: MacAddress,
arp: ArpPeer<N>,
nonce: u32,
) -> Self {
let ready = ReadySockets {
ready: VecDeque::new(),
endpoints: HashSet::new(),
waker: None,
};
let ready = Rc::new(RefCell::new(ready));
Self {
inflight: HashMap::new(),
ready,
max_backlog,
isn_generator: IsnGenerator::new(nonce),
local,
local_link_addr,
rt,
scheduler,
clock,
tcp_config,
arp,
}
}
/// Returns the address that the socket is bound to.
pub fn endpoint(&self) -> SocketAddrV4 {
self.local
}
pub fn poll_accept(&mut self, ctx: &mut Context) -> Poll<Result<ControlBlock<N>, Fail>> {
self.ready.borrow_mut().poll(ctx)
}
pub fn receive(&mut self, ip_header: &Ipv4Header, header: &TcpHeader) -> Result<(), Fail> {
let remote = SocketAddrV4::new(ip_header.get_src_addr(), header.src_port);
if self.ready.borrow().endpoints.contains(&remote) {
// TODO: What should we do if a packet shows up for a connection that hasn't been `accept`ed yet?
return Ok(());
}
let inflight_len = self.inflight.len();
// If the packet is for an inflight connection, route it there.
if self.inflight.contains_key(&remote) {
if !header.ack {
return Err(Fail::new(EBADMSG, "expeting ACK"));
}
debug!("Received ACK: {:?}", header);
let &InflightAccept {
local_isn,
remote_isn,
header_window_size,
remote_window_scale,
mss,
..
} = self.inflight.get(&remote).unwrap();
if header.ack_num != local_isn + SeqNumber::from(1) {
return Err(Fail::new(EBADMSG, "invalid SYN+ACK seq num"));
}
let (local_window_scale, remote_window_scale) = match remote_window_scale {
Some(w) => (self.tcp_config.get_window_scale() as u32, w),
None => (0, 0),
};
let remote_window_size = (header_window_size)
.checked_shl(remote_window_scale as u32)
.expect("TODO: Window size overflow")
.try_into()
.expect("TODO: Window size overflow");
let local_window_size = (self.tcp_config.get_receive_window_size() as u32)
.checked_shl(local_window_scale as u32)
.expect("TODO: Window size overflow");
info!(
"Window sizes: local {}, remote {}",
local_window_size, remote_window_size
);
info!(
"Window scale: local {}, remote {}",
local_window_scale, remote_window_scale
);
if let Some(mut inflight) = self.inflight.remove(&remote) {
inflight.handle.deschedule();
}
let cb = ControlBlock::new(
self.local,
remote,
self.rt.clone(),
self.scheduler.clone(),
self.clock.clone(),
self.local_link_addr,
self.tcp_config.clone(),
self.arp.clone(),
remote_isn + SeqNumber::from(1),
self.tcp_config.get_ack_delay_timeout(),
local_window_size,
local_window_scale,
local_isn + SeqNumber::from(1),
remote_window_size,
remote_window_scale,
mss,
congestion_control::None::new,
None,
);
self.ready.borrow_mut().push_ok(cb);
return Ok(());
}
// Otherwise, start a new connection.
if !header.syn || header.ack || header.rst {
return Err(Fail::new(EBADMSG, "invalid flags"));
}
debug!("Received SYN: {:?}", header);
if inflight_len + self.ready.borrow().len() >= self.max_backlog {
// TODO: Should we send a RST here?
return Err(Fail::new(ECONNREFUSED, "connection refused"));
}
let local_isn = self.isn_generator.generate(&self.local, &remote);
let remote_isn = header.seq_num;
let future = Self::background(
local_isn,
remote_isn,
self.local,
remote,
self.rt.clone(),
self.clock.clone(),
self.tcp_config.clone(),
self.local_link_addr,
self.arp.clone(),
self.ready.clone(),
);
let task: BackgroundTask = BackgroundTask::new(
String::from("Inetstack::TCP::passiveopen::background"),
Box::pin(future),
);
let handle: TaskHandle = match self.scheduler.insert(task) {
Some(handle) => handle,
None => panic!("failed to insert task in the scheduler"),
};
let mut remote_window_scale = None;
let mut mss = FALLBACK_MSS;
for option in header.iter_options() {
match option {
TcpOptions2::WindowScale(w) => {
info!("Received window scale: {:?}", w);
remote_window_scale = Some(*w);
},
TcpOptions2::MaximumSegmentSize(m) => {
info!("Received advertised MSS: {}", m);
mss = *m as usize;
},
_ => continue,
}
}
let accept = InflightAccept {
local_isn,
remote_isn,
header_window_size: header.window_size,
remote_window_scale,
mss,
handle,
};
self.inflight.insert(remote, accept);
Ok(())
}
fn background(
local_isn: SeqNumber,
remote_isn: SeqNumber,
local: SocketAddrV4,
remote: SocketAddrV4,
rt: Rc<dyn NetworkRuntime<N>>,
clock: TimerRc,
tcp_config: TcpConfig,
local_link_addr: MacAddress,
arp: ArpPeer<N>,
ready: Rc<RefCell<ReadySockets<N>>>,
) -> impl Future<Output = ()> {
let handshake_retries: usize = tcp_config.get_handshake_retries();
let handshake_timeout: Duration = tcp_config.get_handshake_timeout();
async move {
for _ in 0..handshake_retries {
let remote_link_addr = match arp.query(remote.ip().clone()).await {
Ok(r) => r,
Err(e) => {
warn!("ARP query failed: {:?}", e);
continue;
},
};
let mut tcp_hdr = TcpHeader::new(local.port(), remote.port());
tcp_hdr.syn = true;
tcp_hdr.seq_num = local_isn;
tcp_hdr.ack = true;
tcp_hdr.ack_num = remote_isn + SeqNumber::from(1);
tcp_hdr.window_size = tcp_config.get_receive_window_size();
let mss = tcp_config.get_advertised_mss() as u16;
tcp_hdr.push_option(TcpOptions2::MaximumSegmentSize(mss));
info!("Advertising MSS: {}", mss);
tcp_hdr.push_option(TcpOptions2::WindowScale(tcp_config.get_window_scale()));
info!("Advertising window scale: {}", tcp_config.get_window_scale());
debug!("Sending SYN+ACK: {:?}", tcp_hdr);
let segment = TcpSegment {
ethernet2_hdr: Ethernet2Header::new(remote_link_addr, local_link_addr, EtherType2::Ipv4),
ipv4_hdr: Ipv4Header::new(local.ip().clone(), remote.ip().clone(), IpProtocol::TCP),
tcp_hdr,
data: None,
tx_checksum_offload: tcp_config.get_rx_checksum_offload(),
};
rt.transmit(Box::new(segment));
clock.wait(clock.clone(), handshake_timeout).await;
}
ready.borrow_mut().push_err(Fail::new(ETIMEDOUT, "handshake timeout"));
}
}
}