Skip to main content

rust_web_server/response/
mod.rs

1//! HTTP responses: [`Response`], its writers and the upstream-response parser.
2//!
3//! A response has a status, headers and a body as a list of
4//! [`ContentRange`](crate::range::ContentRange)s (one, or several for a
5//! `multipart/byteranges` range response), or a `stream_file` / `stream_pipe`
6//! for bodies too large to buffer. `Response::json` / `Response::text` build the
7//! common cases. The writers (`generate_response`, `generate_response_parts`,
8//! …) add `Content-Type`, `Content-Length` and `Content-Range`;
9//! [`Response::parse`] reads a raw upstream response (used by the proxy).
10//! Examples: `src/response/example/`.
11
12#[cfg(test)]
13mod tests;
14#[cfg(test)]
15mod example;
16#[cfg(test)]
17mod reference_parser;
18
19use crate::ext::decimal::Decimal;
20use std::io;
21use std::io::{BufRead, Cursor, Read};
22use crate::body::multipart_form_data::FormMultipartData;
23use crate::core::New;
24use crate::header::Header;
25use crate::ext::string_ext::StringExt;
26use crate::http::{HTTP, VERSION};
27use crate::mime_type::MimeType;
28use crate::range::{ContentRange, Range};
29use crate::request::{METHOD, Request};
30use crate::symbol::SYMBOL;
31
32#[derive(PartialEq, Eq, Clone, Debug)]
33pub struct Error {
34    pub status_code_reason_phrase: &'static StatusCodeReasonPhrase,
35    pub message: String,
36}
37
38/// An HTTP response. Build one inside [`Controller::process`] and return it.
39///
40/// Set `status_code` and `reason_phrase` from [`STATUS_CODE_REASON_PHRASE`],
41/// push body content via [`Range::get_content_range`] into `content_range_list`,
42/// and add any extra headers to `headers`.
43///
44/// For large files, set `stream_file` to the absolute file path instead of loading
45/// the body into `content_range_list`. The server will stream it with
46/// `Transfer-Encoding: chunked` so memory usage stays constant regardless of file size.
47///
48/// For proxy passthrough (SSE, AI token streams, large downloads), set `stream_pipe`
49/// to a boxed `Read` source instead. The server streams its output with
50/// `Transfer-Encoding: chunked` immediately after sending the response headers.
51pub struct Response {
52    /// HTTP version string, e.g. `"HTTP/1.1"`.
53    pub http_version: String,
54    /// Numeric status code, e.g. `200`. Set from [`STATUS_CODE_REASON_PHRASE`].
55    pub status_code: i16,
56    /// Reason phrase, e.g. `"OK"`. Set from [`STATUS_CODE_REASON_PHRASE`].
57    pub reason_phrase: String,
58    /// Response headers. Pre-populated with standard headers by [`Header::get_header_list`].
59    pub headers: Vec<Header>,
60    /// Response body as a list of content ranges (supports multipart and range responses).
61    pub content_range_list: Vec<ContentRange>,
62    /// If set, the server streams this file with `Transfer-Encoding: chunked`
63    /// instead of using `content_range_list`. Use for files larger than ~8 MB.
64    pub stream_file: Option<String>,
65    /// If set, the server pipes bytes from this reader with `Transfer-Encoding: chunked`
66    /// immediately after sending the response headers. Takes precedence over
67    /// `content_range_list` and `stream_file`. The reader is consumed and not cloned.
68    pub stream_pipe: Option<Box<dyn std::io::Read + Send>>,
69    /// Header fields sent after the body (HTTP/2 and HTTP/3; HTTP/1.1 drops
70    /// them) — gRPC's `grpc-status` and `grpc-message`. A streamed body's
71    /// producer fills the slot before it ends the stream. Since 18.3.0.
72    pub trailers: Option<Trailers>,
73}
74
75/// Trailer fields shared between whoever produces a body and the connection
76/// writer that sends them after it (see [`Response::trailers`]). Clones share
77/// the one slot.
78#[derive(Clone, Default, Debug)]
79pub struct Trailers(std::sync::Arc<std::sync::Mutex<Vec<Header>>>);
80
81impl Trailers {
82    /// An empty slot.
83    pub fn new() -> Self {
84        Trailers::default()
85    }
86
87    /// Trailers already known, e.g. for a buffered body.
88    pub fn with(fields: Vec<Header>) -> Self {
89        let trailers = Trailers::new();
90        trailers.set(fields);
91        trailers
92    }
93
94    /// Replace the fields; call before the body's last byte is produced.
95    pub fn set(&self, fields: Vec<Header>) {
96        *self.0.lock().unwrap_or_else(|e| e.into_inner()) = fields;
97    }
98
99    /// The fields set so far.
100    pub fn get(&self) -> Vec<Header> {
101        self.0.lock().unwrap_or_else(|e| e.into_inner()).clone()
102    }
103}
104
105impl Clone for Response {
106    fn clone(&self) -> Self {
107        Response {
108            http_version: self.http_version.clone(),
109            status_code: self.status_code,
110            reason_phrase: self.reason_phrase.clone(),
111            headers: self.headers.clone(),
112            content_range_list: self.content_range_list.clone(),
113            stream_file: self.stream_file.clone(),
114            stream_pipe: None,
115            trailers: self.trailers.clone(),
116        }
117    }
118}
119
120impl PartialEq for Response {
121    fn eq(&self, other: &Self) -> bool {
122        self.http_version == other.http_version
123            && self.status_code == other.status_code
124            && self.reason_phrase == other.reason_phrase
125            && self.headers == other.headers
126            && self.content_range_list == other.content_range_list
127            && self.stream_file == other.stream_file
128    }
129}
130
131impl Eq for Response {}
132
133impl std::fmt::Debug for Response {
134    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135        f.debug_struct("Response")
136            .field("http_version", &self.http_version)
137            .field("status_code", &self.status_code)
138            .field("reason_phrase", &self.reason_phrase)
139            .field("headers", &self.headers)
140            .field("content_range_list", &self.content_range_list)
141            .field("stream_file", &self.stream_file)
142            .field("stream_pipe", &self.stream_pipe.as_ref().map(|_| "<stream>"))
143            .finish()
144    }
145}
146
147#[derive(PartialEq, Eq, Clone, Debug)]
148pub struct StatusCodeReasonPhrase {
149    pub status_code: &'static i16,
150    pub reason_phrase: &'static str,
151}
152
153#[derive(PartialEq, Eq, Clone, Debug)]
154pub struct ResponseStatusCodeReasonPhrase {
155    pub n100_continue: &'static StatusCodeReasonPhrase,
156    pub n101_switching_protocols: &'static StatusCodeReasonPhrase,
157    pub n102_processing: &'static StatusCodeReasonPhrase,
158    pub n103_early_hints: &'static StatusCodeReasonPhrase,
159    pub n200_ok: &'static StatusCodeReasonPhrase,
160    pub n201_created: &'static StatusCodeReasonPhrase,
161    pub n202_accepted: &'static StatusCodeReasonPhrase,
162    pub n203_non_authoritative_information: &'static StatusCodeReasonPhrase,
163    pub n204_no_content: &'static StatusCodeReasonPhrase,
164    pub n205_reset_content: &'static StatusCodeReasonPhrase,
165    pub n206_partial_content: &'static StatusCodeReasonPhrase,
166    pub n207_multi_status: &'static StatusCodeReasonPhrase,
167    pub n208_already_reported: &'static StatusCodeReasonPhrase,
168    pub n226_im_used: &'static StatusCodeReasonPhrase,
169    pub n300_multiple_choices: &'static StatusCodeReasonPhrase,
170    pub n301_moved_permanently: &'static StatusCodeReasonPhrase,
171    pub n302_found: &'static StatusCodeReasonPhrase,
172    pub n303_see_other: &'static StatusCodeReasonPhrase,
173    pub n304_not_modified: &'static StatusCodeReasonPhrase,
174    pub n307_temporary_redirect: &'static StatusCodeReasonPhrase,
175    pub n308_permanent_redirect: &'static StatusCodeReasonPhrase,
176    pub n400_bad_request: &'static StatusCodeReasonPhrase,
177    pub n401_unauthorized: &'static StatusCodeReasonPhrase,
178    pub n402_payment_required: &'static StatusCodeReasonPhrase,
179    pub n403_forbidden: &'static StatusCodeReasonPhrase,
180    pub n404_not_found: &'static StatusCodeReasonPhrase,
181    pub n405_method_not_allowed: &'static StatusCodeReasonPhrase,
182    pub n406_not_acceptable: &'static StatusCodeReasonPhrase,
183    pub n407_proxy_authentication_required: &'static StatusCodeReasonPhrase,
184    pub n408_request_timeout: &'static StatusCodeReasonPhrase,
185    pub n409_conflict: &'static StatusCodeReasonPhrase,
186    pub n410_gone: &'static StatusCodeReasonPhrase,
187    pub n411_length_required: &'static StatusCodeReasonPhrase,
188    pub n412_precondition_failed: &'static StatusCodeReasonPhrase,
189    pub n413_payload_too_large: &'static StatusCodeReasonPhrase,
190    pub n414_uri_too_long: &'static StatusCodeReasonPhrase,
191    pub n415_unsupported_media_type: &'static StatusCodeReasonPhrase,
192    pub n416_range_not_satisfiable: &'static StatusCodeReasonPhrase,
193    pub n417_expectation_failed: &'static StatusCodeReasonPhrase,
194    pub n418_im_a_teapot: &'static StatusCodeReasonPhrase,
195    pub n421_misdirected_request: &'static StatusCodeReasonPhrase,
196    pub n422_unprocessable_entity: &'static StatusCodeReasonPhrase,
197    pub n423_locked: &'static StatusCodeReasonPhrase,
198    pub n424_failed_dependency: &'static StatusCodeReasonPhrase,
199    pub n425_too_early: &'static StatusCodeReasonPhrase,
200    pub n426_upgrade_required: &'static StatusCodeReasonPhrase,
201    pub n428_precondition_required: &'static StatusCodeReasonPhrase,
202    pub n429_too_many_requests: &'static StatusCodeReasonPhrase,
203    pub n431_request_header_fields_too_large: &'static StatusCodeReasonPhrase,
204    pub n451_unavailable_for_legal_reasons: &'static StatusCodeReasonPhrase,
205    pub n500_internal_server_error: &'static StatusCodeReasonPhrase,
206    pub n501_not_implemented: &'static StatusCodeReasonPhrase,
207    pub n502_bad_gateway: &'static StatusCodeReasonPhrase,
208    pub n503_service_unavailable: &'static StatusCodeReasonPhrase,
209    pub n504_gateway_timeout: &'static StatusCodeReasonPhrase,
210    pub n505_http_version_not_supported: &'static StatusCodeReasonPhrase,
211    pub n506_variant_also_negotiates: &'static StatusCodeReasonPhrase,
212    pub n507_insufficient_storage: &'static StatusCodeReasonPhrase,
213    pub n508_loop_detected: &'static StatusCodeReasonPhrase,
214    pub n510_not_extended: &'static StatusCodeReasonPhrase,
215    pub n511_network_authentication_required: &'static StatusCodeReasonPhrase,
216}
217
218pub const STATUS_CODE_REASON_PHRASE: ResponseStatusCodeReasonPhrase = ResponseStatusCodeReasonPhrase {
219    n100_continue: &StatusCodeReasonPhrase { status_code: &100, reason_phrase: "Continue" },
220    n101_switching_protocols: &StatusCodeReasonPhrase { status_code: &101, reason_phrase: "Switching Protocols" },
221    n102_processing: &StatusCodeReasonPhrase { status_code: &102, reason_phrase: "Processing" },
222    n103_early_hints: &StatusCodeReasonPhrase { status_code: &103, reason_phrase: "Early Hints" },
223    n200_ok: &StatusCodeReasonPhrase {
224        status_code: &200,
225        reason_phrase: "OK"
226    },
227
228    n201_created: &StatusCodeReasonPhrase { status_code: &201, reason_phrase: "Created" },
229    n202_accepted: &StatusCodeReasonPhrase { status_code: &202, reason_phrase: "Accepted" },
230    n203_non_authoritative_information: &StatusCodeReasonPhrase { status_code: &203, reason_phrase: "Non Authoritative Information" },
231    n204_no_content: &StatusCodeReasonPhrase {
232        status_code: &204,
233        reason_phrase: "No Content"
234    },
235
236    n205_reset_content: &StatusCodeReasonPhrase { status_code: &205, reason_phrase: "Reset Content" },
237    n206_partial_content: &StatusCodeReasonPhrase {
238        status_code: &206,
239        reason_phrase: "Partial Content"
240    },
241
242    n207_multi_status: &StatusCodeReasonPhrase { status_code: &207, reason_phrase: "Multi-Status" },
243    n208_already_reported: &StatusCodeReasonPhrase { status_code: &208, reason_phrase: "Already Reported" },
244    n226_im_used: &StatusCodeReasonPhrase { status_code: &226, reason_phrase: "IM Used" },
245    n300_multiple_choices: &StatusCodeReasonPhrase { status_code: &300, reason_phrase: "Multiple Choices" },
246    n301_moved_permanently: &StatusCodeReasonPhrase { status_code: &301, reason_phrase: "Moved Permanently" },
247    n302_found: &StatusCodeReasonPhrase { status_code: &302, reason_phrase: "Found" },
248    n303_see_other: &StatusCodeReasonPhrase { status_code: &303, reason_phrase: "See Other" },
249    n304_not_modified: &StatusCodeReasonPhrase { status_code: &304, reason_phrase: "Not Modified" },
250    n307_temporary_redirect: &StatusCodeReasonPhrase { status_code: &307, reason_phrase: "Temporary Redirect" },
251    n308_permanent_redirect: &StatusCodeReasonPhrase { status_code: &308, reason_phrase: "Permanent Redirect" },
252    n400_bad_request: &StatusCodeReasonPhrase {
253        status_code: &400,
254        reason_phrase: "Bad Request"
255    },
256
257    n401_unauthorized: &StatusCodeReasonPhrase { status_code: &401, reason_phrase: "Unauthorized" },
258    n402_payment_required: &StatusCodeReasonPhrase { status_code: &402, reason_phrase: "Payment Required" },
259    n403_forbidden: &StatusCodeReasonPhrase { status_code: &403, reason_phrase: "Forbidden" },
260    n404_not_found: &StatusCodeReasonPhrase {
261        status_code: &404,
262        reason_phrase: "Not Found"
263    },
264
265    n405_method_not_allowed: &StatusCodeReasonPhrase { status_code: &405, reason_phrase: "Method Not Allowed" },
266    n406_not_acceptable: &StatusCodeReasonPhrase { status_code: &406, reason_phrase: "Not Acceptable" },
267    n407_proxy_authentication_required: &StatusCodeReasonPhrase { status_code: &407, reason_phrase: "Proxy Authentication Required" },
268    n408_request_timeout: &StatusCodeReasonPhrase { status_code: &408, reason_phrase: "Request Timeout" },
269    n409_conflict: &StatusCodeReasonPhrase { status_code: &409, reason_phrase: "Conflict" },
270    n410_gone: &StatusCodeReasonPhrase { status_code: &410, reason_phrase: "Gone" },
271    n411_length_required: &StatusCodeReasonPhrase { status_code: &411, reason_phrase: "Length Required" },
272    n412_precondition_failed: &StatusCodeReasonPhrase { status_code: &412, reason_phrase: "Precondition Failed" },
273    n413_payload_too_large: &StatusCodeReasonPhrase { status_code: &413, reason_phrase: "Payload Too Large" },
274    n414_uri_too_long: &StatusCodeReasonPhrase { status_code: &414, reason_phrase: "URI Too Long" },
275    n415_unsupported_media_type: &StatusCodeReasonPhrase { status_code: &415, reason_phrase: "Unsupported Media Type" },
276    n416_range_not_satisfiable: &StatusCodeReasonPhrase {
277        status_code: &416,
278        reason_phrase: "Range Not Satisfiable"
279    },
280
281    n417_expectation_failed: &StatusCodeReasonPhrase { status_code: &417, reason_phrase: "Expectation Failed" },
282    n418_im_a_teapot: &StatusCodeReasonPhrase { status_code: &418, reason_phrase: "I'm A Teapot" },
283    n421_misdirected_request: &StatusCodeReasonPhrase { status_code: &421, reason_phrase: "Misdirected Request" },
284    n422_unprocessable_entity: &StatusCodeReasonPhrase { status_code: &422, reason_phrase: "Unprocessable Entity" },
285    n423_locked: &StatusCodeReasonPhrase { status_code: &423, reason_phrase: "Locked" },
286    n424_failed_dependency: &StatusCodeReasonPhrase { status_code: &424, reason_phrase: "Failed Dependency" },
287    n425_too_early: &StatusCodeReasonPhrase { status_code: &425, reason_phrase: "Too Early" },
288    n426_upgrade_required: &StatusCodeReasonPhrase { status_code: &426, reason_phrase: "Upgrade Required" },
289    n428_precondition_required: &StatusCodeReasonPhrase { status_code: &428, reason_phrase: "Precondition Required" },
290    n429_too_many_requests: &StatusCodeReasonPhrase { status_code: &429, reason_phrase: "Too Many Requests" },
291    n431_request_header_fields_too_large: &StatusCodeReasonPhrase { status_code: &431, reason_phrase: "Request Header Fields Too Large" },
292    n451_unavailable_for_legal_reasons: &StatusCodeReasonPhrase { status_code: &451, reason_phrase: "Unavailable For Legal Reasons" },
293    n500_internal_server_error: &StatusCodeReasonPhrase {
294        status_code: &500,
295        reason_phrase: "Internal Server Error"
296    },
297    n501_not_implemented: &StatusCodeReasonPhrase { status_code: &501, reason_phrase: "Not Implemented" },
298    n502_bad_gateway: &StatusCodeReasonPhrase { status_code: &502, reason_phrase: "Bad Gateway" },
299    n503_service_unavailable: &StatusCodeReasonPhrase { status_code: &503, reason_phrase: "Service Unavailable" },
300    n504_gateway_timeout: &StatusCodeReasonPhrase { status_code: &504, reason_phrase: "Gateway Timeout" },
301    n505_http_version_not_supported: &StatusCodeReasonPhrase { status_code: &505, reason_phrase: "HTTP Version Not Supported" },
302    n506_variant_also_negotiates: &StatusCodeReasonPhrase { status_code: &506, reason_phrase: "Variant Also Negotiates" },
303    n507_insufficient_storage: &StatusCodeReasonPhrase { status_code: &507, reason_phrase: "Insufficient Storage" },
304    n508_loop_detected: &StatusCodeReasonPhrase { status_code: &508, reason_phrase: "Loop Detected" },
305    n510_not_extended: &StatusCodeReasonPhrase { status_code: &510, reason_phrase: "Not Extended" },
306    n511_network_authentication_required: &StatusCodeReasonPhrase { status_code: &511, reason_phrase: "Network Authentication Required" }
307};
308
309/// The `Content-Range` value for a single-part body, or `None` when the
310/// response shouldn't carry one. RFC 9110 §14.4 gives `Content-Range` meaning
311/// only on `206 Partial Content` (and `416`, which rws answers with a plain
312/// error body), so full `200` responses get no such header. `range.end` is
313/// inclusive.
314pub fn content_range_header_value(status_code: i16, content_range: &ContentRange) -> Option<String> {
315    if status_code != *STATUS_CODE_REASON_PHRASE.n206_partial_content.status_code {
316        return None;
317    }
318    Some(format!(
319        "{} {}-{}/{}",
320        Range::BYTES, content_range.range.start, content_range.range.end, content_range.size
321    ))
322}
323
324impl Response {
325
326    /// A response with nothing in it and no allocations — a placeholder to
327    /// `std::mem::replace` a real one with.
328    pub(crate) fn empty() -> Response {
329        Response {
330            http_version: String::new(),
331            status_code: 0,
332            reason_phrase: String::new(),
333            headers: Vec::new(),
334            content_range_list: Vec::new(),
335            stream_file: None,
336            stream_pipe: None,
337            trailers: None,
338        }
339    }
340
341    /// Set the status code and reason phrase, reusing the phrase's buffer.
342    pub(crate) fn set_status(&mut self, status: &StatusCodeReasonPhrase) {
343        self.status_code = *status.status_code;
344        self.reason_phrase.clear();
345        self.reason_phrase.push_str(status.reason_phrase);
346    }
347
348    pub fn build(status: StatusCodeReasonPhrase, header_list : Vec<Header>, body: Vec<ContentRange>) -> Response {
349        Response {
350            http_version: VERSION.http_1_1.to_string(),
351            status_code: *status.status_code,
352            reason_phrase: status.reason_phrase.to_string(),
353            headers: header_list,
354            content_range_list: body,
355            stream_file: None,
356            stream_pipe: None,
357            trailers: None,
358        }
359    }
360
361    pub fn status_code_reason_phrase_list() -> Vec<&'static StatusCodeReasonPhrase> {
362        let list = vec![
363            STATUS_CODE_REASON_PHRASE.n100_continue,
364            STATUS_CODE_REASON_PHRASE.n101_switching_protocols,
365            STATUS_CODE_REASON_PHRASE.n102_processing,
366            STATUS_CODE_REASON_PHRASE.n103_early_hints,
367            STATUS_CODE_REASON_PHRASE.n200_ok,
368            STATUS_CODE_REASON_PHRASE.n201_created,
369            STATUS_CODE_REASON_PHRASE.n202_accepted,
370            STATUS_CODE_REASON_PHRASE.n203_non_authoritative_information,
371            STATUS_CODE_REASON_PHRASE.n204_no_content,
372            STATUS_CODE_REASON_PHRASE.n205_reset_content,
373            STATUS_CODE_REASON_PHRASE.n206_partial_content,
374            STATUS_CODE_REASON_PHRASE.n207_multi_status,
375            STATUS_CODE_REASON_PHRASE.n208_already_reported,
376            STATUS_CODE_REASON_PHRASE.n226_im_used,
377            STATUS_CODE_REASON_PHRASE.n300_multiple_choices,
378            STATUS_CODE_REASON_PHRASE.n301_moved_permanently,
379            STATUS_CODE_REASON_PHRASE.n302_found,
380            STATUS_CODE_REASON_PHRASE.n303_see_other,
381            STATUS_CODE_REASON_PHRASE.n304_not_modified,
382            STATUS_CODE_REASON_PHRASE.n307_temporary_redirect,
383            STATUS_CODE_REASON_PHRASE.n308_permanent_redirect,
384            STATUS_CODE_REASON_PHRASE.n400_bad_request,
385            STATUS_CODE_REASON_PHRASE.n401_unauthorized,
386            STATUS_CODE_REASON_PHRASE.n402_payment_required,
387            STATUS_CODE_REASON_PHRASE.n403_forbidden,
388            STATUS_CODE_REASON_PHRASE.n404_not_found,
389            STATUS_CODE_REASON_PHRASE.n405_method_not_allowed,
390            STATUS_CODE_REASON_PHRASE.n406_not_acceptable,
391            STATUS_CODE_REASON_PHRASE.n407_proxy_authentication_required,
392            STATUS_CODE_REASON_PHRASE.n408_request_timeout,
393            STATUS_CODE_REASON_PHRASE.n409_conflict,
394            STATUS_CODE_REASON_PHRASE.n410_gone,
395            STATUS_CODE_REASON_PHRASE.n411_length_required,
396            STATUS_CODE_REASON_PHRASE.n412_precondition_failed,
397            STATUS_CODE_REASON_PHRASE.n413_payload_too_large,
398            STATUS_CODE_REASON_PHRASE.n414_uri_too_long,
399            STATUS_CODE_REASON_PHRASE.n415_unsupported_media_type,
400            STATUS_CODE_REASON_PHRASE.n416_range_not_satisfiable,
401            STATUS_CODE_REASON_PHRASE.n417_expectation_failed,
402            STATUS_CODE_REASON_PHRASE.n418_im_a_teapot,
403            STATUS_CODE_REASON_PHRASE.n421_misdirected_request,
404            STATUS_CODE_REASON_PHRASE.n422_unprocessable_entity,
405            STATUS_CODE_REASON_PHRASE.n423_locked,
406            STATUS_CODE_REASON_PHRASE.n424_failed_dependency,
407            STATUS_CODE_REASON_PHRASE.n425_too_early,
408            STATUS_CODE_REASON_PHRASE.n426_upgrade_required,
409            STATUS_CODE_REASON_PHRASE.n428_precondition_required,
410            STATUS_CODE_REASON_PHRASE.n429_too_many_requests,
411            STATUS_CODE_REASON_PHRASE.n431_request_header_fields_too_large,
412            STATUS_CODE_REASON_PHRASE.n451_unavailable_for_legal_reasons,
413            STATUS_CODE_REASON_PHRASE.n500_internal_server_error,
414            STATUS_CODE_REASON_PHRASE.n501_not_implemented,
415            STATUS_CODE_REASON_PHRASE.n502_bad_gateway,
416            STATUS_CODE_REASON_PHRASE.n503_service_unavailable,
417            STATUS_CODE_REASON_PHRASE.n504_gateway_timeout,
418            STATUS_CODE_REASON_PHRASE.n505_http_version_not_supported,
419            STATUS_CODE_REASON_PHRASE.n506_variant_also_negotiates,
420            STATUS_CODE_REASON_PHRASE.n507_insufficient_storage,
421            STATUS_CODE_REASON_PHRASE.n508_loop_detected,
422            STATUS_CODE_REASON_PHRASE.n510_not_extended,
423            STATUS_CODE_REASON_PHRASE.n511_network_authentication_required,
424        ];
425        list
426    }
427
428    pub const _ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE: &'static str = "Unable to parse status code";
429
430    pub const _HTTP_VERSION_AND_STATUS_CODE_AND_REASON_PHRASE_REGEX: &'static str = "(?P<http_version>\\w+/\\w+.\\w)\\s(?P<status_code>\\w+)\\s(?P<reason_phrase>.+)";
431
432    pub fn _get_header(&self, name: String) -> Option<&Header> {
433        // Header names are case-insensitive (RFC 9110 §5.1), as in Request::get_header.
434        let header =  self.headers.iter().find(|x| x.name.eq_ignore_ascii_case(&name));
435        header
436    }
437
438    /// `true` for a status that never has content: `1xx`, `204`, `304`
439    /// (RFC 9110 §6.4.1, §15.3.5, §15.4.5).
440    pub fn status_has_no_content(status_code: i16) -> bool {
441        (100..200).contains(&status_code) || status_code == 204 || status_code == 304
442    }
443
444    /// For a status without content ([`Response::status_has_no_content`]),
445    /// drop the body — buffered, file or pipe — and any `Content-Length` or
446    /// `Transfer-Encoding`, which those responses must not carry (#54).
447    /// Every connection writer calls it before framing the response.
448    pub fn drop_content_for_status(&mut self) {
449        if !Response::status_has_no_content(self.status_code) {
450            return;
451        }
452        self.content_range_list.clear();
453        self.stream_file = None;
454        self.stream_pipe = None;
455        self.headers.retain(|h| {
456            !h.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH)
457                && !h.name.eq_ignore_ascii_case(Header::_TRANSFER_ENCODING)
458        });
459    }
460
461    pub fn generate_body(content_range_list: Vec<ContentRange>) -> Vec<u8> {
462        let mut body = vec![];
463        let one = 1;
464
465        if content_range_list.len() == one {
466            // Move the body out rather than copy it: for a large file that
467            // copy was a second full-size buffer per in-flight response.
468            let mut content_range_list = content_range_list;
469            return content_range_list.swap_remove(0).body;
470        }
471
472        if content_range_list.len() > one {
473            // RFC 2046 §5.1.1: each part opens with "--boundary", the body
474            // closes with "--boundary--" (#53).
475            let boundary = Range::multipart_boundary(&content_range_list);
476            for (i, content_range) in content_range_list.iter().enumerate() {
477                let mut body_str = SYMBOL.empty_string.to_string();
478                if i != 0 {
479                    body_str.push_str(SYMBOL.new_line_carriage_return);
480                }
481                body_str.push_str(SYMBOL.hyphen);
482                body_str.push_str(SYMBOL.hyphen);
483                body_str.push_str(&boundary);
484                body_str.push_str(SYMBOL.new_line_carriage_return);
485                let content_type = [Header::_CONTENT_TYPE, Header::NAME_VALUE_SEPARATOR, SYMBOL.whitespace, &Header::single_line(&content_range.content_type)].join("");
486                body_str.push_str(content_type.as_str());
487                body_str.push_str(SYMBOL.new_line_carriage_return);
488                let content_range_header = [Header::_CONTENT_RANGE, Header::NAME_VALUE_SEPARATOR, SYMBOL.whitespace, Range::BYTES, SYMBOL.whitespace, &content_range.range.start.to_string(), SYMBOL.hyphen, &content_range.range.end.to_string(), SYMBOL.slash, &Header::single_line(&content_range.size)].join("");
489                body_str.push_str(content_range_header.as_str());
490                body_str.push_str(SYMBOL.new_line_carriage_return);
491                body_str.push_str(SYMBOL.new_line_carriage_return);
492
493                body.extend_from_slice(body_str.as_bytes());
494                body.extend_from_slice(&content_range.body);
495            }
496            body.extend_from_slice(b"\r\n--");
497            body.extend_from_slice(boundary.as_bytes());
498            body.extend_from_slice(b"--\r\n");
499        }
500
501        body
502    }
503
504    /// The serialized response: status line + headers, then the body.
505    pub fn generate_response(response: Response, request: Request) -> Vec<u8> {
506        Response::generate_response_coalesced(response, request, usize::MAX).0
507    }
508
509    /// Like [`generate_response`](Self::generate_response), but returns the
510    /// head (status line + headers + blank line) and the body separately, so
511    /// a connection writer can send them back to back without first copying
512    /// a large body into one combined buffer. The body is empty for HEAD and
513    /// for a status without content.
514    pub fn generate_response_parts(response: Response, request: Request) -> (Vec<u8>, Vec<u8>) {
515        Response::generate_response_coalesced(response, request, 0)
516    }
517
518    /// [`generate_response_parts`](Self::generate_response_parts), except
519    /// that a body of at most `coalesce_limit` bytes is appended to the head
520    /// (sized for both up front) and the returned body is then empty — one
521    /// buffer for one `write`, without growing the head afterwards.
522    pub(crate) fn generate_response_coalesced(mut response: Response, request: Request, coalesce_limit: usize) -> (Vec<u8>, Vec<u8>) {
523        response.drop_content_for_status();
524        let streamed = response.stream_pipe.is_some() || response.stream_file.is_some();
525        let Response { http_version, status_code, reason_phrase, headers, mut content_range_list, .. } = response;
526
527        // Content-Type, Content-Range and Content-Length follow the other
528        // headers; they're written straight into the head rather than pushed
529        // onto `headers` first.
530        let mut content_type: Option<String> = None;
531        let mut content_range: Option<String> = None;
532        let mut content_length: Option<Decimal> = None;
533        if content_range_list.len() == 1 {
534            let range = &mut content_range_list[0];
535            content_range = content_range_header_value(status_code, range);
536            content_length = Some(Decimal::new(range.body.len() as u128));
537            // A single range's body is moved out by generate_body, which
538            // doesn't look at its type.
539            content_type = Some(std::mem::take(&mut range.content_type));
540        }
541        let multipart = content_range_list.len() > 1;
542        if multipart {
543            content_type = Some(Range::multipart_content_type(&content_range_list));
544        }
545
546        // HEAD: the head of the GET response, no body. OPTIONS gets its body
547        // like any other method: dropping it under a Content-Length that
548        // announced it left the client waiting (#54).
549        let is_head = request.method == METHOD.head;
550        let body = if is_head && !multipart {
551            Vec::new()
552        } else {
553            Response::generate_body(content_range_list)
554        };
555        if multipart {
556            // Without it a keep-alive client can't tell where the body ends
557            // (RFC 9112 §6.3; #53). A HEAD gets the GET's length.
558            content_length = Some(Decimal::new(body.len() as u128));
559        }
560        // No body at all: say so, or a keep-alive client waits for one until
561        // the connection closes (a gRPC-web trailers-only error hung a
562        // browser). Not for statuses that never have content, nor when the
563        // handler set the length itself, nor for a streamed body.
564        if content_length.is_none()
565            && !streamed
566            && !Response::status_has_no_content(status_code)
567            && !headers.iter().any(|h| h.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH))
568        {
569            content_length = Some(Decimal::new(0));
570        }
571        let body = if is_head { Vec::new() } else { body };
572        let coalesce = body.len() <= coalesce_limit;
573
574        // One buffer, sized up front, written once: this used to build a
575        // String per header, grow a second one, join the status line and
576        // copy it all again with format! — the biggest allocation cost of a
577        // small response.
578        let status = u16::try_from(status_code).map(|code| Decimal::new(code as u128));
579        let status_text = match &status {
580            Ok(decimal) => std::borrow::Cow::Borrowed(decimal.as_str()),
581            Err(_) => std::borrow::Cow::Owned(status_code.to_string()),
582        };
583        let extra = [
584            (Header::_CONTENT_TYPE, content_type.as_deref()),
585            (Header::_CONTENT_RANGE, content_range.as_deref()),
586            (Header::_CONTENT_LENGTH, content_length.as_ref().map(Decimal::as_str)),
587        ];
588        let capacity = http_version.len() + status_text.len() + reason_phrase.len() + 4
589            + headers.iter().map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
590            + extra.iter().map(|(name, value)| value.map_or(0, |v| name.len() + v.len() + 4)).sum::<usize>()
591            + 2
592            + if coalesce { body.len() } else { 0 };
593        let mut head = Vec::with_capacity(capacity);
594        head.extend_from_slice(http_version.as_bytes());
595        head.push(b' ');
596        head.extend_from_slice(status_text.as_bytes());
597        head.push(b' ');
598        head.extend_from_slice(Header::single_line(&reason_phrase).as_bytes());
599        head.extend_from_slice(b"\r\n");
600        let header_lines = headers.iter().map(|h| (h.name.as_ref(), h.value.as_ref()))
601            .chain(extra.iter().filter_map(|(name, value)| value.map(|v| (*name, v))));
602        for (name, value) in header_lines {
603            head.extend_from_slice(Header::single_line(name).as_bytes());
604            head.extend_from_slice(Header::NAME_VALUE_SEPARATOR.as_bytes());
605            head.extend_from_slice(Header::single_line(value).as_bytes());
606            head.extend_from_slice(b"\r\n");
607        }
608        head.extend_from_slice(b"\r\n");
609
610        if coalesce {
611            head.extend_from_slice(&body);
612            (head, Vec::new())
613        } else {
614            (head, body)
615        }
616    }
617
618    pub fn _parse_response(response_vec_u8: &[u8]) -> Response {
619        let mut cursor = io::Cursor::new(response_vec_u8);
620
621        let mut response = Response {
622            http_version: "".to_string(),
623            status_code: 0,
624            reason_phrase: "".to_string(),
625            headers: vec![],
626            content_range_list: vec![],
627            stream_file: None,
628            stream_pipe: None,
629            trailers: None,
630        };
631
632        let content_length: usize = 0;
633        let iteration_number : usize = 0;
634
635        Response::_parse_raw_response_via_cursor(&mut cursor, iteration_number, &mut response, content_length);
636
637        return response;
638    }
639
640    pub fn _parse_http_version_status_code_reason_phrase_string(http_version_status_code_reason_phrase: &str) -> Result<(String, i16, String), String> {
641        let line = without_cr_lf(http_version_status_code_reason_phrase);
642        let (http_version, status_code, reason_phrase) = Response::status_line_parts(&line)?;
643        Ok((http_version.to_string(), status_code, reason_phrase.to_string()))
644    }
645
646    /// `HTTP-version SP status-code [SP reason-phrase]`, CR/LF already
647    /// removed, borrowed from `line`.
648    fn status_line_parts(line: &str) -> Result<(&str, i16, &str), String> {
649        let boxed_split = line.split_once(SYMBOL.whitespace);
650        if boxed_split.is_none() {
651            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
652        }
653
654        let (http_version, status_code_reason_phrase) = boxed_split.unwrap();
655        if !HTTP::is_supported_version(http_version) {
656            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
657        }
658
659        // RFC 9112 §4: status-line = HTTP-version SP status-code SP [ reason-phrase ].
660        // The reason phrase is optional free text that clients should ignore
661        // (Python's http.server sends "404 File not found"), and any 3-digit
662        // code is valid — so neither is checked against the known list.
663        let (status_code, reason_phrase) = status_code_reason_phrase
664            .split_once(SYMBOL.whitespace)
665            .unwrap_or((status_code_reason_phrase, ""));
666
667        let is_three_digits = status_code.len() == 3 && status_code.bytes().all(|b| b.is_ascii_digit());
668        let status_code_i16 = match status_code.parse::<i16>() {
669            Ok(code) if is_three_digits && code >= 100 => code,
670            _ => return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string()),
671        };
672
673        Ok((http_version, status_code_i16, reason_phrase))
674    }
675
676    pub fn _parse_http_response_header_string(header_string: &str) -> Header {
677        // A line without ": " (malformed upstream input) is a name with an
678        // empty value, as in Request::parse_http_request_header_string —
679        // not an index-out-of-bounds panic.
680        let (header_name, raw_header_value) = header_string
681            .split_once(Header::NAME_VALUE_SEPARATOR)
682            .unwrap_or((header_string, ""));
683        let header_value = StringExt::truncate_new_line_carriage_return(raw_header_value);
684
685
686        Header {
687            name: header_name.to_string().into(),
688            value: header_value.to_string().into()
689        }
690    }
691
692    pub fn _parse_raw_response_via_cursor(
693        cursor: &mut Cursor<&[u8]>,
694        mut iteration_number: usize,
695        response: &mut Response,
696        mut content_length: usize) {
697
698        let mut buffer = vec![];
699        let boxed_read = cursor.read_until(b'\n', &mut buffer);
700        if boxed_read.is_err() {
701            eprintln!("unable to parse raw response via cursor {}", boxed_read.err().unwrap());
702            return;
703        }
704        let bytes_offset = boxed_read.unwrap();
705        let mut buffer_as_u8_array: &[u8] = &buffer;
706        let string = String::from_utf8(Vec::from(buffer_as_u8_array)).unwrap();
707
708        let is_first_iteration = iteration_number == 0;
709        let new_line_char_found = bytes_offset != 0;
710        let current_string_is_empty = string.trim().len() == 0;
711
712        if is_first_iteration {
713            let boxed_http_version_status_code_reason_phrase = Response::_parse_http_version_status_code_reason_phrase_string(&string);
714            if boxed_http_version_status_code_reason_phrase.is_err() {
715                let error = boxed_http_version_status_code_reason_phrase.err().unwrap();
716                eprintln!("{}", error);
717                return;
718            }
719
720            let (http_version, status_code, reason_phrase) = boxed_http_version_status_code_reason_phrase.unwrap();
721
722            response.http_version = http_version;
723            response.status_code = status_code;
724            response.reason_phrase = reason_phrase;
725        }
726
727        if current_string_is_empty {
728            // No Content-Type (a 204, a 304): an empty, non-multipart body.
729            let content_type = response._get_header(Header::_CONTENT_TYPE.to_string()).cloned()
730                .unwrap_or(Header { name: Header::_CONTENT_TYPE.into(), value: "".into() });
731            let is_multipart = Response::_is_multipart_byteranges_content_type(&content_type);
732
733            if is_multipart {
734                let content_range_list : Vec<ContentRange> = vec![];
735
736                let boundary = content_type.value.split(';')
737                    .filter_map(|param| param.trim().strip_prefix("boundary="))
738                    .next()
739                    .map(|b| b.trim_matches('"').to_string())
740                    .unwrap_or_else(|| Range::STRING_SEPARATOR.to_string());
741                let mut buf = vec![];
742                let _ = cursor.read_until(b'\n', &mut buf);
743                let boxed_value = Range::_parse_multipart_body_with_boundary(cursor, content_range_list, &boundary);
744                let mut range_list = vec![];
745                if boxed_value.is_ok() {
746                    range_list = boxed_value.unwrap();
747                }
748                response.content_range_list = range_list;
749            } else {
750                buffer = vec![];
751                let boxed_read = cursor.read_to_end(&mut buffer);
752                if boxed_read.is_ok() {
753                    buffer_as_u8_array = &buffer;
754
755                    let content_range = ContentRange {
756                        unit: Range::BYTES.to_string(),
757                        range: Range {
758                            start: 0,
759                            end: buffer_as_u8_array.len() as u64
760                        },
761                        size: buffer_as_u8_array.len().to_string(),
762                        body: Vec::from(buffer_as_u8_array),
763                        content_type: content_type.value.to_string()
764                    };
765                    response.content_range_list = vec![content_range];
766                } else {
767                    let reason = boxed_read.err().unwrap();
768                    eprintln!("error reading file: {}", reason.to_string())
769                }
770
771            }
772
773            return;
774        }
775
776        if new_line_char_found && !current_string_is_empty {
777            let mut header = Header { name: "".into(), value: "".into() };
778            if !is_first_iteration {
779                header = Response::_parse_http_response_header_string(&string);
780                if header.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH) {
781                    // No error channel here: treat an invalid value as absent.
782                    content_length = header.value.trim().parse().unwrap_or(0);
783                }
784            }
785
786            response.headers.push(header);
787            iteration_number += 1;
788            Response::_parse_raw_response_via_cursor(cursor, iteration_number, response, content_length);
789        }
790    }
791
792    pub fn _is_multipart_byteranges_content_type(content_type: &Header) -> bool {
793        // Asked of every parsed (e.g. every proxied) response: no join.
794        content_type.value.strip_prefix(Range::MULTIPART)
795            .and_then(|rest| rest.strip_prefix(SYMBOL.slash))
796            .is_some_and(|rest| rest.starts_with(Range::BYTERANGES))
797    }
798
799
800    pub fn get_response(
801        status_code_reason_phrase: &StatusCodeReasonPhrase,
802        boxed_header_list: Option<Vec<Header>>,
803        boxed_content_range_list: Option<Vec<ContentRange>>) -> Response {
804
805        let mut header_list: Vec<Header> = vec![];
806        if boxed_header_list.is_some() {
807            header_list = boxed_header_list.unwrap();
808        }
809
810        let mut content_range_list: Vec<ContentRange> = vec![];
811        if boxed_content_range_list.is_some() {
812            content_range_list = boxed_content_range_list.unwrap();
813        }
814
815        let response = Response {
816            http_version: VERSION.http_1_1.to_string(),
817            status_code: *status_code_reason_phrase.status_code,
818            reason_phrase: status_code_reason_phrase.reason_phrase.to_string(),
819            headers: header_list,
820            content_range_list,
821            stream_file: None,
822            stream_pipe: None,
823            trailers: None,
824        };
825
826        response
827    }
828
829    /// Build a `Content-Type: application/json` response from already-serialized bytes.
830    ///
831    /// Takes raw bytes rather than a `Serialize` value so it carries no dependency on the
832    /// `serde` feature — pair it with `serde_json::to_vec` (or hand-rolled JSON) to build `body`.
833    /// For a one-line serialize-and-respond helper on a typed value, see [`crate::json::Json`]
834    /// (`serde` feature).
835    ///
836    /// ```rust,no_run
837    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
838    ///
839    /// let response = Response::json(STATUS_CODE_REASON_PHRASE.n200_ok, br#"{"ok":true}"#.to_vec());
840    /// ```
841    pub fn json(status_code_reason_phrase: &StatusCodeReasonPhrase, body: Vec<u8>) -> Response {
842        let content_range = Range::get_content_range(body, MimeType::APPLICATION_JSON.to_string());
843        Response::get_response(status_code_reason_phrase, None, Some(vec![content_range]))
844    }
845
846    /// Build a `Content-Type: text/plain` response from a body string.
847    ///
848    /// ```rust,no_run
849    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
850    ///
851    /// let response = Response::text(STATUS_CODE_REASON_PHRASE.n400_bad_request, "invalid input");
852    /// ```
853    pub fn text(status_code_reason_phrase: &StatusCodeReasonPhrase, body: &str) -> Response {
854        let content_range = Range::get_content_range(body.as_bytes().to_vec(), MimeType::TEXT_PLAIN.to_string());
855        Response::get_response(status_code_reason_phrase, None, Some(vec![content_range]))
856    }
857
858    pub fn generate(&mut self) -> Vec<u8> {
859        let response = &mut self.clone();
860        response.drop_content_for_status();
861
862        if response.content_range_list.len() == 1 {
863            let content_range_index = 0;
864            let content_range = response.content_range_list.get(content_range_index).unwrap();
865            response.headers.push(Header {
866                name: Header::_CONTENT_TYPE.into(),
867                value: content_range.content_type.to_string().into()
868            });
869
870            if let Some(value) = content_range_header_value(response.status_code, content_range) {
871                response.headers.push(Header {
872                    name: Header::_CONTENT_RANGE.into(),
873                    value: value.into(),
874                });
875            }
876
877            response.headers.push(Header {
878                name: Header::_CONTENT_LENGTH.into(),
879                value: content_range.body.len().to_string().into()
880            });
881        }
882
883        if response.content_range_list.len() > 1 {
884            response.headers.push(Header {
885                name: Header::_CONTENT_TYPE.into(),
886                value: Range::multipart_content_type(&response.content_range_list).into(),
887            });
888        }
889
890        let response_clone = response.clone();
891        let body = Response::generate_body(response_clone.content_range_list);
892        if response.content_range_list.len() > 1 {
893            response.headers.push(Header {
894                name: Header::_CONTENT_LENGTH.into(),
895                value: body.len().to_string().into(),
896            });
897        }
898
899        let mut headers_str = SYMBOL.new_line_carriage_return.to_string();
900
901        let header_list = response.headers.clone();
902        for header in header_list {
903            let mut header_string = SYMBOL.empty_string.to_string();
904            header_string.push_str(&Header::single_line(&header.name));
905            header_string.push_str(Header::NAME_VALUE_SEPARATOR);
906            header_string.push_str(&Header::single_line(&header.value));
907            header_string.push_str(SYMBOL.new_line_carriage_return);
908            headers_str.push_str(&header_string);
909        }
910
911        let response_clone = response.clone();
912        let status = [response_clone.http_version, response.status_code.to_string(), Header::single_line(&response_clone.reason_phrase).into_owned()].join(SYMBOL.whitespace);
913        let response_without_body = format!(
914            "{}{}{}",
915            status,
916            headers_str,
917            SYMBOL.new_line_carriage_return,
918        );
919
920
921        [response_without_body.into_bytes(), body].concat()
922    }
923
924    pub fn get_header(&self, name: String) -> Option<&Header> {
925        self._get_header(name)
926    }
927
928    /// The first header named `name` (case-insensitive), without allocating.
929    pub fn header(&self, name: &str) -> Option<&Header> {
930        self.headers.iter().find(|h| h.name.eq_ignore_ascii_case(name))
931    }
932
933    pub fn parse(response_vec_u8: &[u8]) -> Result<Response, String> {
934        let total_bytes : i32 = response_vec_u8.len() as i32;
935        let bytes_read = 0;
936        let mut cursor = io::Cursor::new(response_vec_u8);
937
938        let mut response = Response {
939            http_version: "".to_string(),
940            status_code: 0,
941            reason_phrase: "".to_string(),
942            // Typical upstream heads have 6–16 headers: grown 1→2→4→8→16
943            // this was four allocations per proxied response.
944            headers: Vec::with_capacity(16),
945            content_range_list: vec![],
946            stream_file: None,
947            stream_pipe: None,
948            trailers: None,
949        };
950
951        let content_length: usize = 0;
952        let iteration_number : usize = 0;
953
954        let boxed_parse = Response::parse_raw_response_via_cursor(
955            &mut cursor, iteration_number,
956            &mut response,
957            content_length,
958            total_bytes,
959            bytes_read
960        );
961        if boxed_parse.is_err() {
962            let message = boxed_parse.err().unwrap();
963            return Err(message);
964        }
965
966        return Ok(response);
967    }
968
969    /// [`Response::parse`] and `proxy::normalize_upstream_response` in one
970    /// pass, for a buffered upstream response: the status line is re-emitted
971    /// as HTTP/1.1, headers named in `dropped` (compared ignoring ASCII case)
972    /// are skipped before their value is copied, and every `Content-Type`
973    /// moves onto the body (the first one is its type). A
974    /// `multipart/byteranges` response goes the general way. The result is
975    /// what the two-step path builds (`response_tests::parse_upstream_*`) —
976    /// minus a copy per dropped header, a second scan for `Content-Type`
977    /// and the `retain` that removed them.
978    pub(crate) fn parse_upstream(input: &[u8], dropped: &[&str]) -> Result<Response, String> {
979        let mut response = Response {
980            http_version: crate::http::VERSION.http_1_1.to_string(),
981            status_code: 0,
982            reason_phrase: String::new(),
983            headers: Vec::with_capacity(16),
984            content_range_list: vec![],
985            stream_file: None,
986            stream_pipe: None,
987            trailers: None,
988        };
989        let mut content_type: Option<&str> = None;
990        let mut pos = 0usize;
991        let mut first = true;
992        loop {
993            let rest = &input[pos.min(input.len())..];
994            let line_len = rest.iter().position(|&b| b == b'\n').map_or(rest.len(), |i| i + 1);
995            pos += line_len;
996            let line = std::str::from_utf8(&rest[..line_len]).map_err(|e| e.to_string())?;
997            if first {
998                let status_line = without_cr_lf(line);
999                let (_, status_code, reason_phrase) = Response::status_line_parts(&status_line)?;
1000                response.status_code = status_code;
1001                response.reason_phrase = reason_phrase.to_string();
1002            }
1003            if line.trim().is_empty() {
1004                if content_type.is_some_and(|ct| ct.starts_with("multipart/byteranges")) {
1005                    return Response::parse(input).map(normalized_like_proxy(dropped));
1006                }
1007                let body = input[pos.min(input.len())..].to_vec();
1008                response.content_range_list = vec![ContentRange {
1009                    unit: Range::BYTES.to_string(),
1010                    range: Range { start: 0, end: body.len() as u64 },
1011                    size: Decimal::new(body.len() as u128).as_str().to_string(),
1012                    content_type: content_type.unwrap_or(MimeType::APPLICATION_OCTET_STREAM).to_string(),
1013                    body,
1014                }];
1015                return Ok(response);
1016            }
1017            if line_len == 0 {
1018                return Err("unable to parse".to_string());
1019            }
1020            if !first {
1021                let (name, raw_value) = split_name_value(line).ok_or_else(|| format!("unable to parse header: {}", line))?;
1022                if name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH) {
1023                    let value = without_cr_lf(raw_value);
1024                    let _: usize = value.trim().parse().map_err(|_| format!("invalid Content-Length: {:?}", value))?;
1025                }
1026                if name.eq_ignore_ascii_case(Header::_CONTENT_TYPE) {
1027                    if content_type.is_none() {
1028                        // Borrowed from `input`; an embedded CR/LF (rare)
1029                        // falls back to the general path to stay exact.
1030                        match without_cr_lf(raw_value) {
1031                            std::borrow::Cow::Borrowed(v) => content_type = Some(v),
1032                            std::borrow::Cow::Owned(_) => return Response::parse(input).map(normalized_like_proxy(dropped)),
1033                        }
1034                    }
1035                    continue;
1036                }
1037                if !dropped.iter().any(|d| name.eq_ignore_ascii_case(d)) {
1038                    response.headers.push(Header {
1039                        name: Header::name_from(name),
1040                        value: without_cr_lf(raw_value).into_owned().into(),
1041                    });
1042                }
1043            }
1044            first = false;
1045        }
1046    }
1047
1048    pub fn parse_raw_response_via_cursor(
1049        cursor: &mut Cursor<&[u8]>,
1050        mut iteration_number: usize,
1051        response: &mut Response,
1052        _content_length: usize,
1053        total_bytes: i32,
1054        mut bytes_read: i32) -> Result<(), String> {
1055        // One pass over the input: each line is a slice of it (this used to
1056        // copy every line into a Vec and then a String, and strip CR/LF with
1057        // two `str::replace` allocations per header), and only the values
1058        // kept are allocated. A loop, not recursion: one stack frame per
1059        // header line let a backend overflow the stack.
1060        let input: &[u8] = cursor.get_ref();
1061        loop {
1062            let start = (cursor.position() as usize).min(input.len());
1063            let rest = &input[start..];
1064            let line_len = rest.iter().position(|&b| b == b'\n').map_or(rest.len(), |i| i + 1);
1065            cursor.set_position((start + line_len) as u64);
1066            bytes_read += line_len as i32;
1067            let line = std::str::from_utf8(&rest[..line_len]).map_err(|e| e.to_string())?;
1068
1069            let is_first_iteration = iteration_number == 0;
1070            let new_line_char_found = line_len != 0;
1071            let current_string_is_empty = line.trim().is_empty();
1072
1073            if is_first_iteration {
1074                let status_line = without_cr_lf(line);
1075                let (http_version, status_code, reason_phrase) = Response::status_line_parts(&status_line)?;
1076                response.http_version = http_version.to_string();
1077                response.status_code = status_code;
1078                response.reason_phrase = reason_phrase.to_string();
1079            }
1080
1081            if current_string_is_empty {
1082                // if response does not contain Content-Type, it will be defaulted to APPLICATION_OCTET_STREAM
1083                let content_type_header = response.header(Header::_CONTENT_TYPE);
1084                let is_multipart = content_type_header.map_or(false, Response::_is_multipart_byteranges_content_type);
1085
1086                if is_multipart {
1087                    let content_type = response.header(Header::_CONTENT_TYPE).ok_or("Content-Type is missing")?;
1088                    let boundary = FormMultipartData::extract_boundary(content_type.value.as_ref())
1089                        .map_err(|_| "unable to extract boundary from Content-Type".to_string())?;
1090                    let is_opening_boundary_read = false;
1091                    response.content_range_list = Range::parse_multipart_body_with_boundary(
1092                        cursor,
1093                        vec![],
1094                        boundary,
1095                        total_bytes,
1096                        bytes_read,
1097                        is_opening_boundary_read)?;
1098                } else {
1099                    let content_type = content_type_header.map_or(MimeType::APPLICATION_OCTET_STREAM, |h| h.value.as_ref());
1100                    let start = (cursor.position() as usize).min(input.len());
1101                    let body = input[start..].to_vec();
1102                    cursor.set_position(input.len() as u64);
1103                    let content_range = ContentRange {
1104                        unit: Range::BYTES.to_string(),
1105                        range: Range {
1106                            start: 0,
1107                            end: body.len() as u64
1108                        },
1109                        size: Decimal::new(body.len() as u128).as_str().to_string(),
1110                        content_type: content_type.to_string(),
1111                        body,
1112                    };
1113                    response.content_range_list = vec![content_range];
1114                }
1115
1116                return Ok(());
1117            }
1118
1119            if new_line_char_found {
1120                if !is_first_iteration {
1121                    let header = Response::parse_http_response_header_string(line)?;
1122                    if header.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH) {
1123                        // An upstream-supplied value: reject garbage instead of panicking.
1124                        let _: usize = header.value.trim().parse()
1125                            .map_err(|_| format!("invalid Content-Length: {:?}", header.value))?;
1126                    }
1127                    response.headers.push(header);
1128                }
1129
1130                iteration_number += 1;
1131            } else {
1132                return Err("unable to parse".to_string());
1133            }
1134        }
1135    }
1136
1137    pub fn parse_http_response_header_string(header_string: &str) -> Result<Header, String> {
1138        match split_name_value(header_string) {
1139            Some((header_name, raw_header_value)) => Ok(Header {
1140                name: Header::name_from(header_name),
1141                value: without_cr_lf(raw_header_value).into_owned().into(),
1142            }),
1143            None => Err(format!("unable to parse header: {}", header_string)),
1144        }
1145    }
1146}
1147
1148impl New for Response {
1149    fn new() -> Self {
1150        Response {
1151            http_version: VERSION.http_1_1.to_string(),
1152            status_code: *STATUS_CODE_REASON_PHRASE.n501_not_implemented.status_code,
1153            reason_phrase: STATUS_CODE_REASON_PHRASE.n501_not_implemented.reason_phrase.to_string(),
1154            headers: vec![],
1155            content_range_list: vec![],
1156            stream_file: None,
1157            stream_pipe: None,
1158            trailers: None,
1159        }
1160    }
1161}
1162/// The general path of [`Response::parse_upstream`]: what
1163/// `proxy::normalize_upstream_response` does to a parsed response.
1164fn normalized_like_proxy<'a>(dropped: &'a [&'a str]) -> impl FnOnce(Response) -> Response + 'a {
1165    move |mut response: Response| {
1166        response.http_version.clear();
1167        response.http_version.push_str(crate::http::VERSION.http_1_1);
1168        let has_body = !response.content_range_list.is_empty();
1169        if let [range] = response.content_range_list.as_mut_slice() {
1170            if let Some(h) = response.headers.iter().find(|h| h.name.eq_ignore_ascii_case(Header::_CONTENT_TYPE)) {
1171                range.content_type.clear();
1172                range.content_type.push_str(&h.value);
1173            }
1174        }
1175        response.headers.retain(|h| {
1176            if h.name.eq_ignore_ascii_case(Header::_CONTENT_TYPE) {
1177                return !has_body;
1178            }
1179            !dropped.iter().any(|d| h.name.eq_ignore_ascii_case(d))
1180        });
1181        response
1182    }
1183}
1184
1185/// `s` with every CR and LF removed — borrowed when they only end the line.
1186fn without_cr_lf(s: &str) -> std::borrow::Cow<'_, str> {
1187    let trimmed = s.strip_suffix('\n').unwrap_or(s);
1188    let trimmed = trimmed.strip_suffix('\r').unwrap_or(trimmed);
1189    if trimmed.contains(['\r', '\n']) {
1190        std::borrow::Cow::Owned(StringExt::truncate_new_line_carriage_return(s))
1191    } else {
1192        std::borrow::Cow::Borrowed(trimmed)
1193    }
1194}
1195
1196/// `line` split at its first `": "` — what `split_once(": ")` returns,
1197/// without a substring searcher.
1198fn split_name_value(line: &str) -> Option<(&str, &str)> {
1199    let bytes = line.as_bytes();
1200    let mut from = 0;
1201    while let Some(offset) = bytes[from..].iter().position(|&b| b == b':') {
1202        let colon = from + offset;
1203        if bytes.get(colon + 1) == Some(&b' ') {
1204            return Some((&line[..colon], &line[colon + 2..]));
1205        }
1206        from = colon + 1;
1207    }
1208    None
1209}