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
use std::io::{Read, Write};
use std::mem;
use std::net::Shutdown;
use std::os::unix::prelude::*;
use std::path::Path;
use std::ptr;

use libc;

use {io, Ready, Poll, PollOpt, Token};
use event::Evented;
use sys::unix::{cvt, Io};
use sys::unix::io::{set_nonblock, set_cloexec};

trait MyInto<T> {
    fn my_into(self) -> T;
}

impl MyInto<u32> for usize {
    fn my_into(self) -> u32 { self as u32 }
}

impl MyInto<usize> for usize {
    fn my_into(self) -> usize { self }
}

unsafe fn sockaddr_un(path: &Path)
                      -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
    let mut addr: libc::sockaddr_un = mem::zeroed();
    addr.sun_family = libc::AF_UNIX as libc::sa_family_t;

    let bytes = path.as_os_str().as_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 libc::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 libc::socklen_t))
}

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

#[derive(Debug)]
pub struct UnixSocket {
    io: Io,
}

impl UnixSocket {
    /// Returns a new, unbound, non-blocking Unix domain socket
    pub fn stream() -> io::Result<UnixSocket> {
        #[cfg(target_os = "linux")]
        use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK};
        #[cfg(not(target_os = "linux"))]
        const SOCK_CLOEXEC: libc::c_int = 0;
        #[cfg(not(target_os = "linux"))]
        const SOCK_NONBLOCK: libc::c_int = 0;

        unsafe {
            if cfg!(target_os = "linux") {
                let flags = libc::SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
                match cvt(libc::socket(libc::AF_UNIX, flags, 0)) {
                    Ok(fd) => return Ok(UnixSocket::from_raw_fd(fd)),
                    Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
                    Err(e) => return Err(e),
                }
            }

            let fd = cvt(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0))?;
            let fd = UnixSocket::from_raw_fd(fd);
            set_cloexec(fd.as_raw_fd())?;
            set_nonblock(fd.as_raw_fd())?;
            Ok(fd)
        }
    }

    /// Connect the socket to the specified address
    pub fn connect<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> {
        unsafe {
            let (addr, len) = sockaddr_un(addr.as_ref())?;
            cvt(libc::connect(self.as_raw_fd(),
                                   &addr as *const _ as *const _,
                                   len))?;
            Ok(())
        }
    }

    /// Listen for incoming requests
    pub fn listen(&self, backlog: usize) -> io::Result<()> {
        unsafe {
            cvt(libc::listen(self.as_raw_fd(), backlog as i32))?;
            Ok(())
        }
    }

    pub fn accept(&self) -> io::Result<UnixSocket> {
        unsafe {
            let fd = cvt(libc::accept(self.as_raw_fd(),
                                           ptr::null_mut(),
                                           ptr::null_mut()))?;
            let fd = Io::from_raw_fd(fd);
            set_cloexec(fd.as_raw_fd())?;
            set_nonblock(fd.as_raw_fd())?;
            Ok(UnixSocket { io: fd })
        }
    }

    /// Bind the socket to the specified address
    pub fn bind<P: AsRef<Path> + ?Sized>(&self, addr: &P) -> io::Result<()> {
        unsafe {
            let (addr, len) = sockaddr_un(addr.as_ref())?;
            cvt(libc::bind(self.as_raw_fd(),
                                &addr as *const _ as *const _,
                                len))?;
            Ok(())
        }
    }

    pub fn try_clone(&self) -> io::Result<UnixSocket> {
        Ok(UnixSocket { io: self.io.try_clone()? })
    }

    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
        let how = match how {
            Shutdown::Read => libc::SHUT_RD,
            Shutdown::Write => libc::SHUT_WR,
            Shutdown::Both => libc::SHUT_RDWR,
        };
        unsafe {
            cvt(libc::shutdown(self.as_raw_fd(), how))?;
            Ok(())
        }
    }

    pub fn read_recv_fd(&mut self, buf: &mut [u8]) -> io::Result<(usize, Option<RawFd>)> {
        unsafe {
            let mut iov = libc::iovec {
                iov_base: buf.as_mut_ptr() as *mut _,
                iov_len: buf.len(),
            };
            struct Cmsg {
                hdr: libc::cmsghdr,
                data: [libc::c_int; 1],
            }
            let mut cmsg: Cmsg = mem::zeroed();
            let mut msg: libc::msghdr = mem::zeroed();
            msg.msg_iov = &mut iov;
            msg.msg_iovlen = 1;
            msg.msg_control = &mut cmsg as *mut _ as *mut _;
            msg.msg_controllen = mem::size_of_val(&cmsg).my_into();
            let bytes = cvt(libc::recvmsg(self.as_raw_fd(), &mut msg, 0))?;

            const SCM_RIGHTS: libc::c_int = 1;

            let fd = if cmsg.hdr.cmsg_level == libc::SOL_SOCKET &&
                        cmsg.hdr.cmsg_type == SCM_RIGHTS {
                Some(cmsg.data[0])
            } else {
                None
            };
            Ok((bytes as usize, fd))
        }
    }

    pub fn write_send_fd(&mut self, buf: &[u8], fd: RawFd) -> io::Result<usize> {
        unsafe {
            let mut iov = libc::iovec {
                iov_base: buf.as_ptr() as *mut _,
                iov_len: buf.len(),
            };
            struct Cmsg {
                hdr: libc::cmsghdr,
                data: [libc::c_int; 1],
            }
            let mut cmsg: Cmsg = mem::zeroed();
            cmsg.hdr.cmsg_len = mem::size_of_val(&cmsg).my_into();
            cmsg.hdr.cmsg_level = libc::SOL_SOCKET;
            cmsg.hdr.cmsg_type = 1; // SCM_RIGHTS
            cmsg.data[0] = fd;
            let mut msg: libc::msghdr = mem::zeroed();
            msg.msg_iov = &mut iov;
            msg.msg_iovlen = 1;
            msg.msg_control = &mut cmsg as *mut _ as *mut _;
            msg.msg_controllen = mem::size_of_val(&cmsg).my_into();
            let bytes = cvt(libc::sendmsg(self.as_raw_fd(), &msg, 0))?;
            Ok(bytes as usize)
        }
    }
}

impl Read for UnixSocket {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.io.read(buf)
    }
}

impl Write for UnixSocket {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.io.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.io.flush()
    }
}

impl Evented for UnixSocket {
    fn register(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
        self.io.register(poll, token, interest, opts)
    }

    fn reregister(&self, poll: &Poll, token: Token, interest: Ready, opts: PollOpt) -> io::Result<()> {
        self.io.reregister(poll, token, interest, opts)
    }

    fn deregister(&self, poll: &Poll) -> io::Result<()> {
        self.io.deregister(poll)
    }
}


impl From<Io> for UnixSocket {
    fn from(io: Io) -> UnixSocket {
        UnixSocket { io }
    }
}

impl FromRawFd for UnixSocket {
    unsafe fn from_raw_fd(fd: RawFd) -> UnixSocket {
        UnixSocket { io: Io::from_raw_fd(fd) }
    }
}

impl IntoRawFd for UnixSocket {
    fn into_raw_fd(self) -> RawFd {
        self.io.into_raw_fd()
    }
}

impl AsRawFd for UnixSocket {
    fn as_raw_fd(&self) -> RawFd {
        self.io.as_raw_fd()
    }
}