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

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

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkInfo {
    pub index: usize,
    pub name: String,
    pub size: u64,
    pub sha256: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SplitManifest {
    pub file: String,
    pub total: u64,
    pub chunk_size: u64,
    pub total_sha256: String,
    pub chunks: Vec<ChunkInfo>,
}

#[derive(Debug, Clone, Default)]
pub struct SplitOptions {
    pub parts: Option<usize>,
    pub size: Option<u64>,
    pub out_dir: Option<PathBuf>,
}

pub fn split_file(src: &Path, opts: &SplitOptions) -> Result<(PathBuf, SplitManifest)> {
    if opts.parts.is_some() && opts.size.is_some() {
        bail!("use either --parts or --size, not both");
    }
    let meta = std::fs::metadata(src).with_context(|| format!("cannot open {}", src.display()))?;
    if !meta.is_file() {
        bail!("not a file: {}", src.display());
    }
    let total = meta.len();
    if total == 0 {
        bail!("cannot split an empty file: {}", src.display());
    }
    let chunk_size = match (opts.parts, opts.size) {
        (Some(n), None) => {
            if n == 0 {
                bail!("--parts must be >= 1");
            }
            total.div_ceil(n as u64).max(1)
        }
        (None, Some(s)) => {
            if s == 0 {
                bail!("--size must be > 0");
            }
            s
        }
        (None, None) => 10 * 1024 * 1024,
        (Some(_), Some(_)) => unreachable!(),
    };
    let count = total.div_ceil(chunk_size) as usize;
    let width = 3.max(count.to_string().len());
    let dir = opts.out_dir.clone().unwrap_or_else(|| {
        src.parent()
            .map(|p| p.to_path_buf())
            .unwrap_or_else(|| PathBuf::from("."))
    });
    std::fs::create_dir_all(&dir).with_context(|| format!("cannot create {}", dir.display()))?;
    let base = src
        .file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| "file".into());

    let mut manifest = SplitManifest {
        file: base.clone(),
        total,
        chunk_size,
        total_sha256: String::new(),
        chunks: Vec::with_capacity(count),
    };
    let mut total_hasher = sha2::Sha256::new();
    use sha2::Digest;
    use std::io::{Read, Write};
    let mut f = std::fs::File::open(src)?;
    let mut left = total;
    for i in 0..count {
        let name = format!("{base}.part-{:0width$}", i + 1);
        let want = left.min(chunk_size);
        let mut hasher = sha2::Sha256::new();
        let mut written = 0u64;
        let out_path = dir.join(&name);
        let mut out = std::fs::File::create(&out_path)
            .with_context(|| format!("cannot write {}", out_path.display()))?;
        let mut buf = [0u8; 128 * 1024];
        while written < want {
            let take = (want - written).min(buf.len() as u64) as usize;
            let n = f.read(&mut buf[..take])?;
            if n == 0 {
                break;
            }
            out.write_all(&buf[..n])?;
            hasher.update(&buf[..n]);
            total_hasher.update(&buf[..n]);
            written += n as u64;
        }
        if written != want {
            bail!(
                "short read on {} (file changed during split?)",
                src.display()
            );
        }
        manifest.chunks.push(ChunkInfo {
            index: i + 1,
            name,
            size: written,
            sha256: hasher
                .finalize()
                .iter()
                .map(|b| format!("{b:02x}"))
                .collect(),
        });
        left -= written;
    }
    manifest.total_sha256 = total_hasher
        .finalize()
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect();
    let manifest_path = dir.join(format!("{base}.xget-parts.json"));
    let raw = serde_json::to_string_pretty(&manifest)?;
    std::fs::write(&manifest_path, raw)?;
    Ok((manifest_path, manifest))
}

pub fn join_parts(source: &Path, dest: &Path) -> Result<u64> {
    let plan = resolve_plan(source)?;
    if let Some(parent) = dest.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("cannot create {}", parent.display()))?;
    }
    let pb = indicatif::ProgressBar::new(plan.total.unwrap_or(0));
    pb.set_style(crate::engine::total_style());
    pb.set_message("join");
    use std::io::Write;
    let mut out =
        std::fs::File::create(dest).with_context(|| format!("cannot write {}", dest.display()))?;
    let mut bytes = 0u64;
    for c in &plan.chunks {
        let data =
            std::fs::read(&c.path).with_context(|| format!("cannot read {}", c.path.display()))?;
        if let Some(expect) = c.sha256.as_deref()
            && !hash_eq(&sha256_hex(&data), expect)
        {
            bail!(
                "chunk {} failed sha256 check (file changed?):\n  got      {}\n  expected {expect}",
                c.path.display(),
                sha256_hex(&data)
            );
        }
        out.write_all(&data)?;
        bytes += data.len() as u64;
        pb.inc(data.len() as u64);
    }
    out.flush()?;
    pb.finish_and_clear();
    if let Some(expect_total) = plan.total
        && bytes != expect_total
    {
        bail!("size mismatch after join: got {bytes}, expected {expect_total}");
    }
    Ok(bytes)
}

struct PlannedChunk {
    path: PathBuf,
    sha256: Option<String>,
}

struct Plan {
    chunks: Vec<PlannedChunk>,
    total: Option<u64>,
}

fn resolve_plan(source: &Path) -> Result<Plan> {
    if source.is_file() && source.extension().is_some_and(|e| e == "json") {
        let raw = std::fs::read_to_string(source)
            .with_context(|| format!("cannot read {}", source.display()))?;
        let m: SplitManifest = serde_json::from_str(&raw)
            .context("not an xget parts manifest (need *.xget-parts.json from `xget split`)")?;
        if m.chunks.is_empty() {
            bail!("manifest has no chunks: {}", source.display());
        }
        let dir = source.parent().unwrap_or_else(|| Path::new("."));
        let chunks = m
            .chunks
            .iter()
            .map(|c| PlannedChunk {
                path: dir.join(&c.name),
                sha256: Some(c.sha256.clone()),
            })
            .collect();
        return Ok(Plan {
            chunks,
            total: Some(m.total),
        });
    }
    if source.is_dir() {
        let mut manifests: Vec<PathBuf> = std::fs::read_dir(source)?
            .flatten()
            .map(|e| e.path())
            .filter(|p| {
                p.extension().is_some_and(|e| e == "json")
                    && p.file_name()
                        .is_some_and(|n| n.to_string_lossy().ends_with(".xget-parts.json"))
            })
            .collect();
        manifests.sort();
        if let Some(m) = manifests.into_iter().next() {
            return resolve_plan(&m);
        }
        let chunks = discover_chunks(source, None)?;
        return Ok(Plan {
            chunks: chunks
                .into_iter()
                .map(|p| PlannedChunk {
                    path: p,
                    sha256: None,
                })
                .collect(),
            total: None,
        });
    }
    if source.is_file() {
        let name = source
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_default();
        if let Some((prefix, _)) = split_chunk_name(&name) {
            let dir = source.parent().unwrap_or_else(|| Path::new("."));
            let chunks = discover_chunks(dir, Some(&prefix))?;
            return Ok(Plan {
                chunks: chunks
                    .into_iter()
                    .map(|p| PlannedChunk {
                        path: p,
                        sha256: None,
                    })
                    .collect(),
                total: None,
            });
        }
    }
    bail!(
        "cannot join {}: need a manifest (*.xget-parts.json), a *.part-NNN chunk, or a directory",
        source.display()
    );
}

fn split_chunk_name(name: &str) -> Option<(String, usize)> {
    let (prefix, num) = name.rsplit_once(".part-")?;
    if prefix.is_empty() || num.is_empty() || !num.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    Some((prefix.to_string(), num.parse().ok()?))
}

fn discover_chunks(dir: &Path, prefix: Option<&str>) -> Result<Vec<PathBuf>> {
    let mut found: Vec<(usize, PathBuf)> = Vec::new();
    for e in std::fs::read_dir(dir).with_context(|| format!("cannot read {}", dir.display()))? {
        let e = e?;
        let name = e.file_name().to_string_lossy().to_string();
        let Some((pfx, num)) = split_chunk_name(&name) else {
            continue;
        };
        if prefix.is_some_and(|p| p != pfx) {
            continue;
        }
        found.push((num, e.path()));
    }
    if found.is_empty() {
        bail!("no *.part-NNN chunks in {}", dir.display());
    }
    found.sort();
    for (i, (num, _)) in found.iter().enumerate() {
        if *num != i + 1 {
            bail!(
                "chunk numbering has a gap in {} (missing part-{:03})",
                dir.display(),
                i + 1
            );
        }
    }
    Ok(found.into_iter().map(|(_, p)| p).collect())
}

fn sha256_hex(data: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    Sha256::digest(data)
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

fn hash_eq(a: &str, b: &str) -> bool {
    a.eq_ignore_ascii_case(b.trim())
}

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

    fn tmpdir(tag: &str) -> (TempGuard, PathBuf) {
        let d = std::env::temp_dir().join(format!("xget-split-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        (TempGuard(d.clone()), d)
    }

    struct TempGuard(PathBuf);
    impl Drop for TempGuard {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    fn sample(n: usize) -> Vec<u8> {
        (0..n).map(|i| (i * 11 % 251) as u8).collect()
    }

    #[test]
    fn split_by_size_and_join_with_manifest() {
        let (_g, dir) = tmpdir("roundtrip");
        let src = dir.join("data.bin");
        let data = sample(5_000_000);
        std::fs::write(&src, &data).unwrap();
        let (manifest_path, m) = split_file(
            &src,
            &SplitOptions {
                size: Some(2_000_000),
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(m.chunks.len(), 3);
        assert_eq!(m.total, 5_000_000);
        let dest = dir.join("back.bin");
        let bytes = join_parts(&manifest_path, &dest).unwrap();
        assert_eq!(bytes, 5_000_000);
        assert_eq!(std::fs::read(&dest).unwrap(), data);
    }

    #[test]
    fn split_by_parts_count() {
        let (_g, dir) = tmpdir("parts");
        let src = dir.join("d.bin");
        std::fs::write(&src, sample(1000)).unwrap();
        let (_, m) = split_file(
            &src,
            &SplitOptions {
                parts: Some(4),
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(m.chunks.len(), 4);
        assert_eq!(m.chunks.iter().map(|c| c.size).sum::<u64>(), 1000);
        let err = split_file(
            &src,
            &SplitOptions {
                parts: Some(2),
                size: Some(10),
                ..Default::default()
            },
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("either"),
            "readable flags error: {err}"
        );
    }

    #[test]
    fn tampered_chunk_fails_join() {
        let (_g, dir) = tmpdir("tamper");
        let src = dir.join("d.bin");
        std::fs::write(&src, sample(3000)).unwrap();
        let (manifest_path, m) = split_file(
            &src,
            &SplitOptions {
                size: Some(1000),
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(m.chunks.len(), 3);
        std::fs::write(dir.join(&m.chunks[1].name), vec![0u8; 1000]).unwrap();
        let err = join_parts(&manifest_path, &dir.join("back.bin")).unwrap_err();
        assert!(
            err.to_string().contains("sha256 check"),
            "verification catches mismatch: {err}"
        );
    }

    #[test]
    fn join_from_first_chunk_without_manifest() {
        let (_g, dir) = tmpdir("nochunks");
        let src = dir.join("d.bin");
        let data = sample(2500);
        std::fs::write(&src, &data).unwrap();
        let (_, m) = split_file(
            &src,
            &SplitOptions {
                size: Some(1000),
                ..Default::default()
            },
        )
        .unwrap();
        std::fs::remove_file(dir.join(format!("{}.xget-parts.json", "d.bin"))).unwrap();
        let first = dir.join(&m.chunks[0].name);
        let bytes = join_parts(&first, &dir.join("back.bin")).unwrap();
        assert_eq!(bytes, 2500);
        assert_eq!(std::fs::read(dir.join("back.bin")).unwrap(), data);
    }

    #[test]
    fn join_rejects_garbage_source() {
        let (_g, dir) = tmpdir("garbage");
        let f = dir.join("note.txt");
        std::fs::write(&f, b"hi").unwrap();
        let err = join_parts(&f, &dir.join("back.bin")).unwrap_err();
        assert!(
            err.to_string().contains("cannot join"),
            "readable error: {err}"
        );
    }
}