xget 0.1.2

xget: fast multi-connection download manager for the terminal: segmented Range downloads, queue, torrents, and curl-like requests.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
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"
        );
    }
}