uni-addr 0.3.8

A unified address type that can represent a `std::net::SocketAddr`, a `std::os::unix::net::SocketAddr`, or a host name with port.
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
//! Platform-specific code for Unix-like systems

use std::ffi::{CStr, OsStr, OsString};
use std::hash::{Hash, Hasher};
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::{fmt, fs, io};

wrapper_lite::general_wrapper! {
    #[wrapper_impl(Deref)]
    #[derive(Clone)]
    /// Wrapper over [`std::os::unix::net::SocketAddr`].
    ///
    /// See [`SocketAddr::new`] for more details.
    pub struct SocketAddr(std::os::unix::net::SocketAddr);
}

impl SocketAddr {
    /// Creates a new [`SocketAddr`] from its string representation.
    ///
    /// # Address Types
    ///
    /// - Strings starting with `@` or `\0` are parsed as abstract unix socket
    ///   addresses (Linux-specific).
    /// - All other strings are parsed as pathname unix socket addresses.
    /// - Empty strings create unnamed unix socket addresses.
    ///
    /// # Notes
    ///
    /// This method accepts an [`OsStr`] and does not guarantee proper null
    /// termination. While pathname addresses reject interior null bytes,
    /// abstract addresses accept them silently, potentially causing unexpected
    /// behavior (e.g., `\0abstract` differs from `\0abstract\0\0\0\0\0...`).
    /// Use [`SocketAddr::new_strict`] to ensure the abstract names do not
    /// contain null bytes, too.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use uni_addr::unix::SocketAddr;
    /// #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
    /// // Abstract address (Linux-specific)
    /// let abstract_addr = SocketAddr::new("@abstract.example.socket").unwrap();
    /// // Pathname address
    /// let pathname_addr = SocketAddr::new("/run/pathname.example.socket").unwrap();
    /// // Unnamed address
    /// let unnamed_addr = SocketAddr::new("").unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the address is invalid or unsupported on the
    /// current platform.
    ///
    /// See [`SocketAddr::from_abstract_name`](std::os::linux::net::SocketAddrExt::from_abstract_name)
    /// and [`SocketAddr::from_pathname`](std::os::unix::net::SocketAddr::from_pathname) for more details.
    pub fn new<S: AsRef<OsStr> + ?Sized>(addr: &S) -> io::Result<Self> {
        let addr = addr.as_ref();

        match addr.as_bytes() {
            #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
            [b'@' | b'\0', rest @ ..] => Self::new_abstract(rest),
            #[cfg(not(any(target_os = "android", target_os = "linux", target_os = "cygwin")))]
            [b'@' | b'\0', ..] => Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "abstract unix socket address is not supported",
            )),
            _ => Self::new_pathname(addr),
        }
    }

    /// See [`SocketAddr::new`].
    ///
    /// # Errors
    ///
    /// See [`SocketAddr::new`].
    pub fn new_strict<S: AsRef<OsStr> + ?Sized>(addr: &S) -> io::Result<Self> {
        let addr = addr.as_ref();

        match addr.as_bytes() {
            #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
            [b'@' | b'\0', rest @ ..] => Self::new_abstract_strict(rest),
            #[cfg(not(any(target_os = "android", target_os = "linux", target_os = "cygwin")))]
            [b'@' | b'\0', ..] => Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "abstract unix socket address is not supported",
            )),
            _ => Self::new_pathname(addr),
        }
    }

    #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
    /// Creates a Unix socket address in the abstract namespace.
    ///
    /// The abstract namespace is a Linux-specific extension that allows Unix
    /// sockets to be bound without creating an entry in the filesystem.
    /// Abstract sockets are unaffected by filesystem layout or permissions, and
    /// no cleanup is necessary when the socket is closed.
    ///
    /// An abstract socket address name may contain any bytes, including zero.
    /// However, we don't recommend using zero bytes, as they may lead to
    /// unexpected behavior. To avoid this, consider using
    /// [`new_abstract_strict`](Self::new_abstract_strict).
    ///
    /// # Errors
    ///
    /// Returns an error if the name is longer than `SUN_LEN - 1`.
    pub fn new_abstract(bytes: &[u8]) -> io::Result<Self> {
        #[cfg(target_os = "android")]
        use std::os::android::net::SocketAddrExt;
        #[cfg(target_os = "cygwin")]
        use std::os::cygwin::net::SocketAddrExt;
        #[cfg(target_os = "linux")]
        use std::os::linux::net::SocketAddrExt;

        std::os::unix::net::SocketAddr::from_abstract_name(bytes).map(Self::from_inner)
    }

    #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
    /// See [`SocketAddr::new_abstract`].
    ///
    /// # Errors
    ///
    /// See [`SocketAddr::new_abstract`].
    pub fn new_abstract_strict(bytes: &[u8]) -> io::Result<Self> {
        if bytes.is_empty() || bytes.contains(&b'\0') {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "parse abstract socket name in strict mode: reject NULL bytes",
            ));
        }

        Self::new_abstract(bytes)
    }

    /// Constructs a [`SocketAddr`] with the family `AF_UNIX` and the provided
    /// path.
    ///
    /// # Errors
    ///
    /// Returns an error if the path is longer than `SUN_LEN` or if it contains
    /// NULL bytes.
    pub fn new_pathname<P: AsRef<Path>>(pathname: P) -> io::Result<Self> {
        let _ = fs::remove_file(pathname.as_ref());

        std::os::unix::net::SocketAddr::from_pathname(pathname).map(Self::from_inner)
    }

    #[allow(clippy::missing_panics_doc)]
    /// Creates an unnamed [`SocketAddr`].
    pub fn new_unnamed() -> Self {
        // SAFETY: `from_pathname` will not fail at all.
        std::os::unix::net::SocketAddr::from_pathname("")
            .map(Self::from_inner)
            .unwrap()
    }

    #[inline]
    /// Creates a new [`SocketAddr`] from bytes.
    ///
    /// # Errors
    ///
    /// See [`SocketAddr::new`].
    pub fn from_bytes(bytes: &[u8]) -> io::Result<Self> {
        Self::new(OsStr::from_bytes(bytes))
    }

    #[inline]
    /// Creates a new [`SocketAddr`] from bytes with null termination.
    ///
    /// Notes that for abstract addresses, the first byte is also `\0`, which is
    /// not treated as the termination byte. And the abstract name starts from
    /// the second byte. cannot be empty or contain interior null bytes, i.e.,
    /// we will reject bytes like `b"\0\0\0..."`. Although `\0\0...` is a valid
    /// abstract name, we will reject it to avoid potential confusion. See
    /// [`SocketAddr::new_abstract_strict`] for more details.
    ///
    /// # Errors
    ///
    /// See [`SocketAddr::new`].
    pub fn from_bytes_until_nul(bytes: &[u8]) -> io::Result<Self> {
        #[allow(clippy::single_match_else)]
        match bytes {
            #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
            [b'\0', rest @ ..] => {
                let addr = CStr::from_bytes_until_nul(rest)
                    .map(CStr::to_bytes)
                    .unwrap_or(rest);

                Self::new_abstract_strict(addr)
            }
            #[cfg(not(any(target_os = "android", target_os = "linux", target_os = "cygwin")))]
            [b'\0', ..] => Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "abstract unix socket address is not supported",
            )),
            _ => {
                let addr = CStr::from_bytes_until_nul(bytes)
                    .map(CStr::to_bytes)
                    .unwrap_or(bytes);

                Self::new_pathname(OsStr::from_bytes(addr))
            }
        }
    }

    /// Serializes the [`SocketAddr`] to an `OsString`.
    ///
    /// # Returns
    ///
    /// - For abstract ones: returns the name prefixed with **`\0`**
    /// - For pathname ones: returns the pathname
    /// - For unnamed ones: returns an empty string.
    pub fn to_os_string(&self) -> OsString {
        self.to_os_string_impl("", "\0")
    }

    /// Likes [`to_os_string`](Self::to_os_string), but returns a `String`
    /// instead of `OsString`, performing lossy UTF-8 conversion.
    ///
    /// # Returns
    ///
    /// - For abstract ones: returns the name prefixed with **`@`**
    /// - For pathname ones: returns the pathname
    /// - For unnamed ones: returns an empty string.
    pub fn to_string_lossy(&self) -> String {
        self.to_os_string_impl("", "@")
            .to_string_lossy()
            .into_owned()
    }

    #[cfg_attr(
        not(any(target_os = "android", target_os = "linux", target_os = "cygwin")),
        allow(unused_variables)
    )]
    pub(crate) fn to_os_string_impl(&self, prefix: &str, abstract_identifier: &str) -> OsString {
        let mut os_string = OsString::from(prefix);

        if let Some(pathname) = self.as_pathname() {
            // Notice: cannot use `extend` here
            os_string.push(pathname);

            return os_string;
        }

        #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
        {
            #[cfg(target_os = "android")]
            use std::os::android::net::SocketAddrExt;
            #[cfg(target_os = "cygwin")]
            use std::os::cygwin::net::SocketAddrExt;
            #[cfg(target_os = "linux")]
            use std::os::linux::net::SocketAddrExt;

            if let Some(abstract_name) = self.as_abstract_name() {
                os_string.push(abstract_identifier);
                os_string.push(OsStr::from_bytes(abstract_name));

                return os_string;
            }
        }

        // An unnamed one...
        os_string
    }
}

impl fmt::Debug for SocketAddr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_inner().fmt(f)
    }
}

impl PartialEq for SocketAddr {
    fn eq(&self, other: &Self) -> bool {
        if let Some((l, r)) = self.as_pathname().zip(other.as_pathname()) {
            return l == r;
        }

        #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
        {
            #[cfg(target_os = "android")]
            use std::os::android::net::SocketAddrExt;
            #[cfg(target_os = "cygwin")]
            use std::os::cygwin::net::SocketAddrExt;
            #[cfg(target_os = "linux")]
            use std::os::linux::net::SocketAddrExt;

            if let Some((l, r)) = self.as_abstract_name().zip(other.as_abstract_name()) {
                return l == r;
            }
        }

        if self.is_unnamed() && other.is_unnamed() {
            return true;
        }

        false
    }
}

impl Eq for SocketAddr {}

impl Hash for SocketAddr {
    fn hash<H: Hasher>(&self, state: &mut H) {
        if let Some(pathname) = self.as_pathname() {
            pathname.hash(state);

            return;
        }

        #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
        {
            #[cfg(target_os = "android")]
            use std::os::android::net::SocketAddrExt;
            #[cfg(target_os = "cygwin")]
            use std::os::cygwin::net::SocketAddrExt;
            #[cfg(target_os = "linux")]
            use std::os::linux::net::SocketAddrExt;

            if let Some(abstract_name) = self.as_abstract_name() {
                b'\0'.hash(state);
                abstract_name.hash(state);

                return;
            }
        }

        debug_assert!(self.is_unnamed(), "SocketAddr is not unnamed one");

        // `Path` cannot contain null bytes, and abstract names are started with
        // null bytes, this is Ok.
        b"(unnamed)\0".hash(state);
    }
}

#[cfg(feature = "feat-serde")]
impl serde::Serialize for SocketAddr {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string_lossy())
    }
}

#[cfg(feature = "feat-serde")]
impl<'de> serde::Deserialize<'de> for SocketAddr {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::new(<&str>::deserialize(deserializer)?).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_unnamed() {
        const TEST_CASE: &str = "";

        let addr = SocketAddr::new(TEST_CASE).unwrap();

        assert!(addr.as_ref().is_unnamed());
    }

    #[test]
    fn test_pathname() {
        const TEST_CASE: &str = "/tmp/test_pathname.socket";

        let addr = SocketAddr::new(TEST_CASE).unwrap();

        assert_eq!(addr.to_os_string().to_str().unwrap(), TEST_CASE);
        assert_eq!(addr.to_string_lossy(), TEST_CASE);
        assert_eq!(addr.as_pathname().unwrap().to_str().unwrap(), TEST_CASE);
    }

    #[test]
    #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
    fn test_abstract() {
        #[cfg(target_os = "android")]
        use std::os::android::net::SocketAddrExt;
        #[cfg(target_os = "cygwin")]
        use std::os::cygwin::net::SocketAddrExt;
        #[cfg(target_os = "linux")]
        use std::os::linux::net::SocketAddrExt;

        const TEST_CASE_1: &[u8] = b"@abstract.socket";
        const TEST_CASE_2: &[u8] = b"\0abstract.socket";
        const TEST_CASE_3: &[u8] = b"@";
        const TEST_CASE_4: &[u8] = b"\0";

        assert_eq!(
            SocketAddr::new(OsStr::from_bytes(TEST_CASE_1))
                .unwrap()
                .as_abstract_name()
                .unwrap(),
            &TEST_CASE_1[1..]
        );

        assert_eq!(
            SocketAddr::new(OsStr::from_bytes(TEST_CASE_2))
                .unwrap()
                .as_abstract_name()
                .unwrap(),
            &TEST_CASE_2[1..]
        );

        assert_eq!(
            SocketAddr::new(OsStr::from_bytes(TEST_CASE_3))
                .unwrap()
                .as_abstract_name()
                .unwrap(),
            &TEST_CASE_3[1..]
        );

        assert_eq!(
            SocketAddr::new(OsStr::from_bytes(TEST_CASE_4))
                .unwrap()
                .as_abstract_name()
                .unwrap(),
            &TEST_CASE_4[1..]
        );
    }

    #[test]
    #[should_panic]
    fn test_pathname_with_null_byte() {
        let _addr = SocketAddr::new_pathname("(unamed)\0").unwrap();
    }

    #[test]
    fn test_partial_eq_hash() {
        let addr_pathname_1 = SocketAddr::new("/tmp/test_pathname_1.socket").unwrap();
        let addr_pathname_2 = SocketAddr::new("/tmp/test_pathname_2.socket").unwrap();
        let addr_unnamed = SocketAddr::new_unnamed();

        assert_eq!(addr_pathname_1, addr_pathname_1);
        assert_ne!(addr_pathname_1, addr_pathname_2);
        assert_ne!(addr_pathname_2, addr_pathname_1);

        assert_eq!(addr_unnamed, addr_unnamed);
        assert_ne!(addr_pathname_1, addr_unnamed);
        assert_ne!(addr_unnamed, addr_pathname_1);
        assert_ne!(addr_pathname_2, addr_unnamed);
        assert_ne!(addr_unnamed, addr_pathname_2);

        #[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
        {
            use core::hash::{BuildHasher, Hash, Hasher};

            use foldhash::fast::RandomState;

            let addr_abstract_1 = SocketAddr::new_abstract(b"/tmp/test_pathname_1.socket").unwrap();
            let addr_abstract_2 = SocketAddr::new_abstract(b"/tmp/test_pathname_2.socket").unwrap();
            let addr_abstract_empty = SocketAddr::new_abstract(&[]).unwrap();
            let addr_abstract_unnamed = SocketAddr::new_abstract(b"(unamed)\0").unwrap();

            assert_eq!(addr_abstract_1, addr_abstract_1);
            assert_ne!(addr_abstract_1, addr_abstract_2);
            assert_ne!(addr_abstract_2, addr_abstract_1);

            // Empty abstract addresses should be equal to unnamed addresses
            assert_ne!(addr_unnamed, addr_abstract_empty);

            // Abstract addresses should not be equal to pathname addresses
            assert_ne!(addr_pathname_1, addr_abstract_1);

            // Abstract unnamed address `@(unamed)\0`' hash should not be equal to unname
            // ones'
            let state = RandomState::default();
            let addr_unnamed_hash = {
                let mut state = state.build_hasher();
                addr_unnamed.hash(&mut state);
                state.finish()
            };
            let addr_abstract_unnamed_hash = {
                let mut state = state.build_hasher();
                addr_abstract_unnamed.hash(&mut state);
                state.finish()
            };
            assert_ne!(addr_unnamed_hash, addr_abstract_unnamed_hash);
        }
    }
}