1#![allow(dead_code)]
4
5extern crate alloc;
6use alloc::string::{String, ToString};
7use alloc::vec::Vec;
8
9#[derive(Debug, Clone, PartialEq, Eq, Default)]
11pub struct CacheControl {
12 pub max_age: Option<u64>,
14 pub s_maxage: Option<u64>,
16 pub no_cache: bool,
18 pub no_store: bool,
20 pub must_revalidate: bool,
22 pub public: bool,
24 pub private: bool,
26 pub immutable: bool,
28}
29
30impl CacheControl {
31 pub fn parse(header_value: &str) -> Self {
34 let mut cc = Self::default();
35
36 for directive in header_value.split(',') {
37 let part = directive.trim();
38 if part.is_empty() {
39 continue;
40 }
41
42 let mut kv = part.splitn(2, '=');
43 let key = kv.next().unwrap_or("").trim();
44 let val = kv.next().map(|v| v.trim().trim_matches('"'));
45
46 if key.eq_ignore_ascii_case("no-cache") {
47 cc.no_cache = true;
48 } else if key.eq_ignore_ascii_case("no-store") {
49 cc.no_store = true;
50 } else if key.eq_ignore_ascii_case("must-revalidate") {
51 cc.must_revalidate = true;
52 } else if key.eq_ignore_ascii_case("public") {
53 cc.public = true;
54 } else if key.eq_ignore_ascii_case("private") {
55 cc.private = true;
56 } else if key.eq_ignore_ascii_case("immutable") {
57 cc.immutable = true;
58 } else if key.eq_ignore_ascii_case("max-age") {
59 if let Some(v_str) = val {
60 if let Ok(secs) = v_str.parse::<u64>() {
61 cc.max_age = Some(secs);
62 }
63 }
64 } else if key.eq_ignore_ascii_case("s-maxage") {
65 if let Some(v_str) = val {
66 if let Ok(secs) = v_str.parse::<u64>() {
67 cc.s_maxage = Some(secs);
68 }
69 }
70 }
71 }
72
73 cc
74 }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct HttpCacheEntry {
80 pub status_code: u16,
82 pub etag: Option<String>,
84 pub last_modified: Option<String>,
86 pub cache_control: CacheControl,
88 pub created_timestamp_sec: u64,
90 pub vary_fields: Vec<(String, Option<String>)>,
92 pub vary_star: bool,
94}
95
96impl HttpCacheEntry {
97 pub fn from_headers_and_req<K: AsRef<str>, V: AsRef<str>, RK: AsRef<str>, RV: AsRef<str>>(
99 status_code: u16,
100 resp_headers: &[(K, V)],
101 req_headers: &[(RK, RV)],
102 now_sec: u64,
103 ) -> Self {
104 let mut etag = None;
105 let mut last_modified = None;
106 let mut cc_str = None;
107 let mut vary_str = None;
108
109 for (k, v) in resp_headers {
110 let key = k.as_ref();
111 let val = v.as_ref();
112 if key.eq_ignore_ascii_case("cache-control") {
113 cc_str = Some(val.to_string());
114 } else if key.eq_ignore_ascii_case("etag") {
115 etag = Some(val.to_string());
116 } else if key.eq_ignore_ascii_case("last-modified") {
117 last_modified = Some(val.to_string());
118 } else if key.eq_ignore_ascii_case("vary") {
119 vary_str = Some(val.to_string());
120 }
121 }
122
123 let cache_control = cc_str
124 .as_deref()
125 .map(CacheControl::parse)
126 .unwrap_or_default();
127
128 let mut vary_fields = Vec::new();
129 let mut vary_star = false;
130
131 if let Some(v_hdr) = vary_str {
132 for part in v_hdr.split(',') {
133 let trimmed = part.trim();
134 if trimmed == "*" {
135 vary_star = true;
136 } else if !trimmed.is_empty() {
137 let req_val = req_headers
138 .iter()
139 .find(|(rk, _)| rk.as_ref().eq_ignore_ascii_case(trimmed))
140 .map(|(_, rv)| rv.as_ref().to_string());
141 vary_fields.push((trimmed.to_string(), req_val));
142 }
143 }
144 }
145
146 Self {
147 status_code,
148 etag,
149 last_modified,
150 cache_control,
151 created_timestamp_sec: now_sec,
152 vary_fields,
153 vary_star,
154 }
155 }
156
157 pub fn from_headers<K: AsRef<str>, V: AsRef<str>>(
159 status_code: u16,
160 headers: &[(K, V)],
161 now_sec: u64,
162 ) -> Self {
163 Self::from_headers_and_req::<K, V, &str, &str>(status_code, headers, &[], now_sec)
164 }
165
166 pub fn matches_request_headers<K: AsRef<str>, V: AsRef<str>>(&self, req_headers: &[(K, V)]) -> bool {
168 if self.vary_star {
169 return false;
170 }
171 for (vary_name, saved_val) in &self.vary_fields {
172 let cur_val = req_headers
173 .iter()
174 .find(|(k, _)| k.as_ref().eq_ignore_ascii_case(vary_name))
175 .map(|(_, v)| v.as_ref());
176 if cur_val != saved_val.as_deref() {
177 return false;
178 }
179 }
180 true
181 }
182
183 pub fn is_fresh(&self, now_sec: u64) -> bool {
185 if self.status_code != 200 && self.status_code != 203 && self.status_code != 204 && self.status_code != 206 {
187 return false;
188 }
189
190 if self.cache_control.no_store {
192 return false;
193 }
194
195 if self.cache_control.no_cache {
197 return false;
198 }
199
200 if let Some(max_age) = self.cache_control.max_age {
202 let age = now_sec.saturating_sub(self.created_timestamp_sec);
203 age < max_age
204 } else {
205 false
207 }
208 }
209
210 pub fn should_revalidate(&self, now_sec: u64) -> bool {
212 if self.cache_control.no_store {
213 return false;
214 }
215
216 let needs_check = !self.is_fresh(now_sec) || self.cache_control.no_cache;
219 needs_check && (self.etag.is_some() || self.last_modified.is_some())
220 }
221
222 pub fn build_conditional_headers(&self) -> Vec<(String, String)> {
224 let mut headers = Vec::new();
225
226 if let Some(ref etag) = self.etag {
227 headers.push((String::from("If-None-Match"), etag.clone()));
228 }
229
230 if let Some(ref lm) = self.last_modified {
231 headers.push((String::from("If-Modified-Since"), lm.clone()));
232 }
233
234 headers
235 }
236
237 pub fn update_304<K: AsRef<str>, V: AsRef<str>>(
239 &mut self,
240 new_headers: &[(K, V)],
241 now_sec: u64,
242 ) {
243 for (k, v) in new_headers {
244 let key = k.as_ref();
245 let val = v.as_ref();
246 if key.eq_ignore_ascii_case("cache-control") {
247 self.cache_control = CacheControl::parse(val);
248 } else if key.eq_ignore_ascii_case("etag") {
249 self.etag = Some(val.to_string());
250 } else if key.eq_ignore_ascii_case("last-modified") {
251 self.last_modified = Some(val.to_string());
252 }
253 }
254 self.created_timestamp_sec = now_sec;
255 }
256}
257
258#[inline]
260pub fn is_304_not_modified(status: u16) -> bool {
261 status == 304
262}
263
264#[derive(Debug, Clone, PartialEq, Eq)]
266pub enum CacheLookup {
267 Hit {
269 body: Vec<u8>,
270 status_code: u16,
271 },
272 Revalidate {
274 conditional_headers: Vec<(String, String)>,
275 },
276 Miss,
278}
279
280pub struct HttpCacheStore {
282 entries: alloc::collections::BTreeMap<String, (HttpCacheEntry, Vec<u8>)>,
283 pub max_entries: usize,
284 pub max_total_bytes: usize,
285 current_total_bytes: usize,
286}
287
288impl Default for HttpCacheStore {
289 fn default() -> Self {
290 Self::new()
291 }
292}
293
294impl HttpCacheStore {
295 pub const DEFAULT_MAX_ENTRIES: usize = 128;
296 pub const DEFAULT_MAX_TOTAL_BYTES: usize = 4 * 1024 * 1024; pub const fn new() -> Self {
299 Self {
300 entries: alloc::collections::BTreeMap::new(),
301 max_entries: Self::DEFAULT_MAX_ENTRIES,
302 max_total_bytes: Self::DEFAULT_MAX_TOTAL_BYTES,
303 current_total_bytes: 0,
304 }
305 }
306
307 pub fn lookup_with_headers<K: AsRef<str>, V: AsRef<str>>(
309 &self,
310 url: &str,
311 req_headers: &[(K, V)],
312 now_sec: u64,
313 ) -> CacheLookup {
314 if let Some((entry, body)) = self.entries.get(url) {
315 if !entry.matches_request_headers(req_headers) {
317 return CacheLookup::Miss;
318 }
319
320 if entry.is_fresh(now_sec) {
321 return CacheLookup::Hit {
322 body: body.clone(),
323 status_code: entry.status_code,
324 };
325 } else if entry.should_revalidate(now_sec) {
326 return CacheLookup::Revalidate {
327 conditional_headers: entry.build_conditional_headers(),
328 };
329 }
330 }
331 CacheLookup::Miss
332 }
333
334 pub fn lookup(&self, url: &str, now_sec: u64) -> CacheLookup {
336 self.lookup_with_headers::<&str, &str>(url, &[], now_sec)
337 }
338
339 pub fn put_with_request_headers<K: AsRef<str>, V: AsRef<str>, RK: AsRef<str>, RV: AsRef<str>>(
341 &mut self,
342 url: &str,
343 status_code: u16,
344 resp_headers: &[(K, V)],
345 req_headers: &[(RK, RV)],
346 body: &[u8],
347 now_sec: u64,
348 ) -> bool {
349 let entry = HttpCacheEntry::from_headers_and_req(status_code, resp_headers, req_headers, now_sec);
350 if entry.cache_control.no_store || entry.vary_star {
351 self.remove(url);
352 return false;
353 }
354
355 if body.len() > self.max_total_bytes / 2 {
356 return false;
357 }
358
359 if let Some((_, old_body)) = self.entries.remove(url) {
360 self.current_total_bytes = self.current_total_bytes.saturating_sub(old_body.len());
361 }
362
363 while (self.entries.len() >= self.max_entries
364 || self.current_total_bytes + body.len() > self.max_total_bytes)
365 && !self.entries.is_empty()
366 {
367 if let Some(first_key) = self.entries.keys().next().cloned() {
368 if let Some((_, removed_body)) = self.entries.remove(&first_key) {
369 self.current_total_bytes =
370 self.current_total_bytes.saturating_sub(removed_body.len());
371 }
372 } else {
373 break;
374 }
375 }
376
377 self.current_total_bytes += body.len();
378 self.entries.insert(String::from(url), (entry, body.to_vec()));
379 true
380 }
381
382 pub fn put<K: AsRef<str>, V: AsRef<str>>(
384 &mut self,
385 url: &str,
386 status_code: u16,
387 headers: &[(K, V)],
388 body: &[u8],
389 now_sec: u64,
390 ) -> bool {
391 self.put_with_request_headers::<K, V, &str, &str>(url, status_code, headers, &[], body, now_sec)
392 }
393
394 pub fn handle_304<K: AsRef<str>, V: AsRef<str>>(
396 &mut self,
397 url: &str,
398 headers: &[(K, V)],
399 now_sec: u64,
400 ) -> Option<Vec<u8>> {
401 if let Some((entry, body)) = self.entries.get_mut(url) {
402 entry.update_304(headers, now_sec);
403 Some(body.clone())
404 } else {
405 None
406 }
407 }
408
409 pub fn remove(&mut self, url: &str) -> bool {
411 if let Some((_, body)) = self.entries.remove(url) {
412 self.current_total_bytes = self.current_total_bytes.saturating_sub(body.len());
413 true
414 } else {
415 false
416 }
417 }
418
419 pub fn len(&self) -> usize {
421 self.entries.len()
422 }
423
424 pub fn is_empty(&self) -> bool {
426 self.entries.is_empty()
427 }
428
429 pub fn total_bytes(&self) -> usize {
431 self.current_total_bytes
432 }
433
434 pub fn clear(&mut self) {
436 self.entries.clear();
437 self.current_total_bytes = 0;
438 }
439}
440
441pub static GLOBAL_HTTP_CACHE: spin::Mutex<HttpCacheStore> = spin::Mutex::new(HttpCacheStore::new());
443
444#[derive(Debug, Clone, Copy, PartialEq, Eq)]
454pub enum DiskCacheRule {
455 Stale,
457 MaxAge(u64),
459 Immutable,
461}
462
463pub fn disk_cache_rule_from_head(head: &[u8]) -> Option<DiskCacheRule> {
466 let end = head.windows(4).position(|w| w == b"\r\n\r\n").unwrap_or(head.len());
467 let text = core::str::from_utf8(&head[..end]).ok()?;
468 let mut lines = text.split("\r\n");
469 let status_line = lines.next()?;
470 let status: u16 = status_line.split_whitespace().nth(1)?.parse().ok()?;
471 if status != 200 && status != 203 && status != 206 {
472 return None;
473 }
474 let mut cc_all = String::new();
475 let mut vary_star = false;
476 for line in lines {
477 let Some((k, v)) = line.split_once(':') else { continue };
478 if k.trim().eq_ignore_ascii_case("cache-control") {
479 if !cc_all.is_empty() {
480 cc_all.push(',');
481 }
482 cc_all.push_str(v.trim());
483 } else if k.trim().eq_ignore_ascii_case("vary") && v.split(',').any(|p| p.trim() == "*") {
484 vary_star = true;
485 }
486 }
487 if vary_star {
488 return Some(DiskCacheRule::Stale);
489 }
490 if cc_all.is_empty() {
491 return None;
492 }
493 let cc = CacheControl::parse(&cc_all);
494 if cc.no_store || cc.no_cache {
495 return Some(DiskCacheRule::Stale);
496 }
497 if cc.immutable {
498 return Some(DiskCacheRule::Immutable);
499 }
500 match cc.max_age {
501 Some(0) => Some(DiskCacheRule::Stale),
502 Some(n) => Some(DiskCacheRule::MaxAge(n)),
503 None => None,
504 }
505}
506
507pub fn disk_cache_is_stale(rule: DiskCacheRule, age_sec: u64, grace_sec: u64) -> bool {
511 match rule {
512 DiskCacheRule::Immutable => false,
513 DiskCacheRule::Stale => age_sec >= grace_sec,
514 DiskCacheRule::MaxAge(n) => age_sec >= n.max(grace_sec),
515 }
516}
517
518const DISK_RULE_BOOK_MAX: usize = 1024;
519
520pub struct DiskRuleBook {
523 pending: alloc::collections::BTreeMap<String, DiskCacheRule>,
524 stored: alloc::collections::BTreeMap<String, (u64, DiskCacheRule)>,
525}
526
527impl Default for DiskRuleBook {
528 fn default() -> Self {
529 Self::new()
530 }
531}
532
533impl DiskRuleBook {
534 pub const fn new() -> Self {
535 Self { pending: alloc::collections::BTreeMap::new(), stored: alloc::collections::BTreeMap::new() }
536 }
537
538 fn trim<V>(m: &mut alloc::collections::BTreeMap<String, V>) {
539 while m.len() >= DISK_RULE_BOOK_MAX {
540 let Some(first) = m.keys().next().cloned() else { break };
541 m.remove(&first);
542 }
543 }
544
545 pub fn note_response(&mut self, key: &str, rule: Option<DiskCacheRule>) {
547 match rule {
548 Some(r) => {
549 Self::trim(&mut self.pending);
550 self.pending.insert(String::from(key), r);
551 }
552 None => {
553 self.pending.remove(key);
554 }
555 }
556 }
557
558 pub fn commit_stored(&mut self, key: &str, now_sec: u64) {
560 match self.pending.remove(key) {
561 Some(r) => {
562 Self::trim(&mut self.stored);
563 self.stored.insert(String::from(key), (now_sec, r));
564 }
565 None => {
566 self.stored.remove(key);
567 }
568 }
569 }
570
571 pub fn is_stale(&self, key: &str, now_sec: u64, grace_sec: u64) -> bool {
573 match self.stored.get(key) {
574 Some((at, rule)) => disk_cache_is_stale(*rule, now_sec.saturating_sub(*at), grace_sec),
575 None => false,
576 }
577 }
578}
579
580pub static DISK_RULES: spin::Mutex<DiskRuleBook> = spin::Mutex::new(DiskRuleBook::new());