1
//! Functions to help test this crate.
2

            
3
use std::io;
4

            
5
use crate::ll_conn::MioStream;
6

            
7
/// The type of blocking stream returned by `construct_socketpair`.
8
#[cfg(not(windows))]
9
pub(crate) type SocketpairStream = socketpair::SocketpairStream;
10
#[cfg(windows)]
11
pub(crate) type SocketpairStream = std::net::TcpStream;
12

            
13
/// Test helper: construct a socketpair.
14
5
fn construct_socketpair_inner() -> io::Result<(SocketpairStream, SocketpairStream)> {
15
    #[cfg(not(windows))]
16
    {
17
5
        socketpair::socketpair_stream()
18
    }
19
    #[cfg(windows)]
20
    {
21
        // Alas, we can't use the socketpair crate on Windows!  It creates a Windows
22
        // "named pipe".  Windows "named pipe"s are not named pipes.  They are strange
23
        // things which a bit like an unholy cross between a Unix named pipe (aka a FIFO)
24
        // and an AF_UNIX socket.  This makes them bizarre and awkward.  They are best
25
        // avoided if possible.
26
        //
27
        // We have to use this nonsense instead.  It will cause these tests to fail on
28
        // some absurdly restrictive windows firewalls; that's a price we can afford.
29
        //
30
        // For details see
31
        // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/2758#note_3155460
32
        let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
33
        let addr = listener.local_addr()?;
34
        let s1 = std::net::TcpStream::connect(addr)?;
35
        let (s2, s2_addr) = listener.accept()?;
36
        // `s1.local_addr()` returns its own address.
37
        // Therefore, `s2_addr` should be the same as `s1.local_addr()`,
38
        // if the connection is established by the code above.
39
        // If they are not the same, that means there is another connector.
40
        // Also, if `local_addr()` fails, it means `c::getsockname` failed.
41
        assert_eq!(
42
            s1.local_addr().expect("Failed to get local address"),
43
            s2_addr
44
        );
45
        Ok((s1, s2))
46
    }
47
5
}
48

            
49
/// Test helper: Construct a socketpair,
50
/// wrapping the first element in a MIO wrapper and making it nonblocking.
51
5
pub(crate) fn construct_socketpair() -> io::Result<(Box<dyn MioStream>, SocketpairStream)> {
52
5
    let (s1, s2) = construct_socketpair_inner()?;
53

            
54
    #[cfg(not(windows))]
55
    let s1 = {
56
        use std::os::fd::OwnedFd;
57

            
58
5
        let owned_fd = OwnedFd::from(s1);
59
5
        std::os::unix::net::UnixStream::from(owned_fd)
60
    };
61

            
62
5
    s1.set_nonblocking(true)?;
63

            
64
    #[cfg(not(windows))]
65
5
    let s1 = mio::net::UnixStream::from_std(s1);
66
    #[cfg(windows)]
67
    let s1 = mio::net::TcpStream::from_std(s1);
68

            
69
5
    Ok((Box::new(s1), s2))
70
5
}