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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
use std::{
    sync::{
        Arc,
    },
    time::{
        Duration,
    },
    net::{
        IpAddr,
        Ipv4Addr,
        Ipv6Addr,
    },
};

use http::{
    uri::{
        Uri,
    },
};

use hyper_util::{
    client::{
        legacy,
    },
};

use tokio::{
    net::{
        TcpStream,
    },
};


use crate::{
    resolver,
    Io,
    Protocols,
    IoStream,
    IoKind,
    IoTcp,
    IoTcpTls,
    TokioIo,
};

#[derive(Debug)]
pub enum Error {
    UriMissingScheme {
        uri: Uri,
    },
    UriMissingHost {
        uri: Uri,
    },
    UriUnsupportedHttpsScheme {
        uri: Uri,
        scheme: http::uri::Scheme,
    },
    ResolverBuild(hickory_resolver::error::ResolveError),
    TlsNonEmptyAlpnProtocols,
    TlsNativeCertsLoad(std::io::Error),
    TlsNativeCertAdd(rustls::Error),
    TlsInvalidDnsName {
        hostname: String,
        error: rustls::pki_types::InvalidDnsNameError,
    },
    Connection(Box<dyn std::error::Error + Send + Sync + 'static>),
    ConnectionToSocks5(Box<dyn std::error::Error + Send + Sync + 'static>),
    ConnectionViaSocks5(async_socks5::Error),
    ConnectionTls(std::io::Error),
}

pub struct ResolverBuilder {
    resolver_kind: resolver::ResolverKind,
}

impl ResolverBuilder {
    pub(super) fn new() -> Self {
        Self {
            resolver_kind: resolver::ResolverKind::System,
        }
    }

    /// Creates a system configuration.
    /// This will use `/etc/resolv.conf` on Unix OSes and the registry on Windows.
    ///
    /// Default resolver is `system`.
    pub fn system(mut self) -> Self {
        self.resolver_kind = resolver::ResolverKind::System;
        self
    }

    /// Creates a configuration using 8.8.8.8, 8.8.4.4 and 2001:4860:4860::8888, 2001:4860:4860::8844.
    ///
    /// Default resolver is `system`.
    pub fn google(mut self) -> Self {
        self.resolver_kind = resolver::ResolverKind::Google;
        self
    }

    /// Creates a configuration using 8.8.8.8, 8.8.4.4 and 2001:4860:4860::8888, 2001:4860:4860::8844.
    /// This limits the registered connections to just TLS lookups.
    ///
    /// Default resolver is `system`.
    pub fn google_tls(mut self) -> Self {
        self.resolver_kind = resolver::ResolverKind::GoogleTls;
        self
    }

    /// Creates a configuration using 8.8.8.8, 8.8.4.4 and 2001:4860:4860::8888, 2001:4860:4860::8844.
    /// This limits the registered connections to just HTTPS lookups.
    ///
    /// Default resolver is `system`.
    pub fn google_https(mut self) -> Self {
        self.resolver_kind = resolver::ResolverKind::GoogleHttps;
        self
    }

    /// Build resolver and proceed with connection setup.
    pub fn connection_setup(self, uri: Uri) -> Result<ConnectionBuilder, Error> {
        let uri_scheme = uri.scheme()
            .ok_or_else(|| Error::UriMissingScheme { uri: uri.clone(), })?
            .clone();
        let uri_host = uri.host()
            .ok_or_else(|| Error::UriMissingHost { uri: uri.clone(), })?
            .to_string();
        let resolver = resolver::HickoryResolver::new(self.resolver_kind)
            .map_err(Error::ResolverBuild)?;
        Ok(ConnectionBuilder::new(resolver, uri, uri_host, uri_scheme))
    }
}

pub struct ConnectionBuilder {
    uri: Uri,
    uri_host: String,
    uri_scheme: http::uri::Scheme,
    resolver: resolver::HickoryResolver,
    http_connector_params: HttpConnectorParams,
}

#[derive(Default)]
struct HttpConnectorParams {
    keepalive_time: Option<Option<Duration>>,
    keepalive_interval_interval: Option<Option<Duration>>,
    keepalive_retries_retries: Option<Option<u32>>,
    nodelay_nodelay: Option<bool>,
    send_buffer_size_size: Option<Option<usize>>,
    recv_buffer_size_size: Option<Option<usize>>,
    local_address_addr: Option<Option<IpAddr>>,
    local_addresses_addrs: Option<(Ipv4Addr, Ipv6Addr)>,
    connect_timeout_dur: Option<Option<Duration>>,
    happy_eyeballs_timeout_dur: Option<Option<Duration>>,
    reuse_address_reuse_address: Option<bool>,
    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
    interface_interface: Option<String>,
}

impl HttpConnectorParams {
    fn apply_resolver(
        &self,
        resolver: &mut resolver::HickoryResolver,
    )
    {
        if let Some(maybe_ip) = &self.local_address_addr {
            if let Some(ip) = maybe_ip {
                if ip.is_ipv4() {
                    resolver.force_ip4();
                } else if ip.is_ipv6() {
                    resolver.force_ip6();
                }
            } else {
                resolver.force_none();
            }
        }
    }

    fn apply(
        self,
        http_connector: &mut legacy::connect::HttpConnector<resolver::HickoryResolver>,
    )
    {
        if let Some(value) = self.keepalive_time {
            http_connector.set_keepalive(value);
        }
        if let Some(value) = self.keepalive_interval_interval {
            http_connector.set_keepalive_interval(value);
        }
        if let Some(value) = self.keepalive_retries_retries {
            http_connector.set_keepalive_retries(value);
        }
        if let Some(value) = self.nodelay_nodelay {
            http_connector.set_nodelay(value);
        }
        if let Some(value) = self.send_buffer_size_size {
            http_connector.set_send_buffer_size(value);
        }
        if let Some(value) = self.recv_buffer_size_size {
            http_connector.set_recv_buffer_size(value);
        }
        if let Some(maybe_ip) = self.local_address_addr {
            http_connector.set_local_address(maybe_ip);
        }
        if let Some((ip4, ip6)) = self.local_addresses_addrs {
            http_connector.set_local_addresses(ip4, ip6);
        }
        if let Some(value) = self.connect_timeout_dur {
            http_connector.set_connect_timeout(value);
        }
        if let Some(value) = self.happy_eyeballs_timeout_dur {
            http_connector.set_happy_eyeballs_timeout(value);
        }
        if let Some(value) = self.reuse_address_reuse_address {
            http_connector.set_reuse_address(value);
        }
        #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
        if let Some(value) = self.interface_interface {
            http_connector.set_interface(value);
        }
    }
}

impl ConnectionBuilder {
    fn new(
        resolver: resolver::HickoryResolver,
        uri: Uri,
        uri_host: String,
        uri_scheme: http::uri::Scheme,
    )
        -> Self
    {
        Self {
            uri,
            uri_host,
            uri_scheme,
            resolver,
            http_connector_params: HttpConnectorParams::default(),
        }
    }

    /// Set that all sockets have `SO_KEEPALIVE` set with the supplied duration
    /// to remain idle before sending TCP keepalive probes.
    ///
    /// If `None`, keepalive is disabled.
    ///
    /// Default is `None`.
    pub fn keepalive(mut self, time: Option<Duration>) -> Self {
        self.http_connector_params.keepalive_time = Some(time);
        self
    }

    /// Set the duration between two successive TCP keepalive retransmissions,
    /// if acknowledgement to the previous keepalive transmission is not received.
    pub fn keepalive_interval(mut self, interval: Option<Duration>) -> Self {
        self.http_connector_params.keepalive_interval_interval = Some(interval);
        self
    }

    /// Set the number of retransmissions to be carried out before declaring that remote end is not available.
    pub fn keepalive_retries(mut self, retries: Option<u32>) -> Self {
        self.http_connector_params.keepalive_retries_retries = Some(retries);
        self
    }

    /// Set that all sockets have `SO_NODELAY` set to the supplied value `nodelay`.
    ///
    /// Default is `false`.
    pub fn nodelay(mut self, nodelay: bool) -> Self {
        self.http_connector_params.nodelay_nodelay = Some(nodelay);
        self
    }

    /// Sets the value of the SO_SNDBUF option on the socket.
    pub fn send_buffer_size(mut self, size: Option<usize>) -> Self {
        self.http_connector_params.send_buffer_size_size = Some(size);
        self
    }

    /// Sets the value of the SO_RCVBUF option on the socket.
    pub fn recv_buffer_size(mut self, size: Option<usize>) -> Self {
        self.http_connector_params.recv_buffer_size_size = Some(size);
        self
    }

    /// Set that all sockets are bound to the configured address before connection.
    ///
    /// If `None`, the sockets will not be bound.
    ///
    /// Default is `None`.
    pub fn local_address(mut self, addr: Option<IpAddr>) -> Self {
        self.http_connector_params.local_address_addr = Some(addr);
        self
    }

    /// Set that all sockets are bound to the configured IPv4 or IPv6 address (depending on host's
    /// preferences) before connection.
    pub fn local_addresses(mut self, addr_ipv4: Ipv4Addr, addr_ipv6: Ipv6Addr) -> Self {
        self.http_connector_params.local_addresses_addrs = Some((addr_ipv4, addr_ipv6));
        self
    }

    /// Set the connect timeout.
    ///
    /// If a domain resolves to multiple IP addresses, the timeout will be
    /// evenly divided across them.
    ///
    /// Default is `None`.
    pub fn connect_timeout(mut self, dur: Option<Duration>) -> Self {
        self.http_connector_params.connect_timeout_dur = Some(dur);
        self
    }

    /// Set timeout for [RFC 6555 (Happy Eyeballs)][RFC 6555] algorithm.
    ///
    /// If hostname resolves to both IPv4 and IPv6 addresses and connection
    /// cannot be established using preferred address family before timeout
    /// elapses, then connector will in parallel attempt connection using other
    /// address family.
    ///
    /// If `None`, parallel connection attempts are disabled.
    ///
    /// Default is 300 milliseconds.
    ///
    /// [RFC 6555]: https://tools.ietf.org/html/rfc6555
    pub fn happy_eyeballs_timeout(mut self, dur: Option<Duration>) -> Self {
        self.http_connector_params.happy_eyeballs_timeout_dur = Some(dur);
        self
    }

    /// Set that all socket have `SO_REUSEADDR` set to the supplied value `reuse_address`.
    ///
    /// Default is `false`.
    pub fn reuse_address(mut self, reuse_address: bool) -> Self {
        self.http_connector_params.reuse_address_reuse_address = Some(reuse_address);
        self
    }

    /// Sets the value for the `SO_BINDTODEVICE` option on this socket.
    ///
    /// If a socket is bound to an interface, only packets received from that particular
    /// interface are processed by the socket. Note that this only works for some socket
    /// types, particularly AF_INET sockets.
    ///
    /// On Linux it can be used to specify a [VRF], but the binary needs
    /// to either have `CAP_NET_RAW` or to be run as root.
    ///
    /// This function is only available on Android、Fuchsia and Linux.
    ///
    /// [VRF]: https://www.kernel.org/doc/Documentation/networking/vrf.txt
    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
    pub fn interface<S: Into<String>>(mut self, interface: S) -> Self {
        self.http_connector_params.interface_interface = Some(interface.into());
        self
    }

    /// Build and establish connection
    pub async fn establish(mut self) -> Result<Io, Error> {
        self.http_connector_params.apply_resolver(
            &mut self.resolver,
        );
        let mut http_connector =
            legacy::connect::HttpConnector::new_with_resolver(
                self.resolver,
            );
        self.http_connector_params.apply(
            &mut http_connector,
        );
        let stream = connection_establish_tcp(http_connector, self.uri).await?;
        Ok(Io {
            protocols: Protocols {
                http1_support: true,
                http2_support: false,
            },
            uri_host: self.uri_host,
            stream: IoStream {
                kind: IoKind::Tcp(
                    IoTcp {
                        stream,
                    },
                ),
            },
        })
    }

    /// Build connection and proceed with tls setup.
    pub async fn tls_setup(mut self) -> Result<TlsBuilder, Error> {
        self.http_connector_params.apply_resolver(
            &mut self.resolver,
        );
        let mut http_connector =
            legacy::connect::HttpConnector::new_with_resolver(
                self.resolver,
            );
        self.http_connector_params.apply(
            &mut http_connector,
        );
        http_connector
            .enforce_http(false);
        let stream = connection_establish_tcp(http_connector, self.uri.clone()).await?;
        Ok(TlsBuilder::new(
            stream,
            self.uri,
            self.uri_host,
            self.uri_scheme,
        ))
    }

    /// Build connection and proceed with socks5 proxy setup.
    pub fn socks5_proxy_setup(mut self, proxy_addr: Uri) -> Socks5ProxyBuilder {
        self.http_connector_params.apply_resolver(
            &mut self.resolver,
        );
        let mut http_connector =
            legacy::connect::HttpConnector::new_with_resolver(
                self.resolver,
            );
        self.http_connector_params.apply(
            &mut http_connector,
        );
        Socks5ProxyBuilder::new(
            proxy_addr,
            http_connector,
            self.uri,
            self.uri_host,
            self.uri_scheme,
        )
    }
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Socks5Auth {
    pub username: String,
    pub password: String,
}

impl From<async_socks5::Auth> for Socks5Auth {
    fn from(auth: async_socks5::Auth) -> Self {
        Self {
            username: auth.username,
            password: auth.password,
        }
    }
}

impl From<Socks5Auth> for async_socks5::Auth {
    fn from(auth: Socks5Auth) -> Self {
        async_socks5::Auth::new(auth.username, auth.password)
    }
}

pub struct Socks5ProxyBuilder {
    uri: Uri,
    uri_host: String,
    uri_scheme: http::uri::Scheme,
    http_connector: legacy::connect::HttpConnector<resolver::HickoryResolver>,
    proxy_addr: Uri,
    proxy_auth: Option<Socks5Auth>,
}

impl Socks5ProxyBuilder {
    fn new(
        proxy_addr: Uri,
        http_connector: legacy::connect::HttpConnector<resolver::HickoryResolver>,
        uri: Uri,
        uri_host: String,
        uri_scheme: http::uri::Scheme,
    )
        -> Self
    {
        Self {
            uri,
            uri_host,
            uri_scheme,
            http_connector,
            proxy_addr,
            proxy_auth: None,
        }
    }

    /// Configure a username + password authentication for the proxy.
    ///
    /// If `None`, no authentication is performed.
    ///
    /// Default is `None`.
    pub fn auth(mut self, proxy_auth: Option<Socks5Auth>) -> Self {
        self.proxy_auth = proxy_auth;
        self
    }

    /// Build and establish connection
    pub async fn establish(self) -> Result<Io, Error> {
        let stream =
            connection_establish_proxy(
                self.proxy_addr,
                self.proxy_auth,
                self.http_connector,
                self.uri,
                self.uri_host.clone(),
            )
            .await?;
        Ok(Io {
            protocols: Protocols {
                http1_support: true,
                http2_support: false,
            },
            uri_host: self.uri_host,
            stream: IoStream {
                kind: IoKind::Tcp(
                    IoTcp {
                        stream,
                    },
                ),
            },
        })
    }

    /// Build connection and proceed with tls setup.
    pub async fn tls_setup(mut self) -> Result<TlsBuilder, Error> {
        self.http_connector
            .enforce_http(false);
        let stream =
            connection_establish_proxy(
                self.proxy_addr,
                self.proxy_auth,
                self.http_connector,
                self.uri.clone(),
                self.uri_host.clone(),
            )
            .await?;

        Ok(TlsBuilder::new(
            stream,
            self.uri,
            self.uri_host,
            self.uri_scheme,
        ))
    }
}

pub struct TlsBuilder {
    uri: Uri,
    uri_host: String,
    uri_scheme: http::uri::Scheme,
    stream: TokioIo<TcpStream>,
}

impl TlsBuilder {
    fn new(
        stream: TokioIo<TcpStream>,
        uri: Uri,
        uri_host: String,
        uri_scheme: http::uri::Scheme,
    )
        -> Self
    {
        Self {
            uri,
            uri_host,
            uri_scheme,
            stream,
        }
    }

    /// Passes a rustls [`ClientConfig`] to configure the TLS connection
    ///
    /// The [`alpn_protocols`](ClientConfig::alpn_protocols) field is
    /// required to be empty and will be rewritten to match the enabled
    /// schemes (see
    /// [`enable_http1`](TlsBuilderConfig::enable_http1),
    /// [`enable_http2`](TlsBuilderConfig::enable_http2)) before the
    /// connector is built.
    pub fn tls_config(self, config: rustls::ClientConfig) -> Result<TlsBuilderConfig, Error> {
        if !config.alpn_protocols.is_empty() {
            Err(Error::TlsNonEmptyAlpnProtocols)
        } else {
            Ok(TlsBuilderConfig::new(
                config,
                self.stream,
                self.uri,
                self.uri_host,
                self.uri_scheme,
            ))
        }
    }

    /// Shorthand for using rustls safe defaults and native roots
    pub fn native_roots(self) -> Result<TlsBuilderConfig, Error> {
        let mut root_store = rustls::RootCertStore::empty();
        let native_certs_iter = rustls_native_certs::load_native_certs()
            .map_err(Error::TlsNativeCertsLoad)?;
        for cert in native_certs_iter {
            root_store.add(cert)
                .map_err(Error::TlsNativeCertAdd)?;
        }
        Ok(TlsBuilderConfig::new(
            rustls::ClientConfig::builder()
                .with_root_certificates(root_store)
                .with_no_client_auth(),
            self.stream,
            self.uri,
            self.uri_host,
            self.uri_scheme,
        ))
    }

    /// Shorthand for using rustls safe defaults and Mozilla roots
    pub fn webpki_roots(self) -> Result<TlsBuilderConfig, Error> {
        let mut root_store = rustls::RootCertStore::empty();
        root_store.extend(
            webpki_roots::TLS_SERVER_ROOTS
                .iter()
                .cloned(),
        );
        Ok(TlsBuilderConfig::new(
            rustls::ClientConfig::builder()
                .with_root_certificates(root_store)
                .with_no_client_auth(),
            self.stream,
            self.uri,
            self.uri_host,
            self.uri_scheme,
        ))
    }
}

pub struct TlsBuilderConfig {
    uri: Uri,
    uri_host: String,
    uri_scheme: http::uri::Scheme,
    stream: TokioIo<TcpStream>,
    tls_config: rustls::ClientConfig,
    https_only: bool,
    http1_enabled: bool,
    http2_enabled: bool,
    override_server_name: Option<String>,
}

impl TlsBuilderConfig {
    fn new(
        tls_config: rustls::ClientConfig,
        stream: TokioIo<TcpStream>,
        uri: Uri,
        uri_host: String,
        uri_scheme: http::uri::Scheme,
    )
        -> Self
    {
        Self {
            uri,
            uri_host,
            uri_scheme,
            stream,
            tls_config,
            https_only: false,
            http1_enabled: false,
            http2_enabled: false,
            override_server_name: None,
        }
    }

    /// Enforce the use of HTTPS when connecting
    ///
    /// Only URLs using the HTTPS scheme will be connectable.
    ///
    /// Default is `https_or_http`.
    pub fn https_only(mut self) -> Self {
        self.https_only = true;
        self
    }

    /// Allow both HTTPS and HTTP when connecting
    ///
    /// HTTPS URLs will be handled through rustls,
    /// HTTP URLs will be handled directly.
    ///
    /// Default is `https_or_http`.
    pub fn https_or_http(mut self) -> Self {
        self.https_only = false;
        self
    }

    /// Enable HTTP1
    ///
    /// This needs to be called explicitly, no protocol is enabled by default
    pub fn enable_http1(mut self) -> Self {
        self.http1_enabled = true;
        self.http2_enabled = false;
        self
    }

    /// Enable HTTP2
    ///
    /// This needs to be called explicitly, no protocol is enabled by default
    pub fn enable_http2(mut self) -> Self {
        self.http1_enabled = false;
        self.http2_enabled = true;
        self
    }

    /// Enable all HTTP versions
    ///
    /// For now, this enables both HTTP 1 and 2. In the future, other supported versions
    /// will be enabled as well.
    pub fn enable_all_versions(mut self) -> Self {
        self.http1_enabled = true;
        self.http2_enabled = true;
        self
    }

    /// Override server name for the TLS stack
    ///
    /// By default, for each connection the library will extract host portion
    /// of the destination URL and verify that server certificate contains
    /// this value.
    ///
    /// If this method is called, the library will instead verify that server
    /// certificate contains `override_server_name`. Domain name included in
    /// the URL will not affect certificate validation.
    pub fn with_server_name(mut self, override_server_name: String) -> Self {
        self.override_server_name = Some(override_server_name);
        self
    }

    /// Build and establish connection
    pub async fn establish(mut self) -> Result<Io, Error> {
        let mut alpn_protocols = Vec::new();
        if self.http2_enabled {
            alpn_protocols.push(b"h2".to_vec());
        }
        if self.http1_enabled {
            alpn_protocols.push(b"http/1.1".to_vec());
        }
        self.tls_config.alpn_protocols = alpn_protocols;

        if self.uri_scheme == http::uri::Scheme::HTTP && !self.https_only {
            return Ok(Io {
                protocols: Protocols {
                    http1_support: true,
                    http2_support: false,
                },
                uri_host: self.uri_host,
                stream: IoStream {
                    kind: IoKind::Tcp(
                        IoTcp {
                            stream: self.stream,
                        },
                    ),
                },
            });
        }
        if self.uri_scheme != http::uri::Scheme::HTTPS {
            return Err(Error::UriUnsupportedHttpsScheme {
                uri: self.uri,
                scheme: self.uri_scheme,
            });
        }

        let mut hostname =
            match self.override_server_name.as_deref() {
                Some(server_name) =>
                    server_name,
                None =>
                    &self.uri_host,
            };

        hostname = hostname
            .trim_start_matches('[')
            .trim_end_matches(']');

        let server_name = rustls::pki_types::ServerName::try_from(hostname)
            .map_err(|error| Error::TlsInvalidDnsName {
                hostname: hostname.to_string(),
                error,
            })?
            .to_owned();

        let connector =
            tokio_rustls::TlsConnector::from(Arc::new(self.tls_config));
        let tls = connector
            .connect(server_name, self.stream.into_inner())
            .await
            .map_err(Error::ConnectionTls)?;

        #[allow(clippy::match_like_matches_macro)]
        let h2_announced = if let Some(b"h2") = tls.get_ref().1.alpn_protocol() {
            true
        } else {
            false
        };

        Ok(Io {
            protocols: Protocols {
                http1_support: self.http1_enabled,
                http2_support: self.http2_enabled && h2_announced,
            },
            uri_host: self.uri_host,
            stream: IoStream {
                kind: IoKind::TcpTls(
                    IoTcpTls {
                        stream: TokioIo::new(tls),
                    },
                ),
            },
        })
    }
}

async fn connection_establish_tcp(
    mut http_connector: legacy::connect::HttpConnector<resolver::HickoryResolver>,
    uri: Uri,
)
    -> Result<TokioIo<TcpStream>, Error>
{
    tower_service::Service::call(&mut http_connector, uri).await
        .map_err(|error| {
            Error::Connection(Box::new(error) as Box<dyn std::error::Error + Send + Sync + 'static>)
        })
}

async fn connection_establish_proxy(
    proxy_addr: Uri,
    proxy_auth: Option<Socks5Auth>,
    mut http_connector: legacy::connect::HttpConnector<resolver::HickoryResolver>,
    uri: Uri,
    uri_host: String,
)
    -> Result<TokioIo<TcpStream>, Error>
{
    let port = match uri.port() {
        Some(port) =>
            port.as_u16(),
        None =>
            if uri.scheme() == Some(&http::uri::Scheme::HTTPS) {
                443
            } else {
                80
            },
    };
    let target_addr =
        async_socks5::AddrKind::Domain(uri_host, port);

    let tokio_io_stream =
        tower_service::Service::call(
            &mut http_connector,
            proxy_addr,
        )
        .await
        .map_err(|error| {
            Error::ConnectionToSocks5(Box::new(error) as Box<dyn std::error::Error + Send + Sync + 'static>)
        })?;
    let stream = tokio_io_stream
        .into_inner();

    let mut buf_stream =
        tokio::io::BufStream::new(stream);
    let _addr_kind =
        async_socks5::connect(
            &mut buf_stream,
            target_addr,
            proxy_auth.map(Into::into),
        )
        .await
        .map_err(Error::ConnectionViaSocks5)?;

    Ok(TokioIo::new(buf_stream.into_inner()))
}