ntex_net/lib.rs
1//! Network transports and runtime reactor integration for ntex.
2//!
3//! This crate provides TCP and Unix domain socket connection helpers, DNS-aware
4//! connectors, and reactor implementations for native ntex, Tokio, and Compio
5//! runtimes. All transports are exposed as [`Io`] values.
6//!
7//! [`DefaultRuntime`] selects a reactor from the enabled Cargo features and the
8//! current platform.
9//!
10//! # Runtime features
11//!
12//! - `tokio` enables the Tokio reactor.
13//! - `compio` enables the Compio reactor.
14//! - `neon-polling` requires the native `polling` reactor on Unix.
15//! - `neon-uring` requires the native `io-uring` reactor on Linux.
16//!
17//! Without an explicit runtime feature, Linux tries `io-uring` and falls back to
18//! `polling`; other Unix platforms use polling and Windows always uses `IOCP`.
19#![deny(clippy::pedantic)]
20#![allow(
21 clippy::clone_on_copy,
22 clippy::cast_possible_truncation,
23 clippy::missing_fields_in_debug,
24 clippy::must_use_candidate,
25 clippy::missing_errors_doc,
26 clippy::missing_panics_doc,
27 clippy::unused_async_trait_impl
28)]
29use std::task::{Context, Poll};
30use std::{any::Any, fmt, future::poll_fn, io, net, net::SocketAddr, panic};
31
32use ntex_io::Io;
33use ntex_rt::{BlockFuture, Driver, Runner};
34use ntex_service::cfg::SharedCfg;
35
36pub mod channel;
37pub mod connect;
38
39#[cfg(unix)]
40pub mod polling;
41
42#[cfg(target_os = "linux")]
43pub mod uring;
44
45#[cfg(windows)]
46pub mod iocp;
47
48#[cfg(any(unix, windows))]
49mod helpers;
50
51#[cfg(feature = "tokio")]
52pub mod tokio;
53
54#[cfg(feature = "compio")]
55pub mod compio;
56
57/// Runtime reactor used for network connection and transport operations.
58#[allow(clippy::wrong_self_convention)]
59pub trait Reactor: Driver {
60 /// Starts an asynchronous TCP connection.
61 fn tcp_connect(&self, addr: net::SocketAddr, cfg: SharedCfg) -> channel::Receiver<Io>;
62
63 /// Starts an asynchronous Unix domain socket connection.
64 fn unix_connect(&self, addr: std::path::PathBuf, cfg: SharedCfg) -> channel::Receiver<Io>;
65
66 /// Converts a standard-library TCP stream into an [`Io`] value.
67 ///
68 /// The reactor does not change `TCP_NODELAY`; the stream keeps the value
69 /// it already has. Callers that need low latency must call
70 /// `stream.set_nodelay(true)` before converting the stream, unless the
71 /// option is already set, for example inherited from a listener with
72 /// `TCP_NODELAY` enabled on Linux and macOS.
73 fn from_tcp_stream(&self, stream: net::TcpStream, cfg: SharedCfg) -> io::Result<Io>;
74
75 #[cfg(unix)]
76 /// Converts a standard-library Unix stream into an [`Io`] value.
77 fn from_unix_stream(&self, _: std::os::unix::net::UnixStream, _: SharedCfg) -> io::Result<Io>;
78
79 /// Registers a TCP listener with the reactor.
80 ///
81 /// The default implementation returns an [`io::ErrorKind::Unsupported`]
82 /// error.
83 fn tcp_listener(&self, sock: net::TcpListener) -> io::Result<Listener> {
84 drop(sock);
85 Err(io::Error::new(
86 io::ErrorKind::Unsupported,
87 "tcp listener is not supported by the reactor",
88 ))
89 }
90
91 /// Returns `true` if [`tcp_listener`](Self::tcp_listener) is supported.
92 ///
93 /// The default implementation returns `false`.
94 fn is_tcp_listener_supported(&self) -> bool {
95 false
96 }
97}
98
99/// Reactor specific part of a [`Listener`].
100pub(crate) trait ListenerOps {
101 fn poll_accept(
102 &mut self,
103 cx: &mut Context<'_>,
104 ) -> Poll<io::Result<(net::TcpStream, SocketAddr)>>;
105
106 fn local_addr(&self) -> io::Result<SocketAddr>;
107}
108
109/// TCP listener that accepts connections through the current reactor.
110///
111/// Created by [`tcp_listener`]. The listener is bound to the thread that
112/// created it. Dropping it deregisters the socket from the reactor and closes
113/// it.
114pub struct Listener(Box<dyn ListenerOps>);
115
116impl Listener {
117 #[allow(dead_code)]
118 pub(crate) fn new<T: ListenerOps + 'static>(ops: T) -> Self {
119 Listener(Box::new(ops))
120 }
121
122 /// Accepts a new incoming connection.
123 ///
124 /// Returns the connected stream and the address of the peer. The stream
125 /// may be in blocking or non-blocking mode depending on the platform,
126 /// [`from_tcp_stream`] switches it to the mode the reactor needs.
127 ///
128 /// Dropping the returned future before it completes does not lose a
129 /// connection, the next call returns it.
130 pub async fn accept(&mut self) -> io::Result<(net::TcpStream, SocketAddr)> {
131 poll_fn(|cx| self.0.poll_accept(cx)).await
132 }
133
134 /// Polls for a new incoming connection.
135 ///
136 /// Same as [`accept`](Self::accept). On `Poll::Pending`, the waker of
137 /// the most recent call is woken when a connection may be accepted. A
138 /// listener that is not polled again keeps an accepted connection for
139 /// the next call.
140 pub fn poll_accept(
141 &mut self,
142 cx: &mut Context<'_>,
143 ) -> Poll<io::Result<(net::TcpStream, SocketAddr)>> {
144 self.0.poll_accept(cx)
145 }
146
147 /// Returns the local address the listener is bound to.
148 pub fn local_addr(&self) -> io::Result<SocketAddr> {
149 self.0.local_addr()
150 }
151}
152
153impl fmt::Debug for Listener {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 f.debug_struct("Listener")
156 .field("local_addr", &self.local_addr().ok())
157 .finish()
158 }
159}
160
161#[inline]
162/// Opens a TCP connection to a remote host.
163///
164/// # Panics
165///
166/// Panics if called outside an ntex runtime, for example from a plain thread
167/// or a runtime from another crate. Call it from code running under
168/// `#[ntex::main]`, `#[ntex::test]`, or an ntex `System`.
169pub async fn tcp_connect(addr: SocketAddr, cfg: SharedCfg) -> io::Result<Io> {
170 with_current(|driver| driver.tcp_connect(addr, cfg)).await
171}
172
173#[inline]
174/// Opens a Unix domain socket connection.
175///
176/// # Panics
177///
178/// Panics if called outside an ntex runtime, for example from a plain thread
179/// or a runtime from another crate. Call it from code running under
180/// `#[ntex::main]`, `#[ntex::test]`, or an ntex `System`.
181pub async fn unix_connect<'a, P>(addr: P, cfg: SharedCfg) -> io::Result<Io>
182where
183 P: AsRef<std::path::Path> + 'a,
184{
185 with_current(|driver| driver.unix_connect(addr.as_ref().into(), cfg)).await
186}
187
188#[inline]
189/// Converts a standard-library TCP stream into an [`Io`] value.
190///
191/// # `TCP_NODELAY`
192///
193/// This function does not change `TCP_NODELAY`; the stream keeps the value
194/// it already has. With the option disabled, Nagle's algorithm may delay
195/// small writes, so callers that need low latency must enable it first:
196///
197/// ```rust,no_run
198/// # fn convert(stream: std::net::TcpStream) -> std::io::Result<()> {
199/// stream.set_nodelay(true)?;
200/// let io = ntex_net::from_tcp_stream(stream, Default::default())?;
201/// # drop(io);
202/// # Ok(())
203/// # }
204/// ```
205///
206/// Streams accepted from a listener with `TCP_NODELAY` enabled inherit the
207/// option on Linux and macOS, so they do not need the extra call.
208///
209/// # Panics
210///
211/// Panics if called outside an ntex runtime, for example from a plain thread
212/// or a runtime from another crate. Call it from code running under
213/// `#[ntex::main]`, `#[ntex::test]`, or an ntex `System`.
214pub fn from_tcp_stream(stream: net::TcpStream, cfg: SharedCfg) -> io::Result<Io> {
215 with_current(|driver| driver.from_tcp_stream(stream, cfg))
216}
217
218#[cfg(unix)]
219#[inline]
220/// Converts a standard-library Unix stream into an [`Io`] value.
221///
222/// # Panics
223///
224/// Panics if called outside an ntex runtime, for example from a plain thread
225/// or a runtime from another crate. Call it from code running under
226/// `#[ntex::main]`, `#[ntex::test]`, or an ntex `System`.
227pub fn from_unix_stream(stream: std::os::unix::net::UnixStream, cfg: SharedCfg) -> io::Result<Io> {
228 with_current(|driver| driver.from_unix_stream(stream, cfg))
229}
230
231#[inline]
232/// Registers a TCP listener with the current reactor.
233///
234/// The socket must be bound, listening and in non-blocking mode; set it with
235/// [`net::TcpListener::set_nonblocking`]. A blocking socket stalls the
236/// runtime thread in [`Listener::accept`].
237///
238/// Only the native `polling` and `io-uring` reactors support listeners. The
239/// Tokio, Compio and IOCP reactors return an [`io::ErrorKind::Unsupported`]
240/// error. The socket is closed on error.
241///
242/// # Panics
243///
244/// Panics if called outside an ntex runtime, for example from a plain thread
245/// or a runtime from another crate. Call it from code running under
246/// `#[ntex::main]`, `#[ntex::test]`, or an ntex `System`.
247pub fn tcp_listener(sock: net::TcpListener) -> io::Result<Listener> {
248 with_current(|driver| driver.tcp_listener(sock))
249}
250
251/// Returns `true` if the current reactor supports [`tcp_listener`].
252///
253/// Returns `false` outside an ntex runtime. The `io-uring` reactor supports
254/// listeners if the kernel supports the `Accept` and `PollAdd` operations.
255pub fn is_tcp_listener_supported() -> bool {
256 CURRENT_DRIVER.is_set() && CURRENT_DRIVER.with(|d| d.is_tcp_listener_supported())
257}
258
259fn with_current<T, F: FnOnce(&dyn Reactor) -> T>(f: F) -> T {
260 #[cold]
261 fn not_in_ntex_driver() -> ! {
262 panic!("not in a ntex driver")
263 }
264
265 if CURRENT_DRIVER.is_set() {
266 CURRENT_DRIVER.with(|d| f(&**d))
267 } else {
268 not_in_ntex_driver()
269 }
270}
271
272#[allow(clippy::borrowed_box)]
273/// Sets the current reactor and runs the provided closure.
274///
275/// # Panics
276///
277/// Panics if a reactor is already active on the current thread.
278pub fn with_reactor<R, F: FnOnce() -> R>(r: &Box<dyn Reactor>, f: F) -> R {
279 #[cold]
280 fn reactor_is_set() -> ! {
281 panic!("reactor is already set");
282 }
283
284 if CURRENT_DRIVER.is_set() {
285 reactor_is_set()
286 }
287 CURRENT_DRIVER.set(r, f)
288}
289
290scoped_tls::scoped_thread_local!(static CURRENT_DRIVER: Box<dyn Reactor>);
291
292/// The default runtime.
293///
294/// Automatically selects the runtime implementation based on the
295/// configured features and the platform on which it runs.
296#[derive(Copy, Clone, Debug)]
297pub struct DefaultRuntime;
298
299impl Runner for DefaultRuntime {
300 #[allow(unused_variables, clippy::too_many_lines)]
301 fn block_on(&self, fut: BlockFuture) -> Result<(), Box<dyn Any + Send>> {
302 #[cfg(feature = "tokio")]
303 {
304 let driver: Box<dyn Reactor> = Box::new(self::tokio::Reactor);
305
306 with_reactor(&driver, || crate::tokio::block_on(fut));
307 Ok(())
308 }
309
310 #[cfg(all(feature = "compio", not(feature = "tokio")))]
311 {
312 let driver: Box<dyn Reactor> = Box::new(self::compio::Reactor);
313
314 with_reactor(&driver, || crate::compio::block_on(fut));
315 Ok(())
316 }
317
318 #[cfg(all(windows, not(feature = "tokio"), not(feature = "compio")))]
319 {
320 let driver: Box<dyn Reactor> =
321 Box::new(crate::iocp::Reactor::new().expect("Cannot construct driver"));
322
323 with_reactor(&driver, || {
324 panic::catch_unwind(panic::AssertUnwindSafe(|| {
325 let rt = ntex_rt::Runtime::new(driver.handle());
326 rt.block_on(fut, &*driver);
327 }))
328 })
329 }
330
331 #[cfg(all(unix, not(feature = "tokio"), not(feature = "compio")))]
332 {
333 #[cfg(feature = "neon-polling")]
334 {
335 let driver: Box<dyn Reactor> = Box::new(
336 crate::polling::Reactor::new().expect("Cannot construct polling reactor"),
337 );
338
339 with_reactor(&driver, || {
340 panic::catch_unwind(panic::AssertUnwindSafe(|| {
341 let rt = ntex_rt::Runtime::new(driver.handle());
342 rt.block_on(fut, &*driver);
343 }))
344 })
345 }
346
347 #[cfg(all(target_os = "linux", feature = "neon-uring"))]
348 {
349 let driver: Box<dyn Reactor> = Box::new(
350 crate::uring::Reactor::new(crate::uring::Reactor::DEFAULT_ENTRIES)
351 .expect("Cannot construct io-uring reactor"),
352 );
353
354 with_reactor(&driver, || {
355 panic::catch_unwind(panic::AssertUnwindSafe(|| {
356 let rt = ntex_rt::Runtime::new(driver.handle());
357 rt.block_on(fut, &*driver);
358 }))
359 })
360 }
361
362 #[cfg(all(not(feature = "neon-uring"), not(feature = "neon-polling")))]
363 {
364 #[cfg(target_os = "linux")]
365 let driver: Box<dyn Reactor> = if let Ok(reactor) =
366 crate::uring::Reactor::new(crate::uring::Reactor::DEFAULT_ENTRIES)
367 {
368 Box::new(reactor)
369 } else {
370 Box::new(
371 crate::polling::Reactor::new().expect("Cannot construct io-uring reactor"),
372 )
373 };
374
375 #[cfg(not(target_os = "linux"))]
376 let driver: Box<dyn Reactor> = Box::new(
377 crate::polling::Reactor::new().expect("Cannot construct polling reactor"),
378 );
379
380 with_reactor(&driver, || {
381 panic::catch_unwind(panic::AssertUnwindSafe(|| {
382 let rt = ntex_rt::Runtime::new(driver.handle());
383 rt.block_on(fut, &*driver);
384 }))
385 })
386 }
387 }
388 }
389}