torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
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
//! Symlink- and hardlink-safe opens under a host download root.
//!
//! Lexical path checks alone are TOCTOU-prone. On Unix we walk with `openat` +
//! `O_NOFOLLOW` and require regular files with `nlink == 1` (hardlinks would
//! allow same-FS jail escape). Symlink components are rejected.

use std::fs::File as StdFile;
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};

use tokio::fs::File as TokioFile;

use crate::error::{Error, Result};
use crate::security::paths::{ensure_path_within_root, join_under_root, sanitize_torrent_relative_path};

/// Ensure `root/relative` exists as a real directory tree (no symlink components).
pub fn ensure_dir_under_root(root: &Path, relative: &Path) -> Result<PathBuf> {
    let relative = if relative.as_os_str().is_empty() {
        PathBuf::new()
    } else {
        sanitize_torrent_relative_path(relative)?
    };
    let target = if relative.as_os_str().is_empty() {
        root.to_path_buf()
    } else {
        join_under_root(root, &relative)?
    };
    ensure_path_within_root(root, &target)?;

    #[cfg(unix)]
    {
        ensure_dir_openat(root, &relative)?;
        Ok(target)
    }

    #[cfg(not(unix))]
    {
        let mut cursor = root.to_path_buf();
        for component in relative.components() {
            let Component::Normal(part) = component else {
                return Err(Error::Store(format!(
                    "invalid directory component under {}",
                    root.display()
                )));
            };
            cursor.push(part);
            match std::fs::symlink_metadata(&cursor) {
                Ok(meta) if meta.file_type().is_symlink() => {
                    return Err(Error::Store(format!(
                        "refusing symlink directory: {}",
                        cursor.display()
                    )));
                }
                Ok(meta) if meta.is_dir() => {}
                Ok(_) => {
                    return Err(Error::Store(format!(
                        "path exists and is not a directory: {}",
                        cursor.display()
                    )));
                }
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    std::fs::create_dir(&cursor).map_err(|e| {
                        Error::Store(format!("create_dir {}: {e}", cursor.display()))
                    })?;
                    let meta = std::fs::symlink_metadata(&cursor)?;
                    if meta.file_type().is_symlink() || !meta.is_dir() {
                        return Err(Error::Store(format!(
                            "directory create raced to non-dir: {}",
                            cursor.display()
                        )));
                    }
                }
                Err(err) => return Err(Error::Io(err)),
            }
        }
        Ok(target)
    }
}

/// Open a content file for read/write without following symlinks (final or intermediate).
pub fn open_content_rw(root: &Path, relative: &Path) -> Result<StdFile> {
    open_under_root(root, relative, true, false)
}

/// Create (or open) a content file and set its length without following symlinks.
pub fn create_content_with_len(root: &Path, relative: &Path, length: u64) -> Result<()> {
    let file = open_under_root(root, relative, true, true)?;
    file.set_len(length)?;
    Ok(())
}

/// Open an existing content file for reading without following symlinks.
pub fn open_content_read(root: &Path, relative: &Path) -> Result<StdFile> {
    open_under_root(root, relative, false, false)
}

/// Read all bytes of a file under `root` via the openat walk.
pub fn read_bytes_under_root(root: &Path, relative: &Path) -> Result<Vec<u8>> {
    let mut file = open_content_read(root, relative)?;
    let mut buf = Vec::new();
    file.read_to_end(&mut buf)?;
    Ok(buf)
}

/// Read at most `max` bytes; refuse larger files without buffering them fully.
pub fn read_bytes_under_root_capped(root: &Path, relative: &Path, max: usize) -> Result<Vec<u8>> {
    let mut file = open_content_read(root, relative)?;
    let meta = file.metadata()?;
    let len = usize::try_from(meta.len()).unwrap_or(usize::MAX);
    if len > max {
        return Err(Error::Store(format!(
            "file exceeds size limit ({max} bytes)"
        )));
    }
    let mut buf = Vec::with_capacity(len);
    file.read_to_end(&mut buf)?;
    if buf.len() > max {
        return Err(Error::Store(format!(
            "file exceeds size limit ({max} bytes)"
        )));
    }
    Ok(buf)
}

/// Write (create/truncate) a file under `root` via the openat walk.
pub fn write_bytes_under_root(root: &Path, relative: &Path, data: &[u8]) -> Result<()> {
    let mut file = open_under_root(root, relative, true, true)?;
    file.set_len(0)?;
    file.write_all(data)?;
    file.sync_all()?;
    Ok(())
}

/// Open an absolute path for reading without following a final-component symlink.
///
/// Intermediate path components are not walked with openat; use jailed helpers for
/// content under a download root. On Unix, `O_NOFOLLOW` + regular-file checks apply.
pub fn open_nofollow_read(path: &Path) -> Result<StdFile> {
    #[cfg(unix)]
    {
        use std::fs::OpenOptions;
        use std::os::unix::fs::OpenOptionsExt;
        let file = OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
            .open(path)
            .map_err(|err| {
                if err.raw_os_error() == Some(libc::ELOOP) {
                    Error::Store(format!("refusing symlink path: {}", path.display()))
                } else {
                    Error::Io(err)
                }
            })?;
        assert_safe_regular_file(&file, path.as_os_str())?;
        Ok(file)
    }
    #[cfg(not(unix))]
    {
        open_path_nofollow(path, false, false)
    }
}

pub async fn open_content_rw_async(root: &Path, relative: &Path) -> Result<TokioFile> {
    let root = root.to_path_buf();
    let relative = relative.to_path_buf();
    let std_file = tokio::task::spawn_blocking(move || open_content_rw(&root, &relative))
        .await
        .map_err(|err| Error::Store(format!("open_content_rw join: {err}")))??;
    Ok(TokioFile::from_std(std_file))
}

pub async fn open_content_read_async(root: &Path, relative: &Path) -> Result<TokioFile> {
    let root = root.to_path_buf();
    let relative = relative.to_path_buf();
    let std_file = tokio::task::spawn_blocking(move || open_content_read(&root, &relative))
        .await
        .map_err(|err| Error::Store(format!("open_content_read join: {err}")))??;
    Ok(TokioFile::from_std(std_file))
}

pub async fn create_content_with_len_async(
    root: &Path,
    relative: &Path,
    length: u64,
) -> Result<()> {
    let root = root.to_path_buf();
    let relative = relative.to_path_buf();
    tokio::task::spawn_blocking(move || create_content_with_len(&root, &relative, length))
        .await
        .map_err(|err| Error::Store(format!("create_content join: {err}")))?
}

pub async fn read_bytes_under_root_async(root: &Path, relative: &Path) -> Result<Vec<u8>> {
    let root = root.to_path_buf();
    let relative = relative.to_path_buf();
    tokio::task::spawn_blocking(move || read_bytes_under_root(&root, &relative))
        .await
        .map_err(|err| Error::Store(format!("read_bytes join: {err}")))?
}

pub async fn write_bytes_under_root_async(
    root: &Path,
    relative: &Path,
    data: Vec<u8>,
) -> Result<()> {
    let root = root.to_path_buf();
    let relative = relative.to_path_buf();
    tokio::task::spawn_blocking(move || write_bytes_under_root(&root, &relative, &data))
        .await
        .map_err(|err| Error::Store(format!("write_bytes join: {err}")))?
}

fn open_under_root(root: &Path, relative: &Path, write: bool, create: bool) -> Result<StdFile> {
    let relative = sanitize_torrent_relative_path(relative)?;
    let _ = join_under_root(root, &relative)?;

    if let Some(parent) = Path::new(&relative).parent() {
        if !parent.as_os_str().is_empty() {
            ensure_dir_under_root(root, parent)?;
        }
    }

    #[cfg(unix)]
    {
        open_under_root_openat(root, &relative, write, create)
    }

    #[cfg(not(unix))]
    {
        let path = join_under_root(root, &relative)?;
        open_path_nofollow(&path, write, create)
    }
}

#[cfg(unix)]
fn ensure_dir_openat(root: &Path, relative: &Path) -> Result<()> {
    use std::ffi::CString;
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
    use std::os::unix::ffi::OsStrExt;

    let root_fd = open_dir_fd(root)?;
    let mut current = root_fd;
    for component in relative.components() {
        let Component::Normal(part) = component else {
            return Err(Error::Store("invalid directory component".into()));
        };
        let c_name = CString::new(part.as_bytes()).map_err(|_| {
            Error::Store("directory component contains NUL".into())
        })?;
        let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
        let fd = unsafe { libc::openat(current.as_raw_fd(), c_name.as_ptr(), flags) };
        if fd >= 0 {
            current = unsafe { OwnedFd::from_raw_fd(fd) };
            continue;
        }
        let err = std::io::Error::last_os_error();
        if err.raw_os_error() == Some(libc::ENOENT) {
            let mk = unsafe {
                libc::mkdirat(current.as_raw_fd(), c_name.as_ptr(), 0o700)
            };
            if mk != 0 {
                let mk_err = std::io::Error::last_os_error();
                // Concurrent create: treat EEXIST as success and open the dir.
                if mk_err.raw_os_error() != Some(libc::EEXIST) {
                    return Err(Error::Io(mk_err));
                }
            }
            let fd = unsafe { libc::openat(current.as_raw_fd(), c_name.as_ptr(), flags) };
            if fd < 0 {
                return Err(map_open_err(std::io::Error::last_os_error(), part));
            }
            current = unsafe { OwnedFd::from_raw_fd(fd) };
        } else {
            return Err(map_open_err(err, part));
        }
    }
    Ok(())
}

#[cfg(unix)]
fn open_under_root_openat(
    root: &Path,
    relative: &Path,
    write: bool,
    create: bool,
) -> Result<StdFile> {
    use std::ffi::CString;
    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
    use std::os::unix::ffi::OsStrExt;

    let components: Vec<_> = relative.components().collect();
    let Some((file_comp, dirs)) = components.split_last() else {
        return Err(Error::Store("empty relative path".into()));
    };
    let Component::Normal(file_name) = file_comp else {
        return Err(Error::Store("invalid file component".into()));
    };

    let root_fd = open_dir_fd(root)?;
    let mut dir_fd = root_fd;
    for component in dirs {
        let Component::Normal(part) = component else {
            return Err(Error::Store("invalid directory component".into()));
        };
        let c_name = CString::new(part.as_bytes()).map_err(|_| {
            Error::Store("directory component contains NUL".into())
        })?;
        let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
        let fd = unsafe { libc::openat(dir_fd.as_raw_fd(), c_name.as_ptr(), flags) };
        if fd < 0 {
            return Err(map_open_err(std::io::Error::last_os_error(), part));
        }
        dir_fd = unsafe { OwnedFd::from_raw_fd(fd) };
    }

    let c_file = CString::new(file_name.as_bytes()).map_err(|_| {
        Error::Store("file name contains NUL".into())
    })?;
    let mut flags = libc::O_CLOEXEC | libc::O_NOFOLLOW;
    if write {
        flags |= libc::O_RDWR;
    } else {
        flags |= libc::O_RDONLY;
    }
    if create {
        flags |= libc::O_CREAT;
    }
    let fd = unsafe {
        libc::openat(dir_fd.as_raw_fd(), c_file.as_ptr(), flags, 0o600)
    };
    if fd < 0 {
        return Err(map_open_err(std::io::Error::last_os_error(), file_name));
    }
    let file = unsafe { StdFile::from_raw_fd(fd) };
    assert_safe_regular_file(&file, file_name)?;
    Ok(file)
}

#[cfg(unix)]
fn open_dir_fd(path: &Path) -> Result<std::os::fd::OwnedFd> {
    use std::ffi::CString;
    use std::os::fd::FromRawFd;
    use std::os::unix::ffi::OsStrExt;

    let c_path = CString::new(path.as_os_str().as_bytes()).map_err(|_| {
        Error::Store(format!("path contains NUL: {}", path.display()))
    })?;
    let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW;
    let fd = unsafe { libc::open(c_path.as_ptr(), flags) };
    if fd < 0 {
        let err = std::io::Error::last_os_error();
        if err.raw_os_error() == Some(libc::ELOOP) {
            return Err(Error::Store(format!(
                "refusing symlink root: {}",
                path.display()
            )));
        }
        return Err(Error::Io(err));
    }
    Ok(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) })
}

#[cfg(unix)]
fn assert_safe_regular_file(file: &StdFile, name: &std::ffi::OsStr) -> Result<()> {
    let meta = file.metadata()?;
    assert_safe_regular_metadata(&meta, &name.to_string_lossy())
}

/// Refuse non-files and hardlinks (nlink != 1) on Unix and Windows.
fn assert_safe_regular_metadata(meta: &std::fs::Metadata, label: &str) -> Result<()> {
    if !meta.is_file() {
        return Err(Error::Store(format!("refusing non-regular file: {label}")));
    }
    let nlink = file_link_count(meta)?;
    // Hardlinks allow same-FS jail escape: a link under download-dir can point
    // at an outside inode. Reflink-heavy volumes that need nlink>1 must opt in
    // via a future host flag — default is fail-closed.
    if nlink != 1 {
        return Err(Error::Store(format!(
            "refusing file with nlink={nlink} (hardlink/reflink): {label}"
        )));
    }
    Ok(())
}

#[cfg(unix)]
fn file_link_count(meta: &std::fs::Metadata) -> Result<u64> {
    use std::os::unix::fs::MetadataExt;
    Ok(meta.nlink())
}

#[cfg(windows)]
fn file_link_count(meta: &std::fs::Metadata) -> Result<u64> {
    use std::os::windows::fs::MetadataExt;
    Ok(u64::from(meta.number_of_links()))
}

#[cfg(all(not(unix), not(windows)))]
fn file_link_count(_meta: &std::fs::Metadata) -> Result<u64> {
    Err(Error::Store(
        "hardlink policy requires Unix or Windows (cannot verify nlink)".into(),
    ))
}

#[cfg(unix)]
fn map_open_err(err: std::io::Error, name: &std::ffi::OsStr) -> Error {
    if err.raw_os_error() == Some(libc::ELOOP) {
        Error::Store(format!(
            "refusing symlink path component: {}",
            name.to_string_lossy()
        ))
    } else {
        Error::Io(err)
    }
}

#[cfg(not(unix))]
fn open_path_nofollow(path: &Path, write: bool, create: bool) -> Result<StdFile> {
    use std::fs::OpenOptions;
    // Check symlink_metadata before open to close the TOCTOU window on non-Unix.
    match std::fs::symlink_metadata(path) {
        Ok(meta) if meta.file_type().is_symlink() => {
            return Err(Error::Store(format!(
                "refusing symlink content path: {}",
                path.display()
            )));
        }
        Ok(meta) if !meta.is_file() => {
            return Err(Error::Store(format!(
                "refusing non-regular file: {}",
                path.display()
            )));
        }
        Ok(_) => {}
        Err(err) if err.kind() == std::io::ErrorKind::NotFound && create => {}
        Err(err) => return Err(Error::Io(err)),
    }
    let mut opts = OpenOptions::new();
    opts.read(true);
    if write {
        opts.write(true);
    }
    if create {
        opts.create(true);
    }
    let file = opts.open(path)?;
    // Prefer handle metadata after open so nlink matches the opened file.
    let meta = file.metadata().map_err(Error::from)?;
    if meta.file_type().is_symlink() {
        return Err(Error::Store(format!(
            "refusing symlink content path: {}",
            path.display()
        )));
    }
    assert_safe_regular_metadata(&meta, &path.display().to_string())?;
    Ok(file)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read, Write};

    #[test]
    fn rejects_symlink_file_on_unix() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        let target = root.join("outside.bin");
        std::fs::write(&target, b"secret").expect("write");
        let link = root.join("evil.bin");
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(&target, &link).expect("symlink");
            let err = open_content_rw(root, Path::new("evil.bin"));
            assert!(err.is_err(), "symlink open must fail");
        }
        #[cfg(not(unix))]
        {
            let _ = (target, link);
        }
    }

    #[test]
    fn rejects_hardlink_on_unix() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        #[cfg(unix)]
        {
            let outside = dir.path().join("outside-secret");
            std::fs::write(&outside, b"secret").expect("write");
            let link = root.join("linked.bin");
            std::fs::hard_link(&outside, &link).expect("hardlink");
            let err = open_content_read(root, Path::new("linked.bin"));
            assert!(err.is_err(), "hardlink open must fail");
        }
        #[cfg(not(unix))]
        {
            let _ = root;
        }
    }

    #[test]
    fn rejects_hardlink_on_windows() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        #[cfg(windows)]
        {
            let outside = dir.path().join("outside-secret");
            std::fs::write(&outside, b"secret").expect("write");
            let link = root.join("linked.bin");
            std::fs::hard_link(&outside, &link).expect("hardlink");
            let err = open_content_read(root, Path::new("linked.bin"));
            assert!(
                err.is_err(),
                "Windows hardlink open must fail (nlink check)"
            );
        }
        #[cfg(not(windows))]
        {
            let _ = root;
        }
    }

    #[test]
    fn creates_and_reads_real_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        create_content_with_len(root, Path::new("a/b.bin"), 8).expect("create");
        {
            let mut f = open_content_rw(root, Path::new("a/b.bin")).expect("rw");
            f.write_all(b"abcdefgh").expect("write");
        }
        let mut buf = Vec::new();
        open_content_read(root, Path::new("a/b.bin"))
            .expect("read")
            .read_to_end(&mut buf)
            .expect("read_to_end");
        assert_eq!(buf, b"abcdefgh");
    }

    #[test]
    fn write_bytes_roundtrip() {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path();
        write_bytes_under_root(root, Path::new(".torrentdht/x.bin"), b"sidecar").expect("write");
        let got = read_bytes_under_root(root, Path::new(".torrentdht/x.bin")).expect("read");
        assert_eq!(got, b"sidecar");
    }
}