PageRenderTime 91ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/src/libstd/sys/unix/net.rs

https://gitlab.com/jianglu/rust
Rust | 424 lines | 320 code | 55 blank | 49 comment | 53 complexity | 202d80526f69d366c8ad2153adc7f793 MD5 | raw file
  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. use ffi::CStr;
  11. use io;
  12. use libc::{self, c_int, c_void, size_t, sockaddr, socklen_t, EAI_SYSTEM, MSG_PEEK};
  13. use mem;
  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, sockaddr_to_addr};
  19. use time::{Duration, Instant};
  20. use cmp;
  21. pub use sys::{cvt, cvt_r};
  22. pub extern crate libc as netc;
  23. pub type wrlen_t = size_t;
  24. // See below for the usage of SOCK_CLOEXEC, but this constant is only defined on
  25. // Linux currently (e.g. support doesn't exist on other platforms). In order to
  26. // get name resolution to work and things to compile we just define a dummy
  27. // SOCK_CLOEXEC here for other platforms. Note that the dummy constant isn't
  28. // actually ever used (the blocks below are wrapped in `if cfg!` as well.
  29. #[cfg(target_os = "linux")]
  30. use libc::SOCK_CLOEXEC;
  31. #[cfg(not(target_os = "linux"))]
  32. const SOCK_CLOEXEC: c_int = 0;
  33. // Another conditional contant for name resolution: Macos et iOS use
  34. // SO_NOSIGPIPE as a setsockopt flag to disable SIGPIPE emission on socket.
  35. // Other platforms do otherwise.
  36. #[cfg(target_vendor = "apple")]
  37. use libc::SO_NOSIGPIPE;
  38. #[cfg(not(target_vendor = "apple"))]
  39. const SO_NOSIGPIPE: c_int = 0;
  40. pub struct Socket(FileDesc);
  41. pub fn init() {}
  42. pub fn cvt_gai(err: c_int) -> io::Result<()> {
  43. if err == 0 {
  44. return Ok(())
  45. }
  46. // We may need to trigger a glibc workaround. See on_resolver_failure() for details.
  47. on_resolver_failure();
  48. if err == EAI_SYSTEM {
  49. return Err(io::Error::last_os_error())
  50. }
  51. let detail = unsafe {
  52. str::from_utf8(CStr::from_ptr(libc::gai_strerror(err)).to_bytes()).unwrap()
  53. .to_owned()
  54. };
  55. Err(io::Error::new(io::ErrorKind::Other,
  56. &format!("failed to lookup address information: {}",
  57. detail)[..]))
  58. }
  59. impl Socket {
  60. pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
  61. let fam = match *addr {
  62. SocketAddr::V4(..) => libc::AF_INET,
  63. SocketAddr::V6(..) => libc::AF_INET6,
  64. };
  65. Socket::new_raw(fam, ty)
  66. }
  67. pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
  68. unsafe {
  69. // On linux we first attempt to pass the SOCK_CLOEXEC flag to
  70. // atomically create the socket and set it as CLOEXEC. Support for
  71. // this option, however, was added in 2.6.27, and we still support
  72. // 2.6.18 as a kernel, so if the returned error is EINVAL we
  73. // fallthrough to the fallback.
  74. if cfg!(target_os = "linux") {
  75. match cvt(libc::socket(fam, ty | SOCK_CLOEXEC, 0)) {
  76. Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
  77. Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
  78. Err(e) => return Err(e),
  79. }
  80. }
  81. let fd = cvt(libc::socket(fam, ty, 0))?;
  82. let fd = FileDesc::new(fd);
  83. fd.set_cloexec()?;
  84. let socket = Socket(fd);
  85. if cfg!(target_vendor = "apple") {
  86. setsockopt(&socket, libc::SOL_SOCKET, SO_NOSIGPIPE, 1)?;
  87. }
  88. Ok(socket)
  89. }
  90. }
  91. pub fn new_pair(fam: c_int, ty: c_int) -> io::Result<(Socket, Socket)> {
  92. unsafe {
  93. let mut fds = [0, 0];
  94. // Like above, see if we can set cloexec atomically
  95. if cfg!(target_os = "linux") {
  96. match cvt(libc::socketpair(fam, ty | SOCK_CLOEXEC, 0, fds.as_mut_ptr())) {
  97. Ok(_) => {
  98. return Ok((Socket(FileDesc::new(fds[0])), Socket(FileDesc::new(fds[1]))));
  99. }
  100. Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {},
  101. Err(e) => return Err(e),
  102. }
  103. }
  104. cvt(libc::socketpair(fam, ty, 0, fds.as_mut_ptr()))?;
  105. let a = FileDesc::new(fds[0]);
  106. let b = FileDesc::new(fds[1]);
  107. a.set_cloexec()?;
  108. b.set_cloexec()?;
  109. Ok((Socket(a), Socket(b)))
  110. }
  111. }
  112. pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
  113. self.set_nonblocking(true)?;
  114. let r = unsafe {
  115. let (addrp, len) = addr.into_inner();
  116. cvt(libc::connect(self.0.raw(), addrp, len))
  117. };
  118. self.set_nonblocking(false)?;
  119. match r {
  120. Ok(_) => return Ok(()),
  121. // there's no ErrorKind for EINPROGRESS :(
  122. Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
  123. Err(e) => return Err(e),
  124. }
  125. let mut pollfd = libc::pollfd {
  126. fd: self.0.raw(),
  127. events: libc::POLLOUT,
  128. revents: 0,
  129. };
  130. if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
  131. return Err(io::Error::new(io::ErrorKind::InvalidInput,
  132. "cannot set a 0 duration timeout"));
  133. }
  134. let start = Instant::now();
  135. loop {
  136. let elapsed = start.elapsed();
  137. if elapsed >= timeout {
  138. return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out"));
  139. }
  140. let timeout = timeout - elapsed;
  141. let mut timeout = timeout.as_secs()
  142. .saturating_mul(1_000)
  143. .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
  144. if timeout == 0 {
  145. timeout = 1;
  146. }
  147. let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int;
  148. match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
  149. -1 => {
  150. let err = io::Error::last_os_error();
  151. if err.kind() != io::ErrorKind::Interrupted {
  152. return Err(err);
  153. }
  154. }
  155. 0 => {}
  156. _ => {
  157. // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
  158. // for POLLHUP rather than read readiness
  159. if pollfd.revents & libc::POLLHUP != 0 {
  160. let e = self.take_error()?
  161. .unwrap_or_else(|| {
  162. io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP")
  163. });
  164. return Err(e);
  165. }
  166. return Ok(());
  167. }
  168. }
  169. }
  170. }
  171. pub fn accept(&self, storage: *mut sockaddr, len: *mut socklen_t)
  172. -> io::Result<Socket> {
  173. // Unfortunately the only known way right now to accept a socket and
  174. // atomically set the CLOEXEC flag is to use the `accept4` syscall on
  175. // Linux. This was added in 2.6.28, however, and because we support
  176. // 2.6.18 we must detect this support dynamically.
  177. if cfg!(target_os = "linux") {
  178. weak! {
  179. fn accept4(c_int, *mut sockaddr, *mut socklen_t, c_int) -> c_int
  180. }
  181. if let Some(accept) = accept4.get() {
  182. let res = cvt_r(|| unsafe {
  183. accept(self.0.raw(), storage, len, SOCK_CLOEXEC)
  184. });
  185. match res {
  186. Ok(fd) => return Ok(Socket(FileDesc::new(fd))),
  187. Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {}
  188. Err(e) => return Err(e),
  189. }
  190. }
  191. }
  192. let fd = cvt_r(|| unsafe {
  193. libc::accept(self.0.raw(), storage, len)
  194. })?;
  195. let fd = FileDesc::new(fd);
  196. fd.set_cloexec()?;
  197. Ok(Socket(fd))
  198. }
  199. pub fn duplicate(&self) -> io::Result<Socket> {
  200. self.0.duplicate().map(Socket)
  201. }
  202. fn recv_with_flags(&self, buf: &mut [u8], flags: c_int) -> io::Result<usize> {
  203. let ret = cvt(unsafe {
  204. libc::recv(self.0.raw(),
  205. buf.as_mut_ptr() as *mut c_void,
  206. buf.len(),
  207. flags)
  208. })?;
  209. Ok(ret as usize)
  210. }
  211. pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
  212. self.recv_with_flags(buf, 0)
  213. }
  214. pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
  215. self.recv_with_flags(buf, MSG_PEEK)
  216. }
  217. fn recv_from_with_flags(&self, buf: &mut [u8], flags: c_int)
  218. -> io::Result<(usize, SocketAddr)> {
  219. let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() };
  220. let mut addrlen = mem::size_of_val(&storage) as libc::socklen_t;
  221. let n = cvt(unsafe {
  222. libc::recvfrom(self.0.raw(),
  223. buf.as_mut_ptr() as *mut c_void,
  224. buf.len(),
  225. flags,
  226. &mut storage as *mut _ as *mut _,
  227. &mut addrlen)
  228. })?;
  229. Ok((n as usize, sockaddr_to_addr(&storage, addrlen as usize)?))
  230. }
  231. pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
  232. self.recv_from_with_flags(buf, 0)
  233. }
  234. pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
  235. self.recv_from_with_flags(buf, MSG_PEEK)
  236. }
  237. pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
  238. self.0.write(buf)
  239. }
  240. pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
  241. let timeout = match dur {
  242. Some(dur) => {
  243. if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
  244. return Err(io::Error::new(io::ErrorKind::InvalidInput,
  245. "cannot set a 0 duration timeout"));
  246. }
  247. let secs = if dur.as_secs() > libc::time_t::max_value() as u64 {
  248. libc::time_t::max_value()
  249. } else {
  250. dur.as_secs() as libc::time_t
  251. };
  252. let mut timeout = libc::timeval {
  253. tv_sec: secs,
  254. tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t,
  255. };
  256. if timeout.tv_sec == 0 && timeout.tv_usec == 0 {
  257. timeout.tv_usec = 1;
  258. }
  259. timeout
  260. }
  261. None => {
  262. libc::timeval {
  263. tv_sec: 0,
  264. tv_usec: 0,
  265. }
  266. }
  267. };
  268. setsockopt(self, libc::SOL_SOCKET, kind, timeout)
  269. }
  270. pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
  271. let raw: libc::timeval = getsockopt(self, libc::SOL_SOCKET, kind)?;
  272. if raw.tv_sec == 0 && raw.tv_usec == 0 {
  273. Ok(None)
  274. } else {
  275. let sec = raw.tv_sec as u64;
  276. let nsec = (raw.tv_usec as u32) * 1000;
  277. Ok(Some(Duration::new(sec, nsec)))
  278. }
  279. }
  280. pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
  281. let how = match how {
  282. Shutdown::Write => libc::SHUT_WR,
  283. Shutdown::Read => libc::SHUT_RD,
  284. Shutdown::Both => libc::SHUT_RDWR,
  285. };
  286. cvt(unsafe { libc::shutdown(self.0.raw(), how) })?;
  287. Ok(())
  288. }
  289. pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
  290. setsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int)
  291. }
  292. pub fn nodelay(&self) -> io::Result<bool> {
  293. let raw: c_int = getsockopt(self, libc::IPPROTO_TCP, libc::TCP_NODELAY)?;
  294. Ok(raw != 0)
  295. }
  296. pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
  297. let mut nonblocking = nonblocking as libc::c_int;
  298. cvt(unsafe { libc::ioctl(*self.as_inner(), libc::FIONBIO, &mut nonblocking) }).map(|_| ())
  299. }
  300. pub fn take_error(&self) -> io::Result<Option<io::Error>> {
  301. let raw: c_int = getsockopt(self, libc::SOL_SOCKET, libc::SO_ERROR)?;
  302. if raw == 0 {
  303. Ok(None)
  304. } else {
  305. Ok(Some(io::Error::from_raw_os_error(raw as i32)))
  306. }
  307. }
  308. }
  309. impl AsInner<c_int> for Socket {
  310. fn as_inner(&self) -> &c_int { self.0.as_inner() }
  311. }
  312. impl FromInner<c_int> for Socket {
  313. fn from_inner(fd: c_int) -> Socket { Socket(FileDesc::new(fd)) }
  314. }
  315. impl IntoInner<c_int> for Socket {
  316. fn into_inner(self) -> c_int { self.0.into_raw() }
  317. }
  318. // In versions of glibc prior to 2.26, there's a bug where the DNS resolver
  319. // will cache the contents of /etc/resolv.conf, so changes to that file on disk
  320. // can be ignored by a long-running program. That can break DNS lookups on e.g.
  321. // laptops where the network comes and goes. See
  322. // https://sourceware.org/bugzilla/show_bug.cgi?id=984. Note however that some
  323. // distros including Debian have patched glibc to fix this for a long time.
  324. //
  325. // A workaround for this bug is to call the res_init libc function, to clear
  326. // the cached configs. Unfortunately, while we believe glibc's implementation
  327. // of res_init is thread-safe, we know that other implementations are not
  328. // (https://github.com/rust-lang/rust/issues/43592). Code here in libstd could
  329. // try to synchronize its res_init calls with a Mutex, but that wouldn't
  330. // protect programs that call into libc in other ways. So instead of calling
  331. // res_init unconditionally, we call it only when we detect we're linking
  332. // against glibc version < 2.26. (That is, when we both know its needed and
  333. // believe it's thread-safe).
  334. #[cfg(target_env = "gnu")]
  335. fn on_resolver_failure() {
  336. use sys;
  337. // If the version fails to parse, we treat it the same as "not glibc".
  338. if let Some(version) = sys::os::glibc_version() {
  339. if version < (2, 26) {
  340. unsafe { libc::res_init() };
  341. }
  342. }
  343. }
  344. #[cfg(not(target_env = "gnu"))]
  345. fn on_resolver_failure() {}
  346. #[cfg(all(test, taget_env = "gnu"))]
  347. mod test {
  348. use super::*;
  349. #[test]
  350. fn test_res_init() {
  351. // This mostly just tests that the weak linkage doesn't panic wildly...
  352. res_init_if_glibc_before_2_26().unwrap();
  353. }
  354. #[test]
  355. fn test_parse_glibc_version() {
  356. let cases = [
  357. ("0.0", Some((0, 0))),
  358. ("01.+2", Some((1, 2))),
  359. ("3.4.5.six", Some((3, 4))),
  360. ("1", None),
  361. ("1.-2", None),
  362. ("1.foo", None),
  363. ("foo.1", None),
  364. ];
  365. for &(version_str, parsed) in cases.iter() {
  366. assert_eq!(parsed, parse_glibc_version(version_str));
  367. }
  368. }
  369. }