Skip to main content

ntex_server/net/
socket.rs

1use std::{fmt, io, net};
2
3use ntex_io::Io;
4use ntex_service::cfg::SharedCfg;
5
6use super::Token;
7
8/// Accepted socket stream.
9#[derive(Debug)]
10pub enum Stream {
11    /// TCP stream.
12    Tcp(net::TcpStream),
13    /// Unix domain socket stream.
14    #[cfg(unix)]
15    Uds(std::os::unix::net::UnixStream),
16}
17
18impl Stream {
19    /// Converts the stream, `nodelay` tells `TCP_NODELAY` is already set.
20    pub(crate) fn convert(self, nodelay: bool, cfg: SharedCfg) -> Result<Io, io::Error> {
21        match self {
22            Stream::Tcp(stream) => {
23                if !nodelay {
24                    stream.set_nodelay(true)?;
25                }
26                ntex_net::from_tcp_stream(stream, cfg)
27            }
28            #[cfg(unix)]
29            Stream::Uds(stream) => ntex_net::from_unix_stream(stream, cfg),
30        }
31    }
32}
33
34/// Accepted connection dispatched to a worker.
35#[derive(Debug)]
36pub struct Connection {
37    pub(crate) io: Stream,
38    pub(crate) token: Token,
39    /// `TCP_NODELAY` is inherited from the listener.
40    pub(crate) nodelay: bool,
41}
42
43impl Connection {
44    /// Returns the CPU that handled the connection's incoming packets.
45    pub(crate) fn incoming_cpu(&self) -> Option<usize> {
46        match self.io {
47            Stream::Tcp(ref stream) => crate::affinity::incoming_cpu(stream),
48            #[cfg(unix)]
49            Stream::Uds(_) => None,
50        }
51    }
52}
53
54pub enum Listener {
55    Tcp(net::TcpListener),
56    #[cfg(unix)]
57    Uds(std::os::unix::net::UnixListener),
58}
59
60impl fmt::Debug for Listener {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match *self {
63            Listener::Tcp(ref lst) => write!(f, "{lst:?}"),
64            #[cfg(unix)]
65            Listener::Uds(ref lst) => write!(f, "{lst:?}"),
66        }
67    }
68}
69
70impl fmt::Display for Listener {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match *self {
73            Listener::Tcp(ref lst) => write!(f, "{}", lst.local_addr().ok().unwrap()),
74            #[cfg(unix)]
75            Listener::Uds(ref lst) => {
76                write!(f, "{:?}", lst.local_addr().ok().unwrap())
77            }
78        }
79    }
80}
81
82pub(crate) enum SocketAddr {
83    Tcp(net::SocketAddr),
84    #[cfg(unix)]
85    Uds(std::os::unix::net::SocketAddr),
86}
87
88impl fmt::Display for SocketAddr {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match *self {
91            SocketAddr::Tcp(ref addr) => write!(f, "{addr}"),
92            #[cfg(unix)]
93            SocketAddr::Uds(ref addr) => write!(f, "{addr:?}"),
94        }
95    }
96}
97
98impl fmt::Debug for SocketAddr {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        match *self {
101            SocketAddr::Tcp(ref addr) => write!(f, "{addr:?}"),
102            #[cfg(unix)]
103            SocketAddr::Uds(ref addr) => write!(f, "{addr:?}"),
104        }
105    }
106}
107
108impl Listener {
109    pub(super) fn from_tcp(lst: net::TcpListener) -> Self {
110        let _ = lst.set_nonblocking(true);
111        // accepted sockets inherit the option, so workers skip setting it
112        if let Err(e) = socket2::SockRef::from(&lst).set_tcp_nodelay(true) {
113            log::warn!("Cannot set TCP_NODELAY for {lst:?}: {e}");
114        }
115        Listener::Tcp(lst)
116    }
117
118    /// Returns `true` if accepted streams inherit `TCP_NODELAY`.
119    pub(crate) fn nodelay(&self) -> bool {
120        match self {
121            Listener::Tcp(lst) => tcp_nodelay(lst),
122            #[cfg(unix)]
123            Listener::Uds(_) => false,
124        }
125    }
126
127    #[cfg(unix)]
128    pub(super) fn from_uds(lst: std::os::unix::net::UnixListener) -> Self {
129        let _ = lst.set_nonblocking(true);
130        Listener::Uds(lst)
131    }
132
133    pub(crate) fn local_addr(&self) -> SocketAddr {
134        match self {
135            Listener::Tcp(lst) => SocketAddr::Tcp(lst.local_addr().unwrap()),
136            #[cfg(unix)]
137            Listener::Uds(lst) => SocketAddr::Uds(lst.local_addr().unwrap()),
138        }
139    }
140
141    pub(crate) fn accept(&self) -> io::Result<Option<Stream>> {
142        match *self {
143            Listener::Tcp(ref lst) => lst.accept().map(|(stream, _)| Some(Stream::Tcp(stream))),
144            #[cfg(unix)]
145            Listener::Uds(ref lst) => lst.accept().map(|(stream, _)| Some(Stream::Uds(stream))),
146        }
147    }
148
149    pub(crate) fn remove_source(&self) {
150        match *self {
151            Listener::Tcp(_) => (),
152            #[cfg(unix)]
153            Listener::Uds(ref lst) => {
154                // cleanup file path
155                if let Ok(addr) = lst.local_addr()
156                    && let Some(path) = addr.as_pathname()
157                {
158                    let _ = std::fs::remove_file(path);
159                }
160            }
161        }
162    }
163}
164
165/// Returns `true` if streams accepted on `lst` inherit `TCP_NODELAY`.
166///
167/// Only Linux and Apple platforms are known to copy the option to accepted
168/// sockets.
169pub(crate) fn tcp_nodelay(lst: &net::TcpListener) -> bool {
170    cfg!(any(
171        target_os = "linux",
172        target_os = "android",
173        target_vendor = "apple"
174    )) && socket2::SockRef::from(lst).tcp_nodelay().unwrap_or(false)
175}
176
177#[cfg(unix)]
178mod listener_impl {
179    use std::os::fd::{AsFd, BorrowedFd};
180    use std::os::unix::io::{AsRawFd, RawFd};
181
182    impl AsFd for super::Listener {
183        fn as_fd(&self) -> BorrowedFd<'_> {
184            match *self {
185                super::Listener::Tcp(ref lst) => lst.as_fd(),
186                super::Listener::Uds(ref lst) => lst.as_fd(),
187            }
188        }
189    }
190
191    impl AsRawFd for super::Listener {
192        fn as_raw_fd(&self) -> RawFd {
193            match *self {
194                super::Listener::Tcp(ref lst) => lst.as_raw_fd(),
195                super::Listener::Uds(ref lst) => lst.as_raw_fd(),
196            }
197        }
198    }
199}
200
201#[cfg(windows)]
202mod listener_impl {
203    use std::os::windows::io::{AsRawSocket, AsSocket, BorrowedSocket, RawSocket};
204
205    impl AsSocket for super::Listener {
206        fn as_socket(&self) -> BorrowedSocket<'_> {
207            match *self {
208                super::Listener::Tcp(ref lst) => lst.as_socket(),
209            }
210        }
211    }
212
213    impl AsRawSocket for super::Listener {
214        fn as_raw_socket(&self) -> RawSocket {
215            match *self {
216                super::Listener::Tcp(ref lst) => lst.as_raw_socket(),
217            }
218        }
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    /// STATEMENT: TCP `SocketAddr` and `Listener` debug and display output show the address.
227    ///
228    /// HOW:
229    /// - Format a TCP socket address; expect the address in `Debug` and as `Display`.
230    /// - Format a bound TCP listener; expect `TcpListener` in `Debug` and the IP in `Display`.
231    #[test]
232    fn socket_addr() {
233        use socket2::{Domain, SockAddr, Socket, Type};
234
235        let addr = SocketAddr::Tcp("127.0.0.1:8080".parse().unwrap());
236        assert!(format!("{addr:?}").contains("127.0.0.1:8080"));
237        assert_eq!(format!("{addr}"), "127.0.0.1:8080");
238
239        let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
240        let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap();
241        socket.set_reuse_address(true).unwrap();
242        socket.bind(&SockAddr::from(addr)).unwrap();
243        let lst = Listener::Tcp(net::TcpListener::from(socket));
244        assert!(format!("{lst:?}").contains("TcpListener"));
245        assert!(format!("{lst}").contains("127.0.0.1"));
246    }
247
248    /// STATEMENT: A server TCP listener enables `TCP_NODELAY` and accepted
249    /// streams inherit it, so workers may skip setting the option.
250    ///
251    /// HOW:
252    /// - Wrap a plain listener with `Listener::from_tcp`.
253    /// - Check `Listener::nodelay` matches the platform support.
254    /// - Accept a connection and read `TCP_NODELAY` on the accepted stream.
255    #[test]
256    fn listener_nodelay_is_inherited() {
257        let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
258        let addr = tcp.local_addr().unwrap();
259        let lst = Listener::from_tcp(tcp);
260        let supported = cfg!(any(
261            target_os = "linux",
262            target_os = "android",
263            target_vendor = "apple"
264        ));
265        assert_eq!(lst.nodelay(), supported);
266
267        let _client = net::TcpStream::connect(addr).unwrap();
268        let stream = loop {
269            match lst.accept() {
270                Ok(Some(Stream::Tcp(stream))) => break stream,
271                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
272                    std::thread::sleep(std::time::Duration::from_millis(10));
273                }
274                res => panic!("unexpected accept result: {res:?}"),
275            }
276        };
277        if supported {
278            assert!(stream.nodelay().unwrap());
279        }
280    }
281
282    /// STATEMENT: Unix `SocketAddr` and `Listener` debug and display output show the socket
283    /// path.
284    ///
285    /// HOW:
286    /// - Bind a Unix listener at a fixed path, skipping the test if binding fails.
287    /// - Format its address and the listener; expect the path in `Debug` and `Display`.
288    #[test]
289    #[cfg(unix)]
290    fn uds() {
291        use std::os::unix::net::UnixListener;
292
293        let _ = std::fs::remove_file("/tmp/sock.xxxxx");
294        if let Ok(lst) = UnixListener::bind("/tmp/sock.xxxxx") {
295            let addr = lst.local_addr().expect("Couldn't get local address");
296            let a = SocketAddr::Uds(addr);
297            assert!(format!("{a:?}").contains("/tmp/sock.xxxxx"));
298            assert!(format!("{a}").contains("/tmp/sock.xxxxx"));
299
300            let lst = Listener::Uds(lst);
301            assert!(format!("{lst:?}").contains("/tmp/sock.xxxxx"));
302            assert!(format!("{lst}").contains("/tmp/sock.xxxxx"));
303        }
304    }
305}