Skip to main content

libp2p_websocket/
framed.rs

1// Copyright 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
21use std::{
22    borrow::Cow,
23    collections::HashMap,
24    fmt, io, mem,
25    net::IpAddr,
26    ops::DerefMut,
27    pin::Pin,
28    sync::Arc,
29    task::{Context, Poll},
30};
31
32use either::Either;
33use futures::{future::BoxFuture, prelude::*, ready, stream::BoxStream};
34use futures_rustls::{client, rustls::pki_types::ServerName, server};
35use libp2p_core::{
36    Transport,
37    multiaddr::{Multiaddr, Protocol},
38    transport::{DialOpts, ListenerId, TransportError, TransportEvent},
39};
40use parking_lot::Mutex;
41use soketto::{
42    connection::{self, CloseReason},
43    handshake,
44};
45use url::Url;
46
47use crate::{error::Error, quicksink, tls};
48
49/// Max. number of payload bytes of a single frame.
50const MAX_DATA_SIZE: usize = 256 * 1024 * 1024;
51
52/// A Websocket transport whose output type is a [`Stream`] and [`Sink`] of
53/// frame payloads which does not implement [`AsyncRead`] or
54/// [`AsyncWrite`]. See [`crate::Config`] if you require the latter.
55#[deprecated = "Use `Config` instead"]
56pub type WsConfig<T> = Config<T>;
57
58#[derive(Debug)]
59pub struct Config<T> {
60    transport: Arc<Mutex<T>>,
61    max_data_size: usize,
62    tls_config: tls::Config,
63    max_redirects: u8,
64    /// Websocket protocol of the inner listener.
65    listener_protos: HashMap<ListenerId, WsListenProto<'static>>,
66}
67
68impl<T> Config<T>
69where
70    T: Send,
71{
72    /// Create a new websocket transport based on another transport.
73    pub fn new(transport: T) -> Self {
74        Config {
75            transport: Arc::new(Mutex::new(transport)),
76            max_data_size: MAX_DATA_SIZE,
77            tls_config: tls::Config::client(),
78            max_redirects: 0,
79            listener_protos: HashMap::new(),
80        }
81    }
82
83    /// Return the configured maximum number of redirects.
84    pub fn max_redirects(&self) -> u8 {
85        self.max_redirects
86    }
87
88    /// Set max. number of redirects to follow.
89    pub fn set_max_redirects(&mut self, max: u8) -> &mut Self {
90        self.max_redirects = max;
91        self
92    }
93
94    /// Get the max. frame data size we support.
95    pub fn max_data_size(&self) -> usize {
96        self.max_data_size
97    }
98
99    /// Set the max. frame data size we support.
100    ///
101    /// The limit applies to the payload of a single frame as well as to a complete
102    /// message, on both dialed (outbound) and accepted (inbound) connections.
103    pub fn set_max_data_size(&mut self, size: usize) -> &mut Self {
104        self.max_data_size = size;
105        self
106    }
107
108    /// Set the TLS configuration if TLS support is desired.
109    pub fn set_tls_config(&mut self, c: tls::Config) -> &mut Self {
110        self.tls_config = c;
111        self
112    }
113}
114
115type TlsOrPlain<T> = future::Either<future::Either<client::TlsStream<T>, server::TlsStream<T>>, T>;
116
117impl<T> Transport for Config<T>
118where
119    T: Transport + Send + Unpin + 'static,
120    T::Error: Send + 'static,
121    T::Dial: Send + 'static,
122    T::ListenerUpgrade: Send + 'static,
123    T::Output: AsyncRead + AsyncWrite + Unpin + Send + 'static,
124{
125    type Output = Connection<T::Output>;
126    type Error = Error<T::Error>;
127    type ListenerUpgrade = BoxFuture<'static, Result<Self::Output, Self::Error>>;
128    type Dial = BoxFuture<'static, Result<Self::Output, Self::Error>>;
129
130    fn listen_on(
131        &mut self,
132        id: ListenerId,
133        addr: Multiaddr,
134    ) -> Result<(), TransportError<Self::Error>> {
135        let (inner_addr, proto) = parse_ws_listen_addr(&addr).ok_or_else(|| {
136            tracing::debug!(address=%addr, "Address is not a websocket multiaddr");
137            TransportError::MultiaddrNotSupported(addr.clone())
138        })?;
139
140        if proto.use_tls() && self.tls_config.server.is_none() {
141            tracing::debug!(
142                "{} address but TLS server support is not configured",
143                proto.prefix()
144            );
145            return Err(TransportError::MultiaddrNotSupported(addr));
146        }
147
148        match self.transport.lock().listen_on(id, inner_addr) {
149            Ok(()) => {
150                self.listener_protos.insert(id, proto);
151                Ok(())
152            }
153            Err(e) => Err(e.map(Error::Transport)),
154        }
155    }
156
157    fn remove_listener(&mut self, id: ListenerId) -> bool {
158        self.transport.lock().remove_listener(id)
159    }
160
161    fn dial(
162        &mut self,
163        addr: Multiaddr,
164        dial_opts: DialOpts,
165    ) -> Result<Self::Dial, TransportError<Self::Error>> {
166        self.do_dial(addr, dial_opts)
167    }
168
169    fn poll(
170        mut self: Pin<&mut Self>,
171        cx: &mut Context<'_>,
172    ) -> Poll<libp2p_core::transport::TransportEvent<Self::ListenerUpgrade, Self::Error>> {
173        let inner_event = {
174            let mut transport = self.transport.lock();
175            match Transport::poll(Pin::new(transport.deref_mut()), cx) {
176                Poll::Ready(ev) => ev,
177                Poll::Pending => return Poll::Pending,
178            }
179        };
180        let event = match inner_event {
181            TransportEvent::NewAddress {
182                listener_id,
183                mut listen_addr,
184            } => {
185                // Append the ws / wss protocol back to the inner address.
186                self.listener_protos
187                    .get(&listener_id)
188                    .expect("Protocol was inserted in Transport::listen_on.")
189                    .append_on_addr(&mut listen_addr);
190                tracing::debug!(address=%listen_addr, "Listening on address");
191                TransportEvent::NewAddress {
192                    listener_id,
193                    listen_addr,
194                }
195            }
196            TransportEvent::AddressExpired {
197                listener_id,
198                mut listen_addr,
199            } => {
200                self.listener_protos
201                    .get(&listener_id)
202                    .expect("Protocol was inserted in Transport::listen_on.")
203                    .append_on_addr(&mut listen_addr);
204                TransportEvent::AddressExpired {
205                    listener_id,
206                    listen_addr,
207                }
208            }
209            TransportEvent::ListenerError { listener_id, error } => TransportEvent::ListenerError {
210                listener_id,
211                error: Error::Transport(error),
212            },
213            TransportEvent::ListenerClosed {
214                listener_id,
215                reason,
216            } => {
217                self.listener_protos
218                    .remove(&listener_id)
219                    .expect("Protocol was inserted in Transport::listen_on.");
220                TransportEvent::ListenerClosed {
221                    listener_id,
222                    reason: reason.map_err(Error::Transport),
223                }
224            }
225            TransportEvent::Incoming {
226                listener_id,
227                upgrade,
228                mut local_addr,
229                mut send_back_addr,
230            } => {
231                let proto = self
232                    .listener_protos
233                    .get(&listener_id)
234                    .expect("Protocol was inserted in Transport::listen_on.");
235                let use_tls = proto.use_tls();
236                proto.append_on_addr(&mut local_addr);
237                proto.append_on_addr(&mut send_back_addr);
238                let upgrade = self.map_upgrade(upgrade, send_back_addr.clone(), use_tls);
239                TransportEvent::Incoming {
240                    listener_id,
241                    upgrade,
242                    local_addr,
243                    send_back_addr,
244                }
245            }
246        };
247        Poll::Ready(event)
248    }
249}
250
251impl<T> Config<T>
252where
253    T: Transport + Send + Unpin + 'static,
254    T::Error: Send + 'static,
255    T::Dial: Send + 'static,
256    T::ListenerUpgrade: Send + 'static,
257    T::Output: AsyncRead + AsyncWrite + Unpin + Send + 'static,
258{
259    fn do_dial(
260        &mut self,
261        addr: Multiaddr,
262        dial_opts: DialOpts,
263    ) -> Result<<Self as Transport>::Dial, TransportError<<Self as Transport>::Error>> {
264        let mut addr = match parse_ws_dial_addr(addr) {
265            Ok(addr) => addr,
266            Err(Error::InvalidMultiaddr(a)) => {
267                return Err(TransportError::MultiaddrNotSupported(a));
268            }
269            Err(e) => return Err(TransportError::Other(e)),
270        };
271
272        // We are looping here in order to follow redirects (if any):
273        let mut remaining_redirects = self.max_redirects;
274
275        let transport = self.transport.clone();
276        let tls_config = self.tls_config.clone();
277        let max_redirects = self.max_redirects;
278        let max_data_size = self.max_data_size;
279
280        let future = async move {
281            loop {
282                match Self::dial_once(
283                    transport.clone(),
284                    addr,
285                    tls_config.clone(),
286                    dial_opts,
287                    max_data_size,
288                )
289                .await
290                {
291                    Ok(Either::Left(redirect)) => {
292                        if remaining_redirects == 0 {
293                            tracing::debug!(%max_redirects, "Too many redirects");
294                            return Err(Error::TooManyRedirects);
295                        }
296                        remaining_redirects -= 1;
297                        addr = parse_ws_dial_addr(location_to_multiaddr(&redirect)?)?
298                    }
299                    Ok(Either::Right(conn)) => return Ok(conn),
300                    Err(e) => return Err(e),
301                }
302            }
303        };
304
305        Ok(Box::pin(future))
306    }
307
308    /// Attempts to dial the given address and perform a websocket handshake.
309    async fn dial_once(
310        transport: Arc<Mutex<T>>,
311        addr: WsAddress,
312        tls_config: tls::Config,
313        dial_opts: DialOpts,
314        max_data_size: usize,
315    ) -> Result<Either<String, Connection<T::Output>>, Error<T::Error>> {
316        tracing::trace!(address=?addr, "Dialing websocket address");
317
318        let dial = transport
319            .lock()
320            .dial(addr.tcp_addr, dial_opts)
321            .map_err(|e| match e {
322                TransportError::MultiaddrNotSupported(a) => Error::InvalidMultiaddr(a),
323                TransportError::Other(e) => Error::Transport(e),
324            })?;
325
326        let stream = dial.map_err(Error::Transport).await?;
327        tracing::trace!(port=%addr.host_port, "TCP connection established");
328
329        let stream = if addr.use_tls {
330            // begin TLS session
331            tracing::trace!(?addr.server_name, "Starting TLS handshake");
332            let stream = tls_config
333                .client
334                .connect(addr.server_name.clone(), stream)
335                .map_err(|e| {
336                    tracing::debug!(?addr.server_name, "TLS handshake failed: {}", e);
337                    Error::Tls(tls::Error::from(e))
338                })
339                .await?;
340
341            let stream: TlsOrPlain<_> = future::Either::Left(future::Either::Left(stream));
342            stream
343        } else {
344            // continue with plain stream
345            future::Either::Right(stream)
346        };
347
348        tracing::trace!(port=%addr.host_port, "Sending websocket handshake");
349
350        let mut client = handshake::Client::new(stream, &addr.host_port, addr.path.as_ref());
351
352        match client
353            .handshake()
354            .map_err(|e| Error::Handshake(Box::new(e)))
355            .await?
356        {
357            handshake::ServerResponse::Redirect {
358                status_code,
359                location,
360            } => {
361                tracing::debug!(
362                    %status_code,
363                    %location,
364                    "received redirect"
365                );
366                Ok(Either::Left(location))
367            }
368            handshake::ServerResponse::Rejected { status_code } => {
369                let msg = format!("server rejected handshake; status code = {status_code}");
370                Err(Error::Handshake(msg.into()))
371            }
372            handshake::ServerResponse::Accepted { .. } => {
373                tracing::trace!(port=%addr.host_port, "websocket handshake successful");
374                let mut builder = client.into_builder();
375                builder.set_max_message_size(max_data_size);
376                builder.set_max_frame_size(max_data_size);
377                Ok(Either::Right(Connection::new(builder)))
378            }
379        }
380    }
381
382    fn map_upgrade(
383        &self,
384        upgrade: T::ListenerUpgrade,
385        remote_addr: Multiaddr,
386        use_tls: bool,
387    ) -> <Self as Transport>::ListenerUpgrade {
388        let remote_addr2 = remote_addr.clone(); // used for logging
389        let tls_config = self.tls_config.clone();
390        let max_size = self.max_data_size;
391
392        async move {
393            let stream = upgrade.map_err(Error::Transport).await?;
394            tracing::trace!(address=%remote_addr, "incoming connection from address");
395
396            let stream = if use_tls {
397                // begin TLS session
398                let server = tls_config
399                    .server
400                    .expect("for use_tls we checked server is not none");
401
402                tracing::trace!(address=%remote_addr, "awaiting TLS handshake with address");
403
404                let stream = server
405                    .accept(stream)
406                    .map_err(move |e| {
407                        tracing::debug!(address=%remote_addr, "TLS handshake with address failed: {}", e);
408                        Error::Tls(tls::Error::from(e))
409                    })
410                    .await?;
411
412                let stream: TlsOrPlain<_> = future::Either::Left(future::Either::Right(stream));
413
414                stream
415            } else {
416                // continue with plain stream
417                future::Either::Right(stream)
418            };
419
420            tracing::trace!(
421                address=%remote_addr2,
422                "receiving websocket handshake request from address"
423            );
424
425            let mut server = handshake::Server::new(stream);
426
427            let ws_key = {
428                let request = server
429                    .receive_request()
430                    .map_err(|e| Error::Handshake(Box::new(e)))
431                    .await?;
432                request.key()
433            };
434
435            tracing::trace!(
436                address=%remote_addr2,
437                "accepting websocket handshake request from address"
438            );
439
440            let response = handshake::server::Response::Accept {
441                key: ws_key,
442                protocol: None,
443            };
444
445            server
446                .send_response(&response)
447                .map_err(|e| Error::Handshake(Box::new(e)))
448                .await?;
449
450            let conn = {
451                let mut builder = server.into_builder();
452                builder.set_max_message_size(max_size);
453                builder.set_max_frame_size(max_size);
454                Connection::new(builder)
455            };
456
457            Ok(conn)
458        }
459        .boxed()
460    }
461}
462
463#[derive(Debug, PartialEq)]
464pub(crate) enum WsListenProto<'a> {
465    Ws(Cow<'a, str>),
466    Wss(Cow<'a, str>),
467    TlsWs(Cow<'a, str>),
468}
469
470impl WsListenProto<'_> {
471    pub(crate) fn append_on_addr(&self, addr: &mut Multiaddr) {
472        match self {
473            WsListenProto::Ws(path) => {
474                addr.push(Protocol::Ws(path.clone()));
475            }
476            // `/tls/ws` and `/wss` are equivalend, however we regenerate
477            // the one that user passed at `listen_on` for backward compatibility.
478            WsListenProto::Wss(path) => {
479                addr.push(Protocol::Wss(path.clone()));
480            }
481            WsListenProto::TlsWs(path) => {
482                addr.push(Protocol::Tls);
483                addr.push(Protocol::Ws(path.clone()));
484            }
485        }
486    }
487
488    pub(crate) fn use_tls(&self) -> bool {
489        match self {
490            WsListenProto::Ws(_) => false,
491            WsListenProto::Wss(_) => true,
492            WsListenProto::TlsWs(_) => true,
493        }
494    }
495
496    pub(crate) fn prefix(&self) -> &'static str {
497        match self {
498            WsListenProto::Ws(_) => "/ws",
499            WsListenProto::Wss(_) => "/wss",
500            WsListenProto::TlsWs(_) => "/tls/ws",
501        }
502    }
503}
504
505#[derive(Debug)]
506struct WsAddress {
507    host_port: String,
508    path: String,
509    server_name: ServerName<'static>,
510    use_tls: bool,
511    tcp_addr: Multiaddr,
512}
513
514/// Tries to parse the given `Multiaddr` into a `WsAddress` used
515/// for dialing.
516///
517/// Fails if the given `Multiaddr` does not represent a TCP/IP-based
518/// websocket protocol stack.
519fn parse_ws_dial_addr<T>(addr: Multiaddr) -> Result<WsAddress, Error<T>> {
520    // The encapsulating protocol must be based on TCP/IP, possibly via DNS.
521    // We peek at it in order to learn the hostname and port to use for
522    // the websocket handshake.
523    let mut protocols = addr.iter();
524    let mut ip = protocols.next();
525    let mut tcp = protocols.next();
526    let (host_port, mut server_name) = loop {
527        match (ip, tcp) {
528            (Some(Protocol::Ip4(ip)), Some(Protocol::Tcp(port))) => {
529                let server_name = ServerName::IpAddress(IpAddr::V4(ip).into());
530                break (format!("{ip}:{port}"), server_name);
531            }
532            (Some(Protocol::Ip6(ip)), Some(Protocol::Tcp(port))) => {
533                let server_name = ServerName::IpAddress(IpAddr::V6(ip).into());
534                break (format!("[{ip}]:{port}"), server_name);
535            }
536            (Some(Protocol::Dns(h)), Some(Protocol::Tcp(port)))
537            | (Some(Protocol::Dns4(h)), Some(Protocol::Tcp(port)))
538            | (Some(Protocol::Dns6(h)), Some(Protocol::Tcp(port))) => {
539                break (format!("{h}:{port}"), tls::dns_name_ref(&h)?);
540            }
541            (Some(_), Some(p)) => {
542                ip = Some(p);
543                tcp = protocols.next();
544            }
545            _ => return Err(Error::InvalidMultiaddr(addr)),
546        }
547    };
548
549    // Will hold a value if the multiaddr carries `/tls/sni/<host>`.
550    let mut sni_override: Option<ServerName<'static>> = None;
551    // Now consume the `Ws` / `Wss` protocol from the end of the address,
552    // preserving the trailing `P2p` protocol that identifies the remote,
553    // if any.
554    let mut protocols = addr.clone();
555    let mut p2p = None;
556    let (use_tls, path) = loop {
557        match protocols.pop() {
558            p @ Some(Protocol::P2p(_)) => p2p = p,
559            Some(Protocol::Ws(path)) => match protocols.pop() {
560                Some(Protocol::Sni(domain)) => match protocols.pop() {
561                    Some(Protocol::Tls) => {
562                        sni_override = Some(tls::dns_name_ref(&domain)?);
563                        break (true, path.into_owned());
564                    }
565                    _ => return Err(Error::InvalidMultiaddr(addr)),
566                },
567                Some(Protocol::Tls) => break (true, path.into_owned()),
568                Some(p) => {
569                    protocols.push(p);
570                    break (false, path.into_owned());
571                }
572                None => return Err(Error::InvalidMultiaddr(addr)),
573            },
574            Some(Protocol::Wss(path)) => break (true, path.into_owned()),
575            _ => return Err(Error::InvalidMultiaddr(addr)),
576        }
577    };
578
579    // The original address, stripped of the `/ws` and `/wss` protocols,
580    // makes up the address for the inner TCP-based transport.
581    let tcp_addr = match p2p {
582        Some(p) => protocols.with(p),
583        None => protocols,
584    };
585
586    if let Some(name) = sni_override {
587        server_name = name;
588    }
589    Ok(WsAddress {
590        host_port,
591        server_name,
592        path,
593        use_tls,
594        tcp_addr,
595    })
596}
597
598fn parse_ws_listen_addr(addr: &Multiaddr) -> Option<(Multiaddr, WsListenProto<'static>)> {
599    let mut inner_addr = addr.clone();
600
601    match inner_addr.pop()? {
602        Protocol::Wss(path) => Some((inner_addr, WsListenProto::Wss(path))),
603        Protocol::Ws(path) => match inner_addr.pop()? {
604            Protocol::Tls => Some((inner_addr, WsListenProto::TlsWs(path))),
605            p => {
606                inner_addr.push(p);
607                Some((inner_addr, WsListenProto::Ws(path)))
608            }
609        },
610        _ => None,
611    }
612}
613
614// Given a location URL, build a new websocket [`Multiaddr`].
615fn location_to_multiaddr<T>(location: &str) -> Result<Multiaddr, Error<T>> {
616    match Url::parse(location) {
617        Ok(url) => {
618            let mut a = Multiaddr::empty();
619            match url.host() {
620                Some(url::Host::Domain(h)) => a.push(Protocol::Dns(h.into())),
621                Some(url::Host::Ipv4(ip)) => a.push(Protocol::Ip4(ip)),
622                Some(url::Host::Ipv6(ip)) => a.push(Protocol::Ip6(ip)),
623                None => return Err(Error::InvalidRedirectLocation),
624            }
625            if let Some(p) = url.port() {
626                a.push(Protocol::Tcp(p))
627            }
628            let s = url.scheme();
629            if s.eq_ignore_ascii_case("https") | s.eq_ignore_ascii_case("wss") {
630                a.push(Protocol::Tls);
631                a.push(Protocol::Ws(url.path().into()));
632            } else if s.eq_ignore_ascii_case("http") | s.eq_ignore_ascii_case("ws") {
633                a.push(Protocol::Ws(url.path().into()))
634            } else {
635                tracing::debug!(scheme=%s, "unsupported scheme");
636                return Err(Error::InvalidRedirectLocation);
637            }
638            Ok(a)
639        }
640        Err(e) => {
641            tracing::debug!("failed to parse url as multi-address: {:?}", e);
642            Err(Error::InvalidRedirectLocation)
643        }
644    }
645}
646
647/// The websocket connection.
648pub struct Connection<T> {
649    receiver: BoxStream<'static, Result<Incoming, connection::Error>>,
650    sender: Pin<Box<dyn Sink<OutgoingData, Error = quicksink::Error<connection::Error>> + Send>>,
651    _marker: std::marker::PhantomData<T>,
652}
653
654/// Data or control information received over the websocket connection.
655#[derive(Debug, Clone)]
656pub enum Incoming {
657    /// Application data.
658    Data(Data),
659    /// PONG control frame data.
660    Pong(Vec<u8>),
661    /// Close reason.
662    Closed(CloseReason),
663}
664
665/// Application data received over the websocket connection
666#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
667pub enum Data {
668    /// UTF-8 encoded textual data.
669    Text(Vec<u8>),
670    /// Binary data.
671    Binary(Vec<u8>),
672}
673
674impl Data {
675    pub fn into_bytes(self) -> Vec<u8> {
676        match self {
677            Data::Text(d) => d,
678            Data::Binary(d) => d,
679        }
680    }
681}
682
683impl AsRef<[u8]> for Data {
684    fn as_ref(&self) -> &[u8] {
685        match self {
686            Data::Text(d) => d,
687            Data::Binary(d) => d,
688        }
689    }
690}
691
692impl Incoming {
693    pub fn is_data(&self) -> bool {
694        self.is_binary() || self.is_text()
695    }
696
697    pub fn is_binary(&self) -> bool {
698        matches!(self, Incoming::Data(Data::Binary(_)))
699    }
700
701    pub fn is_text(&self) -> bool {
702        matches!(self, Incoming::Data(Data::Text(_)))
703    }
704
705    pub fn is_pong(&self) -> bool {
706        matches!(self, Incoming::Pong(_))
707    }
708
709    pub fn is_close(&self) -> bool {
710        matches!(self, Incoming::Closed(_))
711    }
712}
713
714/// Data sent over the websocket connection.
715#[derive(Debug, Clone)]
716pub enum OutgoingData {
717    /// Send some bytes.
718    Binary(Vec<u8>),
719    /// Send a PING message.
720    Ping(Vec<u8>),
721    /// Send an unsolicited PONG message.
722    /// (Incoming PINGs are answered automatically.)
723    Pong(Vec<u8>),
724}
725
726impl<T> fmt::Debug for Connection<T> {
727    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
728        f.write_str("Connection")
729    }
730}
731
732impl<T> Connection<T>
733where
734    T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
735{
736    fn new(builder: connection::Builder<TlsOrPlain<T>>) -> Self {
737        let (sender, receiver) = builder.finish();
738        let sink = quicksink::make_sink(sender, |mut sender, action| async move {
739            match action {
740                quicksink::Action::Send(OutgoingData::Binary(x)) => {
741                    sender.send_binary_mut(x).await?
742                }
743                quicksink::Action::Send(OutgoingData::Ping(x)) => {
744                    let data = x[..].try_into().map_err(|_| {
745                        io::Error::new(io::ErrorKind::InvalidInput, "PING data must be < 126 bytes")
746                    })?;
747                    sender.send_ping(data).await?
748                }
749                quicksink::Action::Send(OutgoingData::Pong(x)) => {
750                    let data = x[..].try_into().map_err(|_| {
751                        io::Error::new(io::ErrorKind::InvalidInput, "PONG data must be < 126 bytes")
752                    })?;
753                    sender.send_pong(data).await?
754                }
755                quicksink::Action::Flush => sender.flush().await?,
756                quicksink::Action::Close => sender.close().await?,
757            }
758            Ok(sender)
759        });
760        let stream = stream::unfold((Vec::new(), receiver), |(mut data, mut receiver)| async {
761            match receiver.receive(&mut data).await {
762                Ok(soketto::Incoming::Data(soketto::Data::Text(_))) => Some((
763                    Ok(Incoming::Data(Data::Text(mem::take(&mut data)))),
764                    (data, receiver),
765                )),
766                Ok(soketto::Incoming::Data(soketto::Data::Binary(_))) => Some((
767                    Ok(Incoming::Data(Data::Binary(mem::take(&mut data)))),
768                    (data, receiver),
769                )),
770                Ok(soketto::Incoming::Pong(pong)) => {
771                    Some((Ok(Incoming::Pong(Vec::from(pong))), (data, receiver)))
772                }
773                Ok(soketto::Incoming::Closed(reason)) => {
774                    Some((Ok(Incoming::Closed(reason)), (data, receiver)))
775                }
776                Err(connection::Error::Closed) => None,
777                Err(e) => Some((Err(e), (data, receiver))),
778            }
779        });
780        Connection {
781            receiver: stream.boxed(),
782            sender: Box::pin(sink),
783            _marker: std::marker::PhantomData,
784        }
785    }
786
787    /// Send binary application data to the remote.
788    pub fn send_data(&mut self, data: Vec<u8>) -> sink::Send<'_, Self, OutgoingData> {
789        self.send(OutgoingData::Binary(data))
790    }
791
792    /// Send a PING to the remote.
793    pub fn send_ping(&mut self, data: Vec<u8>) -> sink::Send<'_, Self, OutgoingData> {
794        self.send(OutgoingData::Ping(data))
795    }
796
797    /// Send an unsolicited PONG to the remote.
798    pub fn send_pong(&mut self, data: Vec<u8>) -> sink::Send<'_, Self, OutgoingData> {
799        self.send(OutgoingData::Pong(data))
800    }
801}
802
803impl<T> Stream for Connection<T>
804where
805    T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
806{
807    type Item = io::Result<Incoming>;
808
809    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
810        let item = ready!(self.receiver.poll_next_unpin(cx));
811        let item = item.map(|result| result.map_err(io::Error::other));
812        Poll::Ready(item)
813    }
814}
815
816impl<T> Sink<OutgoingData> for Connection<T>
817where
818    T: AsyncRead + AsyncWrite + Send + Unpin + 'static,
819{
820    type Error = io::Error;
821
822    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
823        Pin::new(&mut self.sender)
824            .poll_ready(cx)
825            .map_err(io::Error::other)
826    }
827
828    fn start_send(mut self: Pin<&mut Self>, item: OutgoingData) -> io::Result<()> {
829        Pin::new(&mut self.sender)
830            .start_send(item)
831            .map_err(io::Error::other)
832    }
833
834    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
835        Pin::new(&mut self.sender)
836            .poll_flush(cx)
837            .map_err(io::Error::other)
838    }
839
840    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
841        Pin::new(&mut self.sender)
842            .poll_close(cx)
843            .map_err(io::Error::other)
844    }
845}
846
847#[cfg(test)]
848mod tests {
849    use std::io;
850
851    use libp2p_identity::PeerId;
852
853    use super::*;
854
855    #[test]
856    fn listen_addr() {
857        let tcp_addr = "/ip4/0.0.0.0/tcp/2222".parse::<Multiaddr>().unwrap();
858
859        // Check `/tls/ws`
860        let addr = tcp_addr
861            .clone()
862            .with(Protocol::Tls)
863            .with(Protocol::Ws("/".into()));
864        let (inner_addr, proto) = parse_ws_listen_addr(&addr).unwrap();
865        assert_eq!(&inner_addr, &tcp_addr);
866        assert_eq!(proto, WsListenProto::TlsWs("/".into()));
867
868        let mut listen_addr = tcp_addr.clone();
869        proto.append_on_addr(&mut listen_addr);
870        assert_eq!(listen_addr, addr);
871
872        // Check `/wss`
873        let addr = tcp_addr.clone().with(Protocol::Wss("/".into()));
874        let (inner_addr, proto) = parse_ws_listen_addr(&addr).unwrap();
875        assert_eq!(&inner_addr, &tcp_addr);
876        assert_eq!(proto, WsListenProto::Wss("/".into()));
877
878        let mut listen_addr = tcp_addr.clone();
879        proto.append_on_addr(&mut listen_addr);
880        assert_eq!(listen_addr, addr);
881
882        // Check `/ws`
883        let addr = tcp_addr.clone().with(Protocol::Ws("/".into()));
884        let (inner_addr, proto) = parse_ws_listen_addr(&addr).unwrap();
885        assert_eq!(&inner_addr, &tcp_addr);
886        assert_eq!(proto, WsListenProto::Ws("/".into()));
887
888        let mut listen_addr = tcp_addr.clone();
889        proto.append_on_addr(&mut listen_addr);
890        assert_eq!(listen_addr, addr);
891    }
892
893    #[test]
894    fn dial_addr() {
895        let peer_id = PeerId::random();
896
897        // Check `/tls/ws`
898        let addr = "/dns4/example.com/tcp/2222/tls/ws"
899            .parse::<Multiaddr>()
900            .unwrap();
901        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
902        assert_eq!(info.host_port, "example.com:2222");
903        assert_eq!(info.path, "/");
904        assert!(info.use_tls);
905        assert_eq!(info.server_name, "example.com".try_into().unwrap());
906        assert_eq!(info.tcp_addr, "/dns4/example.com/tcp/2222".parse().unwrap());
907
908        // Check `/tls/ws` with `/p2p`
909        let addr = format!("/dns4/example.com/tcp/2222/tls/ws/p2p/{peer_id}")
910            .parse()
911            .unwrap();
912        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
913        assert_eq!(info.host_port, "example.com:2222");
914        assert_eq!(info.path, "/");
915        assert!(info.use_tls);
916        assert_eq!(info.server_name, "example.com".try_into().unwrap());
917        assert_eq!(
918            info.tcp_addr,
919            format!("/dns4/example.com/tcp/2222/p2p/{peer_id}")
920                .parse()
921                .unwrap()
922        );
923
924        // Check `/tls/ws` with `/ip4`
925        let addr = "/ip4/127.0.0.1/tcp/2222/tls/ws"
926            .parse::<Multiaddr>()
927            .unwrap();
928        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
929        assert_eq!(info.host_port, "127.0.0.1:2222");
930        assert_eq!(info.path, "/");
931        assert!(info.use_tls);
932        assert_eq!(info.server_name, "127.0.0.1".try_into().unwrap());
933        assert_eq!(info.tcp_addr, "/ip4/127.0.0.1/tcp/2222".parse().unwrap());
934
935        // Check `/tls/ws` with `/ip6`
936        let addr = "/ip6/::1/tcp/2222/tls/ws".parse::<Multiaddr>().unwrap();
937        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
938        assert_eq!(info.host_port, "[::1]:2222");
939        assert_eq!(info.path, "/");
940        assert!(info.use_tls);
941        assert_eq!(info.server_name, "::1".try_into().unwrap());
942        assert_eq!(info.tcp_addr, "/ip6/::1/tcp/2222".parse().unwrap());
943
944        // Check `/wss`
945        let addr = "/dns4/example.com/tcp/2222/wss"
946            .parse::<Multiaddr>()
947            .unwrap();
948        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
949        assert_eq!(info.host_port, "example.com:2222");
950        assert_eq!(info.path, "/");
951        assert!(info.use_tls);
952        assert_eq!(info.server_name, "example.com".try_into().unwrap());
953        assert_eq!(info.tcp_addr, "/dns4/example.com/tcp/2222".parse().unwrap());
954
955        // Check `/wss` with `/p2p`
956        let addr = format!("/dns4/example.com/tcp/2222/wss/p2p/{peer_id}")
957            .parse()
958            .unwrap();
959        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
960        assert_eq!(info.host_port, "example.com:2222");
961        assert_eq!(info.path, "/");
962        assert!(info.use_tls);
963        assert_eq!(info.server_name, "example.com".try_into().unwrap());
964        assert_eq!(
965            info.tcp_addr,
966            format!("/dns4/example.com/tcp/2222/p2p/{peer_id}")
967                .parse()
968                .unwrap()
969        );
970
971        // Check `/wss` with `/ip4`
972        let addr = "/ip4/127.0.0.1/tcp/2222/wss".parse::<Multiaddr>().unwrap();
973        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
974        assert_eq!(info.host_port, "127.0.0.1:2222");
975        assert_eq!(info.path, "/");
976        assert!(info.use_tls);
977        assert_eq!(info.server_name, "127.0.0.1".try_into().unwrap());
978        assert_eq!(info.tcp_addr, "/ip4/127.0.0.1/tcp/2222".parse().unwrap());
979
980        // Check `/wss` with `/ip6`
981        let addr = "/ip6/::1/tcp/2222/wss".parse::<Multiaddr>().unwrap();
982        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
983        assert_eq!(info.host_port, "[::1]:2222");
984        assert_eq!(info.path, "/");
985        assert!(info.use_tls);
986        assert_eq!(info.server_name, "::1".try_into().unwrap());
987        assert_eq!(info.tcp_addr, "/ip6/::1/tcp/2222".parse().unwrap());
988
989        // Check `/ws`
990        let addr = "/dns4/example.com/tcp/2222/ws"
991            .parse::<Multiaddr>()
992            .unwrap();
993        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
994        assert_eq!(info.host_port, "example.com:2222");
995        assert_eq!(info.path, "/");
996        assert!(!info.use_tls);
997        assert_eq!(info.server_name, "example.com".try_into().unwrap());
998        assert_eq!(info.tcp_addr, "/dns4/example.com/tcp/2222".parse().unwrap());
999
1000        // Check `/ws` with `/p2p`
1001        let addr = format!("/dns4/example.com/tcp/2222/ws/p2p/{peer_id}")
1002            .parse()
1003            .unwrap();
1004        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
1005        assert_eq!(info.host_port, "example.com:2222");
1006        assert_eq!(info.path, "/");
1007        assert!(!info.use_tls);
1008        assert_eq!(info.server_name, "example.com".try_into().unwrap());
1009        assert_eq!(
1010            info.tcp_addr,
1011            format!("/dns4/example.com/tcp/2222/p2p/{peer_id}")
1012                .parse()
1013                .unwrap()
1014        );
1015
1016        // Check `/ws` with `/ip4`
1017        let addr = "/ip4/127.0.0.1/tcp/2222/ws".parse::<Multiaddr>().unwrap();
1018        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
1019        assert_eq!(info.host_port, "127.0.0.1:2222");
1020        assert_eq!(info.path, "/");
1021        assert!(!info.use_tls);
1022        assert_eq!(info.server_name, "127.0.0.1".try_into().unwrap());
1023        assert_eq!(info.tcp_addr, "/ip4/127.0.0.1/tcp/2222".parse().unwrap());
1024
1025        // Check `/ws` with `/ip6`
1026        let addr = "/ip6/::1/tcp/2222/ws".parse::<Multiaddr>().unwrap();
1027        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
1028        assert_eq!(info.host_port, "[::1]:2222");
1029        assert_eq!(info.path, "/");
1030        assert!(!info.use_tls);
1031        assert_eq!(info.server_name, "::1".try_into().unwrap());
1032        assert_eq!(info.tcp_addr, "/ip6/::1/tcp/2222".parse().unwrap());
1033
1034        // Check `/dnsaddr`
1035        let addr = "/dnsaddr/example.com/tcp/2222/ws"
1036            .parse::<Multiaddr>()
1037            .unwrap();
1038        parse_ws_dial_addr::<io::Error>(addr).unwrap_err();
1039
1040        // Check non-ws address
1041        let addr = "/ip4/127.0.0.1/tcp/2222".parse::<Multiaddr>().unwrap();
1042        parse_ws_dial_addr::<io::Error>(addr).unwrap_err();
1043
1044        // Check `/tls/sni/.../ws` with `/dns4`
1045        let addr = "/dns4/example.com/tcp/2222/tls/sni/example.com/ws"
1046            .parse::<Multiaddr>()
1047            .unwrap();
1048        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
1049        assert_eq!(info.host_port, "example.com:2222");
1050        assert_eq!(info.path, "/");
1051        assert!(info.use_tls);
1052        assert_eq!(info.server_name, "example.com".try_into().unwrap());
1053        assert_eq!(info.tcp_addr, "/dns4/example.com/tcp/2222".parse().unwrap());
1054
1055        // Check `/tls/sni/.../ws` with `/ip4`
1056        let addr = "/ip4/127.0.0.1/tcp/2222/tls/sni/example.test/ws"
1057            .parse::<Multiaddr>()
1058            .unwrap();
1059        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
1060        assert_eq!(info.host_port, "127.0.0.1:2222");
1061        assert_eq!(info.path, "/");
1062        assert!(info.use_tls);
1063        assert_eq!(info.server_name, "example.test".try_into().unwrap());
1064        assert_eq!(info.tcp_addr, "/ip4/127.0.0.1/tcp/2222".parse().unwrap());
1065
1066        // Check `/tls/sni/.../ws` with trailing `/p2p`
1067        let addr = format!("/dns4/example.com/tcp/2222/tls/sni/example.com/ws/p2p/{peer_id}")
1068            .parse()
1069            .unwrap();
1070        let info = parse_ws_dial_addr::<io::Error>(addr).unwrap();
1071        assert_eq!(info.host_port, "example.com:2222");
1072        assert_eq!(info.path, "/");
1073        assert!(info.use_tls);
1074        assert_eq!(info.server_name, "example.com".try_into().unwrap());
1075        assert_eq!(
1076            info.tcp_addr,
1077            format!("/dns4/example.com/tcp/2222/p2p/{peer_id}")
1078                .parse()
1079                .unwrap()
1080        );
1081
1082        // Negative: `/tls/sni/...` *without* `/ws` → error
1083        let bad = "/dns4/example.com/tcp/2222/tls/sni/example.com"
1084            .parse::<Multiaddr>()
1085            .unwrap();
1086        parse_ws_dial_addr::<io::Error>(bad).unwrap_err();
1087    }
1088}