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
use super::{super::AF_UNIX, SockAddr};

pub enum FromPathnameError {
    NullByte,
    TooLarge,
}

#[repr(C)]
#[allow(non_camel_case_types)]
pub struct SockAddrUn {
    family: u16,
    pub path: [u8; Self::PATH_LEN],
}

impl SockAddrUn {
    const PATH_LEN: usize = 108;

    pub fn new(path: [u8; 108]) -> Self {
        Self {
            family: AF_UNIX.into(),
            path,
        }
    }

    /// Create a pathname UNIX socket address.
    ///
    /// # Errors
    ///
    /// An error is returned if the address contains a null byte or if it is too long.
    pub fn from_pathname(pathname: &impl AsRef<[u8]>) -> Result<Self, FromPathnameError> {
        let pathname = pathname.as_ref();
        if pathname.len() >= Self::PATH_LEN {
            return Err(FromPathnameError::TooLarge);
        }
        if pathname.contains(&0) {
            return Err(FromPathnameError::NullByte);
        }
        let mut path = [0; Self::PATH_LEN];
        path[..pathname.len()].copy_from_slice(&pathname);
        Ok(Self::new(path))
    }
}

unsafe impl SockAddr for SockAddrUn {
    fn family() -> u8 {
        AF_UNIX
    }
}