1 // Copyright 2014 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.
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.
18 use sync::{Arc, Mutex};
19 use sync::atomic::{AtomicBool, Ordering};
20 use old_io::{self, IoResult, IoError};
22 use sys::{self, timer, retry, c, set_nonblocking, wouldblock};
23 use sys::fs::{fd_t, FileDesc};
24 use sys_common::net::*;
25 use sys_common::net::SocketStatus::*;
26 use sys_common::{eof, mkerr_libc};
28 fn unix_socket(ty: libc::c_int) -> IoResult<fd_t> {
29 match unsafe { libc::socket(libc::AF_UNIX, ty, 0) } {
30 -1 => Err(super::last_error()),
35 fn addr_to_sockaddr_un(addr: &CString,
36 storage: &mut libc::sockaddr_storage)
37 -> IoResult<libc::socklen_t> {
38 // the sun_path length is limited to SUN_LEN (with null)
39 assert!(mem::size_of::<libc::sockaddr_storage>() >=
40 mem::size_of::<libc::sockaddr_un>());
41 let s = unsafe { &mut *(storage as *mut _ as *mut libc::sockaddr_un) };
43 let len = addr.as_bytes().len();
44 if len > s.sun_path.len() - 1 {
46 kind: old_io::InvalidInput,
47 desc: "invalid argument: path must be smaller than SUN_LEN",
51 s.sun_family = libc::AF_UNIX as libc::sa_family_t;
52 for (slot, value) in s.sun_path.iter_mut().zip(addr.as_bytes().iter()) {
53 *slot = *value as libc::c_char;
56 // count the null terminator
57 let len = mem::size_of::<libc::sa_family_t>() + len + 1;
58 return Ok(len as libc::socklen_t);
64 // Unused on Linux, where this lock is not necessary.
70 fn new(fd: fd_t) -> Inner {
71 Inner { fd: fd, lock: Mutex::new(()) }
76 fn drop(&mut self) { unsafe { let _ = libc::close(self.fd); } }
79 fn connect(addr: &CString, ty: libc::c_int,
80 timeout: Option<u64>) -> IoResult<Inner> {
81 let mut storage = unsafe { mem::zeroed() };
82 let len = try!(addr_to_sockaddr_un(addr, &mut storage));
83 let inner = Inner::new(try!(unix_socket(ty)));
84 let addrp = &storage as *const _ as *const libc::sockaddr;
88 match retry(|| unsafe { libc::connect(inner.fd, addrp, len) }) {
89 -1 => Err(super::last_error()),
94 try!(connect_timeout(inner.fd, addrp, len, timeout_ms));
100 fn bind(addr: &CString, ty: libc::c_int) -> IoResult<Inner> {
101 let mut storage = unsafe { mem::zeroed() };
102 let len = try!(addr_to_sockaddr_un(addr, &mut storage));
103 let inner = Inner::new(try!(unix_socket(ty)));
104 let addrp = &storage as *const _ as *const libc::sockaddr;
106 libc::bind(inner.fd, addrp, len)
108 -1 => Err(super::last_error()),
113 ////////////////////////////////////////////////////////////////////////////////
115 ////////////////////////////////////////////////////////////////////////////////
117 pub struct UnixStream {
124 pub fn connect(addr: &CString,
125 timeout: Option<u64>) -> IoResult<UnixStream> {
126 connect(addr, libc::SOCK_STREAM, timeout).map(|inner| {
127 UnixStream::new(Arc::new(inner))
131 fn new(inner: Arc<Inner>) -> UnixStream {
139 pub fn fd(&self) -> fd_t { self.inner.fd }
141 #[cfg(target_os = "linux")]
142 fn lock_nonblocking(&self) {}
144 #[cfg(not(target_os = "linux"))]
145 fn lock_nonblocking<'a>(&'a self) -> Guard<'a> {
148 guard: self.inner.lock.lock().unwrap(),
150 set_nonblocking(self.fd(), true);
154 pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
156 let dolock = || self.lock_nonblocking();
157 let doread = |nb| unsafe {
158 let flags = if nb {c::MSG_DONTWAIT} else {0};
160 buf.as_mut_ptr() as *mut libc::c_void,
161 buf.len() as libc::size_t,
162 flags) as libc::c_int
164 read(fd, self.read_deadline, dolock, doread)
167 pub fn write(&mut self, buf: &[u8]) -> IoResult<()> {
169 let dolock = || self.lock_nonblocking();
170 let dowrite = |nb: bool, buf: *const u8, len: uint| unsafe {
171 let flags = if nb {c::MSG_DONTWAIT} else {0};
177 match write(fd, self.write_deadline, buf, true, dolock, dowrite) {
183 pub fn close_write(&mut self) -> IoResult<()> {
184 mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_WR) })
187 pub fn close_read(&mut self) -> IoResult<()> {
188 mkerr_libc(unsafe { libc::shutdown(self.fd(), libc::SHUT_RD) })
191 pub fn set_timeout(&mut self, timeout: Option<u64>) {
192 let deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
193 self.read_deadline = deadline;
194 self.write_deadline = deadline;
197 pub fn set_read_timeout(&mut self, timeout: Option<u64>) {
198 self.read_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
201 pub fn set_write_timeout(&mut self, timeout: Option<u64>) {
202 self.write_deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
206 impl Clone for UnixStream {
207 fn clone(&self) -> UnixStream {
208 UnixStream::new(self.inner.clone())
212 ////////////////////////////////////////////////////////////////////////////////
214 ////////////////////////////////////////////////////////////////////////////////
216 pub struct UnixListener {
221 // we currently own the CString, so these impls should be safe
222 unsafe impl Send for UnixListener {}
223 unsafe impl Sync for UnixListener {}
226 pub fn bind(addr: &CString) -> IoResult<UnixListener> {
227 bind(addr, libc::SOCK_STREAM).map(|fd| {
228 UnixListener { inner: fd, path: addr.clone() }
232 pub fn fd(&self) -> fd_t { self.inner.fd }
234 pub fn listen(self) -> IoResult<UnixAcceptor> {
235 match unsafe { libc::listen(self.fd(), 128) } {
236 -1 => Err(super::last_error()),
239 let (reader, writer) = try!(unsafe { sys::os::pipe() });
240 set_nonblocking(reader.fd(), true);
241 set_nonblocking(writer.fd(), true);
242 set_nonblocking(self.fd(), true);
244 inner: Arc::new(AcceptorInner {
248 closed: AtomicBool::new(false),
257 pub struct UnixAcceptor {
258 inner: Arc<AcceptorInner>,
262 struct AcceptorInner {
263 listener: UnixListener,
270 pub fn fd(&self) -> fd_t { self.inner.listener.fd() }
272 pub fn accept(&mut self) -> IoResult<UnixStream> {
273 let deadline = if self.deadline == 0 {None} else {Some(self.deadline)};
275 while !self.inner.closed.load(Ordering::SeqCst) {
277 let mut storage: libc::sockaddr_storage = mem::zeroed();
278 let storagep = &mut storage as *mut libc::sockaddr_storage;
279 let size = mem::size_of::<libc::sockaddr_storage>();
280 let mut size = size as libc::socklen_t;
282 libc::accept(self.fd(),
283 storagep as *mut libc::sockaddr,
284 &mut size as *mut libc::socklen_t) as libc::c_int
286 -1 if wouldblock() => {}
287 -1 => return Err(super::last_error()),
288 fd => return Ok(UnixStream::new(Arc::new(Inner::new(fd)))),
291 try!(await(&[self.fd(), self.inner.reader.fd()],
292 deadline, Readable));
298 pub fn set_timeout(&mut self, timeout: Option<u64>) {
299 self.deadline = timeout.map(|a| timer::now() + a).unwrap_or(0);
302 pub fn close_accept(&mut self) -> IoResult<()> {
303 self.inner.closed.store(true, Ordering::SeqCst);
304 let fd = FileDesc::new(self.inner.writer.fd(), false);
305 match fd.write(&[0]) {
307 Err(..) if wouldblock() => Ok(()),
313 impl Clone for UnixAcceptor {
314 fn clone(&self) -> UnixAcceptor {
315 UnixAcceptor { inner: self.inner.clone(), deadline: 0 }
319 impl Drop for UnixListener {
321 // Unlink the path to the socket to ensure that it doesn't linger. We're
322 // careful to unlink the path before we close the file descriptor to
323 // prevent races where we unlink someone else's path.
325 let _ = libc::unlink(self.path.as_ptr());