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