Skip to main content

aria2_protocol/http/
response.rs

1use tracing::debug;
2
3/// HTTP status codes that aria2 treats as redirects.
4///
5/// `304 Not Modified` is intentionally excluded: it is a conditional
6/// response, not a redirect, even though it is in the 3xx range.
7pub fn is_redirect_status(status_code: u16) -> bool {
8    matches!(status_code, 300..=303 | 307 | 308)
9}
10
11#[derive(Debug, Clone)]
12pub struct HttpResponse {
13    pub status_code: u16,
14    pub status_text: String,
15    pub headers: Vec<(String, String)>,
16    pub body: Vec<u8>,
17}
18
19impl HttpResponse {
20    pub fn new(status_code: u16, status_text: String) -> Self {
21        Self {
22            status_code,
23            status_text,
24            headers: Vec::new(),
25            body: Vec::new(),
26        }
27    }
28
29    pub fn is_success(&self) -> bool {
30        (200..300).contains(&self.status_code)
31    }
32
33    pub fn is_redirect(&self) -> bool {
34        // Match C++ `HttpResponse::isRedirect()`: a recognized redirect status
35        // is actionable only when the response supplies a Location header.
36        is_redirect_status(self.status_code) && self.location().is_some()
37    }
38
39    pub fn is_partial_content(&self) -> bool {
40        self.status_code == 206
41    }
42
43    pub fn is_client_error(&self) -> bool {
44        (400..500).contains(&self.status_code)
45    }
46
47    pub fn is_server_error(&self) -> bool {
48        (500..600).contains(&self.status_code)
49    }
50
51    pub fn header(&self, name: &str) -> Option<&String> {
52        self.headers
53            .iter()
54            .find(|(k, _)| k.eq_ignore_ascii_case(name))
55            .map(|(_, v)| v)
56    }
57
58    pub fn header_all(&self, name: &str) -> Vec<&String> {
59        self.headers
60            .iter()
61            .filter(|(k, _)| k.eq_ignore_ascii_case(name))
62            .map(|(_, v)| v)
63            .collect()
64    }
65
66    pub fn content_length(&self) -> Option<u64> {
67        self.header("content-length")
68            .and_then(|v| v.parse::<u64>().ok())
69    }
70
71    pub fn content_type(&self) -> Option<&str> {
72        self.header("content-type").map(|s| s.as_str())
73    }
74
75    pub fn content_encoding(&self) -> Option<&str> {
76        self.header("content-encoding").map(|s| s.as_str())
77    }
78
79    pub fn content_disposition(&self) -> Option<&str> {
80        self.header("content-disposition").map(|s| s.as_str())
81    }
82
83    pub fn accept_ranges(&self) -> bool {
84        self.header("accept-ranges")
85            .map(|v| v.eq_ignore_ascii_case("bytes"))
86            .unwrap_or(false)
87    }
88
89    pub fn location(&self) -> Option<&str> {
90        self.header("location").map(|s| s.as_str())
91    }
92
93    pub fn etag(&self) -> Option<&str> {
94        self.header("etag").map(|s| s.as_str())
95    }
96
97    pub fn last_modified(&self) -> Option<&str> {
98        self.header("last-modified").map(|s| s.as_str())
99    }
100
101    pub fn server(&self) -> Option<&str> {
102        self.header("server").map(|s| s.as_str())
103    }
104
105    pub fn connection(&self) -> Option<&str> {
106        self.header("connection").map(|s| s.as_str())
107    }
108
109    pub fn transfer_encoding(&self) -> Option<&str> {
110        self.header("transfer-encoding").map(|s| s.as_str())
111    }
112
113    pub fn body_as_utf8(&self) -> Result<&str, std::str::Utf8Error> {
114        std::str::from_utf8(&self.body)
115    }
116
117    pub fn body_len(&self) -> usize {
118        self.body.len()
119    }
120
121    pub fn parse_content_range(&self) -> Option<ContentRange> {
122        let raw = self.header("content-range")?;
123        ContentRange::parse(raw)
124    }
125}
126
127#[derive(Debug, Clone, PartialEq)]
128pub struct ContentRange {
129    pub unit: String,
130    pub start: u64,
131    pub end: u64,
132    pub total_size: Option<u64>,
133}
134
135impl ContentRange {
136    pub fn parse(value: &str) -> Option<Self> {
137        let value = value.trim();
138        if !value.starts_with("bytes ") {
139            debug!("Content-Range format error: not 'bytes' unit");
140            return None;
141        }
142
143        let range_part = &value[6..];
144        let parts: Vec<&str> = range_part.split('/').collect();
145        if parts.len() != 2 {
146            debug!("Content-Range format error: split failed");
147            return None;
148        }
149
150        let range_values: Vec<&str> = parts[0].split('-').collect();
151        if range_values.len() != 2 {
152            debug!("Content-Range range parse failed");
153            return None;
154        }
155
156        let start: u64 = range_values[0].trim().parse().ok()?;
157        let end: u64 = range_values[1].trim().parse().ok()?;
158        let total_size = match parts[1].trim() {
159            "*" => None,
160            s => s.parse().ok(),
161        };
162
163        Some(Self {
164            unit: "bytes".to_string(),
165            start,
166            end,
167            total_size,
168        })
169    }
170
171    pub fn size(&self) -> u64 {
172        self.end - self.start + 1
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use crate::http::request::HttpRequest;
180
181    #[test]
182    fn test_response_status_checks() {
183        let resp_ok = HttpResponse::new(200, "OK".into());
184        assert!(resp_ok.is_success());
185        assert!(!resp_ok.is_redirect());
186        assert!(!resp_ok.is_partial_content());
187
188        let resp_206 = HttpResponse::new(206, "Partial Content".into());
189        assert!(resp_206.is_success());
190        assert!(resp_206.is_partial_content());
191
192        let mut resp_301 = HttpResponse::new(301, "Moved".into());
193        resp_301
194            .headers
195            .push(("Location".to_string(), "/new".to_string()));
196        assert!(resp_301.is_redirect());
197
198        let resp_302_without_location = HttpResponse::new(302, "Found".into());
199        assert!(!resp_302_without_location.is_redirect());
200
201        let mut resp_300 = HttpResponse::new(300, "Multiple Choices".into());
202        resp_300
203            .headers
204            .push(("Location".to_string(), "/choice".to_string()));
205        assert!(resp_300.is_redirect());
206
207        let resp_404 = HttpResponse::new(404, "Not Found".into());
208        assert!(resp_404.is_client_error());
209
210        let resp_500 = HttpResponse::new(500, "Server Error".into());
211        assert!(resp_500.is_server_error());
212    }
213
214    #[test]
215    fn test_headers_lookup() {
216        let mut resp = HttpResponse::new(200, "OK".into());
217        resp.headers
218            .push(("Content-Length".to_string(), "1024".to_string()));
219        resp.headers.push((
220            "Content-Type".to_string(),
221            "application/octet-stream".to_string(),
222        ));
223
224        assert_eq!(resp.content_length(), Some(1024));
225        assert_eq!(resp.content_type(), Some("application/octet-stream"));
226        assert_eq!(resp.header("content-length"), Some(&"1024".to_string()));
227    }
228
229    #[test]
230    fn test_content_range_parse() {
231        let cr = ContentRange::parse("bytes 0-499/1000").unwrap();
232        assert_eq!(cr.start, 0);
233        assert_eq!(cr.end, 499);
234        assert_eq!(cr.total_size, Some(1000));
235        assert_eq!(cr.size(), 500);
236
237        let cr_unknown_total = ContentRange::parse("bytes 0-499/*").unwrap();
238        assert_eq!(cr_unknown_total.total_size, None);
239
240        assert!(ContentRange::parse("invalid").is_none());
241        assert!(ContentRange::parse("bits 0-499/1000").is_none());
242    }
243
244    #[test]
245    fn test_request_builder() {
246        let req = HttpRequest::get("https://example.com/file.bin")
247            .with_range(500, Some(999))
248            .with_user_agent(crate::identity::DEFAULT_USER_AGENT);
249
250        assert_eq!(req.method, "GET");
251        assert!(req.has_range());
252        assert_eq!(req.get_header("Range"), Some(&"bytes=500-999".to_string()));
253        assert_eq!(
254            req.get_header("User-Agent"),
255            Some(&crate::identity::DEFAULT_USER_AGENT.to_string())
256        );
257    }
258}