summaryrefslogtreecommitdiffstats
path: root/third_party/rust/mio-uds/src
diff options
context:
space:
mode:
Diffstat (limited to 'third_party/rust/mio-uds/src')
-rw-r--r--third_party/rust/mio-uds/src/datagram.rs183
-rw-r--r--third_party/rust/mio-uds/src/lib.rs28
-rw-r--r--third_party/rust/mio-uds/src/listener.rs143
-rw-r--r--third_party/rust/mio-uds/src/socket.rs166
-rw-r--r--third_party/rust/mio-uds/src/stream.rs246
5 files changed, 766 insertions, 0 deletions
diff --git a/third_party/rust/mio-uds/src/datagram.rs b/third_party/rust/mio-uds/src/datagram.rs
new file mode 100644
index 0000000000..4fbefd1ceb
--- /dev/null
+++ b/third_party/rust/mio-uds/src/datagram.rs
@@ -0,0 +1,183 @@
+use std::io;
+use std::net::Shutdown;
+use std::os::unix::net;
+use std::os::unix::prelude::*;
+use std::path::Path;
+
+use libc;
+use mio::event::Evented;
+use mio::unix::EventedFd;
+use mio::{Poll, Token, Ready, PollOpt};
+
+use cvt;
+use socket::{sockaddr_un, Socket};
+
+/// A Unix datagram socket.
+#[derive(Debug)]
+pub struct UnixDatagram {
+ inner: net::UnixDatagram,
+}
+
+impl UnixDatagram {
+ /// Creates a Unix datagram socket bound to the given path.
+ pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
+ UnixDatagram::_bind(path.as_ref())
+ }
+
+ fn _bind(path: &Path) -> io::Result<UnixDatagram> {
+ unsafe {
+ let (addr, len) = try!(sockaddr_un(path));
+ let fd = try!(Socket::new(libc::SOCK_DGRAM));
+
+ let addr = &addr as *const _ as *const _;
+ try!(cvt(libc::bind(fd.fd(), addr, len)));
+
+ Ok(UnixDatagram::from_raw_fd(fd.into_fd()))
+ }
+ }
+
+ /// Consumes a standard library `UnixDatagram` and returns a wrapped
+ /// `UnixDatagram` compatible with mio.
+ ///
+ /// The returned stream is moved into nonblocking mode and is otherwise
+ /// ready to get associated with an event loop.
+ pub fn from_datagram(stream: net::UnixDatagram) -> io::Result<UnixDatagram> {
+ try!(stream.set_nonblocking(true));
+ Ok(UnixDatagram { inner: stream })
+ }
+
+ /// Create an unnamed pair of connected sockets.
+ ///
+ /// Returns two `UnixDatagrams`s which are connected to each other.
+ pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
+ unsafe {
+ let (a, b) = try!(Socket::pair(libc::SOCK_DGRAM));
+ Ok((UnixDatagram::from_raw_fd(a.into_fd()),
+ UnixDatagram::from_raw_fd(b.into_fd())))
+ }
+ }
+
+ /// Creates a Unix Datagram socket which is not bound to any address.
+ pub fn unbound() -> io::Result<UnixDatagram> {
+ let stream = try!(net::UnixDatagram::unbound());
+ try!(stream.set_nonblocking(true));
+ Ok(UnixDatagram { inner: stream })
+ }
+
+ /// Connects the socket to the specified address.
+ ///
+ /// The `send` method may be used to send data to the specified address.
+ /// `recv` and `recv_from` will only receive data from that address.
+ pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
+ self.inner.connect(path)
+ }
+
+ /// Creates a new independently owned handle to the underlying socket.
+ ///
+ /// The returned `UnixListener` is a reference to the same socket that this
+ /// object references. Both handles can be used to accept incoming
+ /// connections and options set on one listener will affect the other.
+ pub fn try_clone(&self) -> io::Result<UnixDatagram> {
+ self.inner.try_clone().map(|i| {
+ UnixDatagram { inner: i }
+ })
+ }
+
+ /// Returns the address of this socket.
+ pub fn local_addr(&self) -> io::Result<net::SocketAddr> {
+ self.inner.local_addr()
+ }
+
+ /// Returns the address of this socket's peer.
+ ///
+ /// The `connect` method will connect the socket to a peer.
+ pub fn peer_addr(&self) -> io::Result<net::SocketAddr> {
+ self.inner.peer_addr()
+ }
+
+ /// Receives data from the socket.
+ ///
+ /// On success, returns the number of bytes read and the address from
+ /// whence the data came.
+ pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, net::SocketAddr)> {
+ self.inner.recv_from(buf)
+ }
+
+ /// Receives data from the socket.
+ ///
+ /// On success, returns the number of bytes read.
+ pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
+ self.inner.recv(buf)
+ }
+
+ /// Sends data on the socket to the specified address.
+ ///
+ /// On success, returns the number of bytes written.
+ pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
+ self.inner.send_to(buf, path)
+ }
+
+ /// Sends data on the socket to the socket's peer.
+ ///
+ /// The peer address may be set by the `connect` method, and this method
+ /// will return an error if the socket has not already been connected.
+ ///
+ /// On success, returns the number of bytes written.
+ pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
+ self.inner.send(buf)
+ }
+
+ /// Returns the value of the `SO_ERROR` option.
+ pub fn take_error(&self) -> io::Result<Option<io::Error>> {
+ self.inner.take_error()
+ }
+
+ /// Shut down the read, write, or both halves of this connection.
+ ///
+ /// This function will cause all pending and future I/O calls on the
+ /// specified portions to immediately return with an appropriate value
+ /// (see the documentation of `Shutdown`).
+ pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
+ self.inner.shutdown(how)
+ }
+}
+
+impl Evented for UnixDatagram {
+ fn register(&self,
+ poll: &Poll,
+ token: Token,
+ events: Ready,
+ opts: PollOpt) -> io::Result<()> {
+ EventedFd(&self.as_raw_fd()).register(poll, token, events, opts)
+ }
+
+ fn reregister(&self,
+ poll: &Poll,
+ token: Token,
+ events: Ready,
+ opts: PollOpt) -> io::Result<()> {
+ EventedFd(&self.as_raw_fd()).reregister(poll, token, events, opts)
+ }
+
+ fn deregister(&self, poll: &Poll) -> io::Result<()> {
+ EventedFd(&self.as_raw_fd()).deregister(poll)
+ }
+}
+
+impl AsRawFd for UnixDatagram {
+ fn as_raw_fd(&self) -> i32 {
+ self.inner.as_raw_fd()
+ }
+}
+
+impl IntoRawFd for UnixDatagram {
+ fn into_raw_fd(self) -> i32 {
+ self.inner.into_raw_fd()
+ }
+}
+
+impl FromRawFd for UnixDatagram {
+ unsafe fn from_raw_fd(fd: i32) -> UnixDatagram {
+ UnixDatagram { inner: net::UnixDatagram::from_raw_fd(fd) }
+ }
+}
diff --git a/third_party/rust/mio-uds/src/lib.rs b/third_party/rust/mio-uds/src/lib.rs
new file mode 100644
index 0000000000..ed29e4ac92
--- /dev/null
+++ b/third_party/rust/mio-uds/src/lib.rs
@@ -0,0 +1,28 @@
+//! MIO bindings for Unix Domain Sockets
+
+#![cfg(unix)]
+#![deny(missing_docs)]
+#![doc(html_root_url = "https://docs.rs/mio-uds/0.6")]
+
+extern crate iovec;
+extern crate libc;
+extern crate mio;
+
+use std::io;
+
+mod datagram;
+mod listener;
+mod socket;
+mod stream;
+
+pub use stream::UnixStream;
+pub use listener::UnixListener;
+pub use datagram::UnixDatagram;
+
+fn cvt(i: libc::c_int) -> io::Result<libc::c_int> {
+ if i == -1 {
+ Err(io::Error::last_os_error())
+ } else {
+ Ok(i)
+ }
+}
diff --git a/third_party/rust/mio-uds/src/listener.rs b/third_party/rust/mio-uds/src/listener.rs
new file mode 100644
index 0000000000..c79830eeb0
--- /dev/null
+++ b/third_party/rust/mio-uds/src/listener.rs
@@ -0,0 +1,143 @@
+use std::io;
+use std::os::unix::net;
+use std::os::unix::prelude::*;
+use std::path::Path;
+
+use libc;
+use mio::event::Evented;
+use mio::unix::EventedFd;
+use mio::{Poll, PollOpt, Ready, Token};
+
+use UnixStream;
+use cvt;
+use socket::{sockaddr_un, Socket};
+
+/// A structure representing a Unix domain socket server.
+///
+/// This listener can be used to accept new streams connected to a remote
+/// endpoint, through which the `read` and `write` methods can be used to
+/// communicate.
+#[derive(Debug)]
+pub struct UnixListener {
+ inner: net::UnixListener,
+}
+
+impl UnixListener {
+ /// Creates a new `UnixListener` bound to the specified socket.
+ pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
+ UnixListener::_bind(path.as_ref())
+ }
+
+ fn _bind(path: &Path) -> io::Result<UnixListener> {
+ unsafe {
+ let (addr, len) = try!(sockaddr_un(path));
+ let fd = try!(Socket::new(libc::SOCK_STREAM));
+
+ let addr = &addr as *const _ as *const _;
+ try!(cvt(libc::bind(fd.fd(), addr, len)));
+ try!(cvt(libc::listen(fd.fd(), 128)));
+
+ Ok(UnixListener::from_raw_fd(fd.into_fd()))
+ }
+ }
+
+ /// Consumes a standard library `UnixListener` and returns a wrapped
+ /// `UnixListener` compatible with mio.
+ ///
+ /// The returned stream is moved into nonblocking mode and is otherwise
+ /// ready to get associated with an event loop.
+ pub fn from_listener(stream: net::UnixListener) -> io::Result<UnixListener> {
+ try!(stream.set_nonblocking(true));
+ Ok(UnixListener { inner: stream })
+ }
+
+ /// Accepts a new incoming connection to this listener.
+ ///
+ /// When established, the corresponding `UnixStream` and the remote peer's
+ /// address will be returned as `Ok(Some(...))`. If there is no connection
+ /// waiting to be accepted, then `Ok(None)` is returned.
+ ///
+ /// If an error happens while accepting, `Err` is returned.
+ pub fn accept(&self) -> io::Result<Option<(UnixStream, net::SocketAddr)>> {
+ match try!(self.accept_std()) {
+ Some((stream, addr)) => Ok(Some((UnixStream::from_stream(stream)?, addr))),
+ None => Ok(None),
+ }
+ }
+
+ /// Accepts a new incoming connection to this listener.
+ ///
+ /// This method is the same as `accept`, except that it returns a `net::UnixStream` *in blocking mode*
+ /// which isn't bound to a `mio` type. This can later be converted to a `mio` type, if
+ /// necessary.
+ ///
+ /// If an error happens while accepting, `Err` is returned.
+ pub fn accept_std(&self) -> io::Result<Option<(net::UnixStream, net::SocketAddr)>> {
+ match self.inner.accept() {
+ Ok((socket, addr)) => Ok(Some(unsafe {
+ (net::UnixStream::from_raw_fd(socket.into_raw_fd()), addr)
+ })),
+ Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Ok(None),
+ Err(e) => Err(e),
+ }
+ }
+
+ /// Creates a new independently owned handle to the underlying socket.
+ ///
+ /// The returned `UnixListener` is a reference to the same socket that this
+ /// object references. Both handles can be used to accept incoming
+ /// connections and options set on one listener will affect the other.
+ pub fn try_clone(&self) -> io::Result<UnixListener> {
+ self.inner.try_clone().map(|l| UnixListener { inner: l })
+ }
+
+ /// Returns the local socket address of this listener.
+ pub fn local_addr(&self) -> io::Result<net::SocketAddr> {
+ self.inner.local_addr()
+ }
+
+ /// Returns the value of the `SO_ERROR` option.
+ pub fn take_error(&self) -> io::Result<Option<io::Error>> {
+ self.inner.take_error()
+ }
+}
+
+impl Evented for UnixListener {
+ fn register(&self, poll: &Poll, token: Token, events: Ready, opts: PollOpt) -> io::Result<()> {
+ EventedFd(&self.as_raw_fd()).register(poll, token, events, opts)
+ }
+
+ fn reregister(
+ &self,
+ poll: &Poll,
+ token: Token,
+ events: Ready,
+ opts: PollOpt,
+ ) -> io::Result<()> {
+ EventedFd(&self.as_raw_fd()).reregister(poll, token, events, opts)
+ }
+
+ fn deregister(&self, poll: &Poll) -> io::Result<()> {
+ EventedFd(&self.as_raw_fd()).deregister(poll)
+ }
+}
+
+impl AsRawFd for UnixListener {
+ fn as_raw_fd(&self) -> i32 {
+ self.inner.as_raw_fd()
+ }
+}
+
+impl IntoRawFd for UnixListener {
+ fn into_raw_fd(self) -> i32 {
+ self.inner.into_raw_fd()
+ }
+}
+
+impl FromRawFd for UnixListener {
+ unsafe fn from_raw_fd(fd: i32) -> UnixListener {
+ UnixListener {
+ inner: net::UnixListener::from_raw_fd(fd),
+ }
+ }
+}
diff --git a/third_party/rust/mio-uds/src/socket.rs b/third_party/rust/mio-uds/src/socket.rs
new file mode 100644
index 0000000000..820f74dde7
--- /dev/null
+++ b/third_party/rust/mio-uds/src/socket.rs
@@ -0,0 +1,166 @@
+use std::cmp::Ordering;
+use std::io;
+use std::mem;
+use std::os::unix::prelude::*;
+use std::path::Path;
+
+use libc::{self, c_int, c_ulong};
+
+use cvt;
+
+// See below for the usage of SOCK_CLOEXEC, but this constant is only defined on
+// Linux currently (e.g. support doesn't exist on other platforms). In order to
+// get name resolution to work and things to compile we just define a dummy
+// SOCK_CLOEXEC here for other platforms. Note that the dummy constant isn't
+// actually ever used (the blocks below are wrapped in `if cfg!` as well.
+#[cfg(any(
+ target_os = "linux",
+ target_os = "android",
+ target_os = "illumos",
+ target_os = "solaris"
+))]
+use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK};
+#[cfg(not(any(
+ target_os = "linux",
+ target_os = "android",
+ target_os = "illumos",
+ target_os = "solaris"
+)))]
+const SOCK_CLOEXEC: c_int = 0;
+#[cfg(not(any(
+ target_os = "linux",
+ target_os = "android",
+ target_os = "illumos",
+ target_os = "solaris"
+)))]
+const SOCK_NONBLOCK: c_int = 0;
+
+pub struct Socket {
+ fd: c_int,
+}
+
+impl Socket {
+ pub fn new(ty: c_int) -> io::Result<Socket> {
+ unsafe {
+ // On linux we first attempt to pass the SOCK_CLOEXEC flag to
+ // atomically create the socket and set it as CLOEXEC. Support for
+ // this option, however, was added in 2.6.27, and we still support
+ // 2.6.18 as a kernel, so if the returned error is EINVAL we
+ // fallthrough to the fallback.
+ if cfg!(any(
+ target_os = "linux",
+ target_os = "android",
+ target_os = "illumos",
+ target_os = "solaris"
+ )) {
+ let flags = ty | SOCK_CLOEXEC | SOCK_NONBLOCK;
+ match cvt(libc::socket(libc::AF_UNIX, flags, 0)) {
+ Ok(fd) => return Ok(Socket { fd: fd }),
+ Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {}
+ Err(e) => return Err(e),
+ }
+ }
+
+ let fd = Socket { fd: try!(cvt(libc::socket(libc::AF_UNIX, ty, 0))) };
+ try!(cvt(libc::ioctl(fd.fd, libc::FIOCLEX)));
+ let mut nonblocking = 1 as c_ulong;
+ try!(cvt(libc::ioctl(fd.fd, libc::FIONBIO, &mut nonblocking)));
+ Ok(fd)
+ }
+ }
+
+ pub fn pair(ty: c_int) -> io::Result<(Socket, Socket)> {
+ unsafe {
+ let mut fds = [0, 0];
+
+ // Like above, see if we can set cloexec atomically
+ if cfg!(any(
+ target_os = "linux",
+ target_os = "android",
+ target_os = "illumos",
+ target_os = "solaris"
+ )) {
+ let flags = ty | SOCK_CLOEXEC | SOCK_NONBLOCK;
+ match cvt(libc::socketpair(libc::AF_UNIX, flags, 0, fds.as_mut_ptr())) {
+ Ok(_) => {
+ return Ok((Socket { fd: fds[0] }, Socket { fd: fds[1] }))
+ }
+ Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {},
+ Err(e) => return Err(e),
+ }
+ }
+
+ try!(cvt(libc::socketpair(libc::AF_UNIX, ty, 0, fds.as_mut_ptr())));
+ let a = Socket { fd: fds[0] };
+ let b = Socket { fd: fds[1] };
+ try!(cvt(libc::ioctl(a.fd, libc::FIOCLEX)));
+ try!(cvt(libc::ioctl(b.fd, libc::FIOCLEX)));
+ let mut nonblocking = 1 as c_ulong;
+ try!(cvt(libc::ioctl(a.fd, libc::FIONBIO, &mut nonblocking)));
+ try!(cvt(libc::ioctl(b.fd, libc::FIONBIO, &mut nonblocking)));
+ Ok((a, b))
+ }
+ }
+
+ pub fn fd(&self) -> c_int {
+ self.fd
+ }
+
+ pub fn into_fd(self) -> c_int {
+ let ret = self.fd;
+ mem::forget(self);
+ ret
+ }
+}
+
+impl Drop for Socket {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = libc::close(self.fd);
+ }
+ }
+}
+
+pub unsafe fn sockaddr_un(path: &Path)
+ -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
+ let mut addr: libc::sockaddr_un = mem::zeroed();
+ addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
+
+ let bytes = path.as_os_str().as_bytes();
+
+ match (bytes.get(0), bytes.len().cmp(&addr.sun_path.len())) {
+ // Abstract paths don't need a null terminator
+ (Some(&0), Ordering::Greater) => {
+ return Err(io::Error::new(io::ErrorKind::InvalidInput,
+ "path must be no longer than SUN_LEN"));
+ }
+ (_, Ordering::Greater) | (_, Ordering::Equal) => {
+ return Err(io::Error::new(io::ErrorKind::InvalidInput,
+ "path must be shorter than SUN_LEN"));
+ }
+ _ => {}
+ }
+ for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
+ *dst = *src as libc::c_char;
+ }
+ // null byte for pathname addresses is already there because we zeroed the
+ // struct
+
+ let mut len = sun_path_offset() + bytes.len();
+ match bytes.get(0) {
+ Some(&0) | None => {}
+ Some(_) => len += 1,
+ }
+ Ok((addr, len as libc::socklen_t))
+}
+
+fn sun_path_offset() -> usize {
+ unsafe {
+ // Work with an actual instance of the type since using a null pointer is UB
+ let addr: libc::sockaddr_un = mem::uninitialized();
+ let base = &addr as *const _ as usize;
+ let path = &addr.sun_path as *const _ as usize;
+ path - base
+ }
+}
+
diff --git a/third_party/rust/mio-uds/src/stream.rs b/third_party/rust/mio-uds/src/stream.rs
new file mode 100644
index 0000000000..82a283492b
--- /dev/null
+++ b/third_party/rust/mio-uds/src/stream.rs
@@ -0,0 +1,246 @@
+use std::cmp;
+use std::io::prelude::*;
+use std::io;
+use std::os::unix::net;
+use std::os::unix::prelude::*;
+use std::path::Path;
+use std::net::Shutdown;
+
+use iovec::IoVec;
+use iovec::unix as iovec;
+use libc;
+use mio::event::Evented;
+use mio::unix::EventedFd;
+use mio::{Poll, Token, Ready, PollOpt};
+
+use cvt;
+use socket::{sockaddr_un, Socket};
+
+/// A Unix stream socket.
+///
+/// This type represents a `SOCK_STREAM` connection of the `AF_UNIX` family,
+/// otherwise known as Unix domain sockets or Unix sockets. This stream is
+/// readable/writable and acts similarly to a TCP stream where reads/writes are
+/// all in order with respect to the other connected end.
+///
+/// Streams can either be connected to paths locally or another ephemeral socket
+/// created by the `pair` function.
+///
+/// A `UnixStream` implements the `Read`, `Write`, `Evented`, `AsRawFd`,
+/// `IntoRawFd`, and `FromRawFd` traits for interoperating with other I/O code.
+///
+/// Note that all values of this type are typically in nonblocking mode, so the
+/// `read` and `write` methods may return an error with the kind of
+/// `WouldBlock`, indicating that it's not ready to read/write just yet.
+#[derive(Debug)]
+pub struct UnixStream {
+ inner: net::UnixStream,
+}
+
+impl UnixStream {
+ /// Connects to the socket named by `path`.
+ ///
+ /// The socket returned may not be readable and/or writable yet, as the
+ /// connection may be in progress. The socket should be registered with an
+ /// event loop to wait on both of these properties being available.
+ pub fn connect<P: AsRef<Path>>(p: P) -> io::Result<UnixStream> {
+ UnixStream::_connect(p.as_ref())
+ }
+
+ fn _connect(path: &Path) -> io::Result<UnixStream> {
+ unsafe {
+ let (addr, len) = try!(sockaddr_un(path));
+ let socket = try!(Socket::new(libc::SOCK_STREAM));
+ let addr = &addr as *const _ as *const _;
+ match cvt(libc::connect(socket.fd(), addr, len)) {
+ Ok(_) => {}
+ Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
+ Err(e) => return Err(e),
+ }
+
+ Ok(UnixStream::from_raw_fd(socket.into_fd()))
+ }
+ }
+
+ /// Consumes a standard library `UnixStream` and returns a wrapped
+ /// `UnixStream` compatible with mio.
+ ///
+ /// The returned stream is moved into nonblocking mode and is otherwise
+ /// ready to get associated with an event loop.
+ pub fn from_stream(stream: net::UnixStream) -> io::Result<UnixStream> {
+ try!(stream.set_nonblocking(true));
+ Ok(UnixStream { inner: stream })
+ }
+
+ /// Creates an unnamed pair of connected sockets.
+ ///
+ /// Returns two `UnixStream`s which are connected to each other.
+ pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
+ Socket::pair(libc::SOCK_STREAM).map(|(a, b)| unsafe {
+ (UnixStream::from_raw_fd(a.into_fd()),
+ UnixStream::from_raw_fd(b.into_fd()))
+ })
+ }
+
+ /// Creates a new independently owned handle to the underlying socket.
+ ///
+ /// The returned `UnixStream` is a reference to the same stream that this
+ /// object references. Both handles will read and write the same stream of
+ /// data, and options set on one stream will be propogated to the other
+ /// stream.
+ pub fn try_clone(&self) -> io::Result<UnixStream> {
+ self.inner.try_clone().map(|s| {
+ UnixStream { inner: s }
+ })
+ }
+
+ /// Returns the socket address of the local half of this connection.
+ pub fn local_addr(&self) -> io::Result<net::SocketAddr> {
+ self.inner.local_addr()
+ }
+
+ /// Returns the socket address of the remote half of this connection.
+ pub fn peer_addr(&self) -> io::Result<net::SocketAddr> {
+ self.inner.peer_addr()
+ }
+
+ /// Returns the value of the `SO_ERROR` option.
+ pub fn take_error(&self) -> io::Result<Option<io::Error>> {
+ self.inner.take_error()
+ }
+
+ /// Shuts down the read, write, or both halves of this connection.
+ ///
+ /// This function will cause all pending and future I/O calls on the
+ /// specified portions to immediately return with an appropriate value
+ /// (see the documentation of `Shutdown`).
+ pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
+ self.inner.shutdown(how)
+ }
+
+ /// Read in a list of buffers all at once.
+ ///
+ /// This operation will attempt to read bytes from this socket and place
+ /// them into the list of buffers provided. Note that each buffer is an
+ /// `IoVec` which can be created from a byte slice.
+ ///
+ /// The buffers provided will be filled in sequentially. A buffer will be
+ /// entirely filled up before the next is written to.
+ ///
+ /// The number of bytes read is returned, if successful, or an error is
+ /// returned otherwise. If no bytes are available to be read yet then
+ /// a "would block" error is returned. This operation does not block.
+ pub fn read_bufs(&self, bufs: &mut [&mut IoVec]) -> io::Result<usize> {
+ unsafe {
+ let slice = iovec::as_os_slice_mut(bufs);
+ let len = cmp::min(<libc::c_int>::max_value() as usize, slice.len());
+ let rc = libc::readv(self.inner.as_raw_fd(),
+ slice.as_ptr(),
+ len as libc::c_int);
+ if rc < 0 {
+ Err(io::Error::last_os_error())
+ } else {
+ Ok(rc as usize)
+ }
+ }
+ }
+
+ /// Write a list of buffers all at once.
+ ///
+ /// This operation will attempt to write a list of byte buffers to this
+ /// socket. Note that each buffer is an `IoVec` which can be created from a
+ /// byte slice.
+ ///
+ /// The buffers provided will be written sequentially. A buffer will be
+ /// entirely written before the next is written.
+ ///
+ /// The number of bytes written is returned, if successful, or an error is
+ /// returned otherwise. If the socket is not currently writable then a
+ /// "would block" error is returned. This operation does not block.
+ pub fn write_bufs(&self, bufs: &[&IoVec]) -> io::Result<usize> {
+ unsafe {
+ let slice = iovec::as_os_slice(bufs);
+ let len = cmp::min(<libc::c_int>::max_value() as usize, slice.len());
+ let rc = libc::writev(self.inner.as_raw_fd(),
+ slice.as_ptr(),
+ len as libc::c_int);
+ if rc < 0 {
+ Err(io::Error::last_os_error())
+ } else {
+ Ok(rc as usize)
+ }
+ }
+ }
+}
+
+impl Evented for UnixStream {
+ fn register(&self,
+ poll: &Poll,
+ token: Token,
+ events: Ready,
+ opts: PollOpt) -> io::Result<()> {
+ EventedFd(&self.as_raw_fd()).register(poll, token, events, opts)
+ }
+
+ fn reregister(&self,
+ poll: &Poll,
+ token: Token,
+ events: Ready,
+ opts: PollOpt) -> io::Result<()> {
+ EventedFd(&self.as_raw_fd()).reregister(poll, token, events, opts)
+ }
+
+ fn deregister(&self, poll: &Poll) -> io::Result<()> {
+ EventedFd(&self.as_raw_fd()).deregister(poll)
+ }
+}
+
+impl Read for UnixStream {
+ fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
+ self.inner.read(bytes)
+ }
+}
+
+impl<'a> Read for &'a UnixStream {
+ fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
+ (&self.inner).read(bytes)
+ }
+}
+
+impl Write for UnixStream {
+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ self.inner.write(bytes)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.inner.flush()
+ }
+}
+
+impl<'a> Write for &'a UnixStream {
+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ (&self.inner).write(bytes)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ (&self.inner).flush()
+ }
+}
+
+impl AsRawFd for UnixStream {
+ fn as_raw_fd(&self) -> i32 {
+ self.inner.as_raw_fd()
+ }
+}
+
+impl IntoRawFd for UnixStream {
+ fn into_raw_fd(self) -> i32 {
+ self.inner.into_raw_fd()
+ }
+}
+
+impl FromRawFd for UnixStream {
+ unsafe fn from_raw_fd(fd: i32) -> UnixStream {
+ UnixStream { inner: net::UnixStream::from_raw_fd(fd) }
+ }
+}