snare 0.1.1

Network communication testing library for rust
Documentation
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
use std::{
    cmp,
    io::{self, Read, Write},
    net::{IpAddr, Shutdown, SocketAddr, ToSocketAddrs},
    time::{Duration, Instant},
};

use crate::state::{
    add_tcp_connection, add_tcp_listener_state, assign_tcp_stream_to_listener,
    clone_tcp_listener_state, find_tcp_listener, is_ip_addr_valid, is_port_available,
    mark_peer_read_shutdown, notify_peer_dropped, release_stream, remove_tcp_connection,
    remove_tcp_listener_state, reserve_ephemeral_addr, wait_for_event, with_tcp_connection,
    with_tcp_listener_state,
};

#[derive(Debug)]
pub struct ShimStdTcpStream {
    stream_id: usize,
}

#[derive(Debug)]
pub struct ShimStdTcpListener {
    bound_addr: SocketAddr,
}

enum TcpReadStatus {
    Data(Vec<u8>),
    Eof,
    Pending { nonblocking: bool, timeout: Option<Duration> },
}

impl ShimStdTcpStream {
    #[doc(alias = "std::net::TcpStream::connect")]
    pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<Self> {
        let mut last_err = None;
        for target in addr.to_socket_addrs()? {
            match Self::connect_addr(target) {
                Ok(stream) => return Ok(stream),
                Err(err) => last_err = Some(err),
            }
        }
        Err(last_err.unwrap_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidInput, "could not resolve to any addresses")
        }))
    }

    #[doc(alias = "std::net::TcpStream::connect_timeout")]
    pub fn connect_timeout<A: ToSocketAddrs>(addr: A, timeout: Duration) -> io::Result<Self> {
        if timeout == Duration::from_secs(0) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "timeout duration must be non-zero",
            ));
        }
        Self::connect(addr)
    }

    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        self.with_conn(|conn| Ok(conn.peer_addr))
    }

    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.with_conn(|conn| Ok(conn.local_addr))
    }

    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        self.with_conn(|conn| {
            conn.nonblocking = nonblocking;
            Ok(())
        })
    }

    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
        self.with_conn(|conn| {
            conn.nodelay = nodelay;
            Ok(())
        })
    }

    pub fn nodelay(&self) -> io::Result<bool> {
        self.with_conn(|conn| Ok(conn.nodelay))
    }

    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        self.with_conn(|conn| {
            conn.ttl = ttl;
            Ok(())
        })
    }

    pub fn ttl(&self) -> io::Result<u32> {
        self.with_conn(|conn| Ok(conn.ttl))
    }

    pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
        if let Some(dur) = linger {
            if dur == Duration::from_secs(0) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "linger duration must be non-zero",
                ));
            }
        }
        self.with_conn(|conn| {
            conn.linger = linger;
            Ok(())
        })
    }

    pub fn linger(&self) -> io::Result<Option<Duration>> {
        self.with_conn(|conn| Ok(conn.linger))
    }

    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        if let Some(d) = timeout {
            if d == Duration::from_secs(0) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "timeout duration must be non-zero",
                ));
            }
        }
        self.with_conn(|conn| {
            conn.read_timeout = timeout;
            Ok(())
        })
    }

    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
        self.with_conn(|conn| Ok(conn.read_timeout))
    }

    pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
        if let Some(d) = timeout {
            if d == Duration::from_secs(0) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "timeout duration must be non-zero",
                ));
            }
        }
        self.with_conn(|conn| {
            conn.write_timeout = timeout;
            Ok(())
        })
    }

    pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
        self.with_conn(|conn| Ok(conn.write_timeout))
    }

    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        self.with_conn(|conn| Ok(conn.external_error.take()))
    }

    pub fn try_clone(&self) -> io::Result<Self> {
        self.with_conn(|conn| {
            conn.ref_count += 1;
            Ok(())
        })?;
        Ok(Self {
            stream_id: self.stream_id,
        })
    }

    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        let peer = self.with_conn(|conn| {
            match how {
                Shutdown::Both => {
                    conn.read_shutdown = true;
                    conn.write_shutdown = true;
                }
                Shutdown::Read => {
                    conn.read_shutdown = true;
                    conn.incoming.clear();
                }
                Shutdown::Write => {
                    conn.write_shutdown = true;
                }
            }
            Ok(conn.peer_stream_id)
        })?;
        if let Shutdown::Write | Shutdown::Both = how {
            if let Some(peer_id) = peer {
                mark_peer_read_shutdown(peer_id);
            }
        }
        Ok(())
    }

    pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
        self.read_internal(buf, false)
    }

    fn read_internal(&self, buf: &mut [u8], consume: bool) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        let mut deadline = None;
        loop {
            match self.try_read(buf.len(), consume)? {
                TcpReadStatus::Data(data) => {
                    let len = data.len();
                    if len > 0 {
                        buf[..len].copy_from_slice(&data[..len]);
                    }
                    return Ok(len);
                }
                TcpReadStatus::Eof => return Ok(0),
                TcpReadStatus::Pending { nonblocking, timeout } => {
                    if nonblocking {
                        return Err(io::Error::new(
                            io::ErrorKind::WouldBlock,
                            "no data available",
                        ));
                    }
                    self.wait_for_read_ready(timeout, &mut deadline)?;
                }
            }
        }
    }

    fn try_read(&self, len: usize, consume: bool) -> io::Result<TcpReadStatus> {
        self.with_conn(|conn| {
            if conn.is_destroyed {
                return Err(io::Error::new(
                    io::ErrorKind::NotConnected,
                    "stream destroyed",
                ));
            }
            if conn.incoming.is_empty() {
                if conn.read_shutdown || conn.peer_stream_id.is_none() {
                    return Ok(TcpReadStatus::Eof);
                }
                return Ok(TcpReadStatus::Pending {
                    nonblocking: conn.nonblocking,
                    timeout: conn.read_timeout,
                });
            }
            let take = cmp::min(len, conn.incoming.len());
            let mut data = Vec::with_capacity(take);
            if consume {
                for _ in 0..take {
                    if let Some(byte) = conn.incoming.pop_front() {
                        data.push(byte);
                    }
                }
            } else {
                data.extend(conn.incoming.iter().take(take).copied());
            }
            Ok(TcpReadStatus::Data(data))
        })
    }

    fn wait_for_read_ready(
        &self,
        timeout: Option<Duration>,
        deadline: &mut Option<Instant>,
    ) -> io::Result<()> {
        if let Some(duration) = timeout {
            let now = Instant::now();
            let target = match deadline {
                Some(existing) => *existing,
                None => {
                    let new_deadline = now + duration;
                    *deadline = Some(new_deadline);
                    new_deadline
                }
            };
            if now >= target {
                return Err(io::Error::new(
                    io::ErrorKind::WouldBlock,
                    "operation timed out",
                ));
            }
            let remaining = target - now;
            if !wait_for_event(Some(remaining)) {
                return Err(io::Error::new(
                    io::ErrorKind::WouldBlock,
                    "operation timed out",
                ));
            }
        } else {
            *deadline = None;
            wait_for_event(None);
        }
        Ok(())
    }

    fn connect_addr(target: SocketAddr) -> io::Result<Self> {
        if !is_ip_addr_valid(target.ip()) {
            return Err(io::Error::new(
                io::ErrorKind::AddrNotAvailable,
                "invalid target address",
            ));
        }
        let listener_addr = find_tcp_listener(target).ok_or_else(|| {
            io::Error::new(io::ErrorKind::ConnectionRefused, "no listener available")
        })?;
        let client_ip = preferred_client_ip(&target);
        let local_addr = reserve_ephemeral_addr(client_ip);
        let server_ip = if listener_addr.ip().is_unspecified() {
            target.ip()
        } else {
            listener_addr.ip()
        };
        let server_addr = SocketAddr::new(server_ip, listener_addr.port());
        let client_stream = add_tcp_connection(local_addr, server_addr, true);
        let server_stream = add_tcp_connection(server_addr, local_addr, false);
        with_tcp_connection(client_stream, |conn| -> io::Result<()> {
            conn.peer_stream_id = Some(server_stream);
            Ok(())
        })?;
        with_tcp_connection(server_stream, |conn| -> io::Result<()> {
            conn.peer_stream_id = Some(client_stream);
            Ok(())
        })?;
        assign_tcp_stream_to_listener(listener_addr, server_stream);
        Ok(Self {
            stream_id: client_stream,
        })
    }

    fn with_conn<T, F>(&self, func: F) -> io::Result<T>
    where
        F: FnOnce(&mut crate::state::TcpConnection) -> io::Result<T>,
    {
        with_tcp_connection(self.stream_id, func)
    }
}

impl Read for ShimStdTcpStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.read_internal(buf, true)
    }
}

impl Write for ShimStdTcpStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        let peer_id = self.with_conn(|conn| {
            if conn.write_shutdown {
                return Err(io::Error::new(
                    io::ErrorKind::BrokenPipe,
                    "write half closed",
                ));
            }
            conn.peer_stream_id.ok_or_else(|| {
                io::Error::new(io::ErrorKind::NotConnected, "no peer connected")
            })
        })?;
        with_tcp_connection(peer_id, |peer| {
            if peer.read_shutdown {
                return Err(io::Error::new(
                    io::ErrorKind::BrokenPipe,
                    "peer closed the read half",
                ));
            }
            peer.incoming.extend(buf.iter().copied());
            Ok(buf.len())
        })
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

impl Drop for ShimStdTcpStream {
    fn drop(&mut self) {
        if let Some(peer_id) = release_stream(self.stream_id) {
            notify_peer_dropped(peer_id);
        }
    }
}

impl ShimStdTcpListener {
    #[doc(alias = "std::net::TcpListener::bind")]
    pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<Self> {
        for address in addr.to_socket_addrs()? {
            if !is_ip_addr_valid(address.ip()) {
                continue;
            }
            let actual_addr = if address.port() == 0 {
                reserve_ephemeral_addr(address.ip())
            } else if is_port_available(address.port()) {
                address
            } else {
                continue;
            };
            add_tcp_listener_state(actual_addr);
            return Ok(Self {
                bound_addr: actual_addr,
            });
        }
        Err(io::Error::new(
            io::ErrorKind::AddrNotAvailable,
            "could not bind to any addresses",
        ))
    }

    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        Ok(self.bound_addr)
    }

    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        with_tcp_listener_state(self.bound_addr, |listener| {
            listener.nonblocking = nonblocking;
        });
        Ok(())
    }

    pub fn accept(&self) -> io::Result<(ShimStdTcpStream, SocketAddr)> {
        loop {
            let (stream_id, nonblocking, is_closed) =
                with_tcp_listener_state(self.bound_addr, |listener| {
                    (
                        listener.pending_streams.pop_front(),
                        listener.nonblocking,
                        listener.is_closed,
                    )
                });
            if is_closed {
                return Err(io::Error::new(
                    io::ErrorKind::NotConnected,
                    "listener closed",
                ));
            }
            if let Some(stream_id) = stream_id {
                let peer_addr = with_tcp_connection(stream_id, |conn| -> io::Result<SocketAddr> {
                    Ok(conn.peer_addr)
                })?;
                return Ok((ShimStdTcpStream { stream_id }, peer_addr));
            }
            if nonblocking {
                return Err(io::Error::new(
                    io::ErrorKind::WouldBlock,
                    "no pending connections",
                ));
            }
            wait_for_event(None);
        }
    }

    pub fn set_ttl(&self, _ttl: u32) -> io::Result<()> {
        todo!()
    }

    pub fn ttl(&self) -> io::Result<u32> {
        todo!()
    }

    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
        with_tcp_listener_state(self.bound_addr, |listener| Ok(listener.error.take()))
    }

    pub fn try_clone(&self) -> io::Result<Self> {
        clone_tcp_listener_state(self.bound_addr)?;
        Ok(Self {
            bound_addr: self.bound_addr,
        })
    }
}

impl Drop for ShimStdTcpListener {
    fn drop(&mut self) {
        if let Some(state) = remove_tcp_listener_state(self.bound_addr) {
            for stream_id in state.pending_streams {
                cleanup_unaccepted_stream(stream_id);
            }
        }
    }
}

fn cleanup_unaccepted_stream(stream_id: usize) {
    if let Some(conn) = remove_tcp_connection(stream_id) {
        if let Some(peer_id) = conn.peer_stream_id {
            notify_peer_dropped(peer_id);
        }
    }
}

fn preferred_client_ip(target: &SocketAddr) -> IpAddr {
    if is_ip_addr_valid(target.ip()) {
        target.ip()
    } else {
        match target {
            SocketAddr::V4(_) => IpAddr::from([127, 0, 0, 1]),
            SocketAddr::V6(_) => IpAddr::from([0, 0, 0, 0, 0, 0, 0, 1]),
        }
    }
}