Skip to main content

libp2p_quic/connection/
connecting.rs

1// Copyright 2017-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
21//! Future that drives a QUIC connection until is has performed its TLS handshake.
22
23use std::{
24    pin::Pin,
25    task::{Context, Poll},
26    time::Duration,
27};
28
29use futures::{
30    future::{Either, FutureExt, Select, select},
31    prelude::*,
32};
33use futures_timer::Delay;
34use libp2p_identity::PeerId;
35use quinn::rustls::pki_types::CertificateDer;
36use quinn_proto::TransportError;
37
38use crate::{Connection, ConnectionError, Error};
39
40/// A QUIC connection currently being negotiated.
41#[derive(Debug)]
42pub struct Connecting {
43    connecting: Select<quinn::Connecting, Delay>,
44}
45
46impl Connecting {
47    pub(crate) fn new(connection: quinn::Connecting, timeout: Duration) -> Self {
48        Connecting {
49            connecting: select(connection, Delay::new(timeout)),
50        }
51    }
52}
53
54impl Connecting {
55    fn remote_peer_id(connection: &quinn::Connection) -> Result<PeerId, Error> {
56        fn transport_err(reason: &str) -> Error {
57            Error::Connection(ConnectionError(quinn::ConnectionError::TransportError(
58                TransportError {
59                    code: quinn::TransportErrorCode::PROTOCOL_VIOLATION,
60                    frame: None,
61                    reason: reason.to_string(),
62                },
63            )))
64        }
65
66        let identity = connection
67            .peer_identity()
68            .ok_or_else(|| transport_err("No crypto identity in quinn's Connection"))?;
69        let certificates: Box<Vec<CertificateDer>> = identity
70            .downcast()
71            .map_err(|_| transport_err("Could not downcast identity"))?;
72        let end_entity = certificates
73            .first()
74            .ok_or_else(|| transport_err("No certificate found"))?;
75        let p2p_cert = libp2p_tls::certificate::parse(end_entity)
76            .map_err(|_| transport_err("Could not parse certificate"))?;
77        Ok(p2p_cert.peer_id())
78    }
79}
80
81impl Future for Connecting {
82    type Output = Result<(PeerId, Connection), Error>;
83
84    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
85        let connection = match futures::ready!(self.connecting.poll_unpin(cx)) {
86            Either::Right(_) => return Poll::Ready(Err(Error::HandshakeTimedOut)),
87            Either::Left((connection, _)) => connection.map_err(ConnectionError)?,
88        };
89
90        let peer_id = Self::remote_peer_id(&connection)?;
91        let muxer = Connection::new(connection);
92        Poll::Ready(Ok((peer_id, muxer)))
93    }
94}