]> git.lizzy.rs Git - rust.git/blob - src/libstd/net/tcp.rs
Rollup merge of #58137 - ljedrz:cleanup_node_id_to_type, r=estebank
[rust.git] / src / libstd / net / tcp.rs
1 use io::prelude::*;
2
3 use fmt;
4 use io::{self, Initializer};
5 use net::{ToSocketAddrs, SocketAddr, Shutdown};
6 use sys_common::net as net_imp;
7 use sys_common::{AsInner, FromInner, IntoInner};
8 use 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     #[inline]
573     unsafe fn initializer(&self) -> Initializer {
574         Initializer::nop()
575     }
576 }
577 #[stable(feature = "rust1", since = "1.0.0")]
578 impl Write for TcpStream {
579     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
580     fn flush(&mut self) -> io::Result<()> { Ok(()) }
581 }
582 #[stable(feature = "rust1", since = "1.0.0")]
583 impl<'a> Read for &'a TcpStream {
584     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
585
586     #[inline]
587     unsafe fn initializer(&self) -> Initializer {
588         Initializer::nop()
589     }
590 }
591 #[stable(feature = "rust1", since = "1.0.0")]
592 impl<'a> Write for &'a TcpStream {
593     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
594     fn flush(&mut self) -> io::Result<()> { Ok(()) }
595 }
596
597 impl AsInner<net_imp::TcpStream> for TcpStream {
598     fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
599 }
600
601 impl FromInner<net_imp::TcpStream> for TcpStream {
602     fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
603 }
604
605 impl IntoInner<net_imp::TcpStream> for TcpStream {
606     fn into_inner(self) -> net_imp::TcpStream { self.0 }
607 }
608
609 #[stable(feature = "rust1", since = "1.0.0")]
610 impl fmt::Debug for TcpStream {
611     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
612         self.0.fmt(f)
613     }
614 }
615
616 impl TcpListener {
617     /// Creates a new `TcpListener` which will be bound to the specified
618     /// address.
619     ///
620     /// The returned listener is ready for accepting connections.
621     ///
622     /// Binding with a port number of 0 will request that the OS assigns a port
623     /// to this listener. The port allocated can be queried via the
624     /// [`local_addr`] method.
625     ///
626     /// The address type can be any implementor of [`ToSocketAddrs`] trait. See
627     /// its documentation for concrete examples.
628     ///
629     /// If `addr` yields multiple addresses, `bind` will be attempted with
630     /// each of the addresses until one succeeds and returns the listener. If
631     /// none of the addresses succeed in creating a listener, the error returned
632     /// from the last attempt (the last address) is returned.
633     ///
634     /// [`local_addr`]: #method.local_addr
635     /// [`ToSocketAddrs`]: ../../std/net/trait.ToSocketAddrs.html
636     ///
637     /// # Examples
638     ///
639     /// Creates a TCP listener bound to `127.0.0.1:80`:
640     ///
641     /// ```no_run
642     /// use std::net::TcpListener;
643     ///
644     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
645     /// ```
646     ///
647     /// Creates a TCP listener bound to `127.0.0.1:80`. If that fails, create a
648     /// TCP listener bound to `127.0.0.1:443`:
649     ///
650     /// ```no_run
651     /// use std::net::{SocketAddr, TcpListener};
652     ///
653     /// let addrs = [
654     ///     SocketAddr::from(([127, 0, 0, 1], 80)),
655     ///     SocketAddr::from(([127, 0, 0, 1], 443)),
656     /// ];
657     /// let listener = TcpListener::bind(&addrs[..]).unwrap();
658     /// ```
659     #[stable(feature = "rust1", since = "1.0.0")]
660     pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
661         super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
662     }
663
664     /// Returns the local socket address of this listener.
665     ///
666     /// # Examples
667     ///
668     /// ```no_run
669     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener};
670     ///
671     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
672     /// assert_eq!(listener.local_addr().unwrap(),
673     ///            SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
674     /// ```
675     #[stable(feature = "rust1", since = "1.0.0")]
676     pub fn local_addr(&self) -> io::Result<SocketAddr> {
677         self.0.socket_addr()
678     }
679
680     /// Creates a new independently owned handle to the underlying socket.
681     ///
682     /// The returned [`TcpListener`] is a reference to the same socket that this
683     /// object references. Both handles can be used to accept incoming
684     /// connections and options set on one listener will affect the other.
685     ///
686     /// [`TcpListener`]: ../../std/net/struct.TcpListener.html
687     ///
688     /// # Examples
689     ///
690     /// ```no_run
691     /// use std::net::TcpListener;
692     ///
693     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
694     /// let listener_clone = listener.try_clone().unwrap();
695     /// ```
696     #[stable(feature = "rust1", since = "1.0.0")]
697     pub fn try_clone(&self) -> io::Result<TcpListener> {
698         self.0.duplicate().map(TcpListener)
699     }
700
701     /// Accept a new incoming connection from this listener.
702     ///
703     /// This function will block the calling thread until a new TCP connection
704     /// is established. When established, the corresponding [`TcpStream`] and the
705     /// remote peer's address will be returned.
706     ///
707     /// [`TcpStream`]: ../../std/net/struct.TcpStream.html
708     ///
709     /// # Examples
710     ///
711     /// ```no_run
712     /// use std::net::TcpListener;
713     ///
714     /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
715     /// match listener.accept() {
716     ///     Ok((_socket, addr)) => println!("new client: {:?}", addr),
717     ///     Err(e) => println!("couldn't get client: {:?}", e),
718     /// }
719     /// ```
720     #[stable(feature = "rust1", since = "1.0.0")]
721     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
722         // On WASM, `TcpStream` is uninhabited (as it's unsupported) and so
723         // the `a` variable here is technically unused.
724         #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
725         self.0.accept().map(|(a, b)| (TcpStream(a), b))
726     }
727
728     /// Returns an iterator over the connections being received on this
729     /// listener.
730     ///
731     /// The returned iterator will never return [`None`] and will also not yield
732     /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
733     /// calling [`accept`] in a loop.
734     ///
735     /// [`None`]: ../../std/option/enum.Option.html#variant.None
736     /// [`SocketAddr`]: ../../std/net/enum.SocketAddr.html
737     /// [`accept`]: #method.accept
738     ///
739     /// # Examples
740     ///
741     /// ```no_run
742     /// use std::net::TcpListener;
743     ///
744     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
745     ///
746     /// for stream in listener.incoming() {
747     ///     match stream {
748     ///         Ok(stream) => {
749     ///             println!("new client!");
750     ///         }
751     ///         Err(e) => { /* connection failed */ }
752     ///     }
753     /// }
754     /// ```
755     #[stable(feature = "rust1", since = "1.0.0")]
756     pub fn incoming(&self) -> Incoming {
757         Incoming { listener: self }
758     }
759
760     /// Sets the value for the `IP_TTL` option on this socket.
761     ///
762     /// This value sets the time-to-live field that is used in every packet sent
763     /// from this socket.
764     ///
765     /// # Examples
766     ///
767     /// ```no_run
768     /// use std::net::TcpListener;
769     ///
770     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
771     /// listener.set_ttl(100).expect("could not set TTL");
772     /// ```
773     #[stable(feature = "net2_mutators", since = "1.9.0")]
774     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
775         self.0.set_ttl(ttl)
776     }
777
778     /// Gets the value of the `IP_TTL` option for this socket.
779     ///
780     /// For more information about this option, see [`set_ttl`][link].
781     ///
782     /// [link]: #method.set_ttl
783     ///
784     /// # Examples
785     ///
786     /// ```no_run
787     /// use std::net::TcpListener;
788     ///
789     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
790     /// listener.set_ttl(100).expect("could not set TTL");
791     /// assert_eq!(listener.ttl().unwrap_or(0), 100);
792     /// ```
793     #[stable(feature = "net2_mutators", since = "1.9.0")]
794     pub fn ttl(&self) -> io::Result<u32> {
795         self.0.ttl()
796     }
797
798     #[stable(feature = "net2_mutators", since = "1.9.0")]
799     #[rustc_deprecated(since = "1.16.0",
800                        reason = "this option can only be set before the socket is bound")]
801     #[allow(missing_docs)]
802     pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
803         self.0.set_only_v6(only_v6)
804     }
805
806     #[stable(feature = "net2_mutators", since = "1.9.0")]
807     #[rustc_deprecated(since = "1.16.0",
808                        reason = "this option can only be set before the socket is bound")]
809     #[allow(missing_docs)]
810     pub fn only_v6(&self) -> io::Result<bool> {
811         self.0.only_v6()
812     }
813
814     /// Gets the value of the `SO_ERROR` option on this socket.
815     ///
816     /// This will retrieve the stored error in the underlying socket, clearing
817     /// the field in the process. This can be useful for checking errors between
818     /// calls.
819     ///
820     /// # Examples
821     ///
822     /// ```no_run
823     /// use std::net::TcpListener;
824     ///
825     /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
826     /// listener.take_error().expect("No error was expected");
827     /// ```
828     #[stable(feature = "net2_mutators", since = "1.9.0")]
829     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
830         self.0.take_error()
831     }
832
833     /// Moves this TCP stream into or out of nonblocking mode.
834     ///
835     /// This will result in the `accept` operation becoming nonblocking,
836     /// i.e., immediately returning from their calls. If the IO operation is
837     /// successful, `Ok` is returned and no further action is required. If the
838     /// IO operation could not be completed and needs to be retried, an error
839     /// with kind [`io::ErrorKind::WouldBlock`] is returned.
840     ///
841     /// On Unix platforms, calling this method corresponds to calling `fcntl`
842     /// `FIONBIO`. On Windows calling this method corresponds to calling
843     /// `ioctlsocket` `FIONBIO`.
844     ///
845     /// # Examples
846     ///
847     /// Bind a TCP listener to an address, listen for connections, and read
848     /// bytes in nonblocking mode:
849     ///
850     /// ```no_run
851     /// use std::io;
852     /// use std::net::TcpListener;
853     ///
854     /// let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
855     /// listener.set_nonblocking(true).expect("Cannot set non-blocking");
856     ///
857     /// # fn wait_for_fd() { unimplemented!() }
858     /// # fn handle_connection(stream: std::net::TcpStream) { unimplemented!() }
859     /// for stream in listener.incoming() {
860     ///     match stream {
861     ///         Ok(s) => {
862     ///             // do something with the TcpStream
863     ///             handle_connection(s);
864     ///         }
865     ///         Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
866     ///             // wait until network socket is ready, typically implemented
867     ///             // via platform-specific APIs such as epoll or IOCP
868     ///             wait_for_fd();
869     ///             continue;
870     ///         }
871     ///         Err(e) => panic!("encountered IO error: {}", e),
872     ///     }
873     /// }
874     /// ```
875     ///
876     /// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
877     #[stable(feature = "net2_mutators", since = "1.9.0")]
878     pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
879         self.0.set_nonblocking(nonblocking)
880     }
881 }
882
883 #[stable(feature = "rust1", since = "1.0.0")]
884 impl<'a> Iterator for Incoming<'a> {
885     type Item = io::Result<TcpStream>;
886     fn next(&mut self) -> Option<io::Result<TcpStream>> {
887         Some(self.listener.accept().map(|p| p.0))
888     }
889 }
890
891 impl AsInner<net_imp::TcpListener> for TcpListener {
892     fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
893 }
894
895 impl FromInner<net_imp::TcpListener> for TcpListener {
896     fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
897         TcpListener(inner)
898     }
899 }
900
901 impl IntoInner<net_imp::TcpListener> for TcpListener {
902     fn into_inner(self) -> net_imp::TcpListener { self.0 }
903 }
904
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl fmt::Debug for TcpListener {
907     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
908         self.0.fmt(f)
909     }
910 }
911
912 #[cfg(all(test, not(any(target_os = "cloudabi", target_os = "emscripten"))))]
913 mod tests {
914     use io::ErrorKind;
915     use io::prelude::*;
916     use net::*;
917     use net::test::{next_test_ip4, next_test_ip6};
918     use sync::mpsc::channel;
919     use sys_common::AsInner;
920     use time::{Instant, Duration};
921     use thread;
922
923     fn each_ip(f: &mut dyn FnMut(SocketAddr)) {
924         f(next_test_ip4());
925         f(next_test_ip6());
926     }
927
928     macro_rules! t {
929         ($e:expr) => {
930             match $e {
931                 Ok(t) => t,
932                 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
933             }
934         }
935     }
936
937     #[test]
938     fn bind_error() {
939         match TcpListener::bind("1.1.1.1:9999") {
940             Ok(..) => panic!(),
941             Err(e) =>
942                 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
943         }
944     }
945
946     #[test]
947     fn connect_error() {
948         match TcpStream::connect("0.0.0.0:1") {
949             Ok(..) => panic!(),
950             Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
951                               e.kind() == ErrorKind::InvalidInput ||
952                               e.kind() == ErrorKind::AddrInUse ||
953                               e.kind() == ErrorKind::AddrNotAvailable,
954                               "bad error: {} {:?}", e, e.kind()),
955         }
956     }
957
958     #[test]
959     fn listen_localhost() {
960         let socket_addr = next_test_ip4();
961         let listener = t!(TcpListener::bind(&socket_addr));
962
963         let _t = thread::spawn(move || {
964             let mut stream = t!(TcpStream::connect(&("localhost",
965                                                      socket_addr.port())));
966             t!(stream.write(&[144]));
967         });
968
969         let mut stream = t!(listener.accept()).0;
970         let mut buf = [0];
971         t!(stream.read(&mut buf));
972         assert!(buf[0] == 144);
973     }
974
975     #[test]
976     fn connect_loopback() {
977         each_ip(&mut |addr| {
978             let acceptor = t!(TcpListener::bind(&addr));
979
980             let _t = thread::spawn(move|| {
981                 let host = match addr {
982                     SocketAddr::V4(..) => "127.0.0.1",
983                     SocketAddr::V6(..) => "::1",
984                 };
985                 let mut stream = t!(TcpStream::connect(&(host, addr.port())));
986                 t!(stream.write(&[66]));
987             });
988
989             let mut stream = t!(acceptor.accept()).0;
990             let mut buf = [0];
991             t!(stream.read(&mut buf));
992             assert!(buf[0] == 66);
993         })
994     }
995
996     #[test]
997     fn smoke_test() {
998         each_ip(&mut |addr| {
999             let acceptor = t!(TcpListener::bind(&addr));
1000
1001             let (tx, rx) = channel();
1002             let _t = thread::spawn(move|| {
1003                 let mut stream = t!(TcpStream::connect(&addr));
1004                 t!(stream.write(&[99]));
1005                 tx.send(t!(stream.local_addr())).unwrap();
1006             });
1007
1008             let (mut stream, addr) = t!(acceptor.accept());
1009             let mut buf = [0];
1010             t!(stream.read(&mut buf));
1011             assert!(buf[0] == 99);
1012             assert_eq!(addr, t!(rx.recv()));
1013         })
1014     }
1015
1016     #[test]
1017     fn read_eof() {
1018         each_ip(&mut |addr| {
1019             let acceptor = t!(TcpListener::bind(&addr));
1020
1021             let _t = thread::spawn(move|| {
1022                 let _stream = t!(TcpStream::connect(&addr));
1023                 // Close
1024             });
1025
1026             let mut stream = t!(acceptor.accept()).0;
1027             let mut buf = [0];
1028             let nread = t!(stream.read(&mut buf));
1029             assert_eq!(nread, 0);
1030             let nread = t!(stream.read(&mut buf));
1031             assert_eq!(nread, 0);
1032         })
1033     }
1034
1035     #[test]
1036     fn write_close() {
1037         each_ip(&mut |addr| {
1038             let acceptor = t!(TcpListener::bind(&addr));
1039
1040             let (tx, rx) = channel();
1041             let _t = thread::spawn(move|| {
1042                 drop(t!(TcpStream::connect(&addr)));
1043                 tx.send(()).unwrap();
1044             });
1045
1046             let mut stream = t!(acceptor.accept()).0;
1047             rx.recv().unwrap();
1048             let buf = [0];
1049             match stream.write(&buf) {
1050                 Ok(..) => {}
1051                 Err(e) => {
1052                     assert!(e.kind() == ErrorKind::ConnectionReset ||
1053                             e.kind() == ErrorKind::BrokenPipe ||
1054                             e.kind() == ErrorKind::ConnectionAborted,
1055                             "unknown error: {}", e);
1056                 }
1057             }
1058         })
1059     }
1060
1061     #[test]
1062     fn multiple_connect_serial() {
1063         each_ip(&mut |addr| {
1064             let max = 10;
1065             let acceptor = t!(TcpListener::bind(&addr));
1066
1067             let _t = thread::spawn(move|| {
1068                 for _ in 0..max {
1069                     let mut stream = t!(TcpStream::connect(&addr));
1070                     t!(stream.write(&[99]));
1071                 }
1072             });
1073
1074             for stream in acceptor.incoming().take(max) {
1075                 let mut stream = t!(stream);
1076                 let mut buf = [0];
1077                 t!(stream.read(&mut buf));
1078                 assert_eq!(buf[0], 99);
1079             }
1080         })
1081     }
1082
1083     #[test]
1084     fn multiple_connect_interleaved_greedy_schedule() {
1085         const MAX: usize = 10;
1086         each_ip(&mut |addr| {
1087             let acceptor = t!(TcpListener::bind(&addr));
1088
1089             let _t = thread::spawn(move|| {
1090                 let acceptor = acceptor;
1091                 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
1092                     // Start another thread to handle the connection
1093                     let _t = thread::spawn(move|| {
1094                         let mut stream = t!(stream);
1095                         let mut buf = [0];
1096                         t!(stream.read(&mut buf));
1097                         assert!(buf[0] == i as u8);
1098                     });
1099                 }
1100             });
1101
1102             connect(0, addr);
1103         });
1104
1105         fn connect(i: usize, addr: SocketAddr) {
1106             if i == MAX { return }
1107
1108             let t = thread::spawn(move|| {
1109                 let mut stream = t!(TcpStream::connect(&addr));
1110                 // Connect again before writing
1111                 connect(i + 1, addr);
1112                 t!(stream.write(&[i as u8]));
1113             });
1114             t.join().ok().unwrap();
1115         }
1116     }
1117
1118     #[test]
1119     fn multiple_connect_interleaved_lazy_schedule() {
1120         const MAX: usize = 10;
1121         each_ip(&mut |addr| {
1122             let acceptor = t!(TcpListener::bind(&addr));
1123
1124             let _t = thread::spawn(move|| {
1125                 for stream in acceptor.incoming().take(MAX) {
1126                     // Start another thread to handle the connection
1127                     let _t = thread::spawn(move|| {
1128                         let mut stream = t!(stream);
1129                         let mut buf = [0];
1130                         t!(stream.read(&mut buf));
1131                         assert!(buf[0] == 99);
1132                     });
1133                 }
1134             });
1135
1136             connect(0, addr);
1137         });
1138
1139         fn connect(i: usize, addr: SocketAddr) {
1140             if i == MAX { return }
1141
1142             let t = thread::spawn(move|| {
1143                 let mut stream = t!(TcpStream::connect(&addr));
1144                 connect(i + 1, addr);
1145                 t!(stream.write(&[99]));
1146             });
1147             t.join().ok().unwrap();
1148         }
1149     }
1150
1151     #[test]
1152     fn socket_and_peer_name() {
1153         each_ip(&mut |addr| {
1154             let listener = t!(TcpListener::bind(&addr));
1155             let so_name = t!(listener.local_addr());
1156             assert_eq!(addr, so_name);
1157             let _t = thread::spawn(move|| {
1158                 t!(listener.accept());
1159             });
1160
1161             let stream = t!(TcpStream::connect(&addr));
1162             assert_eq!(addr, t!(stream.peer_addr()));
1163         })
1164     }
1165
1166     #[test]
1167     fn partial_read() {
1168         each_ip(&mut |addr| {
1169             let (tx, rx) = channel();
1170             let srv = t!(TcpListener::bind(&addr));
1171             let _t = thread::spawn(move|| {
1172                 let mut cl = t!(srv.accept()).0;
1173                 cl.write(&[10]).unwrap();
1174                 let mut b = [0];
1175                 t!(cl.read(&mut b));
1176                 tx.send(()).unwrap();
1177             });
1178
1179             let mut c = t!(TcpStream::connect(&addr));
1180             let mut b = [0; 10];
1181             assert_eq!(c.read(&mut b).unwrap(), 1);
1182             t!(c.write(&[1]));
1183             rx.recv().unwrap();
1184         })
1185     }
1186
1187     #[test]
1188     fn double_bind() {
1189         each_ip(&mut |addr| {
1190             let _listener = t!(TcpListener::bind(&addr));
1191             match TcpListener::bind(&addr) {
1192                 Ok(..) => panic!(),
1193                 Err(e) => {
1194                     assert!(e.kind() == ErrorKind::ConnectionRefused ||
1195                             e.kind() == ErrorKind::Other ||
1196                             e.kind() == ErrorKind::AddrInUse,
1197                             "unknown error: {} {:?}", e, e.kind());
1198                 }
1199             }
1200         })
1201     }
1202
1203     #[test]
1204     fn fast_rebind() {
1205         each_ip(&mut |addr| {
1206             let acceptor = t!(TcpListener::bind(&addr));
1207
1208             let _t = thread::spawn(move|| {
1209                 t!(TcpStream::connect(&addr));
1210             });
1211
1212             t!(acceptor.accept());
1213             drop(acceptor);
1214             t!(TcpListener::bind(&addr));
1215         });
1216     }
1217
1218     #[test]
1219     fn tcp_clone_smoke() {
1220         each_ip(&mut |addr| {
1221             let acceptor = t!(TcpListener::bind(&addr));
1222
1223             let _t = thread::spawn(move|| {
1224                 let mut s = t!(TcpStream::connect(&addr));
1225                 let mut buf = [0, 0];
1226                 assert_eq!(s.read(&mut buf).unwrap(), 1);
1227                 assert_eq!(buf[0], 1);
1228                 t!(s.write(&[2]));
1229             });
1230
1231             let mut s1 = t!(acceptor.accept()).0;
1232             let s2 = t!(s1.try_clone());
1233
1234             let (tx1, rx1) = channel();
1235             let (tx2, rx2) = channel();
1236             let _t = thread::spawn(move|| {
1237                 let mut s2 = s2;
1238                 rx1.recv().unwrap();
1239                 t!(s2.write(&[1]));
1240                 tx2.send(()).unwrap();
1241             });
1242             tx1.send(()).unwrap();
1243             let mut buf = [0, 0];
1244             assert_eq!(s1.read(&mut buf).unwrap(), 1);
1245             rx2.recv().unwrap();
1246         })
1247     }
1248
1249     #[test]
1250     fn tcp_clone_two_read() {
1251         each_ip(&mut |addr| {
1252             let acceptor = t!(TcpListener::bind(&addr));
1253             let (tx1, rx) = channel();
1254             let tx2 = tx1.clone();
1255
1256             let _t = thread::spawn(move|| {
1257                 let mut s = t!(TcpStream::connect(&addr));
1258                 t!(s.write(&[1]));
1259                 rx.recv().unwrap();
1260                 t!(s.write(&[2]));
1261                 rx.recv().unwrap();
1262             });
1263
1264             let mut s1 = t!(acceptor.accept()).0;
1265             let s2 = t!(s1.try_clone());
1266
1267             let (done, rx) = channel();
1268             let _t = thread::spawn(move|| {
1269                 let mut s2 = s2;
1270                 let mut buf = [0, 0];
1271                 t!(s2.read(&mut buf));
1272                 tx2.send(()).unwrap();
1273                 done.send(()).unwrap();
1274             });
1275             let mut buf = [0, 0];
1276             t!(s1.read(&mut buf));
1277             tx1.send(()).unwrap();
1278
1279             rx.recv().unwrap();
1280         })
1281     }
1282
1283     #[test]
1284     fn tcp_clone_two_write() {
1285         each_ip(&mut |addr| {
1286             let acceptor = t!(TcpListener::bind(&addr));
1287
1288             let _t = thread::spawn(move|| {
1289                 let mut s = t!(TcpStream::connect(&addr));
1290                 let mut buf = [0, 1];
1291                 t!(s.read(&mut buf));
1292                 t!(s.read(&mut buf));
1293             });
1294
1295             let mut s1 = t!(acceptor.accept()).0;
1296             let s2 = t!(s1.try_clone());
1297
1298             let (done, rx) = channel();
1299             let _t = thread::spawn(move|| {
1300                 let mut s2 = s2;
1301                 t!(s2.write(&[1]));
1302                 done.send(()).unwrap();
1303             });
1304             t!(s1.write(&[2]));
1305
1306             rx.recv().unwrap();
1307         })
1308     }
1309
1310     #[test]
1311     fn shutdown_smoke() {
1312         each_ip(&mut |addr| {
1313             let a = t!(TcpListener::bind(&addr));
1314             let _t = thread::spawn(move|| {
1315                 let mut c = t!(a.accept()).0;
1316                 let mut b = [0];
1317                 assert_eq!(c.read(&mut b).unwrap(), 0);
1318                 t!(c.write(&[1]));
1319             });
1320
1321             let mut s = t!(TcpStream::connect(&addr));
1322             t!(s.shutdown(Shutdown::Write));
1323             assert!(s.write(&[1]).is_err());
1324             let mut b = [0, 0];
1325             assert_eq!(t!(s.read(&mut b)), 1);
1326             assert_eq!(b[0], 1);
1327         })
1328     }
1329
1330     #[test]
1331     fn close_readwrite_smoke() {
1332         each_ip(&mut |addr| {
1333             let a = t!(TcpListener::bind(&addr));
1334             let (tx, rx) = channel::<()>();
1335             let _t = thread::spawn(move|| {
1336                 let _s = t!(a.accept());
1337                 let _ = rx.recv();
1338             });
1339
1340             let mut b = [0];
1341             let mut s = t!(TcpStream::connect(&addr));
1342             let mut s2 = t!(s.try_clone());
1343
1344             // closing should prevent reads/writes
1345             t!(s.shutdown(Shutdown::Write));
1346             assert!(s.write(&[0]).is_err());
1347             t!(s.shutdown(Shutdown::Read));
1348             assert_eq!(s.read(&mut b).unwrap(), 0);
1349
1350             // closing should affect previous handles
1351             assert!(s2.write(&[0]).is_err());
1352             assert_eq!(s2.read(&mut b).unwrap(), 0);
1353
1354             // closing should affect new handles
1355             let mut s3 = t!(s.try_clone());
1356             assert!(s3.write(&[0]).is_err());
1357             assert_eq!(s3.read(&mut b).unwrap(), 0);
1358
1359             // make sure these don't die
1360             let _ = s2.shutdown(Shutdown::Read);
1361             let _ = s2.shutdown(Shutdown::Write);
1362             let _ = s3.shutdown(Shutdown::Read);
1363             let _ = s3.shutdown(Shutdown::Write);
1364             drop(tx);
1365         })
1366     }
1367
1368     #[test]
1369     #[cfg(unix)] // test doesn't work on Windows, see #31657
1370     fn close_read_wakes_up() {
1371         each_ip(&mut |addr| {
1372             let a = t!(TcpListener::bind(&addr));
1373             let (tx1, rx) = channel::<()>();
1374             let _t = thread::spawn(move|| {
1375                 let _s = t!(a.accept());
1376                 let _ = rx.recv();
1377             });
1378
1379             let s = t!(TcpStream::connect(&addr));
1380             let s2 = t!(s.try_clone());
1381             let (tx, rx) = channel();
1382             let _t = thread::spawn(move|| {
1383                 let mut s2 = s2;
1384                 assert_eq!(t!(s2.read(&mut [0])), 0);
1385                 tx.send(()).unwrap();
1386             });
1387             // this should wake up the child thread
1388             t!(s.shutdown(Shutdown::Read));
1389
1390             // this test will never finish if the child doesn't wake up
1391             rx.recv().unwrap();
1392             drop(tx1);
1393         })
1394     }
1395
1396     #[test]
1397     fn clone_while_reading() {
1398         each_ip(&mut |addr| {
1399             let accept = t!(TcpListener::bind(&addr));
1400
1401             // Enqueue a thread to write to a socket
1402             let (tx, rx) = channel();
1403             let (txdone, rxdone) = channel();
1404             let txdone2 = txdone.clone();
1405             let _t = thread::spawn(move|| {
1406                 let mut tcp = t!(TcpStream::connect(&addr));
1407                 rx.recv().unwrap();
1408                 t!(tcp.write(&[0]));
1409                 txdone2.send(()).unwrap();
1410             });
1411
1412             // Spawn off a reading clone
1413             let tcp = t!(accept.accept()).0;
1414             let tcp2 = t!(tcp.try_clone());
1415             let txdone3 = txdone.clone();
1416             let _t = thread::spawn(move|| {
1417                 let mut tcp2 = tcp2;
1418                 t!(tcp2.read(&mut [0]));
1419                 txdone3.send(()).unwrap();
1420             });
1421
1422             // Try to ensure that the reading clone is indeed reading
1423             for _ in 0..50 {
1424                 thread::yield_now();
1425             }
1426
1427             // clone the handle again while it's reading, then let it finish the
1428             // read.
1429             let _ = t!(tcp.try_clone());
1430             tx.send(()).unwrap();
1431             rxdone.recv().unwrap();
1432             rxdone.recv().unwrap();
1433         })
1434     }
1435
1436     #[test]
1437     fn clone_accept_smoke() {
1438         each_ip(&mut |addr| {
1439             let a = t!(TcpListener::bind(&addr));
1440             let a2 = t!(a.try_clone());
1441
1442             let _t = thread::spawn(move|| {
1443                 let _ = TcpStream::connect(&addr);
1444             });
1445             let _t = thread::spawn(move|| {
1446                 let _ = TcpStream::connect(&addr);
1447             });
1448
1449             t!(a.accept());
1450             t!(a2.accept());
1451         })
1452     }
1453
1454     #[test]
1455     fn clone_accept_concurrent() {
1456         each_ip(&mut |addr| {
1457             let a = t!(TcpListener::bind(&addr));
1458             let a2 = t!(a.try_clone());
1459
1460             let (tx, rx) = channel();
1461             let tx2 = tx.clone();
1462
1463             let _t = thread::spawn(move|| {
1464                 tx.send(t!(a.accept())).unwrap();
1465             });
1466             let _t = thread::spawn(move|| {
1467                 tx2.send(t!(a2.accept())).unwrap();
1468             });
1469
1470             let _t = thread::spawn(move|| {
1471                 let _ = TcpStream::connect(&addr);
1472             });
1473             let _t = thread::spawn(move|| {
1474                 let _ = TcpStream::connect(&addr);
1475             });
1476
1477             rx.recv().unwrap();
1478             rx.recv().unwrap();
1479         })
1480     }
1481
1482     #[test]
1483     fn debug() {
1484         let name = if cfg!(windows) {"socket"} else {"fd"};
1485         let socket_addr = next_test_ip4();
1486
1487         let listener = t!(TcpListener::bind(&socket_addr));
1488         let listener_inner = listener.0.socket().as_inner();
1489         let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
1490                               socket_addr, name, listener_inner);
1491         assert_eq!(format!("{:?}", listener), compare);
1492
1493         let stream = t!(TcpStream::connect(&("localhost",
1494                                                  socket_addr.port())));
1495         let stream_inner = stream.0.socket().as_inner();
1496         let compare = format!("TcpStream {{ addr: {:?}, \
1497                               peer: {:?}, {}: {:?} }}",
1498                               stream.local_addr().unwrap(),
1499                               stream.peer_addr().unwrap(),
1500                               name,
1501                               stream_inner);
1502         assert_eq!(format!("{:?}", stream), compare);
1503     }
1504
1505     // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
1506     //        no longer has rounding errors.
1507     #[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
1508     #[test]
1509     fn timeouts() {
1510         let addr = next_test_ip4();
1511         let listener = t!(TcpListener::bind(&addr));
1512
1513         let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1514         let dur = Duration::new(15410, 0);
1515
1516         assert_eq!(None, t!(stream.read_timeout()));
1517
1518         t!(stream.set_read_timeout(Some(dur)));
1519         assert_eq!(Some(dur), t!(stream.read_timeout()));
1520
1521         assert_eq!(None, t!(stream.write_timeout()));
1522
1523         t!(stream.set_write_timeout(Some(dur)));
1524         assert_eq!(Some(dur), t!(stream.write_timeout()));
1525
1526         t!(stream.set_read_timeout(None));
1527         assert_eq!(None, t!(stream.read_timeout()));
1528
1529         t!(stream.set_write_timeout(None));
1530         assert_eq!(None, t!(stream.write_timeout()));
1531         drop(listener);
1532     }
1533
1534     #[test]
1535     fn test_read_timeout() {
1536         let addr = next_test_ip4();
1537         let listener = t!(TcpListener::bind(&addr));
1538
1539         let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1540         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1541
1542         let mut buf = [0; 10];
1543         let start = Instant::now();
1544         let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1545         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1546                 "unexpected_error: {:?}", kind);
1547         assert!(start.elapsed() > Duration::from_millis(400));
1548         drop(listener);
1549     }
1550
1551     #[test]
1552     fn test_read_with_timeout() {
1553         let addr = next_test_ip4();
1554         let listener = t!(TcpListener::bind(&addr));
1555
1556         let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1557         t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
1558
1559         let mut other_end = t!(listener.accept()).0;
1560         t!(other_end.write_all(b"hello world"));
1561
1562         let mut buf = [0; 11];
1563         t!(stream.read(&mut buf));
1564         assert_eq!(b"hello world", &buf[..]);
1565
1566         let start = Instant::now();
1567         let kind = stream.read_exact(&mut buf).err().expect("expected error").kind();
1568         assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut,
1569                 "unexpected_error: {:?}", kind);
1570         assert!(start.elapsed() > Duration::from_millis(400));
1571         drop(listener);
1572     }
1573
1574     // Ensure the `set_read_timeout` and `set_write_timeout` calls return errors
1575     // when passed zero Durations
1576     #[test]
1577     fn test_timeout_zero_duration() {
1578         let addr = next_test_ip4();
1579
1580         let listener = t!(TcpListener::bind(&addr));
1581         let stream = t!(TcpStream::connect(&addr));
1582
1583         let result = stream.set_write_timeout(Some(Duration::new(0, 0)));
1584         let err = result.unwrap_err();
1585         assert_eq!(err.kind(), ErrorKind::InvalidInput);
1586
1587         let result = stream.set_read_timeout(Some(Duration::new(0, 0)));
1588         let err = result.unwrap_err();
1589         assert_eq!(err.kind(), ErrorKind::InvalidInput);
1590
1591         drop(listener);
1592     }
1593
1594     #[test]
1595     fn nodelay() {
1596         let addr = next_test_ip4();
1597         let _listener = t!(TcpListener::bind(&addr));
1598
1599         let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1600
1601         assert_eq!(false, t!(stream.nodelay()));
1602         t!(stream.set_nodelay(true));
1603         assert_eq!(true, t!(stream.nodelay()));
1604         t!(stream.set_nodelay(false));
1605         assert_eq!(false, t!(stream.nodelay()));
1606     }
1607
1608     #[test]
1609     fn ttl() {
1610         let ttl = 100;
1611
1612         let addr = next_test_ip4();
1613         let listener = t!(TcpListener::bind(&addr));
1614
1615         t!(listener.set_ttl(ttl));
1616         assert_eq!(ttl, t!(listener.ttl()));
1617
1618         let stream = t!(TcpStream::connect(&("localhost", addr.port())));
1619
1620         t!(stream.set_ttl(ttl));
1621         assert_eq!(ttl, t!(stream.ttl()));
1622     }
1623
1624     #[test]
1625     fn set_nonblocking() {
1626         let addr = next_test_ip4();
1627         let listener = t!(TcpListener::bind(&addr));
1628
1629         t!(listener.set_nonblocking(true));
1630         t!(listener.set_nonblocking(false));
1631
1632         let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
1633
1634         t!(stream.set_nonblocking(false));
1635         t!(stream.set_nonblocking(true));
1636
1637         let mut buf = [0];
1638         match stream.read(&mut buf) {
1639             Ok(_) => panic!("expected error"),
1640             Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1641             Err(e) => panic!("unexpected error {}", e),
1642         }
1643     }
1644
1645     #[test]
1646     fn peek() {
1647         each_ip(&mut |addr| {
1648             let (txdone, rxdone) = channel();
1649
1650             let srv = t!(TcpListener::bind(&addr));
1651             let _t = thread::spawn(move|| {
1652                 let mut cl = t!(srv.accept()).0;
1653                 cl.write(&[1,3,3,7]).unwrap();
1654                 t!(rxdone.recv());
1655             });
1656
1657             let mut c = t!(TcpStream::connect(&addr));
1658             let mut b = [0; 10];
1659             for _ in 1..3 {
1660                 let len = c.peek(&mut b).unwrap();
1661                 assert_eq!(len, 4);
1662             }
1663             let len = c.read(&mut b).unwrap();
1664             assert_eq!(len, 4);
1665
1666             t!(c.set_nonblocking(true));
1667             match c.peek(&mut b) {
1668                 Ok(_) => panic!("expected error"),
1669                 Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
1670                 Err(e) => panic!("unexpected error {}", e),
1671             }
1672             t!(txdone.send(()));
1673         })
1674     }
1675
1676     #[test]
1677     fn connect_timeout_unbound() {
1678         // bind and drop a socket to track down a "probably unassigned" port
1679         let socket = TcpListener::bind("127.0.0.1:0").unwrap();
1680         let addr = socket.local_addr().unwrap();
1681         drop(socket);
1682
1683         let timeout = Duration::from_secs(1);
1684         let e = TcpStream::connect_timeout(&addr, timeout).unwrap_err();
1685         assert!(e.kind() == io::ErrorKind::ConnectionRefused ||
1686                 e.kind() == io::ErrorKind::TimedOut ||
1687                 e.kind() == io::ErrorKind::Other,
1688                 "bad error: {} {:?}", e, e.kind());
1689     }
1690
1691     #[test]
1692     fn connect_timeout_valid() {
1693         let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1694         let addr = listener.local_addr().unwrap();
1695         TcpStream::connect_timeout(&addr, Duration::from_secs(2)).unwrap();
1696     }
1697 }