use std::collections::{HashSet, VecDeque};
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use crate::engine::{DownloadParams, EngineSummary, Operation, Output};
use crate::inputs::HttpInput;
#[derive(Debug, Clone)]
pub struct MirrorOptions {
pub recursive: bool,
pub level: usize,
pub include: Vec<String>,
pub exclude: Vec<String>,
pub connections: usize,
pub speed_limit_bps: Option<u64>,
pub retries: u32,
}
impl Default for MirrorOptions {
fn default() -> Self {
Self {
recursive: true,
level: 5,
include: vec![],
exclude: vec![],
connections: 4,
speed_limit_bps: None,
retries: 5,
}
}
}
#[derive(Debug, Default)]
pub struct MirrorReport {
pub pages: usize,
pub files: Vec<PathBuf>,
pub bytes: u64,
pub skipped: Vec<String>,
}
pub async fn mirror_url(start: &str, out_dir: &Path, opts: &MirrorOptions) -> Result<MirrorReport> {
let u = url::Url::parse(start).with_context(|| format!("invalid URL: {start}"))?;
if u.scheme() == "webdav" || u.scheme() == "webdavs" {
return mirror_webdav(start, out_dir, opts).await;
}
if u.scheme() != "http" && u.scheme() != "https" {
bail!(
"mirror supports http(s) and webdav listings only (not {}): {start}",
u.scheme()
);
}
if !opts.recursive {
let target = target_path(out_dir, &u)?;
let sum = download_file(start, &target, opts).await?;
return Ok(MirrorReport {
pages: 0,
files: vec![target],
bytes: sum.total_bytes,
skipped: vec![],
});
}
let mut report = MirrorReport::default();
let mut visited: HashSet<String> = HashSet::new();
let mut pages: VecDeque<(String, usize)> = VecDeque::from([(start.to_string(), 0)]);
let mut file_urls: Vec<String> = Vec::new();
while let Some((page_url, depth)) = pages.pop_front() {
if !visited.insert(page_url.clone()) {
continue;
}
let html = match fetch_html(&page_url).await? {
Some(h) => h,
None => {
file_urls.push(page_url);
continue;
}
};
report.pages += 1;
for href in extract_hrefs(&html) {
let Some(abs) = resolve(&page_url, &href) else {
continue;
};
if visited.contains(&abs) {
continue;
}
if is_skipped_scheme(&abs) {
report
.skipped
.push(format!("{abs} (torrent/s3 outside http recursion)"));
continue;
}
if !same_host(start, &abs) {
report.skipped.push(format!("{abs} (other host)"));
continue;
}
if abs.split(['?', '#']).next().unwrap_or(&abs).ends_with('/') {
if depth < opts.level {
pages.push_back((abs, depth + 1));
} else {
report
.skipped
.push(format!("{abs} (poza --level {})", opts.level));
}
continue;
}
if !wanted(&abs, &opts.include, &opts.exclude) {
report.skipped.push(format!("{abs} (--include/--exclude filtered)"));
continue;
}
file_urls.push(abs);
}
}
for f in file_urls {
let u = url::Url::parse(&f).with_context(|| format!("invalid URL: {f}"))?;
let target = target_path(out_dir, &u)?;
match download_file(&f, &target, opts).await {
Ok(sum) => {
report.bytes += sum.total_bytes;
report.files.push(target);
}
Err(e) => report.skipped.push(format!("{f} (error: {e})")),
}
}
Ok(report)
}
async fn download_file(url: &str, target: &Path, opts: &MirrorOptions) -> Result<EngineSummary> {
if let Some(parent) = target.parent()
&& !parent.as_os_str().is_empty()
{
std::fs::create_dir_all(parent)
.with_context(|| format!("cannot create {}", parent.display()))?;
}
let lower = url.to_lowercase();
if lower.starts_with("webdav://") || lower.starts_with("webdavs://") {
let input = crate::inputs::WebdavInput::new(url.to_owned());
let op = Operation::Download(DownloadParams {
connections: opts.connections,
speed_limit_bps: opts.speed_limit_bps,
retries: opts.retries,
mirrors: vec![],
allow_h3: false,
auto_mirror: false,
proxy: None,
});
let out = Output::File(target.to_path_buf());
return crate::engine::run_input(&input, &op, &out).await;
}
let input = HttpInput::new(url.to_owned());
let op = Operation::Download(DownloadParams {
connections: opts.connections,
speed_limit_bps: opts.speed_limit_bps,
retries: opts.retries,
mirrors: vec![],
allow_h3: false,
auto_mirror: false,
proxy: None,
});
let out = Output::File(target.to_path_buf());
crate::engine::run_input(&input, &op, &out).await
}
async fn mirror_webdav(start: &str, out_dir: &Path, opts: &MirrorOptions) -> Result<MirrorReport> {
let mut report = MirrorReport::default();
let mut visited: HashSet<String> = HashSet::new();
let mut dirs: VecDeque<(String, usize)> = VecDeque::from([(start.to_string(), 0)]);
let mut file_urls: Vec<String> = Vec::new();
let mut seen_files: HashSet<String> = HashSet::new();
while let Some((dir_url, depth)) = dirs.pop_front() {
if !visited.insert(dir_url.clone()) {
continue;
}
let input = crate::inputs::WebdavInput::new(dir_url.clone());
let children = match input.list_dir(None).await {
Ok(c) => c,
Err(e) => {
report.skipped.push(format!("{dir_url} (list error: {e})"));
continue;
}
};
report.pages += 1;
for child in children {
if visited.contains(&child) {
continue;
}
if is_skipped_scheme(&child) {
report
.skipped
.push(format!("{child} (torrent/s3 outside webdav recursion)"));
continue;
}
if !same_webdav_host(start, &child) {
report.skipped.push(format!("{child} (other host)"));
continue;
}
if child.split(['?', '#']).next().unwrap_or(&child).ends_with('/') {
if depth < opts.level {
dirs.push_back((child, depth + 1));
} else {
report
.skipped
.push(format!("{child} (beyond --level {})", opts.level));
}
continue;
}
if !wanted(&child, &opts.include, &opts.exclude) {
report.skipped.push(format!("{child} (--include/--exclude filtered)"));
continue;
}
if !seen_files.insert(child.clone()) {
continue;
}
file_urls.push(child);
}
}
if file_urls.is_empty() && report.pages == 1 {
let u = url::Url::parse(start).with_context(|| format!("invalid URL: {start}"))?;
if !start.split(['?', '#']).next().unwrap_or(start).ends_with('/') {
file_urls.push(start.to_string());
let _ = u;
}
}
for f in file_urls {
let u = url::Url::parse(&f).with_context(|| format!("invalid URL: {f}"))?;
let target = target_path(out_dir, &u)?;
match download_file(&f, &target, opts).await {
Ok(sum) => {
report.bytes += sum.total_bytes;
report.files.push(target);
}
Err(e) => report.skipped.push(format!("{f} (error: {e})")),
}
}
Ok(report)
}
fn same_webdav_host(start: &str, abs: &str) -> bool {
let (Ok(a), Ok(b)) = (url::Url::parse(start), url::Url::parse(abs)) else {
return false;
};
let scheme_ok = |s: &str| s == "webdav" || s == "webdavs";
if !(scheme_ok(a.scheme()) && scheme_ok(b.scheme())) {
return a.scheme() == b.scheme()
&& a.host_str() == b.host_str()
&& a.port_or_known_default() == b.port_or_known_default();
}
a.host_str() == b.host_str() && a.port_or_known_default() == b.port_or_known_default()
}
async fn fetch_html(url: &str) -> Result<Option<String>> {
let client = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
.build()
.context("cannot create HTTP client")?;
let resp = client
.get(url)
.header(reqwest::header::ACCEPT, "text/html")
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send()
.await
.with_context(|| format!("cannot fetch {url}"))?;
if !resp.status().is_success() {
bail!("listing fetch failed (HTTP {}): {url}", resp.status());
}
let is_html = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|ct| {
let ct = ct.to_lowercase();
ct.contains("text/html") || ct.contains("application/xhtml")
});
if !is_html {
return Ok(None);
}
Ok(Some(resp.text().await.context("cannot read listing body")?))
}
fn target_path(out_dir: &Path, u: &url::Url) -> Result<PathBuf> {
let mut p = out_dir.to_path_buf();
p.push(u.host_str().unwrap_or("host"));
let mut segs: Vec<String> = u
.path_segments()
.map(|s| s.filter(|x| !x.is_empty()).map(|x| x.to_string()).collect())
.unwrap_or_default();
if segs.is_empty() {
segs.push("index.html".into());
}
for s in segs {
if s == ".." || s.contains('/') || s.contains('\\') {
bail!("unsafe path segment in URL: {}", u.as_str());
}
p.push(s);
}
if p.as_os_str().to_string_lossy().ends_with('/') {
p.push("index.html");
}
Ok(p)
}
pub fn extract_hrefs(html: &str) -> Vec<String> {
let mut out = Vec::new();
let bytes = html.as_bytes();
let mut i = 0;
while i + 2 < bytes.len() {
if bytes[i] == b'<'
&& (bytes[i + 1] == b'a' || bytes[i + 1] == b'A')
&& matches!(bytes[i + 2], b' ' | b'\t' | b'\n' | b'\r' | b'>')
{
let mut j = i + 2;
while j < bytes.len() && bytes[j] != b'>' {
j += 1;
}
let tag = &html[i..j.min(bytes.len())];
if let Some(h) = tag_href(tag) {
out.push(h);
}
i = j + 1;
} else {
i += 1;
}
}
out
}
fn tag_href(tag: &str) -> Option<String> {
let b = tag.as_bytes();
let mut i = 0;
while i + 4 < b.len() {
if (b[i] == b'h' || b[i] == b'H')
&& (b[i + 1] == b'r' || b[i + 1] == b'R')
&& (b[i + 2] == b'e' || b[i + 2] == b'E')
&& (b[i + 3] == b'f' || b[i + 3] == b'F')
{
let mut j = i + 4;
while j < b.len() && (b[j] == b' ' || b[j] == b'\t' || b[j] == b'\n' || b[j] == b'\r') {
j += 1;
}
if j < b.len() && b[j] == b'=' {
j += 1;
while j < b.len() && (b[j] == b' ' || b[j] == b'\t') {
j += 1;
}
if j >= b.len() {
return None;
}
let (value, _) = if b[j] == b'"' || b[j] == b'\'' {
let q = b[j];
let start = j + 1;
let mut k = start;
while k < b.len() && b[k] != q {
k += 1;
}
(tag[start..k.min(b.len())].to_string(), k + 1)
} else {
let start = j;
let mut k = start;
while k < b.len() && !matches!(b[k], b' ' | b'\t' | b'\n' | b'\r' | b'>') {
k += 1;
}
(tag[start..k].to_string(), k)
};
let value = value.trim().to_string();
if value.is_empty() {
return None;
}
return Some(value);
}
}
i += 1;
}
None
}
fn resolve(page: &str, href: &str) -> Option<String> {
let href = href.trim();
if href.is_empty() || href.starts_with('#') {
return None;
}
let lower = href.to_lowercase();
if lower.starts_with("javascript:")
|| lower.starts_with("mailto:")
|| lower.starts_with("data:")
{
return None;
}
if href == "../" || href == ".." {
return None;
}
let base = url::Url::parse(page).ok()?;
let abs = base.join(href).ok()?;
if abs.scheme() != "http" && abs.scheme() != "https" {
return None;
}
let mut s = abs.to_string();
if let Some(pos) = s.find('#') {
s.truncate(pos);
}
Some(s)
}
fn same_host(start: &str, abs: &str) -> bool {
let (Ok(a), Ok(b)) = (url::Url::parse(start), url::Url::parse(abs)) else {
return false;
};
a.scheme() == b.scheme()
&& a.host_str() == b.host_str()
&& a.port_or_known_default() == b.port_or_known_default()
}
fn is_skipped_scheme(abs: &str) -> bool {
let lower = abs.to_lowercase();
lower.starts_with("magnet:")
|| lower.starts_with("s3://")
|| lower.ends_with(".torrent")
|| lower.contains(".torrent?")
}
pub fn wanted(url: &str, include: &[String], exclude: &[String]) -> bool {
if exclude.iter().any(|p| wildcard(p, url)) {
return false;
}
if include.is_empty() {
return true;
}
include.iter().any(|p| wildcard(p, url))
}
pub fn wildcard(pattern: &str, text: &str) -> bool {
wildcard_bytes(pattern.as_bytes(), text.as_bytes())
}
fn wildcard_bytes(p: &[u8], t: &[u8]) -> bool {
if p.is_empty() {
return t.is_empty();
}
if p[0] == b'*' {
let mut rest = p;
while rest.first() == Some(&b'*') {
rest = &rest[1..];
}
if rest.is_empty() {
return true;
}
for i in 0..=t.len() {
if wildcard_bytes(rest, &t[i..]) {
return true;
}
}
return false;
}
if t.is_empty() {
return false;
}
if p[0] == b'?' || p[0] == t[0] {
return wildcard_bytes(&p[1..], &t[1..]);
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hrefs_from_mixed_markup() {
let html = r##"<html><body>
<a href="/files/a.iso">a</a>
<a HREF='sub/b.txt'>b</a>
<a href=sub/c.bin>c</a>
<a name="x">no href</a>
<a href="#frag">frag</a>
<a href="mailto:a@b">mail</a>
<a href="../">up</a>
</body></html>"##;
let hrefs = extract_hrefs(html);
assert!(hrefs.contains(&"/files/a.iso".to_string()));
assert!(hrefs.contains(&"sub/b.txt".to_string()));
assert!(hrefs.contains(&"sub/c.bin".to_string()));
assert!(
hrefs.contains(&"mailto:a@b".to_string()),
"surowe hrefy bez filtrowania"
);
assert_eq!(
resolve("http://h/dir/", "mailto:a@b"),
None,
"mailto odrzucone w resolve"
);
assert_eq!(resolve("http://h/dir/", "#frag"), None);
assert_eq!(resolve("http://h/dir/", "../"), None);
assert_eq!(
resolve("http://h/dir/", "sub/b.txt").as_deref(),
Some("http://h/dir/sub/b.txt")
);
assert_eq!(
resolve("http://h/dir/", "/abs.bin").as_deref(),
Some("http://h/abs.bin")
);
}
#[test]
fn wildcard_matching() {
assert!(wildcard("*.iso", "http://h/f.iso"));
assert!(!wildcard("*.iso", "http://h/f.zip"));
assert!(wildcard("http://h/sub/*", "http://h/sub/a"));
assert!(wildcard("file.???", "file.bin"));
assert!(!wildcard("file.???", "file.bind"));
assert!(wanted("http://h/a.iso", &["*.iso".into()], &[]));
assert!(!wanted(
"http://h/a.iso",
&["*.iso".into()],
&["*a*".into()]
));
assert!(wanted("http://h/a.iso", &[], &[]));
}
#[test]
fn skips_torrents_s3_and_foreign_hosts() {
assert!(is_skipped_scheme("magnet:?xt=urn:btih:abc"));
assert!(is_skipped_scheme("http://h/f.torrent"));
assert!(is_skipped_scheme("s3://bucket/key"));
assert!(!is_skipped_scheme("http://h/f.iso"));
assert!(same_host("http://h:8080/a/", "http://h:8080/b"));
assert!(!same_host("http://h/a/", "http://evil/a"));
}
async fn start_tree() -> (String, HashSet<String>) {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let files: HashSet<String> = ["/a.bin".into(), "/sub/b.bin".into()].into_iter().collect();
let index = r#"<html><body><a href="a.bin">a</a><a href="sub/">sub</a><a href="http://evil.example/x">evil</a><a href="pack.torrent">t</a></body></html>"#;
let sub = r#"<html><body><a href="b.bin">b</a><a href="../">up</a></body></html>"#;
tokio::spawn(async move {
let data_a: Vec<u8> = (0..50_000u32).map(|i| (i % 251) as u8).collect();
let data_b: Vec<u8> = (0..20_000u32).map(|i| (i * 3 % 251) as u8).collect();
loop {
let Ok((mut s, _)) = listener.accept().await else {
break;
};
let index = index.to_string();
let sub = sub.to_string();
let data_a = data_a.clone();
let data_b = data_b.clone();
tokio::spawn(async move {
let mut buf = vec![0u8; 65536];
while let Ok(n) = AsyncReadExt::read(&mut s, &mut buf).await {
if n == 0 {
break;
}
let req = String::from_utf8_lossy(&buf[..n]).to_string();
let path = req
.lines()
.next()
.and_then(|l| l.split_whitespace().nth(1))
.unwrap_or("/")
.to_string();
let (status, ctype, body): (&str, &str, Vec<u8>) = match path.as_str() {
"/" => ("200 OK", "text/html", index.as_bytes().to_vec()),
"/sub/" => ("200 OK", "text/html", sub.as_bytes().to_vec()),
"/a.bin" => ("200 OK", "application/octet-stream", data_a.clone()),
"/sub/b.bin" => ("200 OK", "application/octet-stream", data_b.clone()),
_ => ("404 Not Found", "text/plain", b"nope".to_vec()),
};
let range = req.lines().find_map(|l| {
l.strip_prefix("Range:")
.or_else(|| l.strip_prefix("range:"))
.map(|v| v.trim().to_string())
});
if let Some(r) = range
&& (path == "/a.bin" || path == "/sub/b.bin")
{
let nums: Vec<u64> = r
.trim_start_matches("bytes=")
.split('-')
.map(|x| x.parse().unwrap_or(0))
.collect();
let (from, to) = (nums[0], nums[1].min(body.len() as u64 - 1));
let slice = body[from as usize..=to as usize].to_vec();
let h = format!(
"HTTP/1.1 206 Partial Content\r\ncontent-range: bytes {from}-{to}/{}\r\ncontent-length: {}\r\naccept-ranges: bytes\r\nconnection: keep-alive\r\n\r\n",
body.len(),
slice.len()
);
let _ = AsyncWriteExt::write_all(&mut s, h.as_bytes()).await;
let _ = AsyncWriteExt::write_all(&mut s, &slice).await;
continue;
}
let h = format!(
"HTTP/1.1 {status}\r\ncontent-type: {ctype}\r\ncontent-length: {}\r\naccept-ranges: bytes\r\nconnection: keep-alive\r\n\r\n",
body.len()
);
let _ = AsyncWriteExt::write_all(&mut s, h.as_bytes()).await;
let _ = AsyncWriteExt::write_all(&mut s, &body).await;
}
});
}
});
(base, files)
}
#[tokio::test]
async fn crawls_tree_and_downloads_files() {
let (base, _files) = start_tree().await;
let dir = std::env::temp_dir().join(format!("xget-mirror-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let opts = MirrorOptions {
level: 5,
connections: 2,
..Default::default()
};
let rep = mirror_url(&format!("{base}/"), &dir, &opts).await.unwrap();
assert_eq!(
rep.files.len(),
2,
"a.bin + sub/b.bin (torrent and foreign host skipped)"
);
assert!(
rep.skipped.iter().any(|s| s.contains("pack.torrent")),
"torrent in skipped"
);
assert!(
rep.skipped.iter().any(|s| s.contains("evil")),
"foreign host in skipped"
);
let host = url::Url::parse(&base)
.unwrap()
.host_str()
.unwrap()
.to_string();
assert!(dir.join(&host).join("a.bin").exists());
assert!(dir.join(&host).join("sub").join("b.bin").exists());
assert_eq!(rep.bytes, 70_000);
let _ = std::fs::remove_dir_all(&dir);
}
#[tokio::test]
async fn level_and_filters_are_honored() {
let (base, _) = start_tree().await;
let dir = std::env::temp_dir().join(format!("xget-mirror-lvl-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let opts = MirrorOptions {
level: 0,
connections: 1,
..Default::default()
};
let rep = mirror_url(&format!("{base}/"), &dir, &opts).await.unwrap();
assert_eq!(rep.files.len(), 1);
assert!(rep.skipped.iter().any(|s| s.contains("--level")));
let opts = MirrorOptions {
exclude: vec!["*.bin".into()],
connections: 1,
..Default::default()
};
let rep = mirror_url(&format!("{base}/"), &dir, &opts).await.unwrap();
assert!(rep.files.is_empty(), "exclude *.bin wycina pliki");
let _ = std::fs::remove_dir_all(&dir);
}
}