Skip to main content

net_io/
opts.rs

1//! Socket options: before bind, per accepted or dialed connection, and live.
2
3use std::time::Duration;
4
5use crate::error::NetError;
6use crate::sys::{self, AsSock};
7
8/// Keepalive probes: idle time before the first, interval between them, and count.
9///
10/// ```
11/// let k = net_io::Keepalive::DEFAULT;
12/// assert_eq!(k.count, 6);
13/// ```
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub struct Keepalive {
16    /// Idle time before the first probe.
17    pub idle: Duration,
18    /// Time between probes.
19    pub interval: Duration,
20    /// Probes before the connection is dropped.
21    pub count: u32,
22}
23
24impl Keepalive {
25    /// 60 s, 10 s, 6.
26    pub const DEFAULT: Keepalive = Keepalive {
27        idle: Duration::from_secs(60),
28        interval: Duration::from_secs(10),
29        count: 6,
30    };
31}
32
33/// What happens to unsent data at close.
34///
35/// ```
36/// assert_ne!(net_io::Linger::Off, net_io::Linger::Abortive);
37/// ```
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum Linger {
40    /// The OS default: close returns at once, the kernel sends what it can.
41    Off,
42    /// RST on close; kernel resources are freed at once.
43    Abortive,
44    /// Close waits up to this long for unsent data.
45    Timeout(Duration),
46}
47
48impl Linger {
49    fn to_sys(self) -> Option<Duration> {
50        match self {
51            Linger::Off => None,
52            Linger::Abortive => Some(Duration::ZERO),
53            Linger::Timeout(d) => Some(d),
54        }
55    }
56}
57
58/// Options applied to each accepted or dialed TCP connection. `None` leaves the OS default.
59///
60/// ```
61/// use net_io::{Keepalive, TcpOptions};
62/// let opts = TcpOptions::new().nodelay(true).keepalive(Keepalive::DEFAULT);
63/// assert_eq!(opts.nodelay, Some(true));
64/// ```
65#[must_use]
66#[non_exhaustive]
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
68pub struct TcpOptions {
69    /// `TCP_NODELAY`.
70    pub nodelay: Option<bool>,
71    /// Keepalive probes.
72    pub keepalive: Option<Keepalive>,
73    /// Linger at close.
74    pub linger: Option<Linger>,
75    /// `SO_SNDBUF`.
76    pub send_buffer: Option<u32>,
77    /// `SO_RCVBUF`.
78    pub receive_buffer: Option<u32>,
79    /// How long sent bytes may stay unacknowledged before the OS drops the connection
80    /// (`TCP_USER_TIMEOUT`; `TCP_MAXRT` on Windows, in whole seconds).
81    pub user_timeout: Option<Duration>,
82    /// Hop limit (`IP_TTL` / `IPV6_UNICAST_HOPS`).
83    pub ttl: Option<u8>,
84}
85
86impl TcpOptions {
87    /// Every option at the OS default.
88    pub fn new() -> TcpOptions {
89        TcpOptions::default()
90    }
91
92    /// `TCP_NODELAY`.
93    pub fn nodelay(mut self, on: bool) -> TcpOptions {
94        self.nodelay = Some(on);
95        self
96    }
97
98    /// Keepalive probes.
99    pub fn keepalive(mut self, k: Keepalive) -> TcpOptions {
100        self.keepalive = Some(k);
101        self
102    }
103
104    /// Linger at close.
105    pub fn linger(mut self, l: Linger) -> TcpOptions {
106        self.linger = Some(l);
107        self
108    }
109
110    /// `SO_SNDBUF`.
111    pub fn send_buffer(mut self, bytes: u32) -> TcpOptions {
112        self.send_buffer = Some(bytes);
113        self
114    }
115
116    /// `SO_RCVBUF`.
117    pub fn receive_buffer(mut self, bytes: u32) -> TcpOptions {
118        self.receive_buffer = Some(bytes);
119        self
120    }
121
122    /// How long sent bytes may stay unacknowledged before the OS drops the connection.
123    /// `Unsupported` on macOS and FreeBSD. The write timeout covers the same case
124    /// inside net-io; this also covers the bytes already in the kernel at a close.
125    pub fn user_timeout(mut self, timeout: Duration) -> TcpOptions {
126        self.user_timeout = Some(timeout);
127        self
128    }
129
130    /// Hop limit.
131    pub fn ttl(mut self, hops: u8) -> TcpOptions {
132        self.ttl = Some(hops);
133        self
134    }
135
136    /// Applies the options that are set to `stream`.
137    pub(crate) fn apply<S: AsSock>(&self, socket: &S, v6: bool) -> Result<(), NetError> {
138        let sock = socket.sock();
139        let os = |op: &'static str| move |e| NetError::from_os(op, e);
140        if let Some(on) = self.nodelay {
141            sys::set_nodelay(sock, on).map_err(os("TCP_NODELAY"))?;
142        }
143        if let Some(k) = self.keepalive {
144            check_keepalive(&k)?;
145            sys::set_keepalive(sock, Some((k.idle, k.interval, k.count)))
146                .map_err(os("keepalive"))?;
147        }
148        if let Some(l) = self.linger {
149            sys::set_linger(sock, l.to_sys()).map_err(os("SO_LINGER"))?;
150        }
151        if let Some(n) = self.send_buffer {
152            sys::set_send_buffer(sock, n).map_err(os("SO_SNDBUF"))?;
153        }
154        if let Some(n) = self.receive_buffer {
155            sys::set_receive_buffer(sock, n).map_err(os("SO_RCVBUF"))?;
156        }
157        if let Some(t) = self.user_timeout {
158            sys::set_user_timeout(sock, t).map_err(|e| {
159                if e.kind() == std::io::ErrorKind::Unsupported {
160                    NetError::Unsupported {
161                        feature: "user_timeout",
162                        platform: std::env::consts::OS,
163                    }
164                } else {
165                    NetError::from_os("TCP_USER_TIMEOUT", e)
166                }
167            })?;
168        }
169        if let Some(h) = self.ttl {
170            sys::set_ttl(sock, v6, h).map_err(os("IP_TTL"))?;
171        }
172        Ok(())
173    }
174
175    /// Whether any option is set.
176    pub(crate) fn is_empty(&self) -> bool {
177        *self == TcpOptions::default()
178    }
179}
180
181fn check_keepalive(k: &Keepalive) -> Result<(), NetError> {
182    if cfg!(windows) && k.count > 255 {
183        return Err(NetError::InvalidConfig {
184            field: "keepalive",
185            reason: crate::error::ConfigReason::TooLarge { max: 255 },
186        });
187    }
188    if k.idle.is_zero() || k.interval.is_zero() || k.count == 0 {
189        return Err(NetError::InvalidConfig {
190            field: "keepalive",
191            reason: crate::error::ConfigReason::Zero,
192        });
193    }
194    Ok(())
195}
196
197/// Options set on a listening socket before `bind` and `listen`.
198///
199/// ```
200/// use net_io::{ListenOptions, TcpListener};
201/// let options = ListenOptions::new().backlog(4096).reuse_port(cfg!(target_os = "linux"));
202/// let listener = TcpListener::bind_with("127.0.0.1:0", options)?;
203/// println!("effective backlog {:?}", listener.info().backlog);
204/// # Ok::<(), net_io::NetError>(())
205/// ```
206#[must_use]
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub struct ListenOptions {
209    pub(crate) backlog: u32,
210    pub(crate) reuse_address: bool,
211    pub(crate) reuse_port: bool,
212    pub(crate) ipv6_only: bool,
213    pub(crate) send_buffer: Option<u32>,
214    pub(crate) receive_buffer: Option<u32>,
215    pub(crate) defer_accept: Option<Duration>,
216    pub(crate) fast_open: Option<u32>,
217    pub(crate) incoming_cpu: Option<u32>,
218    pub(crate) per_worker: bool,
219    pub(crate) tcp: TcpOptions,
220}
221
222impl Default for ListenOptions {
223    fn default() -> ListenOptions {
224        ListenOptions {
225            backlog: 1024,
226            reuse_address: cfg!(unix),
227            reuse_port: false,
228            ipv6_only: true,
229            send_buffer: None,
230            receive_buffer: None,
231            defer_accept: None,
232            fast_open: None,
233            incoming_cpu: None,
234            per_worker: false,
235            tcp: TcpOptions::new().nodelay(true),
236        }
237    }
238}
239
240impl ListenOptions {
241    /// Backlog 1,024; reuse address on Unix, exclusive address use on Windows;
242    /// IPv6-only; `TCP_NODELAY` on accepted sockets.
243    pub fn new() -> ListenOptions {
244        ListenOptions::default()
245    }
246
247    /// The listen backlog (capped by the OS; the effective value is in `ListenerInfo`).
248    pub fn backlog(mut self, n: u32) -> ListenOptions {
249        self.backlog = n;
250        self
251    }
252
253    /// Unix: `SO_REUSEADDR`, so a restart binds while connections of the old
254    /// process linger. Windows: ignored, the port is always `SO_EXCLUSIVEADDRUSE`.
255    /// An exclusive listener there can already bind again at once after a restart,
256    /// and Windows `SO_REUSEADDR` means something else: another local socket could
257    /// bind the same port over the listener and take its connections.
258    pub fn reuse_address(mut self, on: bool) -> ListenOptions {
259        self.reuse_address = on;
260        self
261    }
262
263    /// `SO_REUSEPORT` (`Unsupported` on Windows).
264    pub fn reuse_port(mut self, on: bool) -> ListenOptions {
265        self.reuse_port = on;
266        self
267    }
268
269    /// `IPV6_V6ONLY` for IPv6 addresses (on by default; decision D-026).
270    pub fn ipv6_only(mut self, on: bool) -> ListenOptions {
271        self.ipv6_only = on;
272        self
273    }
274
275    /// `SO_SNDBUF` on the listener (before `listen`).
276    pub fn send_buffer(mut self, bytes: u32) -> ListenOptions {
277        self.send_buffer = Some(bytes);
278        self
279    }
280
281    /// `SO_RCVBUF` on the listener (before `listen`, so window scaling is negotiated).
282    pub fn receive_buffer(mut self, bytes: u32) -> ListenOptions {
283        self.receive_buffer = Some(bytes);
284        self
285    }
286
287    /// `accept` returns once the client has sent bytes, or after `wait`
288    /// (`TCP_DEFER_ACCEPT`, whole seconds; `Unsupported` off Linux). A client that
289    /// connects and stays silent costs no accept for that long. Cost: the gate sees
290    /// the connection later, and a server that speaks first must not use this.
291    pub fn defer_accept(mut self, wait: Option<Duration>) -> ListenOptions {
292        self.defer_accept = wait;
293        self
294    }
295
296    /// Server TCP Fast Open with this many pending requests. Saves a round trip for a
297    /// client that returns. Security: the first flight of data can be replayed by the
298    /// network, so turn this on only for requests that are safe to run twice; the gate
299    /// and the PROXY check run as usual. Linux also needs `net.ipv4.tcp_fastopen`.
300    pub fn fast_open(mut self, queue: Option<u32>) -> ListenOptions {
301        self.fast_open = queue;
302        self
303    }
304
305    /// Accepts on this listener the connections the given CPU received
306    /// (`SO_INCOMING_CPU`, Linux; `Unsupported` elsewhere). For one reuse-port
307    /// listener per CPU.
308    pub fn incoming_cpu(mut self, cpu: Option<u32>) -> ListenOptions {
309        self.incoming_cpu = cpu;
310        self
311    }
312
313    /// One socket per reactor worker, in a `SO_REUSEPORT` group (Linux; `Unsupported`
314    /// elsewhere, `InvalidConfig` on the blocking driver). Each worker accepts on its
315    /// own socket in its own event loop, runs the caps and the gate there, and starts
316    /// the connection in the same turn: no accept thread, no hand-off between threads,
317    /// and no connection crosses to another worker. With `ServerBuilder::placement`
318    /// each socket also takes the connections its worker's CPU received. Costs: a
319    /// socket per worker; the kernel's hash decides the balance; the gate's `admit`
320    /// runs on the worker, so a slow gate delays that worker's other connections; and
321    /// such a listener cannot be handed off: closing one socket of a group resets what
322    /// is queued on it.
323    pub fn per_worker(mut self, on: bool) -> ListenOptions {
324        self.per_worker = on;
325        self.reuse_port = self.reuse_port || on;
326        self
327    }
328
329    /// Options applied to every accepted socket.
330    pub fn tcp_options(mut self, options: TcpOptions) -> ListenOptions {
331        self.tcp = options;
332        self
333    }
334
335    pub(crate) fn params(&self) -> sys::ListenParams {
336        sys::ListenParams {
337            reuse_address: self.reuse_address,
338            reuse_port: self.reuse_port,
339            ipv6_only: self.ipv6_only,
340            send_buffer: self.send_buffer,
341            receive_buffer: self.receive_buffer,
342            backlog: self.backlog,
343            defer_accept: self.defer_accept,
344            fast_open: self.fast_open,
345            incoming_cpu: self.incoming_cpu,
346        }
347    }
348}
349
350/// Live get and set on an open socket.
351///
352/// ```no_run
353/// use net_io::{Keepalive, Linger};
354/// let conn = net_io::connect("127.0.0.1:7000")?;
355/// conn.options().set_keepalive(Some(Keepalive::DEFAULT))?;
356/// conn.options().set_linger(Linger::Abortive)?;
357/// let effective = conn.options().set_receive_buffer(256 * 1024)?;
358/// println!("receive buffer is {effective} bytes");
359/// # Ok::<(), net_io::NetError>(())
360/// ```
361#[derive(Debug)]
362pub struct SocketOptions<'a> {
363    pub(crate) sock: sys::Sock<'a>,
364    pub(crate) v6: bool,
365}
366
367fn os(op: &'static str) -> impl Fn(std::io::Error) -> NetError {
368    move |e| NetError::from_os(op, e)
369}
370
371impl SocketOptions<'_> {
372    /// `TCP_NODELAY`.
373    ///
374    /// # Errors
375    ///
376    /// `Os` when the OS call fails.
377    pub fn nodelay(&self) -> Result<bool, NetError> {
378        sys::nodelay(self.sock).map_err(os("TCP_NODELAY"))
379    }
380
381    /// Sets `TCP_NODELAY`.
382    ///
383    /// # Errors
384    ///
385    /// `Os` when the OS call fails.
386    pub fn set_nodelay(&self, on: bool) -> Result<(), NetError> {
387        sys::set_nodelay(self.sock, on).map_err(os("TCP_NODELAY"))
388    }
389
390    /// Keepalive probes (`None` = off).
391    ///
392    /// # Errors
393    ///
394    /// `Os` when the OS call fails.
395    pub fn keepalive(&self) -> Result<Option<Keepalive>, NetError> {
396        Ok(sys::keepalive(self.sock)
397            .map_err(os("keepalive"))?
398            .map(|(idle, interval, count)| Keepalive {
399                idle,
400                interval,
401                count,
402            }))
403    }
404
405    /// Sets keepalive probes (`None` = off).
406    ///
407    /// # Errors
408    ///
409    /// `InvalidConfig` for a zero value or a count above 255 on Windows; `Os`.
410    pub fn set_keepalive(&self, k: Option<Keepalive>) -> Result<(), NetError> {
411        if let Some(k) = &k {
412            check_keepalive(k)?;
413        }
414        sys::set_keepalive(self.sock, k.map(|k| (k.idle, k.interval, k.count)))
415            .map_err(os("keepalive"))
416    }
417
418    /// Linger at close.
419    ///
420    /// # Errors
421    ///
422    /// `Os` when the OS call fails.
423    pub fn linger(&self) -> Result<Linger, NetError> {
424        Ok(match sys::linger(self.sock).map_err(os("SO_LINGER"))? {
425            None => Linger::Off,
426            Some(d) if d.is_zero() => Linger::Abortive,
427            Some(d) => Linger::Timeout(d),
428        })
429    }
430
431    /// Sets linger at close.
432    ///
433    /// # Errors
434    ///
435    /// `Os` when the OS call fails.
436    pub fn set_linger(&self, l: Linger) -> Result<(), NetError> {
437        sys::set_linger(self.sock, l.to_sys()).map_err(os("SO_LINGER"))
438    }
439
440    /// The effective `SO_SNDBUF`.
441    ///
442    /// # Errors
443    ///
444    /// `Os` when the OS call fails.
445    pub fn send_buffer(&self) -> Result<u32, NetError> {
446        sys::send_buffer(self.sock).map_err(os("SO_SNDBUF"))
447    }
448
449    /// Sets `SO_SNDBUF` and returns the effective value (Linux doubles it).
450    ///
451    /// # Errors
452    ///
453    /// `Os` when the OS call fails.
454    pub fn set_send_buffer(&self, bytes: u32) -> Result<u32, NetError> {
455        sys::set_send_buffer(self.sock, bytes).map_err(os("SO_SNDBUF"))
456    }
457
458    /// The effective `SO_RCVBUF`.
459    ///
460    /// # Errors
461    ///
462    /// `Os` when the OS call fails.
463    pub fn receive_buffer(&self) -> Result<u32, NetError> {
464        sys::receive_buffer(self.sock).map_err(os("SO_RCVBUF"))
465    }
466
467    /// Sets `SO_RCVBUF` and returns the effective value (Linux doubles it).
468    ///
469    /// # Errors
470    ///
471    /// `Os` when the OS call fails.
472    pub fn set_receive_buffer(&self, bytes: u32) -> Result<u32, NetError> {
473        sys::set_receive_buffer(self.sock, bytes).map_err(os("SO_RCVBUF"))
474    }
475
476    /// The hop limit.
477    ///
478    /// # Errors
479    ///
480    /// `Os` when the OS call fails.
481    pub fn ttl(&self) -> Result<u8, NetError> {
482        sys::ttl(self.sock, self.v6).map_err(os("IP_TTL"))
483    }
484
485    /// Sets the hop limit.
486    ///
487    /// # Errors
488    ///
489    /// `Os` when the OS call fails.
490    pub fn set_ttl(&self, hops: u8) -> Result<(), NetError> {
491        sys::set_ttl(self.sock, self.v6, hops).map_err(os("IP_TTL"))
492    }
493}
494
495/// Options for a Unix socket listener. The defaults: mode `0600` (only the
496/// owner may connect, decision D-024), stale socket files removed, backlog 1,024.
497///
498/// ```
499/// let options = net_io::LocalOptions::new().group_access(33).require_uid(1000);
500/// # let _ = options;
501/// ```
502#[must_use]
503#[derive(Clone, Debug, PartialEq, Eq)]
504pub struct LocalOptions {
505    pub(crate) mode: u32,
506    pub(crate) owner: Option<u32>,
507    pub(crate) group: Option<u32>,
508    pub(crate) remove_stale: bool,
509    pub(crate) require_uid: Option<u32>,
510    pub(crate) backlog: u32,
511}
512
513impl Default for LocalOptions {
514    fn default() -> LocalOptions {
515        LocalOptions::new()
516    }
517}
518
519impl LocalOptions {
520    /// Mode `0600`, stale socket files removed, backlog 1,024.
521    pub fn new() -> LocalOptions {
522        LocalOptions {
523            mode: 0o600,
524            owner: None,
525            group: None,
526            remove_stale: true,
527            require_uid: None,
528            backlog: 1024,
529        }
530    }
531
532    /// The socket file's permission bits (only the low 9 bits are used). They
533    /// are set before the socket listens, by the file's name relative to its open
534    /// directory, or inside a private directory when other users can change the
535    /// socket's directory (see `UnixListener::bind_with`); a directory writable by
536    /// every user without the sticky bit is refused.
537    pub fn mode(mut self, mode: u32) -> LocalOptions {
538        self.mode = mode & 0o777;
539        self
540    }
541
542    /// The socket file's owner (needs the privilege to change owners). Set as
543    /// the mode is, after it, and never through a symbolic link.
544    pub fn owner(mut self, uid: u32) -> LocalOptions {
545        self.owner = Some(uid);
546        self
547    }
548
549    /// The socket file's group; the mode is unchanged. Set as the owner is.
550    pub fn group(mut self, gid: u32) -> LocalOptions {
551        self.group = Some(gid);
552        self
553    }
554
555    /// The socket file's group and mode `0660`: members of `gid` may connect.
556    pub fn group_access(mut self, gid: u32) -> LocalOptions {
557        self.group = Some(gid);
558        self.mode = 0o660;
559        self
560    }
561
562    /// Whether a socket file nobody listens on is removed before binding
563    /// (default on). A live listener's file, or anything that is not a socket,
564    /// is never removed.
565    pub fn remove_stale(mut self, on: bool) -> LocalOptions {
566        self.remove_stale = on;
567        self
568    }
569
570    /// Refuses peers whose user id is not `uid`, at accept, before any read.
571    pub fn require_uid(mut self, uid: u32) -> LocalOptions {
572        self.require_uid = Some(uid);
573        self
574    }
575
576    /// The listen backlog (capped by the OS).
577    pub fn backlog(mut self, backlog: u32) -> LocalOptions {
578        self.backlog = backlog;
579        self
580    }
581}
582
583#[cfg(test)]
584mod tests {
585    use super::*;
586
587    #[test]
588    fn test_local_options_builders() {
589        let o = LocalOptions::new();
590        assert_eq!((o.mode, o.remove_stale, o.backlog), (0o600, true, 1024));
591        let o = o
592            .group_access(7)
593            .owner(3)
594            .require_uid(9)
595            .mode(0o1777)
596            .backlog(5);
597        assert_eq!(o.mode, 0o777);
598        assert_eq!(
599            (o.group, o.owner, o.require_uid),
600            (Some(7), Some(3), Some(9))
601        );
602        assert_eq!(LocalOptions::default(), LocalOptions::new());
603    }
604
605    #[test]
606    fn test_keepalive_zero_rejected() {
607        let k = Keepalive {
608            idle: Duration::ZERO,
609            interval: Duration::from_secs(1),
610            count: 1,
611        };
612        assert!(check_keepalive(&k).is_err());
613        assert!(check_keepalive(&Keepalive::DEFAULT).is_ok());
614    }
615
616    #[test]
617    fn test_listen_defaults() {
618        let o = ListenOptions::new();
619        assert_eq!(o.backlog, 1024);
620        assert!(o.ipv6_only);
621        assert_eq!(o.reuse_address, cfg!(unix));
622        assert_eq!(o.tcp.nodelay, Some(true));
623    }
624
625    #[test]
626    fn test_tcp_options_is_empty() {
627        assert!(TcpOptions::new().is_empty());
628        assert!(!TcpOptions::new().ttl(5).is_empty());
629    }
630}