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
// Copyright (C) 2014-2016 Mickaël Salaün
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#![allow(deprecated)]

extern crate fd;
extern crate libc;
extern crate unix_socket;

use fd::FileDesc;
use ffi::{Cmsghdr, Iovec, Msghdr, Scm, SOL_SOCKET, recvmsg, sendmsg};
use libc::{size_t, c_void};
use std::io;
use std::os::unix::io::{AsRawFd, RawFd};
use unix_socket::UnixStream;

mod ffi;

#[repr(C)]
struct FdPadding {
    pub fd: RawFd,
    /* __cmsg_data must be align with size_t */
    #[cfg(target_arch = "x86_64")]
    _padding: u32,
}

impl FdPadding {
    #[cfg(target_arch = "x86_64")]
    pub fn new(fd: RawFd) -> FdPadding {
        FdPadding {
            fd: fd,
            _padding: 0,
        }
    }
    #[cfg(not(target_arch = "x86_64"))]
    pub fn new(fd: RawFd) -> FdPadding {
        FdPadding {
            fd: fd,
        }
    }
}

// TODO: Return iov
// pub fn recv_fd(stream: &mut UnixStream) -> io::Result<(FileDesc, Vec<u8>)> {
pub fn recv_fd(stream: &mut UnixStream, iov_expect: Vec<u8>) -> io::Result<FileDesc> {
    let fd = FdPadding::new(-1 as RawFd);
    match recvmsg(stream, iov_expect.len(), fd) {
        // TODO: Check size?
        Ok((_, iov_recv, data)) => {
            if iov_recv != iov_expect {
                return Err(io::Error::new(io::ErrorKind::Other, "Receive"));
            }
            Ok(FileDesc::new(data.fd, true))
        }
        Err(e) => Err(e),
    }
}

pub fn send_fd(stream: &mut UnixStream, id: &[u8], fd: &AsRawFd) -> io::Result<()> {
    let mut iovv = vec!(Iovec {
        iov_base: id.as_ptr() as *const c_void,
        iov_len: id.len() as size_t,
    });
    let fda = FdPadding::new(fd.as_raw_fd());
    let mut ctrl = Cmsghdr::new(SOL_SOCKET, Scm::Rights, fda);
    let msg = Msghdr::new(None, &mut iovv, &mut ctrl, None);
    match sendmsg(stream, &msg) {
        Ok(_) => Ok(()),
        Err(e) => Err(e),
    }
}