a10 0.4.3

This library is meant as a low-level library safely exposing different OS's abilities to perform non-blocking I/O.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Socket options.
//!
//! See [`AsyncFd::socket_option`] and [`AsyncFd::set_socket_option`].
//!
//! [`AsyncFd::socket_option`]: crate::fd::AsyncFd::socket_option
//! [`AsyncFd::set_socket_option`]: crate::fd::AsyncFd::set_socket_option

use std::io;
use std::mem::MaybeUninit;

use crate::net::{self, Level, Opt, SocketOpt, TcpOpt};

/// Trait that defines how get the value of a socket option.
///
/// See [`AsyncFd::socket_option`].
///
/// [`AsyncFd::socket_option`]: crate::fd::AsyncFd::socket_option
pub trait Get {
    /// Returned output.
    type Output: Sized;
    /// Type passed to the OS in the `getsockopt(2)` call.
    ///
    /// # Notes
    ///
    /// This is NOT part of the stable API, do NOT rely on the type exposed in
    /// the implementations.
    type Storage: Sized;

    /// Level to use, see [`Level`].
    const LEVEL: Level;
    /// Option to retrieve, see [`Opt`].
    const OPT: Opt;

    /// Returns a mutable raw pointer and length to `storage`.
    ///
    /// Default implementation casts a the pointer to `storage` and returns the
    /// size of `Storage` as length.
    ///
    /// # Safety
    ///
    /// Only initialised bytes may be written to the pointer returned.
    unsafe fn as_mut_ptr(storage: &mut MaybeUninit<Self::Storage>) -> (*mut std::ffi::c_void, u32) {
        (
            storage.as_mut_ptr().cast(),
            size_of::<Self::Storage>() as u32,
        )
    }

    /// Initialise the value from `storage`, to which at least `length` bytes
    /// have been written (by the kernel).
    ///
    /// # Safety
    ///
    /// Caller must ensure that at least `length` bytes have been written to
    /// `address`.
    unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> Self::Output;
}

/// Trait that defines how set the value of a socket option.
///
/// See [`AsyncFd::set_socket_option`].
///
/// [`AsyncFd::set_socket_option`]: crate::fd::AsyncFd::set_socket_option
pub trait Set {
    /// Value to set.
    type Value: Sized;
    /// Type passed to the OS in the `setsockopt(2)` call.
    ///
    /// # Notes
    ///
    /// This is NOT part of the stable API, do NOT rely on the type exposed in
    /// the implementations.
    type Storage: Sized;

    /// Level to use, see [`Level`].
    const LEVEL: Level;
    /// Option to retrieve, see [`Opt`].
    const OPT: Opt;

    /// Returns the value as storage for the OS to read.
    fn as_storage(value: Self::Value) -> Self::Storage;
}

new_option! {
    /// Get and clear the pending socket error.
    #[doc(alias = "SO_ERROR")]
    #[doc(alias = "take_error")] // Used by types in std lib.
    pub Error {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::ERROR;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> Option<io::Error> {
            assert!(length == size_of::<Self::Storage>() as u32);
            let errno = unsafe { storage.assume_init() };
            if errno == 0 {
                None
            } else {
                Some(io::Error::from_raw_os_error(errno))
            }
        }
    }

    /// Enable sending of keep-alive messages on connection-oriented
    /// sockets.
    #[doc(alias = "SO_KEEPALIVE")]
    pub KeepAlive {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::KEEP_ALIVE;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> bool {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init() >= 1 }
        }

        fn as_storage(value: bool) -> Self::Storage {
            value.into()
        }
    }

    /// Linger option.
    #[doc(alias = "SO_LINGER")]
    pub Linger {
        type Storage = libc::linger;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::LINGER;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> Option<u32> {
            assert!(length == size_of::<Self::Storage>() as u32);
            let linger = unsafe { storage.assume_init() };
            if linger.l_onoff > 0 {
                Some(linger.l_linger.cast_unsigned())
            } else {
                None
            }
        }

        fn as_storage(value: Option<u32>) -> Self::Storage {
            libc::linger {
                l_onoff: value.is_some().into(),
                l_linger: value.unwrap_or(0).cast_signed(),
            }
        }
    }

    /// Allow reuse of local addresses.
    #[doc(alias = "SO_REUSEADDR")]
    pub ReuseAddress {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::REUSE_ADDR;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> bool {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init() >= 1 }
        }

        fn as_storage(value: bool) -> Self::Storage {
            value.into()
        }
    }

    /// Allow multiple sockets to be bound to an identical socket address.
    #[doc(alias = "SO_REUSEPORT")]
    pub ReusePort {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::REUSE_PORT;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> bool {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init() >= 1 }
        }

        fn as_storage(value: bool) -> Self::Storage {
            value.into()
        }
    }

    /// Type.
    #[doc(alias = "SO_TYPE")]
    pub Type {
        type Storage = u32;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::TYPE;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> net::Type {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { net::Type(storage.assume_init()) }
        }
    }

    /// Maximum receive buffer in bytes.
    ///
    /// Linux doubles this value (to allow space for bookkeeping overhead) when
    /// it is set, and this doubled value is returned.
    #[doc(alias = "SO_RCVBUF")]
    pub RecvBuf {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::RECV_BUF;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> u32 {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init().cast_unsigned() }
        }

        fn as_storage(value: u32) -> Self::Storage {
            value.cast_signed()
        }
    }

    /// Maximum send buffer in bytes.
    ///
    /// Linux doubles this value (to allow space for bookkeeping overhead) when
    /// it is set, and this doubled value is returned.
    #[doc(alias = "SO_SNDBUF")]
    pub SendBuf {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::SEND_BUF;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> u32 {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init().cast_unsigned() }
        }

        fn as_storage(value: u32) -> Self::Storage {
            value.cast_signed()
        }
    }

    /// Minimum number of bytes in the buffer until the socket layer will pass
    /// the data to the user.
    #[doc(alias = "RECV_LOW_WATER")]
    pub RecvLowWater {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::RECV_LOW_WATER;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> u32 {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init().cast_unsigned() }
        }

        fn as_storage(value: u32) -> Self::Storage {
            value.cast_signed()
        }
    }

    /// Minimum number of bytes in the buffer until the socket layer will pass
    /// the data to the protocol.
    #[doc(alias = "SEND_LOW_WATER")]
    pub SendLowWater {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::SEND_LOW_WATER;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> u32 {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init().cast_unsigned() }
        }
    }

    /// Disable the Nagle algorithm.
    #[doc(alias = "TCP_NODELAY")]
    pub TcpNoDelay {
        type Storage = libc::c_int;
        const LEVEL = Level::TCP;
        const OPT = TcpOpt::NO_DELAY;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> bool {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init() >= 1 }
        }

        fn as_storage(value: bool) -> Self::Storage {
            value.into()
        }
    }
}

#[cfg(not(target_os = "openbsd"))]
new_option! {
    /// The maximum number of keepalive probes TCP should send before dropping
    /// the connection.
    #[doc(alias = "TCP_KEEPCNT")]
    pub TcpKeepAliveCount {
        type Storage = libc::c_int;
        const LEVEL = Level::TCP;
        const OPT = TcpOpt::KEEP_CNT;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> u32 {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init().cast_unsigned() }
        }

        fn as_storage(value: u32) -> Self::Storage {
            value.cast_signed()
        }
    }

    /// The time (in seconds) between individual keepalive probes.
    #[doc(alias = "TCP_KEEPINTVL")]
    pub TcpKeepAliveInterval {
        type Storage = libc::c_int;
        const LEVEL = Level::TCP;
        const OPT = TcpOpt::KEEP_INTVL;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> u32 {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init().cast_unsigned() }
        }

        fn as_storage(value: u32) -> Self::Storage {
            value.cast_signed()
        }
    }
}

#[cfg(any(
    target_os = "android",
    target_os = "freebsd",
    target_os = "linux",
    target_os = "netbsd"
))]
new_option! {
    /// Domain.
    #[doc(alias = "SO_DOMAIN")]
    pub Domain {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::DOMAIN;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> net::Domain {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { net::Domain(storage.assume_init()) }
        }
    }

    /// Retrieves the socket protocol.
    #[doc(alias = "SO_PROTOCOL")]
    pub Protocol {
        type Storage = u32;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::PROTOCOL;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> net::Protocol {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { net::Protocol(storage.assume_init()) }
        }
    }

    /// Returns a value indicating whether or not this socket has been
    /// marked to accept connections with `listen(2)`.
    #[doc(alias = "SO_ACCEPTCONN")]
    pub Accept {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::ACCEPT_CONN;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> bool {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init() >= 1 }
        }
    }

    /// The time (in seconds) the connection needs to remain idle before TCP
    /// starts sending keepalive probes, if the socket option [`KeepAlive`] has
    /// been set on this socket.
    #[doc(alias = "TCP_KEEPIDLE")]
    pub TcpKeepAliveIdle {
        type Storage = libc::c_int;
        const LEVEL = Level::TCP;
        const OPT = TcpOpt::KEEP_IDLE;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> u32 {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init().cast_unsigned() }
        }

        fn as_storage(value: u32) -> Self::Storage {
            value.cast_signed()
        }
    }
}

#[cfg(any(target_os = "android", target_os = "linux"))]
new_option! {
    /// CPU affinity.
    #[doc(alias = "SO_INCOMING_CPU")]
    pub IncomingCpu {
        type Storage = libc::c_int;
        const LEVEL = Level::SOCKET;
        const OPT = SocketOpt::INCOMING_CPU;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> Option<u32> {
            assert!(length == size_of::<Self::Storage>() as u32);
            let value = unsafe { storage.assume_init() };
            if value.is_negative() { None } else { Some(value.cast_unsigned()) }
        }

        fn as_storage(value: u32) -> Self::Storage {
            value.cast_signed()
        }
    }

    /// Don't send out partial frames. All queued partial frames are sent when
    /// the option is cleared again.
    #[doc(alias = "TCP_CORK")]
    pub TcpCork {
        type Storage = libc::c_int;
        const LEVEL = Level::TCP;
        const OPT = TcpOpt::CORK;

        unsafe fn init(storage: MaybeUninit<Self::Storage>, length: u32) -> bool {
            assert!(length == size_of::<Self::Storage>() as u32);
            unsafe { storage.assume_init() >= 1 }
        }

        fn as_storage(value: bool) -> Self::Storage {
            value.into()
        }
    }
}

macro_rules! new_option {
    (
        $(
        $(#[$type_meta:meta])*
        $type_vis: vis $type_name: ident {
            type Storage = $storage: ty;
            const LEVEL = $level: expr;
            const OPT = $opt: expr;

            // option::Get implementation.
            $(
            $(
            unsafe fn as_mut_ptr($as_mut_ptr_storage: ident: &mut MaybeUninit<Self::Storage>) -> (*mut std::ffi::c_void, u32) $as_mut_ptr: block
            )?

            unsafe fn init($init_storage: ident: MaybeUninit<Self::Storage>, $init_length: ident: u32) -> $output: ty $init: block
            )?

            // option::Set implementation.
            $(
            fn as_storage($as_storage_value: ident: $value: ty) -> Self::Storage $as_storage: block
            )?
        }
        )*
    ) => {
        $(
        $(#[$type_meta])*
        #[allow(missing_debug_implementations)]
        pub enum $type_name {}

        $(
        impl Get for $type_name {
            type Output = $output;
            #[doc(hidden)] // Not part of the stable API.
            type Storage = $storage;

            const LEVEL: Level = $level;
            const OPT: Opt = $opt.into_opt();

            $(
            unsafe fn as_mut_ptr($as_mut_ptr_storage: &mut MaybeUninit<Self::Storage>) -> (*mut std::ffi::c_void, u32) {
                $as_mut_ptr
            }
            )?

            unsafe fn init($init_storage: MaybeUninit<Self::Storage>, $init_length: u32) -> Self::Output {
                $init
            }
        }
        )?

        $(
        impl Set for $type_name {
            type Value = $value;
            #[doc(hidden)] // Not part of the stable API.
            type Storage = $storage;

            const LEVEL: Level = $level;
            const OPT: Opt = $opt.into_opt();

            fn as_storage($as_storage_value: Self::Value) -> Self::Storage {
                $as_storage
            }
        }
        )?
        )*
    };
}

use new_option;