Skip to main content

coqui_peer_tls/
asynch.rs

1//! Async dial and accept over `tokio-rustls`, for any `AsyncRead + AsyncWrite` stream.
2
3use alloc::sync::Arc;
4use core::net::SocketAddr;
5
6use core::pin::Pin;
7use core::task::{Context, Poll};
8use rustls::pki_types::ServerName;
9use rustls::server::ClientHello;
10use rustls::{ClientConfig, ServerConfig};
11use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
12use tokio_rustls::{TlsConnector, client, server};
13
14use core::time::Duration;
15use std::time::Instant;
16
17use coqui_peer::asynch::{read_frame, write_frame};
18use coqui_peer::pair::{
19    Paired, Pairing, PairingDesk, PairingJoiner, PairingResponder, Rotation, Shown,
20};
21use coqui_peer::{PeerId, TrustStore};
22
23use crate::error::PeerError;
24use crate::error::Refusal;
25use crate::identity::{Identity, PeerIdentity};
26use crate::pairing::{PairConfig, ResponderTrust, ends, left, sooner};
27use crate::policy::CertificateType;
28use crate::source::scoped;
29use crate::stream::{Addressed, PeerAddr, default_server_name, handshake_error, identity_of};
30
31/// Dials a peer over `io`, completing the handshake before returning. The server name sent
32/// is [`SERVER_NAME`](crate::SERVER_NAME); [`dial_named`] sends another.
33///
34/// # Errors
35///
36/// [`PeerError::Io`] when the handshake fails, including a refused peer certificate;
37/// [`PeerError::refusal`] says why this side refused one.
38pub async fn dial<S>(
39    config: Arc<ClientConfig>,
40    io: S,
41) -> Result<(client::TlsStream<S>, PeerIdentity), PeerError>
42where
43    S: AsyncRead + AsyncWrite + Unpin,
44{
45    dial_named(config, default_server_name(), io).await
46}
47
48/// [`dial`] sending `name` as the server name, as [`crate::dial_named`] does.
49///
50/// # Errors
51///
52/// [`PeerError::Io`] when the handshake fails, including a refused server certificate;
53/// [`PeerError::refusal`] says why this side refused one.
54pub async fn dial_named<S>(
55    config: Arc<ClientConfig>,
56    name: ServerName<'static>,
57    io: S,
58) -> Result<(client::TlsStream<S>, PeerIdentity), PeerError>
59where
60    S: AsyncRead + AsyncWrite + Unpin,
61{
62    let stream = TlsConnector::from(config)
63        .connect(name, io)
64        .await
65        .map_err(PeerError::Io)?;
66    let peer = identity_of(stream.get_ref().1.peer_certificates())?;
67    Ok((stream, peer))
68}
69
70impl PeerAddr for tokio::net::TcpStream {
71    fn peer_addr(&self) -> Option<SocketAddr> {
72        tokio::net::TcpStream::peer_addr(self).ok()
73    }
74
75    fn local_addr(&self) -> Option<SocketAddr> {
76        tokio::net::TcpStream::local_addr(self).ok()
77    }
78}
79
80impl<S: AsyncRead + Unpin> AsyncRead for Addressed<S> {
81    fn poll_read(
82        self: Pin<&mut Self>,
83        context: &mut Context<'_>,
84        buffer: &mut ReadBuf<'_>,
85    ) -> Poll<std::io::Result<()>> {
86        Pin::new(Addressed::get_mut(Pin::get_mut(self))).poll_read(context, buffer)
87    }
88}
89
90impl<S: AsyncWrite + Unpin> AsyncWrite for Addressed<S> {
91    fn poll_write(
92        self: Pin<&mut Self>,
93        context: &mut Context<'_>,
94        buffer: &[u8],
95    ) -> Poll<std::io::Result<usize>> {
96        Pin::new(Addressed::get_mut(Pin::get_mut(self))).poll_write(context, buffer)
97    }
98
99    fn poll_flush(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<std::io::Result<()>> {
100        Pin::new(Addressed::get_mut(Pin::get_mut(self))).poll_flush(context)
101    }
102
103    fn poll_shutdown(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<std::io::Result<()>> {
104        Pin::new(Addressed::get_mut(Pin::get_mut(self))).poll_shutdown(context)
105    }
106}
107
108/// Polls `future` with the connection's addresses in scope, since the verifiers' and the
109/// address check's callbacks run inside the poll; returns its output and the refusal the
110/// address check recorded.
111async fn scoped_poll<F: Future>(
112    source: Option<SocketAddr>,
113    local: Option<SocketAddr>,
114    future: F,
115) -> (F::Output, Option<Refusal>) {
116    let mut future = std::pin::pin!(future);
117    let mut refused = None;
118    let output = core::future::poll_fn(|context| {
119        let (poll, refusal) = scoped(source, local, || future.as_mut().poll(context));
120        refused = refused.or(refusal);
121        poll
122    })
123    .await;
124    (output, refused)
125}
126
127/// Accepts a peer over `io`, completing the handshake before returning.
128///
129/// A peer that proved its key and is refused by a store-backed pin set is recorded as waiting
130/// under the address of `io`.
131///
132/// # Errors
133///
134/// [`PeerError::Io`] when the handshake fails; [`PeerError::refusal`] says why this side
135/// refused the peer certificate, when it did.
136pub async fn accept<S>(
137    config: Arc<ServerConfig>,
138    io: S,
139) -> Result<(server::TlsStream<S>, PeerIdentity), PeerError>
140where
141    S: AsyncRead + AsyncWrite + Unpin + PeerAddr,
142{
143    let (source, local) = (io.peer_addr(), io.local_addr());
144    accept_as(config, io, source, local).await
145}
146
147async fn accept_as<S>(
148    config: Arc<ServerConfig>,
149    io: S,
150    source: Option<SocketAddr>,
151    local: Option<SocketAddr>,
152) -> Result<(server::TlsStream<S>, PeerIdentity), PeerError>
153where
154    S: AsyncRead + AsyncWrite + Unpin,
155{
156    let (stream, refused) = scoped_poll(
157        source,
158        local,
159        tokio_rustls::TlsAcceptor::from(config).accept(io),
160    )
161    .await;
162    let stream = stream.map_err(|error| handshake_error(error, refused))?;
163    let peer = identity_of(stream.get_ref().1.peer_certificates())?;
164    Ok((stream, peer))
165}
166
167/// Accepts a peer over `io`, choosing the configuration from the `ClientHello` (for example
168/// by its offered ALPN protocols), so one port can serve peers and other clients.
169///
170/// # Errors
171///
172/// [`PeerError::Io`] when the hello cannot be read or the handshake fails;
173/// [`PeerError::refusal`] says why this side refused the peer certificate, when it did.
174pub async fn accept_with<S>(
175    io: S,
176    select: impl FnOnce(&ClientHello<'_>) -> Arc<ServerConfig>,
177) -> Result<(server::TlsStream<S>, PeerIdentity), PeerError>
178where
179    S: AsyncRead + AsyncWrite + Unpin + PeerAddr,
180{
181    let (source, local) = (io.peer_addr(), io.local_addr());
182    accept_with_as(io, (source, local), select).await
183}
184
185async fn accept_with_as<S>(
186    io: S,
187    (source, local): (Option<SocketAddr>, Option<SocketAddr>),
188    select: impl FnOnce(&ClientHello<'_>) -> Arc<ServerConfig>,
189) -> Result<(server::TlsStream<S>, PeerIdentity), PeerError>
190where
191    S: AsyncRead + AsyncWrite + Unpin,
192{
193    let start = tokio_rustls::LazyConfigAcceptor::new(rustls::server::Acceptor::default(), io)
194        .await
195        .map_err(PeerError::Io)?;
196    let config = select(&start.client_hello());
197    let (stream, refused) = scoped_poll(source, local, start.into_stream(config)).await;
198    let stream = stream.map_err(|error| handshake_error(error, refused))?;
199    let peer = identity_of(stream.get_ref().1.peer_certificates())?;
200    Ok((stream, peer))
201}
202
203/// `work`, given at most `wait` (forever when `None`); `TimedOut` when it took longer.
204async fn within<F: Future>(wait: Option<Duration>, work: F) -> std::io::Result<F::Output> {
205    match wait {
206        Some(wait) => tokio::time::timeout(wait, work)
207            .await
208            .map_err(|_| std::io::ErrorKind::TimedOut.into()),
209        None => Ok(work.await),
210    }
211}
212
213/// The asynchronous [`PairDial`](crate::PairDial).
214#[derive(Debug)]
215pub struct PairDial<S> {
216    tls: client::TlsStream<S>,
217    joiner: PairingJoiner,
218    until: Option<Instant>,
219}
220
221impl<S: AsyncRead + AsyncWrite + Unpin> PairDial<S> {
222    /// What to show a person now, as [`crate::PairDial::shown`].
223    pub fn shown(&self) -> Option<&Shown> {
224        self.joiner.shown()
225    }
226
227    /// Runs the exchange to its end and accepts the responder in `store`, as
228    /// [`crate::PairDial::finish`].
229    ///
230    /// # Errors
231    ///
232    /// As [`crate::PairDial::finish`].
233    pub async fn finish(mut self, store: &TrustStore) -> Result<Paired, PeerError> {
234        join_until(&mut self.tls, &mut self.joiner, self.until, |_| false).await?;
235        let paired = self.joiner.finish()?;
236        match store.accept_key(&paired.peer) {
237            Ok(_) | Err(coqui_peer::Error::AlreadyAccepted) => {}
238            Err(error) => return Err(error.into()),
239        }
240        let _ = tokio::io::AsyncWriteExt::shutdown(&mut self.tls).await;
241        Ok(paired)
242    }
243}
244
245async fn join_until<S: AsyncRead + AsyncWrite + Unpin>(
246    tls: &mut client::TlsStream<S>,
247    joiner: &mut PairingJoiner,
248    until: Option<Instant>,
249    stop: impl Fn(&PairingJoiner) -> bool,
250) -> Result<(), PeerError> {
251    loop {
252        while let Some(message) = joiner.transmit() {
253            within(left(until), write_frame(tls, &message))
254                .await
255                .and_then(|written| written)
256                .map_err(PeerError::Io)?;
257        }
258        if joiner.is_complete() || stop(joiner) {
259            return Ok(());
260        }
261        let message = within(left(until), read_frame(tls))
262            .await
263            .and_then(|read| read)
264            .map_err(PeerError::Io)?;
265        if let Err(error) = joiner.receive(&message) {
266            while let Some(message) = joiner.transmit() {
267                let _ = write_frame(tls, &message).await;
268            }
269            return Err(error.into());
270        }
271    }
272}
273
274/// [`crate::pair_dial`] over an async stream.
275///
276/// # Errors
277///
278/// As [`crate::pair_dial`].
279pub async fn pair_dial<S>(
280    stream: S,
281    identity: &Identity,
282    pairing: Pairing,
283    responder: &ResponderTrust,
284    config: &PairConfig,
285) -> Result<PairDial<S>, PeerError>
286where
287    S: AsyncRead + AsyncWrite + Unpin,
288{
289    let until = ends(config.timeout);
290    let (client, name) = crate::pair_client_config(identity, &pairing, responder, config)?;
291    let verified = crate::pairing::responder_verified(&pairing, responder);
292    let (tls, peer) = within(left(until), dial_named(Arc::new(client), name, stream))
293        .await
294        .map_err(PeerError::Io)??;
295    let connection = tls.get_ref().1;
296    let exporter = connection
297        .export_keying_material([0u8; 32], crate::EXPORTER_LABEL, Some(&[]))
298        .map_err(|_| PeerError::Tls)?;
299    let channel = crate::pairing::channel(
300        connection,
301        exporter,
302        identity,
303        &peer,
304        verified,
305        config.alpn.as_bytes(),
306        config.policy.certificate,
307    )?;
308    let mut dial = PairDial {
309        tls,
310        joiner: pairing.join(channel)?,
311        until,
312    };
313    join_until(&mut dial.tls, &mut dial.joiner, until, |joiner| {
314        joiner.shown().is_some()
315    })
316    .await?;
317    Ok(dial)
318}
319
320/// [`crate::pair_accept`] over an async stream; it waits for the operator without blocking
321/// the runtime, and sweeps `desk` every second meanwhile so expiry is seen.
322///
323/// # Errors
324///
325/// As [`crate::pair_accept`].
326pub async fn pair_accept<S>(
327    stream: S,
328    identity: &Identity,
329    store: &TrustStore,
330    desk: &PairingDesk,
331    config: &PairConfig,
332) -> Result<Paired, PeerError>
333where
334    S: AsyncRead + AsyncWrite + Unpin + PeerAddr,
335{
336    let (source, local) = (stream.peer_addr(), stream.local_addr());
337    pair_accept_as(stream, (source, local), identity, store, desk, config).await
338}
339
340async fn pair_accept_as<S>(
341    stream: S,
342    (source, local): (Option<SocketAddr>, Option<SocketAddr>),
343    identity: &Identity,
344    store: &TrustStore,
345    desk: &PairingDesk,
346    config: &PairConfig,
347) -> Result<Paired, PeerError>
348where
349    S: AsyncRead + AsyncWrite + Unpin,
350{
351    let until = ends(config.timeout);
352    let server = Arc::new(crate::pair_server_config(identity, config)?);
353    let (tls, _) = within(left(until), accept_as(server, stream, source, local))
354        .await
355        .map_err(PeerError::Io)??;
356    respond_on(tls, source, identity, store, desk, config, until).await
357}
358
359/// Runs the responder's side of pairing on a connection already accepted with
360/// [`pair_server_config`](crate::pair_server_config) (for example chosen by
361/// [`accept_with`] for a client that offered the pairing ALPN), as `identity`, for a client
362/// from `source`. The exchange waits at most [`PairConfig::timeout`] from this call.
363///
364/// # Errors
365///
366/// As [`crate::pair_accept`].
367pub async fn pair_respond<S>(
368    tls: server::TlsStream<S>,
369    source: Option<SocketAddr>,
370    identity: &Identity,
371    store: &TrustStore,
372    desk: &PairingDesk,
373    config: &PairConfig,
374) -> Result<Paired, PeerError>
375where
376    S: AsyncRead + AsyncWrite + Unpin,
377{
378    let until = ends(config.timeout);
379    respond_on(tls, source, identity, store, desk, config, until).await
380}
381
382async fn respond_on<S>(
383    mut tls: server::TlsStream<S>,
384    source: Option<SocketAddr>,
385    identity: &Identity,
386    store: &TrustStore,
387    desk: &PairingDesk,
388    config: &PairConfig,
389    until: Option<Instant>,
390) -> Result<Paired, PeerError>
391where
392    S: AsyncRead + AsyncWrite + Unpin,
393{
394    let connection = tls.get_ref().1;
395    let peer = identity_of(connection.peer_certificates())?;
396    let exporter = connection
397        .export_keying_material([0u8; 32], crate::EXPORTER_LABEL, Some(&[]))
398        .map_err(|_| PeerError::Tls)?;
399    let channel = crate::pairing::channel(
400        connection,
401        exporter,
402        identity,
403        &peer,
404        false,
405        config.alpn.as_bytes(),
406        config.policy.certificate,
407    )?;
408    let mut responder = PairingResponder::new(channel, store, desk, source);
409    let result = respond(&mut tls, &mut responder, desk, until).await;
410    let _ = tokio::io::AsyncWriteExt::shutdown(&mut tls).await;
411    result?;
412    Ok(responder.finish()?)
413}
414
415async fn respond<S: AsyncRead + AsyncWrite + Unpin>(
416    tls: &mut server::TlsStream<S>,
417    responder: &mut PairingResponder,
418    desk: &PairingDesk,
419    until: Option<Instant>,
420) -> Result<(), PeerError> {
421    loop {
422        while let Some(message) = responder.transmit() {
423            within(left(until), write_frame(tls, &message))
424                .await
425                .and_then(|written| written)
426                .map_err(PeerError::Io)?;
427        }
428        if responder.is_complete() {
429            return Ok(());
430        }
431        let step = match responder.awaiting() {
432            Some(ticket) => {
433                let decision = loop {
434                    let wait = tokio::time::timeout(Duration::from_secs(1), desk.decided(ticket));
435                    match wait.await {
436                        Ok(decision) => break decision,
437                        Err(_) => desk.sweep(),
438                    }
439                };
440                responder.resume(decision)
441            }
442            None => {
443                let wait = sooner(left(until), responder.time_left());
444                match within(wait, read_frame(tls)).await {
445                    Ok(Ok(message)) => responder.receive(&message),
446                    Ok(Err(error)) => return Err(PeerError::Io(error)),
447                    // Past the responder's deadline the joiner is told; past the transport's
448                    // own timeout the connection just ends.
449                    Err(error) => match responder.check_deadline() {
450                        Err(expired) => Err(expired),
451                        Ok(()) => return Err(PeerError::Io(error)),
452                    },
453                }
454            }
455        };
456        if let Err(error) = step {
457            while let Some(message) = responder.transmit() {
458                let _ = write_frame(tls, &message).await;
459            }
460            return Err(error.into());
461        }
462    }
463}
464
465/// [`crate::announce`] over an async stream.
466///
467/// # Errors
468///
469/// As [`crate::announce`].
470pub async fn announce<S: AsyncWrite + Unpin>(
471    stream: &mut S,
472    successor: &Identity,
473) -> Result<(), PeerError> {
474    announce_as(stream, successor, CertificateType::X509).await
475}
476
477/// [`crate::announce_as`] over an async stream.
478///
479/// # Errors
480///
481/// As [`crate::announce_as`].
482pub async fn announce_as<S: AsyncWrite + Unpin>(
483    stream: &mut S,
484    successor: &Identity,
485    kind: CertificateType,
486) -> Result<(), PeerError> {
487    let der = match kind {
488        CertificateType::X509 => successor.certificate_der(),
489        CertificateType::RawPublicKey => successor.public_key_der(),
490    };
491    let key = crate::certificate::key_for(kind, der)?;
492    write_frame(stream, &Rotation::announce(&key))
493        .await
494        .map_err(PeerError::Io)
495}
496
497/// [`crate::receive_announcement`] over an async stream.
498///
499/// # Errors
500///
501/// As [`crate::receive_announcement`].
502pub async fn receive_announcement<S: AsyncRead + Unpin>(
503    stream: &mut S,
504    store: &TrustStore,
505    sender: &PeerIdentity,
506) -> Result<PeerId, PeerError> {
507    let message = read_frame(stream).await.map_err(PeerError::Io)?;
508    crate::pairing::record_announcement(&message, store, sender)
509}