synclaire 0.1.2

Transport-layer TCP/TLS library with guards, routing, and proxy primitives
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use std::{future::Future, net::SocketAddr};

#[cfg(feature = "async")]
use std::{io, pin::Pin, task::{Context, Poll}};

#[cfg(feature = "async")]
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

#[cfg(all(feature = "sync", not(feature = "async")))]
use std::io;

#[cfg(feature = "sync")]
use std::io::{Read, Write};

#[cfg(any(feature = "async", feature = "sync"))]
use futures::future::BoxFuture;

use crate::{guard::GuardSession, SynError};

#[cfg(any(feature = "async", feature = "sync"))]
pub type HandlerResult = Result<(), SynError>;
#[cfg(any(feature = "async", feature = "sync"))]
pub type HandlerFuture<'a> = BoxFuture<'a, HandlerResult>;

#[derive(Clone, Debug)]
pub struct ConnectionMetadata {
    pub peer_addr: SocketAddr,
    pub local_addr: Option<SocketAddr>,
    pub tls: bool,
    pub tls_server_name: Option<String>,
}

impl ConnectionMetadata {
    pub fn new(peer_addr: SocketAddr, local_addr: Option<SocketAddr>, tls: bool) -> Self {
        Self {
            peer_addr,
            local_addr,
            tls,
            tls_server_name: None,
        }
    }
}

/// Async transport — use as `AsyncRead + AsyncWrite` or pattern-match for the concrete socket.
#[cfg(feature = "async")]
pub enum AsyncStream {
    Tcp(tokio::net::TcpStream),
    ServerTls(tokio_rustls::server::TlsStream<tokio::net::TcpStream>),
    ClientTls(tokio_rustls::client::TlsStream<tokio::net::TcpStream>),
}

#[cfg(feature = "async")]
impl AsyncStream {
    pub fn is_tls(&self) -> bool {
        matches!(self, AsyncStream::ServerTls(_) | AsyncStream::ClientTls(_))
    }

    pub fn as_tcp(&self) -> Option<&tokio::net::TcpStream> {
        match self { AsyncStream::Tcp(s) => Some(s), _ => None }
    }

    pub fn as_tcp_mut(&mut self) -> Option<&mut tokio::net::TcpStream> {
        match self { AsyncStream::Tcp(s) => Some(s), _ => None }
    }

    pub fn as_server_tls(&self) -> Option<&tokio_rustls::server::TlsStream<tokio::net::TcpStream>> {
        match self { AsyncStream::ServerTls(s) => Some(s), _ => None }
    }

    pub fn as_server_tls_mut(&mut self) -> Option<&mut tokio_rustls::server::TlsStream<tokio::net::TcpStream>> {
        match self { AsyncStream::ServerTls(s) => Some(s), _ => None }
    }

    pub fn as_client_tls(&self) -> Option<&tokio_rustls::client::TlsStream<tokio::net::TcpStream>> {
        match self { AsyncStream::ClientTls(s) => Some(s), _ => None }
    }

    pub fn as_client_tls_mut(&mut self) -> Option<&mut tokio_rustls::client::TlsStream<tokio::net::TcpStream>> {
        match self { AsyncStream::ClientTls(s) => Some(s), _ => None }
    }

    pub fn tcp(&self) -> &tokio::net::TcpStream {
        match self {
            AsyncStream::Tcp(s) => s,
            AsyncStream::ServerTls(s) => s.get_ref().0,
            AsyncStream::ClientTls(s) => s.get_ref().0,
        }
    }
}

#[cfg(feature = "async")]
impl AsyncRead for AsyncStream {
    fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
        match self.get_mut() {
            AsyncStream::Tcp(s) => Pin::new(s).poll_read(cx, buf),
            AsyncStream::ServerTls(s) => Pin::new(s).poll_read(cx, buf),
            AsyncStream::ClientTls(s) => Pin::new(s).poll_read(cx, buf),
        }
    }
}

#[cfg(feature = "async")]
impl AsyncWrite for AsyncStream {
    fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
        match self.get_mut() {
            AsyncStream::Tcp(s) => Pin::new(s).poll_write(cx, buf),
            AsyncStream::ServerTls(s) => Pin::new(s).poll_write(cx, buf),
            AsyncStream::ClientTls(s) => Pin::new(s).poll_write(cx, buf),
        }
    }
    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match self.get_mut() {
            AsyncStream::Tcp(s) => Pin::new(s).poll_flush(cx),
            AsyncStream::ServerTls(s) => Pin::new(s).poll_flush(cx),
            AsyncStream::ClientTls(s) => Pin::new(s).poll_flush(cx),
        }
    }
    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        match self.get_mut() {
            AsyncStream::Tcp(s) => Pin::new(s).poll_shutdown(cx),
            AsyncStream::ServerTls(s) => Pin::new(s).poll_shutdown(cx),
            AsyncStream::ClientTls(s) => Pin::new(s).poll_shutdown(cx),
        }
    }
}

#[cfg(feature = "sync")]
pub enum SyncStream {
    Tcp(std::net::TcpStream),
    #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
    ServerTls(rustls::StreamOwned<rustls::ServerConnection, std::net::TcpStream>),
    #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
    ClientTls(rustls::StreamOwned<rustls::ClientConnection, std::net::TcpStream>),
}

#[cfg(feature = "sync")]
impl SyncStream {
    pub fn is_tls(&self) -> bool {
        #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
        { matches!(self, SyncStream::ServerTls(_) | SyncStream::ClientTls(_)) }
        #[cfg(not(any(feature = "rustls-backend", feature = "aws-lc-backend")))]
        { false }
    }
}

#[cfg(feature = "sync")]
impl Read for SyncStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            SyncStream::Tcp(s) => s.read(buf),
            #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
            SyncStream::ServerTls(s) => s.read(buf),
            #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
            SyncStream::ClientTls(s) => s.read(buf),
        }
    }
}

#[cfg(feature = "sync")]
impl Write for SyncStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            SyncStream::Tcp(s) => s.write(buf),
            #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
            SyncStream::ServerTls(s) => s.write(buf),
            #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
            SyncStream::ClientTls(s) => s.write(buf),
        }
    }
    fn flush(&mut self) -> io::Result<()> {
        match self {
            SyncStream::Tcp(s) => s.flush(),
            #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
            SyncStream::ServerTls(s) => s.flush(),
            #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
            SyncStream::ClientTls(s) => s.flush(),
        }
    }
}

pub enum ConnectionStream {
    #[cfg(feature = "async")]
    Async(AsyncStream),
    #[cfg(feature = "sync")]
    Sync(SyncStream),
}

impl ConnectionStream {
    pub fn is_tls(&self) -> bool {
        // Deref so that the match is on `ConnectionStream` (not `&ConnectionStream`).
        // When neither feature is enabled the enum is uninhabited, and matching on
        // an uninhabited value with no arms is valid Rust — the block is unreachable.
        match *self {
            #[cfg(feature = "async")]
            ConnectionStream::Async(ref s) => s.is_tls(),
            #[cfg(feature = "sync")]
            ConnectionStream::Sync(ref s) => s.is_tls(),
        }
    }

    #[cfg(feature = "async")]
    pub fn as_async(&self) -> Option<&AsyncStream> {
        match self {
            ConnectionStream::Async(s) => Some(s),
            #[cfg(feature = "sync")]
            ConnectionStream::Sync(_) => None,
        }
    }

    #[cfg(feature = "async")]
    pub fn as_async_mut(&mut self) -> Option<&mut AsyncStream> {
        match self {
            ConnectionStream::Async(s) => Some(s),
            #[cfg(feature = "sync")]
            ConnectionStream::Sync(_) => None,
        }
    }

    #[cfg(feature = "async")]
    pub fn into_async(self) -> Option<AsyncStream> {
        match self {
            ConnectionStream::Async(s) => Some(s),
            #[cfg(feature = "sync")]
            ConnectionStream::Sync(_) => None,
        }
    }

    #[cfg(feature = "sync")]
    pub fn as_sync(&self) -> Option<&SyncStream> {
        match self {
            ConnectionStream::Sync(s) => Some(s),
            #[cfg(feature = "async")]
            ConnectionStream::Async(_) => None,
        }
    }

    #[cfg(feature = "sync")]
    pub fn as_sync_mut(&mut self) -> Option<&mut SyncStream> {
        match self {
            ConnectionStream::Sync(s) => Some(s),
            #[cfg(feature = "async")]
            ConnectionStream::Async(_) => None,
        }
    }

    #[cfg(feature = "sync")]
    pub fn into_sync(self) -> Option<SyncStream> {
        match self {
            ConnectionStream::Sync(s) => Some(s),
            #[cfg(feature = "async")]
            ConnectionStream::Async(_) => None,
        }
    }
}

pub struct Connection {
    metadata: ConnectionMetadata,
    stream: Option<ConnectionStream>,
    guard_session: Option<GuardSession>,
}

impl Connection {
    #[cfg(feature = "async")]
    pub fn from_async_tcp(metadata: ConnectionMetadata, stream: tokio::net::TcpStream) -> Self {
        Self { metadata, stream: Some(ConnectionStream::Async(AsyncStream::Tcp(stream))), guard_session: None }
    }

    #[cfg(feature = "async")]
    pub fn from_async_server_tls(
        metadata: ConnectionMetadata,
        stream: tokio_rustls::server::TlsStream<tokio::net::TcpStream>,
    ) -> Self {
        Self { metadata, stream: Some(ConnectionStream::Async(AsyncStream::ServerTls(stream))), guard_session: None }
    }

    #[cfg(feature = "async")]
    pub fn from_client_tls(
        metadata: ConnectionMetadata,
        stream: tokio_rustls::client::TlsStream<tokio::net::TcpStream>,
    ) -> Self {
        Self { metadata, stream: Some(ConnectionStream::Async(AsyncStream::ClientTls(stream))), guard_session: None }
    }

    #[cfg(feature = "async")]
    pub fn from_async_stream(metadata: ConnectionMetadata, stream: AsyncStream) -> Self {
        Self { metadata, stream: Some(ConnectionStream::Async(stream)), guard_session: None }
    }

    #[cfg(feature = "sync")]
    pub fn from_sync_tcp(metadata: ConnectionMetadata, stream: std::net::TcpStream) -> Self {
        Self { metadata, stream: Some(ConnectionStream::Sync(SyncStream::Tcp(stream))), guard_session: None }
    }

    #[cfg(all(feature = "sync", any(feature = "rustls-backend", feature = "aws-lc-backend")))]
    pub(crate) fn from_sync_server_tls(
        metadata: ConnectionMetadata,
        stream: rustls::StreamOwned<rustls::ServerConnection, std::net::TcpStream>,
    ) -> Self {
        Self { metadata, stream: Some(ConnectionStream::Sync(SyncStream::ServerTls(stream))), guard_session: None }
    }

    #[cfg(all(feature = "sync", any(feature = "rustls-backend", feature = "aws-lc-backend")))]
    pub(crate) fn from_sync_client_tls(
        metadata: ConnectionMetadata,
        stream: rustls::StreamOwned<rustls::ClientConnection, std::net::TcpStream>,
    ) -> Self {
        Self { metadata, stream: Some(ConnectionStream::Sync(SyncStream::ClientTls(stream))), guard_session: None }
    }

    pub(crate) fn with_guard_session(mut self, guard_session: GuardSession) -> Self {
        self.guard_session = Some(guard_session);
        self
    }

    pub fn metadata(&self) -> &ConnectionMetadata {
        &self.metadata
    }

    pub fn stream(&self) -> &ConnectionStream {
        self.stream.as_ref().expect("stream was already taken")
    }

    pub fn stream_mut(&mut self) -> &mut ConnectionStream {
        self.stream.as_mut().expect("stream was already taken")
    }

    pub fn into_stream(mut self) -> ConnectionStream {
        self.stream.take().expect("stream was already taken")
    }

    #[cfg(feature = "async")]
    pub fn async_stream(&self) -> Option<&AsyncStream> {
        self.stream().as_async()
    }

    #[cfg(feature = "async")]
    pub fn async_stream_mut(&mut self) -> Option<&mut AsyncStream> {
        self.stream_mut().as_async_mut()
    }

    pub fn peer_addr(&self) -> SocketAddr {
        self.metadata.peer_addr
    }

    pub fn local_addr(&self) -> Option<SocketAddr> {
        self.metadata.local_addr
    }

    pub fn is_tls(&self) -> bool {
        self.stream.as_ref().map(|s| s.is_tls()).unwrap_or(false)
    }

    pub fn tls_server_name(&self) -> Option<&str> {
        self.metadata.tls_server_name.as_deref()
    }

    // --- Convenience async I/O helpers ---

    #[cfg(feature = "async")]
    pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, SynError> {
        let stream = self.stream.as_mut()
            .ok_or_else(|| SynError::connection_error("stream taken"))?
            .as_async_mut()
            .ok_or_else(|| SynError::connection_error("async stream required"))?;
        let read = tokio::io::AsyncReadExt::read(stream, buf).await?;
        if read > 0 {
            if let Some(session) = &self.guard_session {
                session.record_payload(&buf[..read])?;
            }
        }
        Ok(read)
    }

    #[cfg(feature = "async")]
    pub async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), SynError> {
        {
            let stream = self.stream.as_mut()
                .ok_or_else(|| SynError::connection_error("stream taken"))?
                .as_async_mut()
                .ok_or_else(|| SynError::connection_error("async stream required"))?;
            tokio::io::AsyncReadExt::read_exact(stream, buf).await?;
        }
        if let Some(session) = &self.guard_session {
            session.record_payload(buf)?;
        }
        Ok(())
    }

    #[cfg(feature = "async")]
    pub async fn write_all(&mut self, buf: &[u8]) -> Result<(), SynError> {
        {
            let stream = self.stream.as_mut().expect("stream taken").as_async_mut().expect("async stream");
            tokio::io::AsyncWriteExt::write_all(stream, buf).await?;
        }
        if let Some(session) = &self.guard_session {
            session.touch()?;
        }
        Ok(())
    }

    #[cfg(feature = "async")]
    pub async fn flush(&mut self) -> Result<(), SynError> {
        let stream = self.stream.as_mut().expect("stream taken").as_async_mut().expect("async stream");
        tokio::io::AsyncWriteExt::flush(stream).await?;
        Ok(())
    }

    #[cfg(feature = "async")]
    pub async fn shutdown(&mut self) -> Result<(), SynError> {
        let stream = self.stream.as_mut()
            .ok_or_else(|| SynError::connection_error("stream taken"))?
            .as_async_mut()
            .ok_or_else(|| SynError::connection_error("async stream required"))?;
        tokio::io::AsyncWriteExt::shutdown(stream).await?;
        Ok(())
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        if let Some(session) = &self.guard_session {
            session.close();
        }
    }
}

#[cfg(any(feature = "async", feature = "sync"))]
pub trait ConnectionHandler: Send + Sync + 'static {
    fn handle<'a>(&'a self, connection: Connection) -> HandlerFuture<'a>;
}

#[cfg(any(feature = "async", feature = "sync"))]
impl<F, Fut> ConnectionHandler for F
where
    F: Fn(Connection) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = HandlerResult> + Send + 'static,
{
    fn handle<'a>(&'a self, connection: Connection) -> HandlerFuture<'a> {
        Box::pin((self)(connection))
    }
}

#[cfg(feature = "sync")]
pub trait SyncConnectionHandler: Send + Sync + 'static {
    fn handle(&self, connection: Connection) -> HandlerResult;
}

#[cfg(feature = "sync")]
impl<F> SyncConnectionHandler for F
where
    F: Fn(Connection) -> HandlerResult + Send + Sync + 'static,
{
    fn handle(&self, connection: Connection) -> HandlerResult {
        (self)(connection)
    }
}

pub(crate) fn attach_guard_session(connection: Connection, guard_session: GuardSession) -> Connection {
    connection.with_guard_session(guard_session)
}

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

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_tcp_stream_is_accessible_and_movable() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind");
        let addr = listener.local_addr().expect("local addr");
        let _client = tokio::net::TcpStream::connect(addr).await.expect("client connect");
        let (server_stream, peer_addr) = listener.accept().await.expect("accept");
        let metadata = ConnectionMetadata::new(peer_addr, None, false);
        let connection = Connection::from_async_tcp(metadata, server_stream);
        assert!(!connection.is_tls());
        assert!(connection.async_stream().expect("async stream").as_tcp().is_some());
        assert!(connection.async_stream().expect("async stream").as_server_tls().is_none());
        match connection.into_stream().into_async().expect("async stream") {
            AsyncStream::Tcp(_) => {}
            _ => panic!("expected TCP stream"),
        }
    }

    #[cfg(feature = "sync")]
    #[test]
    fn sync_tcp_stream_is_accessible_and_movable() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        let addr = listener.local_addr().expect("local addr");
        let _client = std::thread::spawn(move || std::net::TcpStream::connect(addr));
        let (server_stream, peer_addr) = listener.accept().expect("accept");
        let metadata = ConnectionMetadata::new(peer_addr, None, false);
        let connection = Connection::from_sync_tcp(metadata, server_stream);
        assert!(!connection.is_tls());
        match connection.into_stream().into_sync().expect("sync stream") {
            SyncStream::Tcp(_) => {}
            #[cfg(any(feature = "rustls-backend", feature = "aws-lc-backend"))]
            _ => panic!("expected TCP stream"),
        }
    }
}