1
//! One way to turn a URI into bytes, whatever scheme it names.
2
//!
3
//! Several places now hold a URI-valued field and need the CONTENT rather than
4
//! the string: album art (`NowPlayingInfo::artwork_url`), and anything else
5
//! that follows. Each of them faces the same two-case split - a local file is
6
//! a `read`, a remote one is an HTTP GET - and writing that split per call site
7
//! is how one of them ends up supporting only half the schemes, which is
8
//! exactly what the macOS artwork path did.
9
//!
10
//! # Scheme handling
11
//!
12
//! | input | route |
13
//! |---|---|
14
//! | `file:///a/b.png` | percent-DECODED, then read from disk |
15
//! | `/a/b.png`, `b.png` | read from disk as written |
16
//! | `http://…`, `https://…` | `HttpRequestConfig::http_get` |
17
//! | anything else | rejected by name, not silently treated as a path |
18
//!
19
//! A bare path is deliberately accepted: an app that stored a filename rather
20
//! than a URI is the common case, and `Url::parse` rejects it precisely because
21
//! it is not a URL.
22
//!
23
//! # This does NOT decide WHERE to call it from
24
//!
25
//! [`fetch_uri`] blocks. That is correct for a file and wrong for a network
26
//! round trip on the event loop, so a caller that may be handed a remote URI
27
//! runs it on a thread and re-publishes when the bytes land. Keeping the policy
28
//! out of here is what lets a caller that only ever sees local paths stay
29
//! synchronous.
30

            
31
use alloc::{string::String, vec::Vec};
32

            
33
/// Why a fetch produced no bytes.
34
#[derive(Debug, Clone, PartialEq, Eq)]
35
pub enum FetchError {
36
    /// The URI names a scheme this cannot resolve (`data:`, `ftp:`, …).
37
    UnsupportedScheme(String),
38
    /// A local read failed - missing file, no permission.
39
    Io(String),
40
    /// The HTTP request failed, or answered with a non-2xx status.
41
    Http(String),
42
    /// The `http` feature is not built in, so a remote URI cannot be fetched.
43
    HttpUnavailable,
44
}
45

            
46
impl core::fmt::Display for FetchError {
47
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
48
        match self {
49
            Self::UnsupportedScheme(s) => write!(f, "unsupported URI scheme: {s}"),
50
            Self::Io(e) => write!(f, "read failed: {e}"),
51
            Self::Http(e) => write!(f, "http failed: {e}"),
52
            Self::HttpUnavailable => {
53
                write!(
54
                    f,
55
                    "a remote URI needs the `http` feature, which is not built in"
56
                )
57
            }
58
        }
59
    }
60
}
61

            
62
/// How a URI resolves, decided before any I/O happens.
63
///
64
/// Separated from the fetch itself so a caller can ask "would this block on a
65
/// network?" without performing it - which is what a media publish on the event
66
/// loop needs to know.
67
#[derive(Debug, Clone, PartialEq, Eq)]
68
pub enum UriRoute {
69
    /// Read this path from disk. Already percent-decoded.
70
    LocalPath(String),
71
    /// GET this URL.
72
    Remote(String),
73
    /// Neither, and naming it is better than guessing.
74
    Unsupported(String),
75
}
76

            
77
impl UriRoute {
78
    /// Would resolving this block on a network round trip?
79
    #[must_use]
80
3
    pub const fn is_remote(&self) -> bool {
81
3
        matches!(self, Self::Remote(_))
82
3
    }
83
}
84

            
85
/// Decide how a URI resolves, without touching the disk or the network.
86
///
87
/// The scheme comes from the real URL parser rather than a hand-rolled scan -
88
/// `azul_core::url::Url` is backed by the `url` crate, and getting scheme
89
/// detection subtly wrong is how `mailto:` or a Windows drive letter ends up in
90
/// the wrong branch.
91
#[must_use]
92
16
pub fn route_of(uri: &str) -> UriRoute {
93
16
    let trimmed = uri.trim();
94
16
    if trimmed.is_empty() {
95
1
        return UriRoute::LocalPath(String::new());
96
15
    }
97

            
98
    // A WINDOWS DRIVE LETTER IS A PATH, and the URL spec disagrees: `C:` is a
99
    // perfectly good one-character scheme, so `C:\cover.png` parses as a URL
100
    // with scheme "c". This is checked before parsing rather than after,
101
    // because the parser's answer is not wrong so much as about a different
102
    // question.
103
15
    let mut chars = trimmed.chars();
104
15
    if let (Some(first), Some(':')) = (chars.next(), chars.next()) {
105
2
        if first.is_ascii_alphabetic() {
106
2
            return UriRoute::LocalPath(String::from(trimmed));
107
        }
108
13
    }
109

            
110
13
    match parse_scheme_and_path(trimmed) {
111
        // A `file:` URL's path is PERCENT-ENCODED: a space is `%20`, and
112
        // handing that to the filesystem asks for a file nobody has.
113
8
        Some((scheme, path)) if scheme == "file" => UriRoute::LocalPath(percent_decode(&path)),
114
5
        Some((scheme, _)) if scheme == "http" || scheme == "https" => {
115
3
            UriRoute::Remote(String::from(trimmed))
116
        }
117
2
        Some((scheme, _)) => UriRoute::Unsupported(scheme),
118
        // Not a URL at all - a bare path, which is what an app that stored a
119
        // filename has.
120
5
        None => UriRoute::LocalPath(String::from(trimmed)),
121
    }
122
16
}
123

            
124
/// `(scheme, path)` when this parses as an absolute URL.
125
#[cfg(feature = "http")]
126
fn parse_scheme_and_path(uri: &str) -> Option<(String, String)> {
127
    let parsed = azul_core::url::Url::parse(uri).ok()?;
128
    Some((
129
        parsed.scheme.as_str().to_ascii_lowercase(),
130
        String::from(parsed.path.as_str()),
131
    ))
132
}
133

            
134
/// Without the `url` dependency the scheme is read directly.
135
///
136
/// Deliberately CONSERVATIVE where it differs from the parser: it accepts only
137
/// what RFC 3986 allows in a scheme, so anything it is unsure about falls
138
/// through to "a path", which is the safe answer - a wrong path fails loudly
139
/// when the file is missing, where a wrong scheme fails silently.
140
#[cfg(not(feature = "http"))]
141
13
fn parse_scheme_and_path(uri: &str) -> Option<(String, String)> {
142
13
    let colon = uri.find(':')?;
143
8
    let scheme = &uri[..colon];
144
8
    if scheme.len() < 2
145
8
        || !scheme.starts_with(|c: char| c.is_ascii_alphabetic())
146
8
        || !scheme
147
8
            .chars()
148
33
            .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
149
    {
150
        return None;
151
8
    }
152
8
    let rest = &uri[colon + 1..];
153
8
    let path = rest.strip_prefix("//").map_or(rest, |after| {
154
        // Skip the authority: `//host/path` -> `/path`.
155
7
        after.find('/').map_or("", |slash| &after[slash..])
156
7
    });
157
8
    Some((scheme.to_ascii_lowercase(), String::from(path)))
158
13
}
159

            
160
/// Decode `%XX` escapes. Invalid escapes are left as written rather than
161
/// dropped, so a filename that legitimately contains a `%` still resolves.
162
7
fn percent_decode(s: &str) -> String {
163
7
    let bytes = s.as_bytes();
164
7
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
165
7
    let mut i = 0;
166
106
    while i < bytes.len() {
167
99
        if bytes[i] == b'%' && i + 2 < bytes.len() {
168
5
            let hex = core::str::from_utf8(&bytes[i + 1..i + 3])
169
5
                .ok()
170
5
                .and_then(|h| u8::from_str_radix(h, 16).ok());
171
5
            if let Some(byte) = hex {
172
3
                out.push(byte);
173
3
                i += 3;
174
3
                continue;
175
2
            }
176
94
        }
177
96
        out.push(bytes[i]);
178
96
        i += 1;
179
    }
180
7
    String::from_utf8_lossy(&out).into_owned()
181
7
}
182

            
183
/// Resolve a URI to bytes. BLOCKS - see the module docs.
184
///
185
/// # Errors
186
///
187
/// [`FetchError`] naming which half failed, so a caller can tell a missing
188
/// file from a refused download.
189
#[cfg(feature = "std")]
190
3
pub fn fetch_uri(uri: &str) -> Result<Vec<u8>, FetchError> {
191
3
    match route_of(uri) {
192
3
        UriRoute::LocalPath(path) => {
193
3
            std::fs::read(&path).map_err(|e| FetchError::Io(alloc::format!("{path}: {e}")))
194
        }
195
        UriRoute::Remote(url) => fetch_remote(&url),
196
        UriRoute::Unsupported(scheme) => Err(FetchError::UnsupportedScheme(scheme)),
197
    }
198
3
}
199

            
200
#[cfg(all(feature = "std", feature = "http"))]
201
fn fetch_remote(url: &str) -> Result<Vec<u8>, FetchError> {
202
    use azul_css::AzString;
203

            
204
    use crate::http::HttpRequestConfig;
205

            
206
    match HttpRequestConfig::default().http_get_blocking(AzString::from(String::from(url))) {
207
        crate::http::ResultHttpResponseHttpError::Ok(response) => {
208
            // A 404 body is an error page, not the image asked for. Treating a
209
            // non-2xx as success is how a broken URL becomes a corrupt file.
210
            if !(200..300).contains(&response.status_code) {
211
                return Err(FetchError::Http(alloc::format!(
212
                    "{url}: status {}",
213
                    response.status_code
214
                )));
215
            }
216
            Ok(response.body.as_ref().to_vec())
217
        }
218
        crate::http::ResultHttpResponseHttpError::Err(e) => {
219
            Err(FetchError::Http(alloc::format!("{url}: {e:?}")))
220
        }
221
    }
222
}
223

            
224
#[cfg(all(feature = "std", not(feature = "http")))]
225
const fn fetch_remote(_url: &str) -> Result<Vec<u8>, FetchError> {
226
    Err(FetchError::HttpUnavailable)
227
}
228

            
229
#[cfg(test)]
230
mod tests {
231
    use super::*;
232

            
233
    #[test]
234
1
    fn a_file_url_is_local_and_percent_decoded() {
235
1
        assert_eq!(
236
1
            route_of("file:///Users/me/My%20Covers/art.png"),
237
1
            UriRoute::LocalPath(String::from("/Users/me/My Covers/art.png")),
238
            "a space is `%20` in a real cover path, and the filesystem wants the space"
239
        );
240
1
        assert_eq!(
241
1
            route_of("file:///plain.png"),
242
1
            UriRoute::LocalPath(String::from("/plain.png"))
243
        );
244
1
    }
245

            
246
    /// An app that stored a FILENAME rather than a URI is the common case, and
247
    /// `Url::parse` rejects those precisely because they are not URLs.
248
    #[test]
249
1
    fn a_bare_path_is_local_and_left_alone() {
250
4
        for path in ["/abs/cover.png", "cover.png", "./art/cover.jpg", ""] {
251
4
            assert_eq!(
252
4
                route_of(path),
253
4
                UriRoute::LocalPath(String::from(path)),
254
                "`{path}` must be treated as a path, unchanged"
255
            );
256
        }
257
1
    }
258

            
259
    /// The URL spec says `C:` is a scheme. The filesystem says it is a drive.
260
    #[test]
261
1
    fn a_windows_drive_letter_is_a_path_not_a_scheme() {
262
1
        assert_eq!(
263
1
            route_of("C:\\Music\\cover.png"),
264
1
            UriRoute::LocalPath(String::from("C:\\Music\\cover.png"))
265
        );
266
1
        assert_eq!(
267
1
            route_of("d:/music/cover.png"),
268
1
            UriRoute::LocalPath(String::from("d:/music/cover.png"))
269
        );
270
1
    }
271

            
272
    #[test]
273
1
    fn http_and_https_are_remote_and_everything_else_is_named() {
274
1
        assert!(route_of("http://example.com/a.png").is_remote());
275
1
        assert!(route_of("https://example.com/a.png").is_remote());
276
1
        assert!(route_of("HTTPS://EXAMPLE.COM/a.png").is_remote());
277

            
278
        // NOT silently treated as a path: a caller that gets `Unsupported`
279
        // can say which scheme it could not follow.
280
1
        assert_eq!(
281
1
            route_of("ftp://example.com/a.png"),
282
1
            UriRoute::Unsupported(String::from("ftp"))
283
        );
284
1
        assert!(matches!(
285
1
            route_of("data:image/png;base64,AAAA"),
286
            UriRoute::Unsupported(_)
287
        ));
288
1
    }
289

            
290
    #[test]
291
1
    fn a_percent_that_is_not_an_escape_survives() {
292
        // `100%` in a folder name is legal and must not be eaten.
293
1
        assert_eq!(percent_decode("100%_done/a.png"), "100%_done/a.png");
294
1
        assert_eq!(percent_decode("a%zzb"), "a%zzb");
295
1
        assert_eq!(percent_decode("a%2"), "a%2");
296
1
        assert_eq!(percent_decode("a%2Fb"), "a/b");
297
1
    }
298

            
299
    #[cfg(feature = "std")]
300
    #[test]
301
1
    fn a_missing_local_file_names_itself_in_the_error() {
302
1
        let err = fetch_uri("/definitely/not/here/cover.png").unwrap_err();
303
1
        match err {
304
1
            FetchError::Io(msg) => assert!(
305
1
                msg.contains("/definitely/not/here/cover.png"),
306
                "the error must name the path, got {msg}"
307
            ),
308
            other => panic!("expected an Io error, got {other:?}"),
309
        }
310
1
    }
311

            
312
    #[cfg(feature = "std")]
313
    #[test]
314
1
    fn a_local_file_round_trips() {
315
1
        let dir = std::env::temp_dir().join("azul_fetch_test");
316
1
        let _ = std::fs::create_dir_all(&dir);
317
1
        let path = dir.join("cover bytes.bin");
318
1
        std::fs::write(&path, b"hello").expect("write");
319

            
320
1
        assert_eq!(fetch_uri(path.to_str().expect("utf8")).unwrap(), b"hello");
321
        // ...and through a percent-encoded file URL, which is the whole point
322
        // of the decode step.
323
1
        let url = alloc::format!("file://{}", path.display().to_string().replace(' ', "%20"));
324
1
        assert_eq!(fetch_uri(&url).unwrap(), b"hello");
325

            
326
1
        let _ = std::fs::remove_file(&path);
327
1
    }
328
}