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