Skip to main content

cosmic_applet_avestruz/
http.rs

1// SPDX-License-Identifier: MIT
2
3//! Fetching from the web: the one client everything is fetched with, and
4//! the one way of fetching.
5//!
6//! Every address comes from whoever wrote a profile or a note. Only `https`
7//! is fetched, redirects included; nothing waits longer than
8//! [`FETCH_TIMEOUT`]; and no more is read than the caller is ready to keep,
9//! so a hostile address costs a refused request at worst. Of a web page
10//! only the head is read, and that only if the server calls it a page.
11//!
12//! Videos are the one thing fetched that is not fetched here: see
13//! [`crate::video`].
14
15use std::time::Duration;
16
17/// How long anything gets to arrive.
18const FETCH_TIMEOUT: Duration = Duration::from_secs(20);
19
20/// The HTTP client: `https` only, redirects included, and never waiting
21/// longer than [`FETCH_TIMEOUT`].
22pub fn client() -> reqwest::Client {
23    reqwest::Client::builder()
24        .https_only(true)
25        .timeout(FETCH_TIMEOUT)
26        .user_agent(concat!("avestruz/", env!("CARGO_PKG_VERSION")))
27        .build()
28        .unwrap_or_default()
29}
30
31/// What is at `url`, if it answers with success and is no more than
32/// `max_bytes` long.
33pub async fn get(http: &reqwest::Client, url: &str, max_bytes: usize) -> Result<Vec<u8>, String> {
34    let response = http.get(url).send().await.map_err(|e| e.to_string())?;
35    read(response, max_bytes).await
36}
37
38/// As [`get`], of an address that has to answer for itself: what came from
39/// anywhere it sent the request on to is refused.
40pub async fn get_in_place(http: &reqwest::Client, url: &str, max_bytes: usize) -> Result<Vec<u8>, String> {
41    let response = http.get(url).send().await.map_err(|e| e.to_string())?;
42    if response.url().as_str() != url {
43        return Err("redirected".to_string());
44    }
45    read(response, max_bytes).await
46}
47
48/// What `response` carries, if it is a success and no more than `max_bytes`
49/// long.
50async fn read(response: reqwest::Response, max_bytes: usize) -> Result<Vec<u8>, String> {
51    let mut response = response.error_for_status().map_err(|e| e.to_string())?;
52    if response.content_length().is_some_and(|length| length > max_bytes as u64) {
53        return Err(format!("larger than {max_bytes} bytes"));
54    }
55
56    // A server may not say how much it will send, or may say less than it
57    // does: count what arrives.
58    let mut bytes = Vec::new();
59    while let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? {
60        if bytes.len() + chunk.len() > max_bytes {
61            return Err(format!("larger than {max_bytes} bytes"));
62        }
63        bytes.extend_from_slice(&chunk);
64    }
65    Ok(bytes)
66}
67
68/// What `url` answers when it is asked for `accept`, up to `max_bytes`:
69/// a relay's account of itself, say, which is at the relay's own address
70/// for whoever asks for that and not for a page.
71pub async fn get_as(http: &reqwest::Client, url: &str, accept: &str, max_bytes: usize) -> Result<Vec<u8>, String> {
72    let response = http.get(url).header(reqwest::header::ACCEPT, accept).send().await.map_err(|e| e.to_string())?;
73    let response = response.error_for_status().map_err(|e| e.to_string())?;
74    read(response, max_bytes).await
75}
76
77/// The head of a web page: where it was found, after whatever redirects,
78/// and its bytes as far as they were read.
79pub struct PageHead {
80    pub url: reqwest::Url,
81    pub bytes: Vec<u8>,
82}
83
84/// What a link turned out to be, asked for as a web page.
85pub enum Linked {
86    /// A page: its head.
87    Page(PageHead),
88    /// A video, as its server calls it. None of it was read.
89    Video,
90}
91
92/// The media type in what a server calls `content_type`, without what
93/// follows it.
94fn media_type(content_type: &str) -> &str {
95    content_type.split(';').next().unwrap_or_default().trim()
96}
97
98/// Whether what a server calls `content_type` is a web page.
99fn is_html(content_type: &str) -> bool {
100    let kind = media_type(content_type);
101    kind.eq_ignore_ascii_case("text/html") || kind.eq_ignore_ascii_case("application/xhtml+xml")
102}
103
104/// Whether what a server, or a note, calls `content_type` is a video.
105pub fn is_video(content_type: &str) -> bool {
106    media_type(content_type).get(.."video/".len()).is_some_and(|start| start.eq_ignore_ascii_case("video/"))
107}
108
109/// Where the head of a page ends in `bytes`, looking from `from` on: at the
110/// tag that closes it, or the one that opens the body.
111fn head_end(bytes: &[u8], from: usize) -> Option<usize> {
112    const ENDS: [&[u8]; 2] = [b"</head", b"<body"];
113    (from..bytes.len())
114        .find(|&at| ENDS.iter().any(|end| bytes.get(at..at + end.len()).is_some_and(|tag| tag.eq_ignore_ascii_case(end))))
115}
116
117/// The head of the web page at `url`: what it sends until its head ends,
118/// and `max_bytes` of it at most. Unlike [`get`], a page longer than that
119/// is no error: the rest is left unread. What the server doesn't call a
120/// web page is refused before any of it is read; if it calls it a video,
121/// that is the answer.
122pub async fn get_page_head(http: &reqwest::Client, url: &str, max_bytes: usize) -> Result<Linked, String> {
123    let response = http.get(url).header(reqwest::header::ACCEPT, "text/html").send().await.map_err(|e| e.to_string())?;
124    let mut response = response.error_for_status().map_err(|e| e.to_string())?;
125    let content_type = response.headers().get(reqwest::header::CONTENT_TYPE).and_then(|value| value.to_str().ok());
126    if content_type.is_some_and(is_video) {
127        return Ok(Linked::Video);
128    }
129    if !content_type.is_some_and(is_html) {
130        return Err(format!("not a web page: {}", content_type.unwrap_or("of no kind it names")));
131    }
132
133    let url = response.url().clone();
134    let mut bytes = Vec::new();
135    while bytes.len() < max_bytes {
136        let Some(chunk) = response.chunk().await.map_err(|e| e.to_string())? else {
137            break;
138        };
139        // A tag may lie across two chunks: look again from a little before
140        // the new one.
141        let from = bytes.len().saturating_sub(8);
142        let room = max_bytes - bytes.len();
143        bytes.extend(chunk.iter().take(room));
144        if let Some(end) = head_end(&bytes, from) {
145            bytes.truncate(end);
146            break;
147        }
148    }
149    Ok(Linked::Page(PageHead { url, bytes }))
150}
151
152#[cfg(test)]
153mod tests {
154    use super::{head_end, is_html, is_video};
155
156    #[test]
157    fn a_web_page_is_what_the_server_calls_one() {
158        assert!(is_html("text/html"));
159        assert!(is_html("Text/HTML; charset=utf-8"));
160        assert!(is_html("application/xhtml+xml"));
161        for other in ["application/pdf", "video/mp4", "text/plain", "application/json", ""] {
162            assert!(!is_html(other), "{other}");
163        }
164    }
165
166    #[test]
167    fn a_video_is_what_the_server_calls_one() {
168        for video in ["video/mp4", "Video/WebM; codecs=vp9", " video/quicktime "] {
169            assert!(is_video(video), "{video}");
170        }
171        for other in ["text/html", "application/octet-stream", "audio/mpeg", "image/gif", "video", ""] {
172            assert!(!is_video(other), "{other}");
173        }
174    }
175
176    #[test]
177    fn the_head_of_a_page_ends_where_it_closes_or_the_body_opens() {
178        let page = b"<html><head><title>a</title></HEAD><body>text</body>";
179        assert_eq!(head_end(page, 0), Some(28));
180        assert_eq!(head_end(b"<title>a</title><BODY class=x>", 0), Some(16), "a head that is never closed");
181        assert_eq!(head_end(b"<html><head><title>a</title><meta", 0), None, "not there yet");
182        // Looked for from where the last look left off, less a tag's length.
183        assert_eq!(head_end(page, 28), Some(28));
184        assert_eq!(head_end(page, 29), Some(35), "the body, having missed the end of the head");
185    }
186
187    #[test]
188    fn one_tls_provider_is_compiled_in() {
189        // With no provider installed by name (as `main` does), rustls has to
190        // work one out from its crate features, and panics if it finds two.
191        // That is what a dependency turning on a second provider looks like,
192        // and it would cost a second crypto library in the binary.
193        let _ = rustls::ClientConfig::builder();
194        let _ = super::client();
195    }
196}