use anyhow::{Context, Result, bail};
use crate::downloader::{meta_path, part_path, pause_sentinel};
use crate::engine::{EngineSummary, Input, Operation, Output, backoff, total_style};
use crate::inputs::HttpInput;
#[derive(Debug, Clone)]
pub struct WebdavParts {
pub host: String,
pub port: u16,
pub user: String,
pub pass: String,
pub path: String,
pub tls: bool,
}
pub struct WebdavInput {
pub url: String,
}
impl WebdavInput {
pub fn new(url: impl Into<String>) -> Self {
Self { url: url.into() }
}
pub fn parse(url: &str) -> Result<WebdavParts> {
let u = url::Url::parse(url).with_context(|| format!("invalid WebDAV URL: {url}"))?;
let scheme = u.scheme().to_ascii_lowercase();
if scheme != "webdav" && scheme != "webdavs" {
bail!("not a webdav URL: {url}");
}
let host = u.host_str().unwrap_or("").to_string();
if host.is_empty() {
bail!("WebDAV URL has no host: {url}");
}
let tls = scheme == "webdavs";
let port = u.port().unwrap_or(if tls { 443 } else { 80 });
let user = if u.username().is_empty() {
String::new()
} else {
u.username().to_string()
};
let pass = u.password().unwrap_or("").to_string();
let mut path = u.path().to_string();
if path.is_empty() {
path = "/".to_string();
}
path = percent_decode(&path);
Ok(WebdavParts {
host,
port,
user,
pass,
path,
tls,
})
}
pub fn http_url(&self) -> Result<String> {
let p = Self::parse(&self.url)?;
let scheme = if p.tls { "https" } else { "http" };
let auth = if p.user.is_empty() {
String::new()
} else if p.pass.is_empty() {
format!("{}@", p.user)
} else {
format!("{}:{}@", p.user, p.pass)
};
let port_part = if (p.tls && p.port == 443) || (!p.tls && p.port == 80) {
String::new()
} else {
format!(":{}", p.port)
};
Ok(format!("{scheme}://{auth}{}{}{}", p.host, port_part, p.path))
}
fn client(proxy: Option<&str>) -> Result<reqwest::Client> {
let mut b = reqwest::Client::builder()
.user_agent("xget/0.1 (+https://github.com/JustRoccat/xget)")
.connect_timeout(std::time::Duration::from_secs(10))
.timeout(std::time::Duration::from_secs(60));
if let Some(p) = proxy {
b = b.proxy(reqwest::Proxy::all(p).with_context(|| format!("bad proxy URL: {p}"))?);
}
b.build().context("cannot create HTTP client")
}
pub async fn propfind(&self, depth: &str, proxy: Option<&str>) -> Result<String> {
let target = self.http_url()?;
let client = Self::client(proxy)?;
let body = r#"<?xml version="1.0"?><propfind xmlns="DAV:"><prop><resourcetype/><getcontentlength/><href/></prop></propfind>"#;
let resp = client
.request(reqwest::Method::from_bytes(b"PROPFIND").unwrap(), target.as_str())
.header("Depth", depth)
.header("Content-Type", "application/xml")
.body(body)
.send()
.await
.context("webdav PROPFIND failed")?;
if resp.status() != reqwest::StatusCode::from_u16(207).unwrap() && !resp.status().is_success() {
bail!("webdav PROPFIND failed (HTTP {})", resp.status());
}
resp.text().await.context("cannot read PROPFIND body")
}
pub async fn list_dir(&self, proxy: Option<&str>) -> Result<Vec<String>> {
let xml = self.propfind("1", proxy).await?;
let hrefs = parse_propfind_hrefs(&xml);
let mut out = Vec::new();
let base_path = Self::parse(&self.url)?.path;
for h in hrefs {
let full = prop_href_to_webdav(&self.url, &h);
let p = WebdavInput::parse(&full).map(|x| x.path).unwrap_or_default();
if p == base_path {
continue;
}
if full == self.url {
continue;
}
out.push(full);
}
Ok(out)
}
}
pub fn parse_propfind_hrefs(xml: &str) -> Vec<String> {
let mut out = Vec::new();
let lower = xml.to_lowercase();
let mut i = 0;
while let Some(rel) = lower[i..].find('<') {
let start = i + rel;
let Some(gt_rel) = xml[start..].find('>') else {
break;
};
let tag = &lower[start + 1..start + gt_rel];
let name = tag.split_whitespace().next().unwrap_or("");
let is_href = name == "href" || name.ends_with(":href");
if !is_href || name.starts_with('/') {
i = start + 1;
continue;
}
let open_end = start + gt_rel + 1;
let mut j = open_end;
let mut found: Option<usize> = None;
while let Some(crel) = lower[j..].find("</") {
let cs = j + crel;
let Some(cgt) = xml[cs..].find('>') else {
break;
};
let ctag = &lower[cs + 2..cs + cgt];
let cname = ctag.split_whitespace().next().unwrap_or("");
if cname == "href" || cname.ends_with(":href") {
found = Some(cs);
break;
}
j = cs + 2;
}
let Some(close) = found else {
break;
};
let value = xml[open_end..close].trim().to_string();
if !value.is_empty() {
out.push(value);
}
i = close + 1;
}
out.sort();
out.dedup();
out
}
pub fn prop_href_to_webdav(base: &str, href: &str) -> String {
if href.starts_with("webdav://") || href.starts_with("webdavs://") {
return href.to_string();
}
if href.starts_with("http://") || href.starts_with("https://") {
if let Ok(u) = url::Url::parse(href) {
let scheme = if u.scheme() == "https" { "webdavs" } else { "webdav" };
let mut s = format!("{scheme}://{}", u.host_str().unwrap_or(""));
if let Some(port) = u.port() {
s.push_str(&format!(":{port}"));
}
s.push_str(u.path());
if let Some(q) = u.query() {
s.push_str(&format!("?{q}"));
}
return s;
}
return href.to_string();
}
let Ok(b) = url::Url::parse(base) else {
return href.to_string();
};
let scheme = b.scheme().to_string();
let host = b.host_str().unwrap_or("").to_string();
let port_part = b.port().map(|p| format!(":{p}")).unwrap_or_default();
if href.starts_with('/') {
return format!("{scheme}://{host}{port_part}{href}");
}
let mut dir = b.path().to_string();
if !dir.ends_with('/') {
if let Some(pos) = dir.rfind('/') {
dir.truncate(pos + 1);
} else {
dir = "/".to_string();
}
}
format!("{scheme}://{host}{port_part}{dir}{href}")
}
fn percent_decode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let b = s.as_bytes();
let mut i = 0;
while i < b.len() {
if b[i] == b'%'
&& i + 2 < b.len()
&& let (Some(h), Some(l)) = (hexval(b[i + 1]), hexval(b[i + 2]))
{
out.push((h * 16 + l) as char);
i += 3;
continue;
}
out.push(b[i] as char);
i += 1;
}
out
}
fn hexval(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
impl Input for WebdavInput {
fn label(&self) -> &'static str {
"webdav"
}
async fn open(&self) -> Result<()> {
match self.size().await? {
Some(_) => Ok(()),
None => bail!("webdav object not found: {}", self.url),
}
}
async fn size(&self) -> Result<Option<u64>> {
let target = self.http_url()?;
let client = Self::client(None)?;
if let Ok(resp) = client.head(&target).send().await
&& resp.status().is_success()
&& let Some(v) = resp.headers().get(reqwest::header::CONTENT_LENGTH)
&& let Ok(s) = v.to_str()
&& let Ok(n) = s.trim().parse::<u64>()
{
return Ok(Some(n));
}
let xml = self.propfind("0", None).await?;
for h in parse_propfind_hrefs(&xml) {
let _ = h;
}
if let Some(n) = getcontentlength_of(&xml) {
return Ok(Some(n));
}
let input = HttpInput::new(target);
input.size().await
}
async fn read_range(&self, offset: u64, len: u64) -> Result<Vec<u8>> {
if len == 0 {
return Ok(Vec::new());
}
let target = self.http_url()?;
let input = HttpInput::new(target);
input.read_range(offset, len).await
}
async fn download(&self, op: &Operation, out: &Output) -> Result<EngineSummary> {
let target = match out {
Output::File(p) => p.clone(),
_ => bail!("webdav input writes to Output::File only (use -o <PATH>)"),
};
let http_url = self.http_url()?;
let (retries, limit, proxy) = match op {
Operation::Download(p) => (p.retries, p.speed_limit_bps, p.proxy.clone()),
_ => bail!("webdav input needs Operation::Download"),
};
let part = part_path(&target);
let meta = meta_path(&target);
let sentinel = pause_sentinel(&target);
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 input = HttpInput::new(http_url);
let hop = Operation::Download(crate::engine::DownloadParams {
connections: crate::config::DEFAULT_CONNECTIONS,
speed_limit_bps: limit,
retries,
mirrors: Vec::new(),
allow_h3: false,
auto_mirror: false,
proxy,
});
let sum = input.download(&hop, &Output::File(target.clone())).await?;
let _ = (part, meta, sentinel);
let _ = backoff;
let _ = total_style;
Ok(sum)
}
}
#[allow(dead_code)]
pub fn getcontentlength_of(xml: &str) -> Option<u64> {
let lower = xml.to_lowercase();
let mut i = 0;
while let Some(pos) = lower[i..].find("getcontentlength") {
let start = i + pos;
let Some(gt) = xml[start..].find('>') else {
break;
};
let open_end = start + gt + 1;
let rest = &lower[open_end..];
let Some(close) = rest.find('<') else {
break;
};
let val = xml[open_end..open_end + close].trim();
if let Ok(n) = val.parse::<u64>() {
return Some(n);
}
i = open_end + close + 1;
}
None
}
#[allow(dead_code)]
pub fn is_collection_xml(xml: &str) -> bool {
xml.to_lowercase().contains("<collection")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_webdav_urls() {
let p = WebdavInput::parse("webdav://example.com/files/a.bin").unwrap();
assert_eq!(p.host, "example.com");
assert_eq!(p.port, 80);
assert!(!p.tls);
assert_eq!(p.path, "/files/a.bin");
let p = WebdavInput::parse("webdavs://bob:sekret@example.com:8443/f.bin").unwrap();
assert!(p.tls);
assert_eq!(p.port, 8443);
assert_eq!((p.user.as_str(), p.pass.as_str()), ("bob", "sekret"));
assert!(WebdavInput::parse("https://example.com/f").is_err());
assert!(WebdavInput::parse("webdav://").is_err());
}
#[test]
fn http_mapping_keeps_path_and_auth() {
let i = WebdavInput::new("webdav://example.com/f/a.bin");
assert_eq!(i.http_url().unwrap(), "http://example.com/f/a.bin");
let i = WebdavInput::new("webdavs://example.com:8443/f/a.bin");
assert_eq!(i.http_url().unwrap(), "https://example.com:8443/f/a.bin");
let i = WebdavInput::new("webdav://bob:pw@example.com/f.bin");
assert_eq!(i.http_url().unwrap(), "http://bob:pw@example.com/f.bin");
}
#[test]
fn propfind_hrefs_parsed() {
let xml = r#"<?xml version="1.0"?><multistatus xmlns="DAV:"><response><href>/files/</href></response><response><href>/files/a.bin</href></response><response><HREF>/files/b.bin</HREF></response></multistatus>"#;
let h = parse_propfind_hrefs(xml);
assert_eq!(h, vec!["/files/", "/files/a.bin", "/files/b.bin"]);
let xml_ns = r#"<?xml version="1.0"?><D:multistatus xmlns:D="DAV:"><D:response><D:href>/files/c.bin</D:href></D:response><d:response><d:href>/files/d.bin</d:href></d:response><D:response><D:href>/files/c.bin</D:href></D:response></D:multistatus>"#;
let h_ns = parse_propfind_hrefs(xml_ns);
assert_eq!(h_ns, vec!["/files/c.bin", "/files/d.bin"]);
assert_eq!(getcontentlength_of("<a><getcontentlength>42</getcontentlength></a>"), Some(42));
assert!(is_collection_xml("<x><collection/></x>"));
assert!(!is_collection_xml("<x><file/></x>"));
}
#[test]
fn href_to_webdav_urls() {
assert_eq!(
prop_href_to_webdav("webdav://h/files/", "/files/a.bin"),
"webdav://h/files/a.bin"
);
assert_eq!(
prop_href_to_webdav("webdavs://h:8443/dir/", "a.bin"),
"webdavs://h:8443/dir/a.bin"
);
assert_eq!(
prop_href_to_webdav("webdav://h/dir/", "https://h/other.bin"),
"webdavs://h/other.bin"
);
}
}