]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/tcp.rs
SGX target: fix std unit tests
[rust.git] / src / libstd / net / tcp.rs
1 use crate::io::prelude::*;
2
3 use crate::fmt;
4 use crate::io::{self, Initializer, IoVec, IoVecMut};
5 use crate::net::{ToSocketAddrs, SocketAddr, Shutdown};
6 use crate::sys_common::net as net_imp;
7 use crate::sys_common::{AsInner, FromInner, IntoInner};
8 use crate::time::Duration;
9
10 /// A TCP stream between a local and a remote socket.
11 ///
12 /// After creating a `TcpStream` by either [`connect`]ing to a remote host or
13 /// [`accept`]ing a connection on a [`TcpListener`], data can be transmitted
14 /// by [reading] and [writing] to it.
15 ///
16 /// The connection will be closed when the value is dropped. The reading and writing
17 /// portions of the connection can also be shut down individually with the [`shutdown`]
18 /// method.
19 ///
20 /// The Transmission Control Protocol is specified in [IETF RFC 793].
21 ///
22 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
23 /// [`connect`]: #method.connect
24 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
25 /// [reading]: ../../std/io/trait.Read.html
26 /// [`shutdown`]: #method.shutdown
27 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
28 /// [writing]: ../../std/io/trait.Write.html
29 ///
30 /// # Examples
31 ///
32 /// ```no_run
33 /// use std::io::prelude::*;
34 /// use std::net::TcpStream;
35 ///
36 /// fn main() -> std::io::Result<()> {
37 ///     let mut stream = TcpStream::connect("127.0.0.1:34254")?;
38 ///
39 ///     stream.write(&[1])?;
40 ///     stream.read(&mut [0; 128])?;
41 ///     Ok(())
42 /// } // the stream is closed here
43 /// ```
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub struct TcpStream(net_imp::TcpStream);
46
47 /// A TCP socket server, listening for connections.
48 ///
49 /// After creating a `TcpListener` by [`bind`]ing it to a socket address, it listens
50 /// for incoming TCP connections. These can be accepted by calling [`accept`] or by
51 /// iterating over the [`Incoming`] iterator returned by [`incoming`][`TcpListener::incoming`].
52 ///
53 /// The socket will be closed when the value is dropped.
54 ///
55 /// The Transmission Control Protocol is specified in [IETF RFC 793].
56 ///
57 /// [`accept`]: #method.accept
58 /// [`bind`]: #method.bind
59 /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793
60 /// [`Incoming`]: ../../std/net/struct.Incoming.html
61 /// [`TcpListener::incoming`]: #method.incoming
62 ///
63 /// # Examples
64 ///
65 /// ```no_run
66 /// # use std::io;
67 /// use std::net::{TcpListener, TcpStream};
68 ///
69 /// fn handle_client(stream: TcpStream) {
70 ///     // ...
71 /// }
72 ///
73 /// fn main() -> io::Result<()> {
74 ///     let listener = TcpListener::bind("127.0.0.1:80")?;
75 ///
76 ///     // accept connections and process them serially
77 ///     for stream in listener.incoming() {
78 ///         handle_client(stream?);
79 ///     }
80 ///     Ok(())
81 /// }
82 /// ```
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct TcpListener(net_imp::TcpListener);
85
86 /// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
87 ///
88 /// This `struct` is created by the [`incoming`] method on [`TcpListener`].
89 /// See its documentation for more.
90 ///
91 /// [`accept`]: ../../std/net/struct.TcpListener.html#method.accept
92 /// [`incoming`]: ../../std/net/struct.TcpListener.html#method.incoming
93 /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
94 #[stable(feature = "rust1", since = "1.0.0")]
95 #[derive(Debug)]
96 pub struct Incoming<'a> { listener: &'a TcpListener }
97
98 impl TcpStream {
99     /// Opens a TCP connection to a remote host.
100     ///
101     /// `addr` is an address of the remote host. Anything which implements
102     /// [`ToSocketAddrs`] trait can be supplied for the address; see this trait
103     /// documentation for concrete examples.
104     ///
105     /// If `addr` yields multiple addresses, `connect` will be attempted with
106     /// each of the addresses until a connection is successful. If none of
107     /// the addresses result in a successful connection, the error returned from
108     /// the last connection attempt (the last address) is returned.
109     ///
110     /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
111     ///
112     /// # Examples
113     ///
114     /// Open a TCP connection to `127.0.0.1:8080`:
115     ///
116     /// ```no_run
117     /// use std::net::TcpStream;
118     ///
119     /// if let Ok(stream) = TcpStream::connect("127.0.0.1:8080") {
120     ///     println!("Connected to the server!");
121     /// } else {
122     ///     println!("Couldn't connect to server...");
123     /// }
124     /// ```
125     ///
126     /// Open a TCP connection to `127.0.0.1:8080`. If the connection fails, open
127     /// a TCP connection to `127.0.0.1:8081`:
128     ///
129     /// ```no_run
130     /// use std::net::{SocketAddr, TcpStream};
131     ///
132     /// let addrs = [
133     ///     SocketAddr::from(([127, 0, 0, 1], 8080)),
134     ///     SocketAddr::from(([127, 0, 0, 1], 8081)),
135     /// ];
136     /// if let Ok(stream) = TcpStream::connect(&addrs[..]) {
137     ///     println!("Connected to the server!");
138     /// } else {
139     ///     println!("Couldn't connect to server...");
140     /// }
141     /// ```
142     #[stable(feature = "rust1", since = "1.0.0")]
143     pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
144         super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
145     }
146
147     /// Opens a TCP connection to a remote host with a timeout.
148     ///
149     /// Unlike `connect`, `connect_timeout` takes a single [`SocketAddr`] since
150     /// timeout must be applied to individual addresses.
151     ///
152     /// It is an error to pass a zero `Duration` to this function.
153     ///
154     /// Unlike other methods on `TcpStream`, this does not correspond to a
155     /// single system call. It instead calls `connect` in nonblocking mode and
156     /// then uses an OS-specific mechanism to await the completion of the
157     /// connection request.
158     ///
159     /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
160     #[stable(feature = "tcpstream_connect_timeout", since = "1.21.0")]
161     pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
162         net_imp::TcpStream::connect_timeout(addr, timeout).map(TcpStream)
163     }
164
165     /// Returns the socket address of the remote peer of this TCP connection.
166     ///
167     /// # Examples
168     ///
169     /// ```no_run
170     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
171     ///
172     /// let stream = TcpStream::connect("127.0.0.1:8080")
173     ///                        .expect("Couldn't connect to the server...");
174     /// assert_eq!(stream.peer_addr().unwrap(),
175     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
176     /// ```
177     #[stable(feature = "rust1", since = "1.0.0")]
178     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
179         self.0.peer_addr()
180     }
181
182     /// Returns the socket address of the local half of this TCP connection.
183     ///
184     /// # Examples
185     ///
186     /// ```no_run
187     /// use std::net::{IpAddr, Ipv4Addr, TcpStream};
188     ///
189     /// let stream = TcpStream::connect("127.0.0.1:8080")
190     ///                        .expect("Couldn't connect to the server...");
191     /// assert_eq!(stream.local_addr().unwrap().ip(),
192     ///            IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
193     /// ```
194     #[stable(feature = "rust1", since = "1.0.0")]
195     pub fn local_addr(&self) -> io::Result<SocketAddr> {
196         self.0.socket_addr()
197     }
198
199     /// Shuts down the read, write, or both halves of this connection.
200     ///
201     /// This function will cause all pending and future I/O on the specified
202     /// portions to return immediately with an appropriate value (see the
203     /// documentation of [`Shutdown`]).
204     ///
205     /// [`Shutdown`]: ../../std/net/enum.Shutdown.html
206     ///
207     /// # Platform-specific behavior
208     ///
209     /// Calling this function multiple times may result in different behavior,
210     /// depending on the operating system. On Linux, the second call will
211     /// return `Ok(())`, but on macOS, it will return `ErrorKind::NotConnected`.
212     /// This may change in the future.
213     ///
214     /// # Examples
215     ///
216     /// ```no_run
217     /// use std::net::{Shutdown, TcpStream};
218     ///
219     /// let stream = TcpStream::connect("127.0.0.1:8080")
220     ///                        .expect("Couldn't connect to the server...");
221     /// stream.shutdown(Shutdown::Both).expect("shutdown call failed");
222     /// ```
223     #[stable(feature = "rust1", since = "1.0.0")]
224     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
225         self.0.shutdown(how)
226     }
227
228     /// Creates a new independently owned handle to the underlying socket.
229     ///
230     /// The returned `TcpStream` is a reference to the same stream that this
231     /// object references. Both handles will read and write the same stream of
232     /// data, and options set on one stream will be propagated to the other
233     /// stream.
234     ///
235     /// # Examples
236     ///
237     /// ```no_run
238     /// use std::net::TcpStream;
239     ///
240     /// let stream = TcpStream::connect("127.0.0.1:8080")
241     ///                        .expect("Couldn't connect to the server...");
242     /// let stream_clone = stream.try_clone().expect("clone failed...");
243     /// ```
244     #[stable(feature = "rust1", since = "1.0.0")]
245     pub fn try_clone(&self) -> io::Result<TcpStream> {
246         self.0.duplicate().map(TcpStream)
247     }
248
249     /// Sets the read timeout to the timeout specified.
250     ///
251     /// If the value specified is [`None`], then [`read`] calls will block
252     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
253     /// passed to this method.
254     ///
255     /// # Platform-specific behavior
256     ///
257     /// Platforms may return a different error code whenever a read times out as
258     /// a result of setting this option. For example Unix typically returns an
259     /// error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
260     ///
261     /// [`None`]: ../../std/option/enum.Option.html#variant.None
262     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
263     /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
264     /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
265     /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
266     /// [`Duration`]: ../../std/time/struct.Duration.html
267     ///
268     /// # Examples
269     ///
270     /// ```no_run
271     /// use std::net::TcpStream;
272     ///
273     /// let stream = TcpStream::connect("127.0.0.1:8080")
274     ///                        .expect("Couldn't connect to the server...");
275     /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
276     /// ```
277     ///
278     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
279     /// method:
280     ///
281     /// ```no_run
282     /// use std::io;
283     /// use std::net::TcpStream;
284     /// use std::time::Duration;
285     ///
286     /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
287     /// let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
288     /// let err = result.unwrap_err();
289     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
290     /// ```
291     #[stable(feature = "socket_timeout", since = "1.4.0")]
292     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
293         self.0.set_read_timeout(dur)
294     }
295
296     /// Sets the write timeout to the timeout specified.
297     ///
298     /// If the value specified is [`None`], then [`write`] calls will block
299     /// indefinitely. An [`Err`] is returned if the zero [`Duration`] is
300     /// passed to this method.
301     ///
302     /// # Platform-specific behavior
303     ///
304     /// Platforms may return a different error code whenever a write times out
305     /// as a result of setting this option. For example Unix typically returns
306     /// an error of the kind [`WouldBlock`], but Windows may return [`TimedOut`].
307     ///
308     /// [`None`]: ../../std/option/enum.Option.html#variant.None
309     /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
310     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
311     /// [`Duration`]: ../../std/time/struct.Duration.html
312     /// [`WouldBlock`]: ../../std/io/enum.ErrorKind.html#variant.WouldBlock
313     /// [`TimedOut`]: ../../std/io/enum.ErrorKind.html#variant.TimedOut
314     ///
315     /// # Examples
316     ///
317     /// ```no_run
318     /// use std::net::TcpStream;
319     ///
320     /// let stream = TcpStream::connect("127.0.0.1:8080")
321     ///                        .expect("Couldn't connect to the server...");
322     /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
323     /// ```
324     ///
325     /// An [`Err`] is returned if the zero [`Duration`] is passed to this
326     /// method:
327     ///
328     /// ```no_run
329     /// use std::io;
330     /// use std::net::TcpStream;
331     /// use std::time::Duration;
332     ///
333     /// let stream = TcpStream::connect("127.0.0.1:8080").unwrap();
334     /// let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
335     /// let err = result.unwrap_err();
336     /// assert_eq!(err.kind(), io::ErrorKind::InvalidInput)
337     /// ```
338     #[stable(feature = "socket_timeout", since = "1.4.0")]
339     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
340         self.0.set_write_timeout(dur)
341     }
342
343     /// Returns the read timeout of this socket.
344     ///
345     /// If the timeout is [`None`], then [`read`] calls will block indefinitely.
346     ///
347     /// # Platform-specific behavior
348     ///
349     /// Some platforms do not provide access to the current timeout.
350     ///
351     /// [`None`]: ../../std/option/enum.Option.html#variant.None
352     /// [`read`]: ../../std/io/trait.Read.html#tymethod.read
353     ///
354     /// # Examples
355     ///
356     /// ```no_run
357     /// use std::net::TcpStream;
358     ///
359     /// let stream = TcpStream::connect("127.0.0.1:8080")
360     ///                        .expect("Couldn't connect to the server...");
361     /// stream.set_read_timeout(None).expect("set_read_timeout call failed");
362     /// assert_eq!(stream.read_timeout().unwrap(), None);
363     /// ```
364     #[stable(feature = "socket_timeout", since = "1.4.0")]
365     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
366         self.0.read_timeout()
367     }
368
369     /// Returns the write timeout of this socket.
370     ///
371     /// If the timeout is [`None`], then [`write`] calls will block indefinitely.
372     ///
373     /// # Platform-specific behavior
374     ///
375     /// Some platforms do not provide access to the current timeout.
376     ///
377     /// [`None`]: ../../std/option/enum.Option.html#variant.None
378     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
379     ///
380     /// # Examples
381     ///
382     /// ```no_run
383     /// use std::net::TcpStream;
384     ///
385     /// let stream = TcpStream::connect("127.0.0.1:8080")
386     ///                        .expect("Couldn't connect to the server...");
387     /// stream.set_write_timeout(None).expect("set_write_timeout call failed");
388     /// assert_eq!(stream.write_timeout().unwrap(), None);
389     /// ```
390     #[stable(feature = "socket_timeout", since = "1.4.0")]
391     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
392         self.0.write_timeout()
393     }
394
395     /// Receives data on the socket from the remote address to which it is
396     /// connected, without removing that data from the queue. On success,
397     /// returns the number of bytes peeked.
398     ///
399     /// Successive calls return the same data. This is accomplished by passing
400     /// `MSG_PEEK` as a flag to the underlying `recv` system call.
401     ///
402     /// # Examples
403     ///
404     /// ```no_run
405     /// use std::net::TcpStream;
406     ///
407     /// let stream = TcpStream::connect("127.0.0.1:8000")
408     ///                        .expect("couldn't bind to address");
409     /// let mut buf = [0; 10];
410     /// let len = stream.peek(&mut buf).expect("peek failed");
411     /// ```
412     #[stable(feature = "peek", since = "1.18.0")]
413     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
414         self.0.peek(buf)
415     }
416
417     /// Sets the value of the `TCP_NODELAY` option on this socket.
418     ///
419     /// If set, this option disables the Nagle algorithm. This means that
420     /// segments are always sent as soon as possible, even if there is only a
421     /// small amount of data. When not set, data is buffered until there is a
422     /// sufficient amount to send out, thereby avoiding the frequent sending of
423     /// small packets.
424     ///
425     /// # Examples
426     ///
427     /// ```no_run
428     /// use std::net::TcpStream;
429     ///
430     /// let stream = TcpStream::connect("127.0.0.1:8080")
431     ///                        .expect("Couldn't connect to the server...");
432     /// stream.set_nodelay(true).expect("set_nodelay call failed");
433     /// ```
434     #[stable(feature = "net2_mutators", since = "1.9.0")]
435     pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
436         self.0.set_nodelay(nodelay)
437     }
438
439     /// Gets the value of the `TCP_NODELAY` option on this socket.
440     ///
441     /// For more information about this option, see [`set_nodelay`][link].
442     ///
443     /// [link]: #method.set_nodelay
444     ///
445     /// # Examples
446     ///
447     /// ```no_run
448     /// use std::net::TcpStream;
449     ///
450     /// let stream = TcpStream::connect("127.0.0.1:8080")
451     ///                        .expect("Couldn't connect to the server...");
452     /// stream.set_nodelay(true).expect("set_nodelay call failed");
453     /// assert_eq!(stream.nodelay().unwrap_or(false), true);
454     /// ```
455     #[stable(feature = "net2_mutators", since = "1.9.0")]
456     pub fn nodelay(&self) -> io::Result<bool> {
457         self.0.nodelay()
458     }
459
460     /// Sets the value for the `IP_TTL` option on this socket.
461     ///
462     /// This value sets the time-to-live field that is used in every packet sent
463     /// from this socket.
464     ///
465     /// # Examples
466     ///
467     /// ```no_run
468     /// use std::net::TcpStream;
469     ///
470     /// let stream = TcpStream::connect("127.0.0.1:8080")
471     ///                        .expect("Couldn't connect to the server...");
472     /// stream.set_ttl(100).expect("set_ttl call failed");
473     /// ```
474     #[stable(feature = "net2_mutators", since = "1.9.0")]
475     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
476         self.0.set_ttl(ttl)
477     }
478
479     /// Gets the value of the `IP_TTL` option for this socket.
480     ///
481     /// For more information about this option, see [`set_ttl`][link].
482     ///
483     /// [link]: #method.set_ttl
484     ///
485     /// # Examples
486     ///
487     /// ```no_run
488     /// use std::net::TcpStream;
489     ///
490     /// let stream = TcpStream::connect("127.0.0.1:8080")
491     ///                        .expect("Couldn't connect to the server...");
492     /// stream.set_ttl(100).expect("set_ttl call failed");
493     /// assert_eq!(stream.ttl().unwrap_or(0), 100);
494     /// ```
495     #[stable(feature = "net2_mutators", since = "1.9.0")]
496     pub fn ttl(&self) -> io::Result<u32> {
497         self.0.ttl()
498     }
499
500     /// Gets the value of the `SO_ERROR` option on this socket.
501     ///
502     /// This will retrieve the stored error in the underlying socket, clearing
503     /// the field in the process. This can be useful for checking errors between
504     /// calls.
505     ///
506     /// # Examples
507     ///
508     /// ```no_run
509     /// use std::net::TcpStream;
510     ///
511     /// let stream = TcpStream::connect("127.0.0.1:8080")
512     ///                        .expect("Couldn't connect to the server...");
513     /// stream.take_error().expect("No error was expected...");
514     /// ```
515     #[stable(feature = "net2_mutators", since = "1.9.0")]
516     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
517         self.0.take_error()
518     }
519
520     /// Moves this TCP stream into or out of nonblocking mode.
521     ///
522     /// This will result in `read`, `write`, `recv` and `send` operations
523     /// becoming nonblocking, i.e., immediately returning from their calls.
524     /// If the IO operation is successful, `Ok` is returned and no further
525     /// action is required. If the IO operation could not be completed and needs
526     /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is
527     /// returned.
528     ///
529     /// On Unix platforms, calling this method corresponds to calling `fcntl`
530     /// `FIONBIO`. On Windows calling this method corresponds to calling
531     /// `ioctlsocket` `FIONBIO`.
532     ///
533     /// # Examples
534     ///
535     /// Reading bytes from a TCP stream in non-blocking mode:
536     ///
537     /// ```no_run
538     /// use std::io::{self, Read};
539     /// use std::net::TcpStream;
540     ///
541     /// let mut stream = TcpStream::connect("127.0.0.1:7878")
542     ///     .expect("Couldn't connect to the server...");
543     /// stream.set_nonblocking(true).expect("set_nonblocking call failed");
544     ///
545     /// # fn wait_for_fd() { unimplemented!() }
546     /// let mut buf = vec![];
547     /// loop {
548     ///     match stream.read_to_end(&mut buf) {
549     ///         Ok(_) => break,
550     ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
551     ///             // wait until network socket is ready, typically implemented
552     ///             // via platform-specific APIs such as epoll or IOCP
553     ///             wait_for_fd();
554     ///         }
555     ///         Err(e) => panic!("encountered IO error: {}", e),
556     ///     };
557     /// };
558     /// println!("bytes: {:?}", buf);
559     /// ```
560     ///
561     /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
562     #[stable(feature = "net2_mutators", since = "1.9.0")]
563     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
564         self.0.set_nonblocking(nonblocking)
565     }
566 }
567
568 #[stable(feature = "rust1", since = "1.0.0")]
569 impl Read for TcpStream {
570     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
571
572     fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> io::Result<usize> {
573         self.0.read_vectored(bufs)
574     }
575
576     #[inline]
577     unsafe fn initializer(&self) -> Initializer {
578         Initializer::nop()
579     }
580 }
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl Write for TcpStream {
583     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
584
585     fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> io::Result<usize> {
586         self.0.write_vectored(bufs)
587     }
588
589     fn flush(&mut self) -> io::Result<()> { Ok(()) }
590 }
591 #[stable(feature = "rust1", since = "1.0.0")]
592 impl Read for &TcpStream {
593     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
594
595     fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> io::Result<usize> {
596         self.0.read_vectored(bufs)
597     }
598
599     #[inline]
600     unsafe fn initializer(&self) -> Initializer {
601         Initializer::nop()
602     }
603 }
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl Write for &TcpStream {
606     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
607
608     fn write_vectored(&mut self, bufs: &[IoVec<'_>]) -> io::Result<usize> {
609         self.0.write_vectored(bufs)
610     }
611
612     fn flush(&mut self) -> io::Result<()> { Ok(()) }
613 }
614
615 impl AsInner<net_imp::TcpStream> for TcpStream {
616     fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
617 }
618
619 impl FromInner<net_imp::TcpStream> for TcpStream {
620     fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
621 }
622
623 impl IntoInner<net_imp::TcpStream> for TcpStream {
624     fn into_inner(self) -> net_imp::TcpStream { self.0 }
625 }
626
627 #[stable(feature = "rust1", since = "1.0.0")]
628 impl fmt::Debug for TcpStream {
629     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
630         self.0.fmt(f)
631     }
632 }
633
634 impl TcpListener {
635     /// Creates a new `TcpListener` which will be bound to the specified
636     /// address.
637     ///
638     /// The returned listener is ready for accepting connections.
639     ///
640     /// Binding with a port number of 0 will request that the OS assigns a port
641     /// to this listener. The port allocated can be queried via the
642     /// [`local_addr`] method.
643     ///
644     /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
645     /// its documentation for concrete examples.
646     ///
647     /// If `addr` yields multiple addresses, `bind` will be attempted with
648     /// each of the addresses until one succeeds and returns the listener. If
649     /// none of the addresses succeed in creating a listener, the error returned
650     /// from the last attempt (the last address) is returned.
651     ///
652     /// [`local_addr`]: #method.local_addr
653     /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
654     ///
655     /// # Examples
656     ///
657     /// Creates a TCP listener bound to `127.0.0.1:80`:
658     ///
659     /// ```no_run
660     /// use std::net::TcpListener;
661     ///
662     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
663     /// ```
664     ///
665     /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
666     /// TCP listener bound to `127.0.0.1:443`:
667     ///
668     /// ```no_run
669     /// use std::net::{SocketAddr, TcpListener};
670     ///
671     /// let addrs = [
672     ///     SocketAddr::from(([127, 0, 0, 1], 80)),
673     ///     SocketAddr::from(([127, 0, 0, 1], 443)),
674     /// ];
675     /// let listener = TcpListener::bind(&addrs[..]).unwrap();
676     /// ```
677     #[stable(feature = "rust1", since = "1.0.0")]
678     pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
679         super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
680     }
681
682     /// Returns the local socket address of this listener.
683     ///
684     /// # Examples
685     ///
686     /// ```no_run
687     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
688     ///
689     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
690     /// assert_eq!(listener.local_addr().unwrap(),
691     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
692     /// ```
693     #[stable(feature = "rust1", since = "1.0.0")]
694     pub fn local_addr(&self) -> io::Result<SocketAddr> {
695         self.0.socket_addr()
696     }
697
698     /// Creates a new independently owned handle to the underlying socket.
699     ///
700     /// The returned [`TcpListener`] is a reference to the same socket that this
701     /// object references. Both handles can be used to accept incoming
702     /// connections and options set on one listener will affect the other.
703     ///
704     /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
705     ///
706     /// # Examples
707     ///
708     /// ```no_run
709     /// use std::net::TcpListener;
710     ///
711     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
712     /// let listener_clone = listener.try_clone().unwrap();
713     /// ```
714     #[stable(feature = "rust1", since = "1.0.0")]
715     pub fn try_clone(&self) -> io::Result<TcpListener> {
716         self.0.duplicate().map(TcpListener)
717     }
718
719     /// Accept a new incoming connection from this listener.
720     ///
721     /// This function will block the calling thread until a new TCP connection
722     /// is established. When established, the corresponding [`TcpStream`] and the
723     /// remote peer's address will be returned.
724     ///
725     /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
726     ///
727     /// # Examples
728     ///
729     /// ```no_run
730     /// use std::net::TcpListener;
731     ///
732     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
733     /// match listener.accept() {
734     ///     Ok((_socket, addr)) => println!("new client: {:?}", addr),
735     ///     Err(e) => println!("couldn't get client: {:?}", e),
736     /// }
737     /// ```
738     #[stable(feature = "rust1", since = "1.0.0")]
739     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
740         // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
741         // the `a` variable here is technically unused.
742         #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
743         self.0.accept().map(|(a, b)| (TcpStream(a), b))
744     }
745
746     /// Returns an iterator over the connections being received on this
747     /// listener.
748     ///
749     /// The returned iterator will never return [`None`] and will also not yield
750     /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
751     /// calling [`accept`] in a loop.
752     ///
753     /// [`None`]: ../../std/option/enum.Option.html#variant.None
754     /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
755     /// [`accept`]: #method.accept
756     ///
757     /// # Examples
758     ///
759     /// ```no_run
760     /// use std::net::TcpListener;
761     ///
762     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
763     ///
764     /// for stream in listener.incoming() {
765     ///     match stream {
766     ///         Ok(stream) => {
767     ///             println!("new client!");
768     ///         }
769     ///         Err(e) => { /* connection failed */ }
770     ///     }
771     /// }
772     /// ```
773     #[stable(feature = "rust1", since = "1.0.0")]
774     pub fn incoming(&self) -> Incoming {
775         Incoming { listener: self }
776     }
777
778     /// Sets the value for the `IP_TTL` option on this socket.
779     ///
780     /// This value sets the time-to-live field that is used in every packet sent
781     /// from this socket.
782     ///
783     /// # Examples
784     ///
785     /// ```no_run
786     /// use std::net::TcpListener;
787     ///
788     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
789     /// listener.set_ttl(100).expect("could not set TTL");
790     /// ```
791     #[stable(feature = "net2_mutators", since = "1.9.0")]
792     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
793         self.0.set_ttl(ttl)
794     }
795
796     /// Gets the value of the `IP_TTL` option for this socket.
797     ///
798     /// For more information about this option, see [`set_ttl`][link].
799     ///
800     /// [link]: #method.set_ttl
801     ///
802     /// # Examples
803     ///
804     /// ```no_run
805     /// use std::net::TcpListener;
806     ///
807     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
808     /// listener.set_ttl(100).expect("could not set TTL");
809     /// assert_eq!(listener.ttl().unwrap_or(0), 100);
810     /// ```
811     #[stable(feature = "net2_mutators", since = "1.9.0")]
812     pub fn ttl(&self) -> io::Result<u32> {
813         self.0.ttl()
814     }
815
816     #[stable(feature = "net2_mutators", since = "1.9.0")]
817     #[rustc_deprecated(since = "1.16.0",
818                        reason = "this option can only be set before the socket is bound")]
819     #[allow(missing_docs)]
820     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
821         self.0.set_only_v6(only_v6)
822     }
823
824     #[stable(feature = "net2_mutators", since = "1.9.0")]
825     #[rustc_deprecated(since = "1.16.0",
826                        reason = "this option can only be set before the socket is bound")]
827     #[allow(missing_docs)]
828     pub fn only_v6(&self) -> io::Result<bool> {
829         self.0.only_v6()
830     }
831
832     /// Gets the value of the `SO_ERROR` option on this socket.
833     ///
834     /// This will retrieve the stored error in the underlying socket, clearing
835     /// the field in the process. This can be useful for checking errors between
836     /// calls.
837     ///
838     /// # Examples
839     ///
840     /// ```no_run
841     /// use std::net::TcpListener;
842     ///
843     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
844     /// listener.take_error().expect("No error was expected");
845     /// ```
846     #[stable(feature = "net2_mutators", since = "1.9.0")]
847     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
848         self.0.take_error()
849     }
850
851     /// Moves this TCP stream into or out of nonblocking mode.
852     ///
853     /// This will result in the `accept` operation becoming nonblocking,
854     /// i.e., immediately returning from their calls. If the IO operation is
855     /// successful, `Ok` is returned and no further action is required. If the
856     /// IO operation could not be completed and needs to be retried, an error
857     /// with kind [`io::ErrorKind::WouldBlock`] is returned.
858     ///
859     /// On Unix platforms, calling this method corresponds to calling `fcntl`
860     /// `FIONBIO`. On Windows calling this method corresponds to calling
861     /// `ioctlsocket` `FIONBIO`.
862     ///
863     /// # Examples
864     ///
865     /// Bind a TCP listener to an address, listen for connections, and read
866     /// bytes in nonblocking mode:
867     ///
868     /// ```no_run
869     /// use std::io;
870     /// use std::net::TcpListener;
871     ///
872     /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
873     /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
874     ///
875     /// # fn wait_for_fd() { unimplemented!() }
876     /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
877     /// for stream in listener.incoming() {
878     ///     match stream {
879     ///         Ok(s) => {
880     ///             // do something with the TcpStream
881     ///             handle_connection(s);
882     ///         }
883     ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
884     ///             // wait until network socket is ready, typically implemented
885     ///             // via platform-specific APIs such as epoll or IOCP
886     ///             wait_for_fd();
887     ///             continue;
888     ///         }
889     ///         Err(e) => panic!("encountered IO error: {}", e),
890     ///     }
891     /// }
892     /// ```
893     ///
894     /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
895     #[stable(feature = "net2_mutators", since = "1.9.0")]
896     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
897         self.0.set_nonblocking(nonblocking)
898     }
899 }
900
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a> Iterator for Incoming<'a> {
903     type Item = io::Result<TcpStream>;
904     fn next(&mut self) -> Option<io::Result<TcpStream>> {
905         Some(self.listener.accept().map(|p| p.0))
906     }
907 }
908
909 impl AsInner<net_imp::TcpListener> for TcpListener {
910     fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
911 }
912
913 impl FromInner<net_imp::TcpListener> for TcpListener {
914     fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
915         TcpListener(inner)
916     }
917 }
918
919 impl IntoInner<net_imp::TcpListener> for TcpListener {
920     fn into_inner(self) -> net_imp::TcpListener { self.0 }
921 }
922
923 #[stable(feature = "rust1", since = "1.0.0")]
924 impl fmt::Debug for TcpListener {
925     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
926         self.0.fmt(f)
927     }
928 }
929
930 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
931 mod tests {
932     use crate::fmt;
933     use crate::io::{ErrorKind, IoVec, IoVecMut};
934     use crate::io::prelude::*;
935     use crate::net::*;
936     use crate::net::test::{next_test_ip4, next_test_ip6};
937     use crate::sync::mpsc::channel;
938     use crate::time::{Instant, Duration};
939     use crate::thread;
940
941     fn each_ip(f: &mut dyn FnMut(SocketAddr)) {
942         f(next_test_ip4());
943         f(next_test_ip6());
944     }
945
946     macro_rules! t {
947         ($e:expr) => {
948             match $e {
949                 Ok(t) => t,
950                 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
951             }
952         }
953     }
954
955     #[test]
956     fn bind_error() {
957         match TcpListener::bind("1.1.1.1:9999") {
958             Ok(..) => panic!(),
959             Err(e) =>
960                 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
961         }
962     }
963
964     #[test]
965     fn connect_error() {
966         match TcpStream::connect("0.0.0.0:1") {
967             Ok(..) => panic!(),
968             Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
969                               e.kind() == ErrorKind::InvalidInput ||
970                               e.kind() == ErrorKind::AddrInUse ||
971                               e.kind() == ErrorKind::AddrNotAvailable,
972                               "bad error: {} {:?}", e, e.kind()),
973         }
974     }
975
976     #[test]
977     fn listen_localhost() {
978         let socket_addr = next_test_ip4();
979         let listener = t!(TcpListener::bind(&socket_addr));
980
981         let _t = thread::spawn(move || {
982             let mut stream = t!(TcpStream::connect(&("localhost",
983                                                      socket_addr.port())));
984             t!(stream.write(&[144]));
985         });
986
987         let mut stream = t!(listener.accept()).0;
988         let mut buf = [0];
989         t!(stream.read(&mut buf));
990         assert!(buf[0] == 144);
991     }
992
993     #[test]
994     fn connect_loopback() {
995         each_ip(&mut |addr| {
996             let acceptor = t!(TcpListener::bind(&addr));
997
998             let _t = thread::spawn(move|| {
999                 let host = match addr {
1000                     SocketAddr::V4(..) => "127.0.0.1",
1001                     SocketAddr::V6(..) => "::1",
1002                 };
1003                 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
1004                 t!(stream.write(&[66]));
1005             });
1006
1007             let mut stream = t!(acceptor.accept()).0;
1008             let mut buf = [0];
1009             t!(stream.read(&mut buf));
1010             assert!(buf[0] == 66);
1011         })
1012     }
1013
1014     #[test]
1015     fn smoke_test() {
1016         each_ip(&mut |addr| {
1017             let acceptor = t!(TcpListener::bind(&addr));
1018
1019             let (tx, rx) = channel();
1020             let _t = thread::spawn(move|| {
1021                 let mut stream = t!(TcpStream::connect(&addr));
1022                 t!(stream.write(&[99]));
1023                 tx.send(t!(stream.local_addr())).unwrap();
1024             });
1025
1026             let (mut stream, addr) = t!(acceptor.accept());
1027             let mut buf = [0];
1028             t!(stream.read(&mut buf));
1029             assert!(buf[0] == 99);
1030             assert_eq!(addr, t!(rx.recv()));
1031         })
1032     }
1033
1034     #[test]
1035     fn read_eof() {
1036         each_ip(&mut |addr| {
1037             let acceptor = t!(TcpListener::bind(&addr));
1038
1039             let _t = thread::spawn(move|| {
1040                 let _stream = t!(TcpStream::connect(&addr));
1041                 // Close
1042             });
1043
1044             let mut stream = t!(acceptor.accept()).0;
1045             let mut buf = [0];
1046             let nread = t!(stream.read(&mut buf));
1047             assert_eq!(nread, 0);
1048             let nread = t!(stream.read(&mut buf));
1049             assert_eq!(nread, 0);
1050         })
1051     }
1052
1053     #[test]
1054     fn write_close() {
1055         each_ip(&mut |addr| {
1056             let acceptor = t!(TcpListener::bind(&addr));
1057
1058             let (tx, rx) = channel();
1059             let _t = thread::spawn(move|| {
1060                 drop(t!(TcpStream::connect(&addr)));
1061                 tx.send(()).unwrap();
1062             });
1063
1064             let mut stream = t!(acceptor.accept()).0;
1065             rx.recv().unwrap();
1066             let buf = [0];
1067             match stream.write(&buf) {
1068                 Ok(..) => {}
1069                 Err(e) => {
1070                     assert!(e.kind() == ErrorKind::ConnectionReset ||
1071                             e.kind() == ErrorKind::BrokenPipe ||
1072                             e.kind() == ErrorKind::ConnectionAborted,
1073                             "unknown error: {}", e);
1074                 }
1075             }
1076         })
1077     }
1078
1079     #[test]
1080     fn multiple_connect_serial() {
1081         each_ip(&mut |addr| {
1082             let max = 10;
1083             let acceptor = t!(TcpListener::bind(&addr));
1084
1085             let _t = thread::spawn(move|| {
1086                 for _ in 0..max {
1087                     let mut stream = t!(TcpStream::connect(&addr));
1088                     t!(stream.write(&[99]));
1089                 }
1090             });
1091
1092             for stream in acceptor.incoming().take(max) {
1093                 let mut stream = t!(stream);
1094                 let mut buf = [0];
1095                 t!(stream.read(&mut buf));
1096                 assert_eq!(buf[0], 99);
1097             }
1098         })
1099     }
1100
1101     #[test]
1102     fn multiple_connect_interleaved_greedy_schedule() {
1103         const MAX: usize = 10;
1104         each_ip(&mut |addr| {
1105             let acceptor = t!(TcpListener::bind(&addr));
1106
1107             let _t = thread::spawn(move|| {
1108                 let acceptor = acceptor;
1109                 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
1110                     // Start another thread to handle the connection
1111                     let _t = thread::spawn(move|| {
1112                         let mut stream = t!(stream);
1113                         let mut buf = [0];
1114                         t!(stream.read(&mut buf));
1115                         assert!(buf[0] == i as u8);
1116                     });
1117                 }
1118             });
1119
1120             connect(0, addr);
1121         });
1122
1123         fn connect(i: usize, addr: SocketAddr) {
1124             if i == MAX { return }
1125
1126             let t = thread::spawn(move|| {
1127                 let mut stream = t!(TcpStream::connect(&addr));
1128                 // Connect again before writing
1129                 connect(i + 1, addr);
1130                 t!(stream.write(&[i as u8]));
1131             });
1132             t.join().ok().expect("thread panicked");
1133         }
1134     }
1135
1136     #[test]
1137     fn multiple_connect_interleaved_lazy_schedule() {
1138         const MAX: usize = 10;
1139         each_ip(&mut |addr| {
1140             let acceptor = t!(TcpListener::bind(&addr));
1141
1142             let _t = thread::spawn(move|| {
1143                 for stream in acceptor.incoming().take(MAX) {
1144                     // Start another thread to handle the connection
1145                     let _t = thread::spawn(move|| {
1146                         let mut stream = t!(stream);
1147                         let mut buf = [0];
1148                         t!(stream.read(&mut buf));
1149                         assert!(buf[0] == 99);
1150                     });
1151                 }
1152             });
1153
1154             connect(0, addr);
1155         });
1156
1157         fn connect(i: usize, addr: SocketAddr) {
1158             if i == MAX { return }
1159
1160             let t = thread::spawn(move|| {
1161                 let mut stream = t!(TcpStream::connect(&addr));
1162                 connect(i + 1, addr);
1163                 t!(stream.write(&[99]));
1164             });
1165             t.join().ok().expect("thread panicked");
1166         }
1167     }
1168
1169     #[test]
1170     fn socket_and_peer_name() {
1171         each_ip(&mut |addr| {
1172             let listener = t!(TcpListener::bind(&addr));
1173             let so_name = t!(listener.local_addr());
1174             assert_eq!(addr, so_name);
1175             let _t = thread::spawn(move|| {
1176                 t!(listener.accept());
1177             });
1178
1179             let stream = t!(TcpStream::connect(&addr));
1180             assert_eq!(addr, t!(stream.peer_addr()));
1181         })
1182     }
1183
1184     #[test]
1185     fn partial_read() {
1186         each_ip(&mut |addr| {
1187             let (tx, rx) = channel();
1188             let srv = t!(TcpListener::bind(&addr));
1189             let _t = thread::spawn(move|| {
1190                 let mut cl = t!(srv.accept()).0;
1191                 cl.write(&[10]).unwrap();
1192                 let mut b = [0];
1193                 t!(cl.read(&mut b));
1194                 tx.send(()).unwrap();
1195             });
1196
1197             let mut c = t!(TcpStream::connect(&addr));
1198             let mut b = [0; 10];
1199             assert_eq!(c.read(&mut b).unwrap(), 1);
1200             t!(c.write(&[1]));
1201             rx.recv().unwrap();
1202         })
1203     }
1204
1205     #[test]
1206     fn read_vectored() {
1207         each_ip(&mut |addr| {
1208             let srv = t!(TcpListener::bind(&addr));
1209             let mut s1 = t!(TcpStream::connect(&addr));
1210             let mut s2 = t!(srv.accept()).0;
1211
1212             let len = s1.write(&[10, 11, 12]).unwrap();
1213             assert_eq!(len, 3);
1214
1215             let mut a = [];
1216             let mut b = [0];
1217             let mut c = [0; 3];
1218             let len = t!(s2.read_vectored(
1219                 &mut [IoVecMut::new(&mut a), IoVecMut::new(&mut b), IoVecMut::new(&mut c)],
1220             ));
1221             assert!(len > 0);
1222             assert_eq!(b, [10]);
1223             // some implementations don't support readv, so we may only fill the first buffer
1224             assert!(len == 1 || c == [11, 12, 0]);
1225         })
1226     }
1227
1228     #[test]
1229     fn write_vectored() {
1230         each_ip(&mut |addr| {
1231             let srv = t!(TcpListener::bind(&addr));
1232             let mut s1 = t!(TcpStream::connect(&addr));
1233             let mut s2 = t!(srv.accept()).0;
1234
1235             let a = [];
1236             let b = [10];
1237             let c = [11, 12];
1238             t!(s1.write_vectored(&[IoVec::new(&a), IoVec::new(&b), IoVec::new(&c)]));
1239
1240             let mut buf = [0; 4];
1241             let len = t!(s2.read(&mut buf));
1242             // some implementations don't support writev, so we may only write the first buffer
1243             if len == 1 {
1244                 assert_eq!(buf, [10, 0, 0, 0]);
1245             } else {
1246                 assert_eq!(len, 3);
1247                 assert_eq!(buf, [10, 11, 12, 0]);
1248             }
1249         })
1250     }
1251
1252     #[test]
1253     fn double_bind() {
1254         each_ip(&mut |addr| {
1255             let listener1 = t!(TcpListener::bind(&addr));
1256             match TcpListener::bind(&addr) {
1257                 Ok(listener2) => panic!(
1258                     "This system (perhaps due to options set by TcpListener::bind) \
1259                      permits double binding: {:?} and {:?}",
1260                     listener1, listener2
1261                 ),
1262                 Err(e) => {
1263                     assert!(e.kind() == ErrorKind::ConnectionRefused ||
1264                             e.kind() == ErrorKind::Other ||
1265                             e.kind() == ErrorKind::AddrInUse,
1266                             "unknown error: {} {:?}", e, e.kind());
1267                 }
1268             }
1269         })
1270     }
1271
1272     #[test]
1273     fn fast_rebind() {
1274         each_ip(&mut |addr| {
1275             let acceptor = t!(TcpListener::bind(&addr));
1276
1277             let _t = thread::spawn(move|| {
1278                 t!(TcpStream::connect(&addr));
1279             });
1280
1281             t!(acceptor.accept());
1282             drop(acceptor);
1283             t!(TcpListener::bind(&addr));
1284         });
1285     }
1286
1287     #[test]
1288     fn tcp_clone_smoke() {
1289         each_ip(&mut |addr| {
1290             let acceptor = t!(TcpListener::bind(&addr));
1291
1292             let _t = thread::spawn(move|| {
1293                 let mut s = t!(TcpStream::connect(&addr));
1294                 let mut buf = [0, 0];
1295                 assert_eq!(s.read(&mut buf).unwrap(), 1);
1296                 assert_eq!(buf[0], 1);
1297                 t!(s.write(&[2]));
1298             });
1299
1300             let mut s1 = t!(acceptor.accept()).0;
1301             let s2 = t!(s1.try_clone());
1302
1303             let (tx1, rx1) = channel();
1304             let (tx2, rx2) = channel();
1305             let _t = thread::spawn(move|| {
1306                 let mut s2 = s2;
1307                 rx1.recv().unwrap();
1308                 t!(s2.write(&[1]));
1309                 tx2.send(()).unwrap();
1310             });
1311             tx1.send(()).unwrap();
1312             let mut buf = [0, 0];
1313             assert_eq!(s1.read(&mut buf).unwrap(), 1);
1314             rx2.recv().unwrap();
1315         })
1316     }
1317
1318     #[test]
1319     fn tcp_clone_two_read() {
1320         each_ip(&mut |addr| {
1321             let acceptor = t!(TcpListener::bind(&addr));
1322             let (tx1, rx) = channel();
1323             let tx2 = tx1.clone();
1324
1325             let _t = thread::spawn(move|| {
1326                 let mut s = t!(TcpStream::connect(&addr));
1327                 t!(s.write(&[1]));
1328                 rx.recv().unwrap();
1329                 t!(s.write(&[2]));
1330                 rx.recv().unwrap();
1331             });
1332
1333             let mut s1 = t!(acceptor.accept()).0;
1334             let s2 = t!(s1.try_clone());
1335
1336             let (done, rx) = channel();
1337             let _t = thread::spawn(move|| {
1338                 let mut s2 = s2;
1339                 let mut buf = [0, 0];
1340                 t!(s2.read(&mut buf));
1341                 tx2.send(()).unwrap();
1342                 done.send(()).unwrap();
1343             });
1344             let mut buf = [0, 0];
1345             t!(s1.read(&mut buf));
1346             tx1.send(()).unwrap();
1347
1348             rx.recv().unwrap();
1349         })
1350     }
1351
1352     #[test]
1353     fn tcp_clone_two_write() {
1354         each_ip(&mut |addr| {
1355             let acceptor = t!(TcpListener::bind(&addr));
1356
1357             let _t = thread::spawn(move|| {
1358                 let mut s = t!(TcpStream::connect(&addr));
1359                 let mut buf = [0, 1];
1360                 t!(s.read(&mut buf));
1361                 t!(s.read(&mut buf));
1362             });
1363
1364             let mut s1 = t!(acceptor.accept()).0;
1365             let s2 = t!(s1.try_clone());
1366
1367             let (done, rx) = channel();
1368             let _t = thread::spawn(move|| {
1369                 let mut s2 = s2;
1370                 t!(s2.write(&[1]));
1371                 done.send(()).unwrap();
1372             });
1373             t!(s1.write(&[2]));
1374
1375             rx.recv().unwrap();
1376         })
1377     }
1378
1379     #[test]
1380     // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1381     #[cfg_attr(target_env = "sgx", ignore)]
1382     fn shutdown_smoke() {
1383         each_ip(&mut |addr| {
1384             let a = t!(TcpListener::bind(&addr));
1385             let _t = thread::spawn(move|| {
1386                 let mut c = t!(a.accept()).0;
1387                 let mut b = [0];
1388                 assert_eq!(c.read(&mut b).unwrap(), 0);
1389                 t!(c.write(&[1]));
1390             });
1391
1392             let mut s = t!(TcpStream::connect(&addr));
1393             t!(s.shutdown(Shutdown::Write));
1394             assert!(s.write(&[1]).is_err());
1395             let mut b = [0, 0];
1396             assert_eq!(t!(s.read(&mut b)), 1);
1397             assert_eq!(b[0], 1);
1398         })
1399     }
1400
1401     #[test]
1402     // FIXME: https://github.com/fortanix/rust-sgx/issues/110
1403     #[cfg_attr(target_env = "sgx", ignore)]
1404     fn close_readwrite_smoke() {
1405         each_ip(&mut |addr| {
1406             let a = t!(TcpListener::bind(&addr));
1407             let (tx, rx) = channel::<()>();
1408             let _t = thread::spawn(move|| {
1409                 let _s = t!(a.accept());
1410                 let _ = rx.recv();
1411             });
1412
1413             let mut b = [0];
1414             let mut s = t!(TcpStream::connect(&addr));
1415             let mut s2 = t!(s.try_clone());
1416
1417             // closing should prevent reads/writes
1418             t!(s.shutdown(Shutdown::Write));
1419             assert!(s.write(&[0]).is_err());
1420             t!(s.shutdown(Shutdown::Read));
1421             assert_eq!(s.read(&mut b).unwrap(), 0);
1422
1423             // closing should affect previous handles
1424             assert!(s2.write(&[0]).is_err());
1425             assert_eq!(s2.read(&mut b).unwrap(), 0);
1426
1427             // closing should affect new handles
1428             let mut s3 = t!(s.try_clone());
1429             assert!(s3.write(&[0]).is_err());
1430             assert_eq!(s3.read(&mut b).unwrap(), 0);
1431
1432             // make sure these don't die
1433             let _ = s2.shutdown(Shutdown::Read);
1434             let _ = s2.shutdown(Shutdown::Write);
1435             let _ = s3.shutdown(Shutdown::Read);
1436             let _ = s3.shutdown(Shutdown::Write);
1437             drop(tx);
1438         })
1439     }
1440
1441     #[test]
1442     #[cfg(unix)] // test doesn't work on Windows, see #31657
1443     fn close_read_wakes_up() {
1444         each_ip(&mut |addr| {
1445             let a = t!(TcpListener::bind(&addr));
1446             let (tx1, rx) = channel::<()>();
1447             let _t = thread::spawn(move|| {
1448                 let _s = t!(a.accept());
1449                 let _ = rx.recv();
1450             });
1451
1452             let s = t!(TcpStream::connect(&addr));
1453             let s2 = t!(s.try_clone());
1454             let (tx, rx) = channel();
1455             let _t = thread::spawn(move|| {
1456                 let mut s2 = s2;
1457                 assert_eq!(t!(s2.read(&mut [0])), 0);
1458                 tx.send(()).unwrap();
1459             });
1460             // this should wake up the child thread
1461             t!(s.shutdown(Shutdown::Read));
1462
1463             // this test will never finish if the child doesn't wake up
1464             rx.recv().unwrap();
1465             drop(tx1);
1466         })
1467     }
1468
1469     #[test]
1470     fn clone_while_reading() {
1471         each_ip(&mut |addr| {
1472             let accept = t!(TcpListener::bind(&addr));
1473
1474             // Enqueue a thread to write to a socket
1475             let (tx, rx) = channel();
1476             let (txdone, rxdone) = channel();
1477             let txdone2 = txdone.clone();
1478             let _t = thread::spawn(move|| {
1479                 let mut tcp = t!(TcpStream::connect(&addr));
1480                 rx.recv().unwrap();
1481                 t!(tcp.write(&[0]));
1482                 txdone2.send(()).unwrap();
1483             });
1484
1485             // Spawn off a reading clone
1486             let tcp = t!(accept.accept()).0;
1487             let tcp2 = t!(tcp.try_clone());
1488             let txdone3 = txdone.clone();
1489             let _t = thread::spawn(move|| {
1490                 let mut tcp2 = tcp2;
1491                 t!(tcp2.read(&mut [0]));
1492                 txdone3.send(()).unwrap();
1493             });
1494
1495             // Try to ensure that the reading clone is indeed reading
1496             for _ in 0..50 {
1497                 thread::yield_now();
1498             }
1499
1500             // clone the handle again while it's reading, then let it finish the
1501             // read.
1502             let _ = t!(tcp.try_clone());
1503             tx.send(()).unwrap();
1504             rxdone.recv().unwrap();
1505             rxdone.recv().unwrap();
1506         })
1507     }
1508
1509     #[test]
1510     fn clone_accept_smoke() {
1511         each_ip(&mut |addr| {
1512             let a = t!(TcpListener::bind(&addr));
1513             let a2 = t!(a.try_clone());
1514
1515             let _t = thread::spawn(move|| {
1516                 let _ = TcpStream::connect(&addr);
1517             });
1518             let _t = thread::spawn(move|| {
1519                 let _ = TcpStream::connect(&addr);
1520             });
1521
1522             t!(a.accept());
1523             t!(a2.accept());
1524         })
1525     }
1526
1527     #[test]
1528     fn clone_accept_concurrent() {
1529         each_ip(&mut |addr| {
1530             let a = t!(TcpListener::bind(&addr));
1531             let a2 = t!(a.try_clone());
1532
1533             let (tx, rx) = channel();
1534             let tx2 = tx.clone();
1535
1536             let _t = thread::spawn(move|| {
1537                 tx.send(t!(a.accept())).unwrap();
1538             });
1539             let _t = thread::spawn(move|| {
1540                 tx2.send(t!(a2.accept())).unwrap();
1541             });
1542
1543             let _t = thread::spawn(move|| {
1544                 let _ = TcpStream::connect(&addr);
1545             });
1546             let _t = thread::spawn(move|| {
1547                 let _ = TcpStream::connect(&addr);
1548             });
1549
1550             rx.recv().unwrap();
1551             rx.recv().unwrap();
1552         })
1553     }
1554
1555     #[test]
1556     fn debug() {
1557         #[cfg(not(target_env = "sgx"))]
1558         fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1559             addr
1560         }
1561         #[cfg(target_env = "sgx")]
1562         fn render_socket_addr<'a>(addr: &'a SocketAddr) -> impl fmt::Debug + 'a {
1563             addr.to_string()
1564         }
1565
1566         #[cfg(unix)]
1567         use crate::os::unix::io::AsRawFd;
1568         #[cfg(target_env = "sgx")]
1569         use crate::os::fortanix_sgx::io::AsRawFd;
1570         #[cfg(not(windows))]
1571         fn render_inner(addr: &dyn AsRawFd) -> impl fmt::Debug {
1572             addr.as_raw_fd()
1573         }
1574         #[cfg(windows)]
1575         fn render_inner(addr: &dyn crate::os::windows::io::AsRawSocket) -> impl fmt::Debug {
1576             addr.as_raw_socket()
1577         }
1578
1579         let inner_name = if cfg!(windows) {"socket"} else {"fd"};
1580         let socket_addr = next_test_ip4();
1581
1582         let listener = t!(TcpListener::bind(&socket_addr));
1583         let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
1584                               render_socket_addr(&socket_addr),
1585                               inner_name,
1586                               render_inner(&listener));
1587         assert_eq!(format!("{:?}", listener), compare);
1588
1589         let stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
1590         let compare = format!("TcpStream {{ addr: {:?}, peer: {:?}, {}: {:?} }}",
1591                               render_socket_addr(&stream.local_addr().unwrap()),
1592                               render_socket_addr(&stream.peer_addr().unwrap()),
1593                               inner_name,
1594                               render_inner(&stream));
1595         assert_eq!(format!("{:?}", stream), compare);
1596     }
1597
1598     // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
1599     //        no longer has rounding errors.
1600     #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1601     #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1602     #[test]
1603     fn timeouts() {
1604         let addr = next_test_ip4();
1605         let listener = t!(TcpListener::bind(&addr));
1606
1607         let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1608         let dur = Duration::new(15410, 0);
1609
1610         assert_eq!(None, t!(stream.read_timeout()));
1611
1612         t!(stream.set_read_timeout(Some(dur)));
1613         assert_eq!(Some(dur), t!(stream.read_timeout()));
1614
1615         assert_eq!(None, t!(stream.write_timeout()));
1616
1617         t!(stream.set_write_timeout(Some(dur)));
1618         assert_eq!(Some(dur), t!(stream.write_timeout()));
1619
1620         t!(stream.set_read_timeout(None));
1621         assert_eq!(None, t!(stream.read_timeout()));
1622
1623         t!(stream.set_write_timeout(None));
1624         assert_eq!(None, t!(stream.write_timeout()));
1625         drop(listener);
1626     }
1627
1628     #[test]
1629     #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1630     fn test_read_timeout() {
1631         let addr = next_test_ip4();
1632         let listener = t!(TcpListener::bind(&addr));
1633
1634         let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1635         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1636
1637         let mut buf = [0; 10];
1638         let start = Instant::now();
1639         let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1640         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1641                 "unexpected_error: {:?}", kind);
1642         assert!(start.elapsed() > Duration::from_millis(400));
1643         drop(listener);
1644     }
1645
1646     #[test]
1647     #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1648     fn test_read_with_timeout() {
1649         let addr = next_test_ip4();
1650         let listener = t!(TcpListener::bind(&addr));
1651
1652         let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1653         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1654
1655         let mut other_end = t!(listener.accept()).0;
1656         t!(other_end.write_all(b"hello world"));
1657
1658         let mut buf = [0; 11];
1659         t!(stream.read(&mut buf));
1660         assert_eq!(b"hello world", &buf[..]);
1661
1662         let start = Instant::now();
1663         let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1664         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1665                 "unexpected_error: {:?}", kind);
1666         assert!(start.elapsed() > Duration::from_millis(400));
1667         drop(listener);
1668     }
1669
1670     // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1671     // when passed zero Durations
1672     #[test]
1673     fn test_timeout_zero_duration() {
1674         let addr = next_test_ip4();
1675
1676         let listener = t!(TcpListener::bind(&addr));
1677         let stream = t!(TcpStream::connect(&addr));
1678
1679         let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1680         let err = result.unwrap_err();
1681         assert_eq!(err.kind(), ErrorKind::InvalidInput);
1682
1683         let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1684         let err = result.unwrap_err();
1685         assert_eq!(err.kind(), ErrorKind::InvalidInput);
1686
1687         drop(listener);
1688     }
1689
1690     #[test]
1691     #[cfg_attr(target_env = "sgx", ignore)]
1692     fn nodelay() {
1693         let addr = next_test_ip4();
1694         let _listener = t!(TcpListener::bind(&addr));
1695
1696         let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1697
1698         assert_eq!(false, t!(stream.nodelay()));
1699         t!(stream.set_nodelay(true));
1700         assert_eq!(true, t!(stream.nodelay()));
1701         t!(stream.set_nodelay(false));
1702         assert_eq!(false, t!(stream.nodelay()));
1703     }
1704
1705     #[test]
1706     #[cfg_attr(target_env = "sgx", ignore)]
1707     fn ttl() {
1708         let ttl = 100;
1709
1710         let addr = next_test_ip4();
1711         let listener = t!(TcpListener::bind(&addr));
1712
1713         t!(listener.set_ttl(ttl));
1714         assert_eq!(ttl, t!(listener.ttl()));
1715
1716         let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1717
1718         t!(stream.set_ttl(ttl));
1719         assert_eq!(ttl, t!(stream.ttl()));
1720     }
1721
1722     #[test]
1723     #[cfg_attr(target_env = "sgx", ignore)]
1724     fn set_nonblocking() {
1725         let addr = next_test_ip4();
1726         let listener = t!(TcpListener::bind(&addr));
1727
1728         t!(listener.set_nonblocking(true));
1729         t!(listener.set_nonblocking(false));
1730
1731         let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1732
1733         t!(stream.set_nonblocking(false));
1734         t!(stream.set_nonblocking(true));
1735
1736         let mut buf = [0];
1737         match stream.read(&mut buf) {
1738             Ok(_) => panic!("expected error"),
1739             Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1740             Err(e) => panic!("unexpected error {}", e),
1741         }
1742     }
1743
1744     #[test]
1745     #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1746     fn peek() {
1747         each_ip(&mut |addr| {
1748             let (txdone, rxdone) = channel();
1749
1750             let srv = t!(TcpListener::bind(&addr));
1751             let _t = thread::spawn(move|| {
1752                 let mut cl = t!(srv.accept()).0;
1753                 cl.write(&[1,3,3,7]).unwrap();
1754                 t!(rxdone.recv());
1755             });
1756
1757             let mut c = t!(TcpStream::connect(&addr));
1758             let mut b = [0; 10];
1759             for _ in 1..3 {
1760                 let len = c.peek(&mut b).unwrap();
1761                 assert_eq!(len, 4);
1762             }
1763             let len = c.read(&mut b).unwrap();
1764             assert_eq!(len, 4);
1765
1766             t!(c.set_nonblocking(true));
1767             match c.peek(&mut b) {
1768                 Ok(_) => panic!("expected error"),
1769                 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1770                 Err(e) => panic!("unexpected error {}", e),
1771             }
1772             t!(txdone.send(()));
1773         })
1774     }
1775
1776     #[test]
1777     #[cfg_attr(target_env = "sgx", ignore)] // FIXME: https://github.com/fortanix/rust-sgx/issues/31
1778     fn connect_timeout_valid() {
1779         let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1780         let addr = listener.local_addr().unwrap();
1781         TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();
1782     }
1783 }