summaryrefslogtreecommitdiff
path: root/src/sys/socket/mod.rs
blob: da29ae881cfb3a45348216e31ef7cedbe2edbcb0 (plain)
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
use {NixError, NixResult, from_ffi};
use errno::Errno;
use features;
use fcntl::{fcntl, FD_CLOEXEC, O_NONBLOCK};
use fcntl::FcntlArg::{F_SETFD, F_SETFL};
use libc::{c_void, c_int, socklen_t, size_t, ssize_t};
use std::{fmt, mem, ptr};
use std::os::unix::prelude::*;

mod addr;
mod consts;
mod ffi;
mod multicast;
pub mod sockopt;

/*
 *
 * ===== Re-exports =====
 *
 */

pub use self::addr::{
    SockAddr,
    ToSockAddr,
    FromSockAddr,
    ToInAddr,
};
pub use libc::{
    in_addr,
    sockaddr,
    sockaddr_storage,
    sockaddr_in,
    sockaddr_in6,
    sockaddr_un,
    sa_family_t,
};

pub use self::multicast::{
    ip_mreq,
};
pub use self::consts::*;

// Extra flags - Supported by Linux 2.6.27, normalized on other platforms
bitflags!(
    flags SockFlag: c_int {
        const SOCK_NONBLOCK = 0o0004000,
        const SOCK_CLOEXEC  = 0o2000000
    }
);

pub fn socket(domain: AddressFamily, mut ty: SockType, flags: SockFlag) -> NixResult<Fd> {
    let feat_atomic = features::socket_atomic_cloexec();

    if feat_atomic {
        ty = ty | flags.bits();
    }

    // TODO: Check the kernel version
    let res = unsafe { ffi::socket(domain, ty, 0) };

    if res < 0 {
        return Err(NixError::Sys(Errno::last()));
    }

    if !feat_atomic {
        if flags.contains(SOCK_CLOEXEC) {
            try!(fcntl(res, F_SETFD(FD_CLOEXEC)));
        }

        if flags.contains(SOCK_NONBLOCK) {
            try!(fcntl(res, F_SETFL(O_NONBLOCK)));
        }
    }

    Ok(res)
}

pub fn listen(sockfd: Fd, backlog: usize) -> NixResult<()> {
    let res = unsafe { ffi::listen(sockfd, backlog as c_int) };
    from_ffi(res)
}

pub fn bind<A: ToSockAddr>(sockfd: Fd, addr: &A) -> NixResult<()> {
    let res = unsafe {
        try!(addr.with_sock_addr(|addr| {
            match *addr {
                SockAddr::IpV4(ref addr) => ffi::bind(sockfd, mem::transmute(addr), mem::size_of::<sockaddr_in>() as socklen_t),
                SockAddr::IpV6(ref addr) => ffi::bind(sockfd, mem::transmute(addr), mem::size_of::<sockaddr_in6>() as socklen_t),
                SockAddr::Unix(ref addr) => ffi::bind(sockfd, mem::transmute(addr), mem::size_of::<sockaddr_un>() as socklen_t)
            }
        }))
    };

    from_ffi(res)
}

pub fn accept(sockfd: Fd) -> NixResult<Fd> {
    let res = unsafe { ffi::accept(sockfd, ptr::null_mut(), ptr::null_mut()) };

    if res < 0 {
        return Err(NixError::Sys(Errno::last()));
    }

    Ok(res)
}

#[cfg(not(any(target_os = "macos", target_os = "ios")))]
pub fn accept4(sockfd: Fd, flags: SockFlag) -> NixResult<Fd> {
    use libc::sockaddr;

    type F = unsafe extern "C" fn(c_int, *mut sockaddr, *mut socklen_t, c_int) -> c_int;

    extern {
        #[linkage = "extern_weak"]
        static accept4: *const ();
    }

    if !accept4.is_null() {
        let res = unsafe {
            mem::transmute::<*const (), F>(accept4)(
                sockfd, ptr::null_mut(), ptr::null_mut(), flags.bits)
        };

        if res < 0 {
            return Err(NixError::Sys(Errno::last()));
        }

        Ok(res)
    } else {
        accept4_polyfill(sockfd, flags)
    }
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn accept4(sockfd: Fd, flags: SockFlag) -> NixResult<Fd> {
    accept4_polyfill(sockfd, flags)
}

#[inline]
fn accept4_polyfill(sockfd: Fd, flags: SockFlag) -> NixResult<Fd> {
    let res =  unsafe { ffi::accept(sockfd, ptr::null_mut(), ptr::null_mut()) };

    if res < 0 {
        return Err(NixError::Sys(Errno::last()));
    }

    if flags.contains(SOCK_CLOEXEC) {
        try!(fcntl(res, F_SETFD(FD_CLOEXEC)));
    }

    if flags.contains(SOCK_NONBLOCK) {
        try!(fcntl(res, F_SETFL(O_NONBLOCK)));
    }

    Ok(res)
}

pub fn connect<A: ToSockAddr>(sockfd: Fd, addr: &A) -> NixResult<()> {
    let res = unsafe {
        try!(addr.with_sock_addr(|addr| {
            match *addr {
                SockAddr::IpV4(ref addr) => ffi::connect(sockfd, mem::transmute(addr), mem::size_of::<sockaddr_in>() as socklen_t),
                SockAddr::IpV6(ref addr) => ffi::connect(sockfd, mem::transmute(addr), mem::size_of::<sockaddr_in6>() as socklen_t),
                SockAddr::Unix(ref addr) => ffi::connect(sockfd, mem::transmute(addr), mem::size_of::<sockaddr_un>() as socklen_t)
            }
        }))
    };

    from_ffi(res)
}

mod sa_helpers {
    use std::mem;
    use libc::{sockaddr_storage, sockaddr_in, sockaddr_in6, sockaddr_un};
    use super::SockAddr;

    pub fn to_sockaddr_ipv4(addr: &sockaddr_storage) -> SockAddr {
        let sin : &sockaddr_in = unsafe { mem::transmute(addr) };
        SockAddr::IpV4( *sin )
    }

    pub fn to_sockaddr_ipv6(addr: &sockaddr_storage) -> SockAddr {
        let sin6 : &sockaddr_in6 = unsafe { mem::transmute(addr) };
        SockAddr::IpV6( *sin6 )
    }

    pub fn to_sockaddr_unix(addr: &sockaddr_storage) -> SockAddr {
        let sun : &sockaddr_un = unsafe { mem::transmute(addr) };
        SockAddr::Unix( *sun )
    }
}

pub fn recvfrom(sockfd: Fd, buf: &mut [u8]) -> NixResult<(usize, SockAddr)> {
    let saddr : sockaddr_storage = unsafe { mem::zeroed() };
    let mut len = mem::size_of::<sockaddr_storage>() as socklen_t;

    let ret = unsafe {
        ffi::recvfrom(sockfd, buf.as_ptr() as *mut c_void, buf.len() as size_t, 0, mem::transmute(&saddr), &mut len as *mut socklen_t)
    };

    if ret < 0 {
        return Err(NixError::Sys(Errno::last()));
    }

    Ok((ret as usize,
            match saddr.ss_family as i32 {
                AF_INET => { sa_helpers::to_sockaddr_ipv4(&saddr) },
                AF_INET6 => { sa_helpers::to_sockaddr_ipv6(&saddr) },
                AF_UNIX => { sa_helpers::to_sockaddr_unix(&saddr) },
                _ => unimplemented!()
            }
        ))
}

fn print_ipv4_addr(sin: &sockaddr_in, f: &mut fmt::Formatter) -> fmt::Result {
    use std::num::Int;

    let ip_addr = Int::from_be(sin.sin_addr.s_addr);
    let port = Int::from_be(sin.sin_port);

    write!(f, "{}.{}.{}.{}:{}",
           (ip_addr >> 24) & 0xff,
           (ip_addr >> 16) & 0xff,
           (ip_addr >> 8) & 0xff,
           (ip_addr) & 0xff,
           port)
}

impl fmt::Debug for SockAddr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            SockAddr::IpV4(sin) => print_ipv4_addr(&sin, f),
            _ => unimplemented!()
        }
    }
}

///
/// Generic wrapper around sendto
fn sendto_sockaddr<T>(sockfd: Fd, buf: &[u8], flags: SockMessageFlags, addr: &T) -> ssize_t {
    unsafe {
        ffi::sendto(
            sockfd,
            buf.as_ptr() as *const c_void,
            buf.len() as size_t,
            flags,
            mem::transmute(addr),
            mem::size_of::<T>() as socklen_t)
    }
}

pub fn sendto(sockfd: Fd, buf: &[u8], addr: &SockAddr, flags: SockMessageFlags) -> NixResult<usize> {
    let ret = match *addr {
        SockAddr::IpV4(ref addr) => sendto_sockaddr(sockfd, buf, flags, addr),
        SockAddr::IpV6(ref addr) => sendto_sockaddr(sockfd, buf, flags, addr),
        SockAddr::Unix(ref addr) => sendto_sockaddr(sockfd, buf, flags, addr),
    };

    if ret < 0 {
        Err(NixError::Sys(Errno::last()))
    } else {
        Ok(ret as usize)
    }
}

#[repr(C)]
#[derive(Copy)]
pub struct linger {
    pub l_onoff: c_int,
    pub l_linger: c_int
}

/*
 *
 * ===== Socket Options =====
 *
 */

/// Represents a socket option that can be accessed or set
pub trait SockOpt : Copy + fmt::Debug {
    /// Type of `getsockopt` return value
    type Get;

    /// Type of value used to set the socket option. Used as the argument to
    /// `setsockopt`.
    type Set;

    #[doc(hidden)]
    fn get(&self, fd: Fd, level: c_int) -> NixResult<Self::Get>;

    #[doc(hidden)]
    fn set(&self, fd: Fd, level: c_int, val: Self::Set) -> NixResult<()>;
}

pub enum SockLevel {
    Socket,
    Tcp,
    Ip,
    Ipv6,
    Udp
}

impl SockLevel {
    fn as_cint(&self) -> c_int {
        use self::SockLevel::*;

        match *self {
            Socket => consts::SOL_SOCKET,
            Tcp    => consts::IPPROTO_TCP,
            Ip     => consts::IPPROTO_IP,
            Ipv6   => consts::IPPROTO_IPV6,
            Udp    => consts::IPPROTO_UDP,
        }
    }
}

/// Get the current value for the requested socket option
///
/// [Further reading](http://man7.org/linux/man-pages/man2/setsockopt.2.html)
pub fn getsockopt<O: SockOpt>(fd: Fd, level: SockLevel, opt: O) -> NixResult<O::Get> {
    opt.get(fd, level.as_cint())
}

/// Sets the value for the requested socket option
///
/// [Further reading](http://man7.org/linux/man-pages/man2/setsockopt.2.html)
pub fn setsockopt<O: SockOpt>(fd: Fd, level: SockLevel, opt: O, val: O::Set) -> NixResult<()> {
    opt.set(fd, level.as_cint(), val)
}

fn getpeername_sockaddr<T>(sockfd: Fd, addr: &T) -> NixResult<bool> {
    let addrlen_expected = mem::size_of::<T>() as socklen_t;
    let mut addrlen = addrlen_expected;

    let ret = unsafe { ffi::getpeername(sockfd, mem::transmute(addr), &mut addrlen) };
    if ret < 0 {
        return Err(NixError::Sys(Errno::last()));
    }

    Ok(addrlen == addrlen_expected)
}

pub fn getpeername(sockfd: Fd, addr: &mut SockAddr) -> NixResult<bool> {
    match *addr {
        SockAddr::IpV4(ref addr) => getpeername_sockaddr(sockfd, addr),
        SockAddr::IpV6(ref addr) => getpeername_sockaddr(sockfd, addr),
        SockAddr::Unix(ref addr) => getpeername_sockaddr(sockfd, addr)
    }
}

fn getsockname_sockaddr<T>(sockfd: Fd, addr: &T) -> NixResult<bool> {
    let addrlen_expected = mem::size_of::<T>() as socklen_t;
    let mut addrlen = addrlen_expected;

    let ret = unsafe { ffi::getsockname(sockfd, mem::transmute(addr), &mut addrlen) };
    if ret < 0 {
        return Err(NixError::Sys(Errno::last()));
    }

    Ok(addrlen == addrlen_expected)
}

pub fn getsockname(sockfd: Fd, addr: &mut SockAddr) -> NixResult<bool> {
    match *addr {
        SockAddr::IpV4(ref addr) => getsockname_sockaddr(sockfd, addr),
        SockAddr::IpV6(ref addr) => getsockname_sockaddr(sockfd, addr),
        SockAddr::Unix(ref addr) => getsockname_sockaddr(sockfd, addr)
    }
}