use std::borrow::ToOwned;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::time::{Duration, SystemTime};
use cookie::Cookie;
use net_traits::pub_domains::is_pub_domain;
use net_traits::CookieSource;
use serde::{Deserialize, Serialize};
use servo_url::ServoUrl;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ServoCookie {
#[serde(
deserialize_with = "hyper_serde::deserialize",
serialize_with = "hyper_serde::serialize"
)]
pub cookie: Cookie<'static>,
pub host_only: bool,
pub persistent: bool,
pub creation_time: SystemTime,
pub last_access: SystemTime,
pub expiry_time: Option<SystemTime>,
}
impl ServoCookie {
pub fn from_cookie_string(
cookie_str: String,
request: &ServoUrl,
source: CookieSource,
) -> Option<ServoCookie> {
Cookie::parse(cookie_str)
.ok()
.map(|cookie| ServoCookie::new_wrapped(cookie, request, source))
.unwrap_or(None)
}
pub fn new_wrapped(
mut cookie: Cookie<'static>,
request: &ServoUrl,
source: CookieSource,
) -> Option<ServoCookie> {
let max_age: Option<Duration> =
cookie.max_age().and_then(|max_age| max_age.try_into().ok());
let (persistent, expiry_time) = match (max_age, cookie.expires_datetime()) {
(Some(max_age), _) => (true, Some(SystemTime::now() + max_age)),
(_, Some(date_time)) => (true, Some(date_time.into())),
_ => (false, None),
};
let url_host = request.host_str().unwrap_or("").to_owned();
let mut domain = cookie.domain().unwrap_or("").to_owned();
if is_pub_domain(&domain) {
if domain == url_host {
domain = "".to_string();
} else {
return None;
}
}
let host_only = if !domain.is_empty() {
if !ServoCookie::domain_match(&url_host, &domain) {
return None;
} else {
cookie.set_domain(domain);
false
}
} else {
cookie.set_domain(url_host);
true
};
let mut has_path_specified = true;
let mut path = cookie
.path()
.unwrap_or_else(|| {
has_path_specified = false;
""
})
.to_owned();
if !path.starts_with('/') {
path = ServoCookie::default_path(request.path()).to_string();
}
cookie.set_path(path);
if cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP {
return None;
}
if (cookie.name().starts_with("__Secure-") || cookie.name().starts_with("__Host-")) &&
!(cookie.secure().unwrap_or(false) && request.is_secure_scheme())
{
return None;
}
if cookie.name().starts_with("__Host-") &&
!(host_only && has_path_specified && cookie.path().unwrap() == "/")
{
return None;
}
Some(ServoCookie {
cookie,
host_only,
persistent,
creation_time: SystemTime::now(),
last_access: SystemTime::now(),
expiry_time,
})
}
pub fn touch(&mut self) {
self.last_access = SystemTime::now();
}
pub fn set_expiry_time_in_past(&mut self) {
self.expiry_time = Some(SystemTime::UNIX_EPOCH)
}
pub fn default_path(request_path: &str) -> &str {
if !request_path.starts_with('/') {
return "/";
}
let rightmost_slash_idx = request_path.rfind('/').unwrap();
if rightmost_slash_idx == 0 {
return "/";
}
&request_path[..rightmost_slash_idx]
}
pub fn path_match(request_path: &str, cookie_path: &str) -> bool {
request_path == cookie_path ||
(request_path.starts_with(cookie_path) &&
(
cookie_path.ends_with('/') ||
request_path[cookie_path.len()..].starts_with('/')
))
}
pub fn domain_match(string: &str, domain_string: &str) -> bool {
let string = &string.to_lowercase();
let domain_string = &domain_string.to_lowercase();
string == domain_string ||
(string.ends_with(domain_string) &&
string.as_bytes()[string.len() - domain_string.len() - 1] == b'.' &&
string.parse::<Ipv4Addr>().is_err() &&
string.parse::<Ipv6Addr>().is_err())
}
pub fn appropriate_for_url(&self, url: &ServoUrl, source: CookieSource) -> bool {
let domain = url.host_str();
if self.host_only {
if self.cookie.domain() != domain {
return false;
}
} else if let (Some(domain), Some(cookie_domain)) = (domain, &self.cookie.domain()) {
if !ServoCookie::domain_match(domain, cookie_domain) {
return false;
}
}
if let Some(cookie_path) = self.cookie.path() {
if !ServoCookie::path_match(url.path(), cookie_path) {
return false;
}
}
if self.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() {
return false;
}
if self.cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP {
return false;
}
true
}
}