mio_uds/stream.rs
1use std::cmp;
2use std::io::prelude::*;
3use std::io;
4use std::os::unix::net;
5use std::os::unix::prelude::*;
6use std::path::Path;
7use std::net::Shutdown;
8
9use iovec::IoVec;
10use iovec::unix as iovec;
11use libc;
12use mio::event::Evented;
13use mio::unix::EventedFd;
14use mio::{Poll, Token, Ready, PollOpt};
15
16use cvt;
17use socket::{sockaddr_un, Socket};
18
19/// A Unix stream socket.
20///
21/// This type represents a `SOCK_STREAM` connection of the `AF_UNIX` family,
22/// otherwise known as Unix domain sockets or Unix sockets. This stream is
23/// readable/writable and acts similarly to a TCP stream where reads/writes are
24/// all in order with respect to the other connected end.
25///
26/// Streams can either be connected to paths locally or another ephemeral socket
27/// created by the `pair` function.
28///
29/// A `UnixStream` implements the `Read`, `Write`, `Evented`, `AsRawFd`,
30/// `IntoRawFd`, and `FromRawFd` traits for interoperating with other I/O code.
31///
32/// Note that all values of this type are typically in nonblocking mode, so the
33/// `read` and `write` methods may return an error with the kind of
34/// `WouldBlock`, indicating that it's not ready to read/write just yet.
35#[derive(Debug)]
36pub struct UnixStream {
37 inner: net::UnixStream,
38}
39
40impl UnixStream {
41 /// Connects to the socket named by `path`.
42 ///
43 /// The socket returned may not be readable and/or writable yet, as the
44 /// connection may be in progress. The socket should be registered with an
45 /// event loop to wait on both of these properties being available.
46 pub fn connect<P: AsRef<Path>>(p: P) -> io::Result<UnixStream> {
47 UnixStream::_connect(p.as_ref())
48 }
49
50 fn _connect(path: &Path) -> io::Result<UnixStream> {
51 unsafe {
52 let (addr, len) = try!(sockaddr_un(path));
53 let socket = try!(Socket::new(libc::SOCK_STREAM));
54 let addr = &addr as *const _ as *const _;
55 match cvt(libc::connect(socket.fd(), addr, len)) {
56 Ok(_) => {}
57 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
58 Err(e) => return Err(e),
59 }
60
61 Ok(UnixStream::from_raw_fd(socket.into_fd()))
62 }
63 }
64
65 /// Consumes a standard library `UnixStream` and returns a wrapped
66 /// `UnixStream` compatible with mio.
67 ///
68 /// The returned stream is moved into nonblocking mode and is otherwise
69 /// ready to get associated with an event loop.
70 pub fn from_stream(stream: net::UnixStream) -> io::Result<UnixStream> {
71 try!(stream.set_nonblocking(true));
72 Ok(UnixStream { inner: stream })
73 }
74
75 /// Creates an unnamed pair of connected sockets.
76 ///
77 /// Returns two `UnixStream`s which are connected to each other.
78 pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
79 Socket::pair(libc::SOCK_STREAM).map(|(a, b)| unsafe {
80 (UnixStream::from_raw_fd(a.into_fd()),
81 UnixStream::from_raw_fd(b.into_fd()))
82 })
83 }
84
85 /// Creates a new independently owned handle to the underlying socket.
86 ///
87 /// The returned `UnixStream` is a reference to the same stream that this
88 /// object references. Both handles will read and write the same stream of
89 /// data, and options set on one stream will be propogated to the other
90 /// stream.
91 pub fn try_clone(&self) -> io::Result<UnixStream> {
92 self.inner.try_clone().map(|s| {
93 UnixStream { inner: s }
94 })
95 }
96
97 /// Returns the socket address of the local half of this connection.
98 pub fn local_addr(&self) -> io::Result<net::SocketAddr> {
99 self.inner.local_addr()
100 }
101
102 /// Returns the socket address of the remote half of this connection.
103 pub fn peer_addr(&self) -> io::Result<net::SocketAddr> {
104 self.inner.peer_addr()
105 }
106
107 /// Returns the value of the `SO_ERROR` option.
108 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
109 self.inner.take_error()
110 }
111
112 /// Shuts down the read, write, or both halves of this connection.
113 ///
114 /// This function will cause all pending and future I/O calls on the
115 /// specified portions to immediately return with an appropriate value
116 /// (see the documentation of `Shutdown`).
117 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
118 self.inner.shutdown(how)
119 }
120
121 /// Read in a list of buffers all at once.
122 ///
123 /// This operation will attempt to read bytes from this socket and place
124 /// them into the list of buffers provided. Note that each buffer is an
125 /// `IoVec` which can be created from a byte slice.
126 ///
127 /// The buffers provided will be filled in sequentially. A buffer will be
128 /// entirely filled up before the next is written to.
129 ///
130 /// The number of bytes read is returned, if successful, or an error is
131 /// returned otherwise. If no bytes are available to be read yet then
132 /// a "would block" error is returned. This operation does not block.
133 pub fn read_bufs(&self, bufs: &mut [&mut IoVec]) -> io::Result<usize> {
134 unsafe {
135 let slice = iovec::as_os_slice_mut(bufs);
136 let len = cmp::min(<libc::c_int>::max_value() as usize, slice.len());
137 let rc = libc::readv(self.inner.as_raw_fd(),
138 slice.as_ptr(),
139 len as libc::c_int);
140 if rc < 0 {
141 Err(io::Error::last_os_error())
142 } else {
143 Ok(rc as usize)
144 }
145 }
146 }
147
148 /// Write a list of buffers all at once.
149 ///
150 /// This operation will attempt to write a list of byte buffers to this
151 /// socket. Note that each buffer is an `IoVec` which can be created from a
152 /// byte slice.
153 ///
154 /// The buffers provided will be written sequentially. A buffer will be
155 /// entirely written before the next is written.
156 ///
157 /// The number of bytes written is returned, if successful, or an error is
158 /// returned otherwise. If the socket is not currently writable then a
159 /// "would block" error is returned. This operation does not block.
160 pub fn write_bufs(&self, bufs: &[&IoVec]) -> io::Result<usize> {
161 unsafe {
162 let slice = iovec::as_os_slice(bufs);
163 let len = cmp::min(<libc::c_int>::max_value() as usize, slice.len());
164 let rc = libc::writev(self.inner.as_raw_fd(),
165 slice.as_ptr(),
166 len as libc::c_int);
167 if rc < 0 {
168 Err(io::Error::last_os_error())
169 } else {
170 Ok(rc as usize)
171 }
172 }
173 }
174}
175
176impl Evented for UnixStream {
177 fn register(&self,
178 poll: &Poll,
179 token: Token,
180 events: Ready,
181 opts: PollOpt) -> io::Result<()> {
182 EventedFd(&self.as_raw_fd()).register(poll, token, events, opts)
183 }
184
185 fn reregister(&self,
186 poll: &Poll,
187 token: Token,
188 events: Ready,
189 opts: PollOpt) -> io::Result<()> {
190 EventedFd(&self.as_raw_fd()).reregister(poll, token, events, opts)
191 }
192
193 fn deregister(&self, poll: &Poll) -> io::Result<()> {
194 EventedFd(&self.as_raw_fd()).deregister(poll)
195 }
196}
197
198impl Read for UnixStream {
199 fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
200 self.inner.read(bytes)
201 }
202}
203
204impl<'a> Read for &'a UnixStream {
205 fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
206 (&self.inner).read(bytes)
207 }
208}
209
210impl Write for UnixStream {
211 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
212 self.inner.write(bytes)
213 }
214
215 fn flush(&mut self) -> io::Result<()> {
216 self.inner.flush()
217 }
218}
219
220impl<'a> Write for &'a UnixStream {
221 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
222 (&self.inner).write(bytes)
223 }
224
225 fn flush(&mut self) -> io::Result<()> {
226 (&self.inner).flush()
227 }
228}
229
230impl AsRawFd for UnixStream {
231 fn as_raw_fd(&self) -> i32 {
232 self.inner.as_raw_fd()
233 }
234}
235
236impl IntoRawFd for UnixStream {
237 fn into_raw_fd(self) -> i32 {
238 self.inner.into_raw_fd()
239 }
240}
241
242impl FromRawFd for UnixStream {
243 unsafe fn from_raw_fd(fd: i32) -> UnixStream {
244 UnixStream { inner: net::UnixStream::from_raw_fd(fd) }
245 }
246}