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