]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/net.rs
3f77abd7f44d8f4f56be637a66781da946f300a6
[rust.git] / src / libstd / sys / unix / net.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use ffi::CStr;
12 use io;
13 use libc::{self, c_int, size_t, sockaddr, socklen_t};
14 use net::{SocketAddr, Shutdown};
15 use str;
16 use sys::fd::FileDesc;
17 use sys_common::{AsInner, FromInner, IntoInner};
18 use sys_common::net::{getsockopt, setsockopt};
19 use time::Duration;
20
21 pub use sys::{cvt, cvt_r};
22 pub extern crate libc as netc;
23
24 pub type wrlen_t = size_t;
25
26 // See below for the usage of SOCK_CLOEXEC, but this constant is only defined on
27 // Linux currently (e.g. support doesn't exist on other platforms). In order to
28 // get name resolution to work and things to compile we just define a dummy
29 // SOCK_CLOEXEC here for other platforms. Note that the dummy constant isn't
30 // actually ever used (the blocks below are wrapped in `if cfg!` as well.
31 #[cfg(target_os = "linux")]
32 use libc::SOCK_CLOEXEC;
33 #[cfg(not(target_os = "linux"))]
34 const SOCK_CLOEXEC: c_int = 0;
35
36 pub struct Socket(FileDesc);
37
38 pub fn init() {}
39
40 pub fn cvt_gai(err: c_int) -> io::Result<()> {
41     if err == 0 { return Ok(()) }
42
43     let detail = unsafe {
44         str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap()
45             .to_owned()
46     };
47     Err(io::Error::new(io::ErrorKind::Other,
48                        &format!("failed to lookup address information: {}",
49                                 detail)[..]))
50 }
51
52 impl Socket {
53     pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
54         let fam = match *addr {
55             SocketAddr::V4(..) => libc::AF_INET,
56             SocketAddr::V6(..) => libc::AF_INET6,
57         };
58         Socket::new_raw(fam, ty)
59     }
60
61     pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
62         unsafe {
63             // On linux we first attempt to pass the SOCK_CLOEXEC flag to
64             // atomically create the socket and set it as CLOEXEC. Support for
65             // this option, however, was added in 2.6.27, and we still support
66             // 2.6.18 as a kernel, so if the returned error is EINVAL we
67             // fallthrough to the fallback.
68             if cfg!(target_os = "linux") {
69                 match cvt(libc::socket(fam, ty | SOCK_CLOEXEC, 0)) {
70                     Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
71                     Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
72                     Err(e) => return Err(e),
73                 }
74             }
75
76             let fd = cvt(libc::socket(fam, ty, 0))?;
77             let fd = FileDesc::new(fd);
78             fd.set_cloexec()?;
79             Ok(Socket(fd))
80         }
81     }
82
83     pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
84         unsafe {
85             let mut fds = [0, 0];
86
87             // Like above, see if we can set cloexec atomically
88             if cfg!(target_os = "linux") {
89                 match cvt(libc::socketpair(fam, ty | SOCK_CLOEXEC, 0, fds.as_mut_ptr())) {
90                     Ok(_) => {
91                         return Ok((Socket(FileDesc::new(fds[0])), Socket(FileDesc::new(fds[1]))));
92                     }
93                     Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {},
94                     Err(e) => return Err(e),
95                 }
96             }
97
98             cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
99             let a = FileDesc::new(fds[0]);
100             let b = FileDesc::new(fds[1]);
101             a.set_cloexec()?;
102             b.set_cloexec()?;
103             Ok((Socket(a), Socket(b)))
104         }
105     }
106
107     pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t)
108                   -> io::Result<Socket> {
109         // Unfortunately the only known way right now to accept a socket and
110         // atomically set the CLOEXEC flag is to use the `accept4` syscall on
111         // Linux. This was added in 2.6.28, however, and because we support
112         // 2.6.18 we must detect this support dynamically.
113         if cfg!(target_os = "linux") {
114             weak! {
115                 fn accept4(c_int, *mut sockaddr, *mut socklen_t, c_int) -> c_int
116             }
117             if let Some(accept) = accept4.get() {
118                 let res = cvt_r(|| unsafe {
119                     accept(self.0.raw(), storage, len, SOCK_CLOEXEC)
120                 });
121                 match res {
122                     Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
123                     Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {}
124                     Err(e) => return Err(e),
125                 }
126             }
127         }
128
129         let fd = cvt_r(|| unsafe {
130             libc::accept(self.0.raw(), storage, len)
131         })?;
132         let fd = FileDesc::new(fd);
133         fd.set_cloexec()?;
134         Ok(Socket(fd))
135     }
136
137     pub fn duplicate(&self) -> io::Result<Socket> {
138         self.0.duplicate().map(Socket)
139     }
140
141     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
142         self.0.read(buf)
143     }
144
145     pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
146         self.0.read_to_end(buf)
147     }
148
149     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
150         self.0.write(buf)
151     }
152
153     pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
154         let timeout = match dur {
155             Some(dur) => {
156                 if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
157                     return Err(io::Error::new(io::ErrorKind::InvalidInput,
158                                               "cannot set a 0 duration timeout"));
159                 }
160
161                 let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
162                     libc::time_t::max_value()
163                 } else {
164                     dur.as_secs() as libc::time_t
165                 };
166                 let mut timeout = libc::timeval {
167                     tv_sec: secs,
168                     tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t,
169                 };
170                 if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
171                     timeout.tv_usec = 1;
172                 }
173                 timeout
174             }
175             None => {
176                 libc::timeval {
177                     tv_sec: 0,
178                     tv_usec: 0,
179                 }
180             }
181         };
182         setsockopt(self, libc::SOL_SOCKET, kind, timeout)
183     }
184
185     pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
186         let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
187         if raw.tv_sec == 0 && raw.tv_usec == 0 {
188             Ok(None)
189         } else {
190             let sec = raw.tv_sec as u64;
191             let nsec = (raw.tv_usec as u32) * 1000;
192             Ok(Some(Duration::new(sec, nsec)))
193         }
194     }
195
196     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
197         let how = match how {
198             Shutdown::Write => libc::SHUT_WR,
199             Shutdown::Read => libc::SHUT_RD,
200             Shutdown::Both => libc::SHUT_RDWR,
201         };
202         cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
203         Ok(())
204     }
205
206     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
207         setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
208     }
209
210     pub fn nodelay(&self) -> io::Result<bool> {
211         let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
212         Ok(raw != 0)
213     }
214
215     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
216         let mut nonblocking = nonblocking as libc::c_ulong;
217         cvt(unsafe { libc::ioctl(*self.as_inner(), libc::FIONBIO, &mut nonblocking) }).map(|_| ())
218     }
219
220     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
221         let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
222         if raw == 0 {
223             Ok(None)
224         } else {
225             Ok(Some(io::Error::from_raw_os_error(raw as i32)))
226         }
227     }
228 }
229
230 impl AsInner<c_int> for Socket {
231     fn as_inner(&self) -> &c_int { self.0.as_inner() }
232 }
233
234 impl FromInner<c_int> for Socket {
235     fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
236 }
237
238 impl IntoInner<c_int> for Socket {
239     fn into_inner(self) -> c_int { self.0.into_raw() }
240 }