S010: logins, cookies, proxies, sites and certificates
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
6bdbd20e10
commit
c09ea494b7
27 changed files with 2358 additions and 62 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
|
@ -2224,6 +2224,7 @@ dependencies = [
|
|||
"fastrand",
|
||||
"futures-lite",
|
||||
"log",
|
||||
"md-5",
|
||||
"medlar-testserver",
|
||||
"percent-encoding",
|
||||
"regex",
|
||||
|
|
@ -2231,6 +2232,7 @@ dependencies = [
|
|||
"rusqlite",
|
||||
"rustix 1.1.6",
|
||||
"rustls",
|
||||
"rustls-platform-verifier",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
|
|
|
|||
|
|
@ -12,13 +12,13 @@ FEATURES 1.15, 1.16, 2.2 (per-site rules storage), FDM's site manager.
|
|||
- ~/Projects/Nacre/Cargo.toml (keyring line)
|
||||
|
||||
## Steps
|
||||
- [ ] Basic, Digest and cookie logins; per-download headers, cookies, referrer, user agent
|
||||
- [ ] Credentials scoped to their host: dropped on cross-host redirects (test), never in logs, process arguments or the store
|
||||
- [ ] Secret Service keyring with a fallback that keeps secrets in memory only and says so
|
||||
- [ ] Site profiles: login, connection cap, limit, user agent, proxy, folder; wildcard match, most specific wins
|
||||
- [ ] Proxies: HTTP, SOCKS5 with remote DNS, system setting; per app, site, download; bypass list
|
||||
- [ ] TLS: system roots, plain explanation of certificate errors, per-site exception only by explicit choice
|
||||
- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S010: …`, push
|
||||
- [x] Basic, Digest and cookie logins; per-download headers, cookies, referrer, user agent
|
||||
- [x] Credentials scoped to their host: dropped on cross-host redirects (test), never in logs, process arguments or the store
|
||||
- [x] Secret Service keyring with a fallback that keeps secrets in memory only and says so
|
||||
- [x] Site profiles: login, connection cap, limit, user agent, proxy, folder; wildcard match, most specific wins
|
||||
- [x] Proxies: HTTP, SOCKS5 with remote DNS, system setting; per app, site, download; bypass list
|
||||
- [x] TLS: system roots, plain explanation of certificate errors, per-site exception only by explicit choice
|
||||
- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S010: …`, push
|
||||
|
||||
## End criteria
|
||||
- `nice cargo test -j 2 -p medlar-core --test auth` green, including redaction and redirect leak tests
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H
|
|||
- [x] [S007](02%20Engine/S007-error-recovery.md) Error recovery
|
||||
- [x] [S008](02%20Engine/S008-continue-links.md) Continue from a new link
|
||||
- [ ] [S009](02%20Engine/S009-mirrors-checksums.md) Mirrors, Metalink and checksums
|
||||
- [ ] [S010](02%20Engine/S010-logins-proxies.md) Logins, cookies and proxies
|
||||
- [x] [S010](02%20Engine/S010-logins-proxies.md) Logins, cookies and proxies
|
||||
- [ ] [S011](02%20Engine/S011-ftp-sftp.md) FTP, FTPS and SFTP
|
||||
- [ ] [S012](02%20Engine/S012-streams.md) HLS, DASH, RTSP and MMS
|
||||
|
||||
|
|
|
|||
|
|
@ -11,15 +11,19 @@ chrono = { version = "0.4", default-features = false, features = ["clock", "std"
|
|||
dirs = "6"
|
||||
futures-lite = "2.6"
|
||||
log = { workspace = true, features = ["std"] }
|
||||
md-5 = "0.11.0"
|
||||
percent-encoding = "2.3.2"
|
||||
regex = { version = "1", default-features = false, features = ["std", "unicode-case", "unicode-perl"] }
|
||||
# Pinned: D-017.
|
||||
reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider"] }
|
||||
reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider", "socks"] }
|
||||
rusqlite = { version = "0.43", features = ["bundled", "fallible_uint"] }
|
||||
rustix = { version = "1.1.6", features = ["fs", "process"] }
|
||||
rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
# The one reqwest has.
|
||||
rustls-platform-verifier = "0.7.1"
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2 = "0.11.1"
|
||||
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time"] }
|
||||
url = "2"
|
||||
# Without its tokio feature: the window's accessibility and tray share this build and run outside of tokio.
|
||||
|
|
@ -28,5 +32,4 @@ zbus = "5.19"
|
|||
[dev-dependencies]
|
||||
fastrand = "2.5.0"
|
||||
medlar-testserver.workspace = true
|
||||
sha2 = "0.11.1"
|
||||
tempfile = "3"
|
||||
|
|
|
|||
|
|
@ -98,6 +98,14 @@
|
|||
"error.offline.why": "This computer is not connected. The download goes on when the network is back.",
|
||||
"error.portal": "Network needs a sign-in",
|
||||
"error.portal.why": "This network wants you to sign in on its web page first. The download goes on after that.",
|
||||
"error.tls.expired": "The certificate of {server} has expired, so nothing was downloaded from it. This computer's clock may also be wrong.",
|
||||
"error.tls.not_yet": "The certificate of {server} is not valid yet, so nothing was downloaded from it. This computer's clock may be wrong.",
|
||||
"error.tls.unknown": "Nobody this computer trusts vouches for {server}, so nothing was downloaded from it.",
|
||||
"error.tls.name": "The certificate belongs to another server than {server}, so nothing was downloaded from it.",
|
||||
"error.tls.revoked": "The certificate of {server} was withdrawn, so nothing was downloaded from it.",
|
||||
"error.proxy": "No connection through the proxy",
|
||||
"error.proxy.why": "The proxy for {server} did not answer, or could not reach it.",
|
||||
"error.proxy.setting": "The address of the proxy for {server} makes no sense.",
|
||||
"error.login": "Login needed",
|
||||
"error.login.why": "{server} wants a user name and password.",
|
||||
"error.forbidden": "Access denied",
|
||||
|
|
@ -108,6 +116,9 @@
|
|||
"error.expired.why": "{server} gave out the file before but refuses now (status {code}). A new link for the same file continues the download.",
|
||||
"error.not_found": "File not found",
|
||||
"error.not_found.why": "{server} has no file at this link (status {code}).",
|
||||
"error.login.proxy": "The proxy for {server} wants a user name and password, or the ones it got are wrong.",
|
||||
"secret.memory": "No keyring answered, so logins are only remembered until Medlar closes.",
|
||||
"secret.label": "Medlar login for {host}",
|
||||
"error.rejected": "Request rejected",
|
||||
"error.rejected.why": "{server} did not accept the request (status {code}).",
|
||||
"error.busy": "Server is busy",
|
||||
|
|
|
|||
243
crates/core/src/auth.rs
Normal file
243
crates/core/src/auth.rs
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
//! Logins that servers ask for: Basic and Digest (RFC 7617, RFC 7616).
|
||||
|
||||
use md5::Md5;
|
||||
use reqwest::header::{HeaderMap, WWW_AUTHENTICATE};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use std::fmt;
|
||||
use std::hash::{BuildHasher, Hasher, RandomState};
|
||||
use url::{Position, Url};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct Login {
|
||||
pub user: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Login {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("Login([hidden])")
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the login out of `scheme://user:password@host`, for the keyring. Works for proxies too.
|
||||
pub fn take_login(text: &str) -> (String, Option<Login>) {
|
||||
let Ok(mut url) = Url::parse(text) else { return (text.into(), None) };
|
||||
let plain = |s: &str| percent_encoding::percent_decode_str(s).decode_utf8_lossy().into_owned();
|
||||
let login = Login { user: plain(url.username()), password: plain(url.password().unwrap_or_default()) };
|
||||
if login == Login::default() || url.set_username("").is_err() || url.set_password(None).is_err() {
|
||||
return (text.into(), None);
|
||||
}
|
||||
(url.into(), Some(login))
|
||||
}
|
||||
|
||||
/// What a server wants to see.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Challenge {
|
||||
Basic,
|
||||
Digest(Digest),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Digest {
|
||||
realm: String,
|
||||
pub(crate) nonce: String,
|
||||
opaque: Option<String>,
|
||||
sha: bool,
|
||||
session: bool,
|
||||
qop: bool,
|
||||
/// Requests answered with this nonce.
|
||||
count: u32,
|
||||
}
|
||||
|
||||
impl Challenge {
|
||||
/// The strongest one that Medlar knows.
|
||||
pub fn of(headers: &HeaderMap) -> Option<Challenge> {
|
||||
let mut found: Vec<(u8, Challenge)> = vec![];
|
||||
for value in headers.get_all(WWW_AUTHENTICATE).iter().filter_map(|v| v.to_str().ok()) {
|
||||
for (scheme, params) in schemes(value) {
|
||||
if scheme.eq_ignore_ascii_case("basic") {
|
||||
found.push((0, Challenge::Basic));
|
||||
} else if scheme.eq_ignore_ascii_case("digest")
|
||||
&& let Some(d) = Digest::of(¶ms)
|
||||
{
|
||||
found.push((1 + u8::from(d.sha), Challenge::Digest(d)));
|
||||
}
|
||||
}
|
||||
}
|
||||
found.into_iter().max_by_key(|(strength, _)| *strength).map(|(_, c)| c)
|
||||
}
|
||||
}
|
||||
|
||||
impl Digest {
|
||||
fn of(params: &[(String, String)]) -> Option<Digest> {
|
||||
let get = |key: &str| params.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.clone());
|
||||
let algorithm = get("algorithm").unwrap_or("MD5".into()).to_ascii_uppercase();
|
||||
let (hash, session) = algorithm.strip_suffix("-SESS").map_or((algorithm.as_str(), false), |h| (h, true));
|
||||
let sha = match hash {
|
||||
"MD5" => false,
|
||||
"SHA-256" => true,
|
||||
_ => return None,
|
||||
};
|
||||
let qop = match get("qop") {
|
||||
None => false,
|
||||
Some(q) if q.split(',').any(|q| q.trim().eq_ignore_ascii_case("auth")) => true,
|
||||
// Only the kind that signs bodies.
|
||||
Some(_) => return None,
|
||||
};
|
||||
Some(Digest { realm: get("realm")?, nonce: get("nonce")?, opaque: get("opaque"), sha, session, qop, count: 0 })
|
||||
}
|
||||
|
||||
/// The `Authorization` header for the next GET of `url`.
|
||||
pub fn answer(&mut self, login: &Login, url: &Url) -> String {
|
||||
self.count += 1;
|
||||
let random = || RandomState::new().build_hasher().finish();
|
||||
self.answer_with(login, url, &format!("{:016x}{:016x}", random(), random()))
|
||||
}
|
||||
|
||||
fn answer_with(&self, login: &Login, url: &Url, cnonce: &str) -> String {
|
||||
let Digest { realm, nonce, .. } = self;
|
||||
let uri = &url[Position::BeforePath..Position::AfterQuery];
|
||||
let mut secret = self.hash(&format!("{}:{realm}:{}", login.user, login.password));
|
||||
if self.session {
|
||||
secret = self.hash(&format!("{secret}:{nonce}:{cnonce}"));
|
||||
}
|
||||
let what = self.hash(&format!("GET:{uri}"));
|
||||
let count = format!("{:08x}", self.count);
|
||||
let response = if self.qop {
|
||||
self.hash(&format!("{secret}:{nonce}:{count}:{cnonce}:auth:{what}"))
|
||||
} else {
|
||||
self.hash(&format!("{secret}:{nonce}:{what}"))
|
||||
};
|
||||
let quoted = |s: &str| format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""));
|
||||
let mut out = format!(
|
||||
"Digest username={}, realm={}, nonce={}, uri={}, response=\"{response}\", algorithm={}{}",
|
||||
quoted(&login.user),
|
||||
quoted(realm),
|
||||
quoted(nonce),
|
||||
quoted(uri),
|
||||
if self.sha { "SHA-256" } else { "MD5" },
|
||||
if self.session { "-sess" } else { "" },
|
||||
);
|
||||
if self.qop {
|
||||
out += &format!(", qop=auth, nc={count}, cnonce=\"{cnonce}\"");
|
||||
} else if self.session {
|
||||
out += &format!(", cnonce=\"{cnonce}\"");
|
||||
}
|
||||
if let Some(opaque) = &self.opaque {
|
||||
out += &format!(", opaque={}", quoted(opaque));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn hash(&self, text: &str) -> String {
|
||||
if self.sha { hex(&Sha256::digest(text)) } else { hex(&Md5::digest(text)) }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// `Scheme key=value, key="value", Scheme …`, the parts of a `WWW-Authenticate` header.
|
||||
fn schemes(header: &str) -> Vec<(String, Vec<(String, String)>)> {
|
||||
let mut out: Vec<(String, Vec<(String, String)>)> = vec![];
|
||||
let mut rest = header.trim_start_matches([' ', ',']);
|
||||
while !rest.is_empty() {
|
||||
let end = rest.find([' ', '=', ',']).unwrap_or(rest.len());
|
||||
let word = &rest[..end];
|
||||
let after = rest[end..].trim_start();
|
||||
if let Some(value) = after.strip_prefix('=').map(str::trim_start) {
|
||||
let (value, left) = quoted(value);
|
||||
if let Some((_, params)) = out.last_mut() {
|
||||
params.push((word.into(), value));
|
||||
}
|
||||
rest = left;
|
||||
} else {
|
||||
out.push((word.into(), vec![]));
|
||||
rest = after;
|
||||
}
|
||||
rest = rest.trim_start_matches([' ', ',']);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A token or quoted string at the start, and what follows it.
|
||||
fn quoted(text: &str) -> (String, &str) {
|
||||
let Some(inner) = text.strip_prefix('"') else {
|
||||
let end = text.find([',', ' ']).unwrap_or(text.len());
|
||||
// One that starts with `=` is the rest of a token68 and means nothing here.
|
||||
return (text[..end].into(), &text[end..]);
|
||||
};
|
||||
let (mut value, mut escaped) = (String::new(), false);
|
||||
for (i, c) in inner.char_indices() {
|
||||
match c {
|
||||
c if escaped => {
|
||||
value.push(c);
|
||||
escaped = false;
|
||||
}
|
||||
'\\' => escaped = true,
|
||||
'"' => return (value, &inner[i + 1..]),
|
||||
c => value.push(c),
|
||||
}
|
||||
}
|
||||
(value, "")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use reqwest::header::HeaderValue;
|
||||
|
||||
fn of(lines: &[&str]) -> Option<Challenge> {
|
||||
Challenge::of(&lines.iter().map(|l| (WWW_AUTHENTICATE, HeaderValue::from_str(l).unwrap())).collect())
|
||||
}
|
||||
|
||||
fn digest(lines: &[&str]) -> Digest {
|
||||
let Some(Challenge::Digest(d)) = of(lines) else { panic!("{lines:?}") };
|
||||
d
|
||||
}
|
||||
|
||||
/// RFC 7616, 3.9.1.
|
||||
#[test]
|
||||
fn digest_of_the_standard() {
|
||||
let common = r#"realm="[email protected]", qop="auth, auth-int", nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS""#;
|
||||
let login = Login { user: "Mufasa".into(), password: "Circle of Life".into() };
|
||||
let url = Url::parse("http://www.example.org/dir/index.html").unwrap();
|
||||
for (algorithm, response) in [
|
||||
("SHA-256", "753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1"),
|
||||
("MD5", "8ca523f5e9506fed4657c9700eebdbec"),
|
||||
] {
|
||||
let mut d = digest(&[&format!("Digest {common}, algorithm={algorithm}")]);
|
||||
d.count = 1;
|
||||
let answer = d.answer_with(&login, &url, "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ");
|
||||
assert!(answer.contains(&format!("response=\"{response}\"")), "{answer}");
|
||||
assert!(answer.contains("nc=00000001") && answer.contains("opaque=\"FQhe") && answer.contains("uri=\"/dir/index.html\""));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_strongest_known_one_is_taken() {
|
||||
assert_eq!(of(&["Basic realm=\"x, Digest y\""]), Some(Challenge::Basic));
|
||||
assert_eq!(of(&["Bearer realm=\"x\""]), None);
|
||||
assert_eq!(of(&["Negotiate", "NTLM abc=="]), None);
|
||||
assert_eq!(of(&["Digest realm=\"x\""]), None);
|
||||
assert_eq!(of(&["Digest realm=x, nonce=y, algorithm=SHA-512"]), None);
|
||||
assert_eq!(of(&["Digest realm=x, nonce=y, qop=auth-int, Basic realm=x"]), Some(Challenge::Basic));
|
||||
let d = digest(&["Basic realm=\"a\", Digest realm=\"q\\\"\", nonce=\"n\", algorithm=md5-sess"]);
|
||||
assert_eq!((d.realm.as_str(), d.nonce.as_str(), d.sha, d.session, d.qop), ("q\"", "n", false, true, false));
|
||||
assert!(digest(&["Digest realm=a, nonce=b", "Digest realm=a, nonce=c, algorithm=SHA-256"]).sha);
|
||||
for junk in ["", ",", "=", "Digest =", "a=b", "Digest realm=\"", "\""] {
|
||||
let _ = of(&[junk]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logins_come_out_of_links() {
|
||||
let (url, login) = take_login("https://me%40x:p%[email protected]/f?q");
|
||||
assert_eq!((url.as_str(), login), ("https://h.example/f?q", Some(Login { user: "me@x".into(), password: "p:ss".into() })));
|
||||
assert_eq!(take_login("http://h/f"), ("http://h/f".into(), None));
|
||||
assert_eq!(take_login("no link"), ("no link".into(), None));
|
||||
assert_eq!(format!("{:?}", Login { user: "u".into(), password: "p".into() }), "Login([hidden])");
|
||||
}
|
||||
}
|
||||
203
crates/core/src/cookie.rs
Normal file
203
crates/core/src/cookie.rs
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
//! Cookies of one download: those it was given and those servers set on the way.
|
||||
|
||||
use crate::site::same_site;
|
||||
use chrono::{DateTime, Utc};
|
||||
use reqwest::header::HeaderValue;
|
||||
use url::{Host, Url};
|
||||
|
||||
/// Enough for any sign-in; a server can't make it grow.
|
||||
const MOST: usize = 100;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Jar(Vec<Cookie>);
|
||||
|
||||
struct Cookie {
|
||||
name: String,
|
||||
value: String,
|
||||
domain: String,
|
||||
/// For `domain` only, not for hosts below it.
|
||||
exact: bool,
|
||||
path: String,
|
||||
secure: bool,
|
||||
expires: Option<DateTime<Utc>>,
|
||||
/// Given for this link, not set by a server: for its site only, port and TLS included.
|
||||
given: Option<Url>,
|
||||
}
|
||||
|
||||
impl Jar {
|
||||
/// Takes a `Cookie` header meant for the site of `url`.
|
||||
pub fn give(&mut self, url: &Url, header: &str) {
|
||||
for (name, value) in header.split(';').filter_map(|pair| pair.split_once('=')) {
|
||||
self.put(Cookie {
|
||||
name: name.trim().into(),
|
||||
value: value.trim().into(),
|
||||
domain: host(url),
|
||||
exact: true,
|
||||
path: "/".into(),
|
||||
secure: false,
|
||||
expires: None,
|
||||
given: Some(url.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the value of a `Set-Cookie` header.
|
||||
pub fn set(&mut self, url: &Url, header: &str, now: DateTime<Utc>) {
|
||||
let mut pieces = header.split(';');
|
||||
let Some((name, value)) = pieces.next().and_then(|p| p.split_once('=')) else { return };
|
||||
let mut cookie = Cookie {
|
||||
name: name.trim().into(),
|
||||
value: value.trim().into(),
|
||||
domain: host(url),
|
||||
exact: true,
|
||||
path: default_path(url),
|
||||
secure: false,
|
||||
expires: None,
|
||||
given: None,
|
||||
};
|
||||
let mut max_age = None;
|
||||
for piece in pieces {
|
||||
let (key, value) = piece.split_once('=').unwrap_or((piece, ""));
|
||||
let value = value.trim();
|
||||
match key.trim().to_ascii_lowercase().as_str() {
|
||||
"domain" => {
|
||||
let domain = value.trim_start_matches('.').to_ascii_lowercase();
|
||||
if domain == cookie.domain && !is_name(url) {
|
||||
continue;
|
||||
}
|
||||
// Not its own domain, or a whole top-level one.
|
||||
if !is_name(url) || !domain.contains('.') || !below(&cookie.domain, &domain) {
|
||||
return;
|
||||
}
|
||||
(cookie.domain, cookie.exact) = (domain, false);
|
||||
}
|
||||
"path" if value.starts_with('/') => cookie.path = value.into(),
|
||||
"secure" => cookie.secure = true,
|
||||
"max-age" => max_age = value.parse::<i64>().ok(),
|
||||
"expires" => cookie.expires = date(value),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(seconds) = max_age {
|
||||
let life = chrono::Duration::try_seconds(seconds).unwrap_or(chrono::Duration::MAX);
|
||||
cookie.expires = now.checked_add_signed(life);
|
||||
}
|
||||
if cookie.secure && url.scheme() != "https" {
|
||||
return;
|
||||
}
|
||||
self.put(cookie);
|
||||
}
|
||||
|
||||
/// The `Cookie` header for `url`.
|
||||
pub fn header(&self, url: &Url, now: DateTime<Utc>) -> Option<HeaderValue> {
|
||||
let name = host(url);
|
||||
let mut fit: Vec<&Cookie> = self
|
||||
.0
|
||||
.iter()
|
||||
.filter(|c| c.domain == name || (!c.exact && below(&name, &c.domain)))
|
||||
.filter(|c| c.given.as_ref().is_none_or(|at| same_site(at, url)))
|
||||
.filter(|c| !c.secure || url.scheme() == "https")
|
||||
.filter(|c| c.expires.is_none_or(|at| at > now) && under(url.path(), &c.path))
|
||||
.collect();
|
||||
fit.sort_by_key(|c| std::cmp::Reverse(c.path.len()));
|
||||
let all: Vec<String> = fit.iter().map(|c| format!("{}={}", c.name, c.value)).collect();
|
||||
let mut value = HeaderValue::try_from(all.join("; ")).ok().filter(|v| !v.is_empty())?;
|
||||
value.set_sensitive(true);
|
||||
Some(value)
|
||||
}
|
||||
|
||||
fn put(&mut self, cookie: Cookie) {
|
||||
self.0.retain(|c| (&c.name, &c.domain, &c.path) != (&cookie.name, &cookie.domain, &cookie.path));
|
||||
if self.0.len() < MOST && !cookie.name.is_empty() {
|
||||
self.0.push(cookie);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn host(url: &Url) -> String {
|
||||
url.host_str().unwrap_or_default().to_ascii_lowercase()
|
||||
}
|
||||
|
||||
fn is_name(url: &Url) -> bool {
|
||||
matches!(url.host(), Some(Host::Domain(_)))
|
||||
}
|
||||
|
||||
fn below(host: &str, domain: &str) -> bool {
|
||||
host == domain || host.strip_suffix(domain).is_some_and(|rest| rest.ends_with('.'))
|
||||
}
|
||||
|
||||
fn under(path: &str, of: &str) -> bool {
|
||||
path.strip_prefix(of).is_some_and(|rest| rest.is_empty() || of.ends_with('/') || rest.starts_with('/'))
|
||||
}
|
||||
|
||||
fn default_path(url: &Url) -> String {
|
||||
match url.path().rfind('/') {
|
||||
None | Some(0) => "/".into(),
|
||||
Some(i) => url.path()[..i].into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Wed, 21 Oct 2015 07:28:00 GMT`, also with dashes.
|
||||
fn date(text: &str) -> Option<DateTime<Utc>> {
|
||||
DateTime::parse_from_rfc2822(&text.replace('-', " ")).ok().map(|t| t.to_utc())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn url(text: &str) -> Url {
|
||||
Url::parse(text).unwrap()
|
||||
}
|
||||
|
||||
fn sent(jar: &Jar, to: &str) -> String {
|
||||
jar.header(&url(to), Utc::now()).map_or(String::new(), |v| v.to_str().unwrap().into())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn given_cookies_stay_with_their_host() {
|
||||
let mut jar = Jar::default();
|
||||
jar.give(&url("https://h.example/f"), "a=1; b=x=y; junk");
|
||||
assert_eq!(sent(&jar, "https://h.example/other?q"), "a=1; b=x=y");
|
||||
for other in ["http://h.example/f", "https://cdn.h.example/f", "https://h.example:444/f", "https://example/f", "https://evilh.example/"] {
|
||||
assert_eq!(sent(&jar, other), "", "{other}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_cookies_keep_their_bounds() {
|
||||
let (mut jar, now) = (Jar::default(), Utc::now());
|
||||
let at = url("https://a.h.example/login/in");
|
||||
for header in [
|
||||
"host=1",
|
||||
"wide=1; Domain=.H.example; Path=/",
|
||||
"deep=1; Path=/files",
|
||||
"tls=1; Path=/; Secure",
|
||||
"other=1; Domain=evil.example; Path=/",
|
||||
"top=1; Domain=example; Path=/",
|
||||
"old=1; Path=/; Max-Age=0",
|
||||
"past=1; Path=/; Expires=Wed, 21-Oct-2015 07:28:00 GMT",
|
||||
"fresh=1; Path=/; Max-Age=100",
|
||||
"fresh=2; Path=/; Max-Age=100",
|
||||
"nothing",
|
||||
] {
|
||||
jar.set(&at, header, now);
|
||||
}
|
||||
assert_eq!(sent(&jar, "https://a.h.example/files/x"), "deep=1; wide=1; tls=1; fresh=2");
|
||||
assert_eq!(sent(&jar, "https://a.h.example/filesx"), "wide=1; tls=1; fresh=2");
|
||||
assert_eq!(sent(&jar, "https://a.h.example/login/x"), "host=1; wide=1; tls=1; fresh=2");
|
||||
assert_eq!(sent(&jar, "http://b.h.example/"), "wide=1");
|
||||
assert_eq!(sent(&jar, "https://example/"), "");
|
||||
assert!(jar.header(&at, now + chrono::Duration::seconds(200)).unwrap().is_sensitive());
|
||||
|
||||
jar.set(&at, "wide=; Domain=h.example; Path=/; Max-Age=-1", now);
|
||||
assert_eq!(sent(&jar, "http://b.h.example/"), "");
|
||||
let ip = url("http://127.0.0.1/");
|
||||
jar.set(&ip, "a=1; Domain=0.0.1", now);
|
||||
assert_eq!(sent(&jar, "http://127.0.0.1/"), "");
|
||||
for i in 0..1000 {
|
||||
jar.set(&ip, &format!("n{i}=1"), now);
|
||||
}
|
||||
assert!(jar.0.len() <= MOST);
|
||||
}
|
||||
}
|
||||
|
|
@ -82,7 +82,7 @@ impl ErrorKind {
|
|||
use ErrorKind::*;
|
||||
use Severity::*;
|
||||
match self {
|
||||
Dns | Unreachable => (Passing, later(5, 300), Fix::CheckNetwork),
|
||||
Dns | Unreachable | Proxy => (Passing, later(5, 300), Fix::CheckNetwork),
|
||||
Refused | Timeout | Cut => (Passing, later(5, 300), Fix::TryAgain),
|
||||
Busy => (Passing, later(30, 600), Fix::TryAgain),
|
||||
Server => (Passing, later(15, 600), Fix::TryAgain),
|
||||
|
|
@ -126,7 +126,7 @@ impl ErrorKind {
|
|||
/// Between this computer and the server: what a network change can cure.
|
||||
pub fn of_network(self) -> bool {
|
||||
use ErrorKind::*;
|
||||
matches!(self, Dns | Refused | Unreachable | Timeout | Cut)
|
||||
matches!(self, Proxy | Dns | Refused | Unreachable | Timeout | Cut)
|
||||
}
|
||||
|
||||
/// Others on the same server would fail the same way.
|
||||
|
|
@ -160,6 +160,14 @@ impl Failure {
|
|||
Failure::with_code(kind, place, 0)
|
||||
}
|
||||
|
||||
/// With another reason than the usual one.
|
||||
fn because(kind: ErrorKind, key: Option<&str>, place: Place) -> Failure {
|
||||
let usual = Failure::new(kind, place);
|
||||
let Some(key) = key else { return usual };
|
||||
let why = strings::text(key, &[("server", &place.server)]);
|
||||
Failure { text: tr!("error.full", what = kind.title(), why = why), ..usual }
|
||||
}
|
||||
|
||||
fn with_code(kind: ErrorKind, place: Place, code: u16) -> Failure {
|
||||
let server = if place.server.is_empty() { tr!("error.no_server") } else { place.server.to_string() };
|
||||
let args: strings::Args = &[("server", &server), ("folder", &place.folder.display()), ("code", &code)];
|
||||
|
|
@ -170,12 +178,18 @@ impl Failure {
|
|||
pub fn of(e: &http::Error, place: Place) -> Failure {
|
||||
use http::Error as E;
|
||||
let kind = match e {
|
||||
E::Status { code: 407, .. } => return Failure::because(ErrorKind::Login, Some("error.login.proxy"), place),
|
||||
E::Status { code, retry_after } => {
|
||||
let failure = Failure::with_code(of_status(*code, place.begun), place, *code);
|
||||
return Failure { retry_after: *retry_after, ..failure };
|
||||
}
|
||||
E::Link => ErrorKind::BadLink,
|
||||
E::Net(e) if tls_error(e).is_some() => return Failure::because(ErrorKind::Tls, tls_why(tls_error(e)), place),
|
||||
E::Net(e) => of_net(e),
|
||||
E::Tls(_) => ErrorKind::Tls,
|
||||
E::Proxy(None) => return Failure::because(ErrorKind::Proxy, Some("error.proxy.setting"), place),
|
||||
E::Proxy(Some(e)) if proxy_login(e) => return Failure::because(ErrorKind::Login, Some("error.login.proxy"), place),
|
||||
E::Proxy(Some(_)) => ErrorKind::Proxy,
|
||||
E::Changed => ErrorKind::Changed,
|
||||
E::Page => ErrorKind::WrongContent,
|
||||
E::RangeIgnored | E::NoResume => ErrorKind::NoResume,
|
||||
|
|
@ -210,15 +224,47 @@ fn of_status(code: u16, begun: bool) -> ErrorKind {
|
|||
}
|
||||
}
|
||||
|
||||
/// What went wrong with TLS, if that is it.
|
||||
pub(crate) fn tls_error(e: &reqwest::Error) -> Option<&rustls::Error> {
|
||||
causes(e).find_map(|e| e.downcast_ref())
|
||||
}
|
||||
|
||||
/// The plain reason a certificate was refused.
|
||||
fn tls_why(e: Option<&rustls::Error>) -> Option<&'static str> {
|
||||
use rustls::CertificateError::*;
|
||||
let Some(rustls::Error::InvalidCertificate(e)) = e else { return None };
|
||||
Some(match e {
|
||||
Expired | ExpiredContext { .. } => "error.tls.expired",
|
||||
NotValidYet | NotValidYetContext { .. } => "error.tls.not_yet",
|
||||
UnknownIssuer => "error.tls.unknown",
|
||||
NotValidForName | NotValidForNameContext { .. } => "error.tls.name",
|
||||
Revoked => "error.tls.revoked",
|
||||
// Self-signed ones, mostly.
|
||||
Other(e) if e.to_string().contains("CaUsedAsEndEntity") => "error.tls.unknown",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// hyper's types for it are private.
|
||||
fn proxy_login(e: &reqwest::Error) -> bool {
|
||||
let known = ["proxy authorization required", "credentials not accepted", "does not support user/pass", "implements authentication incorrectly"];
|
||||
causes(e).any(|e| known.iter().any(|k| e.to_string().contains(k)))
|
||||
}
|
||||
|
||||
/// The error and all that led to it.
|
||||
fn causes(e: &reqwest::Error) -> impl Iterator<Item = &(dyn std::error::Error + 'static)> {
|
||||
std::iter::successors(Some(e as &(dyn std::error::Error + 'static)), |e| {
|
||||
// An io::Error's source skips what it wraps.
|
||||
let wrapped = e.downcast_ref::<io::Error>().and_then(|e| e.get_ref());
|
||||
wrapped.map(|e| e as &(dyn std::error::Error + 'static)).or_else(|| e.source())
|
||||
})
|
||||
}
|
||||
|
||||
fn of_net(e: &reqwest::Error) -> ErrorKind {
|
||||
if e.is_redirect() || e.is_builder() {
|
||||
return ErrorKind::BadLink;
|
||||
}
|
||||
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(e);
|
||||
while let Some(e) = source {
|
||||
if e.is::<rustls::Error>() {
|
||||
return ErrorKind::Tls;
|
||||
}
|
||||
for e in causes(e) {
|
||||
if let Some(io) = e.downcast_ref::<io::Error>() {
|
||||
match io.kind() {
|
||||
io::ErrorKind::ConnectionRefused => return ErrorKind::Refused,
|
||||
|
|
@ -231,9 +277,6 @@ fn of_net(e: &reqwest::Error) -> ErrorKind {
|
|||
if e.to_string().starts_with("dns error") {
|
||||
return ErrorKind::Dns;
|
||||
}
|
||||
// An io::Error's source skips what it wraps.
|
||||
let wrapped = e.downcast_ref::<io::Error>().and_then(|e| e.get_ref());
|
||||
source = wrapped.map(|e| e as &(dyn std::error::Error + 'static)).or_else(|| e.source());
|
||||
}
|
||||
if e.is_timeout() { ErrorKind::Timeout } else { ErrorKind::Cut }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -104,7 +104,7 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt
|
|||
let host = host::key(&link.source.url);
|
||||
let asked = host.clone();
|
||||
let known = job.run(move |s| Ok(s.host(&asked)?)).await?.unwrap_or_default();
|
||||
shared.hosts.set_host_cap(&host, known.max_connections);
|
||||
shared.hosts.set_host_cap(&host, link.source.max_connections().or(known.max_connections));
|
||||
let start = host::tolerated(&known, model::now()).unwrap_or(adapt::START);
|
||||
let mut run = Run::new(shared, link, file.clone(), parts, body, host.clone(), start, task.max_parts, options, monitor);
|
||||
let result = run.go(&job, &mut stop).await;
|
||||
|
|
|
|||
|
|
@ -15,11 +15,13 @@ pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot};
|
|||
pub use name::safe as safe_name;
|
||||
pub use probe::{Probe, probe};
|
||||
|
||||
use crate::{disk, store};
|
||||
use crate::site::{Access, same_site};
|
||||
use crate::tls::Trust;
|
||||
use crate::{disk, redact, store};
|
||||
use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue};
|
||||
pub(crate) use reqwest::{Client, Response};
|
||||
use reqwest::{Certificate, StatusCode, redirect};
|
||||
use std::sync::Once;
|
||||
use reqwest::{RequestBuilder, StatusCode, redirect};
|
||||
use std::sync::{Arc, Once};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::watch;
|
||||
use url::Url;
|
||||
|
|
@ -33,6 +35,10 @@ pub enum Error {
|
|||
Link,
|
||||
/// No connection, no answer in time, or a broken one. Never holds the link.
|
||||
Net(reqwest::Error),
|
||||
/// The proxy can't be reached or refuses. None: its setting makes no sense.
|
||||
Proxy(Option<reqwest::Error>),
|
||||
/// TLS can't be set up here.
|
||||
Tls(rustls::Error),
|
||||
Status { code: u16, retry_after: Option<Duration> },
|
||||
/// The file on the server is not the one the parts came from.
|
||||
Changed,
|
||||
|
|
@ -56,6 +62,12 @@ pub enum Error {
|
|||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
impl From<rustls::Error> for Error {
|
||||
fn from(e: rustls::Error) -> Error {
|
||||
Error::Tls(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<disk::Error> for Error {
|
||||
fn from(e: disk::Error) -> Error {
|
||||
Error::Disk(e)
|
||||
|
|
@ -93,23 +105,33 @@ impl Default for ClientOptions {
|
|||
}
|
||||
|
||||
pub fn client(options: &ClientOptions) -> Result<Client> {
|
||||
client_with(options, &trust(options)?, None)
|
||||
}
|
||||
|
||||
/// Reads the system's certificates.
|
||||
pub(crate) fn trust(options: &ClientOptions) -> Result<Arc<Trust>> {
|
||||
Ok(Arc::new(Trust::new(Arc::new(rustls::crypto::ring::default_provider()), &options.only_certs)?))
|
||||
}
|
||||
|
||||
pub(crate) fn client_with(options: &ClientOptions, trust: &Arc<Trust>, proxy: Option<Url>) -> Result<Client> {
|
||||
static TLS: Once = Once::new();
|
||||
// Fails only when one is installed already, which is fine.
|
||||
TLS.call_once(|| drop(rustls::crypto::ring::default_provider().install_default()));
|
||||
let mut builder = Client::builder()
|
||||
.user_agent(concat!("Medlar/", env!("CARGO_PKG_VERSION")))
|
||||
.http1_only()
|
||||
.redirect(redirect::Policy::limited(10))
|
||||
// Each hop has its own headers and its own way.
|
||||
.redirect(redirect::Policy::none())
|
||||
.referer(false)
|
||||
.retry(reqwest::retry::never())
|
||||
.no_proxy()
|
||||
// Reused at once or not at all: idle ones count against what a host stands.
|
||||
.pool_idle_timeout(Duration::from_millis(500))
|
||||
.connect_timeout(options.connect_timeout)
|
||||
.read_timeout(options.idle_timeout);
|
||||
if !options.only_certs.is_empty() {
|
||||
let certs = options.only_certs.iter().map(|der| Certificate::from_der(der)).collect::<reqwest::Result<Vec<_>>>()?;
|
||||
builder = builder.tls_certs_only(certs);
|
||||
.read_timeout(options.idle_timeout)
|
||||
.tls_backend_preconfigured(trust.config(Arc::new(rustls::crypto::ring::default_provider()))?);
|
||||
if let Some(proxy) = proxy {
|
||||
builder = builder.proxy(reqwest::Proxy::all(proxy)?);
|
||||
}
|
||||
Ok(builder.build()?)
|
||||
}
|
||||
|
|
@ -119,56 +141,104 @@ pub fn client(options: &ClientOptions) -> Result<Client> {
|
|||
pub struct Source {
|
||||
pub url: Url,
|
||||
pub headers: HeaderMap,
|
||||
access: Option<Arc<Access>>,
|
||||
}
|
||||
|
||||
/// Redirects followed.
|
||||
const HOPS: usize = 10;
|
||||
|
||||
impl Source {
|
||||
pub fn new(url: &str) -> Result<Source> {
|
||||
let url = Url::parse(url).map_err(|_| Error::Link)?;
|
||||
if !matches!(url.scheme(), "http" | "https") || !url.has_host() {
|
||||
return Err(Error::Link);
|
||||
}
|
||||
Ok(Source { url, headers: HeaderMap::new() })
|
||||
Ok(Source { url, headers: HeaderMap::new(), access: None })
|
||||
}
|
||||
|
||||
/// Adds headers, skipping what isn't valid and what the engine sets itself.
|
||||
pub fn with_headers(mut self, headers: &[(String, String)]) -> Source {
|
||||
for (name, value) in headers {
|
||||
let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::try_from(value)) else { continue };
|
||||
if !matches!(name, header::RANGE | header::IF_RANGE | header::ACCEPT_ENCODING | header::HOST | header::CONNECTION) {
|
||||
self.headers.append(name, value);
|
||||
}
|
||||
for (name, value) in valid(headers) {
|
||||
self.headers.append(name, value);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The same source at the link its redirects led to. Secrets stay with the site they were given for.
|
||||
pub(crate) fn with_access(self, access: Access) -> Source {
|
||||
Source { access: Some(Arc::new(access)), ..self }
|
||||
}
|
||||
|
||||
/// The user's cap on connections to this site.
|
||||
pub(crate) fn max_connections(&self) -> Option<u32> {
|
||||
self.access.as_ref()?.rules(&self.url).max_connections
|
||||
}
|
||||
|
||||
/// The same source at the link its redirects led to. What was given for one site stays with it.
|
||||
pub fn at(&self, url: &Url) -> Source {
|
||||
let mut headers = self.headers.clone();
|
||||
if url.origin() != self.url.origin() {
|
||||
for name in [header::COOKIE, header::AUTHORIZATION, header::PROXY_AUTHORIZATION] {
|
||||
headers.remove(name);
|
||||
}
|
||||
if !same_site(&self.url, url) {
|
||||
let harmless = [header::USER_AGENT, header::ACCEPT, header::ACCEPT_LANGUAGE, header::REFERER];
|
||||
headers = headers.into_iter().filter_map(|(name, value)| Some((name.filter(|n| harmless.contains(n))?, value))).collect();
|
||||
}
|
||||
Source { url: url.clone(), headers }
|
||||
Source { url: url.clone(), headers, access: self.access.clone() }
|
||||
}
|
||||
|
||||
async fn get(&self, client: &Client, range: Option<String>, if_range: Option<&HeaderValue>, stop: &mut Stop) -> Result<Response> {
|
||||
let mut request = client.get(self.url.clone()).headers(self.headers.clone()).header(header::ACCEPT_ENCODING, "identity");
|
||||
if let Some(range) = range {
|
||||
request = request.header(header::RANGE, range);
|
||||
if let Some(validator) = if_range {
|
||||
request = request.header(header::IF_RANGE, validator);
|
||||
}
|
||||
}
|
||||
tokio::select! {
|
||||
_ = stopped(stop) => Err(Error::Stopped),
|
||||
response = request.send() => Ok(response?),
|
||||
response = self.follow(client, range.as_deref(), if_range) => response,
|
||||
}
|
||||
}
|
||||
|
||||
async fn follow(&self, client: &Client, range: Option<&str>, if_range: Option<&HeaderValue>) -> Result<Response> {
|
||||
let mut here = self.clone();
|
||||
for _ in 0..=HOPS {
|
||||
let request = |client: &Client, headers: &HeaderMap| -> RequestBuilder {
|
||||
let mut request = client.get(here.url.clone()).headers(headers.clone()).header(header::ACCEPT_ENCODING, "identity");
|
||||
if let Some(range) = range {
|
||||
request = request.header(header::RANGE, range);
|
||||
if let Some(validator) = if_range {
|
||||
request = request.header(header::IF_RANGE, validator);
|
||||
}
|
||||
}
|
||||
request
|
||||
};
|
||||
let response = match &here.access {
|
||||
Some(access) => access.send(&here.url, &here.headers, request).await?,
|
||||
None => request(client, &here.headers).send().await?,
|
||||
};
|
||||
match redirect(&response)? {
|
||||
Some(next) => here = here.at(&next),
|
||||
None => return Ok(response),
|
||||
}
|
||||
}
|
||||
Err(Error::Link)
|
||||
}
|
||||
}
|
||||
|
||||
/// Headers without those that aren't valid and those the engine sets itself.
|
||||
pub(crate) fn valid(headers: &[(String, String)]) -> impl Iterator<Item = (HeaderName, HeaderValue)> {
|
||||
headers.iter().filter_map(|(name, value)| {
|
||||
let (name, mut value) = (HeaderName::try_from(name).ok()?, HeaderValue::try_from(value).ok()?);
|
||||
value.set_sensitive(redact::is_secret_header(name.as_str()));
|
||||
let own = [header::RANGE, header::IF_RANGE, header::ACCEPT_ENCODING, header::HOST, header::CONNECTION, header::PROXY_AUTHORIZATION];
|
||||
(!own.contains(&name)).then_some((name, value))
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the server sends us, if it does.
|
||||
fn redirect(response: &Response) -> Result<Option<Url>> {
|
||||
let moved = matches!(response.status().as_u16(), 301 | 302 | 303 | 307 | 308);
|
||||
let Some(to) = response.headers().get(header::LOCATION).filter(|_| moved) else { return Ok(None) };
|
||||
let to = std::str::from_utf8(to.as_bytes()).ok().and_then(|to| response.url().join(to).ok());
|
||||
let mut url = to.filter(|u| matches!(u.scheme(), "http" | "https") && u.has_host()).ok_or(Error::Link)?;
|
||||
// A login in there is not the user's.
|
||||
let _ = (url.set_username(""), url.set_password(None));
|
||||
Ok(Some(url))
|
||||
}
|
||||
|
||||
/// Resolves when asked to stop, never when nobody can ask any more.
|
||||
async fn stopped(stop: &mut Stop) {
|
||||
pub(crate) async fn stopped(stop: &mut Stop) {
|
||||
if stop.wait_for(|s| *s).await.is_err() {
|
||||
std::future::pending().await
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,6 +97,7 @@ fn weigh(e: &Error) -> Weight {
|
|||
Error::Status { code: 408 | 425 | 500..=599, .. } | Error::Cut { .. } => Weight::Broken,
|
||||
Error::Status { .. } | Error::RangeIgnored => Weight::Refused { again: false },
|
||||
Error::Net(e) if e.is_redirect() || e.is_builder() => Weight::Fatal,
|
||||
Error::Proxy(Some(_)) => Weight::Broken,
|
||||
Error::Net(e) if e.is_connect() => Weight::Refused { again: true },
|
||||
Error::Net(_) => Weight::Broken,
|
||||
_ => Weight::Fatal,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@
|
|||
|
||||
pub mod adapt;
|
||||
pub mod adopt;
|
||||
pub mod auth;
|
||||
pub mod cookie;
|
||||
pub mod disk;
|
||||
pub mod error;
|
||||
pub mod events;
|
||||
|
|
@ -13,14 +15,18 @@ pub mod model;
|
|||
pub mod net_state;
|
||||
pub mod part;
|
||||
pub mod paths;
|
||||
pub mod proxy;
|
||||
pub mod recover;
|
||||
pub mod redact;
|
||||
pub mod relink;
|
||||
pub mod secret;
|
||||
pub mod segment;
|
||||
pub mod settings;
|
||||
pub mod site;
|
||||
pub mod snapshot;
|
||||
pub mod speed;
|
||||
pub mod store;
|
||||
pub mod strings;
|
||||
pub mod tls;
|
||||
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ use crate::settings::Limits;
|
|||
use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals};
|
||||
use crate::speed::{History, Meter};
|
||||
use crate::store::{self, Store};
|
||||
use crate::{adopt, disk, host, redact, strings, tr};
|
||||
use crate::{adopt, disk, host, redact, site, strings, tr};
|
||||
use arc_swap::ArcSwap;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
|
@ -645,22 +645,26 @@ impl Actor {
|
|||
let _ = answer.send(Err(store::Error::NotFound.into()));
|
||||
return;
|
||||
};
|
||||
let (task, shared) = (e.task.clone(), self.config.shared.clone());
|
||||
let (task, shared, sites) = (e.task.clone(), self.config.shared.clone(), self.config.sites.clone());
|
||||
self.look(answer, host_of(&link.url), async move {
|
||||
let (_keep, mut stop) = watch::channel(false);
|
||||
let store = shared.store.clone();
|
||||
let parts = disk::blocking(move || store.parts(id)).await?;
|
||||
let source = Source::new(&link.url)?.with_headers(&link.headers);
|
||||
let mut with = (*task).clone();
|
||||
link.put_in(&mut with);
|
||||
let source = site::source(sites.as_ref(), &with, &stop).await?;
|
||||
relink::check(&shared.client, &task, &parts, link, source, &mut stop).await
|
||||
});
|
||||
}
|
||||
|
||||
fn check_partial(&self, path: PathBuf, link: NewLink, answer: oneshot::Sender<Result<Found>>) {
|
||||
let shared = self.config.shared.clone();
|
||||
let (shared, sites) = (self.config.shared.clone(), self.config.sites.clone());
|
||||
self.look(answer, host_of(&link.url), async move {
|
||||
let (_keep, mut stop) = watch::channel(false);
|
||||
let partial = disk::blocking(move || adopt::look(&path)).await.map_err(disk::Error::Io)?;
|
||||
let source = Source::new(&link.url)?.with_headers(&link.headers);
|
||||
let mut task = Task::default();
|
||||
link.put_in(&mut task);
|
||||
let source = site::source(sites.as_ref(), &task, &stop).await?;
|
||||
adopt::check(&shared.client, partial, link, source, &mut stop).await
|
||||
});
|
||||
}
|
||||
|
|
@ -921,16 +925,19 @@ impl Actor {
|
|||
return;
|
||||
}
|
||||
let task = self.entries[&id].task.clone();
|
||||
let source = match Source::new(&task.url) {
|
||||
Ok(source) => source.with_headers(&task.headers),
|
||||
Err(e) => return self.failed(id, &Why::Http(e)),
|
||||
};
|
||||
if let Err(e) = Source::new(&task.url) {
|
||||
return self.failed(id, &Why::Http(e));
|
||||
}
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
let monitor = Arc::new(Monitor::new(unlimited(self.config.limits.parts_per_download)));
|
||||
let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false, had: self.entries[&id].downloaded };
|
||||
let (shared, options, to) = (self.config.shared.clone(), self.config.options.clone(), self.to.clone());
|
||||
let sites = self.config.sites.clone();
|
||||
self.runtime().spawn(async move {
|
||||
let work = tokio::spawn(async move { download(&shared, id, source, &options, &monitor, stopped).await });
|
||||
let work = tokio::spawn(async move {
|
||||
let source = site::source(sites.as_ref(), &task, &stopped).await?;
|
||||
download(&shared, id, source, &options, &monitor, stopped).await
|
||||
});
|
||||
let result = match work.await {
|
||||
Ok(result) => result.map_err(Why::Http),
|
||||
Err(_) => Err(Why::Panic),
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ use crate::recover::Recovery;
|
|||
use crate::recover::sleep::Sleep;
|
||||
use crate::relink::{Checked, NewLink};
|
||||
use crate::settings::Limits;
|
||||
use crate::site::Sites;
|
||||
use crate::snapshot::Snapshot;
|
||||
use crate::{store, tr};
|
||||
use arc_swap::ArcSwap;
|
||||
|
|
@ -166,6 +167,8 @@ impl<T> Future for Reply<T> {
|
|||
|
||||
pub struct Config {
|
||||
pub shared: Shared,
|
||||
/// Logins, proxies and rules per site. None: plain requests only (tests).
|
||||
pub sites: Option<Arc<Sites>>,
|
||||
pub options: Options,
|
||||
pub limits: Limits,
|
||||
pub bin: Bin,
|
||||
|
|
@ -180,6 +183,7 @@ impl Config {
|
|||
pub fn new(shared: Shared, limits: Limits) -> Config {
|
||||
Config {
|
||||
shared,
|
||||
sites: None,
|
||||
options: Options::default(),
|
||||
limits,
|
||||
bin: Bin::default(),
|
||||
|
|
|
|||
|
|
@ -97,6 +97,7 @@ named_enum!(
|
|||
ErrorKind {
|
||||
Dns = "dns",
|
||||
Tls = "tls",
|
||||
Proxy = "proxy",
|
||||
Refused = "refused",
|
||||
Unreachable = "unreachable",
|
||||
Timeout = "timeout",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ pub enum Bus {
|
|||
Off,
|
||||
/// The one of the system.
|
||||
System,
|
||||
/// The one of the user.
|
||||
Session,
|
||||
/// A fake one (tests).
|
||||
At(String),
|
||||
}
|
||||
|
|
@ -20,6 +22,7 @@ impl Bus {
|
|||
match self {
|
||||
Bus::Off => Ok(None),
|
||||
Bus::System => zbus::Connection::system().await.map(Some),
|
||||
Bus::Session => zbus::Connection::session().await.map(Some),
|
||||
Bus::At(address) => zbus::connection::Builder::address(address.as_str())?.build().await.map(Some),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
158
crates/core/src/proxy.rs
Normal file
158
crates/core/src/proxy.rs
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
//! Which way to a server: straight, or through a proxy.
|
||||
|
||||
use crate::auth::Login;
|
||||
use crate::net_state::Bus;
|
||||
use crate::site::Pattern;
|
||||
use std::net::IpAddr;
|
||||
use std::time::Duration;
|
||||
use url::{Host, Url};
|
||||
|
||||
/// A proxy setting: `system`, `direct`, or the proxy as `http://host:port`, `https://…` or `socks5://…`, without a login.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Choice {
|
||||
System,
|
||||
Direct,
|
||||
At(Url),
|
||||
}
|
||||
|
||||
impl Choice {
|
||||
pub fn parse(text: &str) -> Option<Choice> {
|
||||
match text.trim() {
|
||||
"system" => Some(Choice::System),
|
||||
"direct" => Some(Choice::Direct),
|
||||
text => address(text).map(Choice::At),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Names are looked up by the proxy, never here, so they don't leak.
|
||||
fn address(text: &str) -> Option<Url> {
|
||||
let text = text.replacen("socks://", "socks5://", 1).replacen("socks5://", "socks5h://", 1);
|
||||
let url = Url::parse(&text).ok()?;
|
||||
let known = matches!(url.scheme(), "http" | "https" | "socks5h");
|
||||
(known && url.has_host() && url.username().is_empty() && url.password().is_none()).then_some(url)
|
||||
}
|
||||
|
||||
/// Keyring item with the login of a proxy.
|
||||
pub fn secret_name(proxy: &Url) -> String {
|
||||
let port = proxy.port_or_known_default().unwrap_or(1080);
|
||||
format!("proxy:{}://{}:{port}", proxy.scheme().trim_end_matches('h'), proxy.host_str().unwrap_or_default())
|
||||
}
|
||||
|
||||
pub(crate) fn with_login(mut proxy: Url, login: &Login) -> Url {
|
||||
// Fails only without a host, which it has.
|
||||
let _ = proxy.set_username(&login.user);
|
||||
let _ = proxy.set_password(Some(&login.password));
|
||||
proxy
|
||||
}
|
||||
|
||||
/// Hosts that the proxy of the app is not used for: site patterns, and networks such as `192.168.0.0/16`.
|
||||
pub fn bypassed<S: AsRef<str>>(list: &[S], url: &Url) -> bool {
|
||||
list.iter().any(|entry| {
|
||||
let entry = entry.as_ref().trim();
|
||||
match entry.split_once('/') {
|
||||
Some((net, bits)) => in_network(url, net, bits),
|
||||
None => !entry.is_empty() && Pattern::new(entry).fits(url),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn in_network(url: &Url, net: &str, bits: &str) -> bool {
|
||||
let ip = match url.host() {
|
||||
Some(Host::Ipv4(ip)) => IpAddr::V4(ip),
|
||||
Some(Host::Ipv6(ip)) => IpAddr::V6(ip),
|
||||
_ => return false,
|
||||
};
|
||||
let (Ok(net), Ok(bits)) = (net.parse::<IpAddr>(), bits.parse::<u32>()) else { return false };
|
||||
match (ip, net) {
|
||||
(IpAddr::V4(a), IpAddr::V4(b)) if bits <= 32 => (a.to_bits() ^ b.to_bits()).checked_shr(32 - bits).unwrap_or(0) == 0,
|
||||
(IpAddr::V6(a), IpAddr::V6(b)) if bits <= 128 => (a.to_bits() ^ b.to_bits()).checked_shr(128 - bits).unwrap_or(0) == 0,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The proxy named by the environment. None when it names none at all, `Some(None)` for straight.
|
||||
pub fn from_env(url: &Url, env: impl Fn(&str) -> Option<String>) -> Option<Option<Url>> {
|
||||
let get = |name: &str| env(name).or_else(|| env(&name.to_uppercase())).filter(|v| !v.trim().is_empty());
|
||||
// Not HTTP_PROXY, which a web server may set from a request.
|
||||
let own = if url.scheme() == "https" { get("https_proxy") } else { env("http_proxy").filter(|v| !v.is_empty()) };
|
||||
let text = own.or_else(|| get("all_proxy"))?;
|
||||
let list = get("no_proxy").unwrap_or_default();
|
||||
let list: Vec<String> = list.split([',', ' ']).filter(|e| !e.is_empty()).map(below).collect();
|
||||
if bypassed(&list, url) {
|
||||
return Some(None);
|
||||
}
|
||||
let text = if text.contains("://") { text } else { format!("http://{text}") };
|
||||
// A login here is the user's own doing; it stays in memory.
|
||||
let (text, login) = crate::auth::take_login(&text);
|
||||
address(&text).map(|proxy| Some(login.map_or(proxy.clone(), |l| with_login(proxy, &l))))
|
||||
}
|
||||
|
||||
/// `no_proxy` names a host and everything below it.
|
||||
fn below(entry: &str) -> String {
|
||||
let name = entry.trim_start_matches("*.").trim_start_matches('.');
|
||||
if name == "*" || name.contains('/') || name.parse::<IpAddr>().is_ok() { name.into() } else { format!("*.{name}") }
|
||||
}
|
||||
|
||||
/// The proxy of the desktop, from its portal. Hears the server's name only. None for straight.
|
||||
pub(crate) async fn from_desktop(bus: &Bus, url: &Url) -> Option<Url> {
|
||||
let asked = format!("{}/", url.origin().ascii_serialization());
|
||||
let ask = async {
|
||||
let bus = bus.connect().await.ok()??;
|
||||
let path = "/org/freedesktop/portal/desktop";
|
||||
let (name, interface) = ("org.freedesktop.portal.Desktop", "org.freedesktop.portal.ProxyResolver");
|
||||
let reply = bus.call_method(Some(name), path, Some(interface), "Lookup", &(asked,)).await.ok()?;
|
||||
reply.body().deserialize::<Vec<String>>().ok()
|
||||
};
|
||||
let found = tokio::time::timeout(Duration::from_secs(2), ask).await.ok()??;
|
||||
address(found.first()?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn url(text: &str) -> Url {
|
||||
Url::parse(text).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choices() {
|
||||
assert_eq!(Choice::parse("system"), Some(Choice::System));
|
||||
assert_eq!(Choice::parse(" direct "), Some(Choice::Direct));
|
||||
assert_eq!(Choice::parse("http://p:3128"), Some(Choice::At(url("http://p:3128"))));
|
||||
assert_eq!(Choice::parse("socks5://p:1080"), Some(Choice::At(url("socks5h://p:1080"))));
|
||||
for bad in ["", "p:3128", "ftp://p", "http://", "http://me:x@p", "socks4://p", "junk"] {
|
||||
assert_eq!(Choice::parse(bad), None, "{bad}");
|
||||
}
|
||||
assert_eq!(secret_name(&url("socks5h://p:1080")), "proxy:socks5://p:1080");
|
||||
assert_eq!(secret_name(&url("http://p")), "proxy:http://p:80");
|
||||
assert_eq!(with_login(url("http://p:1"), &Login { user: "a@b".into(), password: "c:d".into() }).as_str(), "http://a%40b:c%3Ad@p:1/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bypass_lists() {
|
||||
let list = ["localhost", "127.0.0.0/8", "::1", "*.corp.example", "fd00::/8", "10.1.2.3", ""];
|
||||
for yes in ["http://localhost:8/", "http://127.9.9.9/", "http://[::1]/", "https://a.corp.example/", "http://[fd12::1]/", "http://10.1.2.3/"] {
|
||||
assert!(bypassed(&list, &url(yes)), "{yes}");
|
||||
}
|
||||
for no in ["http://128.0.0.1/", "http://example/", "http://corp.example.org/", "http://[fe00::1]/", "http://10.1.2.4/"] {
|
||||
assert!(!bypassed(&list, &url(no)), "{no}");
|
||||
}
|
||||
assert!(bypassed(&["0.0.0.0/0"], &url("http://9.9.9.9/")));
|
||||
assert!(!bypassed(&["1.2.3.4/x", "1.2.3.4/99"], &url("http://1.2.3.4/")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment() {
|
||||
let env = |pairs: &'static [(&str, &str)]| move |name: &str| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| v.to_string());
|
||||
let set = env(&[("https_proxy", "p:8080"), ("ALL_PROXY", "socks5://s:1"), ("no_proxy", ".in.example, 10.0.0.0/8")]);
|
||||
assert_eq!(from_env(&url("https://x/"), set), Some(Some(url("http://p:8080"))));
|
||||
assert_eq!(from_env(&url("http://x/"), set), Some(Some(url("socks5h://s:1"))));
|
||||
assert_eq!(from_env(&url("https://a.in.example/"), set), Some(None));
|
||||
assert_eq!(from_env(&url("https://10.2.3.4/"), set), Some(None));
|
||||
assert_eq!(from_env(&url("https://x/"), env(&[])), None);
|
||||
assert_eq!(from_env(&url("http://x/"), env(&[("HTTP_PROXY", "p:1")])), None);
|
||||
assert_eq!(from_env(&url("http://x/"), env(&[("http_proxy", "http://u:p@h:1")])), Some(Some(url("http://u:p@h:1"))));
|
||||
}
|
||||
}
|
||||
206
crates/core/src/secret.rs
Normal file
206
crates/core/src/secret.rs
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
//! Logins and cookies, in the desktop's keyring (Secret Service) or else in memory only.
|
||||
|
||||
use crate::auth::Login;
|
||||
use crate::net_state::Bus;
|
||||
use crate::tr;
|
||||
use futures_lite::StreamExt;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
|
||||
use zbus::{Connection, Proxy};
|
||||
|
||||
/// For the keyring to answer, and for the user to unlock it.
|
||||
const ANSWER: Duration = Duration::from_secs(10);
|
||||
const UNLOCK: Duration = Duration::from_secs(120);
|
||||
|
||||
/// Everything secret about a site, a download or a proxy.
|
||||
#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Secret {
|
||||
/// The link it was given for, for a download's own secret: without it, or at another site, it is not used.
|
||||
pub home: Option<String>,
|
||||
pub login: Option<Login>,
|
||||
/// As in a `Cookie` header.
|
||||
pub cookies: Option<String>,
|
||||
/// Headers that carry secrets.
|
||||
pub headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Secret {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("Secret([hidden])")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kept {
|
||||
Keyring,
|
||||
/// Until Medlar closes. Say so with `words`.
|
||||
Memory,
|
||||
}
|
||||
|
||||
impl Kept {
|
||||
pub fn words(self) -> Option<String> {
|
||||
(self == Kept::Memory).then(|| tr!("secret.memory"))
|
||||
}
|
||||
}
|
||||
|
||||
/// All secrets, by the name that sites and tasks have in their `secret` field.
|
||||
pub struct Secrets {
|
||||
bus: Bus,
|
||||
memory: Mutex<HashMap<String, Secret>>,
|
||||
}
|
||||
|
||||
impl Secrets {
|
||||
/// `Bus::Off` keeps everything in memory.
|
||||
pub fn new(bus: Bus) -> Secrets {
|
||||
Secrets { bus, memory: Mutex::default() }
|
||||
}
|
||||
|
||||
/// A new one replaces the old one. `label` is what the user sees in the keyring's own window: the host, no secret.
|
||||
pub async fn save(&self, name: &str, label: &str, secret: &Secret) -> Kept {
|
||||
match self.keyring_save(name, label, secret).await {
|
||||
Ok(true) => {
|
||||
self.memory.lock().unwrap().remove(name);
|
||||
return Kept::Keyring;
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(e) => log::warn!("not saved in the keyring: {e}"),
|
||||
}
|
||||
self.memory.lock().unwrap().insert(name.into(), secret.clone());
|
||||
Kept::Memory
|
||||
}
|
||||
|
||||
/// None also when the keyring doesn't answer or stays locked.
|
||||
pub async fn load(&self, name: &str) -> Option<Secret> {
|
||||
if let Some(secret) = self.memory.lock().unwrap().get(name) {
|
||||
return Some(secret.clone());
|
||||
}
|
||||
self.keyring_load(name).await.unwrap_or_else(|e| {
|
||||
log::warn!("not read from the keyring: {e}");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn remove(&self, name: &str) {
|
||||
self.memory.lock().unwrap().remove(name);
|
||||
if let Err(e) = self.keyring_remove(name).await {
|
||||
log::warn!("not removed from the keyring: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn keyring_save(&self, name: &str, label: &str, secret: &Secret) -> zbus::Result<bool> {
|
||||
let Some(ring) = Keyring::open(&self.bus).await? else { return Ok(false) };
|
||||
let collection: OwnedObjectPath = quick(ring.service.call("ReadAlias", &("default",))).await?;
|
||||
if collection.as_str() == "/" || !ring.unlock(&collection).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
let label = tr!("secret.label", host = label);
|
||||
let properties = HashMap::from([
|
||||
("org.freedesktop.Secret.Item.Label", Value::from(label)),
|
||||
("org.freedesktop.Secret.Item.Attributes", Value::from(attributes(name))),
|
||||
]);
|
||||
let bytes = serde_json::to_vec(secret).expect("strings only");
|
||||
let packed = (&ring.session, Vec::<u8>::new(), bytes, "application/json");
|
||||
let proxy = ring.proxy(collection, "org.freedesktop.Secret.Collection").await?;
|
||||
let (item, prompt): (OwnedObjectPath, OwnedObjectPath) = quick(proxy.call("CreateItem", &(properties, packed, true))).await?;
|
||||
Ok(item.as_str() != "/" || ring.prompt(prompt).await?)
|
||||
}
|
||||
|
||||
async fn keyring_load(&self, name: &str) -> zbus::Result<Option<Secret>> {
|
||||
let Some(ring) = Keyring::open(&self.bus).await? else { return Ok(None) };
|
||||
let Some(item) = ring.find(name).await? else { return Ok(None) };
|
||||
let proxy = ring.proxy(item, "org.freedesktop.Secret.Item").await?;
|
||||
let (_, _, bytes, _): Packed = quick(proxy.call("GetSecret", &(&ring.session,))).await?;
|
||||
Ok(serde_json::from_slice(&bytes).ok())
|
||||
}
|
||||
|
||||
async fn keyring_remove(&self, name: &str) -> zbus::Result<()> {
|
||||
let Some(ring) = Keyring::open(&self.bus).await? else { return Ok(()) };
|
||||
let Some(item) = ring.find(name).await? else { return Ok(()) };
|
||||
let proxy = ring.proxy(item, "org.freedesktop.Secret.Item").await?;
|
||||
let prompt: OwnedObjectPath = quick(proxy.call("Delete", &())).await?;
|
||||
ring.prompt(prompt).await.map(drop)
|
||||
}
|
||||
}
|
||||
|
||||
/// Session, parameters, value, content type.
|
||||
type Packed = (OwnedObjectPath, Vec<u8>, Vec<u8>, String);
|
||||
|
||||
fn attributes(name: &str) -> HashMap<String, String> {
|
||||
HashMap::from([("application".into(), "medlar".into()), ("name".into(), name.into())])
|
||||
}
|
||||
|
||||
async fn quick<T>(call: impl Future<Output = zbus::Result<T>>) -> zbus::Result<T> {
|
||||
tokio::time::timeout(ANSWER, call).await.unwrap_or_else(|_| Err(late()))
|
||||
}
|
||||
|
||||
fn late() -> zbus::Error {
|
||||
zbus::Error::Failure("no answer in time".into())
|
||||
}
|
||||
|
||||
struct Keyring {
|
||||
bus: Connection,
|
||||
service: Proxy<'static>,
|
||||
session: OwnedObjectPath,
|
||||
}
|
||||
|
||||
impl Keyring {
|
||||
/// The session isn't encrypted: whoever could read it on this bus may ask for the secrets anyway (D-037).
|
||||
async fn open(bus: &Bus) -> zbus::Result<Option<Keyring>> {
|
||||
let Some(bus) = quick(bus.connect()).await? else { return Ok(None) };
|
||||
let service = secrets(&bus, "/org/freedesktop/secrets", "org.freedesktop.Secret.Service").await?;
|
||||
let (_, session): (OwnedValue, OwnedObjectPath) = quick(service.call("OpenSession", &("plain", Value::from("")))).await?;
|
||||
Ok(Some(Keyring { bus, service, session }))
|
||||
}
|
||||
|
||||
async fn proxy(&self, path: OwnedObjectPath, interface: &'static str) -> zbus::Result<Proxy<'static>> {
|
||||
secrets(&self.bus, path, interface).await
|
||||
}
|
||||
|
||||
async fn find(&self, name: &str) -> zbus::Result<Option<OwnedObjectPath>> {
|
||||
let (open, locked): (Vec<OwnedObjectPath>, Vec<OwnedObjectPath>) = quick(self.service.call("SearchItems", &(attributes(name),))).await?;
|
||||
if let Some(item) = open.into_iter().next() {
|
||||
return Ok(Some(item));
|
||||
}
|
||||
let Some(item) = locked.into_iter().next() else { return Ok(None) };
|
||||
Ok(self.unlock(&item).await?.then_some(item))
|
||||
}
|
||||
|
||||
async fn unlock(&self, what: &OwnedObjectPath) -> zbus::Result<bool> {
|
||||
let (_, prompt): (Vec<OwnedObjectPath>, OwnedObjectPath) = quick(self.service.call("Unlock", &(vec![what],))).await?;
|
||||
self.prompt(prompt).await
|
||||
}
|
||||
|
||||
/// Lets the keyring ask the user, if it has to. False when the user said no.
|
||||
async fn prompt(&self, path: OwnedObjectPath) -> zbus::Result<bool> {
|
||||
if path.as_str() == "/" {
|
||||
return Ok(true);
|
||||
}
|
||||
let prompt = self.proxy(path, "org.freedesktop.Secret.Prompt").await?;
|
||||
let mut answers = quick(prompt.receive_signal("Completed")).await?;
|
||||
let _: () = quick(prompt.call("Prompt", &("",))).await?;
|
||||
let answer = tokio::time::timeout(UNLOCK, answers.next()).await.map_err(|_| late())?;
|
||||
let Some(answer) = answer else { return Ok(false) };
|
||||
let (dismissed, _): (bool, OwnedValue) = answer.body().deserialize()?;
|
||||
Ok(!dismissed)
|
||||
}
|
||||
}
|
||||
|
||||
async fn secrets<P>(bus: &Connection, path: P, interface: &'static str) -> zbus::Result<Proxy<'static>>
|
||||
where
|
||||
P: TryInto<zbus::zvariant::ObjectPath<'static>>,
|
||||
P::Error: Into<zbus::Error>,
|
||||
{
|
||||
// Without reading properties ahead: nothing here needs them.
|
||||
zbus::proxy::Builder::new(bus)
|
||||
.destination("org.freedesktop.secrets")?
|
||||
.path(path)?
|
||||
.interface(interface)?
|
||||
.cache_properties(zbus::proxy::CacheProperties::No)
|
||||
.build()
|
||||
.await
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@
|
|||
//!
|
||||
//! No secrets: logins and tokens are keyring items, named here at most.
|
||||
|
||||
use crate::site::Site;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
use std::fs;
|
||||
|
|
@ -25,6 +26,11 @@ pub struct Settings {
|
|||
pub tries: u32,
|
||||
/// Go on at the next start with what ran when Medlar ended.
|
||||
pub auto_resume: bool,
|
||||
pub sites: Vec<Site>,
|
||||
/// See `proxy::Choice`.
|
||||
pub proxy: String,
|
||||
/// Hosts and networks it is not used for.
|
||||
pub proxy_bypass: Vec<String>,
|
||||
pub connector: bool,
|
||||
pub connector_port: u16,
|
||||
/// Add links from the browser without showing the Add dialog.
|
||||
|
|
@ -122,6 +128,9 @@ impl Default for Settings {
|
|||
snail: Limits::new(32 * 1024, 1, 1, 1, 1),
|
||||
tries: 10,
|
||||
auto_resume: true,
|
||||
sites: vec![],
|
||||
proxy: "system".into(),
|
||||
proxy_bypass: ["localhost", "127.0.0.0/8", "::1"].map(String::from).into(),
|
||||
connector: true,
|
||||
connector_port: 17616,
|
||||
add_without_asking: false,
|
||||
|
|
|
|||
456
crates/core/src/site.rs
Normal file
456
crates/core/src/site.rs
Normal file
|
|
@ -0,0 +1,456 @@
|
|||
//! Rules per site, and what each request of a download takes along: login, cookies, user agent and the way there.
|
||||
|
||||
use crate::auth::{Challenge, Login};
|
||||
use crate::cookie::Jar;
|
||||
use crate::http::{self, Client, ClientOptions, Error, Response, Result, Source, Stop};
|
||||
use crate::model::Task;
|
||||
use crate::net_state::Bus;
|
||||
use crate::proxy::{self, Choice};
|
||||
use crate::secret::{Secret, Secrets};
|
||||
use crate::settings::Settings;
|
||||
use crate::tls::Trust;
|
||||
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue, SET_COOKIE, USER_AGENT};
|
||||
use reqwest::{RequestBuilder, StatusCode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use url::{Host, Url};
|
||||
|
||||
/// What the user set for a site. Stored in the settings; None leaves it to a less specific site or the app.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Site {
|
||||
/// `example.com`, `*.example.com` (with `example.com` itself), `example.com:8080` or `*`.
|
||||
pub pattern: String,
|
||||
/// Keyring item with the login and cookies. Not for patterns that could be anyone's, such as `*` or `*.com`.
|
||||
pub secret: Option<String>,
|
||||
/// All its downloads together.
|
||||
pub max_connections: Option<u32>,
|
||||
/// Bytes per second.
|
||||
pub speed_limit: Option<u64>,
|
||||
pub user_agent: Option<String>,
|
||||
/// See `proxy::Choice`.
|
||||
pub proxy: Option<String>,
|
||||
/// Where its downloads go.
|
||||
pub folder: Option<PathBuf>,
|
||||
/// SHA-256 of a certificate that is accepted though nobody vouches for it. Counts for one exact host only.
|
||||
pub certificate: Option<String>,
|
||||
}
|
||||
|
||||
/// `Site::pattern`, understood.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Pattern {
|
||||
/// Lower case, without the `*.`.
|
||||
name: String,
|
||||
/// Hosts below `name` too.
|
||||
wide: bool,
|
||||
port: Option<u16>,
|
||||
}
|
||||
|
||||
impl Pattern {
|
||||
/// Takes a link as well.
|
||||
pub fn new(text: &str) -> Pattern {
|
||||
let text = text.trim();
|
||||
let text = text.split_once("://").map_or(text, |(_, rest)| rest);
|
||||
let text = text.split(['/', '?', '#']).next().unwrap_or_default();
|
||||
let text = text.rsplit('@').next().unwrap_or_default();
|
||||
let (name, port) = match text.rsplit_once(':') {
|
||||
// More colons are an IPv6 address, with a port only after brackets.
|
||||
Some((name, port)) if !name.contains(':') || name.ends_with(']') => (name, port.parse().ok()),
|
||||
_ => (text, None),
|
||||
};
|
||||
let (name, wide) = match name.strip_prefix('*') {
|
||||
Some(rest) => (rest.trim_start_matches('.'), true),
|
||||
None => (name, false),
|
||||
};
|
||||
let bare = name.trim_matches(['[', ']']);
|
||||
let literal = if bare.contains(':') { format!("[{bare}]") } else { bare.into() };
|
||||
// As hosts are written in links.
|
||||
let name = Host::parse(&literal).map_or(literal.to_ascii_lowercase(), |h| h.to_string());
|
||||
Pattern { name, wide, port }
|
||||
}
|
||||
|
||||
pub fn fits(&self, url: &Url) -> bool {
|
||||
let host = url.host_str().unwrap_or_default().to_ascii_lowercase();
|
||||
let below = || self.name.is_empty() || host.strip_suffix(&self.name).is_some_and(|rest| rest.ends_with('.'));
|
||||
!host.is_empty() && (host == self.name || (self.wide && below())) && self.port.is_none_or(|p| url.port_or_known_default() == Some(p))
|
||||
}
|
||||
|
||||
/// Of two that fit, the larger one counts.
|
||||
fn rank(&self) -> (bool, usize, bool) {
|
||||
(!self.wide, self.name.len(), self.port.is_some())
|
||||
}
|
||||
|
||||
/// Belongs to one owner, as far as can be told.
|
||||
fn owned(&self) -> bool {
|
||||
!self.wide || self.name.contains('.')
|
||||
}
|
||||
}
|
||||
|
||||
/// What counts for one link: each field from the most specific site that has it.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Rules {
|
||||
pub secret: Option<String>,
|
||||
pub max_connections: Option<u32>,
|
||||
pub speed_limit: Option<u64>,
|
||||
pub user_agent: Option<String>,
|
||||
pub proxy: Option<String>,
|
||||
pub folder: Option<PathBuf>,
|
||||
}
|
||||
|
||||
pub fn rules(sites: &[Site], url: &Url) -> Rules {
|
||||
let mut fit: Vec<(Pattern, &Site)> = sites.iter().map(|s| (Pattern::new(&s.pattern), s)).filter(|(p, _)| p.fits(url)).collect();
|
||||
fit.sort_by_key(|(p, _)| p.rank());
|
||||
let mut rules = Rules::default();
|
||||
for (pattern, site) in fit {
|
||||
let Site { secret, max_connections, speed_limit, user_agent, proxy, folder, .. } = site.clone();
|
||||
rules.secret = secret.filter(|_| pattern.owned()).or(rules.secret);
|
||||
rules.max_connections = max_connections.or(rules.max_connections);
|
||||
rules.speed_limit = speed_limit.or(rules.speed_limit);
|
||||
rules.user_agent = user_agent.or(rules.user_agent);
|
||||
rules.proxy = proxy.or(rules.proxy);
|
||||
rules.folder = folder.or(rules.folder);
|
||||
}
|
||||
rules
|
||||
}
|
||||
|
||||
/// Credentials given for `from` may go to `to`: the same site, or the same one over TLS.
|
||||
pub(crate) fn same_site(from: &Url, to: &Url) -> bool {
|
||||
let upgraded = from.scheme() == "http" && to.scheme() == "https" && from.port().is_none() && to.port().is_none();
|
||||
from.origin() == to.origin() || (upgraded && from.host() == to.host())
|
||||
}
|
||||
|
||||
struct Wide {
|
||||
sites: Vec<Site>,
|
||||
proxy: String,
|
||||
bypass: Vec<String>,
|
||||
/// One for each proxy.
|
||||
clients: HashMap<Option<Url>, Client>,
|
||||
/// What the desktop said.
|
||||
desktop: HashMap<String, (Instant, Option<Url>)>,
|
||||
}
|
||||
|
||||
/// One for the whole app.
|
||||
pub struct Sites {
|
||||
pub secrets: Arc<Secrets>,
|
||||
pub trust: Arc<Trust>,
|
||||
options: ClientOptions,
|
||||
/// Where the desktop's portal is.
|
||||
bus: Bus,
|
||||
env: HashMap<String, String>,
|
||||
wide: Mutex<Wide>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Sites {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("Sites")
|
||||
}
|
||||
}
|
||||
|
||||
impl Sites {
|
||||
/// Reads the system's certificates: not for the thread of the window. `bus` is the session's, or off.
|
||||
pub fn new(options: ClientOptions, settings: &Settings, secrets: Arc<Secrets>, bus: Bus) -> Result<Arc<Sites>> {
|
||||
let trust = http::trust(&options)?;
|
||||
let env = ["http_proxy", "https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY", "no_proxy", "NO_PROXY"];
|
||||
let env = env.iter().filter_map(|name| Some((name.to_string(), std::env::var(name).ok()?))).collect();
|
||||
let wide = Wide { sites: vec![], proxy: String::new(), bypass: vec![], clients: HashMap::new(), desktop: HashMap::new() };
|
||||
let sites = Sites { secrets, trust, options, bus, env, wide: Mutex::new(wide) };
|
||||
sites.set(settings);
|
||||
Ok(Arc::new(sites))
|
||||
}
|
||||
|
||||
/// Counts for the next request; those under way end as they are.
|
||||
pub fn set(&self, settings: &Settings) {
|
||||
self.trust.set(settings.sites.clone());
|
||||
let mut wide = self.wide.lock().unwrap();
|
||||
wide.sites = settings.sites.clone();
|
||||
wide.proxy = settings.proxy.clone();
|
||||
wide.bypass = settings.proxy_bypass.clone();
|
||||
// Their connections were made by the old rules.
|
||||
wide.clients.clear();
|
||||
wide.desktop.clear();
|
||||
}
|
||||
|
||||
pub fn rules(&self, url: &Url) -> Rules {
|
||||
rules(&self.wide.lock().unwrap().sites, url)
|
||||
}
|
||||
|
||||
/// Where the task's requests start, with all that goes along.
|
||||
pub async fn source(self: &Arc<Self>, task: &Task) -> Result<Source> {
|
||||
let source = Source::new(&task.url)?.with_headers(&task.headers);
|
||||
let mut secret = match &task.secret {
|
||||
Some(name) => self.secrets.load(name).await.unwrap_or_default(),
|
||||
None => Secret::default(),
|
||||
};
|
||||
// The task may have a new link since.
|
||||
let home = secret.home.as_deref().and_then(|h| Url::parse(h).ok());
|
||||
if !home.is_some_and(|home| same_site(&home, &source.url)) {
|
||||
secret = Secret::default();
|
||||
}
|
||||
let mut jar = Jar::default();
|
||||
if let Some(cookies) = &secret.cookies {
|
||||
jar.give(&source.url, cookies);
|
||||
}
|
||||
let access = Access {
|
||||
sites: self.clone(),
|
||||
home: source.url.clone(),
|
||||
proxy: task.proxy.clone(),
|
||||
login: secret.login,
|
||||
inner: Mutex::new(Inner { jar, challenges: HashMap::new() }),
|
||||
loaded: tokio::sync::Mutex::default(),
|
||||
};
|
||||
Ok(source.with_headers(&secret.headers).with_access(access))
|
||||
}
|
||||
|
||||
/// Forgets a proxy's old login at the next request.
|
||||
pub async fn save_proxy_login(&self, proxy: &str, login: Login) -> Option<crate::secret::Kept> {
|
||||
let Some(Choice::At(url)) = Choice::parse(proxy) else { return None };
|
||||
let secret = Secret { login: Some(login), ..Secret::default() };
|
||||
let kept = self.secrets.save(&proxy::secret_name(&url), url.host_str().unwrap_or_default(), &secret).await;
|
||||
self.wide.lock().unwrap().clients.clear();
|
||||
Some(kept)
|
||||
}
|
||||
|
||||
/// The download's proxy counts first, then the site's, then the bypass list, then the app's.
|
||||
async fn proxy(&self, url: &Url, own: Option<&str>, site: Option<&str>) -> Result<Option<Url>> {
|
||||
let chosen = match own.or(site) {
|
||||
Some(text) => Choice::parse(text),
|
||||
None => {
|
||||
let wide = self.wide.lock().unwrap();
|
||||
if proxy::bypassed(&wide.bypass, url) { Some(Choice::Direct) } else { Choice::parse(&wide.proxy) }
|
||||
}
|
||||
};
|
||||
match chosen {
|
||||
Some(Choice::Direct) => Ok(None),
|
||||
Some(Choice::At(proxy)) => Ok(Some(proxy)),
|
||||
Some(Choice::System) => Ok(self.system(url).await),
|
||||
// Never straight to the server instead.
|
||||
None => Err(Error::Proxy(None)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn system(&self, url: &Url) -> Option<Url> {
|
||||
if let Some(found) = proxy::from_env(url, |name| self.env.get(name).cloned()) {
|
||||
return found;
|
||||
}
|
||||
if self.bus == Bus::Off {
|
||||
return None;
|
||||
}
|
||||
let key = url.origin().ascii_serialization();
|
||||
if let Some((at, found)) = self.wide.lock().unwrap().desktop.get(&key)
|
||||
&& at.elapsed() < Duration::from_secs(60)
|
||||
{
|
||||
return found.clone();
|
||||
}
|
||||
let found = proxy::from_desktop(&self.bus, url).await;
|
||||
self.wide.lock().unwrap().desktop.insert(key, (Instant::now(), found.clone()));
|
||||
found
|
||||
}
|
||||
|
||||
async fn client(&self, proxy: Option<Url>) -> Result<Client> {
|
||||
if let Some(client) = self.wide.lock().unwrap().clients.get(&proxy) {
|
||||
return Ok(client.clone());
|
||||
}
|
||||
let mut address = proxy.clone();
|
||||
if let Some(url) = &proxy
|
||||
&& url.username().is_empty()
|
||||
&& let Some(login) = self.secrets.load(&proxy::secret_name(url)).await.and_then(|s| s.login)
|
||||
{
|
||||
address = Some(proxy::with_login(url.clone(), &login));
|
||||
}
|
||||
let client = http::client_with(&self.options, &self.trust, address)?;
|
||||
Ok(self.wide.lock().unwrap().clients.entry(proxy).or_insert(client).clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// The task's source, by the rules of `sites` if there are any. May wait for the user to unlock the keyring.
|
||||
pub(crate) async fn source(sites: Option<&Arc<Sites>>, task: &Task, stop: &Stop) -> Result<Source> {
|
||||
let Some(sites) = sites else { return Ok(Source::new(&task.url)?.with_headers(&task.headers)) };
|
||||
let mut stop = stop.clone();
|
||||
tokio::select! {
|
||||
_ = http::stopped(&mut stop) => Err(Error::Stopped),
|
||||
source = sites.source(task) => source,
|
||||
}
|
||||
}
|
||||
|
||||
/// What one download carries from request to request.
|
||||
pub(crate) struct Access {
|
||||
sites: Arc<Sites>,
|
||||
/// Where `login` is for.
|
||||
home: Url,
|
||||
proxy: Option<String>,
|
||||
login: Option<Login>,
|
||||
inner: Mutex<Inner>,
|
||||
/// Secrets of sites, by name and host.
|
||||
loaded: tokio::sync::Mutex<HashMap<(String, String), Arc<Secret>>>,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
jar: Jar,
|
||||
/// By site.
|
||||
challenges: HashMap<String, Challenge>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Access {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.write_str("Access")
|
||||
}
|
||||
}
|
||||
|
||||
impl Access {
|
||||
pub(crate) fn rules(&self, url: &Url) -> Rules {
|
||||
self.sites.rules(url)
|
||||
}
|
||||
|
||||
/// Sends what `request` makes, and once more with a login if the server wants one.
|
||||
pub(crate) async fn send(&self, url: &Url, headers: &HeaderMap, request: impl Fn(&Client, &HeaderMap) -> RequestBuilder) -> Result<Response> {
|
||||
let rules = self.rules(url);
|
||||
let way = self.sites.proxy(url, self.proxy.as_deref(), rules.proxy.as_deref()).await?;
|
||||
let proxied = way.is_some();
|
||||
let client = self.sites.client(way).await?;
|
||||
let secret = self.secret(url, rules.secret).await;
|
||||
let login = self.login.as_ref().filter(|_| same_site(&self.home, url)).or(secret.login.as_ref());
|
||||
let mut headers = headers.clone();
|
||||
if let Some(agent) = rules.user_agent.and_then(|a| HeaderValue::try_from(a).ok())
|
||||
&& !headers.contains_key(USER_AGENT)
|
||||
{
|
||||
headers.insert(USER_AGENT, agent);
|
||||
}
|
||||
for (name, value) in http::valid(&secret.headers) {
|
||||
headers.entry(name).or_insert(value);
|
||||
}
|
||||
let key = url.origin().ascii_serialization();
|
||||
let mut tried = false;
|
||||
loop {
|
||||
let mut request = request(&client, &headers);
|
||||
let mut nonce = None;
|
||||
{
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
if let Some(cookies) = inner.jar.header(url, chrono::Utc::now()) {
|
||||
request = request.header(reqwest::header::COOKIE, cookies);
|
||||
}
|
||||
// One that was given goes first.
|
||||
if let Some(login) = login.filter(|_| !headers.contains_key(AUTHORIZATION)) {
|
||||
match inner.challenges.get_mut(&key) {
|
||||
Some(Challenge::Basic) => {
|
||||
tried = true;
|
||||
request = request.basic_auth(&login.user, Some(&login.password));
|
||||
}
|
||||
Some(Challenge::Digest(d)) => {
|
||||
let mut answer = HeaderValue::try_from(d.answer(login, url)).map_err(|_| Error::Link)?;
|
||||
answer.set_sensitive(true);
|
||||
nonce = Some(d.nonce.clone());
|
||||
request = request.header(AUTHORIZATION, answer);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let response = request.send().await.map_err(|e| failed(e, proxied))?;
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
for value in response.headers().get_all(SET_COOKIE).iter().filter_map(|v| v.to_str().ok()) {
|
||||
inner.jar.set(response.url(), value, chrono::Utc::now());
|
||||
}
|
||||
if response.status() != StatusCode::UNAUTHORIZED || tried || login.is_none() || headers.contains_key(AUTHORIZATION) {
|
||||
return Ok(response);
|
||||
}
|
||||
let Some(challenge) = Challenge::of(response.headers()) else { return Ok(response) };
|
||||
// The answer to this very question was wrong.
|
||||
if matches!(&challenge, Challenge::Digest(d) if Some(&d.nonce) == nonce.as_ref()) {
|
||||
return Ok(response);
|
||||
}
|
||||
inner.challenges.insert(key.clone(), challenge);
|
||||
tried = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing for a site without TLS that a link with TLS led to.
|
||||
async fn secret(&self, url: &Url, name: Option<String>) -> Arc<Secret> {
|
||||
let Some(name) = name.filter(|_| self.home.scheme() != "https" || url.scheme() == "https") else { return Arc::default() };
|
||||
let host = url.origin().ascii_serialization();
|
||||
let mut loaded = self.loaded.lock().await;
|
||||
if let Some(secret) = loaded.get(&(name.clone(), host.clone())) {
|
||||
return secret.clone();
|
||||
}
|
||||
let secret = Arc::new(self.sites.secrets.load(&name).await.unwrap_or_default());
|
||||
if let Some(cookies) = &secret.cookies {
|
||||
self.inner.lock().unwrap().jar.give(url, cookies);
|
||||
}
|
||||
loaded.insert((name, host), secret.clone());
|
||||
secret
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(e: reqwest::Error, proxied: bool) -> Error {
|
||||
if proxied && e.is_connect() && crate::error::tls_error(&e).is_none() { Error::Proxy(Some(e.without_url())) } else { e.into() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn url(text: &str) -> Url {
|
||||
Url::parse(text).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patterns() {
|
||||
for (pattern, yes, no) in [
|
||||
("Example.com", "https://example.com/f", "https://a.example.com/"),
|
||||
("*.example.com", "https://a.b.example.com/", "https://badexample.com/"),
|
||||
("*.example.com", "https://example.com/", "https://example.com.evil.org/"),
|
||||
("*", "http://anything/", "file:///x"),
|
||||
("example.com:8080", "http://example.com:8080/", "http://example.com/"),
|
||||
("example.com:443", "https://example.com/", "http://example.com/"),
|
||||
("https://[email protected]/files?x", "http://example.com/", "http://other/"),
|
||||
("::1", "http://[::1]:9/", "http://[::2]/"),
|
||||
("[::1]:9", "http://[::1]:9/", "http://[::1]/"),
|
||||
("bücher.example", "http://xn--bcher-kva.example/", "http://bucher.example/"),
|
||||
("*.bücher.example", "http://a.xn--bcher-kva.example/", "http://x/"),
|
||||
] {
|
||||
let p = Pattern::new(pattern);
|
||||
assert!(p.fits(&url(yes)) && !p.fits(&url(no)), "{pattern}: {p:?}");
|
||||
}
|
||||
assert!(!Pattern::new("").fits(&url("http://h/")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_most_specific_site_wins_field_by_field() {
|
||||
let site = |pattern: &str, cap, agent: Option<&str>| Site {
|
||||
pattern: pattern.into(),
|
||||
max_connections: cap,
|
||||
user_agent: agent.map(Into::into),
|
||||
secret: Some(format!("of {pattern}")),
|
||||
..Site::default()
|
||||
};
|
||||
let sites = [
|
||||
site("a.example.com", None, Some("exact")),
|
||||
site("*", Some(1), Some("all")),
|
||||
site("*.example.com", Some(3), Some("below")),
|
||||
site("*.com", Some(2), None),
|
||||
site("a.example.com:81", Some(9), None),
|
||||
];
|
||||
let of = |link| {
|
||||
let r = rules(&sites, &url(link));
|
||||
(r.max_connections, r.user_agent.unwrap(), r.secret)
|
||||
};
|
||||
let secret = |pattern: &str| Some(format!("of {pattern}"));
|
||||
assert_eq!(of("http://a.example.com/"), (Some(3), "exact".into(), secret("a.example.com")));
|
||||
assert_eq!(of("http://a.example.com:81/"), (Some(9), "exact".into(), secret("a.example.com:81")));
|
||||
assert_eq!(of("http://b.example.com/"), (Some(3), "below".into(), secret("*.example.com")));
|
||||
assert_eq!(of("http://other.com/"), (Some(2), "all".into(), None));
|
||||
assert_eq!(of("http://other.org/"), (Some(1), "all".into(), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_sites() {
|
||||
let same = |a, b| same_site(&url(a), &url(b));
|
||||
assert!(same("http://h/a", "http://h/b") && same("http://h/", "https://h/") && same("https://h/", "https://h:443/"));
|
||||
for (a, b) in [("https://h/", "http://h/"), ("http://h/", "http://h:81/"), ("http://h:81/", "https://h/"), ("http://h/", "http://a.h/")] {
|
||||
assert!(!same(a, b), "{a} {b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue