1use std::borrow::Cow;
13use crate::client_hint::ClientHint;
14use crate::cors::Cors;
15use crate::ext::date_time_ext::DateTimeExt;
16use crate::ext::string_ext::StringExt;
17use crate::range::Range;
18use crate::request::Request;
19use crate::symbol::SYMBOL;
20
21#[cfg(test)]
22mod tests;
23
24pub mod content_disposition;
25
26#[cfg(test)]
27mod example;
28
29#[derive(PartialEq, Eq, Clone, Debug)]
41pub struct Header {
42 pub name: Cow<'static, str>,
44 pub value: Cow<'static, str>,
46}
47
48struct FixedHeaders {
50 before_date: Vec<Header>,
51 after_date: Vec<Header>,
52}
53
54impl Header {
55
56 pub fn new(name: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>) -> Header {
65 Header { name: name.into(), value: value.into() }
66 }
67
68 pub(crate) fn name_from(name: &str) -> Cow<'static, str> {
73 const COMMON: &[&str] = &[
74 "Host", "host", "User-Agent", "user-agent", "Accept", "accept",
75 "Accept-Encoding", "accept-encoding", "Accept-Language", "accept-language",
76 "Connection", "connection", "Content-Type", "content-type",
77 "Content-Length", "content-length", "Date", "date", "Server", "server",
78 "Last-Modified", "last-modified", "ETag", "etag", "Accept-Ranges", "accept-ranges",
79 "Cache-Control", "cache-control", "Cookie", "cookie", "Set-Cookie", "set-cookie",
80 "Referer", "referer", "Origin", "origin", "Authorization", "authorization",
81 "If-None-Match", "if-none-match", "If-Modified-Since", "if-modified-since",
82 "Transfer-Encoding", "transfer-encoding", "Keep-Alive", "keep-alive",
83 "Vary", "vary", "Upgrade-Insecure-Requests", "upgrade-insecure-requests",
84 "X-Forwarded-For", "x-forwarded-for", "Via", "via",
85 ];
86 match COMMON.iter().find(|common| **common == name) {
87 Some(common) => Cow::Borrowed(common),
88 None => Cow::Owned(name.to_string()),
89 }
90 }
91
92 pub fn as_string(&self) -> String {
93 let formatted = format!("{}: {}", self.name, self.value);
94 formatted
95 }
96
97 pub const _ACCESS_CONTROL_REQUEST_METHOD: &'static str = "Access-Control-Request-Method";
98 pub const _ACCESS_CONTROL_REQUEST_HEADERS: &'static str = "Access-Control-Request-Headers";
99 pub const _ACCESS_CONTROL_ALLOW_ORIGIN: &'static str = "Access-Control-Allow-Origin";
100 pub const _ACCESS_CONTROL_ALLOW_METHODS: &'static str = "Access-Control-Allow-Methods";
101 pub const _ACCESS_CONTROL_ALLOW_HEADERS: &'static str = "Access-Control-Allow-Headers";
102 pub const _ACCESS_CONTROL_ALLOW_CREDENTIALS: &'static str = "Access-Control-Allow-Credentials";
103 pub const _ACCESS_CONTROL_MAX_AGE: &'static str = "Access-Control-Max-Age";
104 pub const _ACCESS_CONTROL_EXPOSE_HEADERS: &'static str = "Access-Control-Expose-Headers";
105
106 pub const _ACCEPT: &'static str = "Accept";
107 pub const _ACCEPT_RANGES: &'static str = "Accept-Ranges";
108 pub const _ACCEPT_CH: &'static str = "Accept-CH";
109 pub const _ACCEPT_ENCODING: &'static str = "Accept-Encoding";
110 pub const _ACCEPT_LANGUAGE: &'static str = "Accept-Language";
111 pub const _ACCEPT_PATCH: &'static str = "Accept-Patch";
112 pub const _ACCEPT_POST: &'static str = "Accept-Post";
113 pub const _AGE: &'static str = "Age";
114 pub const _ALLOW: &'static str = "Allow";
115 pub const _ALT_SVC: &'static str = "Alt-Svc";
116 pub const _AUTHORIZATION: &'static str = "Authorization";
117 pub const _CACHE_CONTROL: &'static str = "Cache-Control";
118 pub const _CONNECTION: &'static str = "Connection";
119 pub const _CLEAR_SITE_DATA: &'static str = "Clear-Site-Data";
120 pub const _CONTENT_TYPE: &'static str = "Content-Type";
121 pub const _CONTENT_LENGTH: &'static str = "Content-Length";
122 pub const _CONTENT_RANGE: &'static str = "Content-Range";
123 pub const _CONTENT_DISPOSITION: &'static str = "Content-Disposition";
124 pub const _CONTENT_ENCODING: &'static str = "Content-Encoding";
125 pub const _CONTENT_LANGUAGE: &'static str = "Content-Language";
126 pub const _CONTENT_LOCATION: &'static str = "Content-Location";
127 pub const _CONTENT_SECURITY_POLICY: &'static str = "Content-Security-Policy";
128 pub const _CONTENT_SECURITY_POLICY_REPORT_ONLY: &'static str = "Content-Security-Policy-Report-Only";
129 pub const _COOKIE: &'static str = "Cookie";
130 pub const _CROSS_ORIGIN_EMBEDDER_POLICY: &'static str = "Cross-Origin-Embedder-Policy";
131 pub const _CROSS_ORIGIN_OPENER_POLICY: &'static str = "Cross-Origin-Opener-Policy";
132 pub const _CROSS_ORIGIN_RESOURCE_POLICY: &'static str = "Cross-Origin-Resource-Policy";
133 pub const _DATE: &'static str = "Date";
134 pub const _DATE_UNIX_EPOCH_NANOS: &'static str = "Date-Unix-Epoch-Nanos";
135 pub const _DEVICE_MEMORY: &'static str = "Device-Memory";
136 pub const _DIGEST: &'static str = "Digest";
137 pub const _DOWNLINK: &'static str = "Downlink";
138 pub const _EARLY_DATA: &'static str = "Early-Data";
139 pub const _ECT: &'static str = "ECT";
140 pub const _ETAG: &'static str = "ETag";
141 pub const _EXPECT: &'static str = "Expect";
142 pub const _EXPIRES: &'static str = "Expires";
143 pub const _FEATURE_POLICY: &'static str = "Feature-Policy";
144 pub const _PERMISSIONS_POLICY: &'static str = "Permissions-Policy";
145 pub const _FORWARDED: &'static str = "Forwarded";
146 pub const _FROM: &'static str = "From";
147 pub const _HOST: &'static str = "Host";
148 pub const _IF_MATCH: &'static str = "If-Match";
149 pub const _IF_MODIFIED_SINCE: &'static str = "If-Modified-Since";
150 pub const _IF_NONE_MATCH: &'static str = "If-None-Match";
151 pub const _IF_RANGE: &'static str = "If-Range";
152 pub const _IF_UNMODIFIED_SINCE: &'static str = "If-Unmodified-Since";
153 pub const _LAST_MODIFIED: &'static str = "Last-Modified";
154 pub const _LAST_MODIFIED_UNIX_EPOCH_NANOS: &'static str = "Last-Modified-Unix-Epoch-Nanos";
155 pub const _LINK: &'static str = "Link";
156 pub const _LOCATION: &'static str = "Location";
157 pub const _MAX_FORWARDS: &'static str = "Max-Forwards";
158 pub const _NEL: &'static str = "NEL";
159 pub const _ORIGIN: &'static str = "Origin";
160 pub const _PROXY_AUTHENTICATE: &'static str = "Proxy-Authenticate";
161 pub const _PROXY_AUTHORIZATION: &'static str = "Proxy-Authorization";
162 pub const _RANGE: &'static str = "Range";
163 pub const _REFERER: &'static str = "Referer";
164 pub const _REFERRER_POLICY: &'static str = "Referrer-Policy";
165 pub const _RETRY_AFTER: &'static str = "Retry-After";
166 pub const _RTT: &'static str = "RTT";
167 pub const _SAVE_DATA: &'static str = "Save-Data";
168 pub const _SEC_CH_UA: &'static str = "Sec-CH-UA";
169 pub const _SEC_CH_UA_ARCH: &'static str = "Sec-CH-UA-Arch";
170 pub const _SEC_CH_UA_BITNESS: &'static str = "Sec-CH-UA-Bitness";
171 pub const _SEC_CH_UA_FULL_VERSION_LIST: &'static str = "Sec-CH-UA-Full-Version-List";
172 pub const _SEC_CH_UA_MOBILE: &'static str = "Sec-CH-UA-Mobile";
173 pub const _SEC_CH_UA_MODEL: &'static str = "Sec-CH-UA-Model";
174 pub const _SEC_CH_UA_PLATFORM: &'static str = "Sec-CH-UA-Platform";
175 pub const _SEC_CH_UA_PLATFORM_VERSION: &'static str = "Sec-CH-UA-Platform-Version";
176 pub const _SEC_FETCH_DEST: &'static str = "Sec-Fetch-Dest";
177 pub const _SEC_FETCH_MODE: &'static str = "Sec-Fetch-Mode";
178 pub const _SEC_FETCH_SITE: &'static str = "Sec-Fetch-Site";
179 pub const _SEC_FETCH_USER: &'static str = "Sec-Fetch-User";
180 pub const _SEC_GPC: &'static str = "Sec-GPC";
181 pub const _SERVER: &'static str = "Server";
182 pub const _SERVER_TIMING: &'static str = "Server-Timing";
183 pub const _SERVICE_WORKER_NAVIGATION_PRELOAD: &'static str = "Service-Worker-Navigation-Preload";
184 pub const _SET_COOKIE: &'static str = "Set-Cookie";
185 pub const _SOURCE_MAP: &'static str = "SourceMap";
186 pub const _STRICT_TRANSPORT_SECURITY: &'static str = "Strict-Transport-Security";
187 pub const _TE: &'static str = "TE";
188 pub const _TIMING_ALLOW_ORIGIN: &'static str = "Timing-Allow-Origin";
189 pub const _TRAILER: &'static str = "Trailer";
190 pub const _TRANSFER_ENCODING: &'static str = "Transfer-Encoding";
191 pub const _UPGRADE: &'static str = "Upgrade";
192 pub const _UPGRADE_INSECURE_REQUESTS: &'static str = "Upgrade-Insecure-Requests";
193 pub const _USER_AGENT: &'static str = "User-Agent";
194 pub const _VARY: &'static str = "Vary";
195 pub const _VIA: &'static str = "Via";
196 pub const _WANT_DIGEST: &'static str = "Want-Digest";
197 pub const _WWW_AUTHENTICATE: &'static str = "WWW-Authenticate";
198 pub const _X_CONTENT_TYPE_OPTIONS: &'static str = "X-Content-Type-Options";
199 pub const _X_CONTENT_TYPE_OPTIONS_VALUE_NOSNIFF: &'static str = "nosniff";
200 pub const _X_FRAME_OPTIONS: &'static str = "X-Frame-Options";
201 pub const _X_FRAME_OPTIONS_VALUE_DENY: &'static str = "DENY";
202 pub const _X_FRAME_OPTIONS_VALUE_SAME_ORIGIN: &'static str = "SAMEORIGIN";
203
204 pub const _STRICT_TRANSPORT_SECURITY_VALUE_DEFAULT: &'static str = "max-age=31536000; includeSubDomains";
205 pub const _REFERRER_POLICY_VALUE_DEFAULT: &'static str = "strict-origin-when-cross-origin";
206 pub const _PERMISSIONS_POLICY_VALUE_DEFAULT: &'static str = "geolocation=(), microphone=(), camera=()";
207 pub const _CONTENT_SECURITY_POLICY_VALUE_DEFAULT: &'static str = "default-src 'self'";
208
209
210
211
212 pub const NAME_VALUE_SEPARATOR: &'static str = ": ";
213
214 pub fn single_line(s: &str) -> std::borrow::Cow<'_, str> {
220 if s.contains(['\r', '\n']) {
221 std::borrow::Cow::Owned(s.replace(['\r', '\n'], " "))
222 } else {
223 std::borrow::Cow::Borrowed(s)
224 }
225 }
226
227 pub const _DO_NOT_STORE_CACHE: &'static str = "no-store, no-cache, private, max-age=0, must-revalidate, proxy-revalidate";
228
229
230
231 pub fn get_header_list_with_config(
239 request: &Request,
240 config: &crate::server_config::ServerConfig,
241 ) -> Vec<Header> {
242 let fixed = Header::fixed_headers(&config.csp, config.client_hints, config.security_headers);
247 let mut header_list = Cors::get_headers_from_config(request, config);
248 header_list.reserve(fixed.before_date.len() + 2 + fixed.after_date.len());
249 header_list.extend(fixed.before_date.iter().cloned());
250 header_list.push(Header { name: Header::_DATE.into(), value: crate::http::date::now().into() });
251 if config.nanos_headers {
252 header_list.push(Header::get_date_iso_8601_header());
253 }
254 header_list.extend(fixed.after_date.iter().cloned());
255 header_list
256 }
257
258 fn fixed_headers(csp: &str, client_hints: bool, security_headers: bool) -> std::sync::Arc<FixedHeaders> {
262 use std::sync::{Arc, RwLock};
263 static CACHE: RwLock<Option<(String, bool, bool, Arc<FixedHeaders>)>> = RwLock::new(None);
264 if let Some((cached_csp, cached_hints, cached_security, fixed)) = CACHE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
265 if cached_csp == csp && *cached_hints == client_hints && *cached_security == security_headers {
266 return Arc::clone(fixed);
267 }
268 }
269 let mut before_date = Vec::with_capacity(6);
272 let vary = if client_hints {
273 before_date.push(ClientHint::get_accept_client_hints_header());
274 before_date.push(ClientHint::get_critical_client_hints_header());
275 [Cors::get_vary_header_value(), ClientHint::get_vary_header_value()].join(", ")
276 } else {
277 Cors::get_vary_header_value()
278 };
279 before_date.push(Header { name: Header::_VARY.into(), value: vary.into() });
280 before_date.push(Header::get_x_content_type_options_header());
281 before_date.push(Header::get_accept_ranges_header());
282 if security_headers {
284 before_date.push(Header::get_x_frame_options_header());
285 }
286 let mut after_date = vec![Header::get_no_cache_header()];
287 if security_headers {
288 after_date.push(Header { name: Header::_REFERRER_POLICY.into(), value: Header::_REFERRER_POLICY_VALUE_DEFAULT.into() });
289 after_date.push(Header { name: Header::_PERMISSIONS_POLICY.into(), value: Header::_PERMISSIONS_POLICY_VALUE_DEFAULT.into() });
290 }
291 if !csp.is_empty() {
292 after_date.push(Header { name: Header::_CONTENT_SECURITY_POLICY.into(), value: csp.to_string().into() });
293 }
294 let before_date = before_date.into_iter().map(Header::interned).collect();
297 let after_date = after_date.into_iter().map(Header::interned).collect();
298 let fixed = Arc::new(FixedHeaders { before_date, after_date });
299 *CACHE.write().unwrap_or_else(|e| e.into_inner()) = Some((csp.to_string(), client_hints, security_headers, Arc::clone(&fixed)));
300 fixed
301 }
302
303 fn interned(self) -> Header {
308 fn intern(s: Cow<'static, str>) -> Cow<'static, str> {
309 use std::collections::HashSet;
310 use std::sync::{Mutex, OnceLock};
311 let owned = match s {
312 Cow::Borrowed(_) => return s,
313 Cow::Owned(owned) => owned,
314 };
315 static INTERNED: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
316 let mut set = INTERNED.get_or_init(|| Mutex::new(HashSet::new())).lock().unwrap_or_else(|e| e.into_inner());
317 if let Some(existing) = set.get(owned.as_str()) {
318 return Cow::Borrowed(existing);
319 }
320 let leaked: &'static str = Box::leak(owned.into_boxed_str());
321 set.insert(leaked);
322 Cow::Borrowed(leaked)
323 }
324 Header { name: intern(self.name), value: intern(self.value) }
325 }
326
327 pub fn get_header_list(request: &Request) -> Vec<Header> {
335 Self::get_header_list_with_config(request, &crate::server_config::ServerConfig::current())
336 }
337
338
339 pub fn get_x_content_type_options_header() -> Header {
340 Header {
341 name: Header::_X_CONTENT_TYPE_OPTIONS.into(),
342 value: Header::_X_CONTENT_TYPE_OPTIONS_VALUE_NOSNIFF.into(),
343 }
344 }
345
346 pub fn get_accept_ranges_header() -> Header {
347 Header {
348 name: Header::_ACCEPT_RANGES.into(),
349 value: Range::BYTES.into(),
350 }
351 }
352
353 pub fn get_x_frame_options_header() -> Header {
354 Header {
355 name: Header::_X_FRAME_OPTIONS.into(),
356 value: Header::_X_FRAME_OPTIONS_VALUE_SAME_ORIGIN.into(),
357 }
358 }
359
360 pub fn get_date_iso_8601_header() -> Header {
361 Header {
362 name: Header::_DATE_UNIX_EPOCH_NANOS.into(),
363 value: crate::ext::decimal::Decimal::new(DateTimeExt::_now_unix_epoch_nanos()).as_str().to_string().into(),
364 }
365 }
366
367 pub fn get_no_cache_header() -> Header {
368 Header {
369 name: Header::_CACHE_CONTROL.into(),
370 value: Header::_DO_NOT_STORE_CACHE.into(),
371 }
372 }
373
374 pub fn get_hsts_header() -> Header {
375 Header {
376 name: Header::_STRICT_TRANSPORT_SECURITY.into(),
377 value: Header::_STRICT_TRANSPORT_SECURITY_VALUE_DEFAULT.into(),
378 }
379 }
380
381 pub fn parse_header(raw_header: &str) -> Result<Header, String> {
382 let escaped_header = StringExt::filter_ascii_control_characters(raw_header);
383 let escaped_header = StringExt::truncate_new_line_carriage_return(&escaped_header);
384
385 let boxed_split = escaped_header.split_once(SYMBOL.colon);
386 if boxed_split.is_none() {
387 let message = format!("Unable to parse header: {}", escaped_header);
388 return Err(message)
389 }
390
391 let (name, value) = boxed_split.unwrap();
392
393 let header = Header {
394 name: name.trim().to_string().into(),
395 value: value.trim().to_string().into(),
396 };
397
398 Ok(header)
399 }
400
401 pub fn parse(raw_header: &str) -> Result<Header, String> {
402 Header::parse_header(raw_header)
403 }
404
405 pub fn generate(&self) -> String {
406 self.as_string()
407 }
408
409}
410