S011: FTP, FTPS, SFTP and folder listings

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-25 07:45:25 -06:00
commit 695a4ca4da
23 changed files with 3721 additions and 43 deletions

1155
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -11,13 +11,13 @@ FEATURES 1.9, plus directory listing used by the site explorer.
- suppaftp and russh docs for the pinned versions
## Steps
- [ ] A transport trait drawn from the HTTP path, only as wide as needed
- [ ] FTP and FTPS: passive and extended passive, REST resume, SIZE, MDTM, segments when the server allows several logins
- [ ] SFTP: password and key logins, host key prompt and known_hosts style store, positioned reads in parallel
- [ ] Directory listing (MLSD, LIST variants, SFTP) as one type
- [ ] Errors mapped to S007's kinds if it is merged, else to the model's placeholder kinds
- [ ] In-process FTP and SFTP test servers on loopback (dev-dependency or small own stub)
- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S011: …`, push
- [x] A transport trait drawn from the HTTP path, only as wide as needed
- [x] FTP and FTPS: passive and extended passive, REST resume, SIZE, MDTM, segments when the server allows several logins
- [x] SFTP: password and key logins, host key prompt and known_hosts style store, positioned reads in parallel
- [x] Directory listing (MLSD, LIST variants, SFTP) as one type
- [x] Errors mapped to S007's kinds if it is merged, else to the model's placeholder kinds
- [x] In-process FTP and SFTP test servers on loopback (dev-dependency or small own stub)
- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S011: …`, push
## End criteria
- `nice cargo test -j 2 -p medlar-core --test ftp` green: resume, cut, wrong login, changed host key refused

View file

@ -19,7 +19,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H
- [x] [S008](02%20Engine/S008-continue-links.md) Continue from a new link
- [ ] [S009](02%20Engine/S009-mirrors-checksums.md) Mirrors, Metalink and checksums
- [x] [S010](02%20Engine/S010-logins-proxies.md) Logins, cookies and proxies
- [ ] [S011](02%20Engine/S011-ftp-sftp.md) FTP, FTPS and SFTP
- [x] [S011](02%20Engine/S011-ftp-sftp.md) FTP, FTPS and SFTP
- [ ] [S012](02%20Engine/S012-streams.md) HLS, DASH, RTSP and MMS
## 03 Interface

View file

@ -7,16 +7,23 @@ description = "Medlar's engine, store and settings"
[dependencies]
arc-swap = "1.9.5"
base64 = "0.23"
bytes = "1.10"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
dirs = "6"
futures-lite = "2.6"
http = "1.5"
http-body = "1.1"
hyper-util = { version = "0.1.21", default-features = false, features = ["client-legacy", "client-proxy", "http1", "tokio"] }
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", "socks"] }
# ring, as everywhere else: aws-lc-rs would be a second one.
russh = { version = "=0.65.4", default-features = false, features = ["ring", "rsa"] }
russh-sftp = { version = "4", features = ["raw-string"] }
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"] }
@ -25,7 +32,9 @@ 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"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util"] }
tokio-rustls = { version = "0.26", default-features = false }
tower-service = "0.3"
url = "2"
# Without its tokio feature: the window's accessibility and tray share this build and run outside of tokio.
zbus = "5.19"
@ -33,4 +42,5 @@ zbus = "5.19"
[dev-dependencies]
fastrand = "2.5.0"
medlar-testserver.workspace = true
rcgen = { version = "0.14.10", default-features = false, features = ["crypto", "ring", "pem"] }
tempfile = "3"

View file

@ -227,6 +227,10 @@
"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.host_key.changed": "{server} has another key than before. Someone may be intercepting the connection. Accept the new key only if you know why it changed.",
"error.host_key.new": "Medlar has not seen the key of {server} before. Compare it with one you trust, then accept it.",
"error.tls.old": "{server} and Medlar have no way in common to secure the connection.",
"error.tls.none": "{server} offers no secure connection, 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.",
@ -234,21 +238,27 @@
"error.login": "Login needed",
"error.login.why": "{server} wants a user name and password.",
"error.forbidden": "Access denied",
"error.forbidden.plain": "{server} refused to give out the file. Another login may be allowed to have it.",
"error.forbidden.why": "{server} refused to give out the file (status {code}). The link may need the page it came from.",
"error.link": "Waiting for a new link",
"error.link.why": "Start the download again on the page it came from. Medlar continues this one with the new link.",
"error.expired": "Link expired",
"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.plain": "{server} has no file at this link, or does not show it to you.",
"error.not_found.why": "{server} has no file at this link (status {code}).",
"error.login.key": "The key file for {server} can't be read, or its passphrase is wrong.",
"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.plain": "{server} did not accept the request.",
"error.rejected.why": "{server} did not accept the request (status {code}).",
"error.busy": "Server is busy",
"error.busy.connections": "{server} allows no more connections right now.",
"error.busy.why": "{server} has too many requests right now (status {code}).",
"error.server": "Server error",
"error.server.plain": "{server} had a problem of its own.",
"error.server.why": "{server} had a problem of its own (status {code}).",
"error.bad_reply": "Wrong answer from the server",
"error.bad_reply.why": "{server} contradicted itself about the file, so nothing from that answer was used.",

View file

@ -188,6 +188,7 @@ impl Failure {
E::Net(e) => of_net(e),
E::Idle => ErrorKind::Timeout,
E::Tls(_) => ErrorKind::Tls,
E::Conn { kind, why } => return Failure::because(*kind, *why, place),
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,
@ -231,7 +232,7 @@ pub(crate) fn tls_error(e: &reqwest::Error) -> Option<&rustls::Error> {
}
/// The plain reason a certificate was refused.
fn tls_why(e: Option<&rustls::Error>) -> Option<&'static str> {
pub(crate) 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 {
@ -248,8 +249,12 @@ fn tls_why(e: Option<&rustls::Error>) -> Option<&'static str> {
/// hyper's types for it are private.
fn proxy_login(e: &reqwest::Error) -> bool {
causes(e).any(|e| proxy_wants_login(&e.to_string()))
}
pub(crate) fn proxy_wants_login(text: &str) -> 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)))
known.iter().any(|k| text.contains(k))
}
/// The error and all that led to it.

388
crates/core/src/ftp.rs Normal file
View file

@ -0,0 +1,388 @@
//! FTP and FTPS: passive only, binary only. Links: `ftp` is plain, `ftps` has TLS from the start, `ftpes` asks for it (AUTH TLS).
//! A path counts from the login's own folder; one that starts with `%2F` counts from the root. (D-049)
use crate::auth::Login;
use crate::http::{Error, Result};
use crate::listing::{self, Found, stamp};
use crate::model::ErrorKind;
use crate::transport::{Stat, Transport, Way, dial, host};
use bytes::{Bytes, BytesMut};
use chrono::Utc;
use rustls::pki_types::ServerName;
use std::io;
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
use tokio_rustls::TlsConnector;
use url::Url;
/// Bytes read at once.
const PIECE: usize = 64 * 1024;
/// More than any honest server sends.
const MAX_REPLY: usize = 256 * 1024;
const MAX_LIST: u64 = 32 * 1024 * 1024;
trait Wire: AsyncRead + AsyncWrite + Send + Sync + Unpin {}
impl<T: AsyncRead + AsyncWrite + Send + Sync + Unpin> Wire for T {}
pub(crate) struct Ftp {
control: BufReader<Box<dyn Wire>>,
way: Way,
/// For data connections.
host: String,
tls: Option<(TlsConnector, ServerName<'static>)>,
/// Extended passive mode works, as far as is known.
extended: bool,
mlsd: bool,
resumes: Option<bool>,
data: Option<Box<dyn Wire>>,
/// Bytes to read, if not to the end.
left: Option<u64>,
/// Stopped in the middle of a file.
spent: bool,
}
struct Answer {
code: u16,
text: String,
}
impl Answer {
fn expect(self, codes: &[u16]) -> Result<Answer> {
if codes.contains(&self.code) { Ok(self) } else { Err(self.error()) }
}
fn says(&self, words: &[&str]) -> bool {
let text = self.text.to_ascii_lowercase();
words.iter().any(|w| text.contains(w))
}
/// No room for another connection, whatever the code.
fn full(&self) -> bool {
self.says(&["too many", "maximum", "max number", "limit", "already logged"])
}
fn error(&self) -> Error {
match self.code {
421 => Error::because(ErrorKind::Busy, "error.busy.connections"),
425 | 426 | 451 => Error::conn(ErrorKind::Cut),
430 | 530 | 532 if self.full() => Error::because(ErrorKind::Busy, "error.busy.connections"),
332 | 430 | 530 | 532 => Error::conn(ErrorKind::Login),
522 | 533 | 534 | 535 => Error::because(ErrorKind::Tls, "error.tls.none"),
450 | 550 | 553 if self.says(&["denied", "permission", "not allowed", "forbidden"]) => {
Error::because(ErrorKind::Forbidden, "error.forbidden.plain")
}
450 | 550 | 553 => Error::because(ErrorKind::NotFound, "error.not_found.plain"),
400..=499 => Error::because(ErrorKind::Server, "error.server.plain"),
_ => Error::because(ErrorKind::Rejected, "error.rejected.plain"),
}
}
}
impl Transport for Ftp {
async fn connect(way: Way, url: &Url, known: bool) -> Result<Ftp> {
let implicit = url.scheme() == "ftps";
let name = host(url)?;
let (stream, host) = dial(&way, &name, url.port().unwrap_or(if implicit { 990 } else { 21 })).await?;
let tls = match url.scheme() {
"ftp" => None,
_ => {
let mut config = way.client.trust().config(Arc::new(rustls::crypto::ring::default_provider()))?;
config.alpn_protocols.clear();
Some((TlsConnector::from(Arc::new(config)), ServerName::try_from(name).map_err(|_| Error::Link)?))
}
};
let mut ftp = Ftp {
control: BufReader::new(Box::new(stream)),
way,
host,
tls,
extended: true,
mlsd: false,
resumes: None,
data: None,
left: None,
spent: false,
};
if implicit {
ftp.secure_control().await?;
}
let mut hello = ftp.answer().await?;
while hello.code < 200 {
hello = ftp.answer().await?;
}
hello.expect(&[220])?;
if url.scheme() == "ftpes" {
if ftp.command("AUTH", b"TLS").await?.code != 234 {
return Err(Error::because(ErrorKind::Tls, "error.tls.none"));
}
// Whatever came before the handshake could be anyone's.
if !ftp.control.buffer().is_empty() {
return Err(Error::conn(ErrorKind::Tls));
}
ftp.secure_control().await?;
}
if ftp.tls.is_some() {
ftp.command("PBSZ", b"0").await?;
ftp.command("PROT", b"P").await?.expect(&[200])?;
}
ftp.login(known).await?;
let features = ftp.command("FEAT", b"").await?;
if features.code == 211 {
ftp.mlsd = features.says(&["mlst"]);
if features.says(&["utf8"]) {
// Those who refuse speak it anyway.
ftp.command("OPTS", b"UTF8 ON").await?;
}
}
ftp.command("TYPE", b"I").await?.expect(&[200])?;
Ok(ftp)
}
fn path(url: &Url) -> Result<Vec<u8>> {
let path = url.path();
let path = path.strip_prefix('/').unwrap_or(path);
let path = match path.rsplit_once(";type=") {
Some((path, kind)) if kind.len() == 1 => path,
_ => path,
};
let path: Vec<u8> = percent_encoding::percent_decode_str(path).collect();
// Each line is a command of its own.
if path.iter().any(|b| matches!(b, b'\r' | b'\n' | 0)) { Err(Error::Link) } else { Ok(path) }
}
async fn stat(&mut self, path: &[u8]) -> Result<Stat> {
let fine = |a: Answer| match a.code {
213 => Ok(Some(a.text)),
421 | 530 => Err(a.error()),
// Unknown here, or for this file: the download itself will tell.
_ => Ok(None),
};
let size = fine(self.command("SIZE", path).await?)?;
let modified = fine(self.command("MDTM", path).await?)?;
let size = size.and_then(|s| s.split_whitespace().next()?.parse().ok());
Ok(Stat { size, modified: modified.and_then(|m| stamp(&m)) })
}
async fn resumes(&mut self) -> Result<bool> {
if self.resumes.is_none() {
let can = self.command("REST", b"1").await?.code == 350 && self.command("REST", b"0").await?.code == 350;
self.resumes = Some(can);
}
Ok(self.resumes == Some(true))
}
async fn open(&mut self, path: &[u8], first: u64, len: Option<u64>) -> Result<()> {
// A folder has no bytes.
if path.is_empty() {
return Err(Error::because(ErrorKind::NotFound, "error.not_found.plain"));
}
let rest = (first > 0).then_some(first);
self.transfer("RETR", path, rest).await?;
self.left = len;
Ok(())
}
async fn next(&mut self) -> Result<Option<Bytes>> {
let Some(data) = &mut self.data else { return Ok(None) };
if self.left == Some(0) {
// The rest of the file is on its way already.
(self.data, self.spent) = (None, true);
return Ok(None);
}
let most = self.left.map_or(PIECE, |left| left.min(PIECE as u64) as usize);
let mut piece = BytesMut::with_capacity(most);
let mut data = data.take(most as u64);
// Without a timeout: nobody reads on while limits hold the bytes back, and whoever waits has one.
match data.read_buf(&mut piece).await {
Ok(0) => {}
// TLS without its proper end, as many do. What the server says next counts.
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {}
Err(e) => return Err(e.into()),
Ok(n) => {
self.left = self.left.map(|left| left - n as u64);
return Ok(Some(piece.freeze()));
}
}
self.data = None;
let end = self.answer().await?;
if matches!(end.code, 226 | 250) { Ok(None) } else { Err(Error::conn(ErrorKind::Cut)) }
}
fn reusable(&self) -> bool {
!self.spent && self.data.is_none()
}
async fn list(&mut self, path: &[u8]) -> Result<Vec<Found>> {
// Names with blanks or a dash in front go wrong as an argument of LIST.
if !path.is_empty() {
self.command("CWD", path).await?.expect(&[200, 250])?;
}
let begun = self.transfer(if self.mlsd { "MLSD" } else { "LIST" }, b"", None).await;
match begun {
// How some put it that the folder is empty.
Err(Error::Conn { kind: ErrorKind::NotFound, .. }) => return Ok(vec![]),
begun => begun?,
}
let mut text = vec![];
while let Some(piece) = self.way.client.clone().wait(self.next()).await? {
text.extend_from_slice(&piece);
if text.len() as u64 > MAX_LIST {
return Err(Error::BadReply("a listing without end".into()));
}
}
Ok(if self.mlsd { listing::mlsd(&text) } else { listing::plain(&text, Utc::now()) })
}
}
impl Ftp {
async fn login(&mut self, known: bool) -> Result<()> {
let anonymous = || Login { user: "anonymous".into(), password: "anonymous".into() };
let Login { user, password } = self.way.login.clone().unwrap_or_else(anonymous);
let mut answer = self.command("USER", user.as_bytes()).await?;
if answer.code == 331 {
answer = self.command("PASS", password.as_bytes()).await?;
}
match answer.code {
200 | 202 | 230 => Ok(()),
430 | 530 if known => Err(Error::because(ErrorKind::Busy, "error.busy.connections")),
_ => Err(answer.error()),
}
}
/// Asks for data. They can be read when it returns.
async fn transfer(&mut self, command: &str, argument: &[u8], rest: Option<u64>) -> Result<()> {
let port = self.passive().await?;
let (stream, _) = dial(&self.way, &self.host, port).await?;
if let Some(rest) = rest
&& self.command("REST", rest.to_string().as_bytes()).await?.code != 350
{
return Err(Error::RangeIgnored);
}
self.command(command, argument).await?.expect(&[125, 150])?;
(self.left, self.spent) = (None, false);
self.data = Some(self.secured(Box::new(stream)).await?);
Ok(())
}
/// The port for the next data connection. Always at the same host: an address in the answer could be anyone's.
async fn passive(&mut self) -> Result<u16> {
if self.extended {
let answer = self.command("EPSV", b"").await?;
if answer.code == 229 {
return extended_port(&answer.text).ok_or_else(|| Error::BadReply("no port to connect to".into()));
}
if answer.code < 500 {
return Err(answer.error());
}
self.extended = false;
}
let answer = self.command("PASV", b"").await?.expect(&[227])?;
passive_port(&answer.text).ok_or_else(|| Error::BadReply("no port to connect to".into()))
}
async fn secure_control(&mut self) -> Result<()> {
// Stays for an instant only.
let plain = std::mem::replace(&mut self.control, BufReader::new(Box::new(tokio::io::empty())));
self.control = BufReader::new(self.secured(plain.into_inner()).await?);
Ok(())
}
async fn secured(&self, wire: Box<dyn Wire>) -> Result<Box<dyn Wire>> {
let Some((connector, name)) = &self.tls else { return Ok(wire) };
let wire = self.way.client.wait(connector.connect(name.clone(), wire)).await?;
Ok(Box::new(wire))
}
async fn command(&mut self, verb: &str, argument: &[u8]) -> Result<Answer> {
if argument.iter().any(|b| matches!(b, b'\r' | b'\n' | 0)) {
return Err(Error::Link);
}
let mut line = verb.as_bytes().to_vec();
if !argument.is_empty() {
line.push(b' ');
line.extend_from_slice(argument);
}
line.extend_from_slice(b"\r\n");
let client = self.way.client.clone();
client.wait(self.control.write_all(&line)).await?;
client.wait(self.control.flush()).await?;
self.answer().await
}
async fn answer(&mut self) -> Result<Answer> {
let client = self.way.client.clone();
client.wait(self.read_answer()).await
}
async fn read_answer(&mut self) -> Result<Answer> {
let mut text = vec![];
let mut room = MAX_REPLY;
let mut code = None;
loop {
let mut line = vec![];
let n = (&mut self.control).take(room as u64).read_until(b'\n', &mut line).await?;
room -= n;
if n == 0 {
return Err(if room == 0 { Error::BadReply("an answer without end".into()) } else { Error::conn(ErrorKind::Cut) });
}
let number = line.get(..3).and_then(|n| std::str::from_utf8(n).ok()?.parse::<u16>().ok()).filter(|n| (100..600).contains(n));
// The first line has the code; with a dash the last one begins with it too.
let last = line.get(3) != Some(&b'-');
match code {
None => code = Some(number.ok_or_else(|| Error::BadReply("no FTP server".into()))?),
Some(_) if number != code => {
text.extend_from_slice(&line);
continue;
}
Some(_) => {}
}
text.extend_from_slice(line.get(4..).unwrap_or_default());
if let Some(code) = code.filter(|_| last) {
return Ok(Answer { code, text: String::from_utf8_lossy(&text).trim().into() });
}
}
}
}
/// `(|||port|)`, with any sign in place of the bar.
fn extended_port(text: &str) -> Option<u16> {
let inner = text.split_once('(')?.1.split_once(')')?.0;
let bar = inner.chars().next()?;
inner.split(bar).nth(3)?.parse().ok()
}
/// Six numbers: the address and the port.
fn passive_port(text: &str) -> Option<u16> {
let from = text.find('(').map_or_else(|| text.find(|c: char| c.is_ascii_digit()), |i| Some(i + 1))?;
let inner = text[from..].split(')').next()?;
let numbers: Vec<u8> = inner.split(',').map(|n| n.trim().parse().ok()).collect::<Option<_>>()?;
let [_, _, _, _, high, low] = numbers[..] else { return None };
Some(u16::from_be_bytes([high, low]))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ports() {
assert_eq!(extended_port("Entering Extended Passive Mode (|||6446|)"), Some(6446));
assert_eq!(extended_port("ok (!!!21!)"), Some(21));
assert_eq!(passive_port("Entering Passive Mode (10,0,0,1,19,137)."), Some(5001));
assert_eq!(passive_port("Entering Passive Mode 10,0,0,1,19,137"), Some(5001));
for bad in ["", "(", "()", "(|||x|)", "(1,2,3)", "(1,2,3,4,5,600)", "(|||70000|)"] {
assert_eq!((extended_port(bad), passive_port(bad)), (None, None), "{bad}");
}
}
#[test]
fn paths() {
let path = |url: &str| Ftp::path(&Url::parse(url).unwrap()).ok();
assert_eq!(path("ftp://h/a%20b/c.iso").unwrap(), b"a b/c.iso");
assert_eq!(path("ftps://h/%2Fetc/x;type=i").unwrap(), b"/etc/x");
assert_eq!(path("ftp://h").unwrap(), b"");
for command in ["ftp://h/a%0D%0ADELE%20x", "ftp://h/a%0a", "ftp://h/%00"] {
assert_eq!(path(command), None);
}
}
}

View file

@ -15,12 +15,16 @@ pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot};
pub use name::safe as safe_name;
pub use probe::{Probe, probe};
use crate::model::ErrorKind;
use crate::sftp::HostKeys;
use crate::site::{Access, same_site};
use crate::tls::Trust;
use crate::transport::{Remote, Way};
use crate::{disk, redact, store};
use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue};
pub(crate) use reqwest::Response;
use reqwest::{RequestBuilder, StatusCode, redirect};
use std::path::PathBuf;
use std::sync::{Arc, Once};
use std::time::Duration;
use tokio::sync::watch;
@ -39,6 +43,8 @@ pub enum Error {
Idle,
/// The proxy can't be reached or refuses. None: its setting makes no sense.
Proxy(Option<reqwest::Error>),
/// A connection that isn't HTTP failed. `why` is the text, if it isn't the usual one.
Conn { kind: ErrorKind, why: Option<&'static str> },
/// TLS can't be set up here.
Tls(rustls::Error),
Status { code: u16, retry_after: Option<Duration> },
@ -62,6 +68,16 @@ pub enum Error {
Store(store::Error),
}
impl Error {
pub(crate) fn conn(kind: ErrorKind) -> Error {
Error::Conn { kind, why: None }
}
pub(crate) fn because(kind: ErrorKind, why: &'static str) -> Error {
Error::Conn { kind, why: Some(why) }
}
}
pub type Result<T> = std::result::Result<T, Error>;
impl From<rustls::Error> for Error {
@ -98,11 +114,13 @@ pub struct ClientOptions {
pub idle_timeout: Duration,
/// DER certificates to trust instead of the system's (tests).
pub only_certs: Vec<Vec<u8>>,
/// Where the keys of SSH servers are kept: `Paths::known_hosts`. None forgets them at the end.
pub known_hosts: Option<PathBuf>,
}
impl Default for ClientOptions {
fn default() -> Self {
ClientOptions { connect_timeout: Duration::from_secs(20), idle_timeout: Duration::from_secs(30), only_certs: vec![] }
ClientOptions { connect_timeout: Duration::from_secs(20), idle_timeout: Duration::from_secs(30), only_certs: vec![], known_hosts: None }
}
}
@ -110,7 +128,9 @@ impl Default for ClientOptions {
#[derive(Debug, Clone)]
pub struct Client {
inner: reqwest::Client,
connect: Duration,
idle: Duration,
trust: Arc<Trust>,
}
impl Client {
@ -118,6 +138,18 @@ impl Client {
self.inner.get(url)
}
pub(crate) fn connect_timeout(&self) -> Duration {
self.connect
}
pub(crate) fn idle_timeout(&self) -> Duration {
self.idle
}
pub(crate) fn trust(&self) -> &Arc<Trust> {
&self.trust
}
/// The time counts while it is waited for only: limits may hold back what came before for longer. reqwest's own timeout goes
/// on meanwhile.
pub(crate) async fn wait<T, E: Into<Error>>(&self, what: impl Future<Output = std::result::Result<T, E>>) -> Result<T> {
@ -134,7 +166,8 @@ pub fn client(options: &ClientOptions) -> Result<Client> {
/// 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)?))
let host_keys = HostKeys::new(options.known_hosts.clone());
Ok(Arc::new(Trust::new(Arc::new(rustls::crypto::ring::default_provider()), &options.only_certs, host_keys)?))
}
pub(crate) fn client_with(options: &ClientOptions, trust: &Arc<Trust>, proxy: Option<Url>) -> Result<Client> {
@ -156,7 +189,7 @@ pub(crate) fn client_with(options: &ClientOptions, trust: &Arc<Trust>, proxy: Op
if let Some(proxy) = proxy {
builder = builder.proxy(reqwest::Proxy::all(proxy)?);
}
Ok(Client { inner: builder.build()?, idle: options.idle_timeout })
Ok(Client { inner: builder.build()?, connect: options.connect_timeout, idle: options.idle_timeout, trust: trust.clone() })
}
/// A link and the headers that go with it.
@ -165,6 +198,8 @@ pub struct Source {
pub url: Url,
pub headers: HeaderMap,
access: Option<Arc<Access>>,
/// For a link that isn't HTTP.
remote: Option<Arc<Remote>>,
}
/// Redirects followed.
@ -173,10 +208,11 @@ 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() {
let remote = Remote::of(&url).map(Arc::new);
if !(remote.is_some() || matches!(url.scheme(), "http" | "https")) || url.host_str().is_none_or(str::is_empty) {
return Err(Error::Link);
}
Ok(Source { url, headers: HeaderMap::new(), access: None })
Ok(Source { url, headers: HeaderMap::new(), access: None, remote })
}
/// Adds headers, skipping what isn't valid and what the engine sets itself.
@ -208,7 +244,19 @@ impl Source {
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, access: self.access.clone() }
Source { url: url.clone(), headers, access: self.access.clone(), remote: self.remote.clone() }
}
pub(crate) fn remote(&self) -> Option<&Remote> {
self.remote.as_deref()
}
/// For a link that isn't HTTP.
pub(crate) async fn way(&self, client: &Client) -> Result<Way> {
match &self.access {
Some(access) => access.way(&self.url).await,
None => Ok(Way { client: client.clone(), proxy: None, login: None, key: None }),
}
}
async fn get(&self, client: &Client, range: Option<String>, if_range: Option<&HeaderValue>, stop: &mut Stop) -> Result<Response> {
@ -219,6 +267,9 @@ impl Source {
}
async fn follow(&self, client: &Client, range: Option<&str>, if_range: Option<&HeaderValue>) -> Result<Response> {
if let Some(remote) = &self.remote {
return remote.respond(client, self, range).await;
}
let mut here = self.clone();
for _ in 0..=HOPS {
let request = |client: &Client, headers: &HeaderMap| -> RequestBuilder {
@ -426,7 +477,7 @@ mod tests {
assert_eq!(moved.len(), 1, "{other}");
assert!(moved.contains_key(header::REFERER));
}
for bad in ["ftp://h/f", "file:///etc/passwd", "no link", "http:///"] {
for bad in ["gopher://h/f", "sftp:///f", "file:///etc/passwd", "no link", "http:///"] {
assert!(matches!(Source::new(bad), Err(Error::Link)), "{bad}");
}
}

View file

@ -7,7 +7,7 @@ use super::*;
use crate::adapt::Adapt;
use crate::disk::PartialFile;
use crate::host::{Hosts, Member, Permit};
use crate::model::Part;
use crate::model::{ErrorKind, Part};
use crate::part::LivePart;
use crate::segment::{self, Pick, View};
use std::hash::{BuildHasher, RandomState};
@ -102,6 +102,8 @@ fn weigh(e: &Error) -> Weight {
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::Conn { kind: ErrorKind::Busy | ErrorKind::Refused, .. } => Weight::Refused { again: true },
Error::Conn { kind, .. } if kind.of_network() || *kind == ErrorKind::Server => Weight::Broken,
Error::Net(e) if e.is_connect() => Weight::Refused { again: true },
Error::Net(_) => Weight::Broken,
_ => Weight::Fatal,

View file

@ -7,9 +7,11 @@ pub mod cookie;
pub mod disk;
pub mod error;
pub mod events;
mod ftp;
pub mod host;
pub mod http;
pub mod limit;
pub mod listing;
pub mod logging;
pub mod manager;
pub mod model;
@ -23,11 +25,13 @@ pub mod relink;
pub mod secret;
pub mod segment;
pub mod settings;
pub mod sftp;
pub mod site;
pub mod snapshot;
pub mod speed;
pub mod store;
pub mod strings;
pub mod tls;
mod transport;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

238
crates/core/src/listing.rs Normal file
View file

@ -0,0 +1,238 @@
//! What a folder on a server holds, whichever way it was asked for. (D-050)
use crate::http::{Client, Result, Source, Stop};
use crate::model::Time;
use crate::transport;
use chrono::{DateTime, Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime, Utc};
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_encode};
use regex::bytes::{Captures, Regex};
use std::sync::LazyLock;
use url::Url;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
File,
Folder,
/// To a file or a folder: which one shows when it is opened.
Link,
/// Nothing that can be downloaded.
Other,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
/// For the eye: not safe as a file name.
pub name: String,
pub kind: Kind,
pub size: Option<u64>,
/// As good as the server tells: some give no year or no time zone.
pub modified: Option<Time>,
/// Ends with a slash for a folder. Keeps the bytes that `name` can't show.
pub url: Url,
}
/// The folder at the source's link, in the server's order. FTP, FTPS and SFTP only.
pub async fn list(client: &Client, source: &Source, stop: &mut Stop) -> Result<Vec<Entry>> {
let found = transport::list(client, source, stop).await?;
Ok(found.into_iter().filter_map(|f| entry(&source.url, f)).collect())
}
/// One line of a listing.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Found {
pub name: Vec<u8>,
pub kind: Kind,
pub size: Option<u64>,
pub modified: Option<Time>,
}
/// None for what no server should send.
fn entry(folder: &Url, found: Found) -> Option<Entry> {
const PART: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');
let Found { name, kind, size, modified } = found;
if matches!(&name[..], b"" | b"." | b"..") || name.iter().any(|b| *b < 32 || matches!(b, b'/' | 127)) {
return None;
}
let mut url = folder.clone();
let slash = if kind == Kind::Folder { "/" } else { "" };
url.set_path(&format!("{}/{}{slash}", folder.path().trim_end_matches('/'), percent_encode(&name, PART)));
let name = String::from_utf8_lossy(&name).into_owned();
Some(Entry { name, kind, size: size.filter(|_| kind == Kind::File), modified, url })
}
/// Lines of the answer to MLSD (RFC 3659).
pub(crate) fn mlsd(text: &[u8]) -> Vec<Found> {
lines(text).filter_map(mlsd_line).collect()
}
fn mlsd_line(line: &[u8]) -> Option<Found> {
let space = line.iter().position(|b| *b == b' ')?;
let mut found = Found { name: line[space + 1..].into(), kind: Kind::Other, size: None, modified: None };
for fact in std::str::from_utf8(&line[..space]).ok()?.split(';') {
let Some((key, value)) = fact.split_once('=') else { continue };
let value = value.to_ascii_lowercase();
match key.to_ascii_lowercase().as_str() {
"type" => {
found.kind = match value.as_str() {
"file" => Kind::File,
"dir" => Kind::Folder,
"cdir" | "pdir" => return None,
link if link.contains("slink") || link.contains("symlink") => Kind::Link,
_ => Kind::Other,
}
}
"size" => found.size = value.parse().ok(),
"modify" => found.modified = stamp(&value),
_ => {}
}
}
Some(found)
}
/// `20251231235959`, with or without fractions: the time of MLSD and MDTM.
pub(crate) fn stamp(text: &str) -> Option<Time> {
let text = text.split('.').next()?.trim();
Some(NaiveDateTime::parse_from_str(text, "%Y%m%d%H%M%S").ok()?.and_utc().timestamp_millis())
}
/// Lines of the answer to LIST, as Unix, Windows and most others write them.
pub(crate) fn plain(text: &[u8], now: DateTime<Utc>) -> Vec<Found> {
lines(text).filter_map(|line| unix(line, now).or_else(|| dos(line))).collect()
}
fn lines(text: &[u8]) -> impl Iterator<Item = &[u8]> {
text.split(|b| *b == b'\n').map(|l| l.strip_suffix(b"\r").unwrap_or(l))
}
fn text<'a>(c: &'a Captures, i: usize) -> &'a str {
c.get(i).and_then(|m| std::str::from_utf8(m.as_bytes()).ok()).unwrap_or_default()
}
fn unix(line: &[u8], now: DateTime<Utc>) -> Option<Found> {
static LINE: LazyLock<Regex> = LazyLock::new(|| {
let date = r"([A-Z][a-z]{2})\s+(\d{1,2})\s+(\d{1,2}:\d{2}|\d{4})|(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})\S*(?:\s[+-]\d{4})?";
Regex::new(&format!(r"(?-u)^([-a-zA-Z])\S{{9,}}\s+(?:.*?\s)??(\d+)\s+(?:{date})\s(.+)$")).expect("it is fixed")
});
let c = LINE.captures(line)?;
let kind = match text(&c, 1) {
"-" => Kind::File,
"d" => Kind::Folder,
"l" => Kind::Link,
_ => Kind::Other,
};
let modified = if c.get(3).is_some() {
month_day(text(&c, 3), text(&c, 4), text(&c, 5), now)
} else {
NaiveDateTime::parse_from_str(&format!("{} {}", text(&c, 6), text(&c, 7)), "%Y-%m-%d %H:%M").ok()
};
let mut name = c.get(8)?.as_bytes();
if kind == Kind::Link
&& let Some(arrow) = name.windows(4).position(|w| w == b" -> ")
{
name = &name[..arrow];
}
let modified = modified.map(|m| m.and_utc().timestamp_millis());
Some(Found { name: name.into(), kind, size: text(&c, 2).parse().ok(), modified })
}
/// With a clock time instead of the year it is the last such day there was.
fn month_day(month: &str, day: &str, rest: &str, now: DateTime<Utc>) -> Option<NaiveDateTime> {
let month = 1 + "JanFebMarAprMayJunJulAugSepOctNovDec".as_bytes().chunks(3).position(|m| m == month.as_bytes())? as u32;
let day = day.parse().ok()?;
let Ok(time) = NaiveTime::parse_from_str(rest, "%H:%M") else {
return NaiveDate::from_ymd_opt(rest.parse().ok()?, month, day)?.and_hms_opt(0, 0, 0);
};
// The server's clock or zone may be ahead.
let latest = now.naive_utc() + Duration::days(1);
(0..=4).find_map(|ago| NaiveDate::from_ymd_opt(now.year() - ago, month, day).map(|d| d.and_time(time)).filter(|t| *t <= latest))
}
fn dos(line: &[u8]) -> Option<Found> {
static LINE: LazyLock<Regex> = LazyLock::new(|| {
let line = r"(?-u)^(\d\d)-(\d\d)-(\d{2,4})\s+(\d\d):(\d\d)\s*([AP]M)?\s+(<[A-Z]+>|\d+)\s+(?:\[[^\]]*\]\s)?(.+)$";
Regex::new(line).expect("it is fixed")
});
let c = LINE.captures(line)?;
let number = |i| text(&c, i).parse::<u32>().ok();
let year = number(3).map(|y| if y < 70 { 2000 + y } else if y < 100 { 1900 + y } else { y });
let hour = match text(&c, 6) {
"PM" => number(4)? % 12 + 12,
"AM" => number(4)? % 12,
_ => number(4)?,
};
let modified = NaiveDate::from_ymd_opt(year? as i32, number(1)?, number(2)?).and_then(|d| d.and_hms_opt(hour, number(5)?, 0));
let kind = match text(&c, 7) {
"<DIR>" => Kind::Folder,
other if other.starts_with('<') => Kind::Link,
_ => Kind::File,
};
let modified = modified.map(|m| m.and_utc().timestamp_millis());
Some(Found { name: c.get(8)?.as_bytes().into(), kind, size: text(&c, 7).parse().ok(), modified })
}
#[cfg(test)]
mod tests {
use super::*;
fn at(text: &str) -> Option<Time> {
stamp(text)
}
fn found(name: &str, kind: Kind, size: Option<u64>, modified: Option<Time>) -> Found {
Found { name: name.into(), kind, size, modified }
}
#[test]
fn mlsd_lines() {
let text = "type=cdir;modify=20250101000000; .\r\nType=file;Size=25;Modify=20251231235959.123;UNIX.mode=0644; a b.iso\r\n\
type=dir; sub\r\ntype=OS.unix=slink:/x; l\r\ntype=OS.unix=chr; c\r\nnonsense\r\n";
let expected = [
found("a b.iso", Kind::File, Some(25), at("20251231235959")),
found("sub", Kind::Folder, None, None),
found("l", Kind::Link, None, None),
found("c", Kind::Other, None, None),
];
assert_eq!(mlsd(text.as_bytes()), expected);
}
#[test]
fn list_lines() {
let now = stamp("20250310120000").and_then(DateTime::from_timestamp_millis).unwrap();
let one = |line: &str| plain(line.as_bytes(), now).pop();
let file = |name, size, time| Some(found(name, Kind::File, Some(size), at(time)));
assert_eq!(one("total 8"), None);
assert_eq!(one("-rw-r--r-- 1 ftp ftp 1234 Mar 1 12:30 a b.iso"), file("a b.iso", 1234, "20250301123000"));
assert_eq!(one("-rw-r--r-- 1 ftp ftp 1234 Nov 30 12:30 lead\r"), file(" lead", 1234, "20241130123000"));
assert_eq!(one("-rw-r--r--+ 1 a group 5000000000 Feb 29 2024 x"), file("x", 5_000_000_000, "20240229000000"));
assert_eq!(one("-rw-r--r-- 1 1234 May 4 2023 no owner"), file("no owner", 1234, "20230504000000"));
assert_eq!(one("-rw-r--r-- 1 u g 7 2024-05-04 10:11 iso date"), file("iso date", 7, "20240504101100"));
assert_eq!(one("-rw-r--r-- 1 u g 7 2024-05-04 10:11:12.000 +0000 full"), file("full", 7, "20240504101100"));
// Tomorrow there, today here.
assert_eq!(one("-rw-r--r-- 1 u g 7 Mar 11 02:00 x").unwrap().modified, at("20250311020000"));
assert_eq!(one("-rw-r--r-- 1 u g 7 Feb 29 02:00 x").unwrap().modified, at("20240229020000"));
assert_eq!(one("drwxr-xr-x 2 u g 4096 Jan 1 2020 2021").unwrap(), found("2021", Kind::Folder, Some(4096), at("20200101000000")));
assert_eq!(one("lrwxrwxrwx 1 u g 4 Jan 1 2020 now -> old/x").unwrap(), found("now", Kind::Link, Some(4), at("20200101000000")));
assert_eq!(one("crw-rw---- 1 u g 8, 0 Jan 1 2020 tty").unwrap().kind, Kind::Other);
assert_eq!(one("02-03-24 01:05PM <DIR> My Docs").unwrap(), found("My Docs", Kind::Folder, None, at("20240203130500")));
assert_eq!(one("02-03-2024 12:05AM 1048576 a.zip"), file("a.zip", 1 << 20, "20240203000500"));
assert_eq!(one("02-03-24 13:05 <JUNCTION> j [C:\\x]").unwrap().kind, Kind::Link);
for odd in ["", "-rw-r--r--", "drwx------ Jan", "99-99-99 99:99 <DIR> x", "\u{0}\u{ff}"] {
plain(odd.as_bytes(), now);
}
// Not UTF-8.
assert_eq!(plain(b"-rw-r--r-- 1 u g 7 May 4 2023 caf\xe9", now)[0].name, b"caf\xe9");
}
#[test]
fn entries_stay_in_their_folder() {
let folder = Url::parse("sftp://h:22/a%20b/").unwrap();
let of = |name: &[u8], kind| entry(&folder, Found { name: name.into(), kind, size: Some(1), modified: None });
for bad in [&b""[..], b".", b"..", b"a/b", b"../x", b"a\nb", b"a\0"] {
assert_eq!(of(bad, Kind::File), None);
}
assert_eq!(of(b"x:y#?%.iso", Kind::File).unwrap().url.as_str(), "sftp://h:22/a%20b/x%3Ay%23%3F%25.iso");
let sub = of(b"caf\xe9", Kind::Folder).unwrap();
assert_eq!((sub.url.as_str(), sub.name.as_str(), sub.size), ("sftp://h:22/a%20b/caf%E9/", "caf\u{fffd}", None));
assert_eq!(entry(&Url::parse("ftp://h").unwrap(), found("x", Kind::File, None, None)).unwrap().url.as_str(), "ftp://h/x");
}
}

View file

@ -75,6 +75,11 @@ impl Paths {
self.data.join("medlar.db")
}
/// The keys of SSH servers.
pub fn known_hosts(&self) -> PathBuf {
self.data.join("known_hosts")
}
pub fn log(&self) -> PathBuf {
self.state.join("medlar.log")
}

View file

@ -5,7 +5,7 @@ use crate::net_state::Bus;
use crate::site::Pattern;
use std::net::IpAddr;
use std::time::Duration;
use url::{Host, Url};
use url::Url;
/// A proxy setting: `system`, `direct`, or the proxy as `http://host:port`, `https://…` or `socks5://…`, without a login.
#[derive(Debug, Clone, PartialEq, Eq)]
@ -58,11 +58,8 @@ pub fn bypassed<S: AsRef<str>>(list: &[S], url: &Url) -> bool {
}
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,
};
// As text: the host of an `sftp` link is nothing more.
let Some(Ok(ip)) = url.host_str().map(|h| h.trim_matches(['[', ']']).parse::<IpAddr>()) else { 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,
@ -75,7 +72,11 @@ fn in_network(url: &Url, net: &str, bits: &str) -> bool {
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 own = match url.scheme() {
"https" => get("https_proxy"),
"http" => env("http_proxy").filter(|v| !v.is_empty()),
_ => None,
};
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();
@ -96,7 +97,7 @@ fn below(entry: &str) -> String {
/// 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 asked = format!("{}/", crate::site::place(url));
let ask = async {
let bus = bus.connect().await.ok()??;
let path = "/org/freedesktop/portal/desktop";

View file

@ -0,0 +1,165 @@
//! The keys SSH servers had when the user said yes to them, in a file like OpenSSH's `known_hosts`. (D-051)
use russh::keys::{Algorithm, HashAlg, PublicKey};
use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::path::PathBuf;
use std::sync::Mutex;
#[derive(Debug, Default)]
pub struct HostKeys {
/// None keeps them until the program ends.
file: Option<PathBuf>,
memory: Mutex<String>,
refused: Mutex<HashMap<String, HostKey>>,
}
/// A key that was refused. The user decides with `fingerprint` before their eyes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostKey {
/// As in the file: `host`, or `[host]:port` beside port 22.
pub host: String,
/// `SHA256:…`, as `ssh` shows it.
pub fingerprint: String,
/// `ssh-ed25519`, `ssh-rsa`…
pub algorithm: String,
/// The server had another key before: someone may be in between.
pub changed: bool,
line: String,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Check {
Known,
New,
Changed,
}
impl HostKeys {
pub fn new(file: Option<PathBuf>) -> HostKeys {
HostKeys { file, ..HostKeys::default() }
}
/// The key last refused for a server.
pub fn refused(&self, host: &str, port: u16) -> Option<HostKey> {
self.refused.lock().unwrap().get(&name(host, port)).cloned()
}
/// The user said yes. Other keys of the server count no longer.
pub fn accept(&self, key: &HostKey) -> io::Result<()> {
let mut memory = self.memory.lock().unwrap();
let old = self.read(&memory)?;
let mut text = String::new();
for line in old.lines().filter(|l| hosts(l).is_none_or(|mut names| !names.any(|n| n == key.host))) {
text += line;
text.push('\n');
}
text += &key.line;
text.push('\n');
match &self.file {
Some(file) => {
let new = file.with_extension("new");
let mut out = OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&new)?;
out.write_all(text.as_bytes())?;
out.sync_all()?;
fs::rename(&new, file)?;
}
None => *memory = text,
}
self.refused.lock().unwrap().remove(&key.host);
Ok(())
}
pub(super) fn check(&self, host: &str, port: u16, key: &PublicKey) -> Check {
let known = self.known(host, port);
if known.iter().any(|k| k.key_data() == key.key_data()) {
return Check::Known;
}
let host = name(host, port);
// Without the comment, which is the server's.
let bare = PublicKey::from(key.key_data().clone()).to_openssh().unwrap_or_default();
let refused = HostKey {
fingerprint: key.fingerprint(HashAlg::Sha256).to_string(),
algorithm: key.algorithm().to_string(),
// Also when it is of another kind: the old key is still the one that was trusted.
changed: !known.is_empty(),
line: format!("{host} {bare}"),
host: host.clone(),
};
self.refused.lock().unwrap().insert(host, refused);
if known.is_empty() { Check::New } else { Check::Changed }
}
/// Of the keys a server is known by.
pub(super) fn algorithms(&self, host: &str, port: u16) -> Vec<Algorithm> {
self.known(host, port).iter().map(|k| k.algorithm()).collect()
}
fn known(&self, host: &str, port: u16) -> Vec<PublicKey> {
// Nothing is trusted when it can't be read.
let text = self.read(&self.memory.lock().unwrap()).unwrap_or_default();
let host = name(host, port);
let ours = text.lines().filter(|l| hosts(l).is_some_and(|mut names| names.any(|n| n == host)));
ours.filter_map(|l| PublicKey::from_openssh(l.split_once(char::is_whitespace)?.1.trim()).ok()).collect()
}
fn read(&self, memory: &str) -> io::Result<String> {
let Some(file) = &self.file else { return Ok(memory.into()) };
match fs::read_to_string(file) {
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(String::new()),
text => text,
}
}
}
fn name(host: &str, port: u16) -> String {
let host = host.to_ascii_lowercase();
if port == 22 { host } else { format!("[{host}]:{port}") }
}
/// Whom a line is about. None for comments and marks.
fn hosts(line: &str) -> Option<impl Iterator<Item = &str>> {
let first = line.split_whitespace().next()?;
(!first.starts_with(['#', '@'])).then(|| first.split(','))
}
#[cfg(test)]
mod tests {
use super::*;
const A: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJdD7y3aLq454yWBdwLWbieU1ebz9/cu7/QEXn9OIeZJ";
const B: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILIG2T/B0l0gaqj3puu510tu9N1OkQ4znY3LYuEm5zCF";
#[test]
fn asked_once_and_never_changed_silently() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("known_hosts");
fs::write(&file, format!("# mine\n\nother,third {A}\n")).unwrap();
let (a, b) = (PublicKey::from_openssh(A).unwrap(), PublicKey::from_openssh(B).unwrap());
for keys in [HostKeys::new(Some(file.clone())), HostKeys::default()] {
assert_eq!(keys.check("H", 22, &a), Check::New);
let refused = keys.refused("h", 22).unwrap();
assert!(!refused.changed && refused.fingerprint.starts_with("SHA256:"));
keys.accept(&refused).unwrap();
assert_eq!(keys.refused("h", 22), None);
assert_eq!(keys.check("h", 22, &a), Check::Known);
// Another port is another server.
assert_eq!(keys.check("h", 2222, &a), Check::New);
assert_eq!(keys.check("h", 22, &b), Check::Changed);
let refused = keys.refused("h", 22).unwrap();
assert!(refused.changed);
assert_eq!(keys.check("h", 22, &a), Check::Known);
keys.accept(&refused).unwrap();
assert_eq!((keys.check("h", 22, &b), keys.check("h", 22, &a)), (Check::Known, Check::Changed));
}
let keys = HostKeys::new(Some(file.clone()));
assert_eq!((keys.check("third", 22, &a), keys.check("h", 22, &b)), (Check::Known, Check::Known));
assert!(fs::read_to_string(&file).unwrap().starts_with("# mine"));
// Can't be read: nothing is trusted, nothing is lost.
let keys = HostKeys::new(Some(dir.path().into()));
assert_eq!(keys.check("h", 22, &a), Check::New);
assert!(keys.accept(&keys.refused("h", 22).unwrap()).is_err());
}
}

351
crates/core/src/sftp/mod.rs Normal file
View file

@ -0,0 +1,351 @@
//! SFTP. A path counts from the root; `/~/` in front makes it count from the login's home. (D-050, D-051)
mod known;
pub use known::{HostKey, HostKeys};
use crate::http::{Error, Result};
use crate::listing::{Found, Kind};
use crate::model::ErrorKind;
use crate::transport::{Stat, Transport, Way, dial, host};
use bytes::Bytes;
use known::Check;
use russh::client::{self, AuthResult, Handle, KeyboardInteractiveAuthResponse};
use russh::keys::{self, PrivateKeyWithHashAlg, PublicKeyOrCertificate};
use russh::{Channel, ChannelMsg};
use russh_sftp::client::rawsession::RawSftpSession;
use russh_sftp::client::{Config, error::Error as SftpError};
use russh_sftp::protocol::{FileAttributes, FileMode, OpenFlags, SftpHandle, StatusCode};
use std::borrow::Cow;
use std::collections::VecDeque;
use std::path::Path;
use std::sync::Arc;
use tokio::task::JoinHandle;
use url::Url;
/// What every server gives out in one go.
const PIECE: u32 = 32 * 1024;
/// Reads under way at the same time.
const MOST: usize = 64;
pub(crate) struct Sftp {
/// The connection ends with it.
_ssh: Handle<Checker>,
raw: Arc<RawSftpSession>,
reading: Option<Reading>,
}
struct Reading {
handle: SftpHandle,
/// Where the next piece to ask for begins, and the end.
at: u64,
end: Option<u64>,
/// In the order of the file.
asked: VecDeque<Piece>,
/// How many to ask for at once. More when they come too late; a limited download never needs more than a few.
wide: usize,
}
struct Piece {
at: u64,
len: u32,
data: JoinHandle<Result<Vec<u8>>>,
}
impl Drop for Piece {
fn drop(&mut self) {
self.data.abort();
}
}
/// Compares the server's key with the one it had before.
struct Checker {
trust: Arc<crate::tls::Trust>,
host: String,
port: u16,
}
impl client::Handler for Checker {
type Error = Error;
async fn check_server_key(&mut self, key: &PublicKeyOrCertificate) -> Result<bool> {
// Nobody is asked to vouch for servers, so certificates are never asked for.
let PublicKeyOrCertificate::PublicKey { key, .. } = key else { return Ok(false) };
match self.trust.host_keys.check(&self.host, self.port, key) {
Check::Known => Ok(true),
Check::New => Err(Error::because(ErrorKind::Tls, "error.host_key.new")),
Check::Changed => Err(Error::because(ErrorKind::Tls, "error.host_key.changed")),
}
}
}
impl From<russh::Error> for Error {
fn from(e: russh::Error) -> Error {
match e {
russh::Error::IO(e) => e.into(),
russh::Error::NoCommonAlgo { .. } => Error::because(ErrorKind::Tls, "error.tls.old"),
russh::Error::ChannelOpenFailure(_) => Error::because(ErrorKind::Busy, "error.busy.connections"),
russh::Error::UnknownKey | russh::Error::WrongServerSig => Error::conn(ErrorKind::Tls),
_ => Error::conn(ErrorKind::Cut),
}
}
}
impl From<SftpError> for Error {
fn from(e: SftpError) -> Error {
match e {
SftpError::Status(status) => match status.status_code {
StatusCode::NoSuchFile => Error::because(ErrorKind::NotFound, "error.not_found.plain"),
StatusCode::PermissionDenied => Error::because(ErrorKind::Forbidden, "error.forbidden.plain"),
StatusCode::NoConnection | StatusCode::ConnectionLost => Error::conn(ErrorKind::Cut),
_ => Error::because(ErrorKind::Server, "error.server.plain"),
},
SftpError::Timeout => Error::Idle,
SftpError::UnexpectedPacket | SftpError::Limited(_) => Error::BadReply("no proper SFTP".into()),
SftpError::IO(_) | SftpError::UnexpectedBehavior(_) => Error::conn(ErrorKind::Cut),
}
}
}
impl Transport for Sftp {
async fn connect(way: Way, url: &Url, _known: bool) -> Result<Sftp> {
let user = way.login.as_ref().map(|l| l.user.clone()).filter(|u| !u.is_empty()).ok_or(Error::conn(ErrorKind::Login))?;
let (name, port) = (host(url)?, url.port().unwrap_or(22));
let (stream, _) = dial(&way, &name, port).await?;
let trust = way.client.trust().clone();
let mut preferred = russh::Preferred::DEFAULT;
// Or the server shows another of its keys, one that isn't known.
let mut algorithms = preferred.key.into_owned();
let known = trust.host_keys.algorithms(&name, port);
algorithms.sort_by_key(|a| !known.iter().any(|k| k == a || (is_rsa(k) && is_rsa(a))));
preferred.key = Cow::Owned(algorithms);
let config = client::Config { preferred, nodelay: true, ..client::Config::default() };
let checker = Checker { trust, host: name, port };
let client = way.client.clone();
let mut ssh = client.wait(client::connect_stream(Arc::new(config), stream, checker)).await?;
sign_in(&mut ssh, &way, user).await?;
let open = async {
let mut channel = ssh.channel_open_session().await?;
channel.request_subsystem(true, "sftp").await?;
started(&mut channel).await?;
Ok::<_, Error>(channel)
};
let channel = client.wait(open).await?;
let seconds = client.idle_timeout().as_secs().max(1);
let config = Config { max_concurrent_reads: MOST, request_timeout_secs: seconds, ..Config::default() };
let raw = RawSftpSession::new_with_config(channel.into_stream(), config);
raw.init().await?;
Ok(Sftp { _ssh: ssh, raw: Arc::new(raw), reading: None })
}
fn path(url: &Url) -> Result<Vec<u8>> {
let path: Vec<u8> = percent_encoding::percent_decode_str(url.path()).collect();
let home = path.strip_prefix(b"/~").filter(|rest| rest.is_empty() || rest[0] == b'/');
let path = match home {
Some(rest) => rest.iter().position(|b| *b != b'/').map_or(b".".to_vec(), |at| rest[at..].to_vec()),
None if path.is_empty() => b"/".to_vec(),
None => path,
};
if path.contains(&0) { Err(Error::Link) } else { Ok(path) }
}
async fn stat(&mut self, path: &[u8]) -> Result<Stat> {
let FileAttributes { size, mtime, permissions, .. } = self.raw.stat(path).await?.attrs;
if kind(permissions).is_some_and(|k| k != Kind::File) {
return Err(Error::because(ErrorKind::NotFound, "error.not_found.plain"));
}
Ok(Stat { size, modified: mtime.map(|t| i64::from(t) * 1000) })
}
async fn resumes(&mut self) -> Result<bool> {
Ok(true)
}
async fn open(&mut self, path: &[u8], first: u64, len: Option<u64>) -> Result<()> {
let handle = self.raw.open(path, OpenFlags::READ, FileAttributes::empty()).await?.handle;
self.reading = Some(Reading { handle, at: first, end: len.map(|len| first + len), asked: VecDeque::new(), wide: 2 });
Ok(())
}
async fn next(&mut self) -> Result<Option<Bytes>> {
let Some(r) = &mut self.reading else { return Ok(None) };
while r.asked.len() < r.wide && r.end.is_none_or(|end| r.at < end) {
let len = r.end.map_or(PIECE, |end| (end - r.at).min(PIECE.into()) as u32);
let work = read(self.raw.clone(), r.handle.clone(), r.at, len);
r.asked.push_back(Piece { at: r.at, len, data: tokio::spawn(work) });
r.at += u64::from(len);
}
let Some(mut piece) = r.asked.pop_front() else { return self.close().await };
if !piece.data.is_finished() {
r.wide = (r.wide + 1).min(MOST);
}
let data = (&mut piece.data).await.unwrap_or(Err(Error::conn(ErrorKind::Cut)))?;
if (data.len() as u64) < u64::from(piece.len) {
// The file ends here.
r.asked.clear();
r.end = Some(piece.at);
r.at = piece.at;
if data.is_empty() {
return self.close().await;
}
}
Ok(Some(data.into()))
}
fn reusable(&self) -> bool {
self.reading.is_none()
}
async fn list(&mut self, path: &[u8]) -> Result<Vec<Found>> {
let handle = self.raw.opendir(path).await?.handle;
let mut found = vec![];
loop {
match self.raw.readdir(handle.clone()).await {
Ok(names) => found.extend(names.files.into_iter().map(|f| Found {
name: f.filename.to_vec(),
kind: kind(f.attrs.permissions).unwrap_or(Kind::Other),
size: f.attrs.size,
modified: f.attrs.mtime.map(|t| i64::from(t) * 1000),
})),
Err(SftpError::Status(s)) if s.status_code == StatusCode::Eof => break,
Err(e) => return Err(e.into()),
}
}
let _ = self.raw.close(handle).await;
Ok(found)
}
}
impl Sftp {
async fn close(&mut self) -> Result<Option<Bytes>> {
if let Some(r) = self.reading.take() {
self.raw.close(r.handle).await?;
}
Ok(None)
}
}
/// `len` bytes, or fewer at the end of the file.
async fn read(raw: Arc<RawSftpSession>, handle: SftpHandle, at: u64, len: u32) -> Result<Vec<u8>> {
let mut all = vec![];
while (all.len() as u32) < len {
let got = all.len() as u32;
match raw.read(handle.clone(), at + u64::from(got), len - got).await {
Ok(data) if data.data.is_empty() => break,
Ok(data) if data.data.len() as u32 > len - got => return Err(Error::BadReply("more than asked for".into())),
// Servers may give less than asked for.
Ok(data) if all.is_empty() => all = data.data,
Ok(data) => all.extend_from_slice(&data.data),
Err(SftpError::Status(s)) if s.status_code == StatusCode::Eof => break,
Err(e) => return Err(e.into()),
}
}
Ok(all)
}
fn is_rsa(a: &keys::Algorithm) -> bool {
matches!(a, keys::Algorithm::Rsa { .. })
}
/// None when the server doesn't say.
fn kind(permissions: Option<u32>) -> Option<Kind> {
let mode = permissions? & 0xF000;
Some(if mode == FileMode::REG.bits() {
Kind::File
} else if mode == FileMode::DIR.bits() {
Kind::Folder
} else if mode == FileMode::LNK.bits() {
Kind::Link
} else if mode == 0 {
return None;
} else {
Kind::Other
})
}
async fn started(channel: &mut Channel<client::Msg>) -> Result<()> {
loop {
match channel.wait().await {
Some(ChannelMsg::Success) => return Ok(()),
Some(ChannelMsg::Failure) => return Err(Error::because(ErrorKind::Rejected, "error.rejected.plain")),
Some(_) => {}
None => return Err(Error::conn(ErrorKind::Cut)),
}
}
}
/// With the key file if there is one, then with the password.
async fn sign_in(ssh: &mut Handle<Checker>, way: &Way, user: String) -> Result<()> {
let client = &way.client;
let mut password = way.login.as_ref().map(|l| l.password.clone()).filter(|p| !p.is_empty());
if let Some(file) = &way.key {
let (key, locked) = load(file, password.clone()).await?;
if locked {
// It was the passphrase, which is none of the server's business.
password = None;
}
let hash = client.wait(ssh.best_supported_rsa_hash()).await?.flatten();
let key = PrivateKeyWithHashAlg::new(Arc::new(key), hash);
if client.wait(ssh.authenticate_publickey(user.clone(), key)).await?.success() {
return Ok(());
}
}
let Some(password) = password else { return Err(Error::conn(ErrorKind::Login)) };
match client.wait(ssh.authenticate_password(user.clone(), password.clone())).await? {
AuthResult::Success => return Ok(()),
AuthResult::Failure { remaining_methods, .. } if !remaining_methods.contains(&russh::MethodKind::KeyboardInteractive) => {
return Err(Error::conn(ErrorKind::Login));
}
AuthResult::Failure { .. } => {}
}
// Some ask for the password as a question.
let mut reply = client.wait(ssh.authenticate_keyboard_interactive_start(user, None)).await?;
for _ in 0..4 {
match reply {
KeyboardInteractiveAuthResponse::Success => return Ok(()),
KeyboardInteractiveAuthResponse::Failure { .. } => break,
// Anything but one hidden answer isn't the password.
KeyboardInteractiveAuthResponse::InfoRequest { prompts, .. } => {
if prompts.len() > 1 || prompts.iter().any(|p| p.echo) {
break;
}
let answers = prompts.iter().map(|_| password.clone()).collect();
reply = client.wait(ssh.authenticate_keyboard_interactive_respond(answers)).await?;
}
}
}
Err(Error::conn(ErrorKind::Login))
}
/// Also tells whether the password was the key's.
async fn load(file: &Path, password: Option<String>) -> Result<(keys::PrivateKey, bool)> {
let file = file.to_path_buf();
let loading = tokio::task::spawn_blocking(move || match keys::load_secret_key(&file, None) {
Err(_) if password.is_some() => keys::load_secret_key(&file, password.as_deref()).map(|key| (key, true)),
key => key.map(|key| (key, false)),
});
// The error may name the file.
let wrong = || Error::because(ErrorKind::Login, "error.login.key");
loading.await.map_err(|_| wrong())?.map_err(|_| wrong())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn paths() {
let path = |url: &str| Sftp::path(&Url::parse(url).unwrap()).ok().map(|p| String::from_utf8(p).unwrap());
for (url, expected) in [
("sftp://h/a%20b/c", "/a b/c"),
("sftp://h/~/c", "c"),
("sftp://h/~//c", "c"),
("sftp://h/~", "."),
("sftp://h/~bob/c", "/~bob/c"),
("sftp://h", "/"),
] {
assert_eq!(path(url).as_deref(), Some(expected), "{url}");
}
assert_eq!(path("sftp://h/%00"), None);
}
}

View file

@ -9,6 +9,7 @@ use crate::proxy::{self, Choice};
use crate::secret::{Secret, Secrets};
use crate::settings::Settings;
use crate::tls::Trust;
use crate::transport::Way;
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue, SET_COOKIE, USER_AGENT};
use reqwest::{RequestBuilder, StatusCode};
use serde::{Deserialize, Serialize};
@ -38,6 +39,8 @@ pub struct Site {
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>,
/// File with the private key for SFTP. The login's password is its passphrase.
pub key: Option<PathBuf>,
}
/// `Site::pattern`, understood.
@ -99,6 +102,7 @@ pub struct Rules {
pub user_agent: Option<String>,
pub proxy: Option<String>,
pub folder: Option<PathBuf>,
pub key: Option<PathBuf>,
}
pub fn rules(sites: &[Site], url: &Url) -> Rules {
@ -106,13 +110,14 @@ pub fn rules(sites: &[Site], url: &Url) -> Rules {
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();
let Site { secret, max_connections, speed_limit, user_agent, proxy, folder, key, .. } = 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.key = key.filter(|_| pattern.owned()).or(rules.key);
}
rules
}
@ -120,7 +125,13 @@ pub fn rules(sites: &[Site], url: &Url) -> 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())
place(from) == place(to) || (upgraded && from.host() == to.host())
}
/// Scheme, host and port. Also for schemes that `Url::origin` doesn't know.
pub(crate) fn place(url: &Url) -> String {
let port = url.port().map(|p| format!(":{p}")).unwrap_or_default();
format!("{}://{}{port}", url.scheme(), url.host_str().unwrap_or_default().to_ascii_lowercase())
}
struct Wide {
@ -239,7 +250,7 @@ impl Sites {
if self.bus == Bus::Off {
return None;
}
let key = url.origin().ascii_serialization();
let key = place(url);
if let Some((at, found)) = self.wide.lock().unwrap().desktop.get(&key)
&& at.elapsed() < Duration::from_secs(60)
{
@ -250,17 +261,22 @@ impl Sites {
found
}
/// The proxy with its login.
async fn address(&self, proxy: Option<Url>) -> Option<Url> {
let url = proxy.as_ref()?;
let known = url.username().is_empty().then(|| proxy::secret_name(url));
let login = match known {
Some(name) => self.secrets.load(&name).await.and_then(|s| s.login),
None => None,
};
login.map(|login| proxy::with_login(url.clone(), &login)).or(proxy)
}
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 address = self.address(proxy.clone()).await;
let client = http::client_with(&self.options, &self.trust, address)?;
Ok(self.wide.lock().unwrap().clients.entry(proxy).or_insert(client).clone())
}
@ -305,6 +321,16 @@ impl Access {
self.sites.rules(url)
}
/// For a connection that isn't HTTP.
pub(crate) async fn way(&self, url: &Url) -> Result<Way> {
let rules = self.rules(url);
let proxy = self.sites.proxy(url, self.proxy.as_deref(), rules.proxy.as_deref()).await?;
let client = self.sites.client(proxy.clone()).await?;
let secret = self.secret(url, rules.secret).await;
let login = self.login.clone().filter(|_| same_site(&self.home, url)).or_else(|| secret.login.clone());
Ok(Way { client, proxy: self.sites.address(proxy).await, login, key: rules.key })
}
/// 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);
@ -322,7 +348,7 @@ impl Access {
for (name, value) in http::valid(&secret.headers) {
headers.entry(name).or_insert(value);
}
let key = url.origin().ascii_serialization();
let key = place(url);
let mut tried = false;
loop {
let mut request = request(&client, &headers);
@ -371,7 +397,7 @@ impl Access {
/// 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 host = place(url);
let mut loaded = self.loaded.lock().await;
if let Some(secret) = loaded.get(&(name.clone(), host.clone())) {
return secret.clone();

View file

@ -1,6 +1,7 @@
//! Who is trusted: the system's certificate authorities, and the certificates the user made an exception for.
use crate::auth::hex;
use crate::sftp::HostKeys;
use crate::site::Site;
use arc_swap::ArcSwap;
use rustls::client::WebPkiServerVerifier;
@ -17,11 +18,13 @@ pub struct Trust {
usual: Arc<dyn ServerCertVerifier>,
sites: ArcSwap<Vec<Site>>,
refused: Mutex<HashMap<String, String>>,
/// Of SSH servers, which have no certificates.
pub host_keys: HostKeys,
}
impl Trust {
/// With the system's roots, or only those of `certs` (DER, tests). Reads files.
pub(crate) fn new(provider: Arc<CryptoProvider>, certs: &[Vec<u8>]) -> Result<Trust, Error> {
pub(crate) fn new(provider: Arc<CryptoProvider>, certs: &[Vec<u8>], host_keys: HostKeys) -> Result<Trust, Error> {
let usual: Arc<dyn ServerCertVerifier> = if certs.is_empty() {
Arc::new(rustls_platform_verifier::Verifier::new(provider)?)
} else {
@ -33,7 +36,7 @@ impl Trust {
.build()
.map_err(|e| Error::General(e.to_string()))?
};
Ok(Trust { usual, sites: ArcSwap::default(), refused: Mutex::default() })
Ok(Trust { usual, sites: ArcSwap::default(), refused: Mutex::default(), host_keys })
}
pub(crate) fn set(&self, sites: Vec<Site>) {

View file

@ -0,0 +1,365 @@
//! Downloads over something else than HTTP. They answer the way a HTTP server does, so that parts, resume, limits and all else
//! are the same for them. (D-049)
use crate::auth::Login;
use crate::error::{proxy_wants_login, tls_why};
use crate::ftp::Ftp;
use crate::http::{Client, Error, Response, Result, Source, Stop, stopped};
use crate::listing::Found;
use crate::model::{ErrorKind, Time};
use crate::sftp::Sftp;
use ::http::{HeaderValue, Uri, header};
use base64::prelude::{BASE64_STANDARD, Engine};
use bytes::Bytes;
use chrono::DateTime;
use http_body::{Body, Frame};
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::client::legacy::connect::proxy::{SocksV5, Tunnel};
use reqwest::ResponseBuilderExt;
use std::error::Error as StdError;
use std::io;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tower_service::Service;
use url::{Host, Url};
/// An unused connection is kept for so long.
const IDLE: Duration = Duration::from_secs(10);
/// One connection, logged in.
pub(crate) trait Transport: Sized + Send + 'static {
/// `known`: the login worked a moment ago, so a refusal means too many connections.
fn connect(way: Way, url: &Url, known: bool) -> impl Future<Output = Result<Self>> + Send;
/// What the link names, as the server wants to hear it.
fn path(url: &Url) -> Result<Vec<u8>>;
fn stat(&mut self, path: &[u8]) -> impl Future<Output = Result<Stat>> + Send;
/// Whether reading can begin in the middle of a file.
fn resumes(&mut self) -> impl Future<Output = Result<bool>> + Send;
/// Begins to read, `len` bytes or to the end.
fn open(&mut self, path: &[u8], first: u64, len: Option<u64>) -> impl Future<Output = Result<()>> + Send;
/// None at the end of what was asked for.
fn next(&mut self) -> impl Future<Output = Result<Option<Bytes>>> + Send;
/// Can serve once more after that end.
fn reusable(&self) -> bool;
fn list(&mut self, path: &[u8]) -> impl Future<Output = Result<Vec<Found>>> + Send;
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Stat {
pub size: Option<u64>,
pub modified: Option<Time>,
}
/// How to get to a server and into it.
#[derive(Clone)]
pub(crate) struct Way {
pub client: Client,
/// With its login.
pub proxy: Option<Url>,
pub login: Option<Login>,
/// File with a private key.
pub key: Option<PathBuf>,
}
/// The connections of one download that wait for the next part.
pub(crate) enum Remote {
Ftp(Arc<Pool<Ftp>>),
Sftp(Arc<Pool<Sftp>>),
}
impl std::fmt::Debug for Remote {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("Remote")
}
}
impl Remote {
/// None for a scheme that isn't known here.
pub(crate) fn of(url: &Url) -> Option<Remote> {
match url.scheme() {
"ftp" | "ftps" | "ftpes" => Some(Remote::Ftp(Arc::default())),
"sftp" => Some(Remote::Sftp(Arc::default())),
_ => None,
}
}
/// What a HTTP server would answer. `range` is that of the HTTP request.
pub(crate) async fn respond(&self, client: &Client, source: &Source, range: Option<&str>) -> Result<Response> {
match self {
Remote::Ftp(pool) => respond(pool, client, source, range).await,
Remote::Sftp(pool) => respond(pool, client, source, range).await,
}
}
}
/// The folder at the source's link.
pub(crate) async fn list(client: &Client, source: &Source, stop: &mut Stop) -> Result<Vec<Found>> {
async fn of<T: Transport>(pool: &Pool<T>, client: &Client, source: &Source) -> Result<Vec<Found>> {
pool.connect(client, source).await?.list(&T::path(&source.url)?).await
}
let work = async {
match source.remote() {
Some(Remote::Ftp(pool)) => of(pool, client, source).await,
Some(Remote::Sftp(pool)) => of(pool, client, source).await,
None => Err(Error::Link),
}
};
tokio::select! {
_ = stopped(stop) => Err(Error::Stopped),
found = work => found,
}
}
pub(crate) struct Pool<T> {
idle: Mutex<Vec<(T, Instant)>>,
/// The login worked.
known: AtomicBool,
}
impl<T> Default for Pool<T> {
fn default() -> Self {
Pool { idle: Mutex::default(), known: AtomicBool::new(false) }
}
}
impl<T: Transport> Pool<T> {
fn take(&self) -> Option<T> {
let mut idle = self.idle.lock().unwrap();
idle.retain(|(_, since)| since.elapsed() < IDLE);
idle.pop().map(|(conn, _)| conn)
}
fn give(&self, conn: T) {
self.idle.lock().unwrap().push((conn, Instant::now()));
}
async fn connect(&self, client: &Client, source: &Source) -> Result<T> {
let mut way = source.way(client).await?;
if let (_, Some(login)) = crate::auth::take_login(source.url.as_str()) {
// The link names its user; the password may be known from elsewhere.
let named = way.login.take().filter(|l| l.user == login.user && login.password.is_empty());
way.login = Some(named.unwrap_or(login));
}
let conn = T::connect(way, &source.url, self.known.load(Ordering::Relaxed)).await?;
self.known.store(true, Ordering::Relaxed);
Ok(conn)
}
/// One that answers.
async fn ready(&self, client: &Client, source: &Source, path: &[u8]) -> Result<(T, Stat)> {
while let Some(mut conn) = self.take() {
// It may have been closed in the meantime.
if let Ok(stat) = conn.stat(path).await {
return Ok((conn, stat));
}
}
let mut conn = self.connect(client, source).await?;
let stat = conn.stat(path).await?;
Ok((conn, stat))
}
}
async fn respond<T: Transport>(pool: &Arc<Pool<T>>, client: &Client, source: &Source, range: Option<&str>) -> Result<Response> {
let path = T::path(&source.url)?;
let (mut conn, stat) = pool.ready(client, source, &path).await?;
let reply = ::http::Response::builder().url(source.url.clone()).header(header::ACCEPT_RANGES, "bytes");
let reply = match stat.modified.and_then(DateTime::from_timestamp_millis) {
Some(at) => reply.header(header::LAST_MODIFIED, at.format("%a, %d %b %Y %H:%M:%S GMT").to_string()),
None => reply,
};
let made = |reply: ::http::response::Builder, body| reply.body(body).map(Response::from).map_err(|_| Error::Link);
let asked = range.and_then(|r| r.strip_prefix("bytes=")?.split_once('-'));
let asked = asked.and_then(|(first, last)| Some((first.parse::<u64>().ok()?, last.parse::<u64>().ok())));
if let (Some((first, last)), Some(size)) = (asked, stat.size) {
if first >= size {
pool.give(conn);
let none = reqwest::Body::from(Bytes::new());
return made(reply.status(416).header(header::CONTENT_RANGE, format!("bytes */{size}")), none);
}
if conn.resumes().await? {
let last = last.unwrap_or(u64::MAX).min(size - 1);
let reading = Reading { path, first, len: (last + 1 < size).then_some(last + 1 - first) };
let reply = reply.status(206).header(header::CONTENT_RANGE, format!("bytes {first}-{last}/{size}"));
// A single byte is only a question, mostly: nobody reads it, and the connection stays.
return if first == last {
made(reply, Reply::later(pool, conn, reading))
} else {
conn.open(&reading.path, first, reading.len).await?;
made(reply.header(header::CONTENT_LENGTH, last + 1 - first), Reply::now(pool, conn))
};
}
}
conn.open(&path, 0, None).await?;
let reply = stat.size.map_or_else(|| ::http::Response::builder().url(source.url.clone()), |size| reply.header(header::CONTENT_LENGTH, size));
made(reply.status(200), Reply::now(pool, conn))
}
struct Reading {
path: Vec<u8>,
first: u64,
len: Option<u64>,
}
/// The body of a reply. One that nobody began to read gives its connection back.
struct Reply<T: Transport> {
pool: Arc<Pool<T>>,
waiting: Mutex<Option<(T, Reading)>>,
coming: Option<mpsc::Receiver<io::Result<Bytes>>>,
}
impl<T: Transport> Reply<T> {
fn now(pool: &Arc<Pool<T>>, conn: T) -> reqwest::Body {
let coming = Some(start(pool.clone(), conn, None));
reqwest::Body::wrap(Reply { pool: pool.clone(), waiting: Mutex::default(), coming })
}
fn later(pool: &Arc<Pool<T>>, conn: T, reading: Reading) -> reqwest::Body {
reqwest::Body::wrap(Reply { pool: pool.clone(), waiting: Mutex::new(Some((conn, reading))), coming: None })
}
}
// Nothing in it is pinned.
impl<T: Transport> Unpin for Reply<T> {}
impl<T: Transport> Body for Reply<T> {
type Data = Bytes;
type Error = io::Error;
fn poll_frame(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<io::Result<Frame<Bytes>>>> {
let this = self.get_mut();
if let Some((conn, reading)) = this.waiting.get_mut().unwrap().take() {
this.coming = Some(start(this.pool.clone(), conn, Some(reading)));
}
let Some(coming) = &mut this.coming else { return Poll::Ready(None) };
coming.poll_recv(cx).map(|piece| piece.map(|p| p.map(Frame::data)))
}
}
impl<T: Transport> Drop for Reply<T> {
fn drop(&mut self) {
if let Some((conn, _)) = self.waiting.get_mut().unwrap().take() {
self.pool.give(conn);
}
}
}
/// Reads until the end or until nobody listens any more.
fn start<T: Transport>(pool: Arc<Pool<T>>, mut conn: T, reading: Option<Reading>) -> mpsc::Receiver<io::Result<Bytes>> {
let (send, receive) = mpsc::channel(1);
tokio::spawn(async move {
let all = async {
if let Some(r) = reading {
conn.open(&r.path, r.first, r.len).await?;
}
while let Some(piece) = conn.next().await? {
if send.send(Ok(piece)).await.is_err() {
return Ok(false);
}
}
Ok::<_, Error>(conn.reusable())
};
let result = tokio::select! {
result = all => result,
_ = send.closed() => return,
};
match result {
Ok(true) => pool.give(conn),
Ok(false) => {}
// Nobody listens any more if this fails.
Err(e) => drop(send.send(Err(io::Error::other(format!("{e:?}")))).await),
}
});
receive
}
/// The host in a link, the way names are looked up: also where the `url` crate takes it as it is.
pub(crate) fn host(url: &Url) -> Result<String> {
let host = Host::parse(url.host_str().unwrap_or_default()).map_err(|_| Error::Link)?.to_string();
Ok(host.trim_matches(['[', ']']).into())
}
/// A connection, straight or through the proxy, and the host for more of them to the same server.
pub(crate) async fn dial(way: &Way, host: &str, port: u16) -> Result<(TcpStream, String)> {
let connecting = async {
let stream = match &way.proxy {
None => {
let found = tokio::net::lookup_host((host, port)).await.map_err(|_| Error::conn(ErrorKind::Dns))?;
TcpStream::connect(&found.collect::<Vec<_>>()[..]).await?
}
Some(proxy) => through(proxy, host, port).await?,
};
// Fails only when the connection is gone, which shows soon enough.
let _ = stream.set_nodelay(true);
let host = match &way.proxy {
// A name may stand for several servers.
None => stream.peer_addr()?.ip().to_string(),
Some(_) => host.into(),
};
Ok((stream, host))
};
tokio::time::timeout(way.client.connect_timeout(), connecting).await.unwrap_or(Err(Error::conn(ErrorKind::Timeout)))
}
async fn through(proxy: &Url, host: &str, port: u16) -> Result<TcpStream> {
let wrong = || Error::Proxy(None);
let uri = |text: String| text.parse::<Uri>().map_err(|_| wrong());
let literal = if host.contains(':') { format!("[{host}]") } else { host.into() };
let target = uri(format!("https://{literal}:{port}"))?;
let port = proxy.port_or_known_default().unwrap_or(1080);
let address = uri(format!("http://{}:{port}", proxy.host_str().unwrap_or_default()))?;
let (_, login) = crate::auth::take_login(proxy.as_str());
let mut connector = HttpConnector::new();
connector.enforce_http(false);
let stream = match proxy.scheme() {
"socks5h" => {
let mut proxy = SocksV5::new(address, connector);
if let Some(login) = login {
proxy = proxy.with_auth(login.user, login.password);
}
proxy.call(target).await.map_err(|e| refused(&e))?
}
"http" => {
let mut proxy = Tunnel::new(address, connector);
if let Some(login) = login {
proxy = proxy.with_auth(basic(&login));
}
proxy.call(target).await.map_err(|e| refused(&e))?
}
_ => return Err(wrong()),
};
Ok(stream.into_inner())
}
fn basic(login: &Login) -> HeaderValue {
let packed = BASE64_STANDARD.encode(format!("{}:{}", login.user, login.password));
HeaderValue::try_from(format!("Basic {packed}")).expect("plain letters")
}
fn refused(e: &(dyn StdError + 'static)) -> Error {
let mut all = std::iter::successors(Some(e), |&e| e.source());
if all.any(|e| proxy_wants_login(&e.to_string())) {
return Error::because(ErrorKind::Login, "error.login.proxy");
}
Error::conn(ErrorKind::Proxy)
}
impl From<io::Error> for Error {
/// Of a connection, not of a file here.
fn from(e: io::Error) -> Error {
if let Some(tls) = e.get_ref().and_then(|e| e.downcast_ref::<rustls::Error>()) {
return Error::Conn { kind: ErrorKind::Tls, why: tls_why(Some(tls)) };
}
Error::conn(match e.kind() {
io::ErrorKind::ConnectionRefused => ErrorKind::Refused,
io::ErrorKind::HostUnreachable | io::ErrorKind::NetworkUnreachable | io::ErrorKind::NetworkDown => ErrorKind::Unreachable,
io::ErrorKind::TimedOut => ErrorKind::Timeout,
_ => ErrorKind::Cut,
})
}
}

View file

@ -0,0 +1,221 @@
//! A small FTP server with faults, on loopback.
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio_rustls::TlsAcceptor;
use tokio_rustls::rustls::{self, pki_types::PrivatePkcs8KeyDer};
trait Wire: AsyncRead + AsyncWrite + Send + Unpin {}
impl<T: AsyncRead + AsyncWrite + Send + Unpin> Wire for T {}
#[derive(Clone)]
pub struct Knobs {
pub files: HashMap<String, Arc<Vec<u8>>>,
pub mtime: String,
pub login: Option<(String, String)>,
pub epsv: bool,
pub rest: bool,
pub size: bool,
pub mlsd: Option<String>,
pub list: String,
/// Logins at a time.
pub max: usize,
/// So many transfers are cut after so many bytes.
pub cuts: usize,
pub cut_after: usize,
/// Pause after each 16 KiB.
pub pause: Duration,
/// Takes no AUTH TLS.
pub no_tls: bool,
}
pub struct Ftpd {
pub addr: SocketAddr,
pub cert: Vec<u8>,
pub state: Arc<Inner>,
}
pub struct Inner {
pub knobs: Mutex<Knobs>,
pub log: Mutex<Vec<String>>,
pub sent: AtomicU64,
pub open: AtomicUsize,
pub peak: AtomicUsize,
acceptor: TlsAcceptor,
}
impl Ftpd {
/// `implicit`: TLS from the start.
pub async fn start(data: &[u8], implicit: bool) -> Ftpd {
let key = rcgen::generate_simple_self_signed(["127.0.0.1".to_string()]).unwrap();
let cert = key.cert.der().to_vec();
let secret = PrivatePkcs8KeyDer::from(key.signing_key.serialize_der()).into();
let config = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
.unwrap()
.with_no_client_auth()
.with_single_cert(vec![key.cert.der().clone()], secret)
.unwrap();
let knobs = Knobs {
files: HashMap::from([("f.bin".to_string(), Arc::new(data.to_vec()))]),
mtime: "20250102030405".into(),
login: None,
epsv: true,
rest: true,
size: true,
mlsd: None,
list: String::new(),
max: 100,
cuts: 0,
cut_after: 0,
pause: Duration::ZERO,
no_tls: false,
};
let state = Arc::new(Inner {
knobs: Mutex::new(knobs),
log: Mutex::default(),
sent: AtomicU64::new(0),
open: AtomicUsize::new(0),
peak: AtomicUsize::new(0),
acceptor: TlsAcceptor::from(Arc::new(config)),
});
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let (addr, inner) = (listener.local_addr().unwrap(), state.clone());
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let inner = inner.clone();
tokio::spawn(async move {
let n = inner.open.fetch_add(1, SeqCst) + 1;
let _ = serve(&inner, stream, implicit, n).await;
inner.open.fetch_sub(1, SeqCst);
});
}
});
Ftpd { addr, cert, state }
}
pub fn set(&self, change: impl FnOnce(&mut Knobs)) {
change(&mut self.state.knobs.lock().unwrap());
}
pub fn count(&self, command: &str) -> usize {
self.state.log.lock().unwrap().iter().filter(|l| l.starts_with(command)).count()
}
pub fn sent(&self) -> u64 {
self.state.sent.load(SeqCst)
}
}
async fn serve(inner: &Arc<Inner>, stream: TcpStream, implicit: bool, n: usize) -> std::io::Result<()> {
let mut wire: Box<dyn Wire> = Box::new(stream);
if implicit {
wire = Box::new(inner.acceptor.accept(wire).await?);
}
let mut control = BufReader::new(wire);
if n > inner.knobs.lock().unwrap().max {
return control.write_all(b"421 Too many connections\r\n").await;
}
inner.peak.fetch_max(n, SeqCst);
control.write_all(b"220-Hello\r\n 220 not yet\r\n220 ready\r\n").await?;
let (mut user, mut rest, mut data) = (String::new(), 0, None::<TcpListener>);
let (mut private, mut inside) = (implicit, false);
let mut line = String::new();
loop {
line.clear();
if control.read_line(&mut line).await? == 0 {
return Ok(());
}
let k = inner.knobs.lock().unwrap().clone();
let text = line.trim_end_matches(['\r', '\n']);
inner.log.lock().unwrap().push(text.into());
let (verb, arg) = text.split_once(' ').unwrap_or((text, ""));
let file = k.files.get(arg);
let free = matches!(verb, "USER" | "PASS" | "AUTH" | "PBSZ" | "PROT");
let reply = match verb {
_ if !free && !inside => "530 Log in first".into(),
"AUTH" if !k.no_tls => {
control.write_all(b"234 go\r\n").await?;
control = BufReader::new(Box::new(inner.acceptor.accept(control.into_inner()).await?));
continue;
}
"PBSZ" | "TYPE" | "OPTS" => "200 ok".into(),
"PROT" => {
private = true;
"200 ok".into()
}
"USER" => {
user = arg.into();
"331 password?".into()
}
"PASS" => {
inside = k.login.as_ref().is_none_or(|(u, p)| *u == user && p == arg);
if inside { "230 in".into() } else { "530 Login incorrect".into() }
}
"FEAT" if k.mlsd.is_some() => "211-Features\r\n MLST type*;size*;modify*;\r\n UTF8\r\n211 End".into(),
"SIZE" if k.size => file.map_or("550 none".into(), |f| format!("213 {}", f.len())),
"MDTM" if !k.mtime.is_empty() => file.map_or("550 none".into(), |_| format!("213 {}", k.mtime)),
"REST" if k.rest => {
rest = arg.parse().unwrap();
"350 ok".into()
}
"CWD" => if arg == "gone" { "550 No such folder".into() } else { "250 ok".into() },
"EPSV" | "PASV" if verb == "PASV" || k.epsv => {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let port = listener.local_addr()?.port();
data = Some(listener);
// Another host than this one: not to be believed.
if verb == "EPSV" { format!("229 ok (|||{port}|)") } else { format!("227 ok (192,0,2,1,{},{})", port >> 8, port & 255) }
}
"RETR" | "MLSD" | "LIST" => {
let bytes = match verb {
"RETR" if arg == "secret" => Err("550 Permission denied"),
"RETR" => file.cloned().ok_or("550 No such file"),
"MLSD" => Ok(Arc::new(k.mlsd.clone().unwrap_or_default().into_bytes())),
_ if k.list.is_empty() => Err("450 No files found"),
_ => Ok(Arc::new(k.list.clone().into_bytes())),
};
match (bytes, data.take()) {
(Err(e), _) => e.into(),
(_, None) => "425 no data connection".into(),
(Ok(bytes), Some(listener)) => {
let (stream, _) = listener.accept().await?;
control.write_all(b"150 coming\r\n").await?;
let mut out: Box<dyn Wire> = Box::new(stream);
if private {
out = Box::new(inner.acceptor.accept(out).await?);
}
let from = std::mem::take(&mut rest);
let cut = {
let mut k = inner.knobs.lock().unwrap();
let cut = k.cuts > 0 && verb == "RETR";
k.cuts -= usize::from(cut);
cut.then_some(k.cut_after)
};
let bytes = &bytes[from..];
let whole = cut.is_none_or(|n| n >= bytes.len());
let mut broken = false;
for piece in bytes[..cut.unwrap_or(usize::MAX).min(bytes.len())].chunks(16 << 10) {
if out.write_all(piece).await.is_err() {
broken = true;
break;
}
inner.sent.fetch_add(piece.len() as u64, SeqCst);
tokio::time::sleep(k.pause).await;
}
let _ = out.shutdown().await;
if broken || !whole { "426 cut".into() } else { "226 done".into() }
}
}
}
_ => "502 unknown".to_string(),
};
control.write_all(format!("{reply}\r\n").as_bytes()).await?;
control.flush().await?;
}
}

View file

@ -0,0 +1,435 @@
//! FTP, FTPS and SFTP, whole downloads against servers on loopback.
mod ftpd;
mod sshd;
use ftpd::Ftpd;
use medlar_core::auth::Login;
use medlar_core::error::{Failure, Place};
use medlar_core::host::{Caps, Hosts};
use medlar_core::http::{Client, ClientOptions, Error, Monitor, Options, Shared, client, download};
use medlar_core::listing::{self, Kind};
use medlar_core::model::{ErrorKind, Task, TaskId};
use medlar_core::net_state::Bus;
use medlar_core::secret::{Secret, Secrets};
use medlar_core::segment::Rules;
use medlar_core::settings::Settings;
use medlar_core::site::{Site, Sites};
use medlar_core::store::Store;
use medlar_testserver::expected;
use medlar_testserver::proxy::Proxy;
use sshd::Sshd;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::Ordering::SeqCst;
use std::time::{Duration, Instant};
use tokio::sync::watch;
const SIZE: usize = 2_000_000;
fn ms(n: u64) -> Duration {
Duration::from_millis(n)
}
fn data() -> Vec<u8> {
expected(7, 0, SIZE)
}
struct Bench {
dir: tempfile::TempDir,
store: Arc<Store>,
sites: Arc<Sites>,
client: Client,
options: Options,
monitor: Monitor,
}
fn settings(site: Site) -> Settings {
Settings { proxy: "direct".into(), proxy_bypass: vec![], sites: vec![site], ..Settings::default() }
}
fn here() -> Site {
Site { pattern: "127.0.0.1".into(), secret: Some("here".into()), ..Site::default() }
}
impl Bench {
fn new(only_certs: Vec<Vec<u8>>) -> Bench {
let dir = tempfile::tempdir().unwrap();
let store = Arc::new(Store::open(&dir.path().join("medlar.db")).unwrap());
let known_hosts = Some(dir.path().join("known_hosts"));
let options = ClientOptions { idle_timeout: ms(2000), only_certs, known_hosts, ..ClientOptions::default() };
let client = client(&options).unwrap();
let sites = Sites::new(options, &settings(here()), Arc::new(Secrets::new(Bus::Off)), Bus::Off).unwrap();
let options = Options {
rules: Rules { min: 64 * 1024, align: 4096, min_time: Duration::ZERO },
tries: 3,
tick: ms(20),
backoff: ms(20),
checkpoint: ms(50),
..Options::default()
};
Bench { dir, store, sites, client, options, monitor: Monitor::new(4) }
}
async fn login(&self, user: &str, password: &str) {
let login = Some(Login { user: user.into(), password: password.into() });
self.sites.secrets.save("here", "127.0.0.1", &Secret { login, ..Secret::default() }).await;
}
fn add(&self, url: String) -> TaskId {
self.store.add_task(Task { url, folder: self.dir.path().join("files"), ..Task::default() }).unwrap()
}
async fn run(&self, id: TaskId, stop: watch::Receiver<bool>) -> Result<Vec<u8>, Error> {
let hosts = Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() });
let shared = Shared { client: self.client.clone(), store: self.store.clone(), hosts };
let source = self.sites.source(&self.store.task(id).unwrap()).await?;
let run = download(&shared, id, source, &self.options, &self.monitor, stop);
let path = tokio::time::timeout(Duration::from_secs(60), run).await.unwrap_or_else(|_| panic!("hangs: {:?}", self.monitor.snapshot()))?;
Ok(std::fs::read(path).unwrap())
}
async fn get(&self, url: String) -> Result<Vec<u8>, Error> {
let (_keep, stop) = watch::channel(false);
self.run(self.add(url), stop).await
}
async fn gets(&self, url: String) {
let got = self.get(url.clone()).await.unwrap_or_else(|e| panic!("{url}: {e:?}"));
assert!(got == data(), "{url}: {} bytes", got.len());
}
/// Runs until some of it is safe, then stops.
async fn half(&self, url: String) -> (TaskId, u64) {
let id = self.add(url);
let (tell, stop) = watch::channel(false);
let half = async {
let end = Instant::now() + Duration::from_secs(20);
while self.done(id) < SIZE as u64 / 4 {
assert!(Instant::now() < end, "never came so far");
tokio::time::sleep(ms(5)).await;
}
tell.send_replace(true);
};
let (result, ()) = tokio::join!(self.run(id, stop), half);
assert!(matches!(result, Err(Error::Stopped)), "{:?}", result.map(|d| d.len()));
let done = self.done(id);
assert!(done > 0 && done < SIZE as u64, "{done}");
(id, done)
}
fn done(&self, id: TaskId) -> u64 {
self.store.parts(id).unwrap().iter().map(|p| p.done).sum()
}
async fn again(&self, id: TaskId) -> Result<Vec<u8>, Error> {
let (_keep, stop) = watch::channel(false);
self.run(id, stop).await
}
fn accept(&self, server: &Sshd) -> bool {
let keys = &self.sites.trust.host_keys;
let key = keys.refused("127.0.0.1", server.addr.port()).expect("one was refused");
keys.accept(&key).unwrap();
key.changed
}
}
/// What the user would see.
fn kind(result: Result<Vec<u8>, Error>) -> ErrorKind {
let e = result.map(|d| d.len()).unwrap_err();
let failure = Failure::of(&e, Place { server: "h", folder: Path::new("/"), begun: false });
assert!(!failure.text.contains("status"), "{}", failure.text);
failure.kind
}
fn ftp(server: &Ftpd, path: &str) -> String {
format!("ftp://{}/{path}", server.addr)
}
fn sftp(server: &Sshd, path: &str) -> String {
format!("sftp://me@{}{path}", server.addr)
}
#[tokio::test]
async fn ftp_in_parts() {
let server = Ftpd::start(&data(), false).await;
server.set(|k| k.pause = ms(5));
for epsv in [true, false] {
server.set(|k| k.epsv = epsv);
let b = Bench::new(vec![]);
b.gets(ftp(&server, "f.bin")).await;
assert!(server.state.peak.load(SeqCst) > 1, "several logins");
let received = b.monitor.snapshot().received;
assert!(received <= SIZE as u64 + 200_000, "{received}");
let task = &b.store.tasks().unwrap()[0];
assert_eq!((task.name.as_str(), task.size), ("f.bin", Some(SIZE as u64)));
assert_eq!(task.last_modified.as_deref(), Some("Thu, 02 Jan 2025 03:04:05 GMT"));
}
assert!(server.count("EPSV") > 0 && server.count("PASV") > 0 && server.count("USER anonymous") > 0);
}
#[tokio::test]
async fn ftp_few_logins_allowed() {
let server = Ftpd::start(&data(), false).await;
for max in [1, 2] {
server.set(|k| (k.max, k.pause) = (max, ms(5)));
Bench::new(vec![]).gets(ftp(&server, "f.bin")).await;
}
assert!(server.state.peak.load(SeqCst) <= 2);
}
#[tokio::test]
async fn ftp_resumes() {
let server = Ftpd::start(&data(), false).await;
server.set(|k| k.pause = ms(20));
let b = Bench::new(vec![]);
let (id, done) = b.half(ftp(&server, "f.bin")).await;
let before = server.sent();
server.set(|k| k.pause = ms(5));
assert!(b.again(id).await.unwrap() == data());
// What was cut off may have been on its way once more.
let more = server.sent() - before;
assert!(more < SIZE as u64, "{done} were there, {more} came");
// Another file in its place.
server.set(|k| k.pause = ms(20));
let (id, _) = b.half(ftp(&server, "f.bin")).await;
server.set(|k| k.mtime = "20250102030406".into());
assert_eq!(kind(b.again(id).await), ErrorKind::Changed);
}
#[tokio::test]
async fn ftp_cut() {
let server = Ftpd::start(&data(), false).await;
server.set(|k| (k.cuts, k.cut_after) = (3, 300_000));
Bench::new(vec![]).gets(ftp(&server, "f.bin")).await;
assert_eq!(server.state.knobs.lock().unwrap().cuts, 0);
// Where nothing says how long the file is, the server's last word does.
server.set(|k| (k.cuts, k.cut_after, k.size) = (1, 300_000, false));
assert_eq!(kind(Bench::new(vec![]).get(ftp(&server, "f.bin")).await), ErrorKind::Cut);
}
#[tokio::test]
async fn ftp_poor_servers() {
let server = Ftpd::start(&data(), false).await;
server.set(|k| k.rest = false);
Bench::new(vec![]).gets(ftp(&server, "f.bin")).await;
server.set(|k| (k.rest, k.size, k.mtime) = (true, false, String::new()));
Bench::new(vec![]).gets(ftp(&server, "f.bin")).await;
server.set(|k| k.size = true);
for len in [0, 1] {
server.set(|k| drop(k.files.insert("f.bin".into(), Arc::new(vec![5; len]))));
assert_eq!(Bench::new(vec![]).get(ftp(&server, "f.bin")).await.unwrap(), vec![5; len]);
}
}
#[tokio::test]
async fn ftp_logins_and_refusals() {
let server = Ftpd::start(&data(), false).await;
server.set(|k| k.login = Some(("bob".into(), "p w".into())));
let b = Bench::new(vec![]);
assert_eq!(kind(b.get(ftp(&server, "f.bin")).await), ErrorKind::Login);
b.login("bob", "wrong").await;
assert_eq!(kind(b.get(ftp(&server, "f.bin")).await), ErrorKind::Login);
assert_eq!(server.count("USER bob"), 1, "a wrong password is tried once");
b.login("bob", "p w").await;
b.gets(ftp(&server, "f.bin")).await;
// The link names its user.
b.gets(format!("ftp://bob@{}/f.bin", server.addr)).await;
assert_eq!(kind(b.get(format!("ftp://eve@{}/f.bin", server.addr)).await), ErrorKind::Login);
assert_eq!(kind(b.get(ftp(&server, "none")).await), ErrorKind::NotFound);
assert_eq!(kind(b.get(ftp(&server, "secret")).await), ErrorKind::Forbidden);
assert_eq!(kind(b.get(ftp(&server, "")).await), ErrorKind::NotFound);
assert_eq!(kind(b.get(ftp(&server, "a%0D%0ADELE%20f.bin")).await), ErrorKind::BadLink);
assert_eq!(server.count("DELE"), 0);
let nobody = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap();
assert_eq!(kind(b.get(format!("ftp://{nobody}/f")).await), ErrorKind::Refused);
}
#[tokio::test]
async fn ftps() {
for scheme in ["ftps", "ftpes"] {
let server = Ftpd::start(&data(), scheme == "ftps").await;
let url = format!("{scheme}://{}/f.bin", server.addr);
let b = Bench::new(vec![server.cert.clone()]);
b.gets(url.clone()).await;
// A certificate nobody knows: not even a login gets there.
let other = Ftpd::start(&data(), false).await;
let before = server.count("USER");
let b = Bench::new(vec![other.cert.clone()]);
assert_eq!(kind(b.get(url.clone()).await), ErrorKind::Tls);
assert_eq!(server.count("USER"), before);
// Until the user makes an exception.
let certificate = b.sites.trust.refused("127.0.0.1");
assert!(certificate.is_some());
b.sites.set(&settings(Site { certificate, ..here() }));
b.gets(url.clone()).await;
if scheme == "ftpes" {
server.set(|k| k.no_tls = true);
assert_eq!(kind(b.get(url).await), ErrorKind::Tls);
}
}
}
#[tokio::test]
async fn through_proxies() {
let server = Ftpd::start(&data(), false).await;
let ssh = Sshd::start(&data()).await;
let b = Bench::new(vec![]);
b.login("me", "right").await;
for proxy in [Proxy::start_http(None).await, Proxy::start_socks5(None).await] {
let scheme = if b.store.tasks().unwrap().is_empty() { "http" } else { "socks5" };
b.sites.set(&settings(Site { proxy: Some(format!("{scheme}://{}", proxy.addr())), ..here() }));
b.gets(ftp(&server, "f.bin")).await;
if scheme == "http" {
assert_eq!(kind(b.get(sftp(&ssh, "/pub/f.bin")).await), ErrorKind::Tls);
b.accept(&ssh);
}
b.gets(sftp(&ssh, "/pub/f.bin")).await;
assert!(proxy.seen().len() >= 3, "control and data");
}
// Never straight to the server instead.
let (logins, connections) = (server.count("USER"), ssh.state.connections.load(SeqCst));
let nobody = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap();
for proxy in [format!("http://{nobody}"), format!("socks5://{nobody}"), "nonsense".into(), format!("https://{nobody}")] {
b.sites.set(&settings(Site { proxy: Some(proxy), ..here() }));
assert_eq!(kind(b.get(ftp(&server, "f.bin")).await), ErrorKind::Proxy);
assert_eq!(kind(b.get(sftp(&ssh, "/pub/f.bin")).await), ErrorKind::Proxy);
}
assert_eq!((logins, connections), (server.count("USER"), ssh.state.connections.load(SeqCst)));
let locked = Proxy::start_http(Some(("u", "p"))).await;
b.sites.set(&settings(Site { proxy: Some(format!("http://{}", locked.addr())), ..here() }));
assert_eq!(kind(b.get(ftp(&server, "f.bin")).await), ErrorKind::Login);
b.sites.save_proxy_login(&format!("http://{}", locked.addr()), Login { user: "u".into(), password: "p".into() }).await;
b.gets(ftp(&server, "f.bin")).await;
}
#[tokio::test]
async fn listings() {
let server = Ftpd::start(&data(), false).await;
let b = Bench::new(vec![]);
let (_keep, mut stop) = watch::channel(false);
let mut look = async |url: String| {
let task = Task { url, ..Task::default() };
listing::list(&b.client, &b.sites.source(&task).await.unwrap(), &mut stop).await
};
assert_eq!(look(ftp(&server, "empty")).await.unwrap(), []);
server.set(|k| k.list = "total 1\r\n-rw-r--r-- 1 u g 5 May 4 2023 a b.bin\r\ndrwxr-xr-x 2 u g 4096 May 4 2023 sub\r\n".into());
let found = look(ftp(&server, "some%20where/")).await.unwrap();
assert_eq!(server.count("CWD some where"), 1);
assert_eq!((found[0].name.as_str(), found[0].kind, found[0].size), ("a b.bin", Kind::File, Some(5)));
assert_eq!(found[0].url.as_str(), ftp(&server, "some%20where/a%20b.bin"));
assert_eq!((found[1].kind, found[1].url.as_str()), (Kind::Folder, ftp(&server, "some%20where/sub/").as_str()));
server.set(|k| k.mlsd = Some("type=file;size=7;modify=20230504000000; m\r\ntype=file; ../up\r\n".into()));
let found = look(ftp(&server, "")).await.unwrap();
assert_eq!((found.len(), found[0].name.as_str(), found[0].modified), (1, "m", Some(1_683_158_400_000)));
assert!(look(ftp(&server, "gone")).await.is_err());
let ssh = Sshd::start(&data()).await;
b.login("me", "right").await;
assert!(look(sftp(&ssh, "/pub")).await.is_err());
b.accept(&ssh);
let found = look(sftp(&ssh, "/pub")).await.unwrap();
let kinds: Vec<_> = found.iter().map(|e| (e.name.as_str(), e.kind, e.size, e.modified)).collect();
let time = Some(1_000_000);
assert_eq!(kinds, [("f.bin", Kind::File, Some(9), time), ("caf\u{fffd}", Kind::Folder, None, time), ("l", Kind::Link, None, time)]);
assert_eq!(found[1].url.as_str(), sftp(&ssh, "/pub/caf%E9/"));
assert!(look(sftp(&ssh, "/gone")).await.is_err());
assert!(look("http://127.0.0.1/".into()).await.is_err());
}
#[tokio::test]
async fn sftp_host_key() {
let server = Sshd::start(&data()).await;
let b = Bench::new(vec![]);
b.login("me", "right").await;
let url = sftp(&server, "/pub/f.bin");
// Nothing is sent to a server nobody knows, and asking again doesn't make it known.
for _ in 0..2 {
let e = b.get(url.clone()).await.unwrap_err();
assert!(matches!(e, Error::Conn { kind: ErrorKind::Tls, why: Some("error.host_key.new") }), "{e:?}");
}
assert_eq!(server.state.passwords.lock().unwrap().len(), 0);
assert!(!b.accept(&server));
b.gets(url.clone()).await;
server.set(|k| k.pause = ms(5));
let (id, done) = b.half(url.clone()).await;
server.set_host_key(2);
let asked = server.state.passwords.lock().unwrap().len();
for _ in 0..2 {
let e = b.again(id).await.unwrap_err();
assert!(matches!(e, Error::Conn { kind: ErrorKind::Tls, why: Some("error.host_key.changed") }), "{e:?}");
}
assert_eq!(server.state.passwords.lock().unwrap().len(), asked, "no password for a server with another key");
assert_eq!(b.done(id), done, "nothing is lost");
assert!(b.accept(&server));
assert!(b.again(id).await.unwrap() == data());
}
#[tokio::test]
async fn sftp_resumes_and_survives_cuts() {
let server = Sshd::start(&data()).await;
let b = Bench::new(vec![]);
b.login("me", "right").await;
let url = sftp(&server, "/pub/f.bin");
assert!(b.get(url.clone()).await.is_err());
b.accept(&server);
server.set(|k| k.pause = ms(5));
let (id, done) = b.half(url.clone()).await;
let before = server.sent();
assert!(b.again(id).await.unwrap() == data());
let more = server.sent() - before;
assert!(more < SIZE as u64, "{done} were there, {more} came");
server.set(|k| (k.pause, k.cuts, k.cut_after) = (ms(1), 3, 8));
let connections = server.state.connections.load(SeqCst);
b.gets(url.clone()).await;
assert_eq!(server.state.knobs.lock().unwrap().cuts, 0);
assert!(server.state.connections.load(SeqCst) - connections >= 4);
// Answers shorter than asked for, and files of no size at all.
server.set(|k| (k.pause, k.most) = (Duration::ZERO, 10_000));
b.gets(url.clone()).await;
for len in [0, 1] {
server.set(|k| drop(k.files.insert(b"/pub/f.bin".to_vec(), Arc::new(vec![5; len]))));
assert_eq!(b.get(url.clone()).await.unwrap(), vec![5; len]);
}
server.set(|k| k.files.clear());
assert_eq!(kind(b.get(url).await), ErrorKind::NotFound);
assert_eq!(kind(b.get(sftp(&server, "/pub")).await), ErrorKind::NotFound);
}
#[tokio::test]
async fn sftp_logins() {
let server = Sshd::start(&data()).await;
let b = Bench::new(vec![]);
let url = sftp(&server, "/pub/f.bin");
assert!(b.get(url.clone()).await.is_err());
b.accept(&server);
assert_eq!(kind(b.get(url.replace("me@", "")).await), ErrorKind::Login, "no name");
assert_eq!(kind(b.get(url.clone()).await), ErrorKind::Login, "no password");
b.login("me", "wrong").await;
assert_eq!(kind(b.get(url.clone()).await), ErrorKind::Login);
assert_eq!(*server.state.passwords.lock().unwrap(), ["wrong"], "tried once");
b.login("me", "right").await;
b.gets(url.clone()).await;
server.set(|k| k.asks = true);
b.gets(url.clone()).await;
// A key with a passphrase.
let (key, file) = (sshd::key(9), b.dir.path().join("key"));
server.set(|k| (k.key, k.password) = (Some(key.public_key().clone()), "never".into()));
let mut text = vec![];
russh::keys::encode_pkcs8_pem_encrypted(&key, b"phrase", 10, &mut text).unwrap();
std::fs::write(&file, text).unwrap();
b.sites.set(&settings(Site { key: Some(file), ..here() }));
assert_eq!(kind(b.get(url.clone()).await), ErrorKind::Login);
b.login("me", "phrase").await;
let asked = server.state.passwords.lock().unwrap().len();
b.gets(url.clone()).await;
server.set(|k| k.key = None);
assert_eq!(kind(b.get(url).await), ErrorKind::Login);
assert_eq!(server.state.passwords.lock().unwrap().len(), asked, "the passphrase stays here");
}

Some files were not shown because too many files have changed in this diff Show more