1use std::time::Duration;
4
5use crate::error::NetError;
6use crate::sys::{self, AsSock};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub struct Keepalive {
16 pub idle: Duration,
18 pub interval: Duration,
20 pub count: u32,
22}
23
24impl Keepalive {
25 pub const DEFAULT: Keepalive = Keepalive {
27 idle: Duration::from_secs(60),
28 interval: Duration::from_secs(10),
29 count: 6,
30 };
31}
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum Linger {
40 Off,
42 Abortive,
44 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#[must_use]
66#[non_exhaustive]
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
68pub struct TcpOptions {
69 pub nodelay: Option<bool>,
71 pub keepalive: Option<Keepalive>,
73 pub linger: Option<Linger>,
75 pub send_buffer: Option<u32>,
77 pub receive_buffer: Option<u32>,
79 pub user_timeout: Option<Duration>,
82 pub ttl: Option<u8>,
84}
85
86impl TcpOptions {
87 pub fn new() -> TcpOptions {
89 TcpOptions::default()
90 }
91
92 pub fn nodelay(mut self, on: bool) -> TcpOptions {
94 self.nodelay = Some(on);
95 self
96 }
97
98 pub fn keepalive(mut self, k: Keepalive) -> TcpOptions {
100 self.keepalive = Some(k);
101 self
102 }
103
104 pub fn linger(mut self, l: Linger) -> TcpOptions {
106 self.linger = Some(l);
107 self
108 }
109
110 pub fn send_buffer(mut self, bytes: u32) -> TcpOptions {
112 self.send_buffer = Some(bytes);
113 self
114 }
115
116 pub fn receive_buffer(mut self, bytes: u32) -> TcpOptions {
118 self.receive_buffer = Some(bytes);
119 self
120 }
121
122 pub fn user_timeout(mut self, timeout: Duration) -> TcpOptions {
126 self.user_timeout = Some(timeout);
127 self
128 }
129
130 pub fn ttl(mut self, hops: u8) -> TcpOptions {
132 self.ttl = Some(hops);
133 self
134 }
135
136 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 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#[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 pub fn new() -> ListenOptions {
244 ListenOptions::default()
245 }
246
247 pub fn backlog(mut self, n: u32) -> ListenOptions {
249 self.backlog = n;
250 self
251 }
252
253 pub fn reuse_address(mut self, on: bool) -> ListenOptions {
259 self.reuse_address = on;
260 self
261 }
262
263 pub fn reuse_port(mut self, on: bool) -> ListenOptions {
265 self.reuse_port = on;
266 self
267 }
268
269 pub fn ipv6_only(mut self, on: bool) -> ListenOptions {
271 self.ipv6_only = on;
272 self
273 }
274
275 pub fn send_buffer(mut self, bytes: u32) -> ListenOptions {
277 self.send_buffer = Some(bytes);
278 self
279 }
280
281 pub fn receive_buffer(mut self, bytes: u32) -> ListenOptions {
283 self.receive_buffer = Some(bytes);
284 self
285 }
286
287 pub fn defer_accept(mut self, wait: Option<Duration>) -> ListenOptions {
292 self.defer_accept = wait;
293 self
294 }
295
296 pub fn fast_open(mut self, queue: Option<u32>) -> ListenOptions {
301 self.fast_open = queue;
302 self
303 }
304
305 pub fn incoming_cpu(mut self, cpu: Option<u32>) -> ListenOptions {
309 self.incoming_cpu = cpu;
310 self
311 }
312
313 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 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#[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 pub fn nodelay(&self) -> Result<bool, NetError> {
378 sys::nodelay(self.sock).map_err(os("TCP_NODELAY"))
379 }
380
381 pub fn set_nodelay(&self, on: bool) -> Result<(), NetError> {
387 sys::set_nodelay(self.sock, on).map_err(os("TCP_NODELAY"))
388 }
389
390 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 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 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 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 pub fn send_buffer(&self) -> Result<u32, NetError> {
446 sys::send_buffer(self.sock).map_err(os("SO_SNDBUF"))
447 }
448
449 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 pub fn receive_buffer(&self) -> Result<u32, NetError> {
464 sys::receive_buffer(self.sock).map_err(os("SO_RCVBUF"))
465 }
466
467 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 pub fn ttl(&self) -> Result<u8, NetError> {
482 sys::ttl(self.sock, self.v6).map_err(os("IP_TTL"))
483 }
484
485 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#[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 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 pub fn mode(mut self, mode: u32) -> LocalOptions {
538 self.mode = mode & 0o777;
539 self
540 }
541
542 pub fn owner(mut self, uid: u32) -> LocalOptions {
545 self.owner = Some(uid);
546 self
547 }
548
549 pub fn group(mut self, gid: u32) -> LocalOptions {
551 self.group = Some(gid);
552 self
553 }
554
555 pub fn group_access(mut self, gid: u32) -> LocalOptions {
557 self.group = Some(gid);
558 self.mode = 0o660;
559 self
560 }
561
562 pub fn remove_stale(mut self, on: bool) -> LocalOptions {
566 self.remove_stale = on;
567 self
568 }
569
570 pub fn require_uid(mut self, uid: u32) -> LocalOptions {
572 self.require_uid = Some(uid);
573 self
574 }
575
576 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}