]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/ext/net.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.git] / src / libstd / sys / unix / ext / net.rs
1 // Copyright 2016 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 #![stable(feature = "unix_socket", since = "1.10.0")]
12
13 //! Unix-specific networking functionality
14
15 use libc;
16
17 use ascii;
18 use ffi::OsStr;
19 use fmt;
20 use io;
21 use mem;
22 use net::Shutdown;
23 use os::unix::ffi::OsStrExt;
24 use os::unix::io::{RawFd, AsRawFd, FromRawFd, IntoRawFd};
25 use path::Path;
26 use time::Duration;
27 use sys::cvt;
28 use sys::net::Socket;
29 use sys_common::{AsInner, FromInner, IntoInner};
30
31 #[cfg(any(target_os = "linux", target_os = "android",
32           target_os = "dragonfly", target_os = "freebsd",
33           target_os = "openbsd", target_os = "netbsd",
34           target_os = "haiku", target_os = "bitrig"))]
35 use libc::MSG_NOSIGNAL;
36 #[cfg(not(any(target_os = "linux", target_os = "android",
37               target_os = "dragonfly", target_os = "freebsd",
38               target_os = "openbsd", target_os = "netbsd",
39               target_os = "haiku", target_os = "bitrig")))]
40 const MSG_NOSIGNAL: libc::c_int = 0x0;
41
42 fn sun_path_offset() -> usize {
43     unsafe {
44         // Work with an actual instance of the type since using a null pointer is UB
45         let addr: libc::sockaddr_un = mem::uninitialized();
46         let base = &addr as *const _ as usize;
47         let path = &addr.sun_path as *const _ as usize;
48         path - base
49     }
50 }
51
52 unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> {
53     let mut addr: libc::sockaddr_un = mem::zeroed();
54     addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
55
56     let bytes = path.as_os_str().as_bytes();
57
58     if bytes.contains(&0) {
59         return Err(io::Error::new(io::ErrorKind::InvalidInput,
60                                   "paths may not contain interior null bytes"));
61     }
62
63     if bytes.len() >= addr.sun_path.len() {
64         return Err(io::Error::new(io::ErrorKind::InvalidInput,
65                                   "path must be shorter than SUN_LEN"));
66     }
67     for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
68         *dst = *src as libc::c_char;
69     }
70     // null byte for pathname addresses is already there because we zeroed the
71     // struct
72
73     let mut len = sun_path_offset() + bytes.len();
74     match bytes.get(0) {
75         Some(&0) | None => {}
76         Some(_) => len += 1,
77     }
78     Ok((addr, len as libc::socklen_t))
79 }
80
81 enum AddressKind<'a> {
82     Unnamed,
83     Pathname(&'a Path),
84     Abstract(&'a [u8]),
85 }
86
87 /// An address associated with a Unix socket.
88 ///
89 /// # Examples
90 ///
91 /// ```
92 /// use std::os::unix::net::UnixListener;
93 ///
94 /// let socket = match UnixListener::bind("/tmp/sock") {
95 ///     Ok(sock) => sock,
96 ///     Err(e) => {
97 ///         println!("Couldn't bind: {:?}", e);
98 ///         return
99 ///     }
100 /// };
101 /// let addr = socket.local_addr().expect("Couldn't get local address");
102 /// ```
103 #[derive(Clone)]
104 #[stable(feature = "unix_socket", since = "1.10.0")]
105 pub struct SocketAddr {
106     addr: libc::sockaddr_un,
107     len: libc::socklen_t,
108 }
109
110 impl SocketAddr {
111     fn new<F>(f: F) -> io::Result<SocketAddr>
112         where F: FnOnce(*mut libc::sockaddr, *mut libc::socklen_t) -> libc::c_int
113     {
114         unsafe {
115             let mut addr: libc::sockaddr_un = mem::zeroed();
116             let mut len = mem::size_of::<libc::sockaddr_un>() as libc::socklen_t;
117             cvt(f(&mut addr as *mut _ as *mut _, &mut len))?;
118             SocketAddr::from_parts(addr, len)
119         }
120     }
121
122     fn from_parts(addr: libc::sockaddr_un, mut len: libc::socklen_t) -> io::Result<SocketAddr> {
123         if len == 0 {
124             // When there is a datagram from unnamed unix socket
125             // linux returns zero bytes of address
126             len = sun_path_offset() as libc::socklen_t;  // i.e. zero-length address
127         } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
128             return Err(io::Error::new(io::ErrorKind::InvalidInput,
129                                       "file descriptor did not correspond to a Unix socket"));
130         }
131
132         Ok(SocketAddr {
133             addr: addr,
134             len: len,
135         })
136     }
137
138     /// Returns true if and only if the address is unnamed.
139     ///
140     /// # Examples
141     ///
142     /// A named address:
143     ///
144     /// ```no_run
145     /// use std::os::unix::net::UnixListener;
146     ///
147     /// let socket = UnixListener::bind("/tmp/sock").unwrap();
148     /// let addr = socket.local_addr().expect("Couldn't get local address");
149     /// assert_eq!(addr.is_unnamed(), false);
150     /// ```
151     ///
152     /// An unnamed address:
153     ///
154     /// ```
155     /// use std::os::unix::net::UnixDatagram;
156     ///
157     /// let socket = UnixDatagram::unbound().unwrap();
158     /// let addr = socket.local_addr().expect("Couldn't get local address");
159     /// assert_eq!(addr.is_unnamed(), true);
160     /// ```
161     #[stable(feature = "unix_socket", since = "1.10.0")]
162     pub fn is_unnamed(&self) -> bool {
163         if let AddressKind::Unnamed = self.address() {
164             true
165         } else {
166             false
167         }
168     }
169
170     /// Returns the contents of this address if it is a `pathname` address.
171     ///
172     /// # Examples
173     ///
174     /// With a pathname:
175     ///
176     /// ```no_run
177     /// use std::os::unix::net::UnixListener;
178     /// use std::path::Path;
179     ///
180     /// let socket = UnixListener::bind("/tmp/sock").unwrap();
181     /// let addr = socket.local_addr().expect("Couldn't get local address");
182     /// assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/sock")));
183     /// ```
184     ///
185     /// Without a pathname:
186     ///
187     /// ```
188     /// use std::os::unix::net::UnixDatagram;
189     ///
190     /// let socket = UnixDatagram::unbound().unwrap();
191     /// let addr = socket.local_addr().expect("Couldn't get local address");
192     /// assert_eq!(addr.as_pathname(), None);
193     /// ```
194     #[stable(feature = "unix_socket", since = "1.10.0")]
195     pub fn as_pathname(&self) -> Option<&Path> {
196         if let AddressKind::Pathname(path) = self.address() {
197             Some(path)
198         } else {
199             None
200         }
201     }
202
203     fn address<'a>(&'a self) -> AddressKind<'a> {
204         let len = self.len as usize - sun_path_offset();
205         let path = unsafe { mem::transmute::<&[libc::c_char], &[u8]>(&self.addr.sun_path) };
206
207         // macOS seems to return a len of 16 and a zeroed sun_path for unnamed addresses
208         if len == 0 || (cfg!(not(target_os = "linux")) && self.addr.sun_path[0] == 0) {
209             AddressKind::Unnamed
210         } else if self.addr.sun_path[0] == 0 {
211             AddressKind::Abstract(&path[1..len])
212         } else {
213             AddressKind::Pathname(OsStr::from_bytes(&path[..len - 1]).as_ref())
214         }
215     }
216 }
217
218 #[stable(feature = "unix_socket", since = "1.10.0")]
219 impl fmt::Debug for SocketAddr {
220     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
221         match self.address() {
222             AddressKind::Unnamed => write!(fmt, "(unnamed)"),
223             AddressKind::Abstract(name) => write!(fmt, "{} (abstract)", AsciiEscaped(name)),
224             AddressKind::Pathname(path) => write!(fmt, "{:?} (pathname)", path),
225         }
226     }
227 }
228
229 struct AsciiEscaped<'a>(&'a [u8]);
230
231 impl<'a> fmt::Display for AsciiEscaped<'a> {
232     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
233         write!(fmt, "\"")?;
234         for byte in self.0.iter().cloned().flat_map(ascii::escape_default) {
235             write!(fmt, "{}", byte as char)?;
236         }
237         write!(fmt, "\"")
238     }
239 }
240
241 /// A Unix stream socket.
242 ///
243 /// # Examples
244 ///
245 /// ```no_run
246 /// use std::os::unix::net::UnixStream;
247 /// use std::io::prelude::*;
248 ///
249 /// let mut stream = UnixStream::connect("/path/to/my/socket").unwrap();
250 /// stream.write_all(b"hello world").unwrap();
251 /// let mut response = String::new();
252 /// stream.read_to_string(&mut response).unwrap();
253 /// println!("{}", response);
254 /// ```
255 #[stable(feature = "unix_socket", since = "1.10.0")]
256 pub struct UnixStream(Socket);
257
258 #[stable(feature = "unix_socket", since = "1.10.0")]
259 impl fmt::Debug for UnixStream {
260     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
261         let mut builder = fmt.debug_struct("UnixStream");
262         builder.field("fd", self.0.as_inner());
263         if let Ok(addr) = self.local_addr() {
264             builder.field("local", &addr);
265         }
266         if let Ok(addr) = self.peer_addr() {
267             builder.field("peer", &addr);
268         }
269         builder.finish()
270     }
271 }
272
273 impl UnixStream {
274     /// Connects to the socket named by `path`.
275     ///
276     /// # Examples
277     ///
278     /// ```no_run
279     /// use std::os::unix::net::UnixStream;
280     ///
281     /// let socket = match UnixStream::connect("/tmp/sock") {
282     ///     Ok(sock) => sock,
283     ///     Err(e) => {
284     ///         println!("Couldn't connect: {:?}", e);
285     ///         return
286     ///     }
287     /// };
288     /// ```
289     #[stable(feature = "unix_socket", since = "1.10.0")]
290     pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
291         fn inner(path: &Path) -> io::Result<UnixStream> {
292             unsafe {
293                 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
294                 let (addr, len) = sockaddr_un(path)?;
295
296                 cvt(libc::connect(*inner.as_inner(), &addr as *const _ as *const _, len))?;
297                 Ok(UnixStream(inner))
298             }
299         }
300         inner(path.as_ref())
301     }
302
303     /// Creates an unnamed pair of connected sockets.
304     ///
305     /// Returns two `UnixStream`s which are connected to each other.
306     ///
307     /// # Examples
308     ///
309     /// ```no_run
310     /// use std::os::unix::net::UnixStream;
311     ///
312     /// let (sock1, sock2) = match UnixStream::pair() {
313     ///     Ok((sock1, sock2)) => (sock1, sock2),
314     ///     Err(e) => {
315     ///         println!("Couldn't create a pair of sockets: {:?}", e);
316     ///         return
317     ///     }
318     /// };
319     /// ```
320     #[stable(feature = "unix_socket", since = "1.10.0")]
321     pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
322         let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_STREAM)?;
323         Ok((UnixStream(i1), UnixStream(i2)))
324     }
325
326     /// Creates a new independently owned handle to the underlying socket.
327     ///
328     /// The returned `UnixStream` is a reference to the same stream that this
329     /// object references. Both handles will read and write the same stream of
330     /// data, and options set on one stream will be propogated to the other
331     /// stream.
332     ///
333     /// # Examples
334     ///
335     /// ```no_run
336     /// use std::os::unix::net::UnixStream;
337     ///
338     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
339     /// let sock_copy = socket.try_clone().expect("Couldn't clone socket");
340     /// ```
341     #[stable(feature = "unix_socket", since = "1.10.0")]
342     pub fn try_clone(&self) -> io::Result<UnixStream> {
343         self.0.duplicate().map(UnixStream)
344     }
345
346     /// Returns the socket address of the local half of this connection.
347     ///
348     /// # Examples
349     ///
350     /// ```no_run
351     /// use std::os::unix::net::UnixStream;
352     ///
353     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
354     /// let addr = socket.local_addr().expect("Couldn't get local address");
355     /// ```
356     #[stable(feature = "unix_socket", since = "1.10.0")]
357     pub fn local_addr(&self) -> io::Result<SocketAddr> {
358         SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
359     }
360
361     /// Returns the socket address of the remote half of this connection.
362     ///
363     /// # Examples
364     ///
365     /// ```no_run
366     /// use std::os::unix::net::UnixStream;
367     ///
368     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
369     /// let addr = socket.peer_addr().expect("Couldn't get peer address");
370     /// ```
371     #[stable(feature = "unix_socket", since = "1.10.0")]
372     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
373         SocketAddr::new(|addr, len| unsafe { libc::getpeername(*self.0.as_inner(), addr, len) })
374     }
375
376     /// Sets the read timeout for the socket.
377     ///
378     /// If the provided value is [`None`], then [`read`] calls will block
379     /// indefinitely. It is an error to pass the zero [`Duration`] to this
380     /// method.
381     ///
382     /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
383     /// [`read`]: ../../../../std/io/trait.Read.html#tymethod.read
384     /// [`Duration`]: ../../../../std/time/struct.Duration.html
385     ///
386     /// # Examples
387     ///
388     /// ```no_run
389     /// use std::os::unix::net::UnixStream;
390     /// use std::time::Duration;
391     ///
392     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
393     /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
394     /// ```
395     #[stable(feature = "unix_socket", since = "1.10.0")]
396     pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
397         self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
398     }
399
400     /// Sets the write timeout for the socket.
401     ///
402     /// If the provided value is [`None`], then [`write`] calls will block
403     /// indefinitely. It is an error to pass the zero [`Duration`] to this
404     /// method.
405     ///
406     /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
407     /// [`read`]: ../../../../std/io/trait.Write.html#tymethod.write
408     /// [`Duration`]: ../../../../std/time/struct.Duration.html
409     ///
410     /// # Examples
411     ///
412     /// ```no_run
413     /// use std::os::unix::net::UnixStream;
414     /// use std::time::Duration;
415     ///
416     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
417     /// socket.set_write_timeout(Some(Duration::new(1, 0))).expect("Couldn't set write timeout");
418     /// ```
419     #[stable(feature = "unix_socket", since = "1.10.0")]
420     pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
421         self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
422     }
423
424     /// Returns the read timeout of this socket.
425     ///
426     /// # Examples
427     ///
428     /// ```no_run
429     /// use std::os::unix::net::UnixStream;
430     /// use std::time::Duration;
431     ///
432     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
433     /// socket.set_read_timeout(Some(Duration::new(1, 0))).expect("Couldn't set read timeout");
434     /// assert_eq!(socket.read_timeout().unwrap(), Some(Duration::new(1, 0)));
435     /// ```
436     #[stable(feature = "unix_socket", since = "1.10.0")]
437     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
438         self.0.timeout(libc::SO_RCVTIMEO)
439     }
440
441     /// Returns the write timeout of this socket.
442     ///
443     /// # Examples
444     ///
445     /// ```no_run
446     /// use std::os::unix::net::UnixStream;
447     /// use std::time::Duration;
448     ///
449     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
450     /// socket.set_write_timeout(Some(Duration::new(1, 0))).expect("Couldn't set write timeout");
451     /// assert_eq!(socket.write_timeout().unwrap(), Some(Duration::new(1, 0)));
452     /// ```
453     #[stable(feature = "unix_socket", since = "1.10.0")]
454     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
455         self.0.timeout(libc::SO_SNDTIMEO)
456     }
457
458     /// Moves the socket into or out of nonblocking mode.
459     ///
460     /// # Examples
461     ///
462     /// ```no_run
463     /// use std::os::unix::net::UnixStream;
464     ///
465     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
466     /// socket.set_nonblocking(true).expect("Couldn't set nonblocking");
467     /// ```
468     #[stable(feature = "unix_socket", since = "1.10.0")]
469     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
470         self.0.set_nonblocking(nonblocking)
471     }
472
473     /// Returns the value of the `SO_ERROR` option.
474     ///
475     /// # Examples
476     ///
477     /// ```no_run
478     /// use std::os::unix::net::UnixStream;
479     ///
480     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
481     /// if let Ok(Some(err)) = socket.take_error() {
482     ///     println!("Got error: {:?}", err);
483     /// }
484     /// ```
485     #[stable(feature = "unix_socket", since = "1.10.0")]
486     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
487         self.0.take_error()
488     }
489
490     /// Shuts down the read, write, or both halves of this connection.
491     ///
492     /// This function will cause all pending and future I/O calls on the
493     /// specified portions to immediately return with an appropriate value
494     /// (see the documentation of [`Shutdown`]).
495     ///
496     /// [`Shutdown`]: ../../../../std/net/enum.Shutdown.html
497     ///
498     /// # Examples
499     ///
500     /// ```no_run
501     /// use std::os::unix::net::UnixStream;
502     /// use std::net::Shutdown;
503     ///
504     /// let socket = UnixStream::connect("/tmp/sock").unwrap();
505     /// socket.shutdown(Shutdown::Both).expect("shutdown function failed");
506     /// ```
507     #[stable(feature = "unix_socket", since = "1.10.0")]
508     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
509         self.0.shutdown(how)
510     }
511 }
512
513 #[stable(feature = "unix_socket", since = "1.10.0")]
514 impl io::Read for UnixStream {
515     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
516         io::Read::read(&mut &*self, buf)
517     }
518
519     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
520         io::Read::read_to_end(&mut &*self, buf)
521     }
522 }
523
524 #[stable(feature = "unix_socket", since = "1.10.0")]
525 impl<'a> io::Read for &'a UnixStream {
526     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
527         self.0.read(buf)
528     }
529
530     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
531         self.0.read_to_end(buf)
532     }
533 }
534
535 #[stable(feature = "unix_socket", since = "1.10.0")]
536 impl io::Write for UnixStream {
537     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
538         io::Write::write(&mut &*self, buf)
539     }
540
541     fn flush(&mut self) -> io::Result<()> {
542         io::Write::flush(&mut &*self)
543     }
544 }
545
546 #[stable(feature = "unix_socket", since = "1.10.0")]
547 impl<'a> io::Write for &'a UnixStream {
548     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
549         self.0.write(buf)
550     }
551
552     fn flush(&mut self) -> io::Result<()> {
553         Ok(())
554     }
555 }
556
557 #[stable(feature = "unix_socket", since = "1.10.0")]
558 impl AsRawFd for UnixStream {
559     fn as_raw_fd(&self) -> RawFd {
560         *self.0.as_inner()
561     }
562 }
563
564 #[stable(feature = "unix_socket", since = "1.10.0")]
565 impl FromRawFd for UnixStream {
566     unsafe fn from_raw_fd(fd: RawFd) -> UnixStream {
567         UnixStream(Socket::from_inner(fd))
568     }
569 }
570
571 #[stable(feature = "unix_socket", since = "1.10.0")]
572 impl IntoRawFd for UnixStream {
573     fn into_raw_fd(self) -> RawFd {
574         self.0.into_inner()
575     }
576 }
577
578 /// A structure representing a Unix domain socket server.
579 ///
580 /// # Examples
581 ///
582 /// ```no_run
583 /// use std::thread;
584 /// use std::os::unix::net::{UnixStream, UnixListener};
585 ///
586 /// fn handle_client(stream: UnixStream) {
587 ///     // ...
588 /// }
589 ///
590 /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
591 ///
592 /// // accept connections and process them, spawning a new thread for each one
593 /// for stream in listener.incoming() {
594 ///     match stream {
595 ///         Ok(stream) => {
596 ///             /* connection succeeded */
597 ///             thread::spawn(|| handle_client(stream));
598 ///         }
599 ///         Err(err) => {
600 ///             /* connection failed */
601 ///             break;
602 ///         }
603 ///     }
604 /// }
605 /// ```
606 #[stable(feature = "unix_socket", since = "1.10.0")]
607 pub struct UnixListener(Socket);
608
609 #[stable(feature = "unix_socket", since = "1.10.0")]
610 impl fmt::Debug for UnixListener {
611     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
612         let mut builder = fmt.debug_struct("UnixListener");
613         builder.field("fd", self.0.as_inner());
614         if let Ok(addr) = self.local_addr() {
615             builder.field("local", &addr);
616         }
617         builder.finish()
618     }
619 }
620
621 impl UnixListener {
622     /// Creates a new `UnixListener` bound to the specified socket.
623     ///
624     /// # Examples
625     ///
626     /// ```no_run
627     /// use std::os::unix::net::UnixListener;
628     ///
629     /// let listener = match UnixListener::bind("/path/to/the/socket") {
630     ///     Ok(sock) => sock,
631     ///     Err(e) => {
632     ///         println!("Couldn't connect: {:?}", e);
633     ///         return
634     ///     }
635     /// };
636     /// ```
637     #[stable(feature = "unix_socket", since = "1.10.0")]
638     pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
639         fn inner(path: &Path) -> io::Result<UnixListener> {
640             unsafe {
641                 let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
642                 let (addr, len) = sockaddr_un(path)?;
643
644                 cvt(libc::bind(*inner.as_inner(), &addr as *const _ as *const _, len))?;
645                 cvt(libc::listen(*inner.as_inner(), 128))?;
646
647                 Ok(UnixListener(inner))
648             }
649         }
650         inner(path.as_ref())
651     }
652
653     /// Accepts a new incoming connection to this listener.
654     ///
655     /// This function will block the calling thread until a new Unix connection
656     /// is established. When established, the corersponding [`UnixStream`] and
657     /// the remote peer's address will be returned.
658     ///
659     /// [`UnixStream`]: ../../../../std/os/unix/net/struct.UnixStream.html
660     ///
661     /// # Examples
662     ///
663     /// ```no_run
664     /// use std::os::unix::net::UnixListener;
665     ///
666     /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
667     ///
668     /// match listener.accept() {
669     ///     Ok((socket, addr)) => println!("Got a client: {:?}", addr),
670     ///     Err(e) => println!("accept function failed: {:?}", e),
671     /// }
672     /// ```
673     #[stable(feature = "unix_socket", since = "1.10.0")]
674     pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
675         let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
676         let mut len = mem::size_of_val(&storage) as libc::socklen_t;
677         let sock = self.0.accept(&mut storage as *mut _ as *mut _, &mut len)?;
678         let addr = SocketAddr::from_parts(storage, len)?;
679         Ok((UnixStream(sock), addr))
680     }
681
682     /// Creates a new independently owned handle to the underlying socket.
683     ///
684     /// The returned `UnixListener` is a reference to the same socket that this
685     /// object references. Both handles can be used to accept incoming
686     /// connections and options set on one listener will affect the other.
687     ///
688     /// # Examples
689     ///
690     /// ```no_run
691     /// use std::os::unix::net::UnixListener;
692     ///
693     /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
694     ///
695     /// let listener_copy = listener.try_clone().expect("try_clone failed");
696     /// ```
697     #[stable(feature = "unix_socket", since = "1.10.0")]
698     pub fn try_clone(&self) -> io::Result<UnixListener> {
699         self.0.duplicate().map(UnixListener)
700     }
701
702     /// Returns the local socket address of this listener.
703     ///
704     /// # Examples
705     ///
706     /// ```no_run
707     /// use std::os::unix::net::UnixListener;
708     ///
709     /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
710     ///
711     /// let addr = listener.local_addr().expect("Couldn't get local address");
712     /// ```
713     #[stable(feature = "unix_socket", since = "1.10.0")]
714     pub fn local_addr(&self) -> io::Result<SocketAddr> {
715         SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
716     }
717
718     /// Moves the socket into or out of nonblocking mode.
719     ///
720     /// # Examples
721     ///
722     /// ```no_run
723     /// use std::os::unix::net::UnixListener;
724     ///
725     /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
726     ///
727     /// listener.set_nonblocking(true).expect("Couldn't set non blocking");
728     /// ```
729     #[stable(feature = "unix_socket", since = "1.10.0")]
730     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
731         self.0.set_nonblocking(nonblocking)
732     }
733
734     /// Returns the value of the `SO_ERROR` option.
735     ///
736     /// # Examples
737     ///
738     /// ```no_run
739     /// use std::os::unix::net::UnixListener;
740     ///
741     /// let listener = UnixListener::bind("/tmp/sock").unwrap();
742     ///
743     /// if let Ok(Some(err)) = listener.take_error() {
744     ///     println!("Got error: {:?}", err);
745     /// }
746     /// ```
747     #[stable(feature = "unix_socket", since = "1.10.0")]
748     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
749         self.0.take_error()
750     }
751
752     /// Returns an iterator over incoming connections.
753     ///
754     /// The iterator will never return [`None`] and will also not yield the
755     /// peer's [`SocketAddr`] structure.
756     ///
757     /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
758     /// [`SocketAddr`]: struct.SocketAddr.html
759     ///
760     /// # Examples
761     ///
762     /// ```no_run
763     /// use std::thread;
764     /// use std::os::unix::net::{UnixStream, UnixListener};
765     ///
766     /// fn handle_client(stream: UnixStream) {
767     ///     // ...
768     /// }
769     ///
770     /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
771     ///
772     /// for stream in listener.incoming() {
773     ///     match stream {
774     ///         Ok(stream) => {
775     ///             thread::spawn(|| handle_client(stream));
776     ///         }
777     ///         Err(err) => {
778     ///             break;
779     ///         }
780     ///     }
781     /// }
782     /// ```
783     #[stable(feature = "unix_socket", since = "1.10.0")]
784     pub fn incoming<'a>(&'a self) -> Incoming<'a> {
785         Incoming { listener: self }
786     }
787 }
788
789 #[stable(feature = "unix_socket", since = "1.10.0")]
790 impl AsRawFd for UnixListener {
791     fn as_raw_fd(&self) -> RawFd {
792         *self.0.as_inner()
793     }
794 }
795
796 #[stable(feature = "unix_socket", since = "1.10.0")]
797 impl FromRawFd for UnixListener {
798     unsafe fn from_raw_fd(fd: RawFd) -> UnixListener {
799         UnixListener(Socket::from_inner(fd))
800     }
801 }
802
803 #[stable(feature = "unix_socket", since = "1.10.0")]
804 impl IntoRawFd for UnixListener {
805     fn into_raw_fd(self) -> RawFd {
806         self.0.into_inner()
807     }
808 }
809
810 #[stable(feature = "unix_socket", since = "1.10.0")]
811 impl<'a> IntoIterator for &'a UnixListener {
812     type Item = io::Result<UnixStream>;
813     type IntoIter = Incoming<'a>;
814
815     fn into_iter(self) -> Incoming<'a> {
816         self.incoming()
817     }
818 }
819
820 /// An iterator over incoming connections to a [`UnixListener`].
821 ///
822 /// It will never return [`None`].
823 ///
824 /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
825 /// [`UnixListener`]: struct.UnixListener.html
826 ///
827 /// # Examples
828 ///
829 /// ```no_run
830 /// use std::thread;
831 /// use std::os::unix::net::{UnixStream, UnixListener};
832 ///
833 /// fn handle_client(stream: UnixStream) {
834 ///     // ...
835 /// }
836 ///
837 /// let listener = UnixListener::bind("/path/to/the/socket").unwrap();
838 ///
839 /// for stream in listener.incoming() {
840 ///     match stream {
841 ///         Ok(stream) => {
842 ///             thread::spawn(|| handle_client(stream));
843 ///         }
844 ///         Err(err) => {
845 ///             break;
846 ///         }
847 ///     }
848 /// }
849 /// ```
850 #[derive(Debug)]
851 #[stable(feature = "unix_socket", since = "1.10.0")]
852 pub struct Incoming<'a> {
853     listener: &'a UnixListener,
854 }
855
856 #[stable(feature = "unix_socket", since = "1.10.0")]
857 impl<'a> Iterator for Incoming<'a> {
858     type Item = io::Result<UnixStream>;
859
860     fn next(&mut self) -> Option<io::Result<UnixStream>> {
861         Some(self.listener.accept().map(|s| s.0))
862     }
863
864     fn size_hint(&self) -> (usize, Option<usize>) {
865         (usize::max_value(), None)
866     }
867 }
868
869 /// A Unix datagram socket.
870 ///
871 /// # Examples
872 ///
873 /// ```no_run
874 /// use std::os::unix::net::UnixDatagram;
875 ///
876 /// let socket = UnixDatagram::bind("/path/to/my/socket").unwrap();
877 /// socket.send_to(b"hello world", "/path/to/other/socket").unwrap();
878 /// let mut buf = [0; 100];
879 /// let (count, address) = socket.recv_from(&mut buf).unwrap();
880 /// println!("socket {:?} sent {:?}", address, &buf[..count]);
881 /// ```
882 #[stable(feature = "unix_socket", since = "1.10.0")]
883 pub struct UnixDatagram(Socket);
884
885 #[stable(feature = "unix_socket", since = "1.10.0")]
886 impl fmt::Debug for UnixDatagram {
887     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
888         let mut builder = fmt.debug_struct("UnixDatagram");
889         builder.field("fd", self.0.as_inner());
890         if let Ok(addr) = self.local_addr() {
891             builder.field("local", &addr);
892         }
893         if let Ok(addr) = self.peer_addr() {
894             builder.field("peer", &addr);
895         }
896         builder.finish()
897     }
898 }
899
900 impl UnixDatagram {
901     /// Creates a Unix datagram socket bound to the given path.
902     ///
903     /// # Examples
904     ///
905     /// ```no_run
906     /// use std::os::unix::net::UnixDatagram;
907     ///
908     /// let sock = match UnixDatagram::bind("/path/to/the/socket") {
909     ///     Ok(sock) => sock,
910     ///     Err(e) => {
911     ///         println!("Couldn't bind: {:?}", e);
912     ///         return
913     ///     }
914     /// };
915     /// ```
916     #[stable(feature = "unix_socket", since = "1.10.0")]
917     pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
918         fn inner(path: &Path) -> io::Result<UnixDatagram> {
919             unsafe {
920                 let socket = UnixDatagram::unbound()?;
921                 let (addr, len) = sockaddr_un(path)?;
922
923                 cvt(libc::bind(*socket.0.as_inner(), &addr as *const _ as *const _, len))?;
924
925                 Ok(socket)
926             }
927         }
928         inner(path.as_ref())
929     }
930
931     /// Creates a Unix Datagram socket which is not bound to any address.
932     ///
933     /// # Examples
934     ///
935     /// ```no_run
936     /// use std::os::unix::net::UnixDatagram;
937     ///
938     /// let sock = match UnixDatagram::unbound() {
939     ///     Ok(sock) => sock,
940     ///     Err(e) => {
941     ///         println!("Couldn't unbound: {:?}", e);
942     ///         return
943     ///     }
944     /// };
945     /// ```
946     #[stable(feature = "unix_socket", since = "1.10.0")]
947     pub fn unbound() -> io::Result<UnixDatagram> {
948         let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_DGRAM)?;
949         Ok(UnixDatagram(inner))
950     }
951
952     /// Create an unnamed pair of connected sockets.
953     ///
954     /// Returns two `UnixDatagrams`s which are connected to each other.
955     ///
956     /// # Examples
957     ///
958     /// ```no_run
959     /// use std::os::unix::net::UnixDatagram;
960     ///
961     /// let (sock1, sock2) = match UnixDatagram::pair() {
962     ///     Ok((sock1, sock2)) => (sock1, sock2),
963     ///     Err(e) => {
964     ///         println!("Couldn't unbound: {:?}", e);
965     ///         return
966     ///     }
967     /// };
968     /// ```
969     #[stable(feature = "unix_socket", since = "1.10.0")]
970     pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
971         let (i1, i2) = Socket::new_pair(libc::AF_UNIX, libc::SOCK_DGRAM)?;
972         Ok((UnixDatagram(i1), UnixDatagram(i2)))
973     }
974
975     /// Connects the socket to the specified address.
976     ///
977     /// The [`send`] method may be used to send data to the specified address.
978     /// [`recv`] and [`recv_from`] will only receive data from that address.
979     ///
980     /// [`send`]: #method.send
981     /// [`recv`]: #method.recv
982     /// [`recv_from`]: #method.recv_from
983     ///
984     /// # Examples
985     ///
986     /// ```no_run
987     /// use std::os::unix::net::UnixDatagram;
988     ///
989     /// let sock = UnixDatagram::unbound().unwrap();
990     /// match sock.connect("/path/to/the/socket") {
991     ///     Ok(sock) => sock,
992     ///     Err(e) => {
993     ///         println!("Couldn't connect: {:?}", e);
994     ///         return
995     ///     }
996     /// };
997     /// ```
998     #[stable(feature = "unix_socket", since = "1.10.0")]
999     pub fn connect<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
1000         fn inner(d: &UnixDatagram, path: &Path) -> io::Result<()> {
1001             unsafe {
1002                 let (addr, len) = sockaddr_un(path)?;
1003
1004                 cvt(libc::connect(*d.0.as_inner(), &addr as *const _ as *const _, len))?;
1005
1006                 Ok(())
1007             }
1008         }
1009         inner(self, path.as_ref())
1010     }
1011
1012     /// Creates a new independently owned handle to the underlying socket.
1013     ///
1014     /// The returned `UnixDatagram` is a reference to the same socket that this
1015     /// object references. Both handles can be used to accept incoming
1016     /// connections and options set on one side will affect the other.
1017     ///
1018     /// # Examples
1019     ///
1020     /// ```no_run
1021     /// use std::os::unix::net::UnixDatagram;
1022     ///
1023     /// let sock = UnixDatagram::bind("/path/to/the/socket").unwrap();
1024     ///
1025     /// let sock_copy = sock.try_clone().expect("try_clone failed");
1026     /// ```
1027     #[stable(feature = "unix_socket", since = "1.10.0")]
1028     pub fn try_clone(&self) -> io::Result<UnixDatagram> {
1029         self.0.duplicate().map(UnixDatagram)
1030     }
1031
1032     /// Returns the address of this socket.
1033     ///
1034     /// # Examples
1035     ///
1036     /// ```no_run
1037     /// use std::os::unix::net::UnixDatagram;
1038     ///
1039     /// let sock = UnixDatagram::bind("/path/to/the/socket").unwrap();
1040     ///
1041     /// let addr = sock.local_addr().expect("Couldn't get local address");
1042     /// ```
1043     #[stable(feature = "unix_socket", since = "1.10.0")]
1044     pub fn local_addr(&self) -> io::Result<SocketAddr> {
1045         SocketAddr::new(|addr, len| unsafe { libc::getsockname(*self.0.as_inner(), addr, len) })
1046     }
1047
1048     /// Returns the address of this socket's peer.
1049     ///
1050     /// The [`connect`] method will connect the socket to a peer.
1051     ///
1052     /// [`connect`]: #method.connect
1053     ///
1054     /// # Examples
1055     ///
1056     /// ```no_run
1057     /// use std::os::unix::net::UnixDatagram;
1058     ///
1059     /// let sock = UnixDatagram::unbound().unwrap();
1060     /// sock.connect("/path/to/the/socket").unwrap();
1061     ///
1062     /// let addr = sock.peer_addr().expect("Couldn't get peer address");
1063     /// ```
1064     #[stable(feature = "unix_socket", since = "1.10.0")]
1065     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
1066         SocketAddr::new(|addr, len| unsafe { libc::getpeername(*self.0.as_inner(), addr, len) })
1067     }
1068
1069     /// Receives data from the socket.
1070     ///
1071     /// On success, returns the number of bytes read and the address from
1072     /// whence the data came.
1073     ///
1074     /// # Examples
1075     ///
1076     /// ```no_run
1077     /// use std::os::unix::net::UnixDatagram;
1078     ///
1079     /// let sock = UnixDatagram::unbound().unwrap();
1080     /// let mut buf = vec![0; 10];
1081     /// match sock.recv_from(buf.as_mut_slice()) {
1082     ///     Ok((size, sender)) => println!("received {} bytes from {:?}", size, sender),
1083     ///     Err(e) => println!("recv_from function failed: {:?}", e),
1084     /// }
1085     /// ```
1086     #[stable(feature = "unix_socket", since = "1.10.0")]
1087     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
1088         let mut count = 0;
1089         let addr = SocketAddr::new(|addr, len| {
1090             unsafe {
1091                 count = libc::recvfrom(*self.0.as_inner(),
1092                                        buf.as_mut_ptr() as *mut _,
1093                                        buf.len(),
1094                                        0,
1095                                        addr,
1096                                        len);
1097                 if count > 0 {
1098                     1
1099                 } else if count == 0 {
1100                     0
1101                 } else {
1102                     -1
1103                 }
1104             }
1105         })?;
1106
1107         Ok((count as usize, addr))
1108     }
1109
1110     /// Receives data from the socket.
1111     ///
1112     /// On success, returns the number of bytes read.
1113     ///
1114     /// # Examples
1115     ///
1116     /// ```no_run
1117     /// use std::os::unix::net::UnixDatagram;
1118     ///
1119     /// let sock = UnixDatagram::bind("/path/to/the/socket").unwrap();
1120     /// let mut buf = vec![0; 10];
1121     /// sock.recv(buf.as_mut_slice()).expect("recv function failed");
1122     /// ```
1123     #[stable(feature = "unix_socket", since = "1.10.0")]
1124     pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
1125         self.0.read(buf)
1126     }
1127
1128     /// Sends data on the socket to the specified address.
1129     ///
1130     /// On success, returns the number of bytes written.
1131     ///
1132     /// # Examples
1133     ///
1134     /// ```no_run
1135     /// use std::os::unix::net::UnixDatagram;
1136     ///
1137     /// let sock = UnixDatagram::unbound().unwrap();
1138     /// sock.send_to(b"omelette au fromage", "/some/sock").expect("send_to function failed");
1139     /// ```
1140     #[stable(feature = "unix_socket", since = "1.10.0")]
1141     pub fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
1142         fn inner(d: &UnixDatagram, buf: &[u8], path: &Path) -> io::Result<usize> {
1143             unsafe {
1144                 let (addr, len) = sockaddr_un(path)?;
1145
1146                 let count = cvt(libc::sendto(*d.0.as_inner(),
1147                                              buf.as_ptr() as *const _,
1148                                              buf.len(),
1149                                              MSG_NOSIGNAL,
1150                                              &addr as *const _ as *const _,
1151                                              len))?;
1152                 Ok(count as usize)
1153             }
1154         }
1155         inner(self, buf, path.as_ref())
1156     }
1157
1158     /// Sends data on the socket to the socket's peer.
1159     ///
1160     /// The peer address may be set by the `connect` method, and this method
1161     /// will return an error if the socket has not already been connected.
1162     ///
1163     /// On success, returns the number of bytes written.
1164     ///
1165     /// # Examples
1166     ///
1167     /// ```no_run
1168     /// use std::os::unix::net::UnixDatagram;
1169     ///
1170     /// let sock = UnixDatagram::unbound().unwrap();
1171     /// sock.connect("/some/sock").expect("Couldn't connect");
1172     /// sock.send(b"omelette au fromage").expect("send_to function failed");
1173     /// ```
1174     #[stable(feature = "unix_socket", since = "1.10.0")]
1175     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
1176         self.0.write(buf)
1177     }
1178
1179     /// Sets the read timeout for the socket.
1180     ///
1181     /// If the provided value is [`None`], then [`recv`] and [`recv_from`] calls will
1182     /// block indefinitely. It is an error to pass the zero [`Duration`] to this
1183     /// method.
1184     ///
1185     /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
1186     /// [`recv`]: #method.recv
1187     /// [`recv_from`]: #method.recv_from
1188     /// [`Duration`]: ../../../../std/time/struct.Duration.html
1189     ///
1190     /// # Examples
1191     ///
1192     /// ```
1193     /// use std::os::unix::net::UnixDatagram;
1194     /// use std::time::Duration;
1195     ///
1196     /// let sock = UnixDatagram::unbound().unwrap();
1197     /// sock.set_read_timeout(Some(Duration::new(1, 0))).expect("set_read_timeout function failed");
1198     /// ```
1199     #[stable(feature = "unix_socket", since = "1.10.0")]
1200     pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
1201         self.0.set_timeout(timeout, libc::SO_RCVTIMEO)
1202     }
1203
1204     /// Sets the write timeout for the socket.
1205     ///
1206     /// If the provided value is [`None`], then [`send`] and [`send_to`] calls will
1207     /// block indefinitely. It is an error to pass the zero [`Duration`] to this
1208     /// method.
1209     ///
1210     /// [`None`]: ../../../../std/option/enum.Option.html#variant.None
1211     /// [`send`]: #method.send
1212     /// [`send_to`]: #method.send_to
1213     /// [`Duration`]: ../../../../std/time/struct.Duration.html
1214     ///
1215     /// # Examples
1216     ///
1217     /// ```
1218     /// use std::os::unix::net::UnixDatagram;
1219     /// use std::time::Duration;
1220     ///
1221     /// let sock = UnixDatagram::unbound().unwrap();
1222     /// sock.set_write_timeout(Some(Duration::new(1, 0)))
1223     ///     .expect("set_write_timeout function failed");
1224     /// ```
1225     #[stable(feature = "unix_socket", since = "1.10.0")]
1226     pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
1227         self.0.set_timeout(timeout, libc::SO_SNDTIMEO)
1228     }
1229
1230     /// Returns the read timeout of this socket.
1231     ///
1232     /// # Examples
1233     ///
1234     /// ```
1235     /// use std::os::unix::net::UnixDatagram;
1236     /// use std::time::Duration;
1237     ///
1238     /// let sock = UnixDatagram::unbound().unwrap();
1239     /// sock.set_read_timeout(Some(Duration::new(1, 0))).expect("set_read_timeout function failed");
1240     /// assert_eq!(sock.read_timeout().unwrap(), Some(Duration::new(1, 0)));
1241     /// ```
1242     #[stable(feature = "unix_socket", since = "1.10.0")]
1243     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
1244         self.0.timeout(libc::SO_RCVTIMEO)
1245     }
1246
1247     /// Returns the write timeout of this socket.
1248     ///
1249     /// # Examples
1250     ///
1251     /// ```
1252     /// use std::os::unix::net::UnixDatagram;
1253     /// use std::time::Duration;
1254     ///
1255     /// let sock = UnixDatagram::unbound().unwrap();
1256     /// sock.set_write_timeout(Some(Duration::new(1, 0)))
1257     ///     .expect("set_write_timeout function failed");
1258     /// assert_eq!(sock.write_timeout().unwrap(), Some(Duration::new(1, 0)));
1259     /// ```
1260     #[stable(feature = "unix_socket", since = "1.10.0")]
1261     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
1262         self.0.timeout(libc::SO_SNDTIMEO)
1263     }
1264
1265     /// Moves the socket into or out of nonblocking mode.
1266     ///
1267     /// # Examples
1268     ///
1269     /// ```
1270     /// use std::os::unix::net::UnixDatagram;
1271     ///
1272     /// let sock = UnixDatagram::unbound().unwrap();
1273     /// sock.set_nonblocking(true).expect("set_nonblocking function failed");
1274     /// ```
1275     #[stable(feature = "unix_socket", since = "1.10.0")]
1276     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
1277         self.0.set_nonblocking(nonblocking)
1278     }
1279
1280     /// Returns the value of the `SO_ERROR` option.
1281     ///
1282     /// # Examples
1283     ///
1284     /// ```no_run
1285     /// use std::os::unix::net::UnixDatagram;
1286     ///
1287     /// let sock = UnixDatagram::unbound().unwrap();
1288     /// if let Ok(Some(err)) = sock.take_error() {
1289     ///     println!("Got error: {:?}", err);
1290     /// }
1291     /// ```
1292     #[stable(feature = "unix_socket", since = "1.10.0")]
1293     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
1294         self.0.take_error()
1295     }
1296
1297     /// Shut down the read, write, or both halves of this connection.
1298     ///
1299     /// This function will cause all pending and future I/O calls on the
1300     /// specified portions to immediately return with an appropriate value
1301     /// (see the documentation of [`Shutdown`]).
1302     ///
1303     /// [`Shutdown`]: ../../../../std/net/enum.Shutdown.html
1304     ///
1305     /// ```no_run
1306     /// use std::os::unix::net::UnixDatagram;
1307     /// use std::net::Shutdown;
1308     ///
1309     /// let sock = UnixDatagram::unbound().unwrap();
1310     /// sock.shutdown(Shutdown::Both).expect("shutdown function failed");
1311     /// ```
1312     #[stable(feature = "unix_socket", since = "1.10.0")]
1313     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
1314         self.0.shutdown(how)
1315     }
1316 }
1317
1318 #[stable(feature = "unix_socket", since = "1.10.0")]
1319 impl AsRawFd for UnixDatagram {
1320     fn as_raw_fd(&self) -> RawFd {
1321         *self.0.as_inner()
1322     }
1323 }
1324
1325 #[stable(feature = "unix_socket", since = "1.10.0")]
1326 impl FromRawFd for UnixDatagram {
1327     unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram {
1328         UnixDatagram(Socket::from_inner(fd))
1329     }
1330 }
1331
1332 #[stable(feature = "unix_socket", since = "1.10.0")]
1333 impl IntoRawFd for UnixDatagram {
1334     fn into_raw_fd(self) -> RawFd {
1335         self.0.into_inner()
1336     }
1337 }
1338
1339 #[cfg(all(test, not(target_os = "emscripten")))]
1340 mod test {
1341     use thread;
1342     use io;
1343     use io::prelude::*;
1344     use time::Duration;
1345     use sys_common::io::test::tmpdir;
1346
1347     use super::*;
1348
1349     macro_rules! or_panic {
1350         ($e:expr) => {
1351             match $e {
1352                 Ok(e) => e,
1353                 Err(e) => panic!("{}", e),
1354             }
1355         }
1356     }
1357
1358     #[test]
1359     fn basic() {
1360         let dir = tmpdir();
1361         let socket_path = dir.path().join("sock");
1362         let msg1 = b"hello";
1363         let msg2 = b"world!";
1364
1365         let listener = or_panic!(UnixListener::bind(&socket_path));
1366         let thread = thread::spawn(move || {
1367             let mut stream = or_panic!(listener.accept()).0;
1368             let mut buf = [0; 5];
1369             or_panic!(stream.read(&mut buf));
1370             assert_eq!(&msg1[..], &buf[..]);
1371             or_panic!(stream.write_all(msg2));
1372         });
1373
1374         let mut stream = or_panic!(UnixStream::connect(&socket_path));
1375         assert_eq!(Some(&*socket_path),
1376                    stream.peer_addr().unwrap().as_pathname());
1377         or_panic!(stream.write_all(msg1));
1378         let mut buf = vec![];
1379         or_panic!(stream.read_to_end(&mut buf));
1380         assert_eq!(&msg2[..], &buf[..]);
1381         drop(stream);
1382
1383         thread.join().unwrap();
1384     }
1385
1386     #[test]
1387     fn pair() {
1388         let msg1 = b"hello";
1389         let msg2 = b"world!";
1390
1391         let (mut s1, mut s2) = or_panic!(UnixStream::pair());
1392         let thread = thread::spawn(move || {
1393             // s1 must be moved in or the test will hang!
1394             let mut buf = [0; 5];
1395             or_panic!(s1.read(&mut buf));
1396             assert_eq!(&msg1[..], &buf[..]);
1397             or_panic!(s1.write_all(msg2));
1398         });
1399
1400         or_panic!(s2.write_all(msg1));
1401         let mut buf = vec![];
1402         or_panic!(s2.read_to_end(&mut buf));
1403         assert_eq!(&msg2[..], &buf[..]);
1404         drop(s2);
1405
1406         thread.join().unwrap();
1407     }
1408
1409     #[test]
1410     fn try_clone() {
1411         let dir = tmpdir();
1412         let socket_path = dir.path().join("sock");
1413         let msg1 = b"hello";
1414         let msg2 = b"world";
1415
1416         let listener = or_panic!(UnixListener::bind(&socket_path));
1417         let thread = thread::spawn(move || {
1418             let mut stream = or_panic!(listener.accept()).0;
1419             or_panic!(stream.write_all(msg1));
1420             or_panic!(stream.write_all(msg2));
1421         });
1422
1423         let mut stream = or_panic!(UnixStream::connect(&socket_path));
1424         let mut stream2 = or_panic!(stream.try_clone());
1425
1426         let mut buf = [0; 5];
1427         or_panic!(stream.read(&mut buf));
1428         assert_eq!(&msg1[..], &buf[..]);
1429         or_panic!(stream2.read(&mut buf));
1430         assert_eq!(&msg2[..], &buf[..]);
1431
1432         thread.join().unwrap();
1433     }
1434
1435     #[test]
1436     fn iter() {
1437         let dir = tmpdir();
1438         let socket_path = dir.path().join("sock");
1439
1440         let listener = or_panic!(UnixListener::bind(&socket_path));
1441         let thread = thread::spawn(move || {
1442             for stream in listener.incoming().take(2) {
1443                 let mut stream = or_panic!(stream);
1444                 let mut buf = [0];
1445                 or_panic!(stream.read(&mut buf));
1446             }
1447         });
1448
1449         for _ in 0..2 {
1450             let mut stream = or_panic!(UnixStream::connect(&socket_path));
1451             or_panic!(stream.write_all(&[0]));
1452         }
1453
1454         thread.join().unwrap();
1455     }
1456
1457     #[test]
1458     fn long_path() {
1459         let dir = tmpdir();
1460         let socket_path = dir.path()
1461                              .join("asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfa\
1462                                     sasdfasdfasdasdfasdfasdfadfasdfasdfasdfasdfasdf");
1463         match UnixStream::connect(&socket_path) {
1464             Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1465             Err(e) => panic!("unexpected error {}", e),
1466             Ok(_) => panic!("unexpected success"),
1467         }
1468
1469         match UnixListener::bind(&socket_path) {
1470             Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1471             Err(e) => panic!("unexpected error {}", e),
1472             Ok(_) => panic!("unexpected success"),
1473         }
1474
1475         match UnixDatagram::bind(&socket_path) {
1476             Err(ref e) if e.kind() == io::ErrorKind::InvalidInput => {}
1477             Err(e) => panic!("unexpected error {}", e),
1478             Ok(_) => panic!("unexpected success"),
1479         }
1480     }
1481
1482     #[test]
1483     fn timeouts() {
1484         let dir = tmpdir();
1485         let socket_path = dir.path().join("sock");
1486
1487         let _listener = or_panic!(UnixListener::bind(&socket_path));
1488
1489         let stream = or_panic!(UnixStream::connect(&socket_path));
1490         let dur = Duration::new(15410, 0);
1491
1492         assert_eq!(None, or_panic!(stream.read_timeout()));
1493
1494         or_panic!(stream.set_read_timeout(Some(dur)));
1495         assert_eq!(Some(dur), or_panic!(stream.read_timeout()));
1496
1497         assert_eq!(None, or_panic!(stream.write_timeout()));
1498
1499         or_panic!(stream.set_write_timeout(Some(dur)));
1500         assert_eq!(Some(dur), or_panic!(stream.write_timeout()));
1501
1502         or_panic!(stream.set_read_timeout(None));
1503         assert_eq!(None, or_panic!(stream.read_timeout()));
1504
1505         or_panic!(stream.set_write_timeout(None));
1506         assert_eq!(None, or_panic!(stream.write_timeout()));
1507     }
1508
1509     #[test]
1510     fn test_read_timeout() {
1511         let dir = tmpdir();
1512         let socket_path = dir.path().join("sock");
1513
1514         let _listener = or_panic!(UnixListener::bind(&socket_path));
1515
1516         let mut stream = or_panic!(UnixStream::connect(&socket_path));
1517         or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1518
1519         let mut buf = [0; 10];
1520         let kind = stream.read(&mut buf).err().expect("expected error").kind();
1521         assert!(kind == io::ErrorKind::WouldBlock || kind == io::ErrorKind::TimedOut);
1522     }
1523
1524     #[test]
1525     fn test_read_with_timeout() {
1526         let dir = tmpdir();
1527         let socket_path = dir.path().join("sock");
1528
1529         let listener = or_panic!(UnixListener::bind(&socket_path));
1530
1531         let mut stream = or_panic!(UnixStream::connect(&socket_path));
1532         or_panic!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1533
1534         let mut other_end = or_panic!(listener.accept()).0;
1535         or_panic!(other_end.write_all(b"hello world"));
1536
1537         let mut buf = [0; 11];
1538         or_panic!(stream.read(&mut buf));
1539         assert_eq!(b"hello world", &buf[..]);
1540
1541         let kind = stream.read(&mut buf).err().expect("expected error").kind();
1542         assert!(kind == io::ErrorKind::WouldBlock || kind == io::ErrorKind::TimedOut);
1543     }
1544
1545     #[test]
1546     fn test_unix_datagram() {
1547         let dir = tmpdir();
1548         let path1 = dir.path().join("sock1");
1549         let path2 = dir.path().join("sock2");
1550
1551         let sock1 = or_panic!(UnixDatagram::bind(&path1));
1552         let sock2 = or_panic!(UnixDatagram::bind(&path2));
1553
1554         let msg = b"hello world";
1555         or_panic!(sock1.send_to(msg, &path2));
1556         let mut buf = [0; 11];
1557         or_panic!(sock2.recv_from(&mut buf));
1558         assert_eq!(msg, &buf[..]);
1559     }
1560
1561     #[test]
1562     fn test_unnamed_unix_datagram() {
1563         let dir = tmpdir();
1564         let path1 = dir.path().join("sock1");
1565
1566         let sock1 = or_panic!(UnixDatagram::bind(&path1));
1567         let sock2 = or_panic!(UnixDatagram::unbound());
1568
1569         let msg = b"hello world";
1570         or_panic!(sock2.send_to(msg, &path1));
1571         let mut buf = [0; 11];
1572         let (usize, addr) = or_panic!(sock1.recv_from(&mut buf));
1573         assert_eq!(usize, 11);
1574         assert!(addr.is_unnamed());
1575         assert_eq!(msg, &buf[..]);
1576     }
1577
1578     #[test]
1579     fn test_connect_unix_datagram() {
1580         let dir = tmpdir();
1581         let path1 = dir.path().join("sock1");
1582         let path2 = dir.path().join("sock2");
1583
1584         let bsock1 = or_panic!(UnixDatagram::bind(&path1));
1585         let bsock2 = or_panic!(UnixDatagram::bind(&path2));
1586         let sock = or_panic!(UnixDatagram::unbound());
1587         or_panic!(sock.connect(&path1));
1588
1589         // Check send()
1590         let msg = b"hello there";
1591         or_panic!(sock.send(msg));
1592         let mut buf = [0; 11];
1593         let (usize, addr) = or_panic!(bsock1.recv_from(&mut buf));
1594         assert_eq!(usize, 11);
1595         assert!(addr.is_unnamed());
1596         assert_eq!(msg, &buf[..]);
1597
1598         // Changing default socket works too
1599         or_panic!(sock.connect(&path2));
1600         or_panic!(sock.send(msg));
1601         or_panic!(bsock2.recv_from(&mut buf));
1602     }
1603
1604     #[test]
1605     fn test_unix_datagram_recv() {
1606         let dir = tmpdir();
1607         let path1 = dir.path().join("sock1");
1608
1609         let sock1 = or_panic!(UnixDatagram::bind(&path1));
1610         let sock2 = or_panic!(UnixDatagram::unbound());
1611         or_panic!(sock2.connect(&path1));
1612
1613         let msg = b"hello world";
1614         or_panic!(sock2.send(msg));
1615         let mut buf = [0; 11];
1616         let size = or_panic!(sock1.recv(&mut buf));
1617         assert_eq!(size, 11);
1618         assert_eq!(msg, &buf[..]);
1619     }
1620
1621     #[test]
1622     fn datagram_pair() {
1623         let msg1 = b"hello";
1624         let msg2 = b"world!";
1625
1626         let (s1, s2) = or_panic!(UnixDatagram::pair());
1627         let thread = thread::spawn(move || {
1628             // s1 must be moved in or the test will hang!
1629             let mut buf = [0; 5];
1630             or_panic!(s1.recv(&mut buf));
1631             assert_eq!(&msg1[..], &buf[..]);
1632             or_panic!(s1.send(msg2));
1633         });
1634
1635         or_panic!(s2.send(msg1));
1636         let mut buf = [0; 6];
1637         or_panic!(s2.recv(&mut buf));
1638         assert_eq!(&msg2[..], &buf[..]);
1639         drop(s2);
1640
1641         thread.join().unwrap();
1642     }
1643
1644     #[test]
1645     fn abstract_namespace_not_allowed() {
1646         assert!(UnixStream::connect("\0asdf").is_err());
1647     }
1648 }