about summary refs log tree commit diff
path: root/src/libstd/sys_common/net.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/libstd/sys_common/net.rs')
-rw-r--r--src/libstd/sys_common/net.rs256
1 files changed, 143 insertions, 113 deletions
diff --git a/src/libstd/sys_common/net.rs b/src/libstd/sys_common/net.rs
index 391f670346f..9d40d9f0afd 100644
--- a/src/libstd/sys_common/net.rs
+++ b/src/libstd/sys_common/net.rs
@@ -1,79 +1,119 @@
 use crate::cmp;
+use crate::convert::{TryFrom, TryInto};
 use crate::ffi::CString;
 use crate::fmt;
 use crate::io::{self, Error, ErrorKind, IoSlice, IoSliceMut};
 use crate::mem;
-use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr};
+use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
 use crate::ptr;
-use crate::sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t};
 use crate::sys::net::netc as c;
+use crate::sys::net::{cvt, cvt_gai, cvt_r, init, wrlen_t, Socket};
 use crate::sys_common::{AsInner, FromInner, IntoInner};
 use crate::time::Duration;
-use crate::convert::{TryFrom, TryInto};
 
 use libc::{c_int, c_void};
 
-#[cfg(any(target_os = "dragonfly", target_os = "freebsd",
-          target_os = "ios", target_os = "macos",
-          target_os = "openbsd", target_os = "netbsd",
-          target_os = "solaris", target_os = "haiku", target_os = "l4re"))]
-use crate::sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP;
-#[cfg(not(any(target_os = "dragonfly", target_os = "freebsd",
-              target_os = "ios", target_os = "macos",
-              target_os = "openbsd", target_os = "netbsd",
-              target_os = "solaris", target_os = "haiku", target_os = "l4re")))]
+#[cfg(not(any(
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "ios",
+    target_os = "macos",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "solaris",
+    target_os = "haiku",
+    target_os = "l4re"
+)))]
 use crate::sys::net::netc::IPV6_ADD_MEMBERSHIP;
-#[cfg(any(target_os = "dragonfly", target_os = "freebsd",
-          target_os = "ios", target_os = "macos",
-          target_os = "openbsd", target_os = "netbsd",
-          target_os = "solaris", target_os = "haiku", target_os = "l4re"))]
-use crate::sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP;
-#[cfg(not(any(target_os = "dragonfly", target_os = "freebsd",
-              target_os = "ios", target_os = "macos",
-              target_os = "openbsd", target_os = "netbsd",
-              target_os = "solaris", target_os = "haiku", target_os = "l4re")))]
+#[cfg(not(any(
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "ios",
+    target_os = "macos",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "solaris",
+    target_os = "haiku",
+    target_os = "l4re"
+)))]
 use crate::sys::net::netc::IPV6_DROP_MEMBERSHIP;
+#[cfg(any(
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "ios",
+    target_os = "macos",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "solaris",
+    target_os = "haiku",
+    target_os = "l4re"
+))]
+use crate::sys::net::netc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP;
+#[cfg(any(
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "ios",
+    target_os = "macos",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "solaris",
+    target_os = "haiku",
+    target_os = "l4re"
+))]
+use crate::sys::net::netc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP;
 
-#[cfg(any(target_os = "linux", target_os = "android",
-          target_os = "dragonfly", target_os = "freebsd",
-          target_os = "openbsd", target_os = "netbsd",
-          target_os = "haiku"))]
+#[cfg(any(
+    target_os = "linux",
+    target_os = "android",
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "haiku"
+))]
 use libc::MSG_NOSIGNAL;
-#[cfg(not(any(target_os = "linux", target_os = "android",
-              target_os = "dragonfly", target_os = "freebsd",
-              target_os = "openbsd", target_os = "netbsd",
-              target_os = "haiku")))]
+#[cfg(not(any(
+    target_os = "linux",
+    target_os = "android",
+    target_os = "dragonfly",
+    target_os = "freebsd",
+    target_os = "openbsd",
+    target_os = "netbsd",
+    target_os = "haiku"
+)))]
 const MSG_NOSIGNAL: c_int = 0x0;
 
 ////////////////////////////////////////////////////////////////////////////////
 // sockaddr and misc bindings
 ////////////////////////////////////////////////////////////////////////////////
 
-pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int,
-                     payload: T) -> io::Result<()> {
+pub fn setsockopt<T>(sock: &Socket, opt: c_int, val: c_int, payload: T) -> io::Result<()> {
     unsafe {
         let payload = &payload as *const T as *const c_void;
-        cvt(c::setsockopt(*sock.as_inner(), opt, val, payload,
-                          mem::size_of::<T>() as c::socklen_t))?;
+        cvt(c::setsockopt(
+            *sock.as_inner(),
+            opt,
+            val,
+            payload,
+            mem::size_of::<T>() as c::socklen_t,
+        ))?;
         Ok(())
     }
 }
 
-pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int,
-                       val: c_int) -> io::Result<T> {
+pub fn getsockopt<T: Copy>(sock: &Socket, opt: c_int, val: c_int) -> io::Result<T> {
     unsafe {
         let mut slot: T = mem::zeroed();
         let mut len = mem::size_of::<T>() as c::socklen_t;
-        cvt(c::getsockopt(*sock.as_inner(), opt, val,
-                          &mut slot as *mut _ as *mut _,
-                          &mut len))?;
+        cvt(c::getsockopt(*sock.as_inner(), opt, val, &mut slot as *mut _ as *mut _, &mut len))?;
         assert_eq!(len as usize, mem::size_of::<T>());
         Ok(slot)
     }
 }
 
 fn sockname<F>(f: F) -> io::Result<SocketAddr>
-    where F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int
+where
+    F: FnOnce(*mut c::sockaddr, *mut c::socklen_t) -> c_int,
 {
     unsafe {
         let mut storage: c::sockaddr_storage = mem::zeroed();
@@ -83,8 +123,7 @@ fn sockname<F>(f: F) -> io::Result<SocketAddr>
     }
 }
 
-pub fn sockaddr_to_addr(storage: &c::sockaddr_storage,
-                    len: usize) -> io::Result<SocketAddr> {
+pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, len: usize) -> io::Result<SocketAddr> {
     match storage.ss_family as c_int {
         c::AF_INET => {
             assert!(len as usize >= mem::size_of::<c::sockaddr_in>());
@@ -98,9 +137,7 @@ pub fn sockaddr_to_addr(storage: &c::sockaddr_storage,
                 *(storage as *const _ as *const c::sockaddr_in6)
             })))
         }
-        _ => {
-            Err(Error::new(ErrorKind::InvalidInput, "invalid argument"))
-        }
+        _ => Err(Error::new(ErrorKind::InvalidInput, "invalid argument")),
     }
 }
 
@@ -121,7 +158,7 @@ fn to_ipv6mr_interface(value: u32) -> libc::c_uint {
 pub struct LookupHost {
     original: *mut c::addrinfo,
     cur: *mut c::addrinfo,
-    port: u16
+    port: u16,
 }
 
 impl LookupHost {
@@ -137,9 +174,7 @@ impl Iterator for LookupHost {
             unsafe {
                 let cur = self.cur.as_ref()?;
                 self.cur = cur.ai_next;
-                match sockaddr_to_addr(mem::transmute(cur.ai_addr),
-                                       cur.ai_addrlen as usize)
-                {
+                match sockaddr_to_addr(mem::transmute(cur.ai_addr), cur.ai_addrlen as usize) {
                     Ok(addr) => return Some(addr),
                     Err(_) => continue,
                 }
@@ -162,13 +197,12 @@ impl TryFrom<&str> for LookupHost {
 
     fn try_from(s: &str) -> io::Result<LookupHost> {
         macro_rules! try_opt {
-            ($e:expr, $msg:expr) => (
+            ($e:expr, $msg:expr) => {
                 match $e {
                     Some(r) => r,
-                    None => return Err(io::Error::new(io::ErrorKind::InvalidInput,
-                                                      $msg)),
+                    None => return Err(io::Error::new(io::ErrorKind::InvalidInput, $msg)),
                 }
-            )
+            };
         }
 
         // split the string by ':' and convert the second part to u16
@@ -192,9 +226,8 @@ impl<'a> TryFrom<(&'a str, u16)> for LookupHost {
         hints.ai_socktype = c::SOCK_STREAM;
         let mut res = ptr::null_mut();
         unsafe {
-            cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)).map(|_| {
-                LookupHost { original: res, cur: res, port }
-            })
+            cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res))
+                .map(|_| LookupHost { original: res, cur: res, port })
         }
     }
 }
@@ -228,9 +261,13 @@ impl TcpStream {
         Ok(TcpStream { inner: sock })
     }
 
-    pub fn socket(&self) -> &Socket { &self.inner }
+    pub fn socket(&self) -> &Socket {
+        &self.inner
+    }
 
-    pub fn into_socket(self) -> Socket { self.inner }
+    pub fn into_socket(self) -> Socket {
+        self.inner
+    }
 
     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
         self.inner.set_timeout(dur, c::SO_RCVTIMEO)
@@ -263,10 +300,7 @@ impl TcpStream {
     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
         let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
         let ret = cvt(unsafe {
-            c::send(*self.inner.as_inner(),
-                    buf.as_ptr() as *const c_void,
-                    len,
-                    MSG_NOSIGNAL)
+            c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL)
         })?;
         Ok(ret as usize)
     }
@@ -276,15 +310,11 @@ impl TcpStream {
     }
 
     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getpeername(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getpeername(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getsockname(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
@@ -339,9 +369,8 @@ impl fmt::Debug for TcpStream {
             res.field("peer", &peer);
         }
 
-        let name = if cfg!(windows) {"socket"} else {"fd"};
-        res.field(name, &self.inner.as_inner())
-            .finish()
+        let name = if cfg!(windows) { "socket" } else { "fd" };
+        res.field(name, &self.inner.as_inner()).finish()
     }
 }
 
@@ -365,8 +394,7 @@ impl TcpListener {
         // to quickly rebind a socket, without needing to wait for
         // the OS to clean up the previous one.
         if !cfg!(windows) {
-            setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR,
-                       1 as c_int)?;
+            setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, 1 as c_int)?;
         }
 
         // Bind our new socket
@@ -378,23 +406,24 @@ impl TcpListener {
         Ok(TcpListener { inner: sock })
     }
 
-    pub fn socket(&self) -> &Socket { &self.inner }
+    pub fn socket(&self) -> &Socket {
+        &self.inner
+    }
 
-    pub fn into_socket(self) -> Socket { self.inner }
+    pub fn into_socket(self) -> Socket {
+        self.inner
+    }
 
     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getsockname(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
         let mut storage: c::sockaddr_storage = unsafe { mem::zeroed() };
         let mut len = mem::size_of_val(&storage) as c::socklen_t;
-        let sock = self.inner.accept(&mut storage as *mut _ as *mut _,
-                                     &mut len)?;
+        let sock = self.inner.accept(&mut storage as *mut _ as *mut _, &mut len)?;
         let addr = sockaddr_to_addr(&storage, len as usize)?;
-        Ok((TcpStream { inner: sock, }, addr))
+        Ok((TcpStream { inner: sock }, addr))
     }
 
     pub fn duplicate(&self) -> io::Result<TcpListener> {
@@ -442,9 +471,8 @@ impl fmt::Debug for TcpListener {
             res.field("addr", &addr);
         }
 
-        let name = if cfg!(windows) {"socket"} else {"fd"};
-        res.field(name, &self.inner.as_inner())
-            .finish()
+        let name = if cfg!(windows) { "socket" } else { "fd" };
+        res.field(name, &self.inner.as_inner()).finish()
     }
 }
 
@@ -468,20 +496,20 @@ impl UdpSocket {
         Ok(UdpSocket { inner: sock })
     }
 
-    pub fn socket(&self) -> &Socket { &self.inner }
+    pub fn socket(&self) -> &Socket {
+        &self.inner
+    }
 
-    pub fn into_socket(self) -> Socket { self.inner }
+    pub fn into_socket(self) -> Socket {
+        self.inner
+    }
 
     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getpeername(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getpeername(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
-        sockname(|buf, len| unsafe {
-            c::getsockname(*self.inner.as_inner(), buf, len)
-        })
+        sockname(|buf, len| unsafe { c::getsockname(*self.inner.as_inner(), buf, len) })
     }
 
     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
@@ -496,9 +524,14 @@ impl UdpSocket {
         let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
         let (dstp, dstlen) = dst.into_inner();
         let ret = cvt(unsafe {
-            c::sendto(*self.inner.as_inner(),
-                      buf.as_ptr() as *const c_void, len,
-                      MSG_NOSIGNAL, dstp, dstlen)
+            c::sendto(
+                *self.inner.as_inner(),
+                buf.as_ptr() as *const c_void,
+                len,
+                MSG_NOSIGNAL,
+                dstp,
+                dstlen,
+            )
         })?;
         Ok(ret as usize)
     }
@@ -559,8 +592,7 @@ impl UdpSocket {
         Ok(raw != 0)
     }
 
-    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
-                         -> io::Result<()> {
+    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
         let mreq = c::ip_mreq {
             imr_multiaddr: *multiaddr.as_inner(),
             imr_interface: *interface.as_inner(),
@@ -568,8 +600,7 @@ impl UdpSocket {
         setsockopt(&self.inner, c::IPPROTO_IP, c::IP_ADD_MEMBERSHIP, mreq)
     }
 
-    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
-                         -> io::Result<()> {
+    pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
         let mreq = c::ipv6_mreq {
             ipv6mr_multiaddr: *multiaddr.as_inner(),
             ipv6mr_interface: to_ipv6mr_interface(interface),
@@ -577,8 +608,7 @@ impl UdpSocket {
         setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq)
     }
 
-    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
         let mreq = c::ip_mreq {
             imr_multiaddr: *multiaddr.as_inner(),
             imr_interface: *interface.as_inner(),
@@ -586,8 +616,7 @@ impl UdpSocket {
         setsockopt(&self.inner, c::IPPROTO_IP, c::IP_DROP_MEMBERSHIP, mreq)
     }
 
-    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32)
-                          -> io::Result<()> {
+    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
         let mreq = c::ipv6_mreq {
             ipv6mr_multiaddr: *multiaddr.as_inner(),
             ipv6mr_interface: to_ipv6mr_interface(interface),
@@ -623,10 +652,7 @@ impl UdpSocket {
     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
         let len = cmp::min(buf.len(), <wrlen_t>::max_value() as usize) as wrlen_t;
         let ret = cvt(unsafe {
-            c::send(*self.inner.as_inner(),
-                    buf.as_ptr() as *const c_void,
-                    len,
-                    MSG_NOSIGNAL)
+            c::send(*self.inner.as_inner(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL)
         })?;
         Ok(ret as usize)
     }
@@ -651,9 +677,8 @@ impl fmt::Debug for UdpSocket {
             res.field("addr", &addr);
         }
 
-        let name = if cfg!(windows) {"socket"} else {"fd"};
-        res.field(name, &self.inner.as_inner())
-            .finish()
+        let name = if cfg!(windows) { "socket" } else { "fd" };
+        res.field(name, &self.inner.as_inner()).finish()
     }
 }
 
@@ -667,10 +692,15 @@ mod tests {
         let mut addrs = HashMap::new();
         let lh = match LookupHost::try_from(("localhost", 0)) {
             Ok(lh) => lh,
-            Err(e) => panic!("couldn't resolve `localhost': {}", e)
+            Err(e) => panic!("couldn't resolve `localhost': {}", e),
         };
-        for sa in lh { *addrs.entry(sa).or_insert(0) += 1; };
-        assert_eq!(addrs.iter().filter(|&(_, &v)| v > 1).collect::<Vec<_>>(), vec![],
-                   "There should be no duplicate localhost entries");
+        for sa in lh {
+            *addrs.entry(sa).or_insert(0) += 1;
+        }
+        assert_eq!(
+            addrs.iter().filter(|&(_, &v)| v > 1).collect::<Vec<_>>(),
+            vec![],
+            "There should be no duplicate localhost entries"
+        );
     }
 }