pelikan-net 0.5.0

Pelikan project's networking abstractions for non-blocking event loops
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// Copyright 2024 Pelikan Foundation
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

use std::io::{BufReader, ErrorKind};
use std::os::unix::prelude::AsRawFd;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;

use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
use rustls::{ClientConnection, ServerConfig, ServerConnection, StreamOwned};

use crate::*;

#[derive(PartialEq, Copy, Clone)]
pub enum ShutdownResult {
    Sent,
    Received,
}

#[derive(PartialEq)]
enum TlsState {
    Handshaking,
    Negotiated,
}

enum ConnectionType {
    Server(StreamOwned<ServerConnection, TcpStream>),
    Client(StreamOwned<ClientConnection, TcpStream>),
}

/// Wraps a TLS/SSL stream so that negotiated and handshaking sessions have a
/// uniform type.
pub struct TlsTcpStream {
    inner: ConnectionType,
    state: TlsState,
}

impl AsRawFd for TlsTcpStream {
    fn as_raw_fd(&self) -> i32 {
        match &self.inner {
            ConnectionType::Server(s) => s.sock.as_raw_fd(),
            ConnectionType::Client(s) => s.sock.as_raw_fd(),
        }
    }
}

impl TlsTcpStream {
    pub fn set_nodelay(&mut self, nodelay: bool) -> Result<()> {
        match &mut self.inner {
            ConnectionType::Server(s) => s.sock.set_nodelay(nodelay),
            ConnectionType::Client(s) => s.sock.set_nodelay(nodelay),
        }
    }

    pub fn is_handshaking(&self) -> bool {
        self.state == TlsState::Handshaking
    }

    pub fn interest(&self) -> Interest {
        if self.is_handshaking() {
            Interest::READABLE.add(Interest::WRITABLE)
        } else {
            Interest::READABLE
        }
    }

    /// Attempts to drive the TLS/SSL handshake to completion. If the return
    /// variant is `Ok` it indicates that the handshake is complete. An error
    /// result of `WouldBlock` indicates that the handshake may complete in the
    /// future. Other error types indicate a handshake failure with no possible
    /// recovery and that the connection should be closed.
    pub fn do_handshake(&mut self) -> Result<()> {
        if self.state != TlsState::Handshaking {
            return Ok(());
        }

        let result = match &mut self.inner {
            ConnectionType::Server(s) => s.conn.complete_io(&mut s.sock),
            ConnectionType::Client(s) => s.conn.complete_io(&mut s.sock),
        };

        let still_handshaking = match &self.inner {
            ConnectionType::Server(s) => s.conn.is_handshaking(),
            ConnectionType::Client(s) => s.conn.is_handshaking(),
        };

        if !still_handshaking {
            metric! {
                STREAM_HANDSHAKE.increment();
            }
            self.state = TlsState::Negotiated;
            return Ok(());
        }

        match result {
            Ok(_) => Err(Error::from(ErrorKind::WouldBlock)),
            Err(e) if e.kind() == ErrorKind::WouldBlock => Err(Error::from(ErrorKind::WouldBlock)),
            Err(e) => {
                metric! {
                    STREAM_HANDSHAKE.increment();
                    STREAM_HANDSHAKE_EX.increment();
                }
                Err(Error::other(format!("handshake failed: {}", e)))
            }
        }
    }

    pub fn shutdown(&mut self) -> Result<ShutdownResult> {
        match &mut self.inner {
            ConnectionType::Server(s) => {
                s.conn.send_close_notify();
                match s.conn.complete_io(&mut s.sock) {
                    Ok(_) => {
                        metric! {
                            STREAM_SHUTDOWN.increment();
                        }
                        // Try to receive peer's close_notify
                        match s.conn.complete_io(&mut s.sock) {
                            Ok(_) => Ok(ShutdownResult::Received),
                            _ => Ok(ShutdownResult::Sent),
                        }
                    }
                    Err(e) if e.kind() == ErrorKind::WouldBlock => Ok(ShutdownResult::Sent),
                    Err(e) => Err(Error::other(e.to_string())),
                }
            }
            ConnectionType::Client(s) => {
                s.conn.send_close_notify();
                match s.conn.complete_io(&mut s.sock) {
                    Ok(_) => {
                        metric! {
                            STREAM_SHUTDOWN.increment();
                        }
                        // Try to receive peer's close_notify
                        match s.conn.complete_io(&mut s.sock) {
                            Ok(_) => Ok(ShutdownResult::Received),
                            _ => Ok(ShutdownResult::Sent),
                        }
                    }
                    Err(e) if e.kind() == ErrorKind::WouldBlock => Ok(ShutdownResult::Sent),
                    Err(e) => Err(Error::other(e.to_string())),
                }
            }
        }
    }
}

impl Debug for TlsTcpStream {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        match &self.inner {
            ConnectionType::Server(s) => write!(f, "{:?}", s.sock),
            ConnectionType::Client(s) => write!(f, "{:?}", s.sock),
        }
    }
}

impl Read for TlsTcpStream {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        if self.is_handshaking() {
            Err(Error::new(
                ErrorKind::WouldBlock,
                "read on handshaking session would block",
            ))
        } else {
            match &mut self.inner {
                ConnectionType::Server(s) => s.read(buf),
                ConnectionType::Client(s) => s.read(buf),
            }
        }
    }
}

impl Write for TlsTcpStream {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        if self.is_handshaking() {
            Err(Error::new(
                ErrorKind::WouldBlock,
                "write on handshaking session would block",
            ))
        } else {
            match &mut self.inner {
                ConnectionType::Server(s) => s.write(buf),
                ConnectionType::Client(s) => s.write(buf),
            }
        }
    }

    fn flush(&mut self) -> Result<()> {
        if self.is_handshaking() {
            Err(Error::new(
                ErrorKind::WouldBlock,
                "flush on handshaking session would block",
            ))
        } else {
            match &mut self.inner {
                ConnectionType::Server(s) => s.flush(),
                ConnectionType::Client(s) => s.flush(),
            }
        }
    }
}

impl event::Source for TlsTcpStream {
    fn register(&mut self, registry: &Registry, token: Token, interest: Interest) -> Result<()> {
        match &mut self.inner {
            ConnectionType::Server(s) => s.sock.register(registry, token, interest),
            ConnectionType::Client(s) => s.sock.register(registry, token, interest),
        }
    }

    fn reregister(
        &mut self,
        registry: &mio::Registry,
        token: mio::Token,
        interest: mio::Interest,
    ) -> Result<()> {
        match &mut self.inner {
            ConnectionType::Server(s) => s.sock.reregister(registry, token, interest),
            ConnectionType::Client(s) => s.sock.reregister(registry, token, interest),
        }
    }

    fn deregister(&mut self, registry: &mio::Registry) -> Result<()> {
        match &mut self.inner {
            ConnectionType::Server(s) => s.sock.deregister(registry),
            ConnectionType::Client(s) => s.sock.deregister(registry),
        }
    }
}

// Builder for TlsTcpAcceptor

#[derive(Default)]
pub struct TlsTcpAcceptorBuilder {
    ca_file: Option<PathBuf>,
    certificate_file: Option<PathBuf>,
    certificate_chain_file: Option<PathBuf>,
    private_key_file: Option<PathBuf>,
}

impl TlsTcpAcceptorBuilder {
    pub fn build(self) -> Result<TlsTcpAcceptor> {
        TlsTcpAcceptor::build(self)
    }

    /// Load trusted root certificates from a file.
    pub fn ca_file<P: AsRef<Path>>(mut self, file: P) -> Self {
        self.ca_file = Some(file.as_ref().to_path_buf());
        self
    }

    /// Load a leaf certificate from a file.
    pub fn certificate_file<P: AsRef<Path>>(mut self, file: P) -> Self {
        self.certificate_file = Some(file.as_ref().to_path_buf());
        self
    }

    /// Load a certificate chain from a file.
    pub fn certificate_chain_file<P: AsRef<Path>>(mut self, file: P) -> Self {
        self.certificate_chain_file = Some(file.as_ref().to_path_buf());
        self
    }

    /// Loads the private key from a PEM-formatted file.
    pub fn private_key_file<P: AsRef<Path>>(mut self, file: P) -> Self {
        self.private_key_file = Some(file.as_ref().to_path_buf());
        self
    }
}

/// Provides a wrapped acceptor for server-side TLS.
pub struct TlsTcpAcceptor {
    config: Arc<ServerConfig>,
}

impl TlsTcpAcceptor {
    pub fn builder() -> TlsTcpAcceptorBuilder {
        TlsTcpAcceptorBuilder::default()
    }

    fn build(builder: TlsTcpAcceptorBuilder) -> Result<TlsTcpAcceptor> {
        let certs = load_certs(&builder.certificate_chain_file, &builder.certificate_file)?;
        let key = load_private_key(&builder.private_key_file)?;

        let config = ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(certs, key)
            .map_err(|e| Error::other(format!("failed to build TLS config: {}", e)))?;

        Ok(TlsTcpAcceptor {
            config: Arc::new(config),
        })
    }

    pub fn accept(&self, stream: TcpStream) -> Result<TlsTcpStream> {
        let conn = ServerConnection::new(Arc::clone(&self.config))
            .map_err(|e| Error::other(format!("failed to create server connection: {}", e)))?;

        let mut tls_stream = StreamOwned::new(conn, stream);

        match tls_stream.conn.complete_io(&mut tls_stream.sock) {
            Ok(_) => {
                let state = if tls_stream.conn.is_handshaking() {
                    TlsState::Handshaking
                } else {
                    TlsState::Negotiated
                };
                Ok(TlsTcpStream {
                    inner: ConnectionType::Server(tls_stream),
                    state,
                })
            }
            Err(e) if e.kind() == ErrorKind::WouldBlock => Ok(TlsTcpStream {
                inner: ConnectionType::Server(tls_stream),
                state: TlsState::Handshaking,
            }),
            Err(e) => Err(Error::other(format!("handshake failed: {}", e))),
        }
    }
}

// Builder for TlsTcpConnector

#[derive(Default)]
pub struct TlsTcpConnectorBuilder {
    server_name: Option<String>,
    ca_file: Option<PathBuf>,
    certificate_file: Option<PathBuf>,
    certificate_chain_file: Option<PathBuf>,
    private_key_file: Option<PathBuf>,
}

impl TlsTcpConnectorBuilder {
    pub fn build(self) -> Result<TlsTcpConnector> {
        TlsTcpConnector::build(self)
    }

    /// Set the server name for SNI and certificate verification.
    pub fn server_name(mut self, name: impl Into<String>) -> Self {
        self.server_name = Some(name.into());
        self
    }

    /// Load trusted root certificates from a file.
    pub fn ca_file<P: AsRef<Path>>(mut self, file: P) -> Self {
        self.ca_file = Some(file.as_ref().to_path_buf());
        self
    }

    /// Load a leaf certificate from a file.
    pub fn certificate_file<P: AsRef<Path>>(mut self, file: P) -> Self {
        self.certificate_file = Some(file.as_ref().to_path_buf());
        self
    }

    /// Load a certificate chain from a file.
    pub fn certificate_chain_file<P: AsRef<Path>>(mut self, file: P) -> Self {
        self.certificate_chain_file = Some(file.as_ref().to_path_buf());
        self
    }

    /// Loads the private key from a PEM-formatted file.
    pub fn private_key_file<P: AsRef<Path>>(mut self, file: P) -> Self {
        self.private_key_file = Some(file.as_ref().to_path_buf());
        self
    }
}

/// Provides a wrapped connector for client-side TLS.
pub struct TlsTcpConnector {
    config: Arc<rustls::ClientConfig>,
    server_name: Option<String>,
}

impl TlsTcpConnector {
    pub fn builder() -> TlsTcpConnectorBuilder {
        TlsTcpConnectorBuilder::default()
    }

    fn build(builder: TlsTcpConnectorBuilder) -> Result<TlsTcpConnector> {
        let mut root_store = rustls::RootCertStore::empty();
        root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());

        if let Some(f) = &builder.ca_file {
            let ca_file = std::fs::File::open(f).map_err(|e| {
                Error::other(format!("failed to open CA file: {}: {}", f.display(), e))
            })?;
            let mut ca_reader = BufReader::new(ca_file);
            let ca_certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut ca_reader)
                .collect::<std::result::Result<Vec<_>, _>>()
                .map_err(|e| {
                    Error::other(format!("failed to parse CA file: {}: {}", f.display(), e))
                })?;
            for cert in ca_certs {
                root_store
                    .add(cert)
                    .map_err(|e| Error::other(format!("failed to add CA certificate: {}", e)))?;
            }
        }

        let config_builder = rustls::ClientConfig::builder().with_root_certificates(root_store);

        let config = if builder.private_key_file.is_some() {
            let certs = load_certs(&builder.certificate_chain_file, &builder.certificate_file)?;
            let key = load_private_key(&builder.private_key_file)?;

            config_builder
                .with_client_auth_cert(certs, key)
                .map_err(|e| Error::other(format!("failed to build TLS config: {}", e)))?
        } else {
            config_builder.with_no_client_auth()
        };

        Ok(TlsTcpConnector {
            config: Arc::new(config),
            server_name: builder.server_name,
        })
    }

    pub fn connect<A: ToSocketAddrs>(&self, addr: A) -> Result<TlsTcpStream> {
        let addrs: Vec<SocketAddr> = addr.to_socket_addrs()?.collect();
        let mut s = Err(Error::other("failed to resolve"));
        for addr in &addrs {
            s = TcpStream::connect(*addr);
            if s.is_ok() {
                break;
            }
        }
        let stream = s?;

        let server_name = if let Some(name) = &self.server_name {
            ServerName::try_from(name.as_str())
                .map_err(|e| Error::other(format!("invalid server name: {}", e)))?
                .to_owned()
        } else {
            let ip = addrs
                .first()
                .ok_or_else(|| Error::other("no addresses resolved"))?
                .ip();
            ServerName::IpAddress(ip.into())
        };

        let conn = ClientConnection::new(Arc::clone(&self.config), server_name)
            .map_err(|e| Error::other(format!("failed to create client connection: {}", e)))?;

        let mut tls_stream = StreamOwned::new(conn, stream);

        match tls_stream.conn.complete_io(&mut tls_stream.sock) {
            Ok(_) => {
                let state = if tls_stream.conn.is_handshaking() {
                    TlsState::Handshaking
                } else {
                    TlsState::Negotiated
                };
                Ok(TlsTcpStream {
                    inner: ConnectionType::Client(tls_stream),
                    state,
                })
            }
            Err(e) if e.kind() == ErrorKind::WouldBlock => Ok(TlsTcpStream {
                inner: ConnectionType::Client(tls_stream),
                state: TlsState::Handshaking,
            }),
            Err(e) => Err(Error::other(format!("handshake failed: {}", e))),
        }
    }
}

// Shared helpers

fn load_certs(
    chain_file: &Option<PathBuf>,
    cert_file: &Option<PathBuf>,
) -> Result<Vec<CertificateDer<'static>>> {
    match (chain_file, cert_file) {
        (Some(chain), Some(cert)) => {
            let mut certs = read_certs_from_file(cert)?;
            certs.extend(read_certs_from_file(chain)?);
            Ok(certs)
        }
        (Some(chain), None) => read_certs_from_file(chain),
        (None, Some(cert)) => read_certs_from_file(cert),
        (None, None) => Err(Error::other(
            "no certificate file or certificate chain file provided",
        )),
    }
}

fn read_certs_from_file(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
    let file = std::fs::File::open(path).map_err(|e| {
        Error::other(format!(
            "failed to open certificate file: {}: {}",
            path.display(),
            e
        ))
    })?;
    let mut reader = BufReader::new(file);
    rustls_pemfile::certs(&mut reader)
        .collect::<std::result::Result<Vec<_>, _>>()
        .map_err(|e| {
            Error::other(format!(
                "failed to parse certificate file: {}: {}",
                path.display(),
                e
            ))
        })
}

fn load_private_key(key_file: &Option<PathBuf>) -> Result<PrivateKeyDer<'static>> {
    let f = key_file
        .as_ref()
        .ok_or_else(|| Error::other("no private key file provided"))?;

    let file = std::fs::File::open(f).map_err(|e| {
        Error::other(format!(
            "failed to open private key file: {}: {}",
            f.display(),
            e
        ))
    })?;
    let mut reader = BufReader::new(file);

    let mut keys = Vec::new();
    loop {
        match rustls_pemfile::read_one(&mut reader) {
            Ok(Some(rustls_pemfile::Item::Pkcs1Key(key))) => {
                keys.push(PrivateKeyDer::Pkcs1(key));
            }
            Ok(Some(rustls_pemfile::Item::Pkcs8Key(key))) => {
                keys.push(PrivateKeyDer::Pkcs8(key));
            }
            Ok(Some(rustls_pemfile::Item::Sec1Key(key))) => {
                keys.push(PrivateKeyDer::Sec1(key));
            }
            Ok(Some(_)) => continue,
            Ok(None) => break,
            Err(e) => {
                return Err(Error::other(format!(
                    "failed to parse private key file: {}: {}",
                    f.display(),
                    e
                )));
            }
        }
    }

    keys.into_iter()
        .next()
        .ok_or_else(|| Error::other(format!("no private key found in file: {}", f.display())))
}