1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 
11 use std::fmt;
12 use std::io::{self, Read, Write};
13 use std::net::{self, Ipv4Addr, Ipv6Addr, Shutdown};
14 #[cfg(all(unix, feature = "unix"))]
15 use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
16 use std::time::Duration;
17 
18 #[cfg(any(unix, target_os = "redox"))]
19 use libc::MSG_OOB;
20 #[cfg(windows)]
21 use winapi::um::winsock2::MSG_OOB;
22 
23 use crate::sys;
24 use crate::{Domain, Protocol, SockAddr, Type};
25 
26 /// Newtype, owned, wrapper around a system socket.
27 ///
28 /// This type simply wraps an instance of a file descriptor (`c_int`) on Unix
29 /// and an instance of `SOCKET` on Windows. This is the main type exported by
30 /// this crate and is intended to mirror the raw semantics of sockets on
31 /// platforms as closely as possible. Almost all methods correspond to
32 /// precisely one libc or OS API call which is essentially just a "Rustic
33 /// translation" of what's below.
34 ///
35 /// # Examples
36 ///
37 /// ```no_run
38 /// use std::net::SocketAddr;
39 /// use socket2::{Socket, Domain, Type, SockAddr};
40 ///
41 /// // create a TCP listener bound to two addresses
42 /// let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
43 ///
44 /// socket.bind(&"127.0.0.1:12345".parse::<SocketAddr>().unwrap().into()).unwrap();
45 /// socket.bind(&"127.0.0.1:12346".parse::<SocketAddr>().unwrap().into()).unwrap();
46 /// socket.listen(128).unwrap();
47 ///
48 /// let listener = socket.into_tcp_listener();
49 /// // ...
50 /// ```
51 pub struct Socket {
52     // The `sys` module most have access to the socket.
53     pub(crate) inner: sys::Socket,
54 }
55 
56 impl Socket {
57     /// Creates a new socket ready to be configured.
58     ///
59     /// This function corresponds to `socket(2)` and simply creates a new
60     /// socket, no other configuration is done and further functions must be
61     /// invoked to configure this socket.
new(domain: Domain, type_: Type, protocol: Option<Protocol>) -> io::Result<Socket>62     pub fn new(domain: Domain, type_: Type, protocol: Option<Protocol>) -> io::Result<Socket> {
63         let protocol = protocol.map(|p| p.0).unwrap_or(0);
64         Ok(Socket {
65             inner: sys::Socket::new(domain.0, type_.0, protocol)?,
66         })
67     }
68 
69     /// Creates a pair of sockets which are connected to each other.
70     ///
71     /// This function corresponds to `socketpair(2)`.
72     ///
73     /// This function is only available on Unix when the `pair` feature is
74     /// enabled.
75     #[cfg(all(unix, feature = "pair"))]
pair( domain: Domain, type_: Type, protocol: Option<Protocol>, ) -> io::Result<(Socket, Socket)>76     pub fn pair(
77         domain: Domain,
78         type_: Type,
79         protocol: Option<Protocol>,
80     ) -> io::Result<(Socket, Socket)> {
81         let protocol = protocol.map(|p| p.0).unwrap_or(0);
82         let sockets = sys::Socket::pair(domain.0, type_.0, protocol)?;
83         Ok((Socket { inner: sockets.0 }, Socket { inner: sockets.1 }))
84     }
85 
86     /// Consumes this `Socket`, converting it to a `TcpStream`.
into_tcp_stream(self) -> net::TcpStream87     pub fn into_tcp_stream(self) -> net::TcpStream {
88         self.into()
89     }
90 
91     /// Consumes this `Socket`, converting it to a `TcpListener`.
into_tcp_listener(self) -> net::TcpListener92     pub fn into_tcp_listener(self) -> net::TcpListener {
93         self.into()
94     }
95 
96     /// Consumes this `Socket`, converting it to a `UdpSocket`.
into_udp_socket(self) -> net::UdpSocket97     pub fn into_udp_socket(self) -> net::UdpSocket {
98         self.into()
99     }
100 
101     /// Consumes this `Socket`, converting it into a `UnixStream`.
102     ///
103     /// This function is only available on Unix when the `unix` feature is
104     /// enabled.
105     #[cfg(all(unix, feature = "unix"))]
into_unix_stream(self) -> UnixStream106     pub fn into_unix_stream(self) -> UnixStream {
107         self.into()
108     }
109 
110     /// Consumes this `Socket`, converting it into a `UnixListener`.
111     ///
112     /// This function is only available on Unix when the `unix` feature is
113     /// enabled.
114     #[cfg(all(unix, feature = "unix"))]
into_unix_listener(self) -> UnixListener115     pub fn into_unix_listener(self) -> UnixListener {
116         self.into()
117     }
118 
119     /// Consumes this `Socket`, converting it into a `UnixDatagram`.
120     ///
121     /// This function is only available on Unix when the `unix` feature is
122     /// enabled.
123     #[cfg(all(unix, feature = "unix"))]
into_unix_datagram(self) -> UnixDatagram124     pub fn into_unix_datagram(self) -> UnixDatagram {
125         self.into()
126     }
127 
128     /// Initiate a connection on this socket to the specified address.
129     ///
130     /// This function directly corresponds to the connect(2) function on Windows
131     /// and Unix.
132     ///
133     /// An error will be returned if `listen` or `connect` has already been
134     /// called on this builder.
connect(&self, addr: &SockAddr) -> io::Result<()>135     pub fn connect(&self, addr: &SockAddr) -> io::Result<()> {
136         self.inner.connect(addr)
137     }
138 
139     /// Initiate a connection on this socket to the specified address, only
140     /// only waiting for a certain period of time for the connection to be
141     /// established.
142     ///
143     /// Unlike many other methods on `Socket`, this does *not* correspond to a
144     /// single C function. It sets the socket to nonblocking mode, connects via
145     /// connect(2), and then waits for the connection to complete with poll(2)
146     /// on Unix and select on Windows. When the connection is complete, the
147     /// socket is set back to blocking mode. On Unix, this will loop over
148     /// `EINTR` errors.
149     ///
150     /// # Warnings
151     ///
152     /// The nonblocking state of the socket is overridden by this function -
153     /// it will be returned in blocking mode on success, and in an indeterminate
154     /// state on failure.
155     ///
156     /// If the connection request times out, it may still be processing in the
157     /// background - a second call to `connect` or `connect_timeout` may fail.
connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()>158     pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> {
159         self.inner.connect_timeout(addr, timeout)
160     }
161 
162     /// Binds this socket to the specified address.
163     ///
164     /// This function directly corresponds to the bind(2) function on Windows
165     /// and Unix.
bind(&self, addr: &SockAddr) -> io::Result<()>166     pub fn bind(&self, addr: &SockAddr) -> io::Result<()> {
167         self.inner.bind(addr)
168     }
169 
170     /// Mark a socket as ready to accept incoming connection requests using
171     /// accept()
172     ///
173     /// This function directly corresponds to the listen(2) function on Windows
174     /// and Unix.
175     ///
176     /// An error will be returned if `listen` or `connect` has already been
177     /// called on this builder.
listen(&self, backlog: i32) -> io::Result<()>178     pub fn listen(&self, backlog: i32) -> io::Result<()> {
179         self.inner.listen(backlog)
180     }
181 
182     /// Accept a new incoming connection from this listener.
183     ///
184     /// This function will block the calling thread until a new connection is
185     /// established. When established, the corresponding `Socket` and the
186     /// remote peer's address will be returned.
accept(&self) -> io::Result<(Socket, SockAddr)>187     pub fn accept(&self) -> io::Result<(Socket, SockAddr)> {
188         self.inner
189             .accept()
190             .map(|(socket, addr)| (Socket { inner: socket }, addr))
191     }
192 
193     /// Returns the socket address of the local half of this TCP connection.
local_addr(&self) -> io::Result<SockAddr>194     pub fn local_addr(&self) -> io::Result<SockAddr> {
195         self.inner.local_addr()
196     }
197 
198     /// Returns the socket address of the remote peer of this TCP connection.
peer_addr(&self) -> io::Result<SockAddr>199     pub fn peer_addr(&self) -> io::Result<SockAddr> {
200         self.inner.peer_addr()
201     }
202 
203     /// Creates a new independently owned handle to the underlying socket.
204     ///
205     /// The returned `TcpStream` is a reference to the same stream that this
206     /// object references. Both handles will read and write the same stream of
207     /// data, and options set on one stream will be propagated to the other
208     /// stream.
try_clone(&self) -> io::Result<Socket>209     pub fn try_clone(&self) -> io::Result<Socket> {
210         self.inner.try_clone().map(|s| Socket { inner: s })
211     }
212 
213     /// Get the value of the `SO_ERROR` option on this socket.
214     ///
215     /// This will retrieve the stored error in the underlying socket, clearing
216     /// the field in the process. This can be useful for checking errors between
217     /// calls.
take_error(&self) -> io::Result<Option<io::Error>>218     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
219         self.inner.take_error()
220     }
221 
222     /// Moves this TCP stream into or out of nonblocking mode.
223     ///
224     /// On Unix this corresponds to calling fcntl, and on Windows this
225     /// corresponds to calling ioctlsocket.
set_nonblocking(&self, nonblocking: bool) -> io::Result<()>226     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
227         self.inner.set_nonblocking(nonblocking)
228     }
229 
230     /// Shuts down the read, write, or both halves of this connection.
231     ///
232     /// This function will cause all pending and future I/O on the specified
233     /// portions to return immediately with an appropriate value.
shutdown(&self, how: Shutdown) -> io::Result<()>234     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
235         self.inner.shutdown(how)
236     }
237 
238     /// Receives data on the socket from the remote address to which it is
239     /// connected.
240     ///
241     /// The [`connect`] method will connect this socket to a remote address. This
242     /// method will fail if the socket is not connected.
243     ///
244     /// [`connect`]: #method.connect
recv(&self, buf: &mut [u8]) -> io::Result<usize>245     pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
246         self.inner.recv(buf, 0)
247     }
248 
249     /// Identical to [`recv`] but allows for specification of arbitrary flags to the underlying
250     /// `recv` call.
251     ///
252     /// [`recv`]: #method.recv
recv_with_flags(&self, buf: &mut [u8], flags: i32) -> io::Result<usize>253     pub fn recv_with_flags(&self, buf: &mut [u8], flags: i32) -> io::Result<usize> {
254         self.inner.recv(buf, flags)
255     }
256 
257     /// Receives out-of-band (OOB) data on the socket from the remote address to
258     /// which it is connected by setting the `MSG_OOB` flag for this call.
259     ///
260     /// For more information, see [`recv`], [`out_of_band_inline`].
261     ///
262     /// [`recv`]: #method.recv
263     /// [`out_of_band_inline`]: #method.out_of_band_inline
recv_out_of_band(&self, buf: &mut [u8]) -> io::Result<usize>264     pub fn recv_out_of_band(&self, buf: &mut [u8]) -> io::Result<usize> {
265         self.inner.recv(buf, MSG_OOB)
266     }
267 
268     /// Receives data on the socket from the remote adress to which it is
269     /// connected, without removing that data from the queue. On success,
270     /// returns the number of bytes peeked.
271     ///
272     /// Successive calls return the same data. This is accomplished by passing
273     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
peek(&self, buf: &mut [u8]) -> io::Result<usize>274     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
275         self.inner.peek(buf)
276     }
277 
278     /// Receives data from the socket. On success, returns the number of bytes
279     /// read and the address from whence the data came.
recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)>280     pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> {
281         self.inner.recv_from(buf, 0)
282     }
283 
284     /// Identical to [`recv_from`] but allows for specification of arbitrary flags to the underlying
285     /// `recvfrom` call.
286     ///
287     /// [`recv_from`]: #method.recv_from
recv_from_with_flags(&self, buf: &mut [u8], flags: i32) -> io::Result<usize>288     pub fn recv_from_with_flags(&self, buf: &mut [u8], flags: i32) -> io::Result<usize> {
289         self.inner.recv(buf, flags)
290     }
291 
292     /// Receives data from the socket, without removing it from the queue.
293     ///
294     /// Successive calls return the same data. This is accomplished by passing
295     /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
296     ///
297     /// On success, returns the number of bytes peeked and the address from
298     /// whence the data came.
peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)>299     pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> {
300         self.inner.peek_from(buf)
301     }
302 
303     /// Sends data on the socket to a connected peer.
304     ///
305     /// This is typically used on TCP sockets or datagram sockets which have
306     /// been connected.
307     ///
308     /// On success returns the number of bytes that were sent.
send(&self, buf: &[u8]) -> io::Result<usize>309     pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
310         self.inner.send(buf, 0)
311     }
312 
313     /// Identical to [`send`] but allows for specification of arbitrary flags to the underlying
314     /// `send` call.
315     ///
316     /// [`send`]: #method.send
send_with_flags(&self, buf: &mut [u8], flags: i32) -> io::Result<usize>317     pub fn send_with_flags(&self, buf: &mut [u8], flags: i32) -> io::Result<usize> {
318         self.inner.send(buf, flags)
319     }
320 
321     /// Sends out-of-band (OOB) data on the socket to connected peer
322     /// by setting the `MSG_OOB` flag for this call.
323     ///
324     /// For more information, see [`send`], [`out_of_band_inline`].
325     ///
326     /// [`send`]: #method.send
327     /// [`out_of_band_inline`]: #method.out_of_band_inline
send_out_of_band(&self, buf: &mut [u8]) -> io::Result<usize>328     pub fn send_out_of_band(&self, buf: &mut [u8]) -> io::Result<usize> {
329         self.inner.send(buf, MSG_OOB)
330     }
331 
332     /// Sends data on the socket to the given address. On success, returns the
333     /// number of bytes written.
334     ///
335     /// This is typically used on UDP or datagram-oriented sockets. On success
336     /// returns the number of bytes that were sent.
send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize>337     pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> {
338         self.inner.send_to(buf, 0, addr)
339     }
340 
341     /// Identical to [`send_to`] but allows for specification of arbitrary flags to the underlying
342     /// `sendto` call.
343     ///
344     /// [`send_to`]: #method.send_to
send_to_with_flags(&self, buf: &mut [u8], flags: i32) -> io::Result<usize>345     pub fn send_to_with_flags(&self, buf: &mut [u8], flags: i32) -> io::Result<usize> {
346         self.inner.recv(buf, flags)
347     }
348 
349     // ================================================
350 
351     /// Gets the value of the `IP_TTL` option for this socket.
352     ///
353     /// For more information about this option, see [`set_ttl`][link].
354     ///
355     /// [link]: #method.set_ttl
ttl(&self) -> io::Result<u32>356     pub fn ttl(&self) -> io::Result<u32> {
357         self.inner.ttl()
358     }
359 
360     /// Sets the value for the `IP_TTL` option on this socket.
361     ///
362     /// This value sets the time-to-live field that is used in every packet sent
363     /// from this socket.
set_ttl(&self, ttl: u32) -> io::Result<()>364     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
365         self.inner.set_ttl(ttl)
366     }
367 
368     /// Gets the value of the `IPV6_UNICAST_HOPS` option for this socket.
369     ///
370     /// Specifies the hop limit for ipv6 unicast packets
unicast_hops_v6(&self) -> io::Result<u32>371     pub fn unicast_hops_v6(&self) -> io::Result<u32> {
372         self.inner.unicast_hops_v6()
373     }
374 
375     /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket.
376     ///
377     /// Specifies the hop limit for ipv6 unicast packets
set_unicast_hops_v6(&self, ttl: u32) -> io::Result<()>378     pub fn set_unicast_hops_v6(&self, ttl: u32) -> io::Result<()> {
379         self.inner.set_unicast_hops_v6(ttl)
380     }
381 
382     /// Gets the value of the `IPV6_V6ONLY` option for this socket.
383     ///
384     /// For more information about this option, see [`set_only_v6`][link].
385     ///
386     /// [link]: #method.set_only_v6
only_v6(&self) -> io::Result<bool>387     pub fn only_v6(&self) -> io::Result<bool> {
388         self.inner.only_v6()
389     }
390 
391     /// Sets the value for the `IPV6_V6ONLY` option on this socket.
392     ///
393     /// If this is set to `true` then the socket is restricted to sending and
394     /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications
395     /// can bind the same port at the same time.
396     ///
397     /// If this is set to `false` then the socket can be used to send and
398     /// receive packets from an IPv4-mapped IPv6 address.
set_only_v6(&self, only_v6: bool) -> io::Result<()>399     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
400         self.inner.set_only_v6(only_v6)
401     }
402 
403     /// Returns the read timeout of this socket.
404     ///
405     /// If the timeout is `None`, then `read` calls will block indefinitely.
read_timeout(&self) -> io::Result<Option<Duration>>406     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
407         self.inner.read_timeout()
408     }
409 
410     /// Sets the read timeout to the timeout specified.
411     ///
412     /// If the value specified is `None`, then `read` calls will block
413     /// indefinitely. It is an error to pass the zero `Duration` to this
414     /// method.
set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()>415     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
416         self.inner.set_read_timeout(dur)
417     }
418 
419     /// Returns the write timeout of this socket.
420     ///
421     /// If the timeout is `None`, then `write` calls will block indefinitely.
write_timeout(&self) -> io::Result<Option<Duration>>422     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
423         self.inner.write_timeout()
424     }
425 
426     /// Sets the write timeout to the timeout specified.
427     ///
428     /// If the value specified is `None`, then `write` calls will block
429     /// indefinitely. It is an error to pass the zero `Duration` to this
430     /// method.
set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()>431     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
432         self.inner.set_write_timeout(dur)
433     }
434 
435     /// Gets the value of the `TCP_NODELAY` option on this socket.
436     ///
437     /// For more information about this option, see [`set_nodelay`][link].
438     ///
439     /// [link]: #method.set_nodelay
nodelay(&self) -> io::Result<bool>440     pub fn nodelay(&self) -> io::Result<bool> {
441         self.inner.nodelay()
442     }
443 
444     /// Sets the value of the `TCP_NODELAY` option on this socket.
445     ///
446     /// If set, this option disables the Nagle algorithm. This means that
447     /// segments are always sent as soon as possible, even if there is only a
448     /// small amount of data. When not set, data is buffered until there is a
449     /// sufficient amount to send out, thereby avoiding the frequent sending of
450     /// small packets.
set_nodelay(&self, nodelay: bool) -> io::Result<()>451     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
452         self.inner.set_nodelay(nodelay)
453     }
454 
455     /// Sets the value of the `SO_BROADCAST` option for this socket.
456     ///
457     /// When enabled, this socket is allowed to send packets to a broadcast
458     /// address.
broadcast(&self) -> io::Result<bool>459     pub fn broadcast(&self) -> io::Result<bool> {
460         self.inner.broadcast()
461     }
462 
463     /// Gets the value of the `SO_BROADCAST` option for this socket.
464     ///
465     /// For more information about this option, see
466     /// [`set_broadcast`][link].
467     ///
468     /// [link]: #method.set_broadcast
set_broadcast(&self, broadcast: bool) -> io::Result<()>469     pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
470         self.inner.set_broadcast(broadcast)
471     }
472 
473     /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket.
474     ///
475     /// For more information about this option, see
476     /// [`set_multicast_loop_v4`][link].
477     ///
478     /// [link]: #method.set_multicast_loop_v4
multicast_loop_v4(&self) -> io::Result<bool>479     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
480         self.inner.multicast_loop_v4()
481     }
482 
483     /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket.
484     ///
485     /// If enabled, multicast packets will be looped back to the local socket.
486     /// Note that this may not have any affect on IPv6 sockets.
set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()>487     pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> {
488         self.inner.set_multicast_loop_v4(multicast_loop_v4)
489     }
490 
491     /// Gets the value of the `IP_MULTICAST_TTL` option for this socket.
492     ///
493     /// For more information about this option, see
494     /// [`set_multicast_ttl_v4`][link].
495     ///
496     /// [link]: #method.set_multicast_ttl_v4
multicast_ttl_v4(&self) -> io::Result<u32>497     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
498         self.inner.multicast_ttl_v4()
499     }
500 
501     /// Sets the value of the `IP_MULTICAST_TTL` option for this socket.
502     ///
503     /// Indicates the time-to-live value of outgoing multicast packets for
504     /// this socket. The default value is 1 which means that multicast packets
505     /// don't leave the local network unless explicitly requested.
506     ///
507     /// Note that this may not have any affect on IPv6 sockets.
set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()>508     pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> {
509         self.inner.set_multicast_ttl_v4(multicast_ttl_v4)
510     }
511 
512     /// Gets the value of the `IPV6_MULTICAST_HOPS` option for this socket
513     ///
514     /// For more information about this option, see
515     /// [`set_multicast_hops_v6`][link].
516     ///
517     /// [link]: #method.set_multicast_hops_v6
multicast_hops_v6(&self) -> io::Result<u32>518     pub fn multicast_hops_v6(&self) -> io::Result<u32> {
519         self.inner.multicast_hops_v6()
520     }
521 
522     /// Sets the value of the `IPV6_MULTICAST_HOPS` option for this socket
523     ///
524     /// Indicates the number of "routers" multicast packets will transit for
525     /// this socket. The default value is 1 which means that multicast packets
526     /// don't leave the local network unless explicitly requested.
set_multicast_hops_v6(&self, hops: u32) -> io::Result<()>527     pub fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()> {
528         self.inner.set_multicast_hops_v6(hops)
529     }
530 
531     /// Gets the value of the `IP_MULTICAST_IF` option for this socket.
532     ///
533     /// For more information about this option, see
534     /// [`set_multicast_if_v4`][link].
535     ///
536     /// [link]: #method.set_multicast_if_v4
537     ///
538     /// Returns the interface to use for routing multicast packets.
multicast_if_v4(&self) -> io::Result<Ipv4Addr>539     pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> {
540         self.inner.multicast_if_v4()
541     }
542 
543     /// Sets the value of the `IP_MULTICAST_IF` option for this socket.
544     ///
545     /// Specifies the interface to use for routing multicast packets.
set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()>546     pub fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()> {
547         self.inner.set_multicast_if_v4(interface)
548     }
549 
550     /// Gets the value of the `IPV6_MULTICAST_IF` option for this socket.
551     ///
552     /// For more information about this option, see
553     /// [`set_multicast_if_v6`][link].
554     ///
555     /// [link]: #method.set_multicast_if_v6
556     ///
557     /// Returns the interface to use for routing multicast packets.
multicast_if_v6(&self) -> io::Result<u32>558     pub fn multicast_if_v6(&self) -> io::Result<u32> {
559         self.inner.multicast_if_v6()
560     }
561 
562     /// Sets the value of the `IPV6_MULTICAST_IF` option for this socket.
563     ///
564     /// Specifies the interface to use for routing multicast packets. Unlike ipv4, this
565     /// is generally required in ipv6 contexts where network routing prefixes may
566     /// overlap.
set_multicast_if_v6(&self, interface: u32) -> io::Result<()>567     pub fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()> {
568         self.inner.set_multicast_if_v6(interface)
569     }
570 
571     /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
572     ///
573     /// For more information about this option, see
574     /// [`set_multicast_loop_v6`][link].
575     ///
576     /// [link]: #method.set_multicast_loop_v6
multicast_loop_v6(&self) -> io::Result<bool>577     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
578         self.inner.multicast_loop_v6()
579     }
580 
581     /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket.
582     ///
583     /// Controls whether this socket sees the multicast packets it sends itself.
584     /// Note that this may not have any affect on IPv4 sockets.
set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()>585     pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> {
586         self.inner.set_multicast_loop_v6(multicast_loop_v6)
587     }
588 
589     /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
590     ///
591     /// This function specifies a new multicast group for this socket to join.
592     /// The address must be a valid multicast address, and `interface` is the
593     /// address of the local interface with which the system should join the
594     /// multicast group. If it's equal to `INADDR_ANY` then an appropriate
595     /// interface is chosen by the system.
join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>596     pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
597         self.inner.join_multicast_v4(multiaddr, interface)
598     }
599 
600     /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
601     ///
602     /// This function specifies a new multicast group for this socket to join.
603     /// The address must be a valid multicast address, and `interface` is the
604     /// index of the interface to join/leave (or 0 to indicate any interface).
join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>605     pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
606         self.inner.join_multicast_v6(multiaddr, interface)
607     }
608 
609     /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
610     ///
611     /// For more information about this option, see
612     /// [`join_multicast_v4`][link].
613     ///
614     /// [link]: #method.join_multicast_v4
leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>615     pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
616         self.inner.leave_multicast_v4(multiaddr, interface)
617     }
618 
619     /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
620     ///
621     /// For more information about this option, see
622     /// [`join_multicast_v6`][link].
623     ///
624     /// [link]: #method.join_multicast_v6
leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>625     pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
626         self.inner.leave_multicast_v6(multiaddr, interface)
627     }
628 
629     /// Reads the linger duration for this socket by getting the SO_LINGER
630     /// option
linger(&self) -> io::Result<Option<Duration>>631     pub fn linger(&self) -> io::Result<Option<Duration>> {
632         self.inner.linger()
633     }
634 
635     /// Sets the linger duration of this socket by setting the SO_LINGER option
set_linger(&self, dur: Option<Duration>) -> io::Result<()>636     pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> {
637         self.inner.set_linger(dur)
638     }
639 
640     /// Check the `SO_REUSEADDR` option on this socket.
reuse_address(&self) -> io::Result<bool>641     pub fn reuse_address(&self) -> io::Result<bool> {
642         self.inner.reuse_address()
643     }
644 
645     /// Set value for the `SO_REUSEADDR` option on this socket.
646     ///
647     /// This indicates that futher calls to `bind` may allow reuse of local
648     /// addresses. For IPv4 sockets this means that a socket may bind even when
649     /// there's a socket already listening on this port.
set_reuse_address(&self, reuse: bool) -> io::Result<()>650     pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> {
651         self.inner.set_reuse_address(reuse)
652     }
653 
654     /// Gets the value of the `SO_RCVBUF` option on this socket.
655     ///
656     /// For more information about this option, see
657     /// [`set_recv_buffer_size`][link].
658     ///
659     /// [link]: #method.set_recv_buffer_size
recv_buffer_size(&self) -> io::Result<usize>660     pub fn recv_buffer_size(&self) -> io::Result<usize> {
661         self.inner.recv_buffer_size()
662     }
663 
664     /// Sets the value of the `SO_RCVBUF` option on this socket.
665     ///
666     /// Changes the size of the operating system's receive buffer associated
667     /// with the socket.
set_recv_buffer_size(&self, size: usize) -> io::Result<()>668     pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> {
669         self.inner.set_recv_buffer_size(size)
670     }
671 
672     /// Gets the value of the `SO_SNDBUF` option on this socket.
673     ///
674     /// For more information about this option, see [`set_send_buffer`][link].
675     ///
676     /// [link]: #method.set_send_buffer
send_buffer_size(&self) -> io::Result<usize>677     pub fn send_buffer_size(&self) -> io::Result<usize> {
678         self.inner.send_buffer_size()
679     }
680 
681     /// Sets the value of the `SO_SNDBUF` option on this socket.
682     ///
683     /// Changes the size of the operating system's send buffer associated with
684     /// the socket.
set_send_buffer_size(&self, size: usize) -> io::Result<()>685     pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> {
686         self.inner.set_send_buffer_size(size)
687     }
688 
689     /// Returns whether keepalive messages are enabled on this socket, and if so
690     /// the duration of time between them.
691     ///
692     /// For more information about this option, see [`set_keepalive`][link].
693     ///
694     /// [link]: #method.set_keepalive
keepalive(&self) -> io::Result<Option<Duration>>695     pub fn keepalive(&self) -> io::Result<Option<Duration>> {
696         self.inner.keepalive()
697     }
698 
699     /// Sets whether keepalive messages are enabled to be sent on this socket.
700     ///
701     /// On Unix, this option will set the `SO_KEEPALIVE` as well as the
702     /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform).
703     /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option.
704     ///
705     /// If `None` is specified then keepalive messages are disabled, otherwise
706     /// the duration specified will be the time to remain idle before sending a
707     /// TCP keepalive probe.
708     ///
709     /// Some platforms specify this value in seconds, so sub-second
710     /// specifications may be omitted.
set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()>711     pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> {
712         self.inner.set_keepalive(keepalive)
713     }
714 
715     /// Returns the value of the `SO_OOBINLINE` flag of the underlying socket.
716     /// For more information about this option, see [`set_out_of_band_inline`][link].
717     ///
718     /// [link]: #method.set_out_of_band_inline
out_of_band_inline(&self) -> io::Result<bool>719     pub fn out_of_band_inline(&self) -> io::Result<bool> {
720         self.inner.out_of_band_inline()
721     }
722 
723     /// Sets the `SO_OOBINLINE` flag of the underlying socket.
724     /// as per RFC6093, TCP sockets using the Urgent mechanism
725     /// are encouraged to set this flag.
726     ///
727     /// If this flag is not set, the `MSG_OOB` flag is needed
728     /// while `recv`ing to aquire the out-of-band data.
set_out_of_band_inline(&self, oob_inline: bool) -> io::Result<()>729     pub fn set_out_of_band_inline(&self, oob_inline: bool) -> io::Result<()> {
730         self.inner.set_out_of_band_inline(oob_inline)
731     }
732 
733     /// Check the value of the `SO_REUSEPORT` option on this socket.
734     ///
735     /// This function is only available on Unix when the `reuseport` feature is
736     /// enabled.
737     #[cfg(all(
738         unix,
739         not(any(target_os = "solaris", target_os = "illumos")),
740         feature = "reuseport"
741     ))]
reuse_port(&self) -> io::Result<bool>742     pub fn reuse_port(&self) -> io::Result<bool> {
743         self.inner.reuse_port()
744     }
745 
746     /// Set value for the `SO_REUSEPORT` option on this socket.
747     ///
748     /// This indicates that further calls to `bind` may allow reuse of local
749     /// addresses. For IPv4 sockets this means that a socket may bind even when
750     /// there's a socket already listening on this port.
751     ///
752     /// This function is only available on Unix when the `reuseport` feature is
753     /// enabled.
754     #[cfg(all(
755         unix,
756         not(any(target_os = "solaris", target_os = "illumos")),
757         feature = "reuseport"
758     ))]
set_reuse_port(&self, reuse: bool) -> io::Result<()>759     pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> {
760         self.inner.set_reuse_port(reuse)
761     }
762 }
763 
764 impl Read for Socket {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>765     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
766         self.inner.read(buf)
767     }
768 }
769 
770 impl<'a> Read for &'a Socket {
read(&mut self, buf: &mut [u8]) -> io::Result<usize>771     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
772         (&self.inner).read(buf)
773     }
774 }
775 
776 impl Write for Socket {
write(&mut self, buf: &[u8]) -> io::Result<usize>777     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
778         self.inner.write(buf)
779     }
780 
flush(&mut self) -> io::Result<()>781     fn flush(&mut self) -> io::Result<()> {
782         self.inner.flush()
783     }
784 }
785 
786 impl<'a> Write for &'a Socket {
write(&mut self, buf: &[u8]) -> io::Result<usize>787     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
788         (&self.inner).write(buf)
789     }
790 
flush(&mut self) -> io::Result<()>791     fn flush(&mut self) -> io::Result<()> {
792         (&self.inner).flush()
793     }
794 }
795 
796 impl fmt::Debug for Socket {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result797     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
798         self.inner.fmt(f)
799     }
800 }
801 
802 impl From<net::TcpStream> for Socket {
from(socket: net::TcpStream) -> Socket803     fn from(socket: net::TcpStream) -> Socket {
804         Socket {
805             inner: socket.into(),
806         }
807     }
808 }
809 
810 impl From<net::TcpListener> for Socket {
from(socket: net::TcpListener) -> Socket811     fn from(socket: net::TcpListener) -> Socket {
812         Socket {
813             inner: socket.into(),
814         }
815     }
816 }
817 
818 impl From<net::UdpSocket> for Socket {
from(socket: net::UdpSocket) -> Socket819     fn from(socket: net::UdpSocket) -> Socket {
820         Socket {
821             inner: socket.into(),
822         }
823     }
824 }
825 
826 #[cfg(all(unix, feature = "unix"))]
827 impl From<UnixStream> for Socket {
from(socket: UnixStream) -> Socket828     fn from(socket: UnixStream) -> Socket {
829         Socket {
830             inner: socket.into(),
831         }
832     }
833 }
834 
835 #[cfg(all(unix, feature = "unix"))]
836 impl From<UnixListener> for Socket {
from(socket: UnixListener) -> Socket837     fn from(socket: UnixListener) -> Socket {
838         Socket {
839             inner: socket.into(),
840         }
841     }
842 }
843 
844 #[cfg(all(unix, feature = "unix"))]
845 impl From<UnixDatagram> for Socket {
from(socket: UnixDatagram) -> Socket846     fn from(socket: UnixDatagram) -> Socket {
847         Socket {
848             inner: socket.into(),
849         }
850     }
851 }
852 
853 impl From<Socket> for net::TcpStream {
from(socket: Socket) -> net::TcpStream854     fn from(socket: Socket) -> net::TcpStream {
855         socket.inner.into()
856     }
857 }
858 
859 impl From<Socket> for net::TcpListener {
from(socket: Socket) -> net::TcpListener860     fn from(socket: Socket) -> net::TcpListener {
861         socket.inner.into()
862     }
863 }
864 
865 impl From<Socket> for net::UdpSocket {
from(socket: Socket) -> net::UdpSocket866     fn from(socket: Socket) -> net::UdpSocket {
867         socket.inner.into()
868     }
869 }
870 
871 #[cfg(all(unix, feature = "unix"))]
872 impl From<Socket> for UnixStream {
from(socket: Socket) -> UnixStream873     fn from(socket: Socket) -> UnixStream {
874         socket.inner.into()
875     }
876 }
877 
878 #[cfg(all(unix, feature = "unix"))]
879 impl From<Socket> for UnixListener {
from(socket: Socket) -> UnixListener880     fn from(socket: Socket) -> UnixListener {
881         socket.inner.into()
882     }
883 }
884 
885 #[cfg(all(unix, feature = "unix"))]
886 impl From<Socket> for UnixDatagram {
from(socket: Socket) -> UnixDatagram887     fn from(socket: Socket) -> UnixDatagram {
888         socket.inner.into()
889     }
890 }
891 
892 #[cfg(test)]
893 mod test {
894     use std::net::SocketAddr;
895 
896     use super::*;
897 
898     #[test]
connect_timeout_unrouteable()899     fn connect_timeout_unrouteable() {
900         // this IP is unroutable, so connections should always time out
901         let addr = "10.255.255.1:80".parse::<SocketAddr>().unwrap().into();
902 
903         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
904         match socket.connect_timeout(&addr, Duration::from_millis(250)) {
905             Ok(_) => panic!("unexpected success"),
906             Err(ref e) if e.kind() == io::ErrorKind::TimedOut => {}
907             Err(e) => panic!("unexpected error {}", e),
908         }
909     }
910 
911     #[test]
connect_timeout_unbound()912     fn connect_timeout_unbound() {
913         // bind and drop a socket to track down a "probably unassigned" port
914         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
915         let addr = "127.0.0.1:0".parse::<SocketAddr>().unwrap().into();
916         socket.bind(&addr).unwrap();
917         let addr = socket.local_addr().unwrap();
918         drop(socket);
919 
920         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
921         match socket.connect_timeout(&addr, Duration::from_millis(250)) {
922             Ok(_) => panic!("unexpected success"),
923             Err(ref e)
924                 if e.kind() == io::ErrorKind::ConnectionRefused
925                     || e.kind() == io::ErrorKind::TimedOut => {}
926             Err(e) => panic!("unexpected error {}", e),
927         }
928     }
929 
930     #[test]
connect_timeout_valid()931     fn connect_timeout_valid() {
932         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
933         socket
934             .bind(&"127.0.0.1:0".parse::<SocketAddr>().unwrap().into())
935             .unwrap();
936         socket.listen(128).unwrap();
937 
938         let addr = socket.local_addr().unwrap();
939 
940         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
941         socket
942             .connect_timeout(&addr, Duration::from_millis(250))
943             .unwrap();
944     }
945 
946     #[test]
947     #[cfg(all(unix, feature = "pair", feature = "unix"))]
pair()948     fn pair() {
949         let (mut a, mut b) = Socket::pair(Domain::unix(), Type::stream(), None).unwrap();
950         a.write_all(b"hello world").unwrap();
951         let mut buf = [0; 11];
952         b.read_exact(&mut buf).unwrap();
953         assert_eq!(buf, &b"hello world"[..]);
954     }
955 
956     #[test]
957     #[cfg(all(unix, feature = "unix"))]
unix()958     fn unix() {
959         use tempdir::TempDir;
960 
961         let dir = TempDir::new("unix").unwrap();
962         let addr = SockAddr::unix(dir.path().join("sock")).unwrap();
963 
964         let listener = Socket::new(Domain::unix(), Type::stream(), None).unwrap();
965         listener.bind(&addr).unwrap();
966         listener.listen(10).unwrap();
967 
968         let mut a = Socket::new(Domain::unix(), Type::stream(), None).unwrap();
969         a.connect(&addr).unwrap();
970 
971         let mut b = listener.accept().unwrap().0;
972 
973         a.write_all(b"hello world").unwrap();
974         let mut buf = [0; 11];
975         b.read_exact(&mut buf).unwrap();
976         assert_eq!(buf, &b"hello world"[..]);
977     }
978 
979     #[test]
keepalive()980     fn keepalive() {
981         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
982         socket.set_keepalive(Some(Duration::from_secs(7))).unwrap();
983         // socket.keepalive() doesn't work on Windows #24
984         #[cfg(unix)]
985         assert_eq!(socket.keepalive().unwrap(), Some(Duration::from_secs(7)));
986         socket.set_keepalive(None).unwrap();
987         #[cfg(unix)]
988         assert_eq!(socket.keepalive().unwrap(), None);
989     }
990 
991     #[test]
nodelay()992     fn nodelay() {
993         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
994 
995         assert!(socket.set_nodelay(true).is_ok());
996 
997         let result = socket.nodelay();
998 
999         assert!(result.is_ok());
1000         assert!(result.unwrap());
1001     }
1002 
1003     #[test]
out_of_band_inline()1004     fn out_of_band_inline() {
1005         let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
1006 
1007         assert_eq!(socket.out_of_band_inline().unwrap(), false);
1008 
1009         socket.set_out_of_band_inline(true).unwrap();
1010         assert_eq!(socket.out_of_band_inline().unwrap(), true);
1011     }
1012 
1013     #[test]
1014     #[cfg(any(target_os = "windows", target_os = "linux"))]
out_of_band_send_recv()1015     fn out_of_band_send_recv() {
1016         let s1 = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
1017         s1.bind(&"127.0.0.1:0".parse::<SocketAddr>().unwrap().into())
1018             .unwrap();
1019         let s1_addr = s1.local_addr().unwrap();
1020         s1.listen(1).unwrap();
1021 
1022         let s2 = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
1023         s2.connect(&s1_addr).unwrap();
1024 
1025         let (s3, _) = s1.accept().unwrap();
1026 
1027         let mut buf = [0; 10];
1028         // send some plain inband data
1029         s2.send(&mut buf).unwrap();
1030         // send a single out of band byte
1031         assert_eq!(s2.send_out_of_band(&mut [b"!"[0]]).unwrap(), 1);
1032         // recv the OOB data first
1033         assert_eq!(s3.recv_out_of_band(&mut buf).unwrap(), 1);
1034         assert_eq!(buf[0], b"!"[0]);
1035         assert_eq!(s3.recv(&mut buf).unwrap(), 10);
1036     }
1037 
1038     #[test]
tcp()1039     fn tcp() {
1040         let s1 = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
1041         s1.bind(&"127.0.0.1:0".parse::<SocketAddr>().unwrap().into())
1042             .unwrap();
1043         let s1_addr = s1.local_addr().unwrap();
1044         s1.listen(1).unwrap();
1045 
1046         let s2 = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap();
1047         s2.connect(&s1_addr).unwrap();
1048 
1049         let (s3, _) = s1.accept().unwrap();
1050 
1051         let mut buf = [0; 11];
1052         assert_eq!(s2.send(&mut buf).unwrap(), 11);
1053         assert_eq!(s3.recv(&mut buf).unwrap(), 11);
1054     }
1055 }
1056