Skip to main content

libp2p_websocket/
lib.rs

1// Copyright 2017-2019 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
21//! Implementation of the libp2p `Transport` trait for Websockets.
22
23#![cfg_attr(docsrs, feature(doc_cfg))]
24
25pub mod error;
26pub mod framed;
27mod quicksink;
28pub mod tls;
29
30use std::{
31    io,
32    pin::Pin,
33    task::{Context, Poll},
34};
35
36use error::Error;
37use framed::{Connection, Incoming};
38use futures::{future::BoxFuture, prelude::*, ready};
39use libp2p_core::{
40    Transport,
41    connection::ConnectedPoint,
42    multiaddr::Multiaddr,
43    transport::{DialOpts, ListenerId, TransportError, TransportEvent, map::MapFuture},
44};
45use rw_stream_sink::RwStreamSink;
46
47/// A Websocket transport.
48///
49/// DO NOT wrap this transport with a DNS transport if you want Secure Websockets to work.
50///
51/// A Secure Websocket transport needs to wrap DNS transport to resolve domain names after
52/// they are checked against the remote certificates. Use a combination of DNS and TCP transports
53/// to build a Secure Websocket transport.
54///
55/// If you don't need Secure Websocket's support, use a plain TCP transport as an inner transport.
56///
57/// # Dependencies
58///
59/// This transport requires the `zlib` shared library to be installed on the system.
60///
61/// Future releases might lift this requirement, see <https://github.com/paritytech/soketto/issues/72>.
62///
63/// # Examples
64///
65/// Secure Websocket transport:
66///
67/// ```
68/// # use futures::future;
69/// # use libp2p_core::{transport::ListenerId, Transport};
70/// # use libp2p_dns as dns;
71/// # use libp2p_tcp as tcp;
72/// # use libp2p_websocket as websocket;
73/// # use std::pin::Pin;
74/// #
75/// # #[tokio::main]
76/// # async fn main() {
77///
78/// let mut transport = websocket::Config::new(
79///     dns::tokio::Transport::system(tcp::tokio::Transport::new(tcp::Config::default())).unwrap(),
80/// );
81///
82/// let rcgen::CertifiedKey {
83///     cert: rcgen_cert,
84///     key_pair,
85/// } = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
86/// let priv_key = websocket::tls::PrivateKey::new(key_pair.serialize_der());
87/// let cert = websocket::tls::Certificate::new(rcgen_cert.der().to_vec());
88/// transport.set_tls_config(websocket::tls::Config::new(priv_key, vec![cert]).unwrap());
89///
90/// let id = transport
91///     .listen_on(
92///         ListenerId::next(),
93///         "/ip4/127.0.0.1/tcp/0/tls/ws".parse().unwrap(),
94///     )
95///     .unwrap();
96///
97/// let addr = future::poll_fn(|cx| Pin::new(&mut transport).poll(cx))
98///     .await
99///     .into_new_address()
100///     .unwrap();
101/// println!("Listening on {addr}");
102///
103/// # }
104/// ```
105///
106/// Plain Websocket transport:
107///
108/// ```
109/// # use futures::future;
110/// # use libp2p_core::{transport::ListenerId, Transport};
111/// # use libp2p_dns as dns;
112/// # use libp2p_tcp as tcp;
113/// # use libp2p_websocket as websocket;
114/// # use std::pin::Pin;
115/// #
116/// # #[tokio::main]
117/// # async fn main() {
118///
119/// let mut transport = websocket::Config::new(tcp::tokio::Transport::new(tcp::Config::default()));
120///
121/// let id = transport
122///     .listen_on(
123///         ListenerId::next(),
124///         "/ip4/127.0.0.1/tcp/0/ws".parse().unwrap(),
125///     )
126///     .unwrap();
127///
128/// let addr = future::poll_fn(|cx| Pin::new(&mut transport).poll(cx))
129///     .await
130///     .into_new_address()
131///     .unwrap();
132/// println!("Listening on {addr}");
133///
134/// # }
135/// ```
136#[deprecated = "Use `Config` instead"]
137pub type WsConfig<Transport> = Config<Transport>;
138
139#[derive(Debug)]
140pub struct Config<T: Transport>
141where
142    T: Transport,
143    T::Output: AsyncRead + AsyncWrite + Send + Unpin + 'static,
144{
145    transport: libp2p_core::transport::map::Map<framed::Config<T>, WrapperFn<T::Output>>,
146}
147
148impl<T: Transport> Config<T>
149where
150    T: Transport + Send + Unpin + 'static,
151    T::Error: Send + 'static,
152    T::Dial: Send + 'static,
153    T::ListenerUpgrade: Send + 'static,
154    T::Output: AsyncRead + AsyncWrite + Send + Unpin + 'static,
155{
156    /// Create a new websocket transport based on the given transport.
157    ///
158    /// > **Note*: The given transport must be based on TCP/IP and should
159    /// > usually incorporate DNS resolution, though the latter is not
160    /// > strictly necessary if one wishes to only use the `Ws` protocol
161    /// > with known IP addresses and ports. See [`libp2p-tcp`](https://docs.rs/libp2p-tcp/)
162    /// > and [`libp2p-dns`](https://docs.rs/libp2p-dns) for constructing
163    /// > the inner transport.
164    pub fn new(transport: T) -> Self {
165        Self {
166            transport: framed::Config::new(transport).map(wrap_connection as WrapperFn<T::Output>),
167        }
168    }
169
170    /// Return the configured maximum number of redirects.
171    pub fn max_redirects(&self) -> u8 {
172        self.transport.inner().max_redirects()
173    }
174
175    /// Set max. number of redirects to follow.
176    pub fn set_max_redirects(&mut self, max: u8) -> &mut Self {
177        self.transport.inner_mut().set_max_redirects(max);
178        self
179    }
180
181    /// Get the max. frame data size we support.
182    pub fn max_data_size(&self) -> usize {
183        self.transport.inner().max_data_size()
184    }
185
186    /// Set the max. frame data size we support.
187    ///
188    /// The limit applies to the payload of a single frame as well as to a complete
189    /// message, on both dialed (outbound) and accepted (inbound) connections.
190    pub fn set_max_data_size(&mut self, size: usize) -> &mut Self {
191        self.transport.inner_mut().set_max_data_size(size);
192        self
193    }
194
195    /// Set the TLS configuration if TLS support is desired.
196    pub fn set_tls_config(&mut self, c: tls::Config) -> &mut Self {
197        self.transport.inner_mut().set_tls_config(c);
198        self
199    }
200}
201
202impl<T> Transport for Config<T>
203where
204    T: Transport + Send + Unpin + 'static,
205    T::Error: Send + 'static,
206    T::Dial: Send + 'static,
207    T::ListenerUpgrade: Send + 'static,
208    T::Output: AsyncRead + AsyncWrite + Unpin + Send + 'static,
209{
210    type Output = RwStreamSink<BytesConnection<T::Output>>;
211    type Error = Error<T::Error>;
212    type ListenerUpgrade = MapFuture<InnerFuture<T::Output, T::Error>, WrapperFn<T::Output>>;
213    type Dial = MapFuture<InnerFuture<T::Output, T::Error>, WrapperFn<T::Output>>;
214
215    fn listen_on(
216        &mut self,
217        id: ListenerId,
218        addr: Multiaddr,
219    ) -> Result<(), TransportError<Self::Error>> {
220        self.transport.listen_on(id, addr)
221    }
222
223    fn remove_listener(&mut self, id: ListenerId) -> bool {
224        self.transport.remove_listener(id)
225    }
226
227    fn dial(
228        &mut self,
229        addr: Multiaddr,
230        opts: DialOpts,
231    ) -> Result<Self::Dial, TransportError<Self::Error>> {
232        self.transport.dial(addr, opts)
233    }
234
235    fn poll(
236        mut self: Pin<&mut Self>,
237        cx: &mut Context<'_>,
238    ) -> Poll<TransportEvent<Self::ListenerUpgrade, Self::Error>> {
239        Pin::new(&mut self.transport).poll(cx)
240    }
241}
242
243/// Type alias corresponding to `framed::Config::Dial` and `framed::Config::ListenerUpgrade`.
244pub type InnerFuture<T, E> = BoxFuture<'static, Result<Connection<T>, Error<E>>>;
245
246/// Function type that wraps a websocket connection (see. `wrap_connection`).
247pub type WrapperFn<T> = fn(Connection<T>, ConnectedPoint) -> RwStreamSink<BytesConnection<T>>;
248
249/// Wrap a websocket connection producing data frames into a `RwStreamSink`
250/// implementing `AsyncRead` + `AsyncWrite`.
251fn wrap_connection<T>(c: Connection<T>, _: ConnectedPoint) -> RwStreamSink<BytesConnection<T>>
252where
253    T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
254{
255    RwStreamSink::new(BytesConnection(c))
256}
257
258/// The websocket connection.
259#[derive(Debug)]
260pub struct BytesConnection<T>(Connection<T>);
261
262impl<T> Stream for BytesConnection<T>
263where
264    T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
265{
266    type Item = io::Result<Vec<u8>>;
267
268    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
269        loop {
270            if let Some(item) = ready!(self.0.try_poll_next_unpin(cx)?) {
271                if let Incoming::Data(payload) = item {
272                    return Poll::Ready(Some(Ok(payload.into_bytes())));
273                }
274            } else {
275                return Poll::Ready(None);
276            }
277        }
278    }
279}
280
281impl<T> Sink<Vec<u8>> for BytesConnection<T>
282where
283    T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
284{
285    type Error = io::Error;
286
287    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
288        Pin::new(&mut self.0).poll_ready(cx)
289    }
290
291    fn start_send(mut self: Pin<&mut Self>, item: Vec<u8>) -> io::Result<()> {
292        Pin::new(&mut self.0).start_send(framed::OutgoingData::Binary(item))
293    }
294
295    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
296        Pin::new(&mut self.0).poll_flush(cx)
297    }
298
299    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
300        Pin::new(&mut self.0).poll_close(cx)
301    }
302}
303
304// Tests //////////////////////////////////////////////////////////////////////////////////////////
305
306#[cfg(test)]
307mod tests {
308    use std::time::Duration;
309
310    use futures::prelude::*;
311    use libp2p_core::{
312        Endpoint, Multiaddr, Transport,
313        multiaddr::Protocol,
314        transport::{DialOpts, ListenerId, PortUse},
315    };
316    use libp2p_identity::PeerId;
317    use libp2p_tcp as tcp;
318    use soketto::handshake;
319
320    use super::Config;
321
322    #[tokio::test]
323    async fn dialer_connects_to_listener_ipv4() {
324        let a = "/ip4/127.0.0.1/tcp/0/ws".parse().unwrap();
325        connect(a).await
326    }
327
328    #[tokio::test]
329    async fn dialer_connects_to_listener_ipv6() {
330        let a = "/ip6/::1/tcp/0/ws".parse().unwrap();
331        connect(a).await
332    }
333
334    fn new_ws_config() -> Config<tcp::tokio::Transport> {
335        Config::new(tcp::tokio::Transport::new(tcp::Config::default()))
336    }
337
338    async fn connect(listen_addr: Multiaddr) {
339        let mut ws_config = new_ws_config().boxed();
340        ws_config
341            .listen_on(ListenerId::next(), listen_addr)
342            .expect("listener");
343
344        let addr = ws_config
345            .next()
346            .await
347            .expect("no error")
348            .into_new_address()
349            .expect("listen address");
350
351        assert_eq!(Some(Protocol::Ws("/".into())), addr.iter().nth(2));
352        assert_ne!(Some(Protocol::Tcp(0)), addr.iter().nth(1));
353
354        let inbound = async move {
355            let (conn, _addr) = ws_config
356                .select_next_some()
357                .map(|ev| ev.into_incoming())
358                .await
359                .unwrap();
360            conn.await
361        };
362
363        let outbound = new_ws_config()
364            .boxed()
365            .dial(
366                addr.with(Protocol::P2p(PeerId::random())),
367                DialOpts {
368                    role: Endpoint::Dialer,
369                    port_use: PortUse::New,
370                },
371            )
372            .unwrap();
373
374        let (a, b) = futures::join!(inbound, outbound);
375        a.and(b).unwrap();
376    }
377
378    const LIMIT: usize = 1024 * 1024;
379
380    #[tokio::test]
381    async fn dialer_applies_max_data_size() {
382        let mut buf = [0u8; 1];
383
384        // A frame header announcing more than the limit is rejected right away,
385        // without waiting for (or allocating) the announced payload.
386        let mut conn = dial_fake_server(LIMIT + 1).await;
387        let err = tokio::time::timeout(Duration::from_secs(10), conn.read(&mut buf))
388            .await
389            .expect("oversized frame header must be rejected without waiting for its payload")
390            .expect_err("oversized frame header must be rejected");
391        let inner = err
392            .get_ref()
393            .and_then(|e| e.downcast_ref::<soketto::connection::Error>());
394        assert!(
395            matches!(
396                inner,
397                Some(soketto::connection::Error::Codec(
398                    soketto::base::Error::PayloadTooLarge { .. }
399                ))
400            ),
401            "unexpected error: {err:?}"
402        );
403
404        // Control: a frame header within the limit waits for its payload.
405        let mut conn = dial_fake_server(LIMIT).await;
406        assert!(
407            tokio::time::timeout(Duration::from_millis(100), conn.read(&mut buf))
408                .await
409                .is_err(),
410            "frame within the limit must wait for its payload"
411        );
412    }
413
414    /// Dials a fake WebSocket server with `max_data_size` set to [`LIMIT`]. The server completes
415    /// the handshake and then only sends the header of a binary frame announcing
416    /// `announced_len` payload bytes.
417    async fn dial_fake_server(announced_len: usize) -> impl AsyncRead + Unpin {
418        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
419        let port = listener.local_addr().unwrap().port();
420
421        tokio::spawn(async move {
422            let (stream, _) = listener.accept().await.unwrap();
423            let mut server = handshake::Server::new(tcp::tokio::TcpStream(stream));
424            let key = server.receive_request().await.unwrap().key();
425            server
426                .send_response(&handshake::server::Response::Accept {
427                    key,
428                    protocol: None,
429                })
430                .await
431                .unwrap();
432
433            let mut stream = server.into_inner();
434            // FIN + binary opcode, unmasked, 64-bit extended payload length, no payload.
435            let mut header = vec![0x82, 0x7f];
436            header.extend_from_slice(&(announced_len as u64).to_be_bytes());
437            stream.write_all(&header).await.unwrap();
438
439            // Keep the connection open so the dialer never sees EOF.
440            future::pending::<()>().await;
441        });
442
443        let mut config = new_ws_config();
444        config.set_max_data_size(LIMIT);
445        config
446            .dial(
447                format!("/ip4/127.0.0.1/tcp/{port}/ws").parse().unwrap(),
448                DialOpts {
449                    role: Endpoint::Dialer,
450                    port_use: PortUse::New,
451                },
452            )
453            .unwrap()
454            .await
455            .unwrap()
456    }
457}