use std::fs;
use std::path::Path;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use url::Url;
use crate::error::{Aria2Error, Result};
use serde::{Deserialize, Serialize};
use super::jar_date::{format_systemtime_as_http_date, parse_http_date};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JarCookie {
pub name: String,
pub value: String,
pub domain: String,
pub path: String,
pub expires: Option<SystemTime>,
pub secure: bool,
pub http_only: bool,
pub creation_time: SystemTime,
pub same_site: super::SameSite,
}
impl JarCookie {
pub fn new(name: &str, value: &str, domain: &str) -> Self {
Self {
name: name.to_string(),
value: value.to_string(),
domain: domain.to_string(),
path: "/".to_string(),
expires: None,
secure: false,
http_only: false,
creation_time: SystemTime::now(),
same_site: super::SameSite::default(),
}
}
pub fn matches_url(&self, url: &str, is_secure: bool) -> bool {
let parsed = match Url::parse(url) {
Ok(url) => url,
Err(_) => return false,
};
let request_host = match parsed.host_str() {
Some(host) => host.trim_end_matches('.').to_ascii_lowercase(),
None => return false,
};
let cookie_domain = self
.domain
.trim()
.trim_start_matches('.')
.trim_end_matches('.')
.to_ascii_lowercase();
if cookie_domain.is_empty() {
return false;
}
if self.secure && (!is_secure || parsed.scheme() != "https") {
return false;
}
if request_host != cookie_domain && !request_host.ends_with(&format!(".{cookie_domain}")) {
return false;
}
let request_path = parsed.path();
let cookie_path = if self.path.is_empty() || !self.path.starts_with('/') {
"/"
} else {
self.path.as_str()
};
if !request_path.starts_with(cookie_path)
|| (cookie_path != "/"
&& request_path.len() > cookie_path.len()
&& !cookie_path.ends_with('/')
&& request_path.as_bytes()[cookie_path.len()] != b'/')
{
return false;
}
self.expires
.is_none_or(|expires| SystemTime::now() <= expires)
}
pub fn to_header_value(&self) -> String {
let mut s = format!("{}={}", self.name, self.value);
if !self.domain.is_empty() {
s.push_str(&format!("; Domain={}", self.domain));
}
s.push_str(&format!("; Path={}", self.path));
if let Some(_expires) = self.expires {
if let Ok(_dur) = _expires.duration_since(SystemTime::UNIX_EPOCH) {
s.push_str(&format!(
"; Expires={}",
format_systemtime_as_http_date(_expires)
));
}
}
if self.secure {
s.push_str("; Secure");
}
if self.http_only {
s.push_str("; HttpOnly");
}
s
}
pub fn parse_set_cookie(header_value: &str) -> Option<Self> {
let header = header_value.trim();
if header.is_empty() {
return None;
}
let parts: Vec<&str> = header.split(';').collect();
if parts.is_empty() {
return None;
}
let nv: Vec<&str> = parts[0].trim().splitn(2, '=').collect();
if nv.len() != 2 {
return None;
}
let name = nv[0].trim();
let value = nv[1].trim();
if name.is_empty() {
return None;
}
let mut cookie = Self::new(name, value, "");
for attr in &parts[1..] {
let attr = attr.trim();
if attr.is_empty() {
continue;
}
let kv: Vec<&str> = attr.splitn(2, '=').collect();
match kv[0].trim().to_lowercase().as_str() {
"domain" if kv.len() > 1 => {
cookie.domain = kv[1].trim().to_string();
}
"path" if kv.len() > 1 => {
cookie.path = kv[1].trim().to_string();
}
"max-age" if kv.len() > 1 => {
if let Ok(secs) = kv[1].trim().parse::<u64>() {
cookie.expires = Some(SystemTime::now() + Duration::from_secs(secs));
}
}
"expires" if kv.len() > 1 => {
if cookie.expires.is_none()
&& let Ok(dt) = parse_http_date(kv[1].trim())
{
cookie.expires = Some(dt);
}
}
"secure" => {
cookie.secure = true;
}
"httponly" => {
cookie.http_only = true;
}
"samesite" if kv.len() > 1 => {
cookie.same_site = match kv[1].trim().to_ascii_lowercase().as_str() {
"strict" => super::SameSite::Strict,
"lax" => super::SameSite::Lax,
_ => super::SameSite::None,
};
}
_ => {} }
}
Some(cookie)
}
}
impl PartialEq for JarCookie {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
&& self.domain.eq_ignore_ascii_case(&other.domain)
&& self.path == other.path
}
}
impl From<JarCookie> for super::Cookie {
fn from(cookie: JarCookie) -> Self {
cookie.into_cookie()
}
}
impl JarCookie {
pub fn into_cookie(self) -> super::Cookie {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
let expiry_time = self
.expires
.and_then(|expiry| expiry.duration_since(UNIX_EPOCH).ok())
.map(|duration| duration.as_secs() as i64)
.unwrap_or(0);
super::Cookie {
name: self.name,
value: self.value,
domain: self.domain,
path: self.path,
expiry_time,
creation_time: self
.creation_time
.duration_since(UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs() as i64)
.unwrap_or(now),
last_access_time: now,
persistent: expiry_time != 0,
host_only: false,
secure: self.secure,
http_only: self.http_only,
same_site: self.same_site,
}
}
}
pub struct CookieJar {
pub cookies: Vec<JarCookie>,
}
impl CookieJar {
pub fn new() -> Self {
Self {
cookies: Vec::new(),
}
}
pub fn store(&mut self, cookie: JarCookie) {
self.cookies.retain(|c| {
!(c.name == cookie.name
&& c.domain.eq_ignore_ascii_case(&cookie.domain)
&& c.path == cookie.path)
});
self.cookies.push(cookie);
}
pub fn get_cookies_for_url(&self, url: &str, is_secure: bool) -> Vec<JarCookie> {
self.cookies
.iter()
.filter(|c| c.matches_url(url, is_secure))
.cloned()
.collect()
}
pub fn cookie_header_for_url(&self, url: &str, is_secure: bool) -> Option<String> {
let matching = self.get_cookies_for_url(url, is_secure);
if matching.is_empty() {
return None;
}
let header: String = matching
.iter()
.map(|c| format!("{}={}", c.name, c.value))
.collect::<Vec<_>>()
.join("; ");
Some(header)
}
pub fn cleanup_expired(&mut self) -> usize {
let before = self.cookies.len();
self.cookies.retain(|c| {
if let Some(exp) = c.expires {
SystemTime::now() <= exp
} else {
true }
});
before - self.cookies.len()
}
pub fn load_netscape_file(&mut self, path: &Path) -> Result<usize> {
let content = fs::read_to_string(path).map_err(|e| Aria2Error::Io(e.to_string()))?;
let mut loaded = 0;
for line in content.lines() {
if line.starts_with('#') || line.starts_with('\n') || line.is_empty() {
continue;
}
let fields: Vec<&str> = line.split('\t').collect();
if fields.len() >= 7 {
let domain = fields[0].trim().to_ascii_lowercase();
let path = fields[2].trim();
let secure = fields[3] == "TRUE";
let expires = fields[4].trim().parse::<i64>().ok().and_then(|ts| {
if ts > 0 {
Some(SystemTime::UNIX_EPOCH + Duration::from_secs(ts as u64))
} else {
None }
});
let name = fields[5].trim().to_string();
let value = if fields.len() > 7 {
fields[6..].join("\t")
} else {
fields[6].trim().to_string()
};
let cookie = JarCookie {
name,
value,
domain: domain.to_string(),
path: path.to_string(),
expires,
secure,
http_only: false, creation_time: SystemTime::now(),
same_site: super::SameSite::default(),
};
self.cookies.push(cookie);
loaded += 1;
}
}
Ok(loaded)
}
pub fn len(&self) -> usize {
self.cookies.len()
}
pub fn is_empty(&self) -> bool {
self.cookies.is_empty()
}
pub fn clear(&mut self) {
self.cookies.clear();
}
}
impl Default for CookieJar {
fn default() -> Self {
Self::new()
}
}