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