1 use crate::io::{Interest, PollEvented};
2 use crate::net::tcp::TcpStream;
3 use crate::net::{to_socket_addrs, ToSocketAddrs};
4 
5 use std::convert::TryFrom;
6 use std::fmt;
7 use std::io;
8 use std::net::{self, SocketAddr};
9 use std::task::{Context, Poll};
10 
11 cfg_net! {
12     /// A TCP socket server, listening for connections.
13     ///
14     /// You can accept a new connection by using the [`accept`](`TcpListener::accept`)
15     /// method.
16     ///
17     /// A `TcpListener` can be turned into a `Stream` with [`TcpListenerStream`].
18     ///
19     /// [`TcpListenerStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.TcpListenerStream.html
20     ///
21     /// # Errors
22     ///
23     /// Note that accepting a connection can lead to various errors and not all
24     /// of them are necessarily fatal ‒ for example having too many open file
25     /// descriptors or the other side closing the connection while it waits in
26     /// an accept queue. These would terminate the stream if not handled in any
27     /// way.
28     ///
29     /// # Examples
30     ///
31     /// Using `accept`:
32     /// ```no_run
33     /// use tokio::net::TcpListener;
34     ///
35     /// use std::io;
36     ///
37     /// async fn process_socket<T>(socket: T) {
38     ///     # drop(socket);
39     ///     // do work with socket here
40     /// }
41     ///
42     /// #[tokio::main]
43     /// async fn main() -> io::Result<()> {
44     ///     let listener = TcpListener::bind("127.0.0.1:8080").await?;
45     ///
46     ///     loop {
47     ///         let (socket, _) = listener.accept().await?;
48     ///         process_socket(socket).await;
49     ///     }
50     /// }
51     /// ```
52     pub struct TcpListener {
53         io: PollEvented<mio::net::TcpListener>,
54     }
55 }
56 
57 impl TcpListener {
58     /// Creates a new TcpListener, which will be bound to the specified address.
59     ///
60     /// The returned listener is ready for accepting connections.
61     ///
62     /// Binding with a port number of 0 will request that the OS assigns a port
63     /// to this listener. The port allocated can be queried via the `local_addr`
64     /// method.
65     ///
66     /// The address type can be any implementor of the [`ToSocketAddrs`] trait.
67     /// If `addr` yields multiple addresses, bind will be attempted with each of
68     /// the addresses until one succeeds and returns the listener. If none of
69     /// the addresses succeed in creating a listener, the error returned from
70     /// the last attempt (the last address) is returned.
71     ///
72     /// This function sets the `SO_REUSEADDR` option on the socket.
73     ///
74     /// To configure the socket before binding, you can use the [`TcpSocket`]
75     /// type.
76     ///
77     /// [`ToSocketAddrs`]: trait@crate::net::ToSocketAddrs
78     /// [`TcpSocket`]: struct@crate::net::TcpSocket
79     ///
80     /// # Examples
81     ///
82     /// ```no_run
83     /// use tokio::net::TcpListener;
84     ///
85     /// use std::io;
86     ///
87     /// #[tokio::main]
88     /// async fn main() -> io::Result<()> {
89     ///     let listener = TcpListener::bind("127.0.0.1:2345").await?;
90     ///
91     ///     // use the listener
92     ///
93     ///     # let _ = listener;
94     ///     Ok(())
95     /// }
96     /// ```
bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener>97     pub async fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
98         let addrs = to_socket_addrs(addr).await?;
99 
100         let mut last_err = None;
101 
102         for addr in addrs {
103             match TcpListener::bind_addr(addr) {
104                 Ok(listener) => return Ok(listener),
105                 Err(e) => last_err = Some(e),
106             }
107         }
108 
109         Err(last_err.unwrap_or_else(|| {
110             io::Error::new(
111                 io::ErrorKind::InvalidInput,
112                 "could not resolve to any address",
113             )
114         }))
115     }
116 
bind_addr(addr: SocketAddr) -> io::Result<TcpListener>117     fn bind_addr(addr: SocketAddr) -> io::Result<TcpListener> {
118         let listener = mio::net::TcpListener::bind(addr)?;
119         TcpListener::new(listener)
120     }
121 
122     /// Accepts a new incoming connection from this listener.
123     ///
124     /// This function will yield once a new TCP connection is established. When
125     /// established, the corresponding [`TcpStream`] and the remote peer's
126     /// address will be returned.
127     ///
128     /// # Cancel safety
129     ///
130     /// This method is cancel safe. If the method is used as the event in a
131     /// [`tokio::select!`](crate::select) statement and some other branch
132     /// completes first, then it is guaranteed that no new connections were
133     /// accepted by this method.
134     ///
135     /// [`TcpStream`]: struct@crate::net::TcpStream
136     ///
137     /// # Examples
138     ///
139     /// ```no_run
140     /// use tokio::net::TcpListener;
141     ///
142     /// use std::io;
143     ///
144     /// #[tokio::main]
145     /// async fn main() -> io::Result<()> {
146     ///     let listener = TcpListener::bind("127.0.0.1:8080").await?;
147     ///
148     ///     match listener.accept().await {
149     ///         Ok((_socket, addr)) => println!("new client: {:?}", addr),
150     ///         Err(e) => println!("couldn't get client: {:?}", e),
151     ///     }
152     ///
153     ///     Ok(())
154     /// }
155     /// ```
accept(&self) -> io::Result<(TcpStream, SocketAddr)>156     pub async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
157         let (mio, addr) = self
158             .io
159             .registration()
160             .async_io(Interest::READABLE, || self.io.accept())
161             .await?;
162 
163         let stream = TcpStream::new(mio)?;
164         Ok((stream, addr))
165     }
166 
167     /// Polls to accept a new incoming connection to this listener.
168     ///
169     /// If there is no connection to accept, `Poll::Pending` is returned and the
170     /// current task will be notified by a waker.  Note that on multiple calls
171     /// to `poll_accept`, only the `Waker` from the `Context` passed to the most
172     /// recent call is scheduled to receive a wakeup.
poll_accept(&self, cx: &mut Context<'_>) -> Poll<io::Result<(TcpStream, SocketAddr)>>173     pub fn poll_accept(&self, cx: &mut Context<'_>) -> Poll<io::Result<(TcpStream, SocketAddr)>> {
174         loop {
175             let ev = ready!(self.io.registration().poll_read_ready(cx))?;
176 
177             match self.io.accept() {
178                 Ok((io, addr)) => {
179                     let io = TcpStream::new(io)?;
180                     return Poll::Ready(Ok((io, addr)));
181                 }
182                 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
183                     self.io.registration().clear_readiness(ev);
184                 }
185                 Err(e) => return Poll::Ready(Err(e)),
186             }
187         }
188     }
189 
190     /// Creates new `TcpListener` from a `std::net::TcpListener`.
191     ///
192     /// This function is intended to be used to wrap a TCP listener from the
193     /// standard library in the Tokio equivalent. The conversion assumes nothing
194     /// about the underlying listener; it is left up to the user to set it in
195     /// non-blocking mode.
196     ///
197     /// This API is typically paired with the `socket2` crate and the `Socket`
198     /// type to build up and customize a listener before it's shipped off to the
199     /// backing event loop. This allows configuration of options like
200     /// `SO_REUSEPORT`, binding to multiple addresses, etc.
201     ///
202     /// # Examples
203     ///
204     /// ```rust,no_run
205     /// use std::error::Error;
206     /// use tokio::net::TcpListener;
207     ///
208     /// #[tokio::main]
209     /// async fn main() -> Result<(), Box<dyn Error>> {
210     ///     let std_listener = std::net::TcpListener::bind("127.0.0.1:0")?;
211     ///     std_listener.set_nonblocking(true)?;
212     ///     let listener = TcpListener::from_std(std_listener)?;
213     ///     Ok(())
214     /// }
215     /// ```
216     ///
217     /// # Panics
218     ///
219     /// This function panics if thread-local runtime is not set.
220     ///
221     /// The runtime is usually set implicitly when this function is called
222     /// from a future driven by a tokio runtime, otherwise runtime can be set
223     /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
from_std(listener: net::TcpListener) -> io::Result<TcpListener>224     pub fn from_std(listener: net::TcpListener) -> io::Result<TcpListener> {
225         let io = mio::net::TcpListener::from_std(listener);
226         let io = PollEvented::new(io)?;
227         Ok(TcpListener { io })
228     }
229 
230     /// Turns a [`tokio::net::TcpListener`] into a [`std::net::TcpListener`].
231     ///
232     /// The returned [`std::net::TcpListener`] will have nonblocking mode set as
233     /// `true`.  Use [`set_nonblocking`] to change the blocking mode if needed.
234     ///
235     /// # Examples
236     ///
237     /// ```rust,no_run
238     /// use std::error::Error;
239     ///
240     /// #[tokio::main]
241     /// async fn main() -> Result<(), Box<dyn Error>> {
242     ///     let tokio_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
243     ///     let std_listener = tokio_listener.into_std()?;
244     ///     std_listener.set_nonblocking(false)?;
245     ///     Ok(())
246     /// }
247     /// ```
248     ///
249     /// [`tokio::net::TcpListener`]: TcpListener
250     /// [`std::net::TcpListener`]: std::net::TcpListener
251     /// [`set_nonblocking`]: fn@std::net::TcpListener::set_nonblocking
into_std(self) -> io::Result<std::net::TcpListener>252     pub fn into_std(self) -> io::Result<std::net::TcpListener> {
253         #[cfg(unix)]
254         {
255             use std::os::unix::io::{FromRawFd, IntoRawFd};
256             self.io
257                 .into_inner()
258                 .map(|io| io.into_raw_fd())
259                 .map(|raw_fd| unsafe { std::net::TcpListener::from_raw_fd(raw_fd) })
260         }
261 
262         #[cfg(windows)]
263         {
264             use std::os::windows::io::{FromRawSocket, IntoRawSocket};
265             self.io
266                 .into_inner()
267                 .map(|io| io.into_raw_socket())
268                 .map(|raw_socket| unsafe { std::net::TcpListener::from_raw_socket(raw_socket) })
269         }
270     }
271 
new(listener: mio::net::TcpListener) -> io::Result<TcpListener>272     pub(crate) fn new(listener: mio::net::TcpListener) -> io::Result<TcpListener> {
273         let io = PollEvented::new(listener)?;
274         Ok(TcpListener { io })
275     }
276 
277     /// Returns the local address that this listener is bound to.
278     ///
279     /// This can be useful, for example, when binding to port 0 to figure out
280     /// which port was actually bound.
281     ///
282     /// # Examples
283     ///
284     /// ```rust,no_run
285     /// use tokio::net::TcpListener;
286     ///
287     /// use std::io;
288     /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
289     ///
290     /// #[tokio::main]
291     /// async fn main() -> io::Result<()> {
292     ///     let listener = TcpListener::bind("127.0.0.1:8080").await?;
293     ///
294     ///     assert_eq!(listener.local_addr()?,
295     ///                SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));
296     ///
297     ///     Ok(())
298     /// }
299     /// ```
local_addr(&self) -> io::Result<SocketAddr>300     pub fn local_addr(&self) -> io::Result<SocketAddr> {
301         self.io.local_addr()
302     }
303 
304     /// Gets the value of the `IP_TTL` option for this socket.
305     ///
306     /// For more information about this option, see [`set_ttl`].
307     ///
308     /// [`set_ttl`]: method@Self::set_ttl
309     ///
310     /// # Examples
311     ///
312     /// ```no_run
313     /// use tokio::net::TcpListener;
314     ///
315     /// use std::io;
316     ///
317     /// #[tokio::main]
318     /// async fn main() -> io::Result<()> {
319     ///    let listener = TcpListener::bind("127.0.0.1:0").await?;
320     ///
321     ///    listener.set_ttl(100).expect("could not set TTL");
322     ///    assert_eq!(listener.ttl()?, 100);
323     ///
324     ///    Ok(())
325     /// }
326     /// ```
ttl(&self) -> io::Result<u32>327     pub fn ttl(&self) -> io::Result<u32> {
328         self.io.ttl()
329     }
330 
331     /// Sets the value for the `IP_TTL` option on this socket.
332     ///
333     /// This value sets the time-to-live field that is used in every packet sent
334     /// from this socket.
335     ///
336     /// # Examples
337     ///
338     /// ```no_run
339     /// use tokio::net::TcpListener;
340     ///
341     /// use std::io;
342     ///
343     /// #[tokio::main]
344     /// async fn main() -> io::Result<()> {
345     ///     let listener = TcpListener::bind("127.0.0.1:0").await?;
346     ///
347     ///     listener.set_ttl(100).expect("could not set TTL");
348     ///
349     ///     Ok(())
350     /// }
351     /// ```
set_ttl(&self, ttl: u32) -> io::Result<()>352     pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
353         self.io.set_ttl(ttl)
354     }
355 }
356 
357 impl TryFrom<net::TcpListener> for TcpListener {
358     type Error = io::Error;
359 
360     /// Consumes stream, returning the tokio I/O object.
361     ///
362     /// This is equivalent to
363     /// [`TcpListener::from_std(stream)`](TcpListener::from_std).
try_from(stream: net::TcpListener) -> Result<Self, Self::Error>364     fn try_from(stream: net::TcpListener) -> Result<Self, Self::Error> {
365         Self::from_std(stream)
366     }
367 }
368 
369 impl fmt::Debug for TcpListener {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result370     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371         self.io.fmt(f)
372     }
373 }
374 
375 #[cfg(unix)]
376 mod sys {
377     use super::TcpListener;
378     use std::os::unix::prelude::*;
379 
380     impl AsRawFd for TcpListener {
as_raw_fd(&self) -> RawFd381         fn as_raw_fd(&self) -> RawFd {
382             self.io.as_raw_fd()
383         }
384     }
385 }
386 
387 #[cfg(windows)]
388 mod sys {
389     use super::TcpListener;
390     use std::os::windows::prelude::*;
391 
392     impl AsRawSocket for TcpListener {
as_raw_socket(&self) -> RawSocket393         fn as_raw_socket(&self) -> RawSocket {
394             self.io.as_raw_socket()
395         }
396     }
397 }
398