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    /// A response with `status`, no headers and no body; set fields or push
342    /// headers and body parts after.
343    ///
344    /// ```rust
345    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
346    ///
347    /// let mut response = Response::with_status(STATUS_CODE_REASON_PHRASE.n204_no_content);
348    /// response.headers.push(rust_web_server::header::Header::new("X-Done", "yes"));
349    /// assert_eq!(response.status_code, 204);
350    /// ```
351    pub fn with_status(status: &StatusCodeReasonPhrase) -> Response {
352        let mut response = <Response as New>::new();
353        response.set_status(status);
354        response
355    }
356
357    /// Set the status code and reason phrase, reusing the phrase's buffer.
358    pub(crate) fn set_status(&mut self, status: &StatusCodeReasonPhrase) {
359        self.status_code = *status.status_code;
360        self.reason_phrase.clear();
361        self.reason_phrase.push_str(status.reason_phrase);
362    }
363
364    pub fn build(status: StatusCodeReasonPhrase, header_list : Vec<Header>, body: Vec<ContentRange>) -> Response {
365        Response {
366            http_version: VERSION.http_1_1.to_string(),
367            status_code: *status.status_code,
368            reason_phrase: status.reason_phrase.to_string(),
369            headers: header_list,
370            content_range_list: body,
371            stream_file: None,
372            stream_pipe: None,
373            trailers: None,
374        }
375    }
376
377    pub fn status_code_reason_phrase_list() -> Vec<&'static StatusCodeReasonPhrase> {
378        let list = vec![
379            STATUS_CODE_REASON_PHRASE.n100_continue,
380            STATUS_CODE_REASON_PHRASE.n101_switching_protocols,
381            STATUS_CODE_REASON_PHRASE.n102_processing,
382            STATUS_CODE_REASON_PHRASE.n103_early_hints,
383            STATUS_CODE_REASON_PHRASE.n200_ok,
384            STATUS_CODE_REASON_PHRASE.n201_created,
385            STATUS_CODE_REASON_PHRASE.n202_accepted,
386            STATUS_CODE_REASON_PHRASE.n203_non_authoritative_information,
387            STATUS_CODE_REASON_PHRASE.n204_no_content,
388            STATUS_CODE_REASON_PHRASE.n205_reset_content,
389            STATUS_CODE_REASON_PHRASE.n206_partial_content,
390            STATUS_CODE_REASON_PHRASE.n207_multi_status,
391            STATUS_CODE_REASON_PHRASE.n208_already_reported,
392            STATUS_CODE_REASON_PHRASE.n226_im_used,
393            STATUS_CODE_REASON_PHRASE.n300_multiple_choices,
394            STATUS_CODE_REASON_PHRASE.n301_moved_permanently,
395            STATUS_CODE_REASON_PHRASE.n302_found,
396            STATUS_CODE_REASON_PHRASE.n303_see_other,
397            STATUS_CODE_REASON_PHRASE.n304_not_modified,
398            STATUS_CODE_REASON_PHRASE.n307_temporary_redirect,
399            STATUS_CODE_REASON_PHRASE.n308_permanent_redirect,
400            STATUS_CODE_REASON_PHRASE.n400_bad_request,
401            STATUS_CODE_REASON_PHRASE.n401_unauthorized,
402            STATUS_CODE_REASON_PHRASE.n402_payment_required,
403            STATUS_CODE_REASON_PHRASE.n403_forbidden,
404            STATUS_CODE_REASON_PHRASE.n404_not_found,
405            STATUS_CODE_REASON_PHRASE.n405_method_not_allowed,
406            STATUS_CODE_REASON_PHRASE.n406_not_acceptable,
407            STATUS_CODE_REASON_PHRASE.n407_proxy_authentication_required,
408            STATUS_CODE_REASON_PHRASE.n408_request_timeout,
409            STATUS_CODE_REASON_PHRASE.n409_conflict,
410            STATUS_CODE_REASON_PHRASE.n410_gone,
411            STATUS_CODE_REASON_PHRASE.n411_length_required,
412            STATUS_CODE_REASON_PHRASE.n412_precondition_failed,
413            STATUS_CODE_REASON_PHRASE.n413_payload_too_large,
414            STATUS_CODE_REASON_PHRASE.n414_uri_too_long,
415            STATUS_CODE_REASON_PHRASE.n415_unsupported_media_type,
416            STATUS_CODE_REASON_PHRASE.n416_range_not_satisfiable,
417            STATUS_CODE_REASON_PHRASE.n417_expectation_failed,
418            STATUS_CODE_REASON_PHRASE.n418_im_a_teapot,
419            STATUS_CODE_REASON_PHRASE.n421_misdirected_request,
420            STATUS_CODE_REASON_PHRASE.n422_unprocessable_entity,
421            STATUS_CODE_REASON_PHRASE.n423_locked,
422            STATUS_CODE_REASON_PHRASE.n424_failed_dependency,
423            STATUS_CODE_REASON_PHRASE.n425_too_early,
424            STATUS_CODE_REASON_PHRASE.n426_upgrade_required,
425            STATUS_CODE_REASON_PHRASE.n428_precondition_required,
426            STATUS_CODE_REASON_PHRASE.n429_too_many_requests,
427            STATUS_CODE_REASON_PHRASE.n431_request_header_fields_too_large,
428            STATUS_CODE_REASON_PHRASE.n451_unavailable_for_legal_reasons,
429            STATUS_CODE_REASON_PHRASE.n500_internal_server_error,
430            STATUS_CODE_REASON_PHRASE.n501_not_implemented,
431            STATUS_CODE_REASON_PHRASE.n502_bad_gateway,
432            STATUS_CODE_REASON_PHRASE.n503_service_unavailable,
433            STATUS_CODE_REASON_PHRASE.n504_gateway_timeout,
434            STATUS_CODE_REASON_PHRASE.n505_http_version_not_supported,
435            STATUS_CODE_REASON_PHRASE.n506_variant_also_negotiates,
436            STATUS_CODE_REASON_PHRASE.n507_insufficient_storage,
437            STATUS_CODE_REASON_PHRASE.n508_loop_detected,
438            STATUS_CODE_REASON_PHRASE.n510_not_extended,
439            STATUS_CODE_REASON_PHRASE.n511_network_authentication_required,
440        ];
441        list
442    }
443
444    pub const _ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE: &'static str = "Unable to parse status code";
445
446    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>.+)";
447
448    pub fn _get_header(&self, name: String) -> Option<&Header> {
449        // Header names are case-insensitive (RFC 9110 §5.1), as in Request::get_header.
450        let header =  self.headers.iter().find(|x| x.name.eq_ignore_ascii_case(&name));
451        header
452    }
453
454    /// `true` for a status that never has content: `1xx`, `204`, `304`
455    /// (RFC 9110 §6.4.1, §15.3.5, §15.4.5).
456    pub fn status_has_no_content(status_code: i16) -> bool {
457        (100..200).contains(&status_code) || status_code == 204 || status_code == 304
458    }
459
460    /// For a status without content ([`Response::status_has_no_content`]),
461    /// drop the body — buffered, file or pipe — and any `Content-Length` or
462    /// `Transfer-Encoding`, which those responses must not carry (#54).
463    /// Every connection writer calls it before framing the response.
464    pub fn drop_content_for_status(&mut self) {
465        if !Response::status_has_no_content(self.status_code) {
466            return;
467        }
468        self.content_range_list.clear();
469        self.stream_file = None;
470        self.stream_pipe = None;
471        self.headers.retain(|h| {
472            !h.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH)
473                && !h.name.eq_ignore_ascii_case(Header::_TRANSFER_ENCODING)
474        });
475    }
476
477    pub fn generate_body(content_range_list: Vec<ContentRange>) -> Vec<u8> {
478        let mut body = vec![];
479        let one = 1;
480
481        if content_range_list.len() == one {
482            // Move the body out rather than copy it: for a large file that
483            // copy was a second full-size buffer per in-flight response.
484            let mut content_range_list = content_range_list;
485            return content_range_list.swap_remove(0).body;
486        }
487
488        if content_range_list.len() > one {
489            // RFC 2046 §5.1.1: each part opens with "--boundary", the body
490            // closes with "--boundary--" (#53).
491            let boundary = Range::multipart_boundary(&content_range_list);
492            for (i, content_range) in content_range_list.iter().enumerate() {
493                let mut body_str = SYMBOL.empty_string.to_string();
494                if i != 0 {
495                    body_str.push_str(SYMBOL.new_line_carriage_return);
496                }
497                body_str.push_str(SYMBOL.hyphen);
498                body_str.push_str(SYMBOL.hyphen);
499                body_str.push_str(&boundary);
500                body_str.push_str(SYMBOL.new_line_carriage_return);
501                let content_type = [Header::_CONTENT_TYPE, Header::NAME_VALUE_SEPARATOR, SYMBOL.whitespace, &Header::single_line(&content_range.content_type)].join("");
502                body_str.push_str(content_type.as_str());
503                body_str.push_str(SYMBOL.new_line_carriage_return);
504                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("");
505                body_str.push_str(content_range_header.as_str());
506                body_str.push_str(SYMBOL.new_line_carriage_return);
507                body_str.push_str(SYMBOL.new_line_carriage_return);
508
509                body.extend_from_slice(body_str.as_bytes());
510                body.extend_from_slice(&content_range.body);
511            }
512            body.extend_from_slice(b"\r\n--");
513            body.extend_from_slice(boundary.as_bytes());
514            body.extend_from_slice(b"--\r\n");
515        }
516
517        body
518    }
519
520    /// The serialized response: status line + headers, then the body.
521    pub fn generate_response(response: Response, request: Request) -> Vec<u8> {
522        Response::generate_response_coalesced(response, request, usize::MAX).0
523    }
524
525    /// Like [`generate_response`](Self::generate_response), but returns the
526    /// head (status line + headers + blank line) and the body separately, so
527    /// a connection writer can send them back to back without first copying
528    /// a large body into one combined buffer. The body is empty for HEAD and
529    /// for a status without content.
530    pub fn generate_response_parts(response: Response, request: Request) -> (Vec<u8>, Vec<u8>) {
531        Response::generate_response_coalesced(response, request, 0)
532    }
533
534    /// [`generate_response_parts`](Self::generate_response_parts), except
535    /// that a body of at most `coalesce_limit` bytes is appended to the head
536    /// (sized for both up front) and the returned body is then empty — one
537    /// buffer for one `write`, without growing the head afterwards.
538    pub(crate) fn generate_response_coalesced(mut response: Response, request: Request, coalesce_limit: usize) -> (Vec<u8>, Vec<u8>) {
539        response.drop_content_for_status();
540        let streamed = response.stream_pipe.is_some() || response.stream_file.is_some();
541        let Response { http_version, status_code, reason_phrase, headers, mut content_range_list, .. } = response;
542
543        // Content-Type, Content-Range and Content-Length follow the other
544        // headers; they're written straight into the head rather than pushed
545        // onto `headers` first.
546        let mut content_type: Option<String> = None;
547        let mut content_range: Option<String> = None;
548        let mut content_length: Option<Decimal> = None;
549        if content_range_list.len() == 1 {
550            let range = &mut content_range_list[0];
551            content_range = content_range_header_value(status_code, range);
552            content_length = Some(Decimal::new(range.body.len() as u128));
553            // A single range's body is moved out by generate_body, which
554            // doesn't look at its type.
555            content_type = Some(std::mem::take(&mut range.content_type));
556        }
557        let multipart = content_range_list.len() > 1;
558        if multipart {
559            content_type = Some(Range::multipart_content_type(&content_range_list));
560        }
561
562        // HEAD: the head of the GET response, no body. OPTIONS gets its body
563        // like any other method: dropping it under a Content-Length that
564        // announced it left the client waiting (#54).
565        let is_head = request.method == METHOD.head;
566        let body = if is_head && !multipart {
567            Vec::new()
568        } else {
569            Response::generate_body(content_range_list)
570        };
571        if multipart {
572            // Without it a keep-alive client can't tell where the body ends
573            // (RFC 9112 §6.3; #53). A HEAD gets the GET's length.
574            content_length = Some(Decimal::new(body.len() as u128));
575        }
576        // No body at all: say so, or a keep-alive client waits for one until
577        // the connection closes (a gRPC-web trailers-only error hung a
578        // browser). Not for statuses that never have content, nor when the
579        // handler set the length itself, nor for a streamed body.
580        if content_length.is_none()
581            && !streamed
582            && !Response::status_has_no_content(status_code)
583            && !headers.iter().any(|h| h.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH))
584        {
585            content_length = Some(Decimal::new(0));
586        }
587        let body = if is_head { Vec::new() } else { body };
588        let coalesce = body.len() <= coalesce_limit;
589
590        // One buffer, sized up front, written once: this used to build a
591        // String per header, grow a second one, join the status line and
592        // copy it all again with format! — the biggest allocation cost of a
593        // small response.
594        let status = u16::try_from(status_code).map(|code| Decimal::new(code as u128));
595        let status_text = match &status {
596            Ok(decimal) => std::borrow::Cow::Borrowed(decimal.as_str()),
597            Err(_) => std::borrow::Cow::Owned(status_code.to_string()),
598        };
599        let extra = [
600            (Header::_CONTENT_TYPE, content_type.as_deref()),
601            (Header::_CONTENT_RANGE, content_range.as_deref()),
602            (Header::_CONTENT_LENGTH, content_length.as_ref().map(Decimal::as_str)),
603        ];
604        let capacity = http_version.len() + status_text.len() + reason_phrase.len() + 4
605            + headers.iter().map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
606            + extra.iter().map(|(name, value)| value.map_or(0, |v| name.len() + v.len() + 4)).sum::<usize>()
607            + 2
608            + if coalesce { body.len() } else { 0 };
609        let mut head = Vec::with_capacity(capacity);
610        head.extend_from_slice(http_version.as_bytes());
611        head.push(b' ');
612        head.extend_from_slice(status_text.as_bytes());
613        head.push(b' ');
614        head.extend_from_slice(Header::single_line(&reason_phrase).as_bytes());
615        head.extend_from_slice(b"\r\n");
616        let header_lines = headers.iter().map(|h| (h.name.as_ref(), h.value.as_ref()))
617            .chain(extra.iter().filter_map(|(name, value)| value.map(|v| (*name, v))));
618        for (name, value) in header_lines {
619            head.extend_from_slice(Header::single_line(name).as_bytes());
620            head.extend_from_slice(Header::NAME_VALUE_SEPARATOR.as_bytes());
621            head.extend_from_slice(Header::single_line(value).as_bytes());
622            head.extend_from_slice(b"\r\n");
623        }
624        head.extend_from_slice(b"\r\n");
625
626        if coalesce {
627            head.extend_from_slice(&body);
628            (head, Vec::new())
629        } else {
630            (head, body)
631        }
632    }
633
634    pub fn _parse_response(response_vec_u8: &[u8]) -> Response {
635        let mut cursor = io::Cursor::new(response_vec_u8);
636
637        let mut response = Response {
638            http_version: "".to_string(),
639            status_code: 0,
640            reason_phrase: "".to_string(),
641            headers: vec![],
642            content_range_list: vec![],
643            stream_file: None,
644            stream_pipe: None,
645            trailers: None,
646        };
647
648        let content_length: usize = 0;
649        let iteration_number : usize = 0;
650
651        Response::_parse_raw_response_via_cursor(&mut cursor, iteration_number, &mut response, content_length);
652
653        return response;
654    }
655
656    pub fn _parse_http_version_status_code_reason_phrase_string(http_version_status_code_reason_phrase: &str) -> Result<(String, i16, String), String> {
657        let line = without_cr_lf(http_version_status_code_reason_phrase);
658        let (http_version, status_code, reason_phrase) = Response::status_line_parts(&line)?;
659        Ok((http_version.to_string(), status_code, reason_phrase.to_string()))
660    }
661
662    /// `HTTP-version SP status-code [SP reason-phrase]`, CR/LF already
663    /// removed, borrowed from `line`.
664    fn status_line_parts(line: &str) -> Result<(&str, i16, &str), String> {
665        let boxed_split = line.split_once(SYMBOL.whitespace);
666        if boxed_split.is_none() {
667            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
668        }
669
670        let (http_version, status_code_reason_phrase) = boxed_split.unwrap();
671        if !HTTP::is_supported_version(http_version) {
672            return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string())
673        }
674
675        // RFC 9112 §4: status-line = HTTP-version SP status-code SP [ reason-phrase ].
676        // The reason phrase is optional free text that clients should ignore
677        // (Python's http.server sends "404 File not found"), and any 3-digit
678        // code is valid — so neither is checked against the known list.
679        let (status_code, reason_phrase) = status_code_reason_phrase
680            .split_once(SYMBOL.whitespace)
681            .unwrap_or((status_code_reason_phrase, ""));
682
683        let is_three_digits = status_code.len() == 3 && status_code.bytes().all(|b| b.is_ascii_digit());
684        let status_code_i16 = match status_code.parse::<i16>() {
685            Ok(code) if is_three_digits && code >= 100 => code,
686            _ => return Err(Response::_ERROR_UNABLE_TO_PARSE_HTTP_VERSION_STATUS_CODE.to_string()),
687        };
688
689        Ok((http_version, status_code_i16, reason_phrase))
690    }
691
692    pub fn _parse_http_response_header_string(header_string: &str) -> Header {
693        // A line without ": " (malformed upstream input) is a name with an
694        // empty value, as in Request::parse_http_request_header_string —
695        // not an index-out-of-bounds panic.
696        let (header_name, raw_header_value) = header_string
697            .split_once(Header::NAME_VALUE_SEPARATOR)
698            .unwrap_or((header_string, ""));
699        let header_value = StringExt::truncate_new_line_carriage_return(raw_header_value);
700
701
702        Header {
703            name: header_name.to_string().into(),
704            value: header_value.to_string().into()
705        }
706    }
707
708    pub fn _parse_raw_response_via_cursor(
709        cursor: &mut Cursor<&[u8]>,
710        mut iteration_number: usize,
711        response: &mut Response,
712        mut content_length: usize) {
713
714        let mut buffer = vec![];
715        let boxed_read = cursor.read_until(b'\n', &mut buffer);
716        if boxed_read.is_err() {
717            eprintln!("unable to parse raw response via cursor {}", boxed_read.err().unwrap());
718            return;
719        }
720        let bytes_offset = boxed_read.unwrap();
721        let mut buffer_as_u8_array: &[u8] = &buffer;
722        let string = String::from_utf8(Vec::from(buffer_as_u8_array)).unwrap();
723
724        let is_first_iteration = iteration_number == 0;
725        let new_line_char_found = bytes_offset != 0;
726        let current_string_is_empty = string.trim().len() == 0;
727
728        if is_first_iteration {
729            let boxed_http_version_status_code_reason_phrase = Response::_parse_http_version_status_code_reason_phrase_string(&string);
730            if boxed_http_version_status_code_reason_phrase.is_err() {
731                let error = boxed_http_version_status_code_reason_phrase.err().unwrap();
732                eprintln!("{}", error);
733                return;
734            }
735
736            let (http_version, status_code, reason_phrase) = boxed_http_version_status_code_reason_phrase.unwrap();
737
738            response.http_version = http_version;
739            response.status_code = status_code;
740            response.reason_phrase = reason_phrase;
741        }
742
743        if current_string_is_empty {
744            // No Content-Type (a 204, a 304): an empty, non-multipart body.
745            let content_type = response._get_header(Header::_CONTENT_TYPE.to_string()).cloned()
746                .unwrap_or(Header { name: Header::_CONTENT_TYPE.into(), value: "".into() });
747            let is_multipart = Response::_is_multipart_byteranges_content_type(&content_type);
748
749            if is_multipart {
750                let content_range_list : Vec<ContentRange> = vec![];
751
752                let boundary = content_type.value.split(';')
753                    .filter_map(|param| param.trim().strip_prefix("boundary="))
754                    .next()
755                    .map(|b| b.trim_matches('"').to_string())
756                    .unwrap_or_else(|| Range::STRING_SEPARATOR.to_string());
757                let mut buf = vec![];
758                let _ = cursor.read_until(b'\n', &mut buf);
759                let boxed_value = Range::_parse_multipart_body_with_boundary(cursor, content_range_list, &boundary);
760                let mut range_list = vec![];
761                if boxed_value.is_ok() {
762                    range_list = boxed_value.unwrap();
763                }
764                response.content_range_list = range_list;
765            } else {
766                buffer = vec![];
767                let boxed_read = cursor.read_to_end(&mut buffer);
768                if boxed_read.is_ok() {
769                    buffer_as_u8_array = &buffer;
770
771                    let content_range = ContentRange {
772                        unit: Range::BYTES.to_string(),
773                        range: Range {
774                            start: 0,
775                            end: buffer_as_u8_array.len() as u64
776                        },
777                        size: buffer_as_u8_array.len().to_string(),
778                        body: Vec::from(buffer_as_u8_array),
779                        content_type: content_type.value.to_string()
780                    };
781                    response.content_range_list = vec![content_range];
782                } else {
783                    let reason = boxed_read.err().unwrap();
784                    eprintln!("error reading file: {}", reason.to_string())
785                }
786
787            }
788
789            return;
790        }
791
792        if new_line_char_found && !current_string_is_empty {
793            let mut header = Header { name: "".into(), value: "".into() };
794            if !is_first_iteration {
795                header = Response::_parse_http_response_header_string(&string);
796                if header.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH) {
797                    // No error channel here: treat an invalid value as absent.
798                    content_length = header.value.trim().parse().unwrap_or(0);
799                }
800            }
801
802            response.headers.push(header);
803            iteration_number += 1;
804            Response::_parse_raw_response_via_cursor(cursor, iteration_number, response, content_length);
805        }
806    }
807
808    pub fn _is_multipart_byteranges_content_type(content_type: &Header) -> bool {
809        // Asked of every parsed (e.g. every proxied) response: no join.
810        content_type.value.strip_prefix(Range::MULTIPART)
811            .and_then(|rest| rest.strip_prefix(SYMBOL.slash))
812            .is_some_and(|rest| rest.starts_with(Range::BYTERANGES))
813    }
814
815
816    pub fn get_response(
817        status_code_reason_phrase: &StatusCodeReasonPhrase,
818        boxed_header_list: Option<Vec<Header>>,
819        boxed_content_range_list: Option<Vec<ContentRange>>) -> Response {
820
821        let mut header_list: Vec<Header> = vec![];
822        if boxed_header_list.is_some() {
823            header_list = boxed_header_list.unwrap();
824        }
825
826        let mut content_range_list: Vec<ContentRange> = vec![];
827        if boxed_content_range_list.is_some() {
828            content_range_list = boxed_content_range_list.unwrap();
829        }
830
831        let response = Response {
832            http_version: VERSION.http_1_1.to_string(),
833            status_code: *status_code_reason_phrase.status_code,
834            reason_phrase: status_code_reason_phrase.reason_phrase.to_string(),
835            headers: header_list,
836            content_range_list,
837            stream_file: None,
838            stream_pipe: None,
839            trailers: None,
840        };
841
842        response
843    }
844
845    /// Build a `Content-Type: application/json` response from already-serialized bytes.
846    ///
847    /// Takes raw bytes rather than a `Serialize` value so it carries no dependency on the
848    /// `serde` feature — pair it with `serde_json::to_vec` (or hand-rolled JSON) to build `body`.
849    /// For a one-line serialize-and-respond helper on a typed value, see [`crate::json::Json`]
850    /// (`serde` feature).
851    ///
852    /// ```rust,no_run
853    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
854    ///
855    /// let response = Response::json(STATUS_CODE_REASON_PHRASE.n200_ok, br#"{"ok":true}"#.to_vec());
856    /// ```
857    pub fn json(status_code_reason_phrase: &StatusCodeReasonPhrase, body: Vec<u8>) -> Response {
858        let content_range = Range::get_content_range(body, MimeType::APPLICATION_JSON.to_string());
859        Response::get_response(status_code_reason_phrase, None, Some(vec![content_range]))
860    }
861
862    /// Build a `Content-Type: text/plain` response from a body string.
863    ///
864    /// ```rust,no_run
865    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
866    ///
867    /// let response = Response::text(STATUS_CODE_REASON_PHRASE.n400_bad_request, "invalid input");
868    /// ```
869    pub fn text(status_code_reason_phrase: &StatusCodeReasonPhrase, body: &str) -> Response {
870        let content_range = Range::get_content_range(body.as_bytes().to_vec(), MimeType::TEXT_PLAIN.to_string());
871        Response::get_response(status_code_reason_phrase, None, Some(vec![content_range]))
872    }
873
874    pub fn generate(&mut self) -> Vec<u8> {
875        let response = &mut self.clone();
876        response.drop_content_for_status();
877
878        if response.content_range_list.len() == 1 {
879            let content_range_index = 0;
880            let content_range = response.content_range_list.get(content_range_index).unwrap();
881            response.headers.push(Header {
882                name: Header::_CONTENT_TYPE.into(),
883                value: content_range.content_type.to_string().into()
884            });
885
886            if let Some(value) = content_range_header_value(response.status_code, content_range) {
887                response.headers.push(Header {
888                    name: Header::_CONTENT_RANGE.into(),
889                    value: value.into(),
890                });
891            }
892
893            response.headers.push(Header {
894                name: Header::_CONTENT_LENGTH.into(),
895                value: content_range.body.len().to_string().into()
896            });
897        }
898
899        if response.content_range_list.len() > 1 {
900            response.headers.push(Header {
901                name: Header::_CONTENT_TYPE.into(),
902                value: Range::multipart_content_type(&response.content_range_list).into(),
903            });
904        }
905
906        let response_clone = response.clone();
907        let body = Response::generate_body(response_clone.content_range_list);
908        if response.content_range_list.len() > 1 {
909            response.headers.push(Header {
910                name: Header::_CONTENT_LENGTH.into(),
911                value: body.len().to_string().into(),
912            });
913        }
914
915        let mut headers_str = SYMBOL.new_line_carriage_return.to_string();
916
917        let header_list = response.headers.clone();
918        for header in header_list {
919            let mut header_string = SYMBOL.empty_string.to_string();
920            header_string.push_str(&Header::single_line(&header.name));
921            header_string.push_str(Header::NAME_VALUE_SEPARATOR);
922            header_string.push_str(&Header::single_line(&header.value));
923            header_string.push_str(SYMBOL.new_line_carriage_return);
924            headers_str.push_str(&header_string);
925        }
926
927        let response_clone = response.clone();
928        let status = [response_clone.http_version, response.status_code.to_string(), Header::single_line(&response_clone.reason_phrase).into_owned()].join(SYMBOL.whitespace);
929        let response_without_body = format!(
930            "{}{}{}",
931            status,
932            headers_str,
933            SYMBOL.new_line_carriage_return,
934        );
935
936
937        [response_without_body.into_bytes(), body].concat()
938    }
939
940    pub fn get_header(&self, name: String) -> Option<&Header> {
941        self._get_header(name)
942    }
943
944    /// The first header named `name` (case-insensitive), without allocating.
945    pub fn header(&self, name: &str) -> Option<&Header> {
946        self.headers.iter().find(|h| h.name.eq_ignore_ascii_case(name))
947    }
948
949    pub fn parse(response_vec_u8: &[u8]) -> Result<Response, String> {
950        let total_bytes : i32 = response_vec_u8.len() as i32;
951        let bytes_read = 0;
952        let mut cursor = io::Cursor::new(response_vec_u8);
953
954        let mut response = Response {
955            http_version: "".to_string(),
956            status_code: 0,
957            reason_phrase: "".to_string(),
958            // Typical upstream heads have 6–16 headers: grown 1→2→4→8→16
959            // this was four allocations per proxied response.
960            headers: Vec::with_capacity(16),
961            content_range_list: vec![],
962            stream_file: None,
963            stream_pipe: None,
964            trailers: None,
965        };
966
967        let content_length: usize = 0;
968        let iteration_number : usize = 0;
969
970        let boxed_parse = Response::parse_raw_response_via_cursor(
971            &mut cursor, iteration_number,
972            &mut response,
973            content_length,
974            total_bytes,
975            bytes_read
976        );
977        if boxed_parse.is_err() {
978            let message = boxed_parse.err().unwrap();
979            return Err(message);
980        }
981
982        return Ok(response);
983    }
984
985    /// [`Response::parse`] and `proxy::normalize_upstream_response` in one
986    /// pass, for a buffered upstream response: the status line is re-emitted
987    /// as HTTP/1.1, headers named in `dropped` (compared ignoring ASCII case)
988    /// are skipped before their value is copied, and every `Content-Type`
989    /// moves onto the body (the first one is its type). A
990    /// `multipart/byteranges` response goes the general way. The result is
991    /// what the two-step path builds (`response_tests::parse_upstream_*`) —
992    /// minus a copy per dropped header, a second scan for `Content-Type`
993    /// and the `retain` that removed them.
994    pub(crate) fn parse_upstream(input: &[u8], dropped: &[&str]) -> Result<Response, String> {
995        let mut response = Response {
996            http_version: crate::http::VERSION.http_1_1.to_string(),
997            status_code: 0,
998            reason_phrase: String::new(),
999            headers: Vec::with_capacity(16),
1000            content_range_list: vec![],
1001            stream_file: None,
1002            stream_pipe: None,
1003            trailers: None,
1004        };
1005        let mut content_type: Option<&str> = None;
1006        let mut pos = 0usize;
1007        let mut first = true;
1008        loop {
1009            let rest = &input[pos.min(input.len())..];
1010            let line_len = memchr::memchr(b'\n', rest).map_or(rest.len(), |i| i + 1);
1011            pos += line_len;
1012            let line = std::str::from_utf8(&rest[..line_len]).map_err(|e| e.to_string())?;
1013            if first {
1014                let status_line = without_cr_lf(line);
1015                let (_, status_code, reason_phrase) = Response::status_line_parts(&status_line)?;
1016                response.status_code = status_code;
1017                response.reason_phrase = reason_phrase.to_string();
1018            }
1019            if is_blank(line) {
1020                if content_type.is_some_and(|ct| ct.starts_with("multipart/byteranges")) {
1021                    return Response::parse(input).map(normalized_like_proxy(dropped));
1022                }
1023                let body = input[pos.min(input.len())..].to_vec();
1024                response.content_range_list = vec![ContentRange {
1025                    unit: Range::BYTES.to_string(),
1026                    range: Range { start: 0, end: body.len() as u64 },
1027                    size: Decimal::new(body.len() as u128).as_str().to_string(),
1028                    content_type: content_type.unwrap_or(MimeType::APPLICATION_OCTET_STREAM).to_string(),
1029                    body,
1030                }];
1031                return Ok(response);
1032            }
1033            if line_len == 0 {
1034                return Err("unable to parse".to_string());
1035            }
1036            if !first {
1037                let (name, raw_value) = split_name_value(line).ok_or_else(|| format!("unable to parse header: {}", line))?;
1038                if name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH) {
1039                    let value = without_cr_lf(raw_value);
1040                    let _: usize = value.trim().parse().map_err(|_| format!("invalid Content-Length: {:?}", value))?;
1041                }
1042                if name.eq_ignore_ascii_case(Header::_CONTENT_TYPE) {
1043                    if content_type.is_none() {
1044                        // Borrowed from `input`; an embedded CR/LF (rare)
1045                        // falls back to the general path to stay exact.
1046                        match without_cr_lf(raw_value) {
1047                            std::borrow::Cow::Borrowed(v) => content_type = Some(v),
1048                            std::borrow::Cow::Owned(_) => return Response::parse(input).map(normalized_like_proxy(dropped)),
1049                        }
1050                    }
1051                    continue;
1052                }
1053                if !dropped.iter().any(|d| name.eq_ignore_ascii_case(d)) {
1054                    response.headers.push(Header {
1055                        name: Header::name_from(name),
1056                        value: without_cr_lf(raw_value).into_owned().into(),
1057                    });
1058                }
1059            }
1060            first = false;
1061        }
1062    }
1063
1064    pub fn parse_raw_response_via_cursor(
1065        cursor: &mut Cursor<&[u8]>,
1066        mut iteration_number: usize,
1067        response: &mut Response,
1068        _content_length: usize,
1069        total_bytes: i32,
1070        mut bytes_read: i32) -> Result<(), String> {
1071        // One pass over the input: each line is a slice of it (this used to
1072        // copy every line into a Vec and then a String, and strip CR/LF with
1073        // two `str::replace` allocations per header), and only the values
1074        // kept are allocated. A loop, not recursion: one stack frame per
1075        // header line let a backend overflow the stack.
1076        let input: &[u8] = cursor.get_ref();
1077        loop {
1078            let start = (cursor.position() as usize).min(input.len());
1079            let rest = &input[start..];
1080            let line_len = memchr::memchr(b'\n', rest).map_or(rest.len(), |i| i + 1);
1081            cursor.set_position((start + line_len) as u64);
1082            bytes_read += line_len as i32;
1083            let line = std::str::from_utf8(&rest[..line_len]).map_err(|e| e.to_string())?;
1084
1085            let is_first_iteration = iteration_number == 0;
1086            let new_line_char_found = line_len != 0;
1087            let current_string_is_empty = is_blank(line);
1088
1089            if is_first_iteration {
1090                let status_line = without_cr_lf(line);
1091                let (http_version, status_code, reason_phrase) = Response::status_line_parts(&status_line)?;
1092                response.http_version = http_version.to_string();
1093                response.status_code = status_code;
1094                response.reason_phrase = reason_phrase.to_string();
1095            }
1096
1097            if current_string_is_empty {
1098                // if response does not contain Content-Type, it will be defaulted to APPLICATION_OCTET_STREAM
1099                let content_type_header = response.header(Header::_CONTENT_TYPE);
1100                let is_multipart = content_type_header.map_or(false, Response::_is_multipart_byteranges_content_type);
1101
1102                if is_multipart {
1103                    let content_type = response.header(Header::_CONTENT_TYPE).ok_or("Content-Type is missing")?;
1104                    let boundary = FormMultipartData::extract_boundary(content_type.value.as_ref())
1105                        .map_err(|_| "unable to extract boundary from Content-Type".to_string())?;
1106                    let is_opening_boundary_read = false;
1107                    response.content_range_list = Range::parse_multipart_body_with_boundary(
1108                        cursor,
1109                        vec![],
1110                        boundary,
1111                        total_bytes,
1112                        bytes_read,
1113                        is_opening_boundary_read)?;
1114                } else {
1115                    let content_type = content_type_header.map_or(MimeType::APPLICATION_OCTET_STREAM, |h| h.value.as_ref());
1116                    let start = (cursor.position() as usize).min(input.len());
1117                    let body = input[start..].to_vec();
1118                    cursor.set_position(input.len() as u64);
1119                    let content_range = ContentRange {
1120                        unit: Range::BYTES.to_string(),
1121                        range: Range {
1122                            start: 0,
1123                            end: body.len() as u64
1124                        },
1125                        size: Decimal::new(body.len() as u128).as_str().to_string(),
1126                        content_type: content_type.to_string(),
1127                        body,
1128                    };
1129                    response.content_range_list = vec![content_range];
1130                }
1131
1132                return Ok(());
1133            }
1134
1135            if new_line_char_found {
1136                if !is_first_iteration {
1137                    let header = Response::parse_http_response_header_string(line)?;
1138                    if header.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH) {
1139                        // An upstream-supplied value: reject garbage instead of panicking.
1140                        let _: usize = header.value.trim().parse()
1141                            .map_err(|_| format!("invalid Content-Length: {:?}", header.value))?;
1142                    }
1143                    response.headers.push(header);
1144                }
1145
1146                iteration_number += 1;
1147            } else {
1148                return Err("unable to parse".to_string());
1149            }
1150        }
1151    }
1152
1153    pub fn parse_http_response_header_string(header_string: &str) -> Result<Header, String> {
1154        match split_name_value(header_string) {
1155            Some((header_name, raw_header_value)) => Ok(Header {
1156                name: Header::name_from(header_name),
1157                value: without_cr_lf(raw_header_value).into_owned().into(),
1158            }),
1159            None => Err(format!("unable to parse header: {}", header_string)),
1160        }
1161    }
1162}
1163
1164impl Default for Response {
1165    /// The same as `Response::new()`: HTTP/1.1, no headers, no body, status
1166    /// `501 Not Implemented` until you set one.
1167    fn default() -> Self {
1168        <Response as New>::new()
1169    }
1170}
1171
1172impl New for Response {
1173    fn new() -> Self {
1174        Response {
1175            http_version: VERSION.http_1_1.to_string(),
1176            status_code: *STATUS_CODE_REASON_PHRASE.n501_not_implemented.status_code,
1177            reason_phrase: STATUS_CODE_REASON_PHRASE.n501_not_implemented.reason_phrase.to_string(),
1178            headers: vec![],
1179            content_range_list: vec![],
1180            stream_file: None,
1181            stream_pipe: None,
1182            trailers: None,
1183        }
1184    }
1185}
1186/// The general path of [`Response::parse_upstream`]: what
1187/// `proxy::normalize_upstream_response` does to a parsed response.
1188fn normalized_like_proxy<'a>(dropped: &'a [&'a str]) -> impl FnOnce(Response) -> Response + 'a {
1189    move |mut response: Response| {
1190        response.http_version.clear();
1191        response.http_version.push_str(crate::http::VERSION.http_1_1);
1192        let has_body = !response.content_range_list.is_empty();
1193        if let [range] = response.content_range_list.as_mut_slice() {
1194            if let Some(h) = response.headers.iter().find(|h| h.name.eq_ignore_ascii_case(Header::_CONTENT_TYPE)) {
1195                range.content_type.clear();
1196                range.content_type.push_str(&h.value);
1197            }
1198        }
1199        response.headers.retain(|h| {
1200            if h.name.eq_ignore_ascii_case(Header::_CONTENT_TYPE) {
1201                return !has_body;
1202            }
1203            !dropped.iter().any(|d| h.name.eq_ignore_ascii_case(d))
1204        });
1205        response
1206    }
1207}
1208
1209/// `s` with every CR and LF removed — borrowed when they only end the line.
1210/// `line.trim().is_empty()`, deciding on the first byte for the usual
1211/// header line instead of decoding chars from both ends.
1212fn is_blank(line: &str) -> bool {
1213    match line.bytes().find(|b| !b.is_ascii_whitespace()) {
1214        None => true,
1215        Some(b) if b.is_ascii() => false,
1216        Some(_) => line.trim().is_empty(),
1217    }
1218}
1219
1220fn without_cr_lf(s: &str) -> std::borrow::Cow<'_, str> {
1221    let trimmed = s.strip_suffix('\n').unwrap_or(s);
1222    let trimmed = trimmed.strip_suffix('\r').unwrap_or(trimmed);
1223    if memchr::memchr2(b'\r', b'\n', trimmed.as_bytes()).is_some() {
1224        std::borrow::Cow::Owned(StringExt::truncate_new_line_carriage_return(s))
1225    } else {
1226        std::borrow::Cow::Borrowed(trimmed)
1227    }
1228}
1229
1230/// `line` split at its first `": "` — what `split_once(": ")` returns,
1231/// without a substring searcher.
1232fn split_name_value(line: &str) -> Option<(&str, &str)> {
1233    let bytes = line.as_bytes();
1234    let mut from = 0;
1235    while let Some(offset) = memchr::memchr(b':', &bytes[from..]) {
1236        let colon = from + offset;
1237        if bytes.get(colon + 1) == Some(&b' ') {
1238            return Some((&line[..colon], &line[colon + 2..]));
1239        }
1240        from = colon + 1;
1241    }
1242    None
1243}