1use compmd_pack::{FilePath, Place};
7use http::header::{self, HeaderValue};
8use http::{Method, Request, Response, StatusCode};
9
10use crate::bundle::Bundle;
11use crate::content_type::content_type;
12use crate::store::Store;
13
14const HEADERS: [(&str, &str); 5] = [
16 ("content-security-policy", "sandbox allow-scripts"),
18 (ALLOW_ORIGIN, "*"),
20 ("access-control-expose-headers", "*"),
22 ("x-content-type-options", "nosniff"),
23 ("cache-control", "max-age=31536000, immutable"),
25];
26
27const ALLOW_ORIGIN: &str = "access-control-allow-origin";
29
30const NOT_SERVED: &str = "not a file of the frames or packs this host serves";
32
33const ONLY_GET: &str = "the frames and packs are only read, with GET";
35
36pub fn respond<B>(bundle: &Bundle, store: &dyn Store, request: &Request<B>) -> Response<Vec<u8>> {
42 if request.method() != Method::GET {
43 return refused(StatusCode::METHOD_NOT_ALLOWED, ONLY_GET);
44 }
45 let path = request.uri().path();
46 file(bundle, store, path).map_or_else(
47 || refused(StatusCode::NOT_FOUND, NOT_SERVED),
48 |(body, path)| served(&path, body),
49 )
50}
51
52fn file(bundle: &Bundle, store: &dyn Store, path: &str) -> Option<(Vec<u8>, FilePath)> {
54 let parts: Vec<&str> = path.strip_prefix('/')?.split('/').collect();
55 match parts.as_slice() {
56 ["frames", hash, file @ ..] if *hash == bundle.manifest().frames.hash.as_str() => {
57 let path = FilePath::new(file.join("/")).ok()?;
58 Some((bundle.frame_file(&path)?, path))
59 }
60 ["packs", place @ ..] => {
61 let place = Place::from_parts(place)?;
62 let body = bundle.pack_file(&place).or_else(|| store.file(&place))?;
63 Some((body, place.path))
64 }
65 _ => None,
66 }
67}
68
69fn served(path: &FilePath, body: Vec<u8>) -> Response<Vec<u8>> {
71 let mut response = with_type(StatusCode::OK, content_type(path.as_str()), body);
72 let headers = response.headers_mut();
73 for (name, value) in HEADERS {
74 headers.insert(name, HeaderValue::from_static(value));
75 }
76 response
77}
78
79fn refused(status: StatusCode, why: &str) -> Response<Vec<u8>> {
81 let mut response = with_type(status, "text/plain; charset=utf-8", why.as_bytes().to_vec());
82 response
83 .headers_mut()
84 .insert(ALLOW_ORIGIN, HeaderValue::from_static("*"));
85 response
86}
87
88fn with_type(status: StatusCode, kind: &'static str, body: Vec<u8>) -> Response<Vec<u8>> {
90 let mut response = Response::new(body);
91 *response.status_mut() = status;
92 response
93 .headers_mut()
94 .insert(header::CONTENT_TYPE, HeaderValue::from_static(kind));
95 response
96}
97
98#[cfg(test)]
99mod tests;