eggfetch-core 0.3.0

Async-first Rust HTTP client engine (tokio + hyper) with connection pooling, phase-aware timeouts, TLS, proxies, and compression
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
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
//! SOCKS5 proxy handshake and tunnel establishment.
//!
//! Implements the SOCKS5 protocol (RFC 1928) for proxy connections,
//! including username/password authentication (RFC 1929). The
//! implementation is bounded to the subset required for HTTPX 0.28.1
//! parity: the pinned HTTPX/httpcore stack sends hostname destinations to the
//! proxy for both `socks5://` and `socks5h://`.
//!
//! # Protocol flow
//!
//! 1. TCP connect to SOCKS5 proxy
//! 2. Method negotiation (no-auth or username/password)
//! 3. Optional username/password subnegotiation
//! 4. CONNECT command with destination address
//! 5. Parse reply — tunnel established

use crate::error::{Error, Result};
use crate::proxy::{ProxyAuth, ProxyConfig};
use crate::timeout::TimeoutPhase;
use crate::transport_hints::ResolvedTarget;

/// Internal cache identity for one SOCKS route. The type deliberately does
/// not implement `Debug` or `Display`: credentials remain memory-only key
/// material and can never be emitted by route diagnostics.
///
/// Connection-scoped: proxy scheme/host/port, auth, pinned proxy peer,
/// pinned ultimate target. Origin TLS, HTTP version/ALPN, and
/// connect-phase timeouts are immutable at `ClientInner` scope (the
/// connector is built from client config), and proxy-only headers have no
/// SOCKS leg, so none of those participate. Request-scoped state
/// (total/read/write/pool deadlines, retry/redirect, body, trace/failure
/// context, decompression limits) is never represented.
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct SocksRouteKey {
    scheme: String,
    host: String,
    port: u16,
    auth: Option<(String, String)>,
    proxy_addresses: Option<Vec<std::net::SocketAddr>>,
    target_addresses: Option<Vec<std::net::SocketAddr>>,
}

impl SocksRouteKey {
    pub(crate) fn from_proxy(proxy: &ProxyConfig, target: Option<&ResolvedTarget>) -> Result<Self> {
        let auth = proxy.auth().map(|auth| match auth {
            ProxyAuth::Basic { username, password } => (username.clone(), password.clone()),
        });
        // Fail closed on missing host: defaulting to `""` would alias
        // distinct misconfigured proxies under one pool key.
        let host = proxy
            .host()
            .ok_or_else(|| Error::Connect("SOCKS proxy URI has no host".into()))?;
        Ok(Self {
            scheme: proxy.scheme().to_owned(),
            host: host.to_owned(),
            port: proxy.port()?,
            auth,
            proxy_addresses: proxy
                .resolved_addresses()
                .map(<[std::net::SocketAddr]>::to_vec),
            target_addresses: target.map(|target| target.addresses().to_vec()),
        })
    }
}

/// SOCKS5 protocol version.
const SOCKS5_VERSION: u8 = 0x05;

/// No authentication method.
const SOCKS5_METHOD_NO_AUTH: u8 = 0x00;

/// Username/password authentication method.
const SOCKS5_METHOD_USERNAME_PASSWORD: u8 = 0x02;

/// No acceptable methods.
const SOCKS5_METHOD_NO_ACCEPTABLE: u8 = 0xFF;

/// Username/password subnegotiation version.
const SOCKS5_SUBNEG_VERSION: u8 = 0x01;

/// CONNECT command.
const SOCKS5_CMD_CONNECT: u8 = 0x01;

/// Address type: IPv4.
const SOCKS5_ATYP_IPV4: u8 = 0x01;

/// Address type: domain name.
const SOCKS5_ATYP_DOMAIN: u8 = 0x03;

/// Address type: IPv6.
const SOCKS5_ATYP_IPV6: u8 = 0x04;

/// Reply code: success.
const SOCKS5_REP_SUCCESS: u8 = 0x00;

/// Maximum domain name length for SOCKS5.
const MAX_SOCKS5_DOMAIN_LEN: usize = 255;

/// Maximum username/password length for SOCKS5 (RFC 1929).
const MAX_SOCKS5_CREDENTIAL_LEN: usize = 255;

/// Classifies a failed SOCKS5 target attempt without changing the public
/// error taxonomy.
///
/// Only reply codes that identify the requested destination as unreachable or
/// refused are safe candidate-specific failures. Authentication, method,
/// protocol, and malformed-response failures belong to the proxy leg and
/// must stop the address sequence rather than being retried against another
/// target.
enum TargetAttemptError {
    /// The proxy explicitly reported a destination-specific failure.
    Retryable(Error),
    /// The failure is not safe to attribute to this destination alone.
    Terminal(Error),
}

impl TargetAttemptError {
    fn terminal(error: Error) -> Self {
        Self::Terminal(error)
    }

    fn into_error(self) -> Error {
        match self {
            Self::Retryable(error) | Self::Terminal(error) => error,
        }
    }
}

/// Perform a SOCKS5 handshake and establish a tunnel to the destination.
///
/// Returns a `BufReader<TcpStream>` connected through the SOCKS5 proxy,
/// ready for HTTP or TLS communication with the origin.
///
/// # Arguments
///
/// * `proxy_config` — SOCKS5 proxy configuration (host, port, auth)
/// * `dest_host` — destination hostname or IP
/// * `dest_port` — destination port
/// * `remote_dns` — whether to send the domain name to the proxy for remote
///   DNS resolution. The compatibility facade passes `true` for both SOCKS
///   schemes because that is the HTTPX 0.28.1 behavior.
/// * `remaining_total` — optional timeout for the entire handshake
///
/// # Errors
///
/// Returns an error if:
/// - TCP connection to the proxy fails
/// - Method negotiation fails
/// - Authentication fails
/// - CONNECT command is rejected
/// - Proxy response is malformed
/// - Timeout expires
pub(crate) async fn socks5_handshake(
    proxy_config: &ProxyConfig,
    dest_host: &str,
    dest_port: u16,
    remote_dns: bool,
    remaining_total: Option<std::time::Duration>,
    pinned_targets: Option<&[std::net::SocketAddr]>,
) -> Result<tokio::net::TcpStream> {
    // `Instant::add` panics on overflow; fail closed with an immediately-expired
    // deadline instead of dropping the deadline (unbounded handshake).
    let now = std::time::Instant::now();
    let deadline = remaining_total.map(|duration| now.checked_add(duration).unwrap_or(now));

    if let Some(targets) = pinned_targets {
        if targets.is_empty() {
            return Err(Error::Connect("empty SOCKS target set".into()));
        }
        let mut last_err = None;
        for (index, target) in targets.iter().copied().enumerate() {
            let mut stream = establish_socks_proxy_connection(proxy_config, deadline).await?;
            match send_connect_ip(&mut stream, target.ip(), target.port(), deadline).await {
                Ok(()) => return Ok(stream),
                Err(TargetAttemptError::Retryable(error)) if index + 1 < targets.len() => {
                    last_err = Some(error);
                }
                Err(error) => return Err(error.into_error()),
            }
        }
        return Err(last_err.unwrap_or_else(|| Error::Connect("empty SOCKS target set".into())));
    }

    // Local-DNS path with multiple resolved addresses: try each destination
    // address with a fresh proxy connection; the first successful CONNECT
    // wins. A failed CONNECT may leave the proxy connection unusable, so
    // retries use a new connection rather than reusing the failed stream.
    // Destination-specific rejections (0x03/0x04/0x05) advance to the next
    // address; proxy-leg failures (TCP, method, auth, malformed) stop the
    // sequence immediately, matching the pinned-target path.
    if !remote_dns && dest_host.parse::<std::net::IpAddr>().is_err() {
        if let Ok(addrs) = resolve_dest_ips(dest_host, deadline).await {
            if addrs.len() > 1 {
                let mut last_err: Option<Error> = None;
                for (index, ip) in addrs.iter().copied().enumerate() {
                    match handshake_with_ip(proxy_config, ip, dest_port, deadline).await {
                        Ok(stream) => return Ok(stream),
                        Err(TargetAttemptError::Retryable(error)) if index + 1 < addrs.len() => {
                            last_err = Some(error);
                        }
                        Err(error) => return Err(error.into_error()),
                    }
                }
                return Err(last_err.unwrap_or_else(|| {
                    Error::Connect(format!(
                        "DNS resolution failed for SOCKS destination {dest_host}"
                    ))
                }));
            }
            // Zero or one address: fall through to the single-attempt path
            // (which re-resolves; cheap and keeps the code path unified).
        }
    }

    let mut stream = establish_socks_proxy_connection(proxy_config, deadline).await?;

    // Phase 4: CONNECT command.
    send_connect(&mut stream, dest_host, dest_port, remote_dns, deadline).await?;

    Ok(stream)
}

/// Establish a SOCKS5 proxy connection through method negotiation and auth.
///
/// Returns a stream ready for the CONNECT command (phases 1-3).
async fn establish_socks_proxy_connection(
    proxy_config: &ProxyConfig,
    deadline: Option<std::time::Instant>,
) -> Result<tokio::net::TcpStream> {
    let proxy_host = proxy_config
        .host()
        .ok_or_else(|| Error::ProxyConnect("SOCKS proxy URI has no host".into()))?
        .to_owned();
    let proxy_port = proxy_config.port()?;

    // Phase 1: TCP connect to proxy.
    let connect_future = async {
        let addresses: Vec<std::net::SocketAddr> =
            if let Some(addresses) = proxy_config.resolved_addresses() {
                addresses.to_vec()
            } else {
                tokio::net::lookup_host(format!("{proxy_host}:{proxy_port}"))
                    .await
                    .map_err(|e| {
                        Error::ProxyConnect(format!(
                            "DNS resolution failed for SOCKS5 proxy {proxy_host}:{proxy_port}: {e}"
                        ))
                    })?
                    .collect()
            };
        let mut last_error = None;
        let mut connected = None;
        for address in addresses {
            match tokio::net::TcpStream::connect(address).await {
                Ok(stream) => {
                    connected = Some(stream);
                    break;
                }
                Err(error) => last_error = Some(error),
            }
        }
        let stream = connected.ok_or_else(|| {
            Error::ProxyConnect(format!(
                "TCP connect to SOCKS5 proxy {proxy_host}:{proxy_port} failed: {}",
                last_error.map_or_else(
                    || "no addresses resolved".to_owned(),
                    |error| error.to_string()
                )
            ))
        })?;
        stream
            .set_nodelay(true)
            .map_err(|e| Error::ProxyConnect(format!("failed to set nodelay: {e}")))?;
        Ok::<_, Error>(stream)
    };

    let mut stream = match deadline {
        Some(deadline) => {
            let dur = deadline.saturating_duration_since(std::time::Instant::now());
            match tokio::time::timeout(dur, connect_future).await {
                Ok(Ok(s)) => s,
                Ok(Err(e)) => return Err(e),
                Err(_) => {
                    return Err(Error::Timeout {
                        phase: TimeoutPhase::ProxyConnect,
                        elapsed: dur,
                    });
                }
            }
        }
        None => connect_future.await?,
    };

    // Phase 2: Method negotiation.
    let selected_method = negotiate_method(&mut stream, proxy_config.auth(), deadline).await?;

    // Phase 3: Username/password authentication (if configured).
    if selected_method == SOCKS5_METHOD_USERNAME_PASSWORD {
        let auth = proxy_config.auth().ok_or_else(|| {
            Error::ProxyConnect(
                "SOCKS5 proxy selected username/password but no credentials were configured".into(),
            )
        })?;
        authenticate(&mut stream, auth, deadline).await?;
    }

    Ok(stream)
}

/// Full handshake against one pre-resolved destination IP (fresh proxy
/// connection + CONNECT with that IP).
async fn handshake_with_ip(
    proxy_config: &ProxyConfig,
    dest_ip: std::net::IpAddr,
    dest_port: u16,
    deadline: Option<std::time::Instant>,
) -> std::result::Result<tokio::net::TcpStream, TargetAttemptError> {
    // Proxy-leg failures (TCP, method negotiation, auth) are not
    // destination-specific: retrying them against the next resolved IP
    // only repeats the same failing handshake, so they are terminal.
    let mut stream = establish_socks_proxy_connection(proxy_config, deadline)
        .await
        .map_err(TargetAttemptError::terminal)?;
    send_connect_ip(&mut stream, dest_ip, dest_port, deadline).await?;
    Ok(stream)
}

/// Stream returned by the SOCKS connector after the tunnel is established.
pub(crate) enum SocksStream {
    /// Plain HTTP tunnel.
    Tcp(tokio::net::TcpStream),
    /// Origin TLS layered over the SOCKS tunnel.
    Tls(Box<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>),
}

impl tokio::io::AsyncRead for SocksStream {
    fn poll_read(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        match &mut *self {
            Self::Tcp(stream) => std::pin::Pin::new(stream).poll_read(cx, buf),
            Self::Tls(stream) => std::pin::Pin::new(stream).poll_read(cx, buf),
        }
    }
}

impl tokio::io::AsyncWrite for SocksStream {
    fn poll_write(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        bytes: &[u8],
    ) -> std::task::Poll<std::io::Result<usize>> {
        match &mut *self {
            Self::Tcp(stream) => std::pin::Pin::new(stream).poll_write(cx, bytes),
            Self::Tls(stream) => std::pin::Pin::new(stream).poll_write(cx, bytes),
        }
    }

    fn poll_flush(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        match &mut *self {
            Self::Tcp(stream) => std::pin::Pin::new(stream).poll_flush(cx),
            Self::Tls(stream) => std::pin::Pin::new(stream).poll_flush(cx),
        }
    }

    fn poll_shutdown(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        match &mut *self {
            Self::Tcp(stream) => std::pin::Pin::new(stream).poll_shutdown(cx),
            Self::Tls(stream) => std::pin::Pin::new(stream).poll_shutdown(cx),
        }
    }
}

impl hyper_util::client::legacy::connect::Connection for SocksStream {
    fn connected(&self) -> hyper_util::client::legacy::connect::Connected {
        let mut connected = hyper_util::client::legacy::connect::Connected::new();
        if let Self::Tls(tls) = self {
            if super::negotiated_http2(tls.get_ref().1.alpn_protocol()) {
                connected = connected.negotiated_h2();
            }
        }
        connected
    }
}

/// Hyper connector that establishes one SOCKS5 tunnel per origin connection.
///
/// The connector owns only connection-scoped policy (proxy endpoint/auth,
/// origin TLS built from immutable client config, pinned target). Its
/// `timeout` handshake budget is always `None` for cached routes: the
/// current request's total budget is enforced at the outer dispatch
/// boundary and by the `ConnectTimeout` wrapper, never captured here.
/// Request trace observers, failure contexts, bodies, and retry/redirect
/// state are never retained.
#[derive(Clone)]
pub(crate) struct SocksConnector {
    proxy: ProxyConfig,
    tls: Option<std::sync::Arc<tokio_rustls::TlsConnector>>,
    timeout: Option<std::time::Duration>,
    target: Option<std::sync::Arc<[std::net::SocketAddr]>>,
}

impl SocksConnector {
    pub(crate) fn new(
        proxy: ProxyConfig,
        tls: Option<tokio_rustls::TlsConnector>,
        timeout: Option<std::time::Duration>,
        target: Option<&ResolvedTarget>,
    ) -> Self {
        Self {
            proxy,
            tls: tls.map(std::sync::Arc::new),
            timeout,
            target: target.map(|target| target.addresses().to_vec().into()),
        }
    }
}

impl tower_service::Service<http::Uri> for SocksConnector {
    type Response = hyper_util::rt::TokioIo<SocksStream>;
    type Error = Box<dyn std::error::Error + Send + Sync>;
    type Future = std::pin::Pin<
        Box<
            dyn std::future::Future<Output = std::result::Result<Self::Response, Self::Error>>
                + Send,
        >,
    >;

    fn poll_ready(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::result::Result<(), Self::Error>> {
        std::task::Poll::Ready(Ok(()))
    }

    fn call(&mut self, dst: http::Uri) -> Self::Future {
        let proxy = self.proxy.clone();
        let tls = self.tls.clone();
        let timeout = self.timeout;
        let target = self.target.clone();
        Box::pin(async move {
            let host = dst.host().ok_or_else(|| -> Self::Error {
                Error::InvalidUrl("SOCKS destination has no host".into()).into()
            })?;
            let port = dst
                .port_u16()
                .or_else(|| (dst.scheme_str() == Some("https")).then_some(443))
                .unwrap_or(80);
            let stream = socks5_handshake(
                &proxy,
                host,
                port,
                proxy.socks_remote_dns(),
                timeout,
                target.as_deref(),
            )
            .await
            .map_err(|e| -> Self::Error { e.into() })?;
            if dst.scheme_str() != Some("https") {
                return Ok(hyper_util::rt::TokioIo::new(SocksStream::Tcp(stream)));
            }
            let connector = tls.ok_or_else(|| -> Self::Error {
                Error::Tls("SOCKS HTTPS requires a TLS connector".into()).into()
            })?;
            let name = crate::transport::direct_connector::tls_server_name(host).map_err(
                |e| -> Self::Error {
                    Error::Tls(format!("invalid SOCKS TLS server name '{host}': {e}")).into()
                },
            )?;
            let stream = connector
                .connect(name, stream)
                .await
                .map_err(|e| -> Self::Error {
                    Error::Tls(format!("TLS handshake through SOCKS tunnel failed: {e}")).into()
                })?;
            Ok(hyper_util::rt::TokioIo::new(SocksStream::Tls(Box::new(
                stream,
            ))))
        })
    }
}

/// Negotiate the authentication method with the SOCKS5 proxy.
///
/// Sends the list of supported methods and reads the proxy's selection.
async fn negotiate_method(
    stream: &mut tokio::net::TcpStream,
    auth: Option<&ProxyAuth>,
    deadline: Option<std::time::Instant>,
) -> Result<u8> {
    // httpcore offers exactly one method: credentials select RFC 1929,
    // otherwise the client offers no authentication. This is intentionally
    // narrower than the set of methods the protocol could support.
    let expected_method = if auth.is_some() {
        SOCKS5_METHOD_USERNAME_PASSWORD
    } else {
        SOCKS5_METHOD_NO_AUTH
    };
    let methods = vec![expected_method];

    // Send: version(1) + nmethods(1) + methods(nmethods)
    let mut greeting = Vec::with_capacity(2 + methods.len());
    greeting.push(SOCKS5_VERSION);
    greeting.push(
        u8::try_from(methods.len())
            .map_err(|_| Error::ProxyConnect("too many SOCKS5 methods".into()))?,
    );
    greeting.extend_from_slice(&methods);

    write_all_timeout(stream, &greeting, deadline, "SOCKS5 greeting").await?;

    // Read: version(1) + method(1)
    let mut response = [0u8; 2];
    read_exact_timeout(stream, &mut response, deadline, "SOCKS5 method response").await?;

    if response[0] != SOCKS5_VERSION {
        return Err(Error::ProxyConnect(format!(
            "SOCKS5 proxy returned invalid version: {}",
            response[0]
        )));
    }

    match response[1] {
        SOCKS5_METHOD_NO_ACCEPTABLE => Err(Error::ProxyConnect(
            "SOCKS5 proxy rejected all authentication methods".into(),
        )),
        selected if selected == expected_method => Ok(selected),
        other => Err(Error::ProxyConnect(format!(
            "SOCKS5 proxy selected method {other}, but the client offered {expected_method}"
        ))),
    }
}

/// Perform username/password subnegotiation (RFC 1929).
async fn authenticate(
    stream: &mut tokio::net::TcpStream,
    auth: &ProxyAuth,
    deadline: Option<std::time::Instant>,
) -> Result<()> {
    let (username, password) = match auth {
        ProxyAuth::Basic { username, password } => (username.as_bytes(), password.as_bytes()),
    };

    if username.len() > MAX_SOCKS5_CREDENTIAL_LEN {
        return Err(Error::ProxyConnect(format!(
            "SOCKS5 username exceeds maximum length of {MAX_SOCKS5_CREDENTIAL_LEN}"
        )));
    }
    if password.len() > MAX_SOCKS5_CREDENTIAL_LEN {
        return Err(Error::ProxyConnect(format!(
            "SOCKS5 password exceeds maximum length of {MAX_SOCKS5_CREDENTIAL_LEN}"
        )));
    }

    // Send: version(1) + ulen(1) + username(ulen) + plen(1) + password(plen)
    let mut auth_request = Vec::with_capacity(3 + username.len() + password.len());
    auth_request.push(SOCKS5_SUBNEG_VERSION);
    auth_request.push(
        u8::try_from(username.len())
            .map_err(|_| Error::ProxyConnect("SOCKS5 username too long".into()))?,
    );
    auth_request.extend_from_slice(username);
    auth_request.push(
        u8::try_from(password.len())
            .map_err(|_| Error::ProxyConnect("SOCKS5 password too long".into()))?,
    );
    auth_request.extend_from_slice(password);

    write_all_timeout(stream, &auth_request, deadline, "SOCKS5 auth request").await?;

    // Read: version(1) + status(1)
    let mut auth_response = [0u8; 2];
    read_exact_timeout(stream, &mut auth_response, deadline, "SOCKS5 auth response").await?;

    if auth_response[0] != SOCKS5_SUBNEG_VERSION {
        return Err(Error::ProxyConnect(format!(
            "SOCKS5 auth returned invalid subnegotiation version: {}",
            auth_response[0]
        )));
    }

    if auth_response[1] != 0x00 {
        return Err(Error::ProxyConnect(
            "SOCKS5 proxy rejected authentication credentials".into(),
        ));
    }

    Ok(())
}

/// Send a CONNECT command and parse the reply.
///
/// Establishes a tunnel to the specified destination through the SOCKS5
/// proxy. Uses the address type appropriate for the DNS mode:
/// - `remote_dns=true`: sends domain name (`ATYP_DOMAIN`)
/// - `remote_dns=false`: resolves locally and sends IP (`ATYP_IPV4`/`ATYP_IPV6`)
async fn send_connect(
    stream: &mut tokio::net::TcpStream,
    dest_host: &str,
    dest_port: u16,
    remote_dns: bool,
    deadline: Option<std::time::Instant>,
) -> Result<()> {
    // Build the CONNECT request.
    let mut request = Vec::with_capacity(64);
    request.push(SOCKS5_VERSION);
    request.push(SOCKS5_CMD_CONNECT);
    request.push(0x00); // reserved

    if let Ok(ip) = dest_host.parse::<std::net::IpAddr>() {
        match ip {
            std::net::IpAddr::V4(ip) => {
                request.push(SOCKS5_ATYP_IPV4);
                request.extend_from_slice(&ip.octets());
            }
            std::net::IpAddr::V6(ip) => {
                request.push(SOCKS5_ATYP_IPV6);
                request.extend_from_slice(&ip.octets());
            }
        }
    } else if remote_dns {
        // Send domain name to proxy for remote resolution.
        let host_bytes = dest_host.as_bytes();
        if host_bytes.len() > MAX_SOCKS5_DOMAIN_LEN {
            return Err(Error::ProxyConnect(format!(
                "SOCKS5 destination domain exceeds maximum length of {MAX_SOCKS5_DOMAIN_LEN}"
            )));
        }
        request.push(SOCKS5_ATYP_DOMAIN);
        request.push(
            u8::try_from(host_bytes.len())
                .map_err(|_| Error::ProxyConnect("SOCKS5 domain name too long".into()))?,
        );
        request.extend_from_slice(host_bytes);
    } else {
        // Resolve locally and send IP address.
        match resolve_dest_ip(dest_host, deadline).await? {
            std::net::IpAddr::V4(ip) => {
                request.push(SOCKS5_ATYP_IPV4);
                request.extend_from_slice(&ip.octets());
            }
            std::net::IpAddr::V6(ip) => {
                request.push(SOCKS5_ATYP_IPV6);
                request.extend_from_slice(&ip.octets());
            }
        }
    }

    request.extend_from_slice(&dest_port.to_be_bytes());

    write_all_timeout(stream, &request, deadline, "SOCKS5 CONNECT").await?;

    // Parse the reply.
    parse_connect_reply(stream, deadline).await
}

/// Send a CONNECT command for a pre-resolved destination IP.
async fn send_connect_ip(
    stream: &mut tokio::net::TcpStream,
    dest_ip: std::net::IpAddr,
    dest_port: u16,
    deadline: Option<std::time::Instant>,
) -> std::result::Result<(), TargetAttemptError> {
    let mut request = Vec::with_capacity(64);
    request.push(SOCKS5_VERSION);
    request.push(SOCKS5_CMD_CONNECT);
    request.push(0x00); // reserved
    match dest_ip {
        std::net::IpAddr::V4(ip) => {
            request.push(SOCKS5_ATYP_IPV4);
            request.extend_from_slice(&ip.octets());
        }
        std::net::IpAddr::V6(ip) => {
            request.push(SOCKS5_ATYP_IPV6);
            request.extend_from_slice(&ip.octets());
        }
    }
    request.extend_from_slice(&dest_port.to_be_bytes());

    write_all_timeout(stream, &request, deadline, "SOCKS5 CONNECT")
        .await
        .map_err(TargetAttemptError::terminal)?;

    // Parse the reply.
    parse_connect_reply_for_target(stream, deadline).await
}

/// Resolve a destination host to all IP addresses.
///
/// Uses Tokio's DNS resolver. Returns both IPv4 and IPv6 in resolver order.
async fn resolve_dest_ips(
    host: &str,
    deadline: Option<std::time::Instant>,
) -> Result<Vec<std::net::IpAddr>> {
    use tokio::net::lookup_host;

    // Try parsing as an IP literal first.
    if let Ok(ip) = host.parse::<std::net::Ipv4Addr>() {
        return Ok(vec![std::net::IpAddr::V4(ip)]);
    }
    if let Ok(ip) = host.parse::<std::net::Ipv6Addr>() {
        return Ok(vec![std::net::IpAddr::V6(ip)]);
    }

    // DNS resolution.
    let lookup = lookup_host(format!("{host}:0"));
    let result = match deadline {
        Some(deadline) => {
            let dur = deadline.saturating_duration_since(std::time::Instant::now());
            tokio::time::timeout(dur, lookup)
                .await
                .map_err(|_| Error::Timeout {
                    phase: TimeoutPhase::ProxyConnect,
                    elapsed: dur,
                })?
        }
        None => lookup.await,
    };
    // Preserve the DNS root cause instead of collapsing to an empty vec.
    let addrs: Vec<std::net::IpAddr> = result
        .map(|addrs| addrs.map(|a| a.ip()).collect())
        .map_err(|e| {
            Error::Connect(format!(
                "DNS resolution failed for SOCKS destination {host}: {e}"
            ))
        })?;

    if addrs.is_empty() {
        // Never redirect an unresolved destination to loopback.
        return Err(Error::Connect(format!(
            "DNS resolution failed for SOCKS destination {host}"
        )));
    }
    Ok(addrs)
}

/// Resolve a destination host to an IP address.
///
/// Uses Tokio's DNS resolver. Returns the first resolved address; callers
/// that need multi-homed fallback should use [`resolve_dest_ips`].
async fn resolve_dest_ip(
    host: &str,
    deadline: Option<std::time::Instant>,
) -> Result<std::net::IpAddr> {
    let addrs = resolve_dest_ips(host, deadline).await?;
    addrs.into_iter().next().ok_or_else(|| {
        Error::Connect(format!(
            "DNS resolution failed for SOCKS destination {host}"
        ))
    })
}

/// Parse the SOCKS5 CONNECT reply from the proxy.
///
/// Validates version, reply code, and bound address. Returns an error
/// for any non-success reply.
async fn parse_connect_reply(
    stream: &mut tokio::net::TcpStream,
    deadline: Option<std::time::Instant>,
) -> Result<()> {
    parse_connect_reply_for_target(stream, deadline)
        .await
        .map_err(TargetAttemptError::into_error)
}

/// Parse a SOCKS5 CONNECT reply while preserving candidate-specific failure
/// evidence for pinned target fallback.
async fn parse_connect_reply_for_target(
    stream: &mut tokio::net::TcpStream,
    deadline: Option<std::time::Instant>,
) -> std::result::Result<(), TargetAttemptError> {
    // Read: version(1) + rep(1) + rsv(1) + atyp(1)
    let mut header = [0u8; 4];
    read_exact_timeout(stream, &mut header, deadline, "SOCKS5 CONNECT reply")
        .await
        .map_err(TargetAttemptError::terminal)?;

    if header[0] != SOCKS5_VERSION {
        return Err(TargetAttemptError::Terminal(Error::ProxyConnect(format!(
            "SOCKS5 reply has invalid version: {}",
            header[0]
        ))));
    }

    if header[1] != SOCKS5_REP_SUCCESS {
        let (retryable, msg) = match header[1] {
            0x01 => (false, "general SOCKS server failure"),
            0x02 => (false, "connection not allowed by ruleset"),
            0x03 => (true, "network unreachable"),
            0x04 => (true, "host unreachable"),
            0x05 => (true, "connection refused"),
            0x06 => (false, "TTL expired"),
            0x07 => (false, "command not supported"),
            0x08 => (false, "address type not supported"),
            code => {
                return Err(TargetAttemptError::Terminal(Error::ProxyConnect(format!(
                    "SOCKS5 CONNECT failed with unknown reply code: {code}"
                ))));
            }
        };
        let error = Error::ProxyConnect(format!("SOCKS5 CONNECT failed: {msg}"));
        return Err(if retryable {
            TargetAttemptError::Retryable(error)
        } else {
            TargetAttemptError::Terminal(error)
        });
    }

    // Read the bound address (variable length based on address type).
    match header[3] {
        SOCKS5_ATYP_IPV4 => {
            let mut addr = [0u8; 4 + 2]; // IPv4 + port
            read_exact_timeout(stream, &mut addr, deadline, "SOCKS5 bound IPv4 address")
                .await
                .map_err(TargetAttemptError::terminal)?;
        }
        SOCKS5_ATYP_IPV6 => {
            let mut addr = [0u8; 16 + 2]; // IPv6 + port
            read_exact_timeout(stream, &mut addr, deadline, "SOCKS5 bound IPv6 address")
                .await
                .map_err(TargetAttemptError::terminal)?;
        }
        SOCKS5_ATYP_DOMAIN => {
            let mut domain_len = [0u8; 1];
            read_exact_timeout(
                stream,
                &mut domain_len,
                deadline,
                "SOCKS5 bound domain length",
            )
            .await
            .map_err(TargetAttemptError::terminal)?;
            let len = domain_len[0] as usize;
            let mut domain_and_port = vec![0u8; len + 2]; // domain + port
            read_exact_timeout(
                stream,
                &mut domain_and_port,
                deadline,
                "SOCKS5 bound domain address",
            )
            .await
            .map_err(TargetAttemptError::terminal)?;
        }
        other => {
            return Err(TargetAttemptError::Terminal(Error::MalformedProxyResponse(
                format!("SOCKS5 reply has unknown address type: {other}"),
            )));
        }
    }

    Ok(())
}

/// Write all bytes with an optional timeout.
///
/// All SOCKS5 stages (TCP connect, method negotiation, auth, CONNECT
/// command) intentionally report [`TimeoutPhase::ProxyConnect`]: they are
/// all part of proxy-connection establishment, and splitting them into
/// dedicated phases would churn the public [`TimeoutPhase`] enum plus its
/// exhaustive matches. The per-stage `phase` label is still carried in
/// non-timeout errors (e.g. `"{phase} write failed: ..."`).
async fn write_all_timeout(
    stream: &mut tokio::net::TcpStream,
    data: &[u8],
    deadline: Option<std::time::Instant>,
    phase: &str,
) -> Result<()> {
    let write_result: std::result::Result<(), std::io::Error> = match deadline {
        Some(deadline) => {
            let dur = deadline.saturating_duration_since(std::time::Instant::now());
            let fut = tokio::io::AsyncWriteExt::write_all(stream, data);
            match tokio::time::timeout(dur, fut).await {
                Ok(r) => r,
                Err(_) => {
                    return Err(Error::Timeout {
                        phase: TimeoutPhase::ProxyConnect,
                        elapsed: dur,
                    });
                }
            }
        }
        None => tokio::io::AsyncWriteExt::write_all(stream, data).await,
    };

    write_result.map_err(|e| Error::ProxyConnect(format!("{phase} write failed: {e}")))
}

/// Read exact bytes with an optional timeout.
///
/// Like [`write_all_timeout`], timeout errors intentionally share
/// [`TimeoutPhase::ProxyConnect`] across all SOCKS5 stages; the `phase`
/// label is preserved in non-timeout errors.
async fn read_exact_timeout(
    stream: &mut tokio::net::TcpStream,
    buf: &mut [u8],
    deadline: Option<std::time::Instant>,
    phase: &str,
) -> Result<()> {
    let read_result: std::result::Result<usize, std::io::Error> = match deadline {
        Some(deadline) => {
            let dur = deadline.saturating_duration_since(std::time::Instant::now());
            let fut = tokio::io::AsyncReadExt::read_exact(stream, buf);
            match tokio::time::timeout(dur, fut).await {
                Ok(r) => r,
                Err(_) => {
                    return Err(Error::Timeout {
                        phase: TimeoutPhase::ProxyConnect,
                        elapsed: dur,
                    });
                }
            }
        }
        None => tokio::io::AsyncReadExt::read_exact(stream, buf).await,
    };

    read_result.map(|_| ()).map_err(|e| match e.kind() {
        std::io::ErrorKind::UnexpectedEof => {
            Error::MalformedProxyResponse(format!("{phase}: connection closed prematurely"))
        }
        _ => Error::ProxyConnect(format!("{phase} read failed: {e}")),
    })
}

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

    #[test]
    fn socks5_method_constants() {
        assert_eq!(SOCKS5_VERSION, 0x05);
        assert_eq!(SOCKS5_METHOD_NO_AUTH, 0x00);
        assert_eq!(SOCKS5_METHOD_USERNAME_PASSWORD, 0x02);
        assert_eq!(SOCKS5_METHOD_NO_ACCEPTABLE, 0xFF);
    }

    #[test]
    fn socks5_reply_constants() {
        assert_eq!(SOCKS5_REP_SUCCESS, 0x00);
        assert_eq!(SOCKS5_ATYP_IPV4, 0x01);
        assert_eq!(SOCKS5_ATYP_DOMAIN, 0x03);
        assert_eq!(SOCKS5_ATYP_IPV6, 0x04);
    }

    #[test]
    fn max_domain_len() {
        assert_eq!(MAX_SOCKS5_DOMAIN_LEN, 255);
    }

    #[test]
    fn socks_route_key_compatibility_matrix() {
        use crate::proxy::Proxy;
        use crate::transport_hints::ResolvedTarget;
        // Connection-scoped: scheme/host/port, auth, pinned proxy peer,
        // pinned target. Origin TLS, HTTP version, and connect-phase
        // timeouts are immutable at `ClientInner` scope for SOCKS (the
        // connector is built from client config; its handshake timeout is
        // `None` so the outer dispatch total plus `ConnectTimeout` apply),
        // and proxy-only headers have no SOCKS leg, so none of those
        // appear in the key. Request-scoped (never in key): total/read/
        // write/pool deadlines, retry/redirect, body, cookies/auth headers,
        // decompression limits, trace/failure context.
        // Keys intentionally lack `Debug`/`Display` (credential material),
        // so compare with `==`/`!=` rather than `assert_eq!`/`assert_ne!`.
        let base = Proxy::all("socks5://proxy.example:1080").unwrap();
        let key_a = SocksRouteKey::from_proxy(&base.config(), None).unwrap();
        let key_b = SocksRouteKey::from_proxy(&base.config(), None).unwrap();
        assert!(key_a == key_b, "same SOCKS policy must reuse");

        // Table-driven connection-affecting mutations: each must fragment.
        let cases: Vec<(&str, Proxy)> = vec![
            (
                "auth change must fragment identity",
                Proxy::all("socks5://user:pass@proxy.example:1080").unwrap(),
            ),
            (
                "endpoint change must fragment identity",
                Proxy::all("socks5://other.example:1080").unwrap(),
            ),
            (
                "scheme change must fragment identity",
                Proxy::all("socks5h://proxy.example:1080").unwrap(),
            ),
            (
                "port change must fragment identity",
                Proxy::all("socks5://proxy.example:1081").unwrap(),
            ),
            (
                "pinned proxy peer must fragment identity",
                Proxy::all("socks5://proxy.example:1080")
                    .unwrap()
                    .resolved_addresses(["127.0.0.1:1080".parse().unwrap()])
                    .unwrap(),
            ),
        ];
        for (message, proxy) in cases {
            assert!(
                key_a != SocksRouteKey::from_proxy(&proxy.config(), None).unwrap(),
                "{message}"
            );
        }

        // Pinned ultimate target fragments identity; unpinned reuses.
        let target_a =
            ResolvedTarget::new(["127.0.0.1:80".parse::<std::net::SocketAddr>().unwrap()]).unwrap();
        let target_b =
            ResolvedTarget::new(["127.0.0.1:81".parse::<std::net::SocketAddr>().unwrap()]).unwrap();
        assert!(
            SocksRouteKey::from_proxy(&base.config(), Some(&target_a)).unwrap()
                != SocksRouteKey::from_proxy(&base.config(), Some(&target_b)).unwrap(),
            "pinned SOCKS target change must fragment identity"
        );
        assert!(
            SocksRouteKey::from_proxy(&base.config(), None).unwrap()
                != SocksRouteKey::from_proxy(&base.config(), Some(&target_a)).unwrap(),
            "adding a pinned SOCKS target must fragment identity"
        );

        // Request-only state is not represented: same connection policy
        // with different logical timeouts/budgets still reuses the route.
        // (Totals are not constructor inputs by design; this asserts the
        // type-level invariant alongside the behavior tests in
        // `proxy_tests.rs`.)
        let key_c = SocksRouteKey::from_proxy(&base.config(), None).unwrap();
        assert!(key_a == key_c, "request-only mutations must not fragment");
    }
}