1use std::cmp::Ordering;
9use std::collections::HashMap;
10use std::collections::hash_map::Entry;
11use std::time::SystemTime;
12
13use cookie::Cookie;
14use itertools::Itertools;
15use log::info;
16use net_traits::CookieSource;
17use net_traits::pub_domains::reg_suffix;
18use serde::{Deserialize, Serialize};
19use servo_url::ServoUrl;
20
21use crate::cookie::ServoCookie;
22
23#[derive(Clone, Debug, Deserialize, Serialize)]
24pub struct CookieStorage {
25 version: u32,
26 cookies_map: HashMap<String, Vec<ServoCookie>>,
27 max_per_host: usize,
28}
29
30#[derive(Debug)]
31pub enum RemoveCookieError {
32 Overlapping,
33 NonHTTP,
34}
35
36impl CookieStorage {
37 pub fn new(max_cookies: usize) -> CookieStorage {
38 CookieStorage {
39 version: 1,
40 cookies_map: HashMap::new(),
41 max_per_host: max_cookies,
42 }
43 }
44
45 pub fn remove(
47 &mut self,
48 cookie: &ServoCookie,
49 url: &ServoUrl,
50 source: CookieSource,
51 ) -> Result<Option<ServoCookie>, RemoveCookieError> {
52 let domain = reg_host(cookie.cookie.domain().as_ref().unwrap_or(&""));
53 let cookies = self.cookies_map.entry(domain).or_default();
54
55 if !cookie.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() {
57 let new_domain = cookie.cookie.domain().as_ref().unwrap().to_owned();
58 let new_path = cookie.cookie.path().as_ref().unwrap().to_owned();
59
60 let any_overlapping = cookies.iter().any(|c| {
61 let existing_domain = c.cookie.domain().as_ref().unwrap().to_owned();
62 let existing_path = c.cookie.path().as_ref().unwrap().to_owned();
63
64 c.cookie.name() == cookie.cookie.name() &&
65 c.cookie.secure().unwrap_or(false) &&
66 (ServoCookie::domain_match(new_domain, existing_domain) ||
67 ServoCookie::domain_match(existing_domain, new_domain)) &&
68 ServoCookie::path_match(new_path, existing_path)
69 });
70
71 if any_overlapping {
72 return Err(RemoveCookieError::Overlapping);
73 }
74 }
75
76 let position = cookies.iter().position(|c| {
78 c.cookie.domain() == cookie.cookie.domain() &&
79 c.cookie.path() == cookie.cookie.path() &&
80 c.cookie.name() == cookie.cookie.name()
81 });
82
83 if let Some(ind) = position {
84 let c = cookies.remove(ind);
86
87 if c.cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP {
89 cookies.push(c);
91 Err(RemoveCookieError::NonHTTP)
92 } else {
93 Ok(Some(c))
94 }
95 } else {
96 Ok(None)
97 }
98 }
99
100 pub fn clear_storage(&mut self, url: Option<&ServoUrl>) {
101 if let Some(url) = url {
102 let domain = reg_host(url.host_str().unwrap_or(""));
103 let cookies = self.cookies_map.entry(domain).or_default();
104 for cookie in cookies.iter_mut() {
105 cookie.set_expiry_time_in_past();
106 }
107 } else {
108 self.cookies_map.clear();
109 }
110 }
111
112 pub fn delete_cookie_with_name(&mut self, url: &ServoUrl, name: String) {
113 let domain = reg_host(url.host_str().unwrap_or(""));
114 let cookies = self.cookies_map.entry(domain).or_default();
115 for cookie in cookies.iter_mut() {
116 if cookie.cookie.name() == name {
117 cookie.set_expiry_time_in_past();
118 }
119 }
120 }
121
122 pub fn push(&mut self, mut cookie: ServoCookie, url: &ServoUrl, source: CookieSource) {
124 if cookie.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() {
126 return;
127 }
128
129 let old_cookie = self.remove(&cookie, url, source);
130 if old_cookie.is_err() {
131 return;
133 }
134
135 if let Some(old_cookie) = old_cookie.unwrap() {
137 cookie.creation_time = old_cookie.creation_time;
139 }
140
141 let domain = reg_host(cookie.cookie.domain().as_ref().unwrap_or(&""));
143 let cookies = self.cookies_map.entry(domain).or_default();
144
145 if cookies.len() == self.max_per_host {
146 let old_len = cookies.len();
147 cookies.retain(|c| !is_cookie_expired(c));
148 let new_len = cookies.len();
149
150 if new_len == old_len &&
152 !evict_one_cookie(cookie.cookie.secure().unwrap_or(false), cookies)
153 {
154 return;
155 }
156 }
157 cookies.push(cookie);
158 }
159
160 pub fn cookie_comparator(a: &ServoCookie, b: &ServoCookie) -> Ordering {
161 let a_path_len = a.cookie.path().as_ref().map_or(0, |p| p.len());
162 let b_path_len = b.cookie.path().as_ref().map_or(0, |p| p.len());
163 match a_path_len.cmp(&b_path_len) {
164 Ordering::Equal => a.creation_time.cmp(&b.creation_time),
165 Ordering::Greater => Ordering::Less,
167 Ordering::Less => Ordering::Greater,
168 }
169 }
170
171 pub fn remove_expired_cookies_for_url(&mut self, url: &ServoUrl) {
172 let domain = reg_host(url.host_str().unwrap_or(""));
173 if let Entry::Occupied(mut entry) = self.cookies_map.entry(domain) {
174 let cookies = entry.get_mut();
175 cookies.retain(|c| !is_cookie_expired(c));
176 if cookies.is_empty() {
177 entry.remove_entry();
178 }
179 }
180 }
181
182 pub fn cookies_for_url(&mut self, url: &ServoUrl, source: CookieSource) -> Option<String> {
184 let cookie_list = self.cookies_data_for_url(url, source);
186
187 let reducer = |acc: String, cookie: Cookie<'static>| -> String {
188 (match acc.len() {
195 0 => acc,
196 _ => acc + "; ",
197 }) + cookie.name() +
198 "=" +
199 cookie.value()
200 };
201
202 let result = cookie_list.fold("".to_owned(), reducer);
204
205 info!(" === COOKIES SENT: {}", result);
206 match result.len() {
207 0 => None,
208 _ => Some(result),
209 }
210 }
211
212 pub fn query_cookies(&mut self, url: &ServoUrl, name: Option<String>) -> Vec<Cookie<'static>> {
214 let cookie_list = self.cookies_data_for_url(url, CookieSource::NonHTTP);
216
217 if let Some(name) = name {
220 cookie_list.filter(|cookie| cookie.name() == name).collect()
223 } else {
224 cookie_list.collect()
225 }
226
227 }
232
233 pub fn cookies_data_for_url<'a>(
234 &'a mut self,
235 url: &'a ServoUrl,
236 source: CookieSource,
237 ) -> impl Iterator<Item = cookie::Cookie<'static>> + 'a {
238 let domain = reg_host(url.host_str().unwrap_or(""));
239 let cookies = self.cookies_map.entry(domain).or_default();
240
241 cookies
242 .iter_mut()
243 .filter(move |c| c.appropriate_for_url(url, source))
244 .sorted_by(|a: &&mut ServoCookie, b: &&mut ServoCookie| {
245 CookieStorage::cookie_comparator(a, b)
247 })
248 .map(|c| {
249 c.touch();
251 c.cookie.clone()
252 })
253 }
254}
255
256fn reg_host(url: &str) -> String {
257 reg_suffix(url).to_lowercase()
258}
259
260fn is_cookie_expired(cookie: &ServoCookie) -> bool {
261 matches!(cookie.expiry_time, Some(date_time) if date_time <= SystemTime::now())
262}
263
264fn evict_one_cookie(is_secure_cookie: bool, cookies: &mut Vec<ServoCookie>) -> bool {
265 let oldest_accessed = get_oldest_accessed(false, cookies);
267
268 if let Some((index, _)) = oldest_accessed {
269 cookies.remove(index);
270 } else {
271 if !is_secure_cookie {
273 return false;
274 }
275 let oldest_accessed = get_oldest_accessed(true, cookies);
276 if let Some((index, _)) = oldest_accessed {
277 cookies.remove(index);
278 }
279 }
280 true
281}
282
283fn get_oldest_accessed(
284 is_secure_cookie: bool,
285 cookies: &mut [ServoCookie],
286) -> Option<(usize, SystemTime)> {
287 let mut oldest_accessed = None;
288 for (i, c) in cookies.iter().enumerate() {
289 if (c.cookie.secure().unwrap_or(false) == is_secure_cookie) &&
290 oldest_accessed
291 .as_ref()
292 .is_none_or(|(_, current_oldest_time)| c.last_access < *current_oldest_time)
293 {
294 oldest_accessed = Some((i, c.last_access));
295 }
296 }
297 oldest_accessed
298}