xget 0.1.0

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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result, bail};
use reqwest::header::{ACCEPT, CONTENT_TYPE, COOKIE, REFERER, SET_COOKIE, USER_AGENT};

#[derive(Debug, Clone)]
pub struct ReqOptions {
    pub method: Option<String>,
    pub headers: Vec<String>,
    pub data: Vec<String>,
    pub json: Option<String>,
    pub head: bool,
    pub follow: bool,
    pub max_redirs: usize,
    pub silent: bool,
    pub verbose: bool,
    pub max_time: Option<f64>,
    pub basic_auth: Option<String>,
    pub cookie: Option<String>,
    pub cookiejar: Option<PathBuf>,
    pub proxy: Option<String>,
    pub insecure: bool,
    pub cert: Option<PathBuf>,
    pub key: Option<PathBuf>,
    pub user_agent: Option<String>,
    pub referer: Option<String>,
    pub output: Option<PathBuf>,
}

impl Default for ReqOptions {
    fn default() -> Self {
        Self {
            method: None,
            headers: Vec::new(),
            data: Vec::new(),
            json: None,
            head: false,
            follow: false,
            max_redirs: 10,
            silent: false,
            verbose: false,
            max_time: None,
            basic_auth: None,
            cookie: None,
            cookiejar: None,
            proxy: None,
            insecure: false,
            cert: None,
            key: None,
            user_agent: None,
            referer: None,
            output: None,
        }
    }
}

#[derive(Debug)]
pub struct FetchResult {
    pub status: u16,
    pub version: String,
    pub headers: reqwest::header::HeaderMap,
    pub body: Vec<u8>,
    pub final_url: String,
}

pub fn parsed_http_url(url: &str) -> Result<url::Url> {
    let u = url::Url::parse(url).with_context(|| format!("invalid URL: {url}"))?;
    match u.scheme() {
        "http" | "https" => Ok(u),
        other => bail!(
            "xget req handles only http(s): {url} (scheme '{other}' is out of scope — ftp/smtp/imap need a dedicated client like curl or lftp)"
        ),
    }
}

pub fn parse_header_arg(s: &str) -> Result<(String, String)> {
    let (name, value) = s
        .split_once(':')
        .with_context(|| format!("bad header (need 'Name: value'): {s}"))?;
    if name.trim().is_empty() {
        bail!("bad header (need 'Name: value'): {s}");
    }
    Ok((name.trim().to_string(), value.trim().to_string()))
}

fn body_for(
    data: &[String],
    json: Option<&str>,
) -> Result<(Option<Vec<u8>>, Option<&'static str>)> {
    if let Some(j) = json {
        if !data.is_empty() {
            bail!("cannot combine --data with --json");
        }
        return Ok((Some(j.as_bytes().to_vec()), Some("application/json")));
    }
    if data.is_empty() {
        return Ok((None, None));
    }
    Ok((
        Some(data.join("&").into_bytes()),
        Some("application/x-www-form-urlencoded"),
    ))
}

fn cookie_header_value(arg: &str) -> Result<String> {
    if arg.contains('=') {
        return Ok(arg.to_string());
    }
    let raw =
        std::fs::read_to_string(arg).with_context(|| format!("cannot read cookie file: {arg}"))?;
    let pairs = parse_netscape_jar(&raw);
    if pairs.is_empty() {
        return Ok(raw.lines().next().unwrap_or("").trim().to_string());
    }
    Ok(pairs
        .iter()
        .map(|(k, v)| format!("{k}={v}"))
        .collect::<Vec<_>>()
        .join("; "))
}

pub fn parse_netscape_jar(text: &str) -> Vec<(String, String)> {
    text.lines()
        .filter(|l| {
            let t = l.trim();
            !t.is_empty() && !t.starts_with('#')
        })
        .filter_map(|l| {
            let f: Vec<&str> = l.split('\t').collect();
            if f.len() >= 7 {
                Some((f[5].to_string(), f[6].to_string()))
            } else {
                None
            }
        })
        .collect()
}

pub fn save_cookiejar(path: &Path, domain: &str, set_cookies: &[String]) -> Result<()> {
    let mut jar: BTreeMap<String, String> = BTreeMap::new();
    if path.exists()
        && let Ok(raw) = std::fs::read_to_string(path)
    {
        for (k, v) in parse_netscape_jar(&raw) {
            jar.insert(k, v);
        }
    }
    for sc in set_cookies {
        let first = sc.split(';').next().unwrap_or("").trim();
        if let Some((k, v)) = first.split_once('=')
            && !k.trim().is_empty()
        {
            jar.insert(k.trim().to_string(), v.trim().to_string());
        }
    }
    let mut out = String::from("# Netscape HTTP Cookie File\n");
    for (k, v) in &jar {
        out.push_str(&format!("{domain}\tTRUE\t/\tFALSE\t0\t{k}\t{v}\n"));
    }
    if let Some(p) = path.parent()
        && !p.as_os_str().is_empty()
    {
        std::fs::create_dir_all(p).with_context(|| format!("cannot create {}", p.display()))?;
    }
    std::fs::write(path, out).with_context(|| format!("cannot write {}", path.display()))
}

fn build_client(o: &ReqOptions) -> Result<reqwest::Client> {
    let mut b = reqwest::Client::builder();
    b = if o.follow {
        b.redirect(reqwest::redirect::Policy::limited(o.max_redirs))
    } else {
        b.redirect(reqwest::redirect::Policy::none())
    };
    if let Some(t) = o.max_time {
        if t <= 0.0 {
            bail!("--max-time must be > 0");
        }
        b = b.timeout(Duration::from_secs_f64(t));
    }
    if let Some(p) = &o.proxy {
        b = b.proxy(reqwest::Proxy::all(p).with_context(|| format!("bad proxy URL: {p}"))?);
    }
    if o.insecure {
        b = b.danger_accept_invalid_certs(true);
    }
    if let Some(cert) = &o.cert {
        let mut pem = std::fs::read(cert)
            .with_context(|| format!("cannot read --cert {}", cert.display()))?;
        if let Some(key) = &o.key {
            pem.extend_from_slice(
                &std::fs::read(key)
                    .with_context(|| format!("cannot read --key {}", key.display()))?,
            );
        }
        b = b.identity(
            reqwest::Identity::from_pem(&pem)
                .context("bad --cert/--key (need a client certificate in PEM)")?,
        );
    } else if o.key.is_some() {
        bail!("--key needs --cert with the matching certificate");
    }
    b.build().context("cannot create HTTP client")
}

fn version_label(v: reqwest::Version) -> &'static str {
    match v {
        reqwest::Version::HTTP_09 => "HTTP/0.9",
        reqwest::Version::HTTP_10 => "HTTP/1.0",
        reqwest::Version::HTTP_11 => "HTTP/1.1",
        reqwest::Version::HTTP_2 => "HTTP/2",
        reqwest::Version::HTTP_3 => "HTTP/3",
        _ => "HTTP/?",
    }
}

pub async fn fetch(url: &str, o: &ReqOptions) -> Result<FetchResult> {
    let parsed = parsed_http_url(url)?;
    let (body, default_ct) = body_for(&o.data, o.json.as_deref())?;
    let method_s = o.method.clone().unwrap_or_else(|| {
        if o.head {
            "HEAD".into()
        } else if body.is_some() {
            "POST".into()
        } else {
            "GET".into()
        }
    });
    let method = reqwest::Method::from_bytes(method_s.as_bytes())
        .with_context(|| format!("bad method: {method_s}"))?;

    let mut headers = reqwest::header::HeaderMap::new();
    let mut explicit_ct = false;
    let mut explicit_accept = false;
    let mut explicit_ua = false;
    let mut explicit_referer = false;
    let mut explicit_cookie = false;
    for h in &o.headers {
        let (n, v) = parse_header_arg(h)?;
        let name = reqwest::header::HeaderName::from_bytes(n.as_bytes())
            .with_context(|| format!("bad header name: {n}"))?;
        let value = reqwest::header::HeaderValue::from_str(&v)
            .with_context(|| format!("bad header value for {n}"))?;
        explicit_ct |= name == CONTENT_TYPE;
        explicit_accept |= name == ACCEPT;
        explicit_ua |= name == USER_AGENT;
        explicit_referer |= name == REFERER;
        explicit_cookie |= name == COOKIE;
        headers.insert(name, value);
    }
    if !explicit_ua {
        headers.insert(
            USER_AGENT,
            reqwest::header::HeaderValue::from_str(
                o.user_agent.as_deref().unwrap_or("xget-req/0.1"),
            )
            .context("bad --user-agent")?,
        );
    }
    if !explicit_referer && let Some(r) = &o.referer {
        headers.insert(
            REFERER,
            reqwest::header::HeaderValue::from_str(r).context("bad --referer")?,
        );
    }
    if let Some(ct) = default_ct
        && !explicit_ct
    {
        headers.insert(CONTENT_TYPE, reqwest::header::HeaderValue::from_static(ct));
    }
    if o.json.is_some() && !explicit_accept {
        headers.insert(
            ACCEPT,
            reqwest::header::HeaderValue::from_static("application/json"),
        );
    }
    if !explicit_cookie && let Some(c) = &o.cookie {
        let v = cookie_header_value(c)?;
        if !v.is_empty() {
            headers.insert(
                COOKIE,
                reqwest::header::HeaderValue::from_str(&v).context("bad cookie value")?,
            );
        }
    }

    let client = build_client(o)?;
    let mut rb = client
        .request(method.clone(), parsed.as_str())
        .headers(headers);
    if let Some(a) = &o.basic_auth {
        let (user, pass) = a
            .split_once(':')
            .map(|(u, p)| (u, Some(p)))
            .unwrap_or((a.as_str(), None));
        rb = rb.basic_auth(user, pass);
    }
    if let Some(b) = body {
        rb = rb.body(b);
    }
    let req = rb.build().context("cannot build request")?;
    if o.verbose {
        let target = parsed.path();
        let target = match parsed.query() {
            Some(q) => format!("{target}?{q}"),
            None => target.to_string(),
        };
        eprintln!("> {} {target} HTTP/1.1", req.method());
        if let Some(h) = parsed.host_str() {
            eprintln!("> Host: {h}");
        }
        for (k, v) in req.headers() {
            eprintln!("> {}: {}", k, v.to_str().unwrap_or("?"));
        }
        eprintln!(">");
    }
    let res = client
        .execute(req)
        .await
        .with_context(|| format!("request failed: {url}"))?;
    let status = res.status().as_u16();
    let version = version_label(res.version()).to_string();
    let headers = res.headers().clone();
    let final_url = res.url().to_string();
    if o.verbose {
        eprintln!(
            "< {version} {status} {}",
            res.status().canonical_reason().unwrap_or("")
        );
        for (k, v) in &headers {
            eprintln!("< {}: {}", k, v.to_str().unwrap_or("?"));
        }
        eprintln!("<");
    }
    if let Some(jar) = &o.cookiejar {
        let set: Vec<String> = headers
            .get_all(SET_COOKIE)
            .iter()
            .filter_map(|v| v.to_str().ok().map(str::to_string))
            .collect();
        if !set.is_empty() {
            save_cookiejar(jar, parsed.host_str().unwrap_or(""), &set)?;
        }
    }
    let body = res
        .bytes()
        .await
        .context("cannot read response body")?
        .to_vec();
    Ok(FetchResult {
        status,
        version,
        headers,
        body,
        final_url,
    })
}

pub async fn run_req(url: &str, o: &ReqOptions) -> Result<()> {
    let res = fetch(url, o).await?;
    if o.head {
        println!("{} {} {}", res.version, res.status, reason_of(res.status));
        for (k, v) in &res.headers {
            println!("{}: {}", k, v.to_str().unwrap_or("?"));
        }
        return Ok(());
    }
    match &o.output {
        Some(p) if p.as_os_str() == "/dev/null" => {}
        Some(p) => {
            if let Some(parent) = p.parent()
                && !parent.as_os_str().is_empty()
            {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("cannot create {}", parent.display()))?;
            }
            std::fs::write(p, &res.body)
                .with_context(|| format!("cannot write {}", p.display()))?;
        }
        None => {
            std::io::stdout()
                .lock()
                .write_all(&res.body)
                .context("cannot write to stdout")?;
        }
    }
    if !o.silent {
        let via = if res.final_url != url {
            format!(" (via {})", res.final_url)
        } else {
            String::new()
        };
        match &o.output {
            Some(p) => eprintln!(
                "xget req: HTTP {} {} B -> {}{via}",
                res.status,
                res.body.len(),
                p.display()
            ),
            None => eprintln!("xget req: HTTP {} {} B{via}", res.status, res.body.len()),
        }
    }
    Ok(())
}

fn reason_of(status: u16) -> &'static str {
    reqwest::StatusCode::from_u16(status)
        .ok()
        .and_then(|s| s.canonical_reason())
        .unwrap_or("")
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    fn opts() -> ReqOptions {
        ReqOptions::default()
    }

    async fn handle_conn(mut sock: tokio::net::TcpStream) {
        let mut buf: Vec<u8> = Vec::new();
        let mut tmp = [0u8; 4096];
        let head_end = loop {
            match sock.read(&mut tmp).await {
                Ok(0) => return,
                Ok(n) => {
                    buf.extend_from_slice(&tmp[..n]);
                    if buf.len() > 2_000_000 {
                        return;
                    }
                    if let Some(i) = find_headers_end(&buf) {
                        break i;
                    }
                }
                Err(_) => return,
            }
        };
        let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
        let mut lines = head.lines();
        let request_line = lines.next().unwrap_or("").to_string();
        let mut hm: std::collections::HashMap<String, String> = std::collections::HashMap::new();
        for l in lines {
            if let Some((k, v)) = l.split_once(':') {
                hm.insert(k.trim().to_lowercase(), v.trim().to_string());
            }
        }
        let cl: usize = hm
            .get("content-length")
            .and_then(|v| v.parse().ok())
            .unwrap_or(0);
        while buf.len() < head_end + cl && buf.len() < 5_000_000 {
            match sock.read(&mut tmp).await {
                Ok(0) => break,
                Ok(n) => buf.extend_from_slice(&tmp[..n]),
                Err(_) => break,
            }
        }
        let mut parts = request_line.split_whitespace();
        let method = parts.next().unwrap_or("").to_string();
        let target = parts.next().unwrap_or("/").to_string();
        let body = String::from_utf8_lossy(
            &buf[head_end..head_end + cl.min(buf.len().saturating_sub(head_end))],
        )
        .to_string();

        let (status, extra, payload) = if target == "/redir" {
            (302, "location: /echo\r\n".to_string(), "go".to_string())
        } else if target == "/setcookie" {
            (
                200,
                "set-cookie: jar1=tasty; Path=/\r\n".to_string(),
                echo_json(&method, &target, &hm, &body),
            )
        } else {
            (200, String::new(), echo_json(&method, &target, &hm, &body))
        };
        let reason = match status {
            200 => "OK",
            302 => "Found",
            _ => "?",
        };
        let resp = format!(
            "HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n{extra}\r\n{payload}",
            payload.len()
        );
        let _ = sock.write_all(resp.as_bytes()).await;
    }

    fn echo_json(
        method: &str,
        target: &str,
        hm: &std::collections::HashMap<String, String>,
        body: &str,
    ) -> String {
        let get = |k: &str| hm.get(k).cloned().unwrap_or_default();
        serde_json::json!({
            "method": method,
            "path": target,
            "body": body,
            "cookie": get("cookie"),
            "echo": get("x-echo"),
            "ua": get("user-agent"),
            "referer": get("referer"),
            "auth": get("authorization"),
            "content_type": get("content-type"),
        })
        .to_string()
    }

    fn find_headers_end(buf: &[u8]) -> Option<usize> {
        buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4)
    }

    async fn spawn_echo() -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) {
        let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let a = l.local_addr().unwrap();
        let h = tokio::spawn(async move {
            loop {
                let Ok((s, _)) = l.accept().await else { break };
                tokio::spawn(handle_conn(s));
            }
        });
        (a, h)
    }

    async fn echo_body(
        addr: &std::net::SocketAddr,
        path: &str,
        o: ReqOptions,
    ) -> serde_json::Value {
        let r = fetch(&format!("http://{addr}{path}"), &o).await.unwrap();
        assert_eq!(r.status, 200);
        serde_json::from_slice(&r.body).unwrap()
    }

    #[tokio::test]
    async fn rejects_non_http() {
        for u in [
            "ftp://h/f",
            "smtp://h",
            "imap://h/x",
            "magnet:?xt=urn:btih:abc",
        ] {
            let e = format!("{}", fetch(u, &opts()).await.unwrap_err());
            assert!(e.contains("only http(s)"), "unexpected: {e}");
        }
    }

    #[tokio::test]
    async fn sends_method_headers_body() {
        let (a, _h) = spawn_echo().await;
        let mut o = opts();
        o.method = Some("PUT".into());
        o.headers = vec!["X-Echo: ping".into()];
        o.data = vec!["a=1".into(), "b=2".into()];
        let v = echo_body(&a, "/echo", o).await;
        assert_eq!(v["method"], "PUT");
        assert_eq!(v["echo"], "ping");
        assert_eq!(v["body"], "a=1&b=2");
        assert_eq!(v["content_type"], "application/x-www-form-urlencoded");
    }

    #[tokio::test]
    async fn json_sets_content_type_and_post() {
        let (a, _h) = spawn_echo().await;
        let mut o = opts();
        o.json = Some(r#"{"a":1}"#.into());
        let v = echo_body(&a, "/echo", o).await;
        assert_eq!(v["method"], "POST");
        assert_eq!(v["body"], r#"{"a":1}"#);
        assert_eq!(v["content_type"], "application/json");
    }

    #[tokio::test]
    async fn redirect_only_with_follow() {
        let (a, _h) = spawn_echo().await;
        let plain = fetch(&format!("http://{a}/redir"), &opts()).await.unwrap();
        assert_eq!(plain.status, 302);
        let mut o = opts();
        o.follow = true;
        let r = fetch(&format!("http://{a}/redir"), &o).await.unwrap();
        assert_eq!(r.status, 200);
        assert!(
            r.final_url.ends_with("/echo"),
            "unexpected: {}",
            r.final_url
        );
    }

    #[tokio::test]
    async fn cookie_send_and_jar_save() {
        let (a, _h) = spawn_echo().await;
        let mut o = opts();
        o.cookie = Some("a=1; b=2".into());
        let v = echo_body(&a, "/echo", o).await;
        assert_eq!(v["cookie"], "a=1; b=2");

        let dir = std::env::temp_dir().join(format!("xget-req-test-{}", std::process::id()));
        let jar = dir.join("jar.txt");
        let mut o2 = opts();
        o2.cookiejar = Some(jar.clone());
        fetch(&format!("http://{a}/setcookie"), &o2).await.unwrap();
        let raw = std::fs::read_to_string(&jar).unwrap();
        assert!(raw.contains("jar1\ttasty"), "unexpected jar: {raw}");

        let mut o3 = opts();
        o3.cookie = Some(jar.to_string_lossy().to_string());
        let v3 = echo_body(&a, "/echo", o3).await;
        assert!(v3["cookie"].as_str().unwrap().contains("jar1=tasty"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn auth_ua_referer_and_output_file() {
        let (a, _h) = spawn_echo().await;
        let dir = std::env::temp_dir().join(format!("xget-req-test-{}.2", std::process::id()));
        let out = dir.join("out.json");
        let mut o = opts();
        o.basic_auth = Some("me:secret".into());
        o.user_agent = Some("ua-test/1".into());
        o.referer = Some("http://ref.example/".into());
        o.output = Some(out.clone());
        o.silent = true;
        run_req(&format!("http://{a}/echo"), &o).await.unwrap();
        let v: serde_json::Value = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap();
        assert_eq!(v["ua"], "ua-test/1");
        assert_eq!(v["referer"], "http://ref.example/");
        assert!(v["auth"].as_str().unwrap().starts_with("Basic "));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn header_arg_rules() {
        assert!(parse_header_arg("X-A: b").is_ok());
        assert!(parse_header_arg("no-colon").is_err());
        assert!(parse_header_arg(": v").is_err());
    }
}