libp2p_tcp/provider/
async_io.rs

1// Copyright 2020 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21use std::{
22    io, net,
23    task::{Context, Poll},
24};
25
26use async_io::Async;
27use futures::future::{BoxFuture, FutureExt};
28
29use super::{Incoming, Provider};
30
31/// A TCP [`Transport`](libp2p_core::Transport) that works with the `async-std` ecosystem.
32///
33/// # Example
34///
35/// ```rust
36/// # use libp2p_tcp as tcp;
37/// # use libp2p_core::{Transport, transport::ListenerId};
38/// # use futures::future;
39/// # use std::pin::Pin;
40/// #
41/// # #[async_std::main]
42/// # async fn main() {
43/// let mut transport = tcp::async_io::Transport::new(tcp::Config::default());
44/// let id = ListenerId::next();
45/// transport
46///     .listen_on(id, "/ip4/127.0.0.1/tcp/0".parse().unwrap())
47///     .unwrap();
48///
49/// let addr = future::poll_fn(|cx| Pin::new(&mut transport).poll(cx))
50///     .await
51///     .into_new_address()
52///     .unwrap();
53///
54/// println!("Listening on {addr}");
55/// # }
56/// ```
57pub type Transport = crate::Transport<Tcp>;
58
59#[derive(Copy, Clone)]
60#[doc(hidden)]
61pub enum Tcp {}
62
63impl Provider for Tcp {
64    type Stream = TcpStream;
65    type Listener = Async<net::TcpListener>;
66    type IfWatcher = if_watch::smol::IfWatcher;
67
68    fn new_if_watcher() -> io::Result<Self::IfWatcher> {
69        Self::IfWatcher::new()
70    }
71
72    fn addrs(if_watcher: &Self::IfWatcher) -> Vec<if_watch::IpNet> {
73        if_watcher.iter().copied().collect()
74    }
75
76    fn new_listener(l: net::TcpListener) -> io::Result<Self::Listener> {
77        Async::new(l)
78    }
79
80    fn new_stream(s: net::TcpStream) -> BoxFuture<'static, io::Result<Self::Stream>> {
81        async move {
82            // Taken from [`Async::connect`].
83
84            let stream = Async::new(s)?;
85
86            // The stream becomes writable when connected.
87            stream.writable().await?;
88
89            // Check if there was an error while connecting.
90            match stream.get_ref().take_error()? {
91                None => Ok(stream),
92                Some(err) => Err(err),
93            }
94        }
95        .boxed()
96    }
97
98    fn poll_accept(
99        l: &mut Self::Listener,
100        cx: &mut Context<'_>,
101    ) -> Poll<io::Result<Incoming<Self::Stream>>> {
102        let (stream, remote_addr) = loop {
103            match l.poll_readable(cx) {
104                Poll::Pending => return Poll::Pending,
105                Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
106                Poll::Ready(Ok(())) => match l.accept().now_or_never() {
107                    Some(Err(e)) => return Poll::Ready(Err(e)),
108                    Some(Ok(res)) => break res,
109                    None => {
110                        // Since it doesn't do any harm, account for false positives of
111                        // `poll_readable` just in case, i.e. try again.
112                    }
113                },
114            }
115        };
116
117        let local_addr = stream.get_ref().local_addr()?;
118
119        Poll::Ready(Ok(Incoming {
120            stream,
121            local_addr,
122            remote_addr,
123        }))
124    }
125}
126
127pub type TcpStream = Async<net::TcpStream>;