xget 0.1.1

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

use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result, bail};

pub const HANDOFF_TIMEOUT: Duration = Duration::from_secs(5 * 60);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaptchaKind {
    Recaptcha,
    Turnstile,
    Sitekey,
    Generic,
}

impl CaptchaKind {
    pub fn label(self) -> &'static str {
        match self {
            CaptchaKind::Recaptcha => "recaptcha",
            CaptchaKind::Turnstile => "cf-turnstile",
            CaptchaKind::Sitekey => "data-sitekey",
            CaptchaKind::Generic => "captcha",
        }
    }
}

pub fn detect_captcha(html: &str) -> Option<CaptchaKind> {
    let h = html.to_lowercase();
    if h.contains("g-recaptcha") || h.contains("recaptcha") {
        Some(CaptchaKind::Recaptcha)
    } else if h.contains("cf-turnstile") || h.contains("turnstile") {
        Some(CaptchaKind::Turnstile)
    } else if h.contains("data-sitekey") {
        Some(CaptchaKind::Sitekey)
    } else if h.contains("captcha") {
        Some(CaptchaKind::Generic)
    } else {
        None
    }
}

pub fn open_in_browser(url: &str) {
    for prog in ["xdg-open", "open"] {
        if std::process::Command::new(prog)
            .arg(url)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
            .is_ok()
        {
            return;
        }
    }
}

fn browser_matches(browser: Option<&str>, aliases: &[&str]) -> bool {
    match browser {
        None => true,
        Some(b) => {
            let b = b.to_lowercase();
            if b == "auto" {
                return true;
            }
            aliases.iter().any(|a| b.contains(a))
        }
    }
}

fn mtime_of(path: &Path) -> Option<std::time::SystemTime> {
    std::fs::metadata(path).and_then(|m| m.modified()).ok()
}

pub fn cookie_candidates(browser: Option<&str>) -> Vec<PathBuf> {
    let home = match dirs::home_dir() {
        Some(h) => h,
        None => return Vec::new(),
    };
    let mut tagged: Vec<(PathBuf, &'static str)> = Vec::new();

    let ff_bases: &[(&str, &[&str])] = &[
        (".mozilla/firefox", &["firefox"]),
        (".librewolf", &["librewolf"]),
        (".zen", &["zen"]),
        (".waterwolf", &["waterfox"]),
        (".waterfox", &["waterfox"]),
        (".tor-browser", &["tor"]),
    ];
    let gecko_group = ["gecko", "firefox-family", "mozilla"];
    for (rel, tags) in ff_bases {
        let mut aliases: Vec<&str> = tags.to_vec();
        aliases.extend(gecko_group);
        if !browser_matches(browser, &aliases) {
            continue;
        }
        let base = home.join(rel);
        if let Ok(rd) = std::fs::read_dir(&base) {
            for e in rd.flatten() {
                let p = e.path();
                let name = p
                    .file_name()
                    .map(|s| s.to_string_lossy().to_string())
                    .unwrap_or_default();
                if p.is_dir() && (name.ends_with(".default") || name.contains("default")) {
                    tagged.push((p.join("cookies.sqlite"), tags[0]));
                    tagged.push((p.join("cookies.txt"), tags[0]));
                }
            }
        }
    }
    let ch_roots: &[(&str, &'static str, &[&str])] = &[
        ("google-chrome", "chrome", &["chrome", "google", "chromium"]),
        ("chromium", "chromium", &["chromium", "chrome", "ungoogled"]),
        ("ungoogled-chromium", "chromium", &["ungoogled", "chromium"]),
        (
            "BraveSoftware/Brave-Browser",
            "brave",
            &["brave", "chromium"],
        ),
        ("microsoft-edge", "edge", &["edge", "microsoft", "chromium"]),
        ("opera", "opera", &["opera", "chromium"]),
        ("vivaldi", "vivaldi", &["vivaldi", "chromium"]),
        ("net.imput.helium", "helium", &["helium", "chromium"]),
        ("helium", "helium", &["helium", "chromium"]),
        ("arc", "arc", &["arc", "chromium"]),
        ("yandex", "yandex", &["yandex", "chromium"]),
    ];
    let profiles = ["Default", "Profile 1", "Profile 2", ""];
    for (root, tag, aliases) in ch_roots {
        if !browser_matches(browser, aliases) {
            continue;
        }
        for prof in profiles {
            let dir = if prof.is_empty() {
                home.join(".config").join(root)
            } else {
                home.join(".config").join(root).join(prof)
            };
            tagged.push((dir.join("Cookies"), tag));
            tagged.push((dir.join("cookies.txt"), tag));
        }
    }
    tagged.sort_by_key(|(p, _)| std::cmp::Reverse(mtime_of(p)));
    tagged.into_iter().map(|(p, _)| p).collect()
}

pub fn parse_netscape_jar(text: &str) -> String {
    let mut pairs = Vec::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let cols: Vec<&str> = line.split('\t').collect();
        if cols.len() >= 7 && !cols[5].is_empty() {
            pairs.push(format!("{}={}", cols[5], cols[6]));
        }
    }
    pairs.join("; ")
}

pub fn scan_cookie_tokens(bytes: &[u8]) -> String {
    let text = String::from_utf8_lossy(bytes);
    let mut pairs = Vec::new();
    for tok in text.split(|c: char| c.is_whitespace() || matches!(c, ';' | '"' | '\'' | ',' | '\0'))
    {
        let tok = tok.trim().trim_matches(|c| c == '"' || c == '\'');
        let Some((name, value)) = tok.split_once('=') else {
            continue;
        };
        let name = name.trim();
        let value = value.trim();
        if !(2..=64).contains(&name.len()) || !(1..=512).contains(&value.len()) {
            continue;
        }
        if !name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
        {
            continue;
        }
        if name.eq_ignore_ascii_case("expires") || name.eq_ignore_ascii_case("path") {
            continue;
        }
        let pair = format!("{name}={value}");
        if !pairs.contains(&pair) {
            pairs.push(pair);
        }
        if pairs.len() >= 32 {
            break;
        }
    }
    pairs.join("; ")
}

pub fn cookies_from_file(path: &Path) -> Result<String> {
    let bytes = std::fs::read(path).with_context(|| format!("cannot read {}", path.display()))?;
    let text = String::from_utf8_lossy(&bytes);
    if text
        .lines()
        .any(|l| l.starts_with("#HttpOnly") || l.split('\t').count() >= 7)
    {
        Ok(parse_netscape_jar(&text))
    } else {
        Ok(scan_cookie_tokens(&bytes))
    }
}

pub fn load_session_cookies(browser: Option<&str>) -> Option<String> {
    for cand in cookie_candidates(browser) {
        if let Ok(header) = cookies_from_file(&cand)
            && !header.trim().is_empty()
        {
            return Some(header);
        }
    }
    None
}

pub async fn wait_for_manual_solution<F>(timeout: Duration, mut poll: F) -> Result<String>
where
    F: FnMut() -> Option<String>,
{
    let start = std::time::Instant::now();
    loop {
        if let Some(s) = poll() {
            let s = s.trim().to_string();
            if !s.is_empty() {
                return Ok(s);
            }
        }
        if start.elapsed() >= timeout {
            bail!("captcha: no solution within {}s", timeout.as_secs());
        }
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

pub async fn wait_for_profile_cookies(browser: Option<&str>, timeout: Duration) -> Result<String> {
    let b = browser.map(str::to_string);
    wait_for_manual_solution(timeout, move || load_session_cookies(b.as_deref())).await
}

pub async fn download_with_cookies(
    url: &str,
    out_path: &Path,
    cookies: &str,
    expected_total: Option<u64>,
) -> Result<u64> {
    if let Some(parent) = out_path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("cannot create {}", parent.display()))?;
    }
    let client = reqwest::Client::builder()
        .connect_timeout(Duration::from_secs(10))
        .build()
        .context("cannot create HTTP client")?;
    let total = match expected_total {
        Some(t) => t,
        None => probe_size_with_cookies(&client, url, cookies)
            .await?
            .with_context(|| format!("captcha: unknown size for {url}"))?,
    };
    loop {
        let done = std::fs::metadata(out_path).map(|m| m.len()).unwrap_or(0);
        if done >= total {
            return Ok(done.min(total));
        }
        let end = (done + 8 * 1024 * 1024).min(total) - 1;
        let resp = client
            .get(url)
            .header("Cookie", cookies)
            .header(reqwest::header::RANGE, format!("bytes={done}-{end}"))
            .header(reqwest::header::ACCEPT_ENCODING, "identity")
            .send()
            .await
            .with_context(|| format!("captcha: GET {url} failed"))?;
        let status = resp.status().as_u16();
        if status == 401 || status == 403 {
            bail!("captcha: session rejected (HTTP {status}) - solve again");
        }
        if status != 200 && status != 206 {
            bail!("captcha: unexpected HTTP {status} for {url}");
        }
        let body = resp.bytes().await.context("captcha: cannot read body")?;
        append_bytes(out_path, &body)?;
        if status == 200 {
            let len = std::fs::metadata(out_path).map(|m| m.len()).unwrap_or(0);
            if len != total {
                bail!("captcha: server ignored Range (got {len}, want {total})");
            }
            return Ok(len);
        }
    }
}

async fn probe_size_with_cookies(
    client: &reqwest::Client,
    url: &str,
    cookies: &str,
) -> Result<Option<u64>> {
    let resp = client
        .get(url)
        .header("Cookie", cookies)
        .header(reqwest::header::RANGE, "bytes=0-0")
        .header(reqwest::header::ACCEPT_ENCODING, "identity")
        .send()
        .await?;
    if resp.status() == reqwest::StatusCode::PARTIAL_CONTENT
        && let Some(v) = resp.headers().get(reqwest::header::CONTENT_RANGE)
        && let Ok(s) = v.to_str()
        && let Some(total) = s
            .rsplit('/')
            .next()
            .and_then(|t| t.trim().parse::<u64>().ok())
    {
        return Ok(Some(total));
    }
    Ok(resp
        .headers()
        .get(reqwest::header::CONTENT_LENGTH)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.trim().parse::<u64>().ok()))
}

fn append_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .with_context(|| format!("cannot write {}", path.display()))?;
    f.write_all(bytes)
        .with_context(|| format!("cannot write {}", path.display()))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_all_shapes() {
        assert_eq!(
            detect_captcha(r#"<div class="g-recaptcha" data-sitekey="abc"></div>"#),
            Some(CaptchaKind::Recaptcha)
        );
        assert_eq!(
            detect_captcha(r#"<div class="cf-turnstile" data-sitekey="x"></div>"#),
            Some(CaptchaKind::Turnstile)
        );
        assert_eq!(
            detect_captcha(r#"<div data-sitekey="abc">check</div>"#),
            Some(CaptchaKind::Sitekey)
        );
        assert_eq!(
            detect_captcha(r#"<html><body><div id="fake-captcha">solve me</div></body></html>"#),
            Some(CaptchaKind::Generic)
        );
        assert_eq!(
            detect_captcha("<html><body><a href=/f.bin>dl</a></body></html>"),
            None
        );
        assert_eq!(detect_captcha("binary \x00\x01"), None);
    }

    #[test]
    fn jar_parsing_joins_pairs() {
        let jar = "# Netscape HTTP Cookie File\n.example.com\tTRUE\t/\tFALSE\t0\tsession\tabc123\n.example.com\tTRUE\t/\tFALSE\t0\tother\t1\n";
        assert_eq!(parse_netscape_jar(jar), "session=abc123; other=1");
        assert_eq!(parse_netscape_jar("# only comments\n"), "");
    }

    #[test]
    fn token_scan_finds_session() {
        let raw = b"SQLite format 3\x00moz_cookies\x00session=solved42\x00other noise";
        let header = scan_cookie_tokens(raw);
        assert!(header.contains("session=solved42"), "scan: {header}");
    }

    #[tokio::test]
    async fn mock_captcha_then_session_takeover() {
        use axum::response::IntoResponse;
        let payload: Vec<u8> = (0..150_000u32).map(|i| (i % 251) as u8).collect();
        let payload2 = payload.clone();
        let app = axum::Router::new()
            .route(
                "/page",
                axum::routing::get(|| async {
                    "<html><body><div id=\"fake-captcha\" data-sitekey=\"test-key\">solve me</div></body></html>"
                }),
            )
            .route(
                "/file",
                axum::routing::get(move |headers: axum::http::HeaderMap| {
                    let payload = payload2.clone();
                    async move {
                        let cookie = headers
                            .get("cookie")
                            .and_then(|v| v.to_str().ok())
                            .unwrap_or("");
                        if !cookie.contains("session=solved") {
                            return (
                                axum::http::StatusCode::FORBIDDEN,
                                "captcha required".to_string(),
                            )
                                .into_response();
                        }
                        let total = payload.len() as u64;
                        let range: Option<(u64, u64)> = headers
                            .get("range")
                            .and_then(|v| v.to_str().ok())
                            .and_then(|s| {
                                let s = s.strip_prefix("bytes=")?;
                                let (a, b) = s.split_once('-')?;
                                Some((a.parse().ok()?, b.parse().ok()?))
                            });
                        match range {
                            Some((from, to)) if from < total => {
                                let to = to.min(total - 1);
                                (
                                    axum::http::StatusCode::PARTIAL_CONTENT,
                                    [("content-range", format!("bytes {from}-{to}/{total}"))],
                                    payload[from as usize..=to as usize].to_vec(),
                                )
                                    .into_response()
                            }
                            _ => (axum::http::StatusCode::OK, payload).into_response(),
                        }
                    }
                }),
            );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });
        let base = format!("http://{addr}");
        let client = reqwest::Client::new();

        let html = client
            .get(format!("{base}/page"))
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        assert_eq!(detect_captcha(&html), Some(CaptchaKind::Sitekey));

        let denied = client.get(format!("{base}/file")).send().await.unwrap();
        assert_eq!(denied.status().as_u16(), 403);

        let dir = std::env::temp_dir().join(format!("xget-captcha-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let jar = dir.join("cookies.txt");
        std::fs::write(&jar, "# Netscape HTTP Cookie File\n").unwrap();
        let jar2 = jar.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(100)).await;
            std::fs::write(
                &jar2,
                "# Netscape HTTP Cookie File\n.example.com\tTRUE\t/\tFALSE\t0\tsession\tsolved\n",
            )
            .unwrap();
        });
        let cookies = wait_for_manual_solution(Duration::from_secs(5), || {
            cookies_from_file(&jar)
                .ok()
                .filter(|h| h.contains("session="))
        })
        .await
        .unwrap();
        assert!(cookies.contains("session=solved"));

        let out = dir.join("f.bin");
        let n = download_with_cookies(
            &format!("{base}/file"),
            &out,
            &cookies,
            Some(payload.len() as u64),
        )
        .await
        .unwrap();
        assert_eq!(n, payload.len() as u64);
        assert_eq!(std::fs::read(&out).unwrap(), payload);

        let pasted = wait_for_manual_solution(Duration::from_secs(2), || {
            Some(format!("{base}/file").replace("http://", "http://"))
        })
        .await
        .unwrap();
        assert!(pasted.starts_with("http://"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn handoff_timeout_is_readable() {
        let err = wait_for_manual_solution(Duration::from_millis(600), || None)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("no solution"), "timeout: {err}");
    }
}