tilo-net 0.5.2

The network capability on Linux, macOS and the web: async HTTP with streaming bodies, WebSocket, WebTransport, network status, raw sockets on the desktop, and Tilo's one TLS provider and trust source.
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
//! Raw TCP, UDP and TLS over TCP, for protocols HTTP, WebSocket and
//! WebTransport do not carry (Gemini, IMAP, a device's own protocol). Desktop
//! only: a page answers [`Unsupported`](crate::Unsupported) from every
//! constructor.

use std::net::SocketAddr;
use std::time::Duration;

use crate::NetError;

#[cfg(not(target_family = "wasm"))]
use imp_native as imp;
#[cfg(target_family = "wasm")]
use imp_web as imp;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Trust {
    #[default]
    System,
    /// Accept any certificate whose handshake signature is valid, for
    /// trust-on-first-use protocols (Gemini); the caller pins
    /// [`TlsStream::peer_certificate`] itself.
    AnyCertificate,
}

pub struct TcpStream(imp::Tcp);

pub struct TlsStream(imp::Tls);

pub struct TcpListener(imp::Listener);

pub struct UdpSocket(imp::Udp);

macro_rules! opaque_debug {
    ($($name:ident),*) => {$(
        impl std::fmt::Debug for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct(stringify!($name)).finish_non_exhaustive()
            }
        }
    )*};
}
opaque_debug!(TcpStream, TlsStream, TcpListener, UdpSocket);

impl TcpStream {
    pub async fn connect(host: &str, port: u16) -> Result<Self, NetError> {
        imp::Tcp::connect(host, port).await.map(Self)
    }

    pub async fn connect_timeout(
        host: &str,
        port: u16,
        timeout: Duration,
    ) -> Result<Self, NetError> {
        imp::deadline(Some(timeout), imp::Tcp::connect(host, port))
            .await
            .map(Self)
    }

    pub async fn read(&mut self, buffer: &mut [u8]) -> Result<usize, NetError> {
        self.0.read(buffer).await
    }

    pub async fn write_all(&mut self, data: &[u8]) -> Result<(), NetError> {
        self.0.write_all(data).await
    }

    pub async fn shutdown(&mut self) -> Result<(), NetError> {
        self.0.shutdown().await
    }

    pub fn peer_addr(&self) -> Result<SocketAddr, NetError> {
        self.0.peer_addr()
    }

    pub async fn into_tls(self, host: &str, trust: Trust) -> Result<TlsStream, NetError> {
        imp::Tls::handshake(self.0, host, trust)
            .await
            .map(TlsStream)
    }
}

impl TlsStream {
    pub async fn connect(host: &str, port: u16, trust: Trust) -> Result<Self, NetError> {
        TcpStream::connect(host, port)
            .await?
            .into_tls(host, trust)
            .await
    }

    #[must_use]
    pub fn peer_certificate(&self) -> Option<Vec<u8>> {
        self.0.peer_certificate()
    }

    pub async fn read(&mut self, buffer: &mut [u8]) -> Result<usize, NetError> {
        self.0.read(buffer).await
    }

    pub async fn read_to_end(&mut self, limit: usize) -> Result<Vec<u8>, NetError> {
        let mut all = Vec::new();
        let mut buffer = vec![0; 16 * 1024];
        loop {
            let read = self.read(&mut buffer).await?;
            if read == 0 {
                return Ok(all);
            }
            if all.len().saturating_add(read) > limit {
                return Err(NetError::TooLarge { limit });
            }
            all.extend_from_slice(buffer.get(..read).unwrap_or_default());
        }
    }

    pub async fn write_all(&mut self, data: &[u8]) -> Result<(), NetError> {
        self.0.write_all(data).await
    }

    pub async fn shutdown(&mut self) -> Result<(), NetError> {
        self.0.shutdown().await
    }
}

impl TcpListener {
    pub async fn bind(address: SocketAddr) -> Result<Self, NetError> {
        imp::Listener::bind(address).await.map(Self)
    }

    pub async fn accept(&self) -> Result<(TcpStream, SocketAddr), NetError> {
        let (tcp, peer) = self.0.accept().await?;
        Ok((TcpStream(tcp), peer))
    }

    pub fn local_addr(&self) -> Result<SocketAddr, NetError> {
        self.0.local_addr()
    }
}

impl UdpSocket {
    pub async fn bind(address: SocketAddr) -> Result<Self, NetError> {
        imp::Udp::bind(address).await.map(Self)
    }

    pub async fn connect(&self, address: SocketAddr) -> Result<(), NetError> {
        self.0.connect(address).await
    }

    pub async fn send(&self, data: &[u8]) -> Result<usize, NetError> {
        self.0.send(data).await
    }

    pub async fn recv(&self, buffer: &mut [u8]) -> Result<usize, NetError> {
        self.0.recv(buffer).await
    }

    pub async fn send_to(&self, data: &[u8], address: SocketAddr) -> Result<usize, NetError> {
        self.0.send_to(data, address).await
    }

    pub async fn recv_from(&self, buffer: &mut [u8]) -> Result<(usize, SocketAddr), NetError> {
        self.0.recv_from(buffer).await
    }

    pub fn local_addr(&self) -> Result<SocketAddr, NetError> {
        self.0.local_addr()
    }
}

#[cfg(not(target_family = "wasm"))]
mod imp_native {
    use std::net::SocketAddr;
    use std::sync::Arc;

    use rustls::pki_types::{CertificateDer, ServerName};
    use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

    use crate::NetError;
    pub(super) use crate::native::deadline;
    use crate::sockets::Trust;

    #[allow(
        clippy::needless_pass_by_value,
        reason = "used as a `map_err` function"
    )]
    fn io(error: std::io::Error) -> NetError {
        NetError::connect(error.to_string())
    }

    pub(super) struct Tcp(tokio::net::TcpStream);
    pub(super) struct Tls(tokio_rustls::client::TlsStream<tokio::net::TcpStream>);
    pub(super) struct Listener(tokio::net::TcpListener);
    pub(super) struct Udp(tokio::net::UdpSocket);

    impl Tcp {
        pub(super) async fn connect(host: &str, port: u16) -> Result<Self, NetError> {
            let host = host.trim_start_matches('[').trim_end_matches(']');
            tokio::net::TcpStream::connect((host, port))
                .await
                .map(Self)
                .map_err(|error| NetError::connect(format!("{host}:{port}: {error}")))
        }

        pub(super) async fn read(&mut self, buffer: &mut [u8]) -> Result<usize, NetError> {
            self.0.read(buffer).await.map_err(io)
        }

        pub(super) async fn write_all(&mut self, data: &[u8]) -> Result<(), NetError> {
            self.0.write_all(data).await.map_err(io)
        }

        pub(super) async fn shutdown(&mut self) -> Result<(), NetError> {
            self.0.shutdown().await.map_err(io)
        }

        pub(super) fn peer_addr(&self) -> Result<SocketAddr, NetError> {
            self.0.peer_addr().map_err(io)
        }
    }

    impl Tls {
        pub(super) async fn handshake(
            tcp: Tcp,
            host: &str,
            trust: Trust,
        ) -> Result<Self, NetError> {
            let config = match trust {
                Trust::System => crate::native::tls::client_config(),
                Trust::AnyCertificate => crate::native::tls::pinned_client_config(|_| true),
            }
            .map_err(|error| NetError::Protocol(format!("TLS: {error}")))?;
            let name = ServerName::try_from(
                host.trim_start_matches('[')
                    .trim_end_matches(']')
                    .to_owned(),
            )
            .map_err(|error| NetError::InvalidUrl(format!("{host}: {error}")))?;
            let stream = tokio_rustls::TlsConnector::from(Arc::new(config))
                .connect(name, tcp.0)
                .await
                .map_err(|error| NetError::Protocol(format!("TLS: {error}")))?;
            Ok(Self(stream))
        }

        pub(super) fn peer_certificate(&self) -> Option<Vec<u8>> {
            let (_, connection) = self.0.get_ref();
            connection
                .peer_certificates()
                .and_then(<[CertificateDer<'_>]>::first)
                .map(|cert| cert.as_ref().to_vec())
        }

        pub(super) async fn read(&mut self, buffer: &mut [u8]) -> Result<usize, NetError> {
            match self.0.read(buffer).await {
                Ok(read) => Ok(read),
                // Many servers close without `close_notify`; the body is still complete for
                // protocols that end at the close.
                Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => Ok(0),
                Err(error) => Err(io(error)),
            }
        }

        pub(super) async fn write_all(&mut self, data: &[u8]) -> Result<(), NetError> {
            self.0.write_all(data).await.map_err(io)?;
            self.0.flush().await.map_err(io)
        }

        pub(super) async fn shutdown(&mut self) -> Result<(), NetError> {
            self.0.shutdown().await.map_err(io)
        }
    }

    impl Listener {
        pub(super) async fn bind(address: SocketAddr) -> Result<Self, NetError> {
            tokio::net::TcpListener::bind(address)
                .await
                .map(Self)
                .map_err(io)
        }

        pub(super) async fn accept(&self) -> Result<(Tcp, SocketAddr), NetError> {
            let (stream, peer) = self.0.accept().await.map_err(io)?;
            Ok((Tcp(stream), peer))
        }

        pub(super) fn local_addr(&self) -> Result<SocketAddr, NetError> {
            self.0.local_addr().map_err(io)
        }
    }

    impl Udp {
        pub(super) async fn bind(address: SocketAddr) -> Result<Self, NetError> {
            tokio::net::UdpSocket::bind(address)
                .await
                .map(Self)
                .map_err(io)
        }

        pub(super) async fn connect(&self, address: SocketAddr) -> Result<(), NetError> {
            self.0.connect(address).await.map_err(io)
        }

        pub(super) async fn send(&self, data: &[u8]) -> Result<usize, NetError> {
            self.0.send(data).await.map_err(io)
        }

        pub(super) async fn recv(&self, buffer: &mut [u8]) -> Result<usize, NetError> {
            self.0.recv(buffer).await.map_err(io)
        }

        pub(super) async fn send_to(
            &self,
            data: &[u8],
            address: SocketAddr,
        ) -> Result<usize, NetError> {
            self.0.send_to(data, address).await.map_err(io)
        }

        pub(super) async fn recv_from(
            &self,
            buffer: &mut [u8],
        ) -> Result<(usize, SocketAddr), NetError> {
            self.0.recv_from(buffer).await.map_err(io)
        }

        pub(super) fn local_addr(&self) -> Result<SocketAddr, NetError> {
            self.0.local_addr().map_err(io)
        }
    }
}

#[cfg(target_family = "wasm")]
mod imp_web {
    //! A page has no sockets: the types are uninhabited, and every constructor
    //! answers `Unsupported`.
    #![allow(
        clippy::unused_async,
        clippy::needless_pass_by_ref_mut,
        reason = "the same signatures as the desktop backend"
    )]

    use std::net::SocketAddr;
    use std::time::Duration;

    use crate::sockets::Trust;
    use crate::{Feature, NetError};

    #[derive(Clone, Copy)]
    enum Never {}

    fn unsupported<T>() -> Result<T, NetError> {
        Err(crate::Unsupported::of(Feature::Sockets).into())
    }

    pub(super) async fn deadline<T>(
        _timeout: Option<Duration>,
        future: impl Future<Output = Result<T, NetError>>,
    ) -> Result<T, NetError> {
        future.await
    }

    pub(super) struct Tcp(Never);
    pub(super) struct Tls(Never);
    pub(super) struct Listener(Never);
    pub(super) struct Udp(Never);

    impl Tcp {
        pub(super) async fn connect(_host: &str, _port: u16) -> Result<Self, NetError> {
            unsupported()
        }
        pub(super) async fn read(&mut self, _buffer: &mut [u8]) -> Result<usize, NetError> {
            match self.0 {}
        }
        pub(super) async fn write_all(&mut self, _data: &[u8]) -> Result<(), NetError> {
            match self.0 {}
        }
        pub(super) async fn shutdown(&mut self) -> Result<(), NetError> {
            match self.0 {}
        }
        pub(super) fn peer_addr(&self) -> Result<SocketAddr, NetError> {
            match self.0 {}
        }
    }

    impl Tls {
        pub(super) async fn handshake(
            tcp: Tcp,
            _host: &str,
            _trust: Trust,
        ) -> Result<Self, NetError> {
            match tcp.0 {}
        }
        pub(super) fn peer_certificate(&self) -> Option<Vec<u8>> {
            match self.0 {}
        }
        pub(super) async fn read(&mut self, _buffer: &mut [u8]) -> Result<usize, NetError> {
            match self.0 {}
        }
        pub(super) async fn write_all(&mut self, _data: &[u8]) -> Result<(), NetError> {
            match self.0 {}
        }
        pub(super) async fn shutdown(&mut self) -> Result<(), NetError> {
            match self.0 {}
        }
    }

    impl Listener {
        pub(super) async fn bind(_address: SocketAddr) -> Result<Self, NetError> {
            unsupported()
        }
        pub(super) async fn accept(&self) -> Result<(Tcp, SocketAddr), NetError> {
            match self.0 {}
        }
        pub(super) fn local_addr(&self) -> Result<SocketAddr, NetError> {
            match self.0 {}
        }
    }

    impl Udp {
        pub(super) async fn bind(_address: SocketAddr) -> Result<Self, NetError> {
            unsupported()
        }
        pub(super) async fn connect(&self, _address: SocketAddr) -> Result<(), NetError> {
            match self.0 {}
        }
        pub(super) async fn send(&self, _data: &[u8]) -> Result<usize, NetError> {
            match self.0 {}
        }
        pub(super) async fn recv(&self, _buffer: &mut [u8]) -> Result<usize, NetError> {
            match self.0 {}
        }
        pub(super) async fn send_to(
            &self,
            _data: &[u8],
            _address: SocketAddr,
        ) -> Result<usize, NetError> {
            match self.0 {}
        }
        pub(super) async fn recv_from(
            &self,
            _buffer: &mut [u8],
        ) -> Result<(usize, SocketAddr), NetError> {
            match self.0 {}
        }
        pub(super) fn local_addr(&self) -> Result<SocketAddr, NetError> {
            match self.0 {}
        }
    }
}

#[cfg(test)]
#[cfg(not(target_family = "wasm"))]
mod tests {
    use super::*;

    #[tokio::test]
    async fn tcp_round_trip_on_loopback() {
        let listener = TcpListener::bind("127.0.0.1:0".parse().unwrap())
            .await
            .unwrap();
        let address = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            let mut buffer = [0; 5];
            let read = stream.read(&mut buffer).await.unwrap();
            stream.write_all(&buffer[..read]).await.unwrap();
        });
        let mut client = TcpStream::connect("127.0.0.1", address.port())
            .await
            .unwrap();
        client.write_all(b"hello").await.unwrap();
        let mut echoed = [0; 5];
        let read = client.read(&mut echoed).await.unwrap();
        assert_eq!(&echoed[..read], b"hello");
        server.await.unwrap();
    }

    #[tokio::test]
    async fn udp_round_trip_on_loopback() {
        let a = UdpSocket::bind("127.0.0.1:0".parse().unwrap())
            .await
            .unwrap();
        let b = UdpSocket::bind("127.0.0.1:0".parse().unwrap())
            .await
            .unwrap();
        a.send_to(b"ping", b.local_addr().unwrap()).await.unwrap();
        let mut buffer = [0; 8];
        let (read, from) = b.recv_from(&mut buffer).await.unwrap();
        assert_eq!(&buffer[..read], b"ping");
        assert_eq!(from, a.local_addr().unwrap());
    }
}