Skip to main content

http_request/request/http_request/
impl.rs

1use super::*;
2
3impl<T> AsyncReadWrite for T where T: AsyncRead + AsyncWrite + Unpin + Send {}
4impl<T> ReadWrite for T where T: Read + Write + Send {}
5
6/// Inherent implementation of [`HttpRequest`].
7impl HttpRequest {
8    /// Send the HTTP request synchronously, returning the parsed response.
9    ///
10    /// # Returns
11    ///
12    /// - `Result<HttpResponse, RequestError>` - The parsed HTTP response, or a `RequestError` on failure.
13    pub fn send(&mut self) -> Result<HttpResponse, RequestError> {
14        self.send_sync()
15    }
16
17    /// Send the HTTP request asynchronously, returning the parsed response.
18    ///
19    /// # Returns
20    ///
21    /// - `Result<HttpResponse, RequestError>` - The parsed HTTP response, or a `RequestError` on failure.
22    pub async fn send_async(&mut self) -> Result<HttpResponse, RequestError> {
23        self.send_async_impl().await
24    }
25
26    /// Parse the configured URL into a [`HttpUrlComponents`].
27    ///
28    /// # Returns
29    ///
30    /// - `Result<HttpUrlComponents, RequestError>` - The parsed URL components, or a `RequestError` when the URL is malformed.
31    pub(crate) fn parse_url(&self) -> Result<HttpUrlComponents, RequestError> {
32        let (scheme, remainder): (&str, &str) = self
33            .get_url()
34            .split_once(SCHEME_SEPARATOR)
35            .ok_or(RequestError::InvalidUrlScheme(HttpStatus::BadRequest))?;
36        if !scheme.eq_ignore_ascii_case(HTTP_SCHEME)
37            && !scheme.eq_ignore_ascii_case(HTTPS_LOWERCASE)
38        {
39            return Err(RequestError::InvalidUrlScheme(HttpStatus::BadRequest));
40        }
41        let authority_end: usize = remainder
42            .find([URL_SLASH, URL_QUERY, URL_FRAGMENT])
43            .unwrap_or(remainder.len());
44        let authority: &str = &remainder[..authority_end];
45        if authority.is_empty()
46            || authority.contains(URL_BACKSLASH)
47            || authority
48                .bytes()
49                .any(|byte: u8| byte.is_ascii_control() || byte == SPACE_U8)
50        {
51            return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
52        }
53        let target: &str = remainder[authority_end..]
54            .split(URL_FRAGMENT)
55            .next()
56            .unwrap_or_default();
57        let (path, query): (&str, &str) = target
58            .split_once(URL_QUERY)
59            .unwrap_or((target, Default::default()));
60        if path
61            .bytes()
62            .any(|byte: u8| byte.is_ascii_control() || byte == SPACE_U8)
63        {
64            return Err(RequestError::InvalidUrlPath(HttpStatus::BadRequest));
65        }
66        if query
67            .bytes()
68            .any(|byte: u8| byte.is_ascii_control() || byte == SPACE_U8)
69        {
70            return Err(RequestError::InvalidUrlQuery(HttpStatus::BadRequest));
71        }
72        let components: HttpUrlComponents = match HttpUrlComponents::parse(self.get_url()) {
73            Ok(value) => value,
74            Err(_) => return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest)),
75        };
76        let host: String = components.get_host().unwrap_or_default();
77        if host.is_empty()
78            || host
79                .bytes()
80                .any(|byte: u8| byte.is_ascii_control() || byte == SPACE_U8)
81        {
82            return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
83        }
84        Ok(components)
85    }
86
87    /// `Host` + path (including query string) for the request line.
88    ///
89    /// # Returns
90    ///
91    /// - `Result<String, RequestError>` - The safe request target, or an error for an invalid URL.
92    #[cfg(test)]
93    pub(crate) fn full_path(&self) -> Result<String, RequestError> {
94        let url_obj: HttpUrlComponents = self.parse_url()?;
95        let query: String = url_obj.get_query().unwrap_or_default();
96        let path: String = url_obj.get_path().unwrap_or_default();
97        if query.is_empty() {
98            Ok(path)
99        } else {
100            Ok(format!("{}{}{}", path, QUERY, query))
101        }
102    }
103
104    /// Build the wire-format header bytes, with `Host`, `Content-Length`,
105    /// `Accept`, `User-Agent` auto-filled if missing.
106    ///
107    /// # Arguments
108    ///
109    /// - `usize` - The length of the encoded request body.
110    ///
111    /// # Returns
112    ///
113    /// - `Result<Vec<u8>, RequestError>` - The validated wire-format headers, or an error for invalid fields.
114    #[cfg(test)]
115    pub(crate) fn header_bytes(&self, body_length: usize) -> Result<Vec<u8>, RequestError> {
116        let mut header: HashMap<String, String> = self.get_headers().clone();
117        let host_value: String = self.parse_url()?.get_host().unwrap_or_default();
118        let content_length_value: String = body_length.to_string();
119        if !Self::header_has_key(&header, HOST) {
120            header.insert(HOST.to_ascii_lowercase(), host_value);
121        }
122        if !Self::header_has_key(&header, CONTENT_LENGTH) {
123            header.insert(CONTENT_LENGTH.to_ascii_lowercase(), content_length_value);
124        }
125        if !Self::header_has_key(&header, ACCEPT) {
126            header.insert(ACCEPT.to_ascii_lowercase(), ACCEPT_ANY.to_owned());
127        }
128        if !Self::header_has_key(&header, USER_AGENT) {
129            header.insert(USER_AGENT.to_ascii_lowercase(), APP_NAME.to_owned());
130        }
131        validate_request_headers(&header)?;
132        let estimated_size: usize = header
133            .iter()
134            .map(|(k, v): (&String, &String)| k.len() + v.len() + 4)
135            .sum();
136        let mut out: Vec<u8> = Vec::with_capacity(estimated_size);
137        for (key, value) in &header {
138            out.extend_from_slice(key.as_bytes());
139            out.extend_from_slice(HEADER_VALUE_SEPARATOR);
140            out.extend_from_slice(value.as_bytes());
141            out.extend_from_slice(HTTP_BR_BYTES);
142        }
143        Ok(out)
144    }
145
146    /// Check whether a header map already contains a key, comparing case-insensitively.
147    ///
148    /// # Arguments
149    ///
150    /// - `&HashMap<String, String>` - The header map to search.
151    /// - `&str` - The header key to look for.
152    ///
153    /// # Returns
154    ///
155    /// - `bool` - `true` when the map contains the key, `false` otherwise.
156    #[cfg(test)]
157    fn header_has_key(header: &HashMap<String, String>, target_key: &str) -> bool {
158        header
159            .keys()
160            .any(|key: &String| key.eq_ignore_ascii_case(target_key))
161    }
162
163    /// Remove every header entry matching `target_key` case-insensitively.
164    ///
165    /// # Arguments
166    ///
167    /// - `&str` - The header name to remove.
168    fn remove_header_ci(&mut self, target_key: &str) {
169        self.get_mut_headers()
170            .retain(|key: &String, _: &mut String| !key.eq_ignore_ascii_case(target_key));
171    }
172
173    /// Return whether a parsed URL targets HTTPS.
174    ///
175    /// # Arguments
176    ///
177    /// - `&HttpUrlComponents` - Parsed URL components.
178    ///
179    /// # Returns
180    ///
181    /// - `bool` - `true` when the URL scheme is `https` (case-insensitive).
182    fn scheme_is_https(url_obj: &HttpUrlComponents) -> bool {
183        url_obj.get_protocol().eq_ignore_ascii_case(HTTPS_LOWERCASE)
184    }
185
186    /// Resolve the effective TCP port from the parsed port and URL scheme.
187    ///
188    /// # Arguments
189    ///
190    /// - `u16` - Parsed URL port (`0` when omitted).
191    /// - `bool` - Whether the URL uses HTTPS.
192    ///
193    /// # Returns
194    ///
195    /// - `u16` - Effective TCP port.
196    fn resolve_port_for_scheme(port: u16, is_https: bool) -> u16 {
197        if port != 0 {
198            return port;
199        }
200        if is_https {
201            HTTPS_DEFAULT_PORT
202        } else {
203            HTTP_DEFAULT_PORT
204        }
205    }
206
207    /// Strip optional square brackets surrounding an IPv6 literal host.
208    ///
209    /// # Arguments
210    ///
211    /// - `&str` - Raw host string from the URL.
212    ///
213    /// # Returns
214    ///
215    /// - `&str` - Bare IPv6 address or original hostname.
216    fn strip_ipv6_brackets(host: &str) -> &str {
217        host.strip_prefix('[')
218            .and_then(|inner: &str| inner.strip_suffix(']'))
219            .unwrap_or(host)
220    }
221
222    /// Format a host and port into `host:port` or `[ipv6]:port` for CONNECT / Host.
223    ///
224    /// # Arguments
225    ///
226    /// - `&str` - Hostname or IP literal.
227    /// - `u16` - TCP port.
228    ///
229    /// # Returns
230    ///
231    /// - `String` - Properly bracketed authority string.
232    fn format_authority(host: &str, port: u16) -> String {
233        if host.contains(':') && !host.starts_with('[') {
234            format!("[{host}]:{port}")
235        } else {
236            format!("{host}:{port}")
237        }
238    }
239
240    /// Build a validated rustls `ServerName` for a DNS name or IPv4/IPv6 literal.
241    ///
242    /// # Arguments
243    ///
244    /// - `&str` - Target host string.
245    ///
246    /// # Returns
247    ///
248    /// - `Result<ServerName<'static>, RequestError>` - Valid TLS SNI / IP server name.
249    fn server_name_for_host(host: &str) -> Result<ServerName<'static>, RequestError> {
250        let clean: &str = Self::strip_ipv6_brackets(host);
251        ServerName::try_from(clean.to_owned())
252            .map_err(|e: InvalidDnsNameError| RequestError::Request(e.to_string()))
253    }
254
255    /// Return the effective non-zero read buffer size.
256    ///
257    /// # Returns
258    ///
259    /// - `usize` - Configured `buffer_size`, or `DEFAULT_EFFECTIVE_BUFFER_SIZE` when zero.
260    fn effective_buffer_size(&self) -> usize {
261        let configured: usize = self.get_config().get_buffer_size();
262        if configured == 0 {
263            DEFAULT_EFFECTIVE_BUFFER_SIZE
264        } else {
265            configured
266        }
267    }
268
269    /// Return a cached `Arc<ClientConfig>` for HTTP/1.1 TLS connections.
270    ///
271    /// # Returns
272    ///
273    /// - `Arc<ClientConfig>` - Shared rustls client configuration with `http/1.1` ALPN.
274    fn tls_client_config(&self) -> Arc<ClientConfig> {
275        resolve_tls_client_config(self.get_tmp().get_root_cert(), false)
276    }
277
278    /// Return a cached `Arc<ClientConfig>` for HTTP/2 TLS connections.
279    ///
280    /// # Returns
281    ///
282    /// - `Arc<ClientConfig>` - Shared rustls client configuration with `h2` ALPN.
283    fn tls_client_config_h2(&self) -> Arc<ClientConfig> {
284        resolve_tls_client_config(self.get_tmp().get_root_cert(), true)
285    }
286
287    /// Return the effective TCP connect timeout in milliseconds (`connect_timeout` or fallback `timeout`).
288    ///
289    /// # Returns
290    ///
291    /// - `u64` - Effective connect timeout in milliseconds (`0` disables the connect deadline).
292    fn effective_connect_timeout_ms(&self) -> u64 {
293        let connect_ms: u64 = self.get_config().get_connect_timeout();
294        if connect_ms > 0 {
295            connect_ms
296        } else {
297            self.get_config().get_timeout()
298        }
299    }
300
301    /// Validate and serialize the configured HTTP method token.
302    ///
303    /// # Returns
304    ///
305    /// - `Result<(Cow<'static, str>, bool), RequestError>` - `(method_token, is_head)` or an error on invalid tokens.
306    fn validated_http_method(&self) -> Result<(Cow<'static, str>, bool), RequestError> {
307        let method: Method = self.get_method();
308        let token: Cow<'static, str> = match method {
309            Method::Get => Cow::Borrowed(GET),
310            Method::Post => Cow::Borrowed(POST),
311            Method::Put => Cow::Borrowed(PUT),
312            Method::Delete => Cow::Borrowed(DELETE),
313            Method::Patch => Cow::Borrowed(PATCH),
314            Method::Head => return Ok((Cow::Borrowed(HEAD), true)),
315            Method::Options => Cow::Borrowed(OPTIONS),
316            Method::Connect => Cow::Borrowed(CONNECT),
317            Method::Trace => Cow::Borrowed(TRACE),
318            Method::Unknown(ref custom) => {
319                if custom.is_empty() || !is_valid_header_name(custom.as_bytes()) {
320                    return Err(RequestError::Request(INVALID_HTTP_METHOD.to_owned()));
321                }
322                Cow::Owned(custom.clone())
323            }
324        };
325        Ok((token, false))
326    }
327
328    /// Validate and serialize the configured HTTP version token.
329    ///
330    /// # Returns
331    ///
332    /// - `Result<&str, RequestError>` - Valid wire HTTP version token or an error.
333    fn validated_http_version(&self) -> Result<&str, RequestError> {
334        let version: &str = self.get_config().get_http_version().as_str();
335        if !version.as_bytes().starts_with(HTTP_STATUS_PREFIX)
336            || version.len() <= HTTP_STATUS_PREFIX.len()
337            || version
338                .bytes()
339                .any(|byte: u8| byte <= SPACE_U8 || byte >= 0x7f)
340        {
341            return Err(RequestError::Request(INVALID_HTTP_VERSION.to_owned()));
342        }
343        Ok(version)
344    }
345
346    /// Validate an HTTP CONNECT proxy response head and return whether status is `2xx`.
347    ///
348    /// # Arguments
349    ///
350    /// - `&[u8]` - Proxy response header block up to `\r\n\r\n`.
351    ///
352    /// # Returns
353    ///
354    /// - `bool` - `true` when the proxy returned a valid `HTTP/1.x 2xx` status line.
355    fn is_connect_success_head(head: &[u8]) -> bool {
356        let has_prefix: bool =
357            head.starts_with(HTTP_CONNECT_PREFIX_1_1) || head.starts_with(HTTP_CONNECT_PREFIX_1_0);
358        if !has_prefix {
359            return false;
360        }
361        let status_start: usize = HTTP_CONNECT_PREFIX_1_1.len();
362        let status_code: usize = head
363            .get(status_start..status_start + 3)
364            .map_or(0, parse_status_code);
365        (200..300).contains(&status_code)
366            && matches!(head.get(status_start + 3), Some(b' ' | b'\r') | None)
367    }
368
369    /// Build a validated HTTP CONNECT request string for an HTTP/HTTPS proxy.
370    ///
371    /// # Arguments
372    ///
373    /// - `&str` - Target host.
374    /// - `u16` - Target port.
375    /// - `&Proxy` - Proxy configuration.
376    ///
377    /// # Returns
378    ///
379    /// - `Result<String, RequestError>` - Validated CONNECT request bytes as a string.
380    fn build_connect_request(
381        target_host: &str,
382        target_port: u16,
383        proxy: &Proxy,
384    ) -> Result<String, RequestError> {
385        if !is_valid_header_value(target_host.as_bytes())
386            || target_host
387                .bytes()
388                .any(|byte: u8| byte <= SPACE_U8 || byte >= 0x7f)
389        {
390            return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
391        }
392        let authority: String = Self::format_authority(target_host, target_port);
393        if let (Some(u), Some(p)) = (proxy.get_username(), proxy.get_password()) {
394            if u.contains(':')
395                || !is_valid_header_value(u.as_bytes())
396                || !is_valid_header_value(p.as_bytes())
397            {
398                return Err(RequestError::Request(PROXY_AUTH_ERROR.to_owned()));
399            }
400            let auth: String = format!("{u}:{p}");
401            let encoded: String = crate::utils::base64_encode(auth.as_bytes());
402            Ok(format!(
403                "CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\nProxy-Authorization: Basic {encoded}\r\n\r\n"
404            ))
405        } else {
406            Ok(format!(
407                "CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n\r\n"
408            ))
409        }
410    }
411
412    /// Resolve a `Location` redirect target (absolute or relative) against the current URL.
413    ///
414    /// # Arguments
415    ///
416    /// - `&HttpUrlComponents` - Current parsed URL.
417    /// - `&str` - Raw `Location` header value.
418    ///
419    /// # Returns
420    ///
421    /// - `Result<String, RequestError>` - Resolved absolute `http://` or `https://` URL.
422    fn resolve_redirect_url(
423        current: &HttpUrlComponents,
424        location: &str,
425    ) -> Result<String, RequestError> {
426        let trimmed: &str = location.trim();
427        if trimmed.is_empty() {
428            return Err(RequestError::Request(MISSING_REDIRECT_URL.to_owned()));
429        }
430        if trimmed.contains(SCHEME_SEPARATOR) {
431            return Ok(trimmed.to_owned());
432        }
433        let raw_protocol: &str = current.get_protocol();
434        let scheme: String = if raw_protocol.is_empty() {
435            HTTP_SCHEME.to_owned()
436        } else {
437            raw_protocol.to_ascii_lowercase()
438        };
439        if let Some(rest) = trimmed.strip_prefix("//") {
440            return Ok(format!("{scheme}://{rest}"));
441        }
442        let host: String = current.get_host().unwrap_or_default();
443        let authority: String = match current.get_port() {
444            Some(port) if port != 0 => Self::format_authority(&host, port),
445            _ => host,
446        };
447        if trimmed.starts_with(URL_SLASH) {
448            return Ok(format!("{scheme}://{authority}{trimmed}"));
449        }
450        if trimmed.starts_with(URL_QUERY) {
451            let base_path: String = current.get_path().unwrap_or_else(|| URL_SLASH.to_string());
452            return Ok(format!("{scheme}://{authority}{base_path}{trimmed}"));
453        }
454        let current_path: String = current.get_path().unwrap_or_else(|| URL_SLASH.to_string());
455        let base_dir: &str = match current_path.rfind(URL_SLASH) {
456            Some(pos) => &current_path[..=pos],
457            None => "/",
458        };
459        Ok(format!("{scheme}://{authority}{base_dir}{trimmed}"))
460    }
461
462    /// Apply RFC 9110 redirect state transitions (loop detection, budget, credential stripping, method rewrite).
463    ///
464    /// # Arguments
465    ///
466    /// - `&HttpUrlComponents` - Parsed URL of the hop that produced the redirect.
467    /// - `usize` - HTTP redirect status code (`301`/`302`/`303`/`307`/`308`).
468    /// - `String` - Raw `Location` header value.
469    ///
470    /// # Returns
471    ///
472    /// - `Result<(), RequestError>` - `Ok(())` when the request is updated for the next hop.
473    fn prepare_redirect_hop(
474        &mut self,
475        current_url: &HttpUrlComponents,
476        status_code: usize,
477        location: String,
478    ) -> Result<(), RequestError> {
479        let resolved: String = Self::resolve_redirect_url(current_url, &location)?;
480        if self.get_tmp().get_visit_url().contains(&resolved) {
481            return Err(RequestError::Request(REDIRECT_URL_DEAD_LOOP.to_string()));
482        }
483        self.get_mut_tmp()
484            .get_mut_visit_url()
485            .insert(resolved.clone());
486        let remaining: usize = self.get_config().get_max_redirect_times();
487        if remaining == 0 {
488            return Err(RequestError::Request(
489                MAX_REDIRECT_TIMES_EXCEEDED.to_string(),
490            ));
491        }
492        self.get_mut_config()
493            .set_max_redirect_times(remaining.saturating_sub(1));
494        let prev_https: bool = Self::scheme_is_https(current_url);
495        let prev_host: String = current_url.get_host().unwrap_or_default();
496        let prev_port: u16 =
497            Self::resolve_port_for_scheme(current_url.get_port().unwrap_or_default(), prev_https);
498        self.set_url(resolved);
499        let next_url: HttpUrlComponents = self.parse_url()?;
500        let next_https: bool = Self::scheme_is_https(&next_url);
501        let next_host: String = next_url.get_host().unwrap_or_default();
502        let next_port: u16 =
503            Self::resolve_port_for_scheme(next_url.get_port().unwrap_or_default(), next_https);
504        let same_origin: bool = prev_https == next_https
505            && prev_host.eq_ignore_ascii_case(&next_host)
506            && prev_port == next_port;
507        if !same_origin || (prev_https && !next_https) {
508            self.remove_header_ci(HEADER_AUTHORIZATION);
509            self.remove_header_ci(HEADER_PROXY_AUTHORIZATION);
510            self.remove_header_ci(HEADER_COOKIE);
511        }
512        self.remove_header_ci(HOST);
513        let current_method: Method = self.get_method();
514        let rewrite_to_get: bool =
515            (status_code == 303 && !current_method.is_get() && !current_method.is_head())
516                || ([301, 302].contains(&status_code) && current_method.is_post());
517        if rewrite_to_get {
518            self.set_method(Method::Get);
519            self.set_body(Body::empty());
520            self.remove_header_ci(CONTENT_TYPE);
521            self.remove_header_ci(CONTENT_LENGTH);
522        }
523        Ok(())
524    }
525
526    /// Synchronous send with connection pooling, idempotent retries, and iterative redirect handling.
527    ///
528    /// # Returns
529    ///
530    /// - `Result<HttpResponse, RequestError>` - The parsed HTTP response, or a `RequestError` on failure.
531    pub(crate) fn send_sync(&mut self) -> Result<HttpResponse, RequestError> {
532        let mut redirect_started: bool = false;
533        loop {
534            let mut owned_url: Option<HttpUrlComponents> = None;
535            let owned_host: String;
536            let owned_path: String;
537            let owned_query: String;
538            let target: FastUrlParts<'_> = if let Some(fast) = parse_url_fast(self.get_url()) {
539                fast
540            } else {
541                let parsed: HttpUrlComponents = self.parse_url()?;
542                let is_https: bool = Self::scheme_is_https(&parsed);
543                owned_host = parsed.get_host().unwrap_or_default();
544                owned_path = parsed.get_path().unwrap_or_default();
545                owned_query = parsed.get_query().unwrap_or_default();
546                let port: u16 =
547                    Self::resolve_port_for_scheme(parsed.get_port().unwrap_or_default(), is_https);
548                owned_url = Some(parsed);
549                FastUrlParts {
550                    is_https,
551                    host: owned_host.as_str(),
552                    port,
553                    path: owned_path.as_str(),
554                    query: owned_query.as_str(),
555                }
556            };
557            validate_request_headers(self.get_headers())?;
558            let (method_token, is_head): (Cow<'static, str>, bool) =
559                self.validated_http_method()?;
560            let version: &str = self.validated_http_version()?;
561            let mut request_bytes: Vec<u8> = take_client_buffer(256);
562            if let Err(error) = build_wire_request_parts_into(
563                self,
564                &target,
565                method_token.as_ref(),
566                is_head,
567                version,
568                &mut request_bytes,
569            ) {
570                return_client_buffer(request_bytes);
571                return Err(error);
572            }
573            let max_retries: usize = if is_idempotent_method(&self.get_method()) {
574                self.get_config().get_max_retries()
575            } else {
576                0
577            };
578            let mut attempt: usize = 0;
579            let exchange_result: Result<(HttpResponse, Option<Vec<u8>>), RequestError> = loop {
580                let res: Result<(HttpResponse, Option<Vec<u8>>), RequestError> = self
581                    .exchange_sync_once(
582                        target.host,
583                        target.port,
584                        target.is_https,
585                        &request_bytes,
586                        is_head,
587                    );
588                match res {
589                    Ok((resp, redir)) => {
590                        if attempt < max_retries && is_retryable_status(resp.get_status_code()) {
591                            thread::sleep(retry_backoff_duration(attempt));
592                            attempt += 1;
593                            continue;
594                        }
595                        break Ok((resp, redir));
596                    }
597                    Err(error) => {
598                        if attempt < max_retries && is_retryable_error(&error) {
599                            thread::sleep(retry_backoff_duration(attempt));
600                            attempt += 1;
601                            continue;
602                        }
603                        break Err(error);
604                    }
605                }
606            };
607            return_client_buffer(request_bytes);
608            let (mut response, redirect_url): (HttpResponse, Option<Vec<u8>>) = exchange_result?;
609            if !self.get_config().get_redirect() || redirect_url.is_none() {
610                if !is_head && self.get_config().get_decode() {
611                    response.decode_in_place(self.effective_buffer_size());
612                }
613                return Ok(response);
614            }
615            if !redirect_started {
616                redirect_started = true;
617                let initial_url: String = self.get_url().to_owned();
618                self.get_mut_tmp().get_mut_visit_url().insert(initial_url);
619            }
620            let url_obj: HttpUrlComponents = match owned_url {
621                Some(parsed) => parsed,
622                None => self.parse_url()?,
623            };
624            let url_bytes: Vec<u8> = redirect_url
625                .ok_or_else(|| RequestError::Request(MISSING_REDIRECT_URL.to_string()))?;
626            let location: String = String::from_utf8(url_bytes)
627                .map_err(|e: FromUtf8Error| RequestError::Request(e.to_string()))?;
628            self.prepare_redirect_hop(&url_obj, response.get_status_code(), location)?;
629        }
630    }
631
632    /// Executes one synchronous HTTP/1 exchange using the idle keep-alive pool with transparent stale redial.
633    ///
634    /// # Arguments
635    ///
636    /// - `&str` - Target host.
637    /// - `u16` - Target TCP port.
638    /// - `bool` - Whether TLS is required.
639    /// - `&[u8]` - Pre-serialized wire request bytes.
640    /// - `bool` - Whether the request method is `HEAD`.
641    ///
642    /// # Returns
643    ///
644    /// - `Result<(HttpResponse, Option<Vec<u8>>), RequestError>` - Parsed response and optional redirect target.
645    fn exchange_sync_once(
646        &self,
647        host: &str,
648        port: u16,
649        is_https: bool,
650        request_bytes: &[u8],
651        is_head: bool,
652    ) -> Result<(HttpResponse, Option<Vec<u8>>), RequestError> {
653        let disable_keep_alive: bool = request_disables_keep_alive(self);
654        let proxy_opt: Option<Proxy> = self.get_config().get_proxy();
655        let proxy: Option<&Proxy> = proxy_opt.as_ref();
656        let roots: &RootCertStore = self.get_tmp().get_root_cert();
657        let sync_timeout_ms: u64 = self.get_config().get_timeout();
658        let mut attempted_pooled: bool = false;
659        loop {
660            let (mut stream, from_pool): (Box<dyn ReadWrite>, bool) = if !disable_keep_alive
661                && !attempted_pooled
662                && let Some(cached) =
663                    take_sync_h1_conn(is_https, host, port, proxy, roots, sync_timeout_ms)
664            {
665                (cached, true)
666            } else {
667                (
668                    self.open_sync_stream(host.to_owned(), port, is_https)?,
669                    false,
670                )
671            };
672            let write_res: Result<(), RequestError> = stream
673                .write_all(request_bytes)
674                .and_then(|_: ()| stream.flush())
675                .map_err(|e: io::Error| RequestError::Request(e.to_string()));
676            if let Err(error) = write_res {
677                if from_pool {
678                    attempted_pooled = true;
679                    continue;
680                }
681                return Err(error);
682            }
683            match self.read_response_once_sync(&mut stream, is_head, disable_keep_alive) {
684                Ok((response, redirect_url, reusable)) => {
685                    if reusable && !disable_keep_alive {
686                        put_sync_h1_conn(
687                            is_https,
688                            host,
689                            port,
690                            proxy,
691                            roots,
692                            sync_timeout_ms,
693                            stream,
694                        );
695                    }
696                    return Ok((response, redirect_url));
697                }
698                Err(error) => {
699                    if from_pool && is_retryable_error(&error) {
700                        attempted_pooled = true;
701                        continue;
702                    }
703                    return Err(error);
704                }
705            }
706        }
707    }
708
709    /// Asynchronous send with H1/H2 pooling, idempotent retries, timeout enforcement, and iterative redirects.
710    ///
711    /// # Returns
712    ///
713    /// - `Result<HttpResponse, RequestError>` - The parsed HTTP response, or a `RequestError` on failure.
714    async fn send_async_impl(&mut self) -> Result<HttpResponse, RequestError> {
715        let mut redirect_started: bool = false;
716        loop {
717            let is_h2: bool = *self.get_config().get_http_version() == HttpVersion::Http2;
718            let mut owned_url: Option<HttpUrlComponents> = None;
719            let owned_host: String;
720            let owned_path: String;
721            let owned_query: String;
722            let target: FastUrlParts<'_> = if !is_h2
723                && let Some(fast) = parse_url_fast(self.get_url())
724            {
725                fast
726            } else {
727                let parsed: HttpUrlComponents = self.parse_url()?;
728                let is_https: bool = Self::scheme_is_https(&parsed);
729                owned_host = parsed.get_host().unwrap_or_default();
730                owned_path = parsed.get_path().unwrap_or_default();
731                owned_query = parsed.get_query().unwrap_or_default();
732                let port: u16 =
733                    Self::resolve_port_for_scheme(parsed.get_port().unwrap_or_default(), is_https);
734                owned_url = Some(parsed);
735                FastUrlParts {
736                    is_https,
737                    host: owned_host.as_str(),
738                    port,
739                    path: owned_path.as_str(),
740                    query: owned_query.as_str(),
741                }
742            };
743            validate_request_headers(self.get_headers())?;
744            let (method_token, is_head): (Cow<'static, str>, bool) =
745                self.validated_http_method()?;
746            let mut request_bytes: Option<Vec<u8>> = if is_h2 {
747                None
748            } else {
749                let version: &str = self.validated_http_version()?;
750                let mut wire_buf: Vec<u8> = take_client_buffer(256);
751                if let Err(error) = build_wire_request_parts_into(
752                    self,
753                    &target,
754                    method_token.as_ref(),
755                    is_head,
756                    version,
757                    &mut wire_buf,
758                ) {
759                    return_client_buffer(wire_buf);
760                    return Err(error);
761                }
762                Some(wire_buf)
763            };
764            let timeout_ms: u64 = self.get_config().get_timeout();
765            let max_retries: usize = if is_idempotent_method(&self.get_method()) {
766                self.get_config().get_max_retries()
767            } else {
768                0
769            };
770            let mut attempt: usize = 0;
771            let exchange_result: Result<(HttpResponse, Option<Vec<u8>>), RequestError> = loop {
772                let attempt_res: Result<(HttpResponse, Option<Vec<u8>>), RequestError> = if is_h2 {
773                    let url_ref: &HttpUrlComponents = match owned_url.as_ref() {
774                        Some(parsed) => parsed,
775                        None => return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest)),
776                    };
777                    let pool_key: PoolKey = make_pool_key(
778                        target.is_https,
779                        target.host,
780                        target.port,
781                        self.get_config().get_proxy().as_ref(),
782                        self.get_tmp().get_root_cert(),
783                        0,
784                    );
785                    let h2_target: H2ExchangeTarget<'_> = H2ExchangeTarget {
786                        url_obj: url_ref,
787                        method_token: method_token.as_ref(),
788                        is_head,
789                        host: target.host,
790                        port: target.port,
791                        is_https: target.is_https,
792                        pool_key,
793                    };
794                    if timeout_ms > 0 {
795                        match tokio::time::timeout(
796                            Duration::from_millis(timeout_ms),
797                            send_h2_exchange_async(self, h2_target),
798                        )
799                        .await
800                        {
801                            Ok(inner) => inner,
802                            Err(_) => Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout)),
803                        }
804                    } else {
805                        send_h2_exchange_async(self, h2_target).await
806                    }
807                } else {
808                    let wire: &[u8] = request_bytes.as_deref().unwrap_or_default();
809                    if timeout_ms > 0 {
810                        match tokio::time::timeout(
811                            Duration::from_millis(timeout_ms),
812                            self.exchange_async_once(
813                                target.host,
814                                target.port,
815                                target.is_https,
816                                wire,
817                                is_head,
818                            ),
819                        )
820                        .await
821                        {
822                            Ok(inner) => inner,
823                            Err(_) => Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout)),
824                        }
825                    } else {
826                        self.exchange_async_once(
827                            target.host,
828                            target.port,
829                            target.is_https,
830                            wire,
831                            is_head,
832                        )
833                        .await
834                    }
835                };
836                match attempt_res {
837                    Ok((resp, redir)) => {
838                        if attempt < max_retries && is_retryable_status(resp.get_status_code()) {
839                            tokio::time::sleep(retry_backoff_duration(attempt)).await;
840                            attempt += 1;
841                            continue;
842                        }
843                        break Ok((resp, redir));
844                    }
845                    Err(error) => {
846                        if attempt < max_retries && is_retryable_error(&error) {
847                            tokio::time::sleep(retry_backoff_duration(attempt)).await;
848                            attempt += 1;
849                            continue;
850                        }
851                        break Err(error);
852                    }
853                }
854            };
855            if let Some(wire_buf) = request_bytes.take() {
856                return_client_buffer(wire_buf);
857            }
858            let (mut response, redirect_url): (HttpResponse, Option<Vec<u8>>) = exchange_result?;
859            if !self.get_config().get_redirect() || redirect_url.is_none() {
860                if !is_head && self.get_config().get_decode() {
861                    response.decode_in_place(self.effective_buffer_size());
862                }
863                return Ok(response);
864            }
865            if !redirect_started {
866                redirect_started = true;
867                let initial_url: String = self.get_url().to_owned();
868                self.get_mut_tmp().get_mut_visit_url().insert(initial_url);
869            }
870            let url_obj: HttpUrlComponents = match owned_url {
871                Some(parsed) => parsed,
872                None => self.parse_url()?,
873            };
874            let url_bytes: Vec<u8> = redirect_url
875                .ok_or_else(|| RequestError::Request(MISSING_REDIRECT_URL.to_string()))?;
876            let location: String = String::from_utf8(url_bytes)
877                .map_err(|e: FromUtf8Error| RequestError::Request(e.to_string()))?;
878            self.prepare_redirect_hop(&url_obj, response.get_status_code(), location)?;
879        }
880    }
881
882    /// Execute one asynchronous HTTP/1 exchange using the idle keep-alive pool with transparent stale redial.
883    ///
884    /// # Arguments
885    ///
886    /// - `&str` - Target host.
887    /// - `u16` - Target TCP port.
888    /// - `bool` - Whether to establish a TLS session.
889    /// - `&[u8]` - Prebuilt wire request bytes.
890    /// - `bool` - Whether the request method is `HEAD`.
891    ///
892    /// # Returns
893    ///
894    /// - `Result<(HttpResponse, Option<Vec<u8>>), RequestError>` - Response and optional redirect location.
895    async fn exchange_async_once(
896        &self,
897        host: &str,
898        port: u16,
899        is_https: bool,
900        request_bytes: &[u8],
901        is_head: bool,
902    ) -> Result<(HttpResponse, Option<Vec<u8>>), RequestError> {
903        let disable_keep_alive: bool = request_disables_keep_alive(self);
904        let proxy_opt: Option<Proxy> = self.get_config().get_proxy();
905        let proxy: Option<&Proxy> = proxy_opt.as_ref();
906        let roots: &RootCertStore = self.get_tmp().get_root_cert();
907        let mut attempted_pooled: bool = false;
908        loop {
909            let (mut stream, from_pool): (Box<dyn AsyncReadWrite>, bool) = if !disable_keep_alive
910                && !attempted_pooled
911                && let Some(cached) = take_async_h1_conn(is_https, host, port, proxy, roots)
912            {
913                (cached, true)
914            } else {
915                (
916                    self.open_async_stream(host.to_owned(), port, is_https)
917                        .await?,
918                    false,
919                )
920            };
921            let write_res: Result<(), RequestError> = match stream.write_all(request_bytes).await {
922                Ok(()) => stream
923                    .flush()
924                    .await
925                    .map_err(|e: io::Error| RequestError::Request(e.to_string())),
926                Err(error) => Err(RequestError::Request(error.to_string())),
927            };
928            if let Err(error) = write_res {
929                if from_pool {
930                    attempted_pooled = true;
931                    continue;
932                }
933                return Err(error);
934            }
935            match self
936                .read_response_once_async(&mut stream, is_head, disable_keep_alive)
937                .await
938            {
939                Ok((response, redirect_url, reusable)) => {
940                    if reusable && !disable_keep_alive {
941                        put_async_h1_conn(is_https, host, port, proxy, roots, stream);
942                    }
943                    return Ok((response, redirect_url));
944                }
945                Err(error) => {
946                    if from_pool && is_retryable_error(&error) {
947                        attempted_pooled = true;
948                        continue;
949                    }
950                    return Err(error);
951                }
952            }
953        }
954    }
955
956    /// Connect a synchronous TCP stream with `TCP_NODELAY` and optional connect/read/write timeouts.
957    ///
958    /// # Arguments
959    ///
960    /// - `&str` - Hostname or IP literal (brackets stripped automatically).
961    /// - `u16` - Target TCP port.
962    ///
963    /// # Returns
964    ///
965    /// - `Result<TcpStream, RequestError>` - Connected TCP stream with timeouts configured.
966    fn connect_sync_tcp(&self, host: &str, port: u16) -> Result<TcpStream, RequestError> {
967        let clean_host: &str = Self::strip_ipv6_brackets(host);
968        let connect_ms: u64 = self.effective_connect_timeout_ms();
969        let io_timeout_ms: u64 = self.get_config().get_timeout();
970        let tcp: TcpStream = if connect_ms > 0 {
971            let connect_dur: Duration = Duration::from_millis(connect_ms);
972            let addrs: Vec<SocketAddr> = (clean_host, port)
973                .to_socket_addrs()
974                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?
975                .collect();
976            let mut last_err: Option<io::Error> = None;
977            let mut connected: Option<TcpStream> = None;
978            for addr in addrs {
979                match TcpStream::connect_timeout(&addr, connect_dur) {
980                    Ok(stream) => {
981                        connected = Some(stream);
982                        break;
983                    }
984                    Err(error) => {
985                        last_err = Some(error);
986                    }
987                }
988            }
989            match connected {
990                Some(stream) => stream,
991                None => {
992                    return Err(RequestError::Request(
993                        last_err
994                            .map(|e: io::Error| e.to_string())
995                            .unwrap_or_else(|| INTERNAL_SERVER_ERROR.to_owned()),
996                    ));
997                }
998            }
999        } else {
1000            TcpStream::connect((clean_host, port))
1001                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?
1002        };
1003        let _: Result<(), io::Error> = tcp.set_nodelay(true);
1004        if io_timeout_ms > 0 {
1005            let io_dur: Duration = Duration::from_millis(io_timeout_ms);
1006            tcp.set_read_timeout(Some(io_dur))
1007                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1008            tcp.set_write_timeout(Some(io_dur))
1009                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1010        }
1011        Ok(tcp)
1012    }
1013
1014    /// Connect an asynchronous TCP stream with `TCP_NODELAY` and optional connect timeout.
1015    ///
1016    /// # Arguments
1017    ///
1018    /// - `&str` - Hostname or IP literal (brackets stripped automatically).
1019    /// - `u16` - Target TCP port.
1020    ///
1021    /// # Returns
1022    ///
1023    /// - `Result<tokio::net::TcpStream, RequestError>` - Connected async TCP stream.
1024    async fn connect_async_tcp(
1025        &self,
1026        host: &str,
1027        port: u16,
1028    ) -> Result<tokio::net::TcpStream, RequestError> {
1029        let clean_host: String = Self::strip_ipv6_brackets(host).to_owned();
1030        let connect_ms: u64 = self.effective_connect_timeout_ms();
1031        let tcp: tokio::net::TcpStream = if connect_ms > 0 {
1032            tokio::time::timeout(
1033                Duration::from_millis(connect_ms),
1034                tokio::net::TcpStream::connect((clean_host, port)),
1035            )
1036            .await
1037            .map_err(|_| RequestError::ReadTimeout(HttpStatus::RequestTimeout))?
1038            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?
1039        } else {
1040            tokio::net::TcpStream::connect((clean_host, port))
1041                .await
1042                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?
1043        };
1044        let _: Result<(), io::Error> = tcp.set_nodelay(true);
1045        Ok(tcp)
1046    }
1047
1048    /// Open a synchronous stream to the target host, directly or through a proxy.
1049    ///
1050    /// # Arguments
1051    ///
1052    /// - `String` - The target host name or IP address.
1053    /// - `u16` - The target TCP port.
1054    /// - `bool` - Whether the target URL requires TLS.
1055    ///
1056    /// # Returns
1057    ///
1058    /// - `Result<Box<dyn ReadWrite>, RequestError>` - The connected stream, TLS-wrapped for HTTPS, or a `RequestError` on failure.
1059    fn open_sync_stream(
1060        &self,
1061        host: String,
1062        port: u16,
1063        is_https: bool,
1064    ) -> Result<Box<dyn ReadWrite>, RequestError> {
1065        if let Some(proxy) = &self.get_config().get_proxy() {
1066            return self.open_sync_proxy_stream(host, port, is_https, proxy);
1067        }
1068        let tcp: TcpStream = self.connect_sync_tcp(&host, port)?;
1069        if is_https {
1070            let tls_cfg: Arc<ClientConfig> = self.tls_client_config();
1071            let dns: ServerName<'static> = Self::server_name_for_host(&host)?;
1072            let session: ClientConnection = ClientConnection::new(tls_cfg, dns)
1073                .map_err(|e: Error| RequestError::Request(e.to_string()))?;
1074            Ok(Box::new(StreamOwned::new(session, tcp)))
1075        } else {
1076            Ok(Box::new(tcp))
1077        }
1078    }
1079
1080    /// Reads one HTTP/1 response synchronously with pooled scratch buffers and keep-alive reuse detection.
1081    ///
1082    /// # Arguments
1083    ///
1084    /// - `&mut Box<dyn ReadWrite>` - The connected stream to read the response from.
1085    /// - `bool` - Whether this response answers a HEAD request.
1086    /// - `bool` - Whether the caller disabled keep-alive.
1087    ///
1088    /// # Returns
1089    ///
1090    /// - `Result<(HttpResponse, Option<Vec<u8>>, bool), RequestError>` - Response, optional redirect target, and pool reusability flag.
1091    fn read_response_once_sync(
1092        &self,
1093        stream: &mut Box<dyn ReadWrite>,
1094        is_head: bool,
1095        disable_keep_alive: bool,
1096    ) -> Result<(HttpResponse, Option<Vec<u8>>, bool), RequestError> {
1097        let buffer_size: usize = self.effective_buffer_size();
1098        let mut buffer: Vec<u8> = take_client_buffer(buffer_size);
1099        buffer.resize(buffer_size, 0u8);
1100        let mut response_bytes: Vec<u8> = take_client_buffer(buffer_size.max(8192));
1101        let mut head: Option<FinalResponseHead> = None;
1102        let mut interim_count: usize = 0;
1103        let mut read_error: Option<RequestError> = None;
1104        loop {
1105            let n: usize = match stream.read(&mut buffer) {
1106                Ok(n) => n,
1107                Err(error) => {
1108                    read_error = Some(RequestError::Request(error.to_string()));
1109                    break;
1110                }
1111            };
1112            if n == 0 {
1113                break;
1114            }
1115            let new_cap: usize =
1116                calculate_buffer_capacity(&response_bytes, n, response_bytes.capacity());
1117            if new_cap > 0 {
1118                response_bytes.reserve(new_cap.saturating_sub(response_bytes.capacity()));
1119            }
1120            let old_len: usize = response_bytes.len();
1121            response_bytes.extend_from_slice(&buffer[..n]);
1122            if head.is_none() {
1123                match find_final_response_head(
1124                    &mut response_bytes,
1125                    old_len.saturating_sub(3),
1126                    is_head,
1127                    &mut interim_count,
1128                ) {
1129                    Ok(found) => head = found,
1130                    Err(error) => {
1131                        read_error = Some(error);
1132                        break;
1133                    }
1134                }
1135            }
1136            if let Some((end, framing, _)) = &head {
1137                let body_slice: &[u8] = &response_bytes[*end..];
1138                if body_slice.len() > MAX_RESPONSE_BODY_BYTES {
1139                    read_error = Some(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
1140                    break;
1141                }
1142                match response_body_is_complete(*framing, body_slice) {
1143                    Ok(true) => break,
1144                    Ok(false) => {}
1145                    Err(error) => {
1146                        read_error = Some(error);
1147                        break;
1148                    }
1149                }
1150            }
1151        }
1152        return_client_buffer(buffer);
1153        if let Some(error) = read_error {
1154            return_client_buffer(response_bytes);
1155            return Err(error);
1156        }
1157        let Some((head_end, framing, redirect_url)) = head else {
1158            return_client_buffer(response_bytes);
1159            return Err(RequestError::HttpRequestPartsInsufficient(
1160                HttpStatus::BadRequest,
1161            ));
1162        };
1163        let body_slice: &[u8] = &response_bytes[head_end..];
1164        let has_trailing: bool = match framing {
1165            ResponseFraming::Fixed(len) => body_slice.len() != len,
1166            ResponseFraming::Chunked => match chunked_body_end(body_slice) {
1167                Ok(Some(end)) => end != body_slice.len(),
1168                _ => true,
1169            },
1170            ResponseFraming::Close => true,
1171        };
1172        let reusable: bool = response_allows_pool_reuse(
1173            &response_bytes[..head_end],
1174            framing,
1175            has_trailing,
1176            disable_keep_alive,
1177        );
1178        let parsed: Result<HttpResponse, RequestError> =
1179            finish_framed_response(&response_bytes, head_end, framing);
1180        return_client_buffer(response_bytes);
1181        let response: HttpResponse = parsed?;
1182        Ok((response, redirect_url, reusable))
1183    }
1184
1185    /// Open an asynchronous HTTP/1 stream to the target host, directly or through a proxy.
1186    ///
1187    /// # Arguments
1188    ///
1189    /// - `String` - The target host name or IP address.
1190    /// - `u16` - The target TCP port.
1191    /// - `bool` - Whether the target URL requires TLS.
1192    ///
1193    /// # Returns
1194    ///
1195    /// - `Result<Box<dyn AsyncReadWrite>, RequestError>` - The connected stream, TLS-wrapped for HTTPS, or a `RequestError` on failure.
1196    async fn open_async_stream(
1197        &self,
1198        host: String,
1199        port: u16,
1200        is_https: bool,
1201    ) -> Result<Box<dyn AsyncReadWrite>, RequestError> {
1202        if let Some(proxy) = &self.get_config().get_proxy() {
1203            return self
1204                .open_async_proxy_stream(host, port, is_https, proxy, false)
1205                .await;
1206        }
1207        let tcp: tokio::net::TcpStream = self.connect_async_tcp(&host, port).await?;
1208        if is_https {
1209            let connector: TlsConnector = TlsConnector::from(self.tls_client_config());
1210            let dns: ServerName<'static> = Self::server_name_for_host(&host)?;
1211            let tls: TlsStream<tokio::net::TcpStream> = connector
1212                .connect(dns, tcp)
1213                .await
1214                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1215            Ok(Box::new(tls))
1216        } else {
1217            Ok(Box::new(tcp))
1218        }
1219    }
1220
1221    /// Open an asynchronous HTTP/2 (`h2` ALPN over TLS or cleartext `h2c`) transport stream.
1222    ///
1223    /// # Arguments
1224    ///
1225    /// - `&str` - Target host name or IP address.
1226    /// - `u16` - Target TCP port.
1227    /// - `bool` - Whether to negotiate TLS + `h2` ALPN (`false` uses cleartext `h2c`).
1228    ///
1229    /// # Returns
1230    ///
1231    /// - `Result<Box<dyn AsyncReadWrite>, RequestError>` - Connected transport ready for `h2::client::handshake`.
1232    pub(crate) async fn open_async_stream_h2(
1233        &self,
1234        host: &str,
1235        port: u16,
1236        is_https: bool,
1237    ) -> Result<Box<dyn AsyncReadWrite>, RequestError> {
1238        if let Some(proxy) = &self.get_config().get_proxy() {
1239            return self
1240                .open_async_proxy_stream(host.to_owned(), port, is_https, proxy, true)
1241                .await;
1242        }
1243        let tcp: tokio::net::TcpStream = self.connect_async_tcp(host, port).await?;
1244        if is_https {
1245            let connector: TlsConnector = TlsConnector::from(self.tls_client_config_h2());
1246            let dns: ServerName<'static> = Self::server_name_for_host(host)?;
1247            let tls: TlsStream<tokio::net::TcpStream> = connector
1248                .connect(dns, tcp)
1249                .await
1250                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1251            if tls.get_ref().1.alpn_protocol() != Some(ALPN_H2) {
1252                return Err(RequestError::Request(H2_ALPN_MISMATCH.to_owned()));
1253            }
1254            Ok(Box::new(tls))
1255        } else {
1256            Ok(Box::new(tcp))
1257        }
1258    }
1259
1260    /// Reads one HTTP/1 response asynchronously with pooled scratch buffers and keep-alive reuse detection.
1261    ///
1262    /// # Arguments
1263    ///
1264    /// - `&mut Box<dyn AsyncReadWrite>` - The connected stream to read the response from.
1265    /// - `bool` - Whether this response answers a HEAD request.
1266    /// - `bool` - Whether the caller disabled keep-alive.
1267    ///
1268    /// # Returns
1269    ///
1270    /// - `Result<(HttpResponse, Option<Vec<u8>>, bool), RequestError>` - Response, optional redirect target, and pool reusability flag.
1271    async fn read_response_once_async(
1272        &self,
1273        stream: &mut Box<dyn AsyncReadWrite>,
1274        is_head: bool,
1275        disable_keep_alive: bool,
1276    ) -> Result<(HttpResponse, Option<Vec<u8>>, bool), RequestError> {
1277        let buffer_size: usize = self.effective_buffer_size();
1278        let mut response_bytes: Vec<u8> = take_client_buffer(buffer_size.max(8192));
1279        let mut head: Option<FinalResponseHead> = None;
1280        let mut interim_count: usize = 0;
1281        let mut read_error: Option<RequestError> = None;
1282        loop {
1283            if response_bytes.capacity() - response_bytes.len() < buffer_size.min(4096) {
1284                let new_cap: usize = calculate_buffer_capacity(
1285                    &response_bytes,
1286                    buffer_size,
1287                    response_bytes.capacity(),
1288                );
1289                if new_cap > 0 {
1290                    response_bytes.reserve(new_cap.saturating_sub(response_bytes.capacity()));
1291                }
1292            }
1293            let old_len: usize = response_bytes.len();
1294            let n: usize = match stream.read_buf(&mut response_bytes).await {
1295                Ok(n) => n,
1296                Err(error) => {
1297                    read_error = Some(RequestError::Request(error.to_string()));
1298                    break;
1299                }
1300            };
1301            if n == 0 {
1302                break;
1303            }
1304            if head.is_none() {
1305                match find_final_response_head(
1306                    &mut response_bytes,
1307                    old_len.saturating_sub(3),
1308                    is_head,
1309                    &mut interim_count,
1310                ) {
1311                    Ok(found) => head = found,
1312                    Err(error) => {
1313                        read_error = Some(error);
1314                        break;
1315                    }
1316                }
1317            }
1318            if let Some((end, framing, _)) = &head {
1319                let body_slice: &[u8] = &response_bytes[*end..];
1320                if body_slice.len() > MAX_RESPONSE_BODY_BYTES {
1321                    read_error = Some(RequestError::ContentLengthTooLarge(HttpStatus::BadRequest));
1322                    break;
1323                }
1324                match response_body_is_complete(*framing, body_slice) {
1325                    Ok(true) => break,
1326                    Ok(false) => {}
1327                    Err(error) => {
1328                        read_error = Some(error);
1329                        break;
1330                    }
1331                }
1332            }
1333        }
1334        if let Some(error) = read_error {
1335            return_client_buffer(response_bytes);
1336            return Err(error);
1337        }
1338        let Some((head_end, framing, redirect_url)) = head else {
1339            return_client_buffer(response_bytes);
1340            return Err(RequestError::HttpRequestPartsInsufficient(
1341                HttpStatus::BadRequest,
1342            ));
1343        };
1344        let body_slice: &[u8] = &response_bytes[head_end..];
1345        let has_trailing: bool = match framing {
1346            ResponseFraming::Fixed(len) => body_slice.len() != len,
1347            ResponseFraming::Chunked => match chunked_body_end(body_slice) {
1348                Ok(Some(end)) => end != body_slice.len(),
1349                _ => true,
1350            },
1351            ResponseFraming::Close => true,
1352        };
1353        let reusable: bool = response_allows_pool_reuse(
1354            &response_bytes[..head_end],
1355            framing,
1356            has_trailing,
1357            disable_keep_alive,
1358        );
1359        let parsed: Result<HttpResponse, RequestError> =
1360            finish_framed_response(&response_bytes, head_end, framing);
1361        return_client_buffer(response_bytes);
1362        let response: HttpResponse = parsed?;
1363        Ok((response, redirect_url, reusable))
1364    }
1365
1366    /// Open a synchronous stream to the target through the configured proxy.
1367    ///
1368    /// # Arguments
1369    ///
1370    /// - `String` - The target host name or IP address.
1371    /// - `u16` - The target TCP port.
1372    /// - `bool` - Whether the target URL requires TLS over the tunnel.
1373    /// - `&Proxy` - The proxy configuration selecting the HTTP or SOCKS5 handshake.
1374    ///
1375    /// # Returns
1376    ///
1377    /// - `Result<Box<dyn ReadWrite>, RequestError>` - The tunnelled stream, or a `RequestError` when the handshake fails.
1378    fn open_sync_proxy_stream(
1379        &self,
1380        target_host: String,
1381        target_port: u16,
1382        is_https: bool,
1383        proxy: &Proxy,
1384    ) -> Result<Box<dyn ReadWrite>, RequestError> {
1385        match *proxy.get_proxy_type() {
1386            ProxyType::Http | ProxyType::Https => {
1387                self.open_sync_http_proxy(target_host, target_port, is_https, proxy)
1388            }
1389            ProxyType::Socks5 => {
1390                self.open_sync_socks5_proxy(target_host, target_port, is_https, proxy)
1391            }
1392        }
1393    }
1394
1395    /// Open a synchronous stream to the target through an HTTP or HTTPS proxy.
1396    ///
1397    /// # Arguments
1398    ///
1399    /// - `String` - The target host name or IP address.
1400    /// - `u16` - The target TCP port.
1401    /// - `bool` - Whether the target URL requires TLS over the tunnel.
1402    /// - `&Proxy` - The proxy configuration.
1403    ///
1404    /// # Returns
1405    ///
1406    /// - `Result<Box<dyn ReadWrite>, RequestError>` - The tunnelled stream, or a `RequestError` when the handshake fails.
1407    fn open_sync_http_proxy(
1408        &self,
1409        target_host: String,
1410        target_port: u16,
1411        is_https: bool,
1412        proxy: &Proxy,
1413    ) -> Result<Box<dyn ReadWrite>, RequestError> {
1414        let connect_request: String =
1415            Self::build_connect_request(&target_host, target_port, proxy)?;
1416        let tcp: TcpStream = self.connect_sync_tcp(proxy.get_host(), proxy.get_port())?;
1417        let mut proxy_stream: Box<dyn ReadWrite> = if proxy.get_proxy_type() == &ProxyType::Https {
1418            let tls_cfg: Arc<ClientConfig> = self.tls_client_config();
1419            let dns: ServerName<'static> = Self::server_name_for_host(proxy.get_host())?;
1420            let session: ClientConnection = ClientConnection::new(tls_cfg, dns)
1421                .map_err(|e: Error| RequestError::Request(e.to_string()))?;
1422            Box::new(StreamOwned::new(session, tcp))
1423        } else {
1424            Box::new(tcp)
1425        };
1426        proxy_stream
1427            .write_all(connect_request.as_bytes())
1428            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1429        proxy_stream
1430            .flush()
1431            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1432        let mut raw_resp: Vec<u8> = Vec::with_capacity(512);
1433        let mut chunk: [u8; 512] = [0u8; 512];
1434        let head_end: usize = loop {
1435            if let Some(pos) = find_double_crlf(&raw_resp, 0) {
1436                break pos;
1437            }
1438            if raw_resp.len() >= MAX_CONNECT_HEAD_BYTES {
1439                return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1440            }
1441            let n: usize = proxy_stream
1442                .read(&mut chunk)
1443                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1444            if n == 0 {
1445                return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1446            }
1447            raw_resp.extend_from_slice(&chunk[..n]);
1448        };
1449        if !Self::is_connect_success_head(&raw_resp[..head_end]) {
1450            return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1451        }
1452        let pre_read: Vec<u8> = raw_resp[head_end + 4..].to_vec();
1453        if is_https {
1454            let tls_cfg: Arc<ClientConfig> = self.tls_client_config();
1455            let dns: ServerName<'static> = Self::server_name_for_host(&target_host)?;
1456            let session: ClientConnection = ClientConnection::new(tls_cfg, dns)
1457                .map_err(|e: Error| RequestError::Request(e.to_string()))?;
1458            let tunnel: SyncProxyTunnelStream = SyncProxyTunnelStream::new(proxy_stream, pre_read);
1459            return Ok(Box::new(StreamOwned::new(session, tunnel)));
1460        }
1461        Ok(Box::new(SyncProxyTunnelStream::new(proxy_stream, pre_read)))
1462    }
1463
1464    /// Open a synchronous stream to the target through a SOCKS5 proxy.
1465    ///
1466    /// # Arguments
1467    ///
1468    /// - `String` - The target host name or IP address.
1469    /// - `u16` - The target TCP port.
1470    /// - `bool` - Whether the target URL requires TLS over the tunnel.
1471    /// - `&Proxy` - The proxy configuration.
1472    ///
1473    /// # Returns
1474    ///
1475    /// - `Result<Box<dyn ReadWrite>, RequestError>` - The tunnelled stream, or a `RequestError` when the handshake fails.
1476    fn open_sync_socks5_proxy(
1477        &self,
1478        target_host: String,
1479        target_port: u16,
1480        is_https: bool,
1481        proxy: &Proxy,
1482    ) -> Result<Box<dyn ReadWrite>, RequestError> {
1483        let has_auth: bool = proxy.get_username().is_some() && proxy.get_password().is_some();
1484        if let (Some(u), Some(p)) = (proxy.get_username(), proxy.get_password())
1485            && (u.len() > usize::from(u8::MAX) || p.len() > usize::from(u8::MAX))
1486        {
1487            return Err(RequestError::Request(PROXY_AUTH_ERROR.to_owned()));
1488        }
1489        let clean_target: &str = Self::strip_ipv6_brackets(&target_host);
1490        let mut connect_req: Vec<u8> = vec![0x05, 0x01, 0x00];
1491        if let Ok(ip) = clean_target.parse::<Ipv4Addr>() {
1492            connect_req.push(0x01);
1493            connect_req.extend_from_slice(&ip.octets());
1494        } else if let Ok(ip) = clean_target.parse::<Ipv6Addr>() {
1495            connect_req.push(0x04);
1496            connect_req.extend_from_slice(&ip.octets());
1497        } else {
1498            let host_len: u8 = u8::try_from(clean_target.len())
1499                .map_err(|_| RequestError::Request(PROXY_AUTH_ERROR.to_owned()))?;
1500            connect_req.push(0x03);
1501            connect_req.push(host_len);
1502            connect_req.extend_from_slice(clean_target.as_bytes());
1503        }
1504        connect_req.extend_from_slice(&target_port.to_be_bytes());
1505        let mut tcp: TcpStream = self.connect_sync_tcp(proxy.get_host(), proxy.get_port())?;
1506        let auth_methods: [u8; 3] = if has_auth {
1507            [0x05, 0x01, 0x02]
1508        } else {
1509            [0x05, 0x01, 0x00]
1510        };
1511        tcp.write_all(&auth_methods)
1512            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1513        let mut resp: [u8; 2] = [0u8; 2];
1514        tcp.read_exact(&mut resp)
1515            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1516        if resp[0] != 0x05 {
1517            return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1518        }
1519        match resp[1] {
1520            0x00 if !has_auth => {}
1521            0x02 => {
1522                let (Some(u), Some(p)) = (proxy.get_username(), proxy.get_password()) else {
1523                    return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1524                };
1525                let mut auth_req: Vec<u8> = Vec::with_capacity(3 + u.len() + p.len());
1526                auth_req.push(0x01);
1527                auth_req.push(u.len() as u8);
1528                auth_req.extend_from_slice(u.as_bytes());
1529                auth_req.push(p.len() as u8);
1530                auth_req.extend_from_slice(p.as_bytes());
1531                tcp.write_all(&auth_req)
1532                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1533                let mut auth_resp: [u8; 2] = [0u8; 2];
1534                tcp.read_exact(&mut auth_resp)
1535                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1536                if auth_resp[0] != 0x01 || auth_resp[1] != 0x00 {
1537                    return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1538                }
1539            }
1540            _ => return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string())),
1541        }
1542        tcp.write_all(&connect_req)
1543            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1544        let mut connect_resp: [u8; 4] = [0u8; 4];
1545        tcp.read_exact(&mut connect_resp)
1546            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1547        if connect_resp[0] != 0x05 || connect_resp[1] != 0x00 {
1548            return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1549        }
1550        match connect_resp[3] {
1551            0x01 => {
1552                let mut skip: [u8; 6] = [0u8; 6];
1553                tcp.read_exact(&mut skip)
1554                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1555            }
1556            0x03 => {
1557                let mut len: [u8; 1] = [0u8; 1];
1558                tcp.read_exact(&mut len)
1559                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1560                let mut skip: Vec<u8> = vec![0u8; len[0] as usize + 2];
1561                tcp.read_exact(&mut skip)
1562                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1563            }
1564            0x04 => {
1565                let mut skip: [u8; 18] = [0u8; 18];
1566                tcp.read_exact(&mut skip)
1567                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1568            }
1569            _ => return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string())),
1570        }
1571        if is_https {
1572            let tls_cfg: Arc<ClientConfig> = self.tls_client_config();
1573            let dns: ServerName<'static> = Self::server_name_for_host(&target_host)?;
1574            let session: ClientConnection = ClientConnection::new(tls_cfg, dns)
1575                .map_err(|e: Error| RequestError::Request(e.to_string()))?;
1576            let proxy_box: Box<dyn ReadWrite> = Box::new(tcp);
1577            let tunnel: SyncProxyTunnelStream = SyncProxyTunnelStream::new(proxy_box, Vec::new());
1578            return Ok(Box::new(StreamOwned::new(session, tunnel)));
1579        }
1580        Ok(Box::new(tcp))
1581    }
1582
1583    /// Open an asynchronous stream to the target through the configured proxy.
1584    ///
1585    /// # Arguments
1586    ///
1587    /// - `String` - The target host name or IP address.
1588    /// - `u16` - The target TCP port.
1589    /// - `bool` - Whether the target URL requires TLS over the tunnel.
1590    /// - `&Proxy` - The proxy configuration selecting the HTTP or SOCKS5 handshake.
1591    /// - `bool` - Whether to negotiate `h2` ALPN on target TLS handshakes.
1592    ///
1593    /// # Returns
1594    ///
1595    /// - `Result<Box<dyn AsyncReadWrite>, RequestError>` - The tunnelled stream, or a `RequestError` when the handshake fails.
1596    async fn open_async_proxy_stream(
1597        &self,
1598        target_host: String,
1599        target_port: u16,
1600        is_https: bool,
1601        proxy: &Proxy,
1602        enable_h2: bool,
1603    ) -> Result<Box<dyn AsyncReadWrite>, RequestError> {
1604        match *proxy.get_proxy_type() {
1605            ProxyType::Http | ProxyType::Https => {
1606                self.open_async_http_proxy(target_host, target_port, is_https, proxy, enable_h2)
1607                    .await
1608            }
1609            ProxyType::Socks5 => {
1610                self.open_async_socks5_proxy(target_host, target_port, is_https, proxy, enable_h2)
1611                    .await
1612            }
1613        }
1614    }
1615
1616    /// Open an asynchronous stream to the target through an HTTP or HTTPS proxy.
1617    ///
1618    /// # Arguments
1619    ///
1620    /// - `String` - The target host name or IP address.
1621    /// - `u16` - The target TCP port.
1622    /// - `bool` - Whether the target URL requires TLS over the tunnel.
1623    /// - `&Proxy` - The proxy configuration.
1624    /// - `bool` - Whether to negotiate `h2` ALPN on target TLS handshakes.
1625    ///
1626    /// # Returns
1627    ///
1628    /// - `Result<Box<dyn AsyncReadWrite>, RequestError>` - The tunnelled stream, or a `RequestError` when the handshake fails.
1629    async fn open_async_http_proxy(
1630        &self,
1631        target_host: String,
1632        target_port: u16,
1633        is_https: bool,
1634        proxy: &Proxy,
1635        enable_h2: bool,
1636    ) -> Result<Box<dyn AsyncReadWrite>, RequestError> {
1637        let connect_request: String =
1638            Self::build_connect_request(&target_host, target_port, proxy)?;
1639        let tcp: tokio::net::TcpStream = self
1640            .connect_async_tcp(proxy.get_host(), proxy.get_port())
1641            .await?;
1642        let mut proxy_stream: Box<dyn AsyncReadWrite> =
1643            if proxy.get_proxy_type() == &ProxyType::Https {
1644                let connector: TlsConnector = TlsConnector::from(self.tls_client_config());
1645                let dns: ServerName<'static> = Self::server_name_for_host(proxy.get_host())?;
1646                let tls: TlsStream<tokio::net::TcpStream> = connector
1647                    .connect(dns, tcp)
1648                    .await
1649                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1650                Box::new(tls)
1651            } else {
1652                Box::new(tcp)
1653            };
1654        proxy_stream
1655            .write_all(connect_request.as_bytes())
1656            .await
1657            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1658        proxy_stream
1659            .flush()
1660            .await
1661            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1662        let mut raw_resp: Vec<u8> = Vec::with_capacity(512);
1663        let mut chunk: [u8; 512] = [0u8; 512];
1664        let head_end: usize = loop {
1665            if let Some(pos) = find_double_crlf(&raw_resp, 0) {
1666                break pos;
1667            }
1668            if raw_resp.len() >= MAX_CONNECT_HEAD_BYTES {
1669                return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1670            }
1671            let n: usize = proxy_stream
1672                .read(&mut chunk)
1673                .await
1674                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1675            if n == 0 {
1676                return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1677            }
1678            raw_resp.extend_from_slice(&chunk[..n]);
1679        };
1680        if !Self::is_connect_success_head(&raw_resp[..head_end]) {
1681            return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1682        }
1683        let pre_read: Vec<u8> = raw_resp[head_end + 4..].to_vec();
1684        if is_https {
1685            let tls_cfg: Arc<ClientConfig> = if enable_h2 {
1686                self.tls_client_config_h2()
1687            } else {
1688                self.tls_client_config()
1689            };
1690            let connector: TlsConnector = TlsConnector::from(tls_cfg);
1691            let dns: ServerName<'static> = Self::server_name_for_host(&target_host)?;
1692            let tunnel: ProxyTunnelStream = ProxyTunnelStream::new(proxy_stream, pre_read);
1693            let tls: TlsStream<ProxyTunnelStream> = connector
1694                .connect(dns, tunnel)
1695                .await
1696                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1697            if enable_h2 && tls.get_ref().1.alpn_protocol() != Some(ALPN_H2) {
1698                return Err(RequestError::Request(H2_ALPN_MISMATCH.to_owned()));
1699            }
1700            Ok(Box::new(tls))
1701        } else {
1702            Ok(Box::new(ProxyTunnelStream::new(proxy_stream, pre_read)))
1703        }
1704    }
1705
1706    /// Open an asynchronous stream to the target through a SOCKS5 proxy.
1707    ///
1708    /// # Arguments
1709    ///
1710    /// - `String` - The target host name or IP address.
1711    /// - `u16` - The target TCP port.
1712    /// - `bool` - Whether the target URL requires TLS over the tunnel.
1713    /// - `&Proxy` - The proxy configuration.
1714    /// - `bool` - Whether to negotiate `h2` ALPN on target TLS handshakes.
1715    ///
1716    /// # Returns
1717    ///
1718    /// - `Result<Box<dyn AsyncReadWrite>, RequestError>` - The tunnelled stream, or a `RequestError` when the handshake fails.
1719    async fn open_async_socks5_proxy(
1720        &self,
1721        target_host: String,
1722        target_port: u16,
1723        is_https: bool,
1724        proxy: &Proxy,
1725        enable_h2: bool,
1726    ) -> Result<Box<dyn AsyncReadWrite>, RequestError> {
1727        let has_auth: bool = proxy.get_username().is_some() && proxy.get_password().is_some();
1728        if let (Some(u), Some(p)) = (proxy.get_username(), proxy.get_password())
1729            && (u.len() > usize::from(u8::MAX) || p.len() > usize::from(u8::MAX))
1730        {
1731            return Err(RequestError::Request(PROXY_AUTH_ERROR.to_owned()));
1732        }
1733        let clean_target: &str = Self::strip_ipv6_brackets(&target_host);
1734        let mut connect_req: Vec<u8> = vec![0x05, 0x01, 0x00];
1735        if let Ok(ip) = clean_target.parse::<Ipv4Addr>() {
1736            connect_req.push(0x01);
1737            connect_req.extend_from_slice(&ip.octets());
1738        } else if let Ok(ip) = clean_target.parse::<Ipv6Addr>() {
1739            connect_req.push(0x04);
1740            connect_req.extend_from_slice(&ip.octets());
1741        } else {
1742            let host_len: u8 = u8::try_from(clean_target.len())
1743                .map_err(|_| RequestError::Request(PROXY_AUTH_ERROR.to_owned()))?;
1744            connect_req.push(0x03);
1745            connect_req.push(host_len);
1746            connect_req.extend_from_slice(clean_target.as_bytes());
1747        }
1748        connect_req.extend_from_slice(&target_port.to_be_bytes());
1749        let mut tcp: tokio::net::TcpStream = self
1750            .connect_async_tcp(proxy.get_host(), proxy.get_port())
1751            .await?;
1752        let auth_methods: [u8; 3] = if has_auth {
1753            [0x05, 0x01, 0x02]
1754        } else {
1755            [0x05, 0x01, 0x00]
1756        };
1757        tcp.write_all(&auth_methods)
1758            .await
1759            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1760        let mut resp: [u8; 2] = [0u8; 2];
1761        tcp.read_exact(&mut resp)
1762            .await
1763            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1764        if resp[0] != 0x05 {
1765            return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1766        }
1767        match resp[1] {
1768            0x00 if !has_auth => {}
1769            0x02 => {
1770                let (Some(u), Some(p)) = (proxy.get_username(), proxy.get_password()) else {
1771                    return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1772                };
1773                let mut auth_req: Vec<u8> = Vec::with_capacity(3 + u.len() + p.len());
1774                auth_req.push(0x01);
1775                auth_req.push(u.len() as u8);
1776                auth_req.extend_from_slice(u.as_bytes());
1777                auth_req.push(p.len() as u8);
1778                auth_req.extend_from_slice(p.as_bytes());
1779                tcp.write_all(&auth_req)
1780                    .await
1781                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1782                let mut auth_resp: [u8; 2] = [0u8; 2];
1783                tcp.read_exact(&mut auth_resp)
1784                    .await
1785                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1786                if auth_resp[0] != 0x01 || auth_resp[1] != 0x00 {
1787                    return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1788                }
1789            }
1790            _ => return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string())),
1791        }
1792        tcp.write_all(&connect_req)
1793            .await
1794            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1795        let mut connect_resp: [u8; 4] = [0u8; 4];
1796        tcp.read_exact(&mut connect_resp)
1797            .await
1798            .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1799        if connect_resp[0] != 0x05 || connect_resp[1] != 0x00 {
1800            return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string()));
1801        }
1802        match connect_resp[3] {
1803            0x01 => {
1804                let mut skip: [u8; 6] = [0u8; 6];
1805                tcp.read_exact(&mut skip)
1806                    .await
1807                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1808            }
1809            0x03 => {
1810                let mut len: [u8; 1] = [0u8; 1];
1811                tcp.read_exact(&mut len)
1812                    .await
1813                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1814                let mut skip: Vec<u8> = vec![0u8; len[0] as usize + 2];
1815                tcp.read_exact(&mut skip)
1816                    .await
1817                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1818            }
1819            0x04 => {
1820                let mut skip: [u8; 18] = [0u8; 18];
1821                tcp.read_exact(&mut skip)
1822                    .await
1823                    .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1824            }
1825            _ => return Err(RequestError::Request(INTERNAL_SERVER_ERROR.to_string())),
1826        }
1827        if is_https {
1828            let tls_cfg: Arc<ClientConfig> = if enable_h2 {
1829                self.tls_client_config_h2()
1830            } else {
1831                self.tls_client_config()
1832            };
1833            let connector: TlsConnector = TlsConnector::from(tls_cfg);
1834            let dns: ServerName<'static> = Self::server_name_for_host(&target_host)?;
1835            let proxy_box: Box<dyn AsyncReadWrite> = Box::new(tcp);
1836            let tunnel: ProxyTunnelStream = ProxyTunnelStream::new(proxy_box, Vec::new());
1837            let tls: TlsStream<ProxyTunnelStream> = connector
1838                .connect(dns, tunnel)
1839                .await
1840                .map_err(|e: io::Error| RequestError::Request(e.to_string()))?;
1841            if enable_h2 && tls.get_ref().1.alpn_protocol() != Some(ALPN_H2) {
1842                return Err(RequestError::Request(H2_ALPN_MISMATCH.to_owned()));
1843            }
1844            Ok(Box::new(tls))
1845        } else {
1846            Ok(Box::new(tcp))
1847        }
1848    }
1849}
1850
1851/// Inherent implementation of [`HttpRequest`].
1852impl HttpRequest {
1853    /// Create a GET request for `url`.
1854    ///
1855    /// # Arguments
1856    ///
1857    /// - `T` - The request URL, converted into an owned `String`.
1858    ///
1859    /// # Returns
1860    ///
1861    /// - `Self` - A GET `HttpRequest` targeting `url`.
1862    pub fn get<T>(url: T) -> Self
1863    where
1864        T: Into<String>,
1865    {
1866        Self {
1867            method: Method::Get,
1868            url: url.into(),
1869            headers: HashMap::new(),
1870            body: Body::default(),
1871            config: RequestConfig::default(),
1872            tmp: Tmp::default(),
1873        }
1874    }
1875
1876    /// Create a POST request for `url`.
1877    ///
1878    /// # Arguments
1879    ///
1880    /// - `T` - The request URL, converted into an owned `String`.
1881    ///
1882    /// # Returns
1883    ///
1884    /// - `Self` - A POST `HttpRequest` targeting `url`.
1885    pub fn post<T>(url: T) -> Self
1886    where
1887        T: Into<String>,
1888    {
1889        Self {
1890            method: Method::Post,
1891            url: url.into(),
1892            headers: HashMap::new(),
1893            body: Body::default(),
1894            config: RequestConfig::default(),
1895            tmp: Tmp::default(),
1896        }
1897    }
1898
1899    /// Builder-style: set method.
1900    ///
1901    /// # Arguments
1902    ///
1903    /// - `Method` - The HTTP method to use for the request.
1904    ///
1905    /// # Returns
1906    ///
1907    /// - `&mut Self` - The request itself, for chaining.
1908    pub fn set_method(&mut self, method: Method) -> &mut Self {
1909        self.method = method;
1910        self
1911    }
1912
1913    /// Builder-style: set URL.
1914    ///
1915    /// # Arguments
1916    ///
1917    /// - `T` - The request URL, converted into an owned `String`.
1918    ///
1919    /// # Returns
1920    ///
1921    /// - `&mut Self` - The request itself, for chaining.
1922    pub fn set_url<T>(&mut self, url: T) -> &mut Self
1923    where
1924        T: Into<String>,
1925    {
1926        self.url = url.into();
1927        self
1928    }
1929
1930    /// Builder-style: set a single header (case-insensitive on read; the
1931    /// last value wins for repeated keys).
1932    ///
1933    /// # Arguments
1934    ///
1935    /// - `K` - The header name, normalised to lowercase.
1936    /// - `V` - The header value, stored as an owned `String`.
1937    ///
1938    /// # Returns
1939    ///
1940    /// - `&mut Self` - The request itself, for chaining.
1941    pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
1942    where
1943        K: AsRef<str>,
1944        V: AsRef<str>,
1945    {
1946        let normalized: String = Self::normalize_header_key(key.as_ref());
1947        self.get_mut_headers()
1948            .insert(normalized, value.as_ref().to_owned());
1949        self
1950    }
1951
1952    /// Remove a header by key.
1953    ///
1954    /// # Arguments
1955    ///
1956    /// - `K` - The header name to remove, matched case-insensitively.
1957    ///
1958    /// # Returns
1959    ///
1960    /// - `&mut Self` - The request itself, for chaining.
1961    pub fn remove_header<K>(&mut self, key: K) -> &mut Self
1962    where
1963        K: AsRef<str>,
1964    {
1965        let normalized: String = Self::normalize_header_key(key.as_ref());
1966        self.get_mut_headers().remove(&normalized);
1967        self
1968    }
1969
1970    /// Clear all headers.
1971    ///
1972    /// # Returns
1973    ///
1974    /// - `&mut Self` - The request itself, for chaining.
1975    pub fn clear_headers(&mut self) -> &mut Self {
1976        self.get_mut_headers().clear();
1977        self
1978    }
1979
1980    /// Set body (raw bytes).
1981    ///
1982    /// # Arguments
1983    ///
1984    /// - `Body` - The body payload to send.
1985    ///
1986    /// # Returns
1987    ///
1988    /// - `&mut Self` - The request itself, for chaining.
1989    pub fn set_body(&mut self, body: Body) -> &mut Self {
1990        self.body = body;
1991        self
1992    }
1993
1994    /// Set a single config field by mutating the embedded `RequestConfig`.
1995    ///
1996    /// # Arguments
1997    ///
1998    /// - `RequestConfig` - The configuration replacing the current one.
1999    ///
2000    /// # Returns
2001    ///
2002    /// - `&mut Self` - The request itself, for chaining.
2003    pub fn set_config(&mut self, config: RequestConfig) -> &mut Self {
2004        self.config = config;
2005        self
2006    }
2007
2008    /// Normalize a header key to lowercase so `set_header` /
2009    /// `remove_header` lookups are case-insensitive.
2010    ///
2011    /// # Arguments
2012    ///
2013    /// - `&str` - The header key to normalise.
2014    ///
2015    /// # Returns
2016    ///
2017    /// - `String` - The lower-cased header key.
2018    fn normalize_header_key(key: &str) -> String {
2019        key.to_ascii_lowercase()
2020    }
2021}