aria2-core 0.3.11

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
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
//! FTP-over-HTTP-proxy GET method
//!
//! When an HTTP proxy is configured for FTP downloads, the default behavior
//! (V_GET in C++ aria2) is to send the FTP URL as a plain HTTP GET request
//! through the proxy. The proxy itself speaks FTP to the target server and
//! returns the data over HTTP.
//!
//! This is distinct from the CONNECT tunnel mode (`proxy_tunnel.rs`), where
//! a tunnel is established and the client speaks FTP directly.
//!
//! # C++ Equivalent
//!
//! Mirrors the V_GET path in `FtpInitiateConnectionCommand::createNextCommandProxied()`:
//! - `getRequest()->setMethod(Request::METHOD_GET)`
//! - Uses `HttpRequestConnectChain` (normal HTTP download pipeline)
//! - `HttpRequest::createRequest()` emits `GET ftp://host/path HTTP/1.1`
//!
//! # Request Format
//!
//! ```text
//! GET ftp://ftp.example.com/pub/file.tar.gz HTTP/1.1\r\n
//! Host: ftp.example.com\r\n
//! User-Agent: aria2-rust/<release-version>\r\n
//! Accept: */*\r\n
//! Connection: Keep-Alive\r\n
//! Proxy-Authorization: Basic <credentials>\r\n    (if proxy auth needed)
//! \r\n
//! ```

use std::fmt;
use std::time::Duration;

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;

use crate::network::OutboundNetworkPolicy;
use tracing::debug;
use url::Url;

use crate::error::{Aria2Error, RecoverableError, Result};
use crate::http::{HttpHeaderProcessor, HttpResponseHead};

// ---------------------------------------------------------------------------
// ProxyMethod — how to route FTP through an HTTP proxy
// ---------------------------------------------------------------------------

/// How to connect through an HTTP proxy for FTP downloads.
///
/// Mirrors C++ `AbstractCommand::resolveProxyMethod()` which returns
/// either `V_GET` or `V_TUNNEL`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProxyMethod {
    /// Send FTP URL as HTTP GET through proxy (default for FTP).
    ///
    /// The proxy translates `ftp://` to FTP and returns data over HTTP.
    /// Equivalent to C++ `V_GET`.
    #[default]
    Get,
    /// Establish CONNECT tunnel, then speak FTP directly.
    /// Already implemented in `proxy_tunnel.rs`.
    /// Equivalent to C++ `V_TUNNEL`.
    Tunnel,
}

impl fmt::Display for ProxyMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProxyMethod::Get => write!(f, "GET"),
            ProxyMethod::Tunnel => write!(f, "TUNNEL"),
        }
    }
}

impl ProxyMethod {
    /// Parse the wire spelling accepted by aria2's `proxy-method` option.
    ///
    /// Keeping this conversion next to the enum prevents each protocol
    /// adapter from inventing a slightly different string policy.
    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "get" => Some(Self::Get),
            "tunnel" => Some(Self::Tunnel),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// FtpProxyConfig — shared proxy configuration
// ---------------------------------------------------------------------------

/// Configuration for FTP proxy routing (shared by both GET and Tunnel modes).
///
/// This struct contains all the information needed to decide which proxy
/// method to use and to construct the appropriate request.
#[derive(Debug, Clone)]
pub struct FtpProxyConfig {
    /// Proxy server hostname
    pub proxy_host: String,
    /// Proxy server port
    pub proxy_port: u16,
    /// Proxy authentication username (empty if no auth)
    pub proxy_username: String,
    /// Proxy authentication password (empty if no auth)
    pub proxy_password: String,
    /// FTP server authentication username (for embedding in URI)
    pub ftp_username: String,
    /// Connection timeout for connecting to the proxy
    pub connect_timeout: Duration,
    /// User-Agent header to send
    pub user_agent: String,
    /// Explicit proxy method override (from --proxy-method option).
    /// When set to `Some(Tunnel)`, forces CONNECT tunnel instead of GET.
    pub explicit_proxy_method: Option<ProxyMethod>,
}

impl Default for FtpProxyConfig {
    fn default() -> Self {
        Self {
            proxy_host: String::new(),
            proxy_port: 8080,
            proxy_username: String::new(),
            proxy_password: String::new(),
            ftp_username: String::new(),
            connect_timeout: Duration::from_secs(30),
            user_agent: crate::constants::USER_AGENT.to_string(),
            explicit_proxy_method: None,
        }
    }
}

// ---------------------------------------------------------------------------
// resolve_proxy_method — mirrors C++ AbstractCommand::resolveProxyMethod()
// ---------------------------------------------------------------------------

/// Resolve which proxy method to use for FTP.
///
/// Mirrors C++ `AbstractCommand::resolveProxyMethod()`:
/// - If `--proxy-method=tunnel` is explicitly set, use Tunnel
/// - For `https` or `sftp` protocols, always use Tunnel
/// - Otherwise, use Get (the default for FTP)
///
/// # Arguments
///
/// * `config` - Proxy configuration with optional explicit method override
/// * `protocol` - The protocol being proxied ("ftp", "https", "sftp")
///
/// # Returns
///
/// The resolved `ProxyMethod`.
pub fn resolve_proxy_method(config: &FtpProxyConfig, protocol: &str) -> ProxyMethod {
    // C++: if protocol == "https" || protocol == "sftp" -> V_TUNNEL
    if protocol.eq_ignore_ascii_case("https") || protocol.eq_ignore_ascii_case("sftp") {
        debug!("Protocol {} requires Tunnel proxy method", protocol);
        return ProxyMethod::Tunnel;
    }

    // C++: if PREF_PROXY_METHOD == V_TUNNEL -> V_TUNNEL
    match config.explicit_proxy_method {
        Some(ProxyMethod::Tunnel) => {
            debug!("Explicit proxy method override: Tunnel");
            ProxyMethod::Tunnel
        }
        _ => {
            // Default for FTP: V_GET
            debug!("Default proxy method for FTP: Get");
            ProxyMethod::Get
        }
    }
}

// ---------------------------------------------------------------------------
// FtpProxyGetRequest — constructs the HTTP GET request for proxy
// ---------------------------------------------------------------------------

/// Result of building an FTP-over-proxy GET request.
///
/// Contains the raw HTTP/1.1 request bytes ready to write to the proxy socket.
#[derive(Debug, Clone)]
pub struct FtpProxyGetRequest {
    /// The raw HTTP/1.1 request bytes (including final \r\n\r\n)
    pub request_bytes: Vec<u8>,
    /// The full FTP URL used in the request line
    pub request_url: String,
}

/// HTTP response returned by an FTP-over-HTTP forward proxy.
///
/// The response head is parsed with the shared Rust HTTP parser. Bytes read
/// together with the head are retained so the payload cannot be lost between
/// header parsing and the FTP command's disk writer.
pub struct FtpProxyGetResponse {
    pub head: HttpResponseHead,
    stream: TcpStream,
    buffered_body: Vec<u8>,
}

impl FtpProxyGetResponse {
    /// Read payload bytes after the HTTP response head.
    pub async fn read_body(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
        if !self.buffered_body.is_empty() {
            let count = buffer.len().min(self.buffered_body.len());
            buffer[..count].copy_from_slice(&self.buffered_body[..count]);
            self.buffered_body.drain(..count);
            return Ok(count);
        }
        self.stream.read(buffer).await
    }
}

/// Execute one HTTP forward-proxy GET request for an FTP URL.
///
/// This is the Rust equivalent of aria2's `V_GET` path. The proxy receives
/// the absolute `ftp://` request target and returns the payload as an HTTP
/// response; the FTP control channel is intentionally not opened in this
/// mode.
pub async fn execute_proxy_get(
    ftp_url: Url,
    proxy_config: &FtpProxyConfig,
    range_start: u64,
    no_cache: bool,
) -> Result<FtpProxyGetResponse> {
    execute_proxy_get_with_policy(
        ftp_url,
        proxy_config,
        range_start,
        no_cache,
        &OutboundNetworkPolicy::direct(),
    )
    .await
}

/// Execute a forward-proxy FTP GET through the shared outbound policy.
pub async fn execute_proxy_get_with_policy(
    ftp_url: Url,
    proxy_config: &FtpProxyConfig,
    range_start: u64,
    no_cache: bool,
    policy: &OutboundNetworkPolicy,
) -> Result<FtpProxyGetResponse> {
    let request = FtpProxyGetRequestBuilder::new(ftp_url, proxy_config.clone())
        .range_start(range_start)
        .no_cache(no_cache)
        .build()?;

    let connect = async {
        if policy.is_direct() {
            TcpStream::connect((proxy_config.proxy_host.as_str(), proxy_config.proxy_port))
                .await
                .map_err(|error| Aria2Error::Network(error.to_string()))
        } else {
            policy
                .connect_host(&proxy_config.proxy_host, proxy_config.proxy_port)
                .await
                .map_err(|error| Aria2Error::Network(error.to_string()))
        }
    };
    let mut stream = tokio::time::timeout(proxy_config.connect_timeout, connect)
        .await
        .map_err(|_| Aria2Error::Recoverable(RecoverableError::Timeout))?
        .map_err(|error| {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: format!(
                    "FTP proxy connection failed to {}:{}: {}",
                    proxy_config.proxy_host, proxy_config.proxy_port, error
                ),
            })
        })?;
    stream.set_nodelay(true).map_err(|error| {
        Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
            message: format!("FTP proxy set_nodelay failed: {}", error),
        })
    })?;

    tokio::time::timeout(
        proxy_config.connect_timeout,
        stream.write_all(&request.request_bytes),
    )
    .await
    .map_err(|_| Aria2Error::Recoverable(RecoverableError::Timeout))?
    .map_err(|error| {
        Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
            message: format!("FTP proxy request failed: {}", error),
        })
    })?;
    stream.flush().await.map_err(|error| {
        Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
            message: format!("FTP proxy request flush failed: {}", error),
        })
    })?;

    let mut processor = HttpHeaderProcessor::new();
    let mut read_buffer = [0u8; 4096];
    let mut body_prefix = Vec::new();
    loop {
        let bytes_read =
            tokio::time::timeout(proxy_config.connect_timeout, stream.read(&mut read_buffer))
                .await
                .map_err(|_| Aria2Error::Recoverable(RecoverableError::Timeout))?
                .map_err(|error| {
                    Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                        message: format!("FTP proxy response failed: {}", error),
                    })
                })?;
        if bytes_read == 0 {
            return Err(Aria2Error::Recoverable(
                RecoverableError::TemporaryNetworkFailure {
                    message: "FTP proxy closed before response headers".into(),
                },
            ));
        }

        let state = processor.feed(&read_buffer[..bytes_read]).clone();
        let header_bytes = processor.last_bytes_processed();
        if state.is_complete() {
            if header_bytes < bytes_read {
                body_prefix.extend_from_slice(&read_buffer[header_bytes..bytes_read]);
            }
            let head = processor.get_result()?;
            debug!(status = head.status_code, "Received FTP proxy GET response");
            return Ok(FtpProxyGetResponse {
                head,
                stream,
                buffered_body: body_prefix,
            });
        }
        if state.is_error() {
            return Err(Aria2Error::HttpProtocol(
                "Invalid FTP proxy response headers".into(),
            ));
        }
    }
}

/// Builder for FTP-over-proxy GET requests.
///
/// Constructs the raw HTTP/1.1 request sent to the proxy in V_GET mode.
/// The request line contains the full FTP URL (not just the path),
/// telling the proxy which FTP resource to fetch.
///
/// Key differences from normal HTTP GET:
/// 1. Request line uses the full FTP URL: `GET ftp://host/path HTTP/1.1`
/// 2. `Host` header contains the FTP server host, not the proxy host
/// 3. `Connection: Keep-Alive` is added for proxy keep-alive
/// 4. `Proxy-Authorization` header is added if proxy credentials exist
/// 5. FTP username is inserted into the URI: `ftp://USER@host/path`
///    when the URL has no embedded username but auth credentials exist
pub struct FtpProxyGetRequestBuilder {
    /// The original FTP URL (e.g., ftp://ftp.example.com/pub/file.tar.gz)
    ftp_url: Url,
    /// Proxy configuration
    proxy_config: FtpProxyConfig,
    /// Resume offset (Range header), 0 means no Range header
    range_start: u64,
    /// Whether to add Pragma/Cache-Control: no-cache headers
    no_cache: bool,
}

impl FtpProxyGetRequestBuilder {
    /// Create a new builder for the given FTP URL and proxy config.
    ///
    /// # Arguments
    ///
    /// * `ftp_url` - The original FTP URL to download
    /// * `proxy_config` - Proxy server configuration
    pub fn new(ftp_url: Url, proxy_config: FtpProxyConfig) -> Self {
        Self {
            ftp_url,
            proxy_config,
            range_start: 0,
            no_cache: false,
        }
    }

    /// Set the resume offset for Range header.
    ///
    /// When `start > 0`, adds `Range: bytes=start-` header.
    /// Mirrors C++ `HttpRequest::createRequest()` segment-based Range logic.
    pub fn range_start(mut self, start: u64) -> Self {
        self.range_start = start;
        self
    }

    /// Enable no-cache headers for conditional GET refresh.
    ///
    /// When enabled, adds `Pragma: no-cache` and `Cache-Control: no-cache`.
    pub fn no_cache(mut self, enabled: bool) -> Self {
        self.no_cache = enabled;
        self
    }

    /// Build the raw HTTP/1.1 GET request for the proxy.
    ///
    /// Constructs the complete request including:
    /// - Request line with full FTP URL
    /// - Standard headers (Host, User-Agent, Accept)
    /// - Proxy-specific headers (Connection, Proxy-Authorization)
    /// - Conditional headers (Range, Cache-Control)
    /// - FTP auth embedded in URI if needed
    ///
    /// # Errors
    ///
    /// Returns an error if the FTP URL cannot be serialized.
    pub fn build(self) -> Result<FtpProxyGetRequest> {
        let request_url = self.build_request_url();

        // Build request line with full URL (proxy-style)
        let mut request = format!("GET {} HTTP/1.1\r\n", request_url);

        // Host header: FTP server host (mirrors C++ getHostText(getURIHost(), getPort()))
        let host_header = Self::build_host_header(&self.ftp_url);
        request.push_str(&format!("Host: {}\r\n", host_header));

        // User-Agent header
        request.push_str(&format!("User-Agent: {}\r\n", self.proxy_config.user_agent));

        // Accept header
        request.push_str("Accept: */*\r\n");

        // No-cache headers (mirrors C++ noCache_)
        if self.no_cache {
            request.push_str("Pragma: no-cache\r\n");
            request.push_str("Cache-Control: no-cache\r\n");
        }

        // Connection: Keep-Alive for proxy requests
        // Mirrors C++: if(proxyRequest_ && isKeepAliveEnabled())
        request.push_str("Connection: Keep-Alive\r\n");

        // Range header for resume (mirrors C++ segment-based Range logic)
        if self.range_start > 0 {
            request.push_str(&format!("Range: bytes={}-\r\n", self.range_start));
        }

        // Proxy-Authorization header (mirrors C++ getProxyAuthString())
        if !self.proxy_config.proxy_username.is_empty() {
            let auth_header = build_basic_proxy_auth(
                &self.proxy_config.proxy_username,
                &self.proxy_config.proxy_password,
            );
            request.push_str(&format!("Proxy-Authorization: {}\r\n", auth_header));
        }

        // End of headers
        request.push_str("\r\n");

        debug!(
            "Built FTP proxy GET request ({} bytes) for {}",
            request.len(),
            request_url
        );

        Ok(FtpProxyGetRequest {
            request_bytes: request.into_bytes(),
            request_url,
        })
    }

    /// Build the request URL, possibly embedding FTP username.
    ///
    /// Mirrors C++ `HttpRequest::createRequest()` lines 149-160:
    /// - If proxy is set and protocol is FTP and URL has no username
    ///   but FTP auth credentials exist, insert `USER@` into the URI.
    /// - Otherwise, use the URL as-is.
    fn build_request_url(&self) -> String {
        // Check if the FTP URL already has a username embedded
        let has_embedded_username = !self.ftp_url.username().is_empty();

        if !has_embedded_username && !self.proxy_config.ftp_username.is_empty() {
            // C++: Insert user into URI, like ftp://USER@host/
            // Percent-encode the username per RFC 3986
            let encoded_user = percent_encode_username(&self.proxy_config.ftp_username);
            let url_str = self.ftp_url.to_string();
            // Insert after "ftp://"
            if let Some(pos) = url_str.find("://") {
                let scheme_end = pos + 3;
                let mut result = String::with_capacity(url_str.len() + encoded_user.len() + 1);
                result.push_str(&url_str[..scheme_end]);
                result.push_str(&encoded_user);
                result.push('@');
                result.push_str(&url_str[scheme_end..]);
                return result;
            }
        }

        self.ftp_url.to_string()
    }

    /// Build the Host header value from the FTP URL.
    ///
    /// Mirrors C++ `getHostText(getURIHost(), getPort())`:
    /// - Omits port 21 for FTP (default port)
    /// - Includes port for non-default ports
    fn build_host_header(url: &Url) -> String {
        let host = url.host_str().unwrap_or("");
        let port = url.port();
        match port {
            Some(21) | None => host.to_string(),
            Some(p) => format!("{}:{}", host, p),
        }
    }
}

// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------

/// Build a Basic Proxy-Authorization header value.
///
/// Mirrors C++ `HttpRequest::getProxyAuthString()`.
fn build_basic_proxy_auth(username: &str, password: &str) -> String {
    use base64::Engine;
    let credentials = format!("{}:{}", username, password);
    let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
    format!("Basic {}", encoded)
}

/// Percent-encode a username for embedding in a URL.
///
/// Mirrors C++ `util::percentEncode()` for the FTP username.
/// Encodes all characters except unreserved (RFC 3986 section 2.3).
fn percent_encode_username(username: &str) -> String {
    const UNRESERVED: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
                                 abcdefghijklmnopqrstuvwxyz\
                                 0123456789\
                                 -._~";
    let mut result = String::with_capacity(username.len());
    for byte in username.bytes() {
        if UNRESERVED.contains(&byte) {
            result.push(byte as char);
        } else {
            result.push_str(&format!("%{:02X}", byte));
        }
    }
    result
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[tokio::test]
    async fn proxy_get_binding_reaches_the_proxy_socket() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
            .await
            .expect("proxy fixture should bind");
        let address = listener.local_addr().expect("proxy fixture address");
        let server = tokio::spawn(async move {
            let (mut stream, peer) = listener.accept().await.expect("proxy should accept");
            let mut request = [0u8; 4096];
            let bytes = stream.read(&mut request).await.expect("read proxy request");
            assert!(bytes > 0, "proxy request should not be empty");
            stream
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
                .await
                .expect("write proxy response");
            peer.ip()
        });

        let proxy = FtpProxyConfig {
            proxy_host: "127.0.0.1".to_string(),
            proxy_port: address.port(),
            ..FtpProxyConfig::default()
        };
        let response = execute_proxy_get_with_policy(
            Url::parse("ftp://ftp.example.com/file.bin").expect("valid FTP URL"),
            &proxy,
            0,
            false,
            &OutboundNetworkPolicy::single(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)),
        )
        .await
        .expect("proxy GET should connect with the configured source address");

        assert_eq!(response.head.status_code, 200);
        assert_eq!(
            server.await.expect("proxy fixture should finish"),
            std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
        );
    }

    /// Helper: build request and return as string for assertions.
    fn build_request_string(ftp_url: Url, proxy_config: FtpProxyConfig) -> String {
        let result = FtpProxyGetRequestBuilder::new(ftp_url, proxy_config)
            .build()
            .unwrap();
        String::from_utf8(result.request_bytes).unwrap()
    }

    #[test]
    fn test_proxy_method_default() {
        assert_eq!(ProxyMethod::default(), ProxyMethod::Get);
    }

    #[test]
    fn test_proxy_method_display() {
        assert_eq!(format!("{}", ProxyMethod::Get), "GET");
        assert_eq!(format!("{}", ProxyMethod::Tunnel), "TUNNEL");
    }

    #[test]
    fn test_resolve_proxy_method_default_ftp() {
        let config = FtpProxyConfig::default();
        assert_eq!(resolve_proxy_method(&config, "ftp"), ProxyMethod::Get);
    }

    #[test]
    fn test_resolve_proxy_method_explicit_tunnel() {
        let config = FtpProxyConfig {
            explicit_proxy_method: Some(ProxyMethod::Tunnel),
            ..Default::default()
        };
        assert_eq!(resolve_proxy_method(&config, "ftp"), ProxyMethod::Tunnel);
    }

    #[test]
    fn test_resolve_proxy_method_https_always_tunnel() {
        let config = FtpProxyConfig::default();
        assert_eq!(resolve_proxy_method(&config, "https"), ProxyMethod::Tunnel);
    }

    #[test]
    fn test_resolve_proxy_method_sftp_always_tunnel() {
        let config = FtpProxyConfig::default();
        assert_eq!(resolve_proxy_method(&config, "sftp"), ProxyMethod::Tunnel);
    }

    #[test]
    fn test_resolve_proxy_method_https_ignores_explicit_get() {
        // Even if someone explicitly sets GET, HTTPS always uses Tunnel
        let config = FtpProxyConfig {
            explicit_proxy_method: Some(ProxyMethod::Get),
            ..Default::default()
        };
        assert_eq!(resolve_proxy_method(&config, "https"), ProxyMethod::Tunnel);
    }

    #[test]
    fn test_ftp_proxy_config_default() {
        let config = FtpProxyConfig::default();
        assert_eq!(config.proxy_port, 8080);
        assert!(config.proxy_username.is_empty());
        assert!(config.proxy_password.is_empty());
        assert!(config.ftp_username.is_empty());
        assert!(config.explicit_proxy_method.is_none());
    }

    #[test]
    fn test_build_basic_proxy_auth() {
        let header = build_basic_proxy_auth("proxyuser", "proxypass");
        assert!(header.starts_with("Basic "));
        // Base64 of "proxyuser:proxypass"
        assert_eq!(header, "Basic cHJveHl1c2VyOnByb3h5cGFzcw==");
    }

    #[test]
    fn test_percent_encode_username_simple() {
        assert_eq!(percent_encode_username("user"), "user");
    }

    #[test]
    fn test_percent_encode_username_special_chars() {
        assert_eq!(percent_encode_username("user@domain"), "user%40domain");
        assert_eq!(percent_encode_username("user name"), "user%20name");
        assert_eq!(percent_encode_username("user/pass"), "user%2Fpass");
    }

    #[test]
    fn test_build_request_simple() {
        let ftp_url = Url::parse("ftp://ftp.example.com/pub/file.tar.gz").unwrap();
        let proxy_config = FtpProxyConfig {
            proxy_host: "proxy.example.com".to_string(),
            proxy_port: 8080,
            user_agent: "test-client/1.0".to_string(),
            ..Default::default()
        };
        let s = build_request_string(ftp_url, proxy_config);
        assert!(s.starts_with("GET ftp://ftp.example.com/pub/file.tar.gz HTTP/1.1\r\n"));
        assert!(s.contains("Host: ftp.example.com\r\n"));
        assert!(s.contains("User-Agent: test-client/1.0\r\n"));
        assert!(s.contains("Connection: Keep-Alive\r\n"));
        assert!(!s.contains("Proxy-Authorization"));
        assert!(!s.contains("Range:"));
        assert!(s.ends_with("\r\n\r\n"));
    }

    #[test]
    fn test_build_request_with_proxy_auth() {
        let ftp_url = Url::parse("ftp://ftp.example.com/pub/file.tar.gz").unwrap();
        let proxy_config = FtpProxyConfig {
            proxy_username: "proxyuser".to_string(),
            proxy_password: "proxypass".to_string(),
            ..Default::default()
        };
        let s = build_request_string(ftp_url, proxy_config);
        assert!(s.contains("Proxy-Authorization: Basic cHJveHl1c2VyOnByb3h5cGFzcw==\r\n"));
    }

    #[test]
    fn test_build_request_with_ftp_username_embedded() {
        let ftp_url = Url::parse("ftp://ftp.example.com/pub/file.tar.gz").unwrap();
        let proxy_config = FtpProxyConfig {
            ftp_username: "ftpuser".to_string(),
            ..Default::default()
        };
        let s = build_request_string(ftp_url, proxy_config);
        assert!(s.contains("GET ftp://ftpuser@ftp.example.com/pub/file.tar.gz HTTP/1.1\r\n"));
    }

    #[test]
    fn test_build_request_no_double_username() {
        let ftp_url = Url::parse("ftp://existing@ftp.example.com/pub/file.tar.gz").unwrap();
        let proxy_config = FtpProxyConfig {
            ftp_username: "ftpuser".to_string(),
            ..Default::default()
        };
        let s = build_request_string(ftp_url, proxy_config);
        assert!(s.contains("ftp://existing@ftp.example.com"));
        assert!(!s.contains("ftp://ftpuser@"));
    }

    #[test]
    fn test_build_request_with_range() {
        let ftp_url = Url::parse("ftp://ftp.example.com/pub/file.tar.gz").unwrap();
        let result = FtpProxyGetRequestBuilder::new(ftp_url, FtpProxyConfig::default())
            .range_start(1024)
            .build()
            .unwrap();
        let s = String::from_utf8(result.request_bytes).unwrap();
        assert!(s.contains("Range: bytes=1024-\r\n"));
    }

    #[test]
    fn test_build_request_with_no_cache() {
        let ftp_url = Url::parse("ftp://ftp.example.com/pub/file.tar.gz").unwrap();
        let result = FtpProxyGetRequestBuilder::new(ftp_url, FtpProxyConfig::default())
            .no_cache(true)
            .build()
            .unwrap();
        let s = String::from_utf8(result.request_bytes).unwrap();
        assert!(s.contains("Pragma: no-cache\r\n"));
        assert!(s.contains("Cache-Control: no-cache\r\n"));
    }

    #[test]
    fn test_build_host_header_default_port() {
        let url = Url::parse("ftp://ftp.example.com/pub/file").unwrap();
        assert_eq!(
            FtpProxyGetRequestBuilder::build_host_header(&url),
            "ftp.example.com"
        );
    }

    #[test]
    fn test_build_host_header_non_default_port() {
        let url = Url::parse("ftp://ftp.example.com:2121/pub/file").unwrap();
        assert_eq!(
            FtpProxyGetRequestBuilder::build_host_header(&url),
            "ftp.example.com:2121"
        );
    }

    #[test]
    fn test_build_request_full_round_trip() {
        let ftp_url = Url::parse("ftp://ftp.example.com/pub/linux/file.tar.gz").unwrap();
        let proxy_config = FtpProxyConfig {
            proxy_host: "proxy.local".to_string(),
            proxy_port: 3128,
            proxy_username: "puser".to_string(),
            proxy_password: "ppass".to_string(),
            ftp_username: "anonymous".to_string(),
            user_agent: "test-client/2.0".to_string(),
            ..Default::default()
        };

        let result = FtpProxyGetRequestBuilder::new(ftp_url, proxy_config)
            .range_start(4096)
            .no_cache(true)
            .build()
            .unwrap();

        let s = String::from_utf8(result.request_bytes).unwrap();
        assert!(
            s.contains("GET ftp://anonymous@ftp.example.com/pub/linux/file.tar.gz HTTP/1.1\r\n")
        );
        assert!(s.contains("Host: ftp.example.com\r\n"));
        assert!(s.contains("User-Agent: test-client/2.0\r\n"));
        assert!(s.contains("Pragma: no-cache\r\n"));
        assert!(s.contains("Connection: Keep-Alive\r\n"));
        assert!(s.contains("Range: bytes=4096-\r\n"));
        assert!(s.contains("Proxy-Authorization: Basic"));
        assert!(s.ends_with("\r\n\r\n"));
        assert_eq!(
            result.request_url,
            "ftp://anonymous@ftp.example.com/pub/linux/file.tar.gz"
        );
    }
}