hadris-ntfs 2.1.0

A library for reading NTFS filesystems
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
//! Integration tests for hadris-ntfs read-only support.
//!
//! Uses ntfsprogs (`mkntfs`, `ntfscp`) and optionally `ntfs-3g` (FUSE) to
//! create test NTFS images, then verifies that hadris-ntfs reads them back
//! correctly.

use std::fs::File;

use hadris_ntfs::sync::{NtfsFs, NtfsFsReadExt};

mod common;
use common::NtfsTestImage;

macro_rules! require_image {
    ($label:expr) => {
        match NtfsTestImage::new($label) {
            Some(img) => img,
            None => return,
        }
    };
}

// ---------------------------------------------------------------------------
// Blank-volume tests (only mkntfs required)
// ---------------------------------------------------------------------------

#[test]
fn open_blank_volume() {
    let img = require_image!("BlankVol");
    let file = File::open(img.path()).unwrap();
    let _fs = NtfsFs::open(file).unwrap();
}

#[test]
fn volume_metadata() {
    let img = require_image!("MetaVol");
    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    assert!(fs.cluster_size() >= 512, "cluster size too small");
    assert!(
        fs.cluster_size().is_power_of_two(),
        "cluster size not power-of-two"
    );
    assert_ne!(fs.volume_serial(), 0, "serial should be non-zero");
    assert!(fs.total_sectors() > 0);
    assert!(fs.mft_record_size() >= 512);
}

#[test]
fn root_dir_lists_system_metafiles() {
    let img = require_image!("RootDir");
    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let root = fs.root_dir();
    let entries = root.entries().unwrap();

    let names: Vec<&str> = entries.iter().map(|e| e.name()).collect();

    // Every NTFS volume has these metafiles in the root directory.
    for expected in ["$MFT", "$MFTMirr", "$Volume", "$Boot", "$Bitmap", "$UpCase"] {
        assert!(
            names.contains(&expected),
            "root dir missing {expected}; found: {names:?}"
        );
    }
}

#[test]
fn root_system_files_are_not_regular_files() {
    let img = require_image!("SysFiles");
    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let entries = fs.root_dir().entries().unwrap();

    // $MFT is a regular (non-directory) metafile
    let mft = entries.iter().find(|e| e.name() == "$MFT").unwrap();
    assert!(mft.is_file());

    // $Extend is a directory container for metadata extensions
    if let Some(extend) = entries.iter().find(|e| e.name() == "$Extend") {
        assert!(extend.is_directory());
    }
}

// ---------------------------------------------------------------------------
// File-read tests (mkntfs + ntfscp required)
// ---------------------------------------------------------------------------

#[test]
fn read_small_resident_file() {
    let img = require_image!("SmallFile");
    let content = b"Hello, NTFS!";
    assert!(img.add_file("hello.txt", content), "ntfscp failed");

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let root = fs.root_dir();
    let entries = root.entries().unwrap();

    let entry = entries.iter().find(|e| e.name() == "hello.txt");
    assert!(entry.is_some(), "hello.txt not found in root dir");

    let entry = entry.unwrap();
    assert!(entry.is_file());

    let mut reader = fs.read_file(entry).unwrap();
    let data = reader.read_to_vec().unwrap();
    assert_eq!(data, content);
}

#[test]
fn read_large_nonresident_file() {
    let img = require_image!("LargeFile");

    // 64 KiB of repeating bytes — guaranteed non-resident.
    let content: Vec<u8> = (0..=255u8).cycle().take(65536).collect();
    assert!(img.add_file("large.bin", &content), "ntfscp failed");

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let entry = fs
        .root_dir()
        .entries()
        .unwrap()
        .into_iter()
        .find(|e| e.name() == "large.bin")
        .expect("large.bin not found");

    assert!(entry.is_file());

    let mut reader = fs.read_file(&entry).unwrap();
    assert_eq!(reader.size(), 65536);

    let data = reader.read_to_vec().unwrap();
    assert_eq!(data.len(), content.len());
    assert_eq!(data, content);
}

#[test]
fn read_empty_file() {
    let img = require_image!("EmptyFile");
    assert!(img.add_file("empty.txt", b""), "ntfscp failed");

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let entry = fs
        .root_dir()
        .entries()
        .unwrap()
        .into_iter()
        .find(|e| e.name() == "empty.txt")
        .expect("empty.txt not found");

    let mut reader = fs.read_file(&entry).unwrap();
    assert_eq!(reader.size(), 0);
    assert_eq!(reader.remaining(), 0);
    let data = reader.read_to_vec().unwrap();
    assert!(data.is_empty());
}

#[test]
fn read_file_incrementally() {
    let img = require_image!("IncrRead");

    let content: Vec<u8> = (0..8192u32).map(|i| (i % 251) as u8).collect();
    assert!(img.add_file("stream.bin", &content), "ntfscp failed");

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let entry = fs
        .root_dir()
        .entries()
        .unwrap()
        .into_iter()
        .find(|e| e.name() == "stream.bin")
        .expect("stream.bin not found");

    let mut reader = fs.read_file(&entry).unwrap();
    let mut collected = Vec::new();
    let mut buf = [0u8; 137]; // odd chunk size to exercise boundary handling
    loop {
        let n = reader.read(&mut buf).unwrap();
        if n == 0 {
            break;
        }
        collected.extend_from_slice(&buf[..n]);
    }
    assert_eq!(collected.len(), content.len());
    assert_eq!(collected, content);
}

#[test]
fn find_posix_file_is_case_sensitive() {
    let img = require_image!("CaseFind");
    assert!(img.add_file("CamelCase.Txt", b"data"), "ntfscp failed");

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();
    let root = fs.root_dir();

    // Exact case
    assert!(root.find("CamelCase.Txt").unwrap().is_some());
    assert!(root.find("camelcase.txt").unwrap().is_none());
    assert!(root.find("CAMELCASE.TXT").unwrap().is_none());
}

#[test]
fn system_names_use_ntfs_upcase_table() {
    let img = require_image!("SystemCase");
    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();
    let root = fs.root_dir();

    assert!(root.find("$mft").unwrap().is_some());
    assert!(root.find("$upcase").unwrap().is_some());
}

#[test]
fn find_posix_unicode_file_is_case_sensitive() {
    let img = require_image!("UnicodeCase");
    assert!(img.add_file("Résumé.Txt", b"data"), "ntfscp failed");

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();
    let root = fs.root_dir();

    assert!(root.find("Résumé.Txt").unwrap().is_some());
    assert!(root.find("RÉSUMÉ.TXT").unwrap().is_none());
    assert!(root.find("résumé.txt").unwrap().is_none());
}

#[test]
fn find_nonexistent_returns_none() {
    let img = require_image!("NoFile");
    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let result = fs.root_dir().find("does_not_exist.txt").unwrap();
    assert!(result.is_none());
}

#[test]
fn long_filename() {
    let img = require_image!("LongName");
    let name = "This is a very long filename that exceeds the 8.3 DOS limit.txt";
    assert!(img.add_file(name, b"long name content"), "ntfscp failed");

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let entry = fs
        .root_dir()
        .entries()
        .unwrap()
        .into_iter()
        .find(|e| e.name() == name)
        .expect("long filename not found");

    assert!(entry.is_file());
    let mut reader = fs.read_file(&entry).unwrap();
    let data = reader.read_to_vec().unwrap();
    assert_eq!(data, b"long name content");
}

#[test]
fn supplementary_unicode_filename() {
    let img = require_image!("UnicodeName");
    let name = "report-\u{1F980}.txt";
    assert!(img.add_file(name, b"unicode content"), "ntfscp failed");

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();
    let entry = fs
        .root_dir()
        .entries()
        .unwrap()
        .into_iter()
        .find(|entry| entry.name() == name)
        .expect("supplementary Unicode filename not found");

    let mut reader = fs.read_file(&entry).unwrap();
    assert_eq!(reader.read_to_vec().unwrap(), b"unicode content");
}

#[test]
fn multiple_files_in_root() {
    let img = require_image!("MultiFile");

    let files: &[(&str, &[u8])] = &[
        ("alpha.txt", b"aaa"),
        ("bravo.txt", b"bbb"),
        ("charlie.txt", b"ccc"),
        ("delta.dat", b"ddd"),
        ("echo.bin", &[0xDE, 0xAD, 0xBE, 0xEF]),
    ];

    for (name, content) in files {
        assert!(img.add_file(name, content), "ntfscp failed for {name}");
    }

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();
    let entries = fs.root_dir().entries().unwrap();

    for (name, expected_content) in files {
        let entry = entries
            .iter()
            .find(|e| e.name() == *name)
            .unwrap_or_else(|| panic!("{name} not found"));

        let mut reader = fs.read_file(entry).unwrap();
        let data = reader.read_to_vec().unwrap();
        assert_eq!(&data, expected_content, "content mismatch for {name}");
    }
}

#[test]
fn open_directory_as_file_fails() {
    let img = require_image!("DirAsFile");
    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let entries = fs.root_dir().entries().unwrap();
    if let Some(dir_entry) = entries.iter().find(|e| e.is_directory()) {
        let result = fs.read_file(dir_entry);
        assert!(result.is_err(), "read_file on a directory should fail");
    }
}

// ---------------------------------------------------------------------------
// Directory tests (requires ntfs-3g FUSE mount)
// ---------------------------------------------------------------------------

#[test]
fn subdirectory_listing() {
    let img = require_image!("SubDir");

    let mounted = img.with_mounted(|mnt| {
        std::fs::create_dir(mnt.join("mydir")).unwrap();
        std::fs::write(mnt.join("mydir/one.txt"), "1").unwrap();
        std::fs::write(mnt.join("mydir/two.txt"), "22").unwrap();
        std::fs::write(mnt.join("mydir/three.txt"), "333").unwrap();
    });
    if mounted.is_none() {
        eprintln!("SKIP: ntfs-3g FUSE mount not available");
        return;
    }

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    // Root should contain "mydir"
    let root_entries = fs.root_dir().entries().unwrap();
    let dir_entry = root_entries
        .iter()
        .find(|e| e.name() == "mydir")
        .expect("mydir not in root");
    assert!(dir_entry.is_directory());

    // Open the subdirectory and list entries
    let subdir = fs.root_dir().open_dir("mydir").unwrap();
    let sub_entries = subdir.entries().unwrap();
    let sub_names: Vec<&str> = sub_entries.iter().map(|e| e.name()).collect();

    assert!(
        sub_names.contains(&"one.txt"),
        "missing one.txt: {sub_names:?}"
    );
    assert!(
        sub_names.contains(&"two.txt"),
        "missing two.txt: {sub_names:?}"
    );
    assert!(
        sub_names.contains(&"three.txt"),
        "missing three.txt: {sub_names:?}"
    );

    // Read content through the subdirectory handle
    let mut reader = subdir.open_file("two.txt").unwrap();
    let data = reader.read_to_vec().unwrap();
    assert_eq!(data, b"22");
}

#[test]
fn large_directory_uses_index_allocation() {
    let img = require_image!("LargeDir");
    let mounted = img.with_mounted(|mnt| {
        std::fs::create_dir(mnt.join("many")).unwrap();
        for index in 0..200 {
            std::fs::write(mnt.join(format!("many/file-{index:03}.txt")), [index as u8]).unwrap();
        }
    });
    if mounted.is_none() {
        eprintln!("SKIP: ntfs-3g FUSE mount not available");
        return;
    }

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();
    let entries = fs.root_dir().open_dir("many").unwrap().entries().unwrap();

    for index in 0..200 {
        let name = format!("file-{index:03}.txt");
        assert!(
            entries.iter().any(|entry| entry.name() == name),
            "missing {name}"
        );
    }
}

#[test]
fn nested_directories_and_open_path() {
    let img = require_image!("Nested");

    let mounted = img.with_mounted(|mnt| {
        std::fs::create_dir_all(mnt.join("a/b/c")).unwrap();
        std::fs::write(mnt.join("a/readme.md"), "# A").unwrap();
        std::fs::write(mnt.join("a/b/data.bin"), [0xCA, 0xFE]).unwrap();
        std::fs::write(mnt.join("a/b/c/deep.txt"), "deep content").unwrap();
    });
    if mounted.is_none() {
        eprintln!("SKIP: ntfs-3g FUSE mount not available");
        return;
    }

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    // Traverse step by step
    let dir_a = fs.root_dir().open_dir("a").unwrap();
    let a_entries = dir_a.entries().unwrap();
    assert!(a_entries.iter().any(|e| e.name() == "readme.md"));
    assert!(
        a_entries
            .iter()
            .any(|e| e.name() == "b" && e.is_directory())
    );

    let dir_b = dir_a.open_dir("b").unwrap();
    let b_entries = dir_b.entries().unwrap();
    assert!(b_entries.iter().any(|e| e.name() == "data.bin"));
    assert!(
        b_entries
            .iter()
            .any(|e| e.name() == "c" && e.is_directory())
    );

    // Read file in nested dir
    let mut reader = dir_b.open_file("data.bin").unwrap();
    assert_eq!(reader.read_to_vec().unwrap(), &[0xCA, 0xFE]);

    // Use open_path for deep navigation
    let deep = fs.open_path("a/b/c/deep.txt").unwrap();
    assert!(deep.is_file());
    assert_eq!(deep.name(), "deep.txt");

    let mut reader = fs.read_file(&deep).unwrap();
    assert_eq!(reader.read_to_vec().unwrap(), b"deep content");

    // open_path with backslash separators
    let deep2 = fs.open_path("a\\b\\c\\deep.txt").unwrap();
    assert_eq!(deep2.name(), "deep.txt");
}

#[test]
fn open_nonexistent_path_fails() {
    let img = require_image!("NoPath");

    let mounted = img.with_mounted(|mnt| {
        std::fs::create_dir(mnt.join("real")).unwrap();
        std::fs::write(mnt.join("real/file.txt"), "x").unwrap();
    });
    if mounted.is_none() {
        eprintln!("SKIP: ntfs-3g FUSE mount not available");
        return;
    }

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    assert!(fs.open_path("real/file.txt").is_ok());
    assert!(fs.open_path("real/nope.txt").is_err());
    assert!(fs.open_path("fake/file.txt").is_err());
}

#[test]
fn open_file_as_directory_fails() {
    let img = require_image!("FileAsDir");
    assert!(img.add_file("plain.txt", b"x"), "ntfscp failed");

    let file = File::open(img.path()).unwrap();
    let fs = NtfsFs::open(file).unwrap();

    let result = fs.root_dir().open_dir("plain.txt");
    assert!(result.is_err(), "open_dir on a file should fail");
}