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
use std::ascii;
use std::fmt;
use std::io;
use std::mem;
use std::path::Path;
use std::os::raw::{c_char, c_int};

use winapi::SOCKADDR;
use ws2_32::WSAGetLastError;

mod ext;
mod net;
mod socket;

mod c {
    use std::ffi::CStr;
    use std::fmt;
    use winapi::{self, ADDRESS_FAMILY, CHAR};

    pub const AF_UNIX: ADDRESS_FAMILY = winapi::AF_UNIX as _;

    #[allow(non_camel_case_types)]
    #[derive(Copy, Clone)]
    #[repr(C)]
    pub struct sockaddr_un {
        pub sun_family: ADDRESS_FAMILY,
        pub sun_path: [CHAR; 108],
    }

    impl fmt::Debug for sockaddr_un {
        fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
            let path = unsafe {
                CStr::from_ptr(&self.sun_path as *const _).to_str()
            };
            fmt.debug_struct("sockaddr_un")
                .field("sun_family", &self.sun_family)
                .field("sun_path", &path.unwrap_or("???"))
                .finish()
        }
    }
}

pub fn sun_path_offset() -> usize {
    // Work with an actual instance of the type since using a null pointer is UB
    let addr: c::sockaddr_un = unsafe { mem::uninitialized() };
    let base = &addr as *const _ as usize;
    let path = &addr.sun_path as *const _ as usize;
    path - base
}

pub unsafe fn sockaddr_un(path: &Path) -> io::Result<(c::sockaddr_un, c_int)> {
    let mut addr: c::sockaddr_un = mem::zeroed();
    addr.sun_family = c::AF_UNIX;

    // Winsock2 expects 'sun_path' to be a Win32 UTF-8 file system path
    let bytes = path
        .to_str()
        .map(|s| s.as_bytes())
        .ok_or(io::Error::new(io::ErrorKind::InvalidInput,
                              "path contains invalid characters"))?;

    if bytes.contains(&0) {
        return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                  "paths may not contain interior null bytes"));
    }

    if bytes.len() >= addr.sun_path.len() {
        return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                  "path must be shorter than SUN_LEN"));
    }
    for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
        *dst = *src as c_char;
    }
    // null byte for pathname addresses is already there because we zeroed the
    // struct

    let mut len = sun_path_offset() + bytes.len();
    match bytes.get(0) {
        Some(&0) | None => {}
        Some(_) => len += 1,
    }
    Ok((addr, len as c_int))
}

/// Returns the last error from the Windows socket interface.
fn last_error() -> io::Error {
    io::Error::from_raw_os_error(unsafe { WSAGetLastError() })
}

pub trait IsMinusOne {
    fn is_minus_one(&self) -> bool;
}

macro_rules! impl_is_minus_one {
    ($($t:ident)*) => ($(impl IsMinusOne for $t {
        fn is_minus_one(&self) -> bool {
            *self == -1
        }
    })*)
}

impl_is_minus_one! { i8 i16 i32 i64 isize }

/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
/// and if so, returns the last error from the Windows socket interface. This
/// function must be called before another call to the socket API is made.
pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
    if t.is_minus_one() {
        Err(last_error())
    } else {
        Ok(t)
    }
}

enum AddressKind<'a> {
    Unnamed,
    Pathname(&'a Path),
    Abstract(&'a [u8]),
}

/// An address associated with a Unix socket
///
/// # Examples
///
/// ```no_run
/// use uds_windows::UnixListener;
///
/// let l = UnixListener::bind("/tmp/sock").unwrap();
/// let addr = l.local_addr().expect("Couldn't get local address");
/// ```
#[derive(Copy, Clone)]
pub struct SocketAddr {
    addr: c::sockaddr_un,
    len: c_int,
}

impl SocketAddr {
    fn new<F>(f: F) -> io::Result<SocketAddr>
        where F: FnOnce(*mut SOCKADDR, *mut c_int) -> c_int
    {
        unsafe {
            let mut addr: c::sockaddr_un = mem::zeroed();
            let mut len = mem::size_of::<c::sockaddr_un>() as c_int;
            cvt(f(&mut addr as *mut _ as *mut _, &mut len))?;
            SocketAddr::from_parts(addr, len)
        }
    }

    fn from_parts(addr: c::sockaddr_un, mut len: c_int) -> io::Result<SocketAddr> {
        if len == 0 {
            // When there is a datagram from unnamed unix socket
            // linux returns zero bytes of address
            len = sun_path_offset() as c_int;  // i.e. zero-length address
        } else if addr.sun_family != c::AF_UNIX {
            return Err(io::Error::new(io::ErrorKind::InvalidInput,
                                      "file descriptor did not correspond to a Unix socket"));
        }

        Ok(SocketAddr {
            addr,
            len,
        })
    }

    /// Returns true if and only if the address is unnamed.
    ///
    /// # Examples
    ///
    /// A named address:
    ///
    /// ```no_run
    /// use uds_windows::UnixListener;
    ///
    /// let socket = UnixListener::bind("/tmp/sock").unwrap();
    /// let addr = socket.local_addr().expect("Couldn't get local address");
    /// assert_eq!(addr.is_unnamed(), false);
    /// ```

    // TODO: Is this following section relevant on Windows? Removed from the
    //       docs for now...
    // An unnamed address:
    //
    // ```ignore
    // use std::os::windows::net::UnixDatagram;
    //
    // let socket = UnixDatagram::unbound().unwrap();
    // let addr = socket.local_addr().expect("Couldn't get local address");
    // assert_eq!(addr.is_unnamed(), true);
    // ```
    pub fn is_unnamed(&self) -> bool {
        if let AddressKind::Unnamed = self.address() {
            true
        } else {
            false
        }
    }

    /// Returns the contents of this address if it is a `pathname` address.
    ///
    /// # Examples
    ///
    /// With a pathname:
    ///
    /// ```no_run
    /// use uds_windows::UnixListener;
    /// use std::path::Path;
    ///
    /// let socket = UnixListener::bind("/tmp/sock").unwrap();
    /// let addr = socket.local_addr().expect("Couldn't get local address");
    /// assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/sock")));
    /// ```

    // TODO: Is this following section relevant on Windows? Removed from the
    //       docs for now...
    // Without a pathname:
    // 
    // ```ignore
    // use std::os::windows::net::UnixDatagram;
    // 
    // let socket = UnixDatagram::unbound().unwrap();
    // let addr = socket.local_addr().expect("Couldn't get local address");
    // assert_eq!(addr.as_pathname(), None);
    // ```
    pub fn as_pathname(&self) -> Option<&Path> {
        if let AddressKind::Pathname(path) = self.address() {
            Some(path)
        } else {
            None
        }
    }

    fn address<'a>(&'a self) -> AddressKind<'a> {
        let len = self.len as usize - sun_path_offset();
        // sockaddr_un::sun_path on Windows is a Win32 UTF-8 file system path
        let path = unsafe { mem::transmute::<&[c_char], &[u8]>(&self.addr.sun_path) };

        // macOS seems to return a len of 16 and a zeroed sun_path for unnamed addresses
        if len == 0
            || (cfg!(not(any(target_os = "linux", target_os = "android")))
                && self.addr.sun_path[0] == 0)
        {
            AddressKind::Unnamed
        } else if self.addr.sun_path[0] == 0 {
            AddressKind::Abstract(&path[1..len])
        } else {
            use std::ffi::CStr;
            let pathname = unsafe { CStr::from_bytes_with_nul_unchecked(&path[..len]) };
            AddressKind::Pathname(Path::new(pathname.to_str().unwrap()))
        }
    }
}

impl fmt::Debug for SocketAddr {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self.address() {
            AddressKind::Unnamed => write!(fmt, "(unnamed)"),
            AddressKind::Abstract(name) => write!(fmt, "{} (abstract)", AsciiEscaped(name)),
            AddressKind::Pathname(path) => write!(fmt, "{:?} (pathname)", path),
        }
    }
}

impl PartialEq for SocketAddr {
    fn eq(&self, other: &SocketAddr) -> bool {
        let ita = self.addr.sun_path.iter();
        let itb = other.addr.sun_path.iter();

        self.len == other.len &&
            self.addr.sun_family == other.addr.sun_family &&
                ita.zip(itb).all(|(a, b)| a == b)
    }
}

pub fn from_sockaddr_un(addr: c::sockaddr_un, len: c_int) -> io::Result<SocketAddr> {
    SocketAddr::from_parts(addr, len)
}

pub fn from_path(path: &Path) -> io::Result<SocketAddr> {
    let (addr, len) = unsafe { sockaddr_un(path)? };
    SocketAddr::from_parts(addr, len)
}

struct AsciiEscaped<'a>(&'a [u8]);

impl<'a> fmt::Display for AsciiEscaped<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "\"")?;
        for byte in self.0.iter().cloned().flat_map(ascii::escape_default) {
            write!(fmt, "{}", byte as char)?;
        }
        write!(fmt, "\"")
    }
}

pub use self::ext::{AcceptAddrs, AcceptAddrsBuf, UnixListenerExt, UnixStreamExt};
pub use self::net::{UnixListener, UnixStream};
pub use self::socket::{init, Socket};