openrtc 2.5.0

OpenRTC: a Rust-first P2P runtime for device discovery, signaling, and iroh/QUIC networking.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Length-framed application-crypto adapters for iroh `SendStream` / `RecvStream`.
//!
//! Mirrors the TypeScript `createCryptoStreams` contract: each
//! `write_all` produces one encrypted frame; `read` reassembles framed ciphertext
//! from arbitrary chunk boundaries before returning plaintext.

use std::collections::VecDeque;
use std::io;

use iroh::endpoint::{ClosedStream, ReadError, RecvStream, SendStream, WriteError};
use tokio::io::AsyncWriteExt;

use crate::application_crypto::{
    protect_frame, CryptoFrameDecoder, CryptoStreamError, APPLICATION_KEY_BYTES,
};

#[derive(Debug)]
struct ApplicationCryptoStreamIoError(CryptoStreamError);

impl std::fmt::Display for ApplicationCryptoStreamIoError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{:?}", self.0)
    }
}

impl std::error::Error for ApplicationCryptoStreamIoError {}

/// Returns true only when encrypted stream decoding reached AEAD verification
/// and rejected the frame. Transport EOF, connection loss, and incomplete
/// shutdown frames are intentionally distinct so callers do not misreport
/// lifecycle teardown as retired key material.
pub fn is_crypto_auth_failure(error: &io::Error) -> bool {
    error
        .get_ref()
        .and_then(|source| source.downcast_ref::<ApplicationCryptoStreamIoError>())
        .is_some_and(|source| matches!(&source.0, CryptoStreamError::AuthenticationFailed(_)))
}

/// Return the peer-provided QUIC stop code without forcing higher layers to
/// parse a transport error's display text.
pub fn peer_stop_code(error: &io::Error) -> Option<u64> {
    error
        .get_ref()
        .and_then(|source| source.downcast_ref::<WriteError>())
        .and_then(|source| match source {
            WriteError::Stopped(code) => Some(code.into_inner()),
            _ => None,
        })
}

#[derive(Debug)]
pub struct CryptoSendStream {
    inner: SendStream,
    key: [u8; APPLICATION_KEY_BYTES],
}

impl CryptoSendStream {
    pub fn new(inner: SendStream, key: [u8; APPLICATION_KEY_BYTES]) -> Self {
        Self { inner, key }
    }

    pub async fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        let frame = protect_frame(&self.key, buf).map_err(crypto_io_error)?;
        self.inner.write_all(&frame).await.map_err(map_write_error)
    }

    pub async fn flush(&mut self) -> io::Result<()> {
        self.inner.flush().await
    }

    pub fn finish(mut self) -> io::Result<()> {
        self.inner.finish().map_err(map_finish_error)
    }

    pub fn into_inner(self) -> SendStream {
        self.inner
    }
}

#[derive(Debug)]
pub struct CryptoRecvStream {
    inner: RecvStream,
    decoder: CryptoFrameDecoder,
    read_buf: Vec<u8>,
    finished: bool,
}

impl CryptoRecvStream {
    pub fn new(inner: RecvStream, key: [u8; APPLICATION_KEY_BYTES]) -> io::Result<Self> {
        Ok(Self {
            inner,
            decoder: CryptoFrameDecoder::new(&key).map_err(crypto_io_error)?,
            read_buf: Vec::new(),
            finished: false,
        })
    }

    pub fn new_with_prefix(
        inner: RecvStream,
        key: [u8; APPLICATION_KEY_BYTES],
        prefix: &[u8],
    ) -> io::Result<Self> {
        let mut decoder = CryptoFrameDecoder::new(&key).map_err(crypto_io_error)?;
        let mut read_buf = Vec::new();
        if !prefix.is_empty() {
            for frame in decoder.push(prefix).map_err(crypto_stream_io_error)? {
                read_buf.extend_from_slice(&frame);
            }
        }
        Ok(Self {
            inner,
            decoder,
            read_buf,
            finished: false,
        })
    }

    pub async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if !self.read_buf.is_empty() {
            let copied = self.read_buf.len().min(buf.len());
            buf[..copied].copy_from_slice(&self.read_buf[..copied]);
            self.read_buf.drain(..copied);
            return Ok(copied);
        }

        if self.finished {
            return Ok(0);
        }

        loop {
            let mut chunk = vec![0u8; 16 * 1024];
            let read_bytes = match self.inner.read(&mut chunk).await {
                Ok(Some(0)) => 0,
                Ok(Some(read_bytes)) => read_bytes,
                Ok(None) => 0,
                Err(error) => return Err(map_read_error(error)),
            };
            if read_bytes == 0 {
                self.finished = true;
                self.decoder.finish().map_err(crypto_stream_io_error)?;
                if self.read_buf.is_empty() {
                    return Ok(0);
                }
                let copied = self.read_buf.len().min(buf.len());
                buf[..copied].copy_from_slice(&self.read_buf[..copied]);
                self.read_buf.drain(..copied);
                return Ok(copied);
            }

            chunk.truncate(read_bytes);
            let opened = self.decoder.push(&chunk).map_err(crypto_stream_io_error)?;
            for frame in opened {
                self.read_buf.extend_from_slice(&frame);
            }

            if !self.read_buf.is_empty() {
                let copied = self.read_buf.len().min(buf.len());
                buf[..copied].copy_from_slice(&self.read_buf[..copied]);
                self.read_buf.drain(..copied);
                return Ok(copied);
            }
        }
    }

    pub fn into_inner(self) -> RecvStream {
        self.inner
    }
}

#[derive(Debug)]
pub enum PeerSendStream {
    Plain(SendStream),
    Encrypted(CryptoSendStream),
}

impl PeerSendStream {
    pub fn plain(inner: SendStream) -> Self {
        Self::Plain(inner)
    }

    pub fn encrypted(inner: SendStream, key: [u8; APPLICATION_KEY_BYTES]) -> Self {
        Self::Encrypted(CryptoSendStream::new(inner, key))
    }

    pub fn is_encrypted(&self) -> bool {
        matches!(self, Self::Encrypted(_))
    }

    pub async fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        match self {
            Self::Plain(stream) => stream.write_all(buf).await.map_err(map_write_error),
            Self::Encrypted(stream) => stream.write_all(buf).await,
        }
    }

    pub async fn flush(&mut self) -> io::Result<()> {
        match self {
            Self::Plain(stream) => stream.flush().await,
            Self::Encrypted(stream) => stream.flush().await,
        }
    }

    pub fn finish(self) -> io::Result<()> {
        match self {
            Self::Plain(mut stream) => stream.finish().map_err(map_finish_error),
            Self::Encrypted(stream) => stream.finish(),
        }
    }

    /// Finish a short control response and keep its QUIC send half alive until
    /// the peer has acknowledged the buffered bytes (or the bounded wait
    /// expires). `finish()` alone only queues the FIN; a concurrent physical-leg
    /// replacement can otherwise close the connection before the verdict is
    /// observable by the admission dialer.
    pub async fn finish_and_wait_for_peer(self, timeout: std::time::Duration) -> io::Result<()> {
        async fn finish_and_wait(
            mut stream: SendStream,
            timeout: std::time::Duration,
        ) -> io::Result<()> {
            stream.finish().map_err(map_finish_error)?;
            #[cfg(not(target_arch = "wasm32"))]
            match tokio::time::timeout(timeout, stream.stopped()).await {
                Ok(Ok(_)) => Ok(()),
                Ok(Err(error)) => Err(io::Error::other(format!(
                    "wait for peer acknowledgement: {error}"
                ))),
                Err(_) => Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "timed out waiting for peer acknowledgement",
                )),
            }
            #[cfg(target_arch = "wasm32")]
            {
                use futures::FutureExt;

                let stopped = stream.stopped().fuse();
                let timeout = gloo_timers::future::sleep(timeout).fuse();
                futures::pin_mut!(stopped, timeout);
                futures::select! {
                    result = stopped => result.map(|_| ()).map_err(|error| {
                        io::Error::other(format!("wait for peer acknowledgement: {error}"))
                    }),
                    _ = timeout => Err(io::Error::new(
                        io::ErrorKind::TimedOut,
                        "timed out waiting for peer acknowledgement",
                    )),
                }
            }
        }

        match self {
            Self::Plain(stream) => finish_and_wait(stream, timeout).await,
            Self::Encrypted(stream) => finish_and_wait(stream.into_inner(), timeout).await,
        }
    }

    pub fn into_plain(self) -> SendStream {
        match self {
            Self::Plain(stream) => stream,
            Self::Encrypted(stream) => stream.into_inner(),
        }
    }
}

#[derive(Debug)]
pub enum PeerRecvStream {
    Plain(RecvStream),
    Encrypted(CryptoRecvStream),
    /// Plaintext bytes read by a host-side protocol classifier, followed by
    /// the original protected stream. This lets one native host inspect a
    /// channel envelope without stealing or duplicating the admitted-stream
    /// queue.
    Prefixed {
        prefix: VecDeque<u8>,
        inner: Box<PeerRecvStream>,
    },
}

impl PeerRecvStream {
    pub fn plain(inner: RecvStream) -> Self {
        Self::Plain(inner)
    }

    pub fn encrypted(inner: RecvStream, key: [u8; APPLICATION_KEY_BYTES]) -> io::Result<Self> {
        Ok(Self::Encrypted(CryptoRecvStream::new(inner, key)?))
    }

    pub fn encrypted_with_prefix(
        inner: RecvStream,
        key: [u8; APPLICATION_KEY_BYTES],
        prefix: &[u8],
    ) -> io::Result<Self> {
        Ok(Self::Encrypted(CryptoRecvStream::new_with_prefix(
            inner, key, prefix,
        )?))
    }

    pub fn is_encrypted(&self) -> bool {
        match self {
            Self::Encrypted(_) => true,
            Self::Prefixed { inner, .. } => inner.is_encrypted(),
            Self::Plain(_) => false,
        }
    }

    /// Restore plaintext consumed during bounded host-side classification.
    pub fn with_plaintext_prefix(self, prefix: impl IntoIterator<Item = u8>) -> Self {
        let prefix = prefix.into_iter().collect::<VecDeque<_>>();
        if prefix.is_empty() {
            self
        } else {
            Self::Prefixed {
                prefix,
                inner: Box::new(self),
            }
        }
    }

    pub async fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let mut current = self;
        loop {
            match current {
                Self::Plain(stream) => return read_recv_stream(stream, buf).await,
                Self::Encrypted(stream) => return stream.read(buf).await,
                Self::Prefixed { prefix, inner } => {
                    if !prefix.is_empty() {
                        let copied = prefix.len().min(buf.len());
                        for slot in &mut buf[..copied] {
                            *slot = prefix.pop_front().expect("prefix length was checked");
                        }
                        return Ok(copied);
                    } else {
                        current = inner.as_mut();
                    }
                }
            }
        }
    }

    pub fn into_plain(self) -> RecvStream {
        match self {
            Self::Plain(stream) => stream,
            Self::Encrypted(stream) => stream.into_inner(),
            Self::Prefixed { inner, .. } => inner.into_plain(),
        }
    }
}

pub fn wrap_peer_streams(
    key: Option<[u8; APPLICATION_KEY_BYTES]>,
    send: SendStream,
    recv: RecvStream,
) -> io::Result<(PeerSendStream, PeerRecvStream)> {
    match key {
        Some(key) => Ok((
            PeerSendStream::encrypted(send, key),
            PeerRecvStream::encrypted(recv, key)?,
        )),
        None => Ok((PeerSendStream::plain(send), PeerRecvStream::plain(recv))),
    }
}

pub fn wrap_send_stream(
    key: Option<[u8; APPLICATION_KEY_BYTES]>,
    send: SendStream,
) -> PeerSendStream {
    match key {
        Some(key) => PeerSendStream::encrypted(send, key),
        None => PeerSendStream::plain(send),
    }
}

async fn read_recv_stream(stream: &mut RecvStream, buf: &mut [u8]) -> io::Result<usize> {
    match stream.read(buf).await {
        Ok(Some(0)) => Ok(0),
        Ok(Some(read_bytes)) => Ok(read_bytes),
        Ok(None) => Ok(0),
        Err(error) => Err(map_read_error(error)),
    }
}

fn map_write_error(error: WriteError) -> io::Error {
    io::Error::other(error)
}

fn map_read_error(error: ReadError) -> io::Error {
    io::Error::new(io::ErrorKind::Other, error.to_string())
}

fn map_finish_error(error: ClosedStream) -> io::Error {
    io::Error::new(io::ErrorKind::NotConnected, error.to_string())
}

fn crypto_io_error(error: crate::application_crypto::CryptoError) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, format!("{error:?}"))
}

fn crypto_stream_io_error(error: CryptoStreamError) -> io::Error {
    io::Error::new(
        io::ErrorKind::InvalidData,
        ApplicationCryptoStreamIoError(error),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn distinguishes_authentication_failure_from_incomplete_shutdown_frame() {
        let authentication = crypto_stream_io_error(CryptoStreamError::AuthenticationFailed(
            crate::application_crypto::CryptoError::DecryptFailed,
        ));
        let incomplete = crypto_stream_io_error(CryptoStreamError::IncompleteFrame);

        assert!(is_crypto_auth_failure(&authentication));
        assert!(!is_crypto_auth_failure(&incomplete));
    }

    #[test]
    fn transport_errors_are_not_crypto_authentication_failures() {
        let transport = io::Error::new(io::ErrorKind::ConnectionReset, "connection lost");
        assert!(!is_crypto_auth_failure(&transport));
    }

    #[test]
    fn preserves_peer_stop_code_without_string_parsing() {
        let stopped = map_write_error(WriteError::Stopped(iroh::endpoint::VarInt::from_u32(0)));
        assert_eq!(peer_stop_code(&stopped), Some(0));

        let lost = io::Error::other("connection lost");
        assert_eq!(peer_stop_code(&lost), None);
    }
}