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