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