use crate::cookies::{
domain_ok, parse_netscape, NetscapeCookie, MAX_COOKIES, MAX_COOKIES_FILE_BYTES,
};
use rightkit_fs::{AtomicWriteOptions, AtomicWriter, FsError, Privacy, ReplaceMode, RetryPolicy};
use std::fs;
use std::path::Path;
use std::time::Duration;
use thiserror::Error;
const HEADER: &str = "# Netscape HTTP Cookie File\n";
const HTTP_ONLY_PREFIX: &str = "#HttpOnly_";
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum CookieExportError {
#[error("no cookie domains were declared")]
NoDomains,
#[error("declared cookie domain {domain:?} is empty or malformed")]
BadDomain { domain: String },
#[error(
"no exportable cookies: {offered} offered, {in_scope} in the declared domains, \
{invalid} invalid; nothing was written"
)]
NothingToExport {
offered: usize,
in_scope: usize,
invalid: usize,
},
#[error(
"cookie {index} in the declared domains has an invalid {field} field; nothing was written"
)]
InvalidCookie { index: usize, field: &'static str },
#[error("{count} cookies match; a file holds at most {limit}; nothing was written")]
TooManyCookies { count: usize, limit: usize },
#[error("the export would be {bytes} bytes; the limit is {limit}; nothing was written")]
TooLarge { bytes: usize, limit: usize },
#[error("the export did not round-trip through parse_netscape ({0}); nothing was written")]
NotRoundTrippable(String),
#[error("publishing the cookie file failed: {0}")]
Publish(#[source] FsError),
#[error("clearing the cookie file failed: {0}")]
Clear(#[source] FsError),
}
impl CookieExportError {
pub fn target_replaced(&self) -> bool {
matches!(self, Self::Publish(e) if e.target_replaced())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExportReport {
pub exported: usize,
pub out_of_scope: usize,
pub invalid_skipped: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClearOutcome {
Removed,
Absent,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CookieExport {
domains: Vec<String>,
mark_http_only: bool,
skip_invalid: bool,
}
fn normalise_declared(raw: &str) -> Option<String> {
let d = raw.trim().trim_start_matches('.').to_ascii_lowercase();
domain_ok(&d).then_some(d)
}
impl CookieExport {
pub fn new<I, S>(domains: I) -> Result<Self, CookieExportError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut out: Vec<String> = Vec::new();
for raw in domains {
let raw = raw.as_ref();
let d = normalise_declared(raw).ok_or_else(|| CookieExportError::BadDomain {
domain: raw.to_string(),
})?;
if !out.contains(&d) {
out.push(d);
}
}
if out.is_empty() {
return Err(CookieExportError::NoDomains);
}
Ok(Self {
domains: out,
mark_http_only: false,
skip_invalid: false,
})
}
#[must_use]
pub fn mark_http_only(mut self, mark: bool) -> Self {
self.mark_http_only = mark;
self
}
#[must_use]
pub fn skip_invalid(mut self, skip: bool) -> Self {
self.skip_invalid = skip;
self
}
pub fn domains(&self) -> &[String] {
&self.domains
}
pub fn matches(&self, cookie_domain: &str) -> bool {
let c = cookie_domain
.trim()
.trim_start_matches('.')
.to_ascii_lowercase();
self.domains.iter().any(|d| {
c == *d
|| (c.len() > d.len()
&& c.ends_with(d.as_str())
&& c.as_bytes()[c.len() - d.len() - 1] == b'.')
})
}
fn prepare(
&self,
cookies: &[NetscapeCookie],
) -> Result<(String, ExportReport), CookieExportError> {
let mut selected: Vec<NetscapeCookie> = Vec::new();
let mut out_of_scope = 0usize;
let mut in_scope = 0usize;
let mut invalid = 0usize;
for (index, cookie) in cookies.iter().enumerate() {
if !self.matches(&cookie.domain) {
out_of_scope += 1;
continue;
}
in_scope += 1;
let mut c = cookie.clone();
c.domain = c.domain.trim().trim_start_matches('.').to_ascii_lowercase();
if let Some(field) = c.invalid_field() {
if self.skip_invalid {
invalid += 1;
continue;
}
return Err(CookieExportError::InvalidCookie { index, field });
}
if !self.mark_http_only {
c.http_only = false;
}
selected.push(c);
}
if selected.is_empty() {
return Err(CookieExportError::NothingToExport {
offered: cookies.len(),
in_scope,
invalid,
});
}
if selected.len() > MAX_COOKIES {
return Err(CookieExportError::TooManyCookies {
count: selected.len(),
limit: MAX_COOKIES,
});
}
let text = render(&selected);
if text.len() > MAX_COOKIES_FILE_BYTES {
return Err(CookieExportError::TooLarge {
bytes: text.len(),
limit: MAX_COOKIES_FILE_BYTES,
});
}
match parse_netscape(&text) {
Err(e) => {
return Err(CookieExportError::NotRoundTrippable(e.to_string()));
}
Ok(parsed) if parsed != selected => {
return Err(CookieExportError::NotRoundTrippable(
"cookie fields differ".to_string(),
));
}
Ok(_) => {}
}
let report = ExportReport {
exported: selected.len(),
out_of_scope,
invalid_skipped: invalid,
};
Ok((text, report))
}
pub fn export_to(
&self,
path: &Path,
cookies: &[NetscapeCookie],
) -> Result<ExportReport, CookieExportError> {
let (text, report) = self.prepare(cookies)?;
publish(path, text.as_bytes())?;
Ok(report)
}
pub fn clear(path: &Path) -> Result<ClearOutcome, CookieExportError> {
let meta = match fs::symlink_metadata(path) {
Ok(m) => m,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(ClearOutcome::Absent),
Err(e) => return Err(CookieExportError::Clear(FsError::io(path, e))),
};
if meta.is_dir() {
return Err(CookieExportError::Clear(FsError::NotAFile(
path.to_path_buf(),
)));
}
match fs::remove_file(path) {
Ok(()) => {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
let _ = rightkit_fs::try_sync_dir(parent);
}
Ok(ClearOutcome::Removed)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(ClearOutcome::Absent),
Err(e) => Err(CookieExportError::Clear(FsError::io(path, e))),
}
}
pub fn clear_with(
path: &Path,
invalidate: impl FnOnce(ClearOutcome),
) -> Result<ClearOutcome, CookieExportError> {
let outcome = Self::clear(path)?;
invalidate(outcome);
Ok(outcome)
}
}
fn render(cookies: &[NetscapeCookie]) -> String {
let mut text = String::from(HEADER);
for c in cookies {
if c.http_only {
text.push_str(HTTP_ONLY_PREFIX);
}
if c.include_subdomains {
text.push('.');
}
text.push_str(&c.domain);
text.push('\t');
text.push_str(if c.include_subdomains {
"TRUE"
} else {
"FALSE"
});
text.push('\t');
text.push_str(&c.path);
text.push('\t');
text.push_str(if c.secure { "TRUE" } else { "FALSE" });
text.push('\t');
text.push_str(&c.expires.unwrap_or(0).to_string());
text.push('\t');
text.push_str(&c.name);
text.push('\t');
text.push_str(c.value());
text.push('\n');
}
text
}
fn publish_options() -> AtomicWriteOptions {
AtomicWriteOptions {
private: true,
create_parents: true,
durable: true,
replace: ReplaceMode::Rename,
retry_sharing_violation: Some(RetryPolicy::new(5, Duration::from_millis(50))),
privacy: Privacy::OwnerOnly,
}
}
fn verify_staged(temp: &Path, expected: &[u8]) -> std::io::Result<()> {
let staged = fs::read(temp)?;
if staged == expected {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"staged cookie file does not match the export",
))
}
}
fn publish(path: &Path, bytes: &[u8]) -> Result<(), CookieExportError> {
let mut writer =
AtomicWriter::create_with(path, publish_options()).map_err(CookieExportError::Publish)?;
writer
.write_all(bytes)
.map_err(CookieExportError::Publish)?;
writer
.commit_checked(|temp| verify_staged(temp, bytes))
.map_err(CookieExportError::Publish)
}