rs-netty 1.1.0

A Tokio-native typed TCP/UDP pipeline framework inspired by Netty.
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
use std::{collections::HashMap, fmt, io::Cursor, marker::PhantomData, sync::Arc};

use rustls::{
    pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName},
    server::{ClientHello, ResolvesServerCert, WebPkiClientVerifier},
    sign::CertifiedKey,
    ClientConfig, RootCertStore, ServerConfig,
};
use tokio_rustls::{client, server, TlsAcceptor, TlsConnector};

use crate::{Error, Result};

/// Entry point for building TLS contexts.
pub struct TlsContextBuilder;

/// Marker for a client TLS builder with no trust strategy selected.
pub struct NoTrust;

/// Marker for a client TLS builder with a trust strategy selected.
pub struct HasTrust;

/// TLS metadata for an established TCP connection.
#[derive(Clone, Debug)]
pub struct TlsInfo {
    peer_certificates: Vec<CertificateDer<'static>>,
    selected_alpn_protocol: Option<Vec<u8>>,
    server_name: Option<String>,
}

impl TlsInfo {
    /// Peer certificate chain presented during TLS handshake.
    pub fn peer_certificates(&self) -> &[CertificateDer<'static>] {
        &self.peer_certificates
    }

    /// ALPN protocol selected by the TLS handshake.
    pub fn selected_alpn_protocol(&self) -> Option<&[u8]> {
        self.selected_alpn_protocol.as_deref()
    }

    /// Server name used for the TLS connection.
    ///
    /// On the server side this is the SNI value supplied by the client. On the
    /// client side this is the effective server name used for SNI and
    /// certificate verification.
    pub fn server_name(&self) -> Option<&str> {
        self.server_name.as_deref()
    }

    fn from_server_connection(connection: &rustls::ServerConnection) -> Self {
        Self {
            peer_certificates: connection
                .peer_certificates()
                .map(|certificates| certificates.to_vec())
                .unwrap_or_default(),
            selected_alpn_protocol: connection.alpn_protocol().map(Vec::from),
            server_name: connection.server_name().map(str::to_string),
        }
    }

    fn from_client_connection(connection: &rustls::ClientConnection, server_name: String) -> Self {
        Self {
            peer_certificates: connection
                .peer_certificates()
                .map(|certificates| certificates.to_vec())
                .unwrap_or_default(),
            selected_alpn_protocol: connection.alpn_protocol().map(Vec::from),
            server_name: Some(server_name),
        }
    }
}

/// Server-side TLS context.
#[derive(Clone)]
pub struct ServerTlsContext {
    config: Arc<ServerConfig>,
}

impl ServerTlsContext {
    pub(crate) fn acceptor(&self) -> TlsAcceptor {
        TlsAcceptor::from(self.config.clone())
    }

    pub(crate) fn info_for_stream<S>(&self, stream: &server::TlsStream<S>) -> Arc<TlsInfo> {
        Arc::new(TlsInfo::from_server_connection(stream.get_ref().1))
    }
}

/// Client-side TLS context.
#[derive(Clone)]
pub struct ClientTlsContext {
    config: Arc<ClientConfig>,
    server_name: Option<String>,
}

impl ClientTlsContext {
    pub(crate) fn connector(&self) -> TlsConnector {
        TlsConnector::from(self.config.clone())
    }

    pub(crate) fn server_name_for(&self, host: &str) -> Result<ResolvedServerName> {
        let name = self.server_name.as_deref().unwrap_or(host);
        let server_name = ServerName::try_from(name.to_string()).map_err(|err| {
            tls_invalid_server_name(format!("invalid TLS server name `{name}`: {err}"))
        })?;
        Ok(ResolvedServerName {
            display: name.to_string(),
            server_name,
        })
    }

    pub(crate) fn info_for_stream<S>(
        &self,
        stream: &client::TlsStream<S>,
        server_name: String,
    ) -> Arc<TlsInfo> {
        Arc::new(TlsInfo::from_client_connection(
            stream.get_ref().1,
            server_name,
        ))
    }
}

pub(crate) struct ResolvedServerName {
    pub(crate) display: String,
    pub(crate) server_name: ServerName<'static>,
}

/// Builder for server-side TLS contexts.
pub struct ServerTlsContextBuilder {
    certificates: Vec<CertificateDer<'static>>,
    private_key: Option<PrivateKeyDer<'static>>,
    client_auth_roots: RootCertStore,
    client_auth_mode: ClientAuthMode,
    sni_identities: Vec<SniIdentity>,
    alpn_protocols: Vec<Vec<u8>>,
    errors: Vec<String>,
}

/// Typestate builder for client-side TLS contexts.
pub struct ClientTlsContextBuilder<TrustState> {
    roots: RootCertStore,
    verifier: Option<Arc<dyn rustls::client::danger::ServerCertVerifier>>,
    client_identity: Option<ClientIdentity>,
    alpn_protocols: Vec<Vec<u8>>,
    server_name: Option<String>,
    errors: Vec<String>,
    _state: PhantomData<TrustState>,
}

struct ClientIdentity {
    certificates: Vec<CertificateDer<'static>>,
    private_key: PrivateKeyDer<'static>,
}

struct SniIdentity {
    name: String,
    certificates: Vec<CertificateDer<'static>>,
    private_key: PrivateKeyDer<'static>,
}

#[derive(Clone, Copy)]
enum ClientAuthMode {
    None,
    Required,
    Optional,
}

impl TlsContextBuilder {
    /// Starts a server-side TLS context builder.
    pub fn for_server() -> ServerTlsContextBuilder {
        ServerTlsContextBuilder {
            certificates: Vec::new(),
            private_key: None,
            client_auth_roots: RootCertStore::empty(),
            client_auth_mode: ClientAuthMode::None,
            sni_identities: Vec::new(),
            alpn_protocols: Vec::new(),
            errors: Vec::new(),
        }
    }

    /// Starts a client-side TLS context builder.
    pub fn for_client() -> ClientTlsContextBuilder<NoTrust> {
        ClientTlsContextBuilder {
            roots: RootCertStore::empty(),
            verifier: None,
            client_identity: None,
            alpn_protocols: Vec::new(),
            server_name: None,
            errors: Vec::new(),
            _state: PhantomData,
        }
    }

    /// Starts a client builder and selects native platform roots.
    #[cfg(feature = "tls-native-roots")]
    pub fn for_client_with_native_roots() -> ClientTlsContextBuilder<HasTrust> {
        Self::for_client().native_roots()
    }

    /// Starts a client builder and selects Mozilla WebPKI roots.
    #[cfg(feature = "tls-webpki-roots")]
    pub fn for_client_with_webpki_roots() -> ClientTlsContextBuilder<HasTrust> {
        Self::for_client().webpki_roots()
    }
}

impl ServerTlsContextBuilder {
    /// Adds a PEM-encoded certificate chain.
    pub fn certificate_chain_pem(mut self, pem: impl AsRef<[u8]>) -> Self {
        match parse_certificates_pem(pem.as_ref()) {
            Ok(mut certificates) => self.certificates.append(&mut certificates),
            Err(err) => self.errors.push(err),
        }
        self
    }

    /// Adds a single DER-encoded certificate to the certificate chain.
    pub fn certificate_der(mut self, der: impl Into<Vec<u8>>) -> Self {
        self.certificates.push(CertificateDer::from(der.into()));
        self
    }

    /// Sets a PEM-encoded private key.
    pub fn private_key_pem(mut self, pem: impl AsRef<[u8]>) -> Self {
        match parse_private_key_pem(pem.as_ref()) {
            Ok(private_key) => self.private_key = Some(private_key),
            Err(err) => self.errors.push(err),
        }
        self
    }

    /// Sets a DER-encoded PKCS#8 private key.
    pub fn private_key_der(mut self, der: impl Into<Vec<u8>>) -> Self {
        self.private_key = Some(PrivatePkcs8KeyDer::from(der.into()).into());
        self
    }

    /// Requires clients to present a certificate trusted by the PEM-encoded roots.
    pub fn client_auth_required_pem(mut self, pem: impl AsRef<[u8]>) -> Self {
        self.client_auth_mode = ClientAuthMode::Required;
        match parse_certificates_pem(pem.as_ref()) {
            Ok(certificates) => {
                add_roots(&mut self.client_auth_roots, certificates, &mut self.errors)
            }
            Err(err) => self.errors.push(err),
        }
        self
    }

    /// Requires clients to present a certificate trusted by this DER-encoded root.
    pub fn client_auth_required_der(mut self, der: impl Into<Vec<u8>>) -> Self {
        self.client_auth_mode = ClientAuthMode::Required;
        add_roots(
            &mut self.client_auth_roots,
            vec![CertificateDer::from(der.into())],
            &mut self.errors,
        );
        self
    }

    /// Allows clients to omit a certificate, but verifies one when presented.
    pub fn client_auth_optional_pem(mut self, pem: impl AsRef<[u8]>) -> Self {
        self.client_auth_mode = ClientAuthMode::Optional;
        match parse_certificates_pem(pem.as_ref()) {
            Ok(certificates) => {
                add_roots(&mut self.client_auth_roots, certificates, &mut self.errors)
            }
            Err(err) => self.errors.push(err),
        }
        self
    }

    /// Allows clients to omit a certificate, but verifies one against this DER root.
    pub fn client_auth_optional_der(mut self, der: impl Into<Vec<u8>>) -> Self {
        self.client_auth_mode = ClientAuthMode::Optional;
        add_roots(
            &mut self.client_auth_roots,
            vec![CertificateDer::from(der.into())],
            &mut self.errors,
        );
        self
    }

    /// Sets ALPN protocols advertised by this server.
    pub fn alpn_protocols<I, P>(mut self, protocols: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: AsRef<[u8]>,
    {
        self.alpn_protocols = collect_alpn_protocols(protocols, &mut self.errors);
        self
    }

    /// Adds an SNI-specific PEM-encoded certificate chain and private key.
    pub fn sni_certificate_pem(
        mut self,
        name: impl Into<String>,
        certificate_chain: impl AsRef<[u8]>,
        private_key: impl AsRef<[u8]>,
    ) -> Self {
        let certificates = match parse_certificates_pem(certificate_chain.as_ref()) {
            Ok(certificates) => certificates,
            Err(err) => {
                self.errors.push(err);
                Vec::new()
            }
        };
        let private_key = match parse_private_key_pem(private_key.as_ref()) {
            Ok(private_key) => Some(private_key),
            Err(err) => {
                self.errors.push(err);
                None
            }
        };

        if let Some(private_key) = private_key {
            self.sni_identities.push(SniIdentity {
                name: name.into(),
                certificates,
                private_key,
            });
        }
        self
    }

    /// Adds an SNI-specific DER-encoded certificate chain and PKCS#8 private key.
    pub fn sni_certificate_der(
        mut self,
        name: impl Into<String>,
        certificate_chain: impl IntoIterator<Item = impl Into<Vec<u8>>>,
        private_key: impl Into<Vec<u8>>,
    ) -> Self {
        self.sni_identities.push(SniIdentity {
            name: name.into(),
            certificates: certificate_chain
                .into_iter()
                .map(|certificate| CertificateDer::from(certificate.into()))
                .collect(),
            private_key: PrivatePkcs8KeyDer::from(private_key.into()).into(),
        });
        self
    }

    /// Builds the server TLS context.
    pub fn build(self) -> Result<ServerTlsContext> {
        if let Some(error) = first_error(self.errors) {
            return Err(tls_config_error(error));
        }

        if self.certificates.is_empty() && self.sni_identities.is_empty() {
            return Err(tls_config_error(
                "server TLS context requires a certificate chain".to_string(),
            ));
        }

        if !self.certificates.is_empty() && self.private_key.is_none() {
            return Err(tls_config_error(
                "server TLS context requires a private key".to_string(),
            ));
        }
        if self.certificates.is_empty() && self.private_key.is_some() {
            return Err(tls_config_error(
                "server TLS context private key requires a certificate chain".to_string(),
            ));
        }

        let builder = ServerConfig::builder();
        let builder = match self.client_auth_mode {
            ClientAuthMode::None => builder.with_no_client_auth(),
            ClientAuthMode::Required | ClientAuthMode::Optional => {
                let mut verifier = WebPkiClientVerifier::builder(Arc::new(self.client_auth_roots));
                if matches!(self.client_auth_mode, ClientAuthMode::Optional) {
                    verifier = verifier.allow_unauthenticated();
                }
                let verifier = verifier.build().map_err(|err| {
                    tls_config_error(format!("invalid client authentication roots: {err}"))
                })?;
                builder.with_client_cert_verifier(verifier)
            }
        };

        let mut config = if self.sni_identities.is_empty() {
            let private_key = self.private_key.ok_or_else(|| {
                tls_config_error("server TLS context requires a private key".to_string())
            })?;
            builder
                .with_single_cert(self.certificates, private_key)
                .map_err(|err| tls_config_error(format!("invalid server TLS identity: {err}")))?
        } else {
            let resolver = build_sni_resolver(
                builder.crypto_provider(),
                self.certificates,
                self.private_key,
                self.sni_identities,
            )?;
            builder.with_cert_resolver(Arc::new(resolver))
        };
        config.alpn_protocols = self.alpn_protocols;

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

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

    /// Sets ALPN protocols advertised by this client.
    pub fn alpn_protocols<I, P>(mut self, protocols: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: AsRef<[u8]>,
    {
        self.alpn_protocols = collect_alpn_protocols(protocols, &mut self.errors);
        self
    }

    /// Adds PEM-encoded root certificates and selects custom roots as the trust strategy.
    pub fn root_certificate_pem(
        mut self,
        pem: impl AsRef<[u8]>,
    ) -> ClientTlsContextBuilder<HasTrust> {
        match parse_certificates_pem(pem.as_ref()) {
            Ok(certificates) => add_roots(&mut self.roots, certificates, &mut self.errors),
            Err(err) => self.errors.push(err),
        }
        self.with_state()
    }

    /// Adds a DER-encoded root certificate and selects custom roots as the trust strategy.
    pub fn root_certificate_der(
        mut self,
        der: impl Into<Vec<u8>>,
    ) -> ClientTlsContextBuilder<HasTrust> {
        add_roots(
            &mut self.roots,
            vec![CertificateDer::from(der.into())],
            &mut self.errors,
        );
        self.with_state()
    }

    /// Selects native platform root certificates as the trust strategy.
    #[cfg(feature = "tls-native-roots")]
    pub fn native_roots(mut self) -> ClientTlsContextBuilder<HasTrust> {
        let certificates = rustls_native_certs::load_native_certs();
        if certificates.certs.is_empty() && !certificates.errors.is_empty() {
            self.errors.push(format!(
                "failed to load native root certificates: {:?}",
                certificates.errors
            ));
        }
        add_roots(&mut self.roots, certificates.certs, &mut self.errors);
        self.with_state()
    }

    /// Selects Mozilla WebPKI root certificates as the trust strategy.
    #[cfg(feature = "tls-webpki-roots")]
    pub fn webpki_roots(mut self) -> ClientTlsContextBuilder<HasTrust> {
        self.roots
            .extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
        self.with_state()
    }

    /// Selects a custom server certificate verifier.
    #[cfg(feature = "tls-dangerous")]
    pub fn custom_verifier(
        mut self,
        verifier: Arc<dyn rustls::client::danger::ServerCertVerifier>,
    ) -> ClientTlsContextBuilder<HasTrust> {
        self.verifier = Some(verifier);
        self.with_state()
    }

    /// Disables server certificate verification.
    ///
    /// This is intended only for local development and tests.
    #[cfg(feature = "tls-dangerous")]
    pub fn danger_accept_invalid_certs(self) -> ClientTlsContextBuilder<HasTrust> {
        self.custom_verifier(Arc::new(DangerAcceptInvalidCerts))
    }

    fn with_state<NextState>(self) -> ClientTlsContextBuilder<NextState> {
        ClientTlsContextBuilder {
            roots: self.roots,
            verifier: self.verifier,
            client_identity: self.client_identity,
            alpn_protocols: self.alpn_protocols,
            server_name: self.server_name,
            errors: self.errors,
            _state: PhantomData,
        }
    }
}

impl ClientTlsContextBuilder<HasTrust> {
    /// Sets the client certificate chain and private key used for mTLS.
    pub fn client_identity_pem(
        mut self,
        certificate_chain: impl AsRef<[u8]>,
        private_key: impl AsRef<[u8]>,
    ) -> Self {
        let certificates = match parse_certificates_pem(certificate_chain.as_ref()) {
            Ok(certificates) => certificates,
            Err(err) => {
                self.errors.push(err);
                Vec::new()
            }
        };
        let private_key = match parse_private_key_pem(private_key.as_ref()) {
            Ok(private_key) => Some(private_key),
            Err(err) => {
                self.errors.push(err);
                None
            }
        };

        if let Some(private_key) = private_key {
            self.client_identity = Some(ClientIdentity {
                certificates,
                private_key,
            });
        }
        self
    }

    /// Sets the DER-encoded client certificate chain and PKCS#8 private key used for mTLS.
    pub fn client_identity_der(
        mut self,
        certificate_chain: impl IntoIterator<Item = impl Into<Vec<u8>>>,
        private_key: impl Into<Vec<u8>>,
    ) -> Self {
        self.client_identity = Some(ClientIdentity {
            certificates: certificate_chain
                .into_iter()
                .map(|certificate| CertificateDer::from(certificate.into()))
                .collect(),
            private_key: PrivatePkcs8KeyDer::from(private_key.into()).into(),
        });
        self
    }

    /// Builds the client TLS context.
    pub fn build(self) -> Result<ClientTlsContext> {
        if let Some(error) = first_error(self.errors) {
            return Err(tls_config_error(error));
        }

        let builder = if let Some(verifier) = self.verifier {
            ClientConfig::builder()
                .dangerous()
                .with_custom_certificate_verifier(verifier)
        } else {
            if self.roots.is_empty() {
                return Err(tls_config_error(
                    "client TLS context requires at least one root certificate".to_string(),
                ));
            }
            ClientConfig::builder().with_root_certificates(self.roots)
        };

        let mut config = if let Some(identity) = self.client_identity {
            if identity.certificates.is_empty() {
                return Err(tls_config_error(
                    "client TLS identity requires a certificate chain".to_string(),
                ));
            }
            builder
                .with_client_auth_cert(identity.certificates, identity.private_key)
                .map_err(|err| tls_config_error(format!("invalid client TLS identity: {err}")))?
        } else {
            builder.with_no_client_auth()
        };
        config.alpn_protocols = self.alpn_protocols;

        Ok(ClientTlsContext {
            config: Arc::new(config),
            server_name: self.server_name,
        })
    }
}

#[derive(Debug)]
struct SniCertResolver {
    by_name: HashMap<String, Arc<CertifiedKey>>,
    fallback: Option<Arc<CertifiedKey>>,
}

impl ResolvesServerCert for SniCertResolver {
    fn resolve(&self, client_hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
        client_hello
            .server_name()
            .and_then(|name| self.by_name.get(name).cloned())
            .or_else(|| self.fallback.clone())
    }
}

fn build_sni_resolver(
    provider: &Arc<rustls::crypto::CryptoProvider>,
    default_certificates: Vec<CertificateDer<'static>>,
    default_private_key: Option<PrivateKeyDer<'static>>,
    sni_identities: Vec<SniIdentity>,
) -> Result<SniCertResolver> {
    let fallback = if default_certificates.is_empty() {
        None
    } else {
        let private_key = default_private_key.ok_or_else(|| {
            tls_config_error("server TLS context requires a private key".to_string())
        })?;
        Some(Arc::new(
            CertifiedKey::from_der(default_certificates, private_key, provider)
                .map_err(|err| tls_config_error(format!("invalid fallback TLS identity: {err}")))?,
        ))
    };

    let mut by_name = HashMap::new();
    for identity in sni_identities {
        let name = normalize_sni_name(&identity.name)?;
        if identity.certificates.is_empty() {
            return Err(tls_config_error(format!(
                "SNI identity `{}` requires a certificate chain",
                identity.name
            )));
        }
        let certified_key =
            CertifiedKey::from_der(identity.certificates, identity.private_key, provider).map_err(
                |err| {
                    tls_config_error(format!(
                        "invalid SNI TLS identity `{}`: {err}",
                        identity.name
                    ))
                },
            )?;
        by_name.insert(name, Arc::new(certified_key));
    }

    Ok(SniCertResolver { by_name, fallback })
}

fn normalize_sni_name(name: &str) -> Result<String> {
    match ServerName::try_from(name.to_string())
        .map_err(|err| tls_config_error(format!("invalid SNI server name `{name}`: {err}")))?
    {
        ServerName::DnsName(name) => Ok(name.as_ref().to_ascii_lowercase()),
        ServerName::IpAddress(_) => Err(tls_config_error(format!(
            "invalid SNI server name `{name}`: IP addresses are not valid SNI names"
        ))),
        _ => Err(tls_config_error(format!(
            "invalid SNI server name `{name}`: unsupported server name type"
        ))),
    }
}

fn collect_alpn_protocols<I, P>(protocols: I, errors: &mut Vec<String>) -> Vec<Vec<u8>>
where
    I: IntoIterator<Item = P>,
    P: AsRef<[u8]>,
{
    let mut values = Vec::new();
    for protocol in protocols {
        let protocol = protocol.as_ref();
        if protocol.is_empty() {
            errors.push("ALPN protocol name must not be empty".to_string());
            continue;
        }
        if protocol.len() > 255 {
            errors.push(format!(
                "ALPN protocol name must be at most 255 bytes, got {}",
                protocol.len()
            ));
            continue;
        }
        values.push(protocol.to_vec());
    }
    values
}

pub(crate) fn tls_handshake_error(action: &str, err: impl fmt::Display) -> Error {
    Error::Tls(format!("TLS handshake failed during {action}: {err}"))
}

fn tls_config_error(message: impl Into<String>) -> Error {
    Error::Tls(format!("TLS configuration failed: {}", message.into()))
}

fn tls_invalid_server_name(message: impl Into<String>) -> Error {
    Error::Tls(format!(
        "TLS server name validation failed: {}",
        message.into()
    ))
}

fn parse_certificates_pem(pem: &[u8]) -> std::result::Result<Vec<CertificateDer<'static>>, String> {
    rustls_pemfile::certs(&mut Cursor::new(pem))
        .collect::<std::result::Result<Vec<_>, _>>()
        .map_err(|err| format!("failed to parse PEM certificate chain: {err}"))
}

fn parse_private_key_pem(pem: &[u8]) -> std::result::Result<PrivateKeyDer<'static>, String> {
    rustls_pemfile::private_key(&mut Cursor::new(pem))
        .map_err(|err| format!("failed to parse PEM private key: {err}"))?
        .ok_or_else(|| "PEM private key was not found".to_string())
}

fn add_roots(
    roots: &mut RootCertStore,
    certificates: Vec<CertificateDer<'static>>,
    errors: &mut Vec<String>,
) {
    let (added, ignored) = roots.add_parsable_certificates(certificates);
    if added == 0 {
        errors.push("no valid root certificates were added".to_string());
    }
    if ignored > 0 {
        errors.push(format!("{ignored} root certificate(s) could not be parsed"));
    }
}

fn first_error(errors: Vec<String>) -> Option<String> {
    errors.into_iter().next()
}

#[cfg(feature = "tls-dangerous")]
#[derive(Debug)]
struct DangerAcceptInvalidCerts;

#[cfg(feature = "tls-dangerous")]
impl rustls::client::danger::ServerCertVerifier for DangerAcceptInvalidCerts {
    fn verify_server_cert(
        &self,
        _end_entity: &CertificateDer<'_>,
        _intermediates: &[CertificateDer<'_>],
        _server_name: &ServerName<'_>,
        _ocsp_response: &[u8],
        _now: rustls::pki_types::UnixTime,
    ) -> std::result::Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
        Ok(rustls::client::danger::ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> std::result::Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        vec![
            rustls::SignatureScheme::RSA_PKCS1_SHA256,
            rustls::SignatureScheme::RSA_PKCS1_SHA384,
            rustls::SignatureScheme::RSA_PKCS1_SHA512,
            rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
            rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
            rustls::SignatureScheme::RSA_PSS_SHA256,
            rustls::SignatureScheme::RSA_PSS_SHA384,
            rustls::SignatureScheme::RSA_PSS_SHA512,
            rustls::SignatureScheme::ED25519,
            rustls::SignatureScheme::ED448,
        ]
    }
}