smb-server 0.12.1

SMB2/3 file-sharing server library with pluggable storage backends.
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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
use std::time::{Duration, SystemTime};

use tempfile::TempDir;

use super::*;
use crate::backend::{FILE_ATTRIBUTE_HIDDEN, FILE_ATTRIBUTE_READONLY, ShareBackend};
use crate::fs::LocalFsBackend;
use crate::fs::dir::ambient_authority;
use crate::fs::windows_dir::is_link;
use crate::path::SmbPath;

/// A backend on a new directory beside the test binary, on the build's
/// volume.
fn backend() -> (TempDir, LocalFsBackend) {
    let td = crate::tests::util::scratch_dir();
    let backend = LocalFsBackend::new(td.path()).unwrap();
    assert!(backend.capabilities().named_streams);
    (td, backend)
}

/// True if `td` is on ReFS, which cannot rename streams.
fn on_refs(td: &TempDir) -> bool {
    let dir = Dir::open_ambient_dir(td.path(), ambient_authority()).unwrap();
    volume(&dir).unwrap().refs
}

fn p(s: &str) -> SmbPath {
    s.parse().unwrap()
}

fn name(s: &str) -> StreamName {
    s.parse().unwrap()
}

fn opts(intent: OpenIntent, write: bool) -> OpenOptions {
    OpenOptions {
        read: true,
        write,
        write_attributes: write,
        intent,
        directory: false,
        non_directory: false,
        delete_on_close: false,
    }
}

/// The file id of `path`, as the backend reports it.
async fn id(backend: &LocalFsBackend, path: &str) -> u64 {
    let (h, _) = backend
        .open(&p(path), opts(OpenIntent::Open, false))
        .await
        .unwrap();
    let id = h.stat().await.unwrap().file_index;
    h.close().await.unwrap();
    id
}

/// Opens the stream `stream` of `path` as CREATE does: the file first,
/// created unless `intent` only opens, then the stream through it.
async fn open(
    backend: &LocalFsBackend,
    path: &str,
    stream: &str,
    intent: OpenIntent,
) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
    let path = p(path);
    let file_intent = match intent {
        OpenIntent::Open | OpenIntent::Truncate => OpenIntent::Open,
        _ => OpenIntent::OpenOrCreate,
    };
    let (file, _) = backend.open(&path, opts(file_intent, false)).await?;
    backend
        .open_stream(file, &path, &name(stream), opts(intent, true))
        .await
}

async fn create(backend: &LocalFsBackend, path: &str, stream: &str, data: &[u8]) {
    let (h, _) = open(backend, path, stream, OpenIntent::OpenOrCreate)
        .await
        .unwrap();
    if !data.is_empty() {
        h.write(0, data).await.unwrap();
    }
    h.close().await.unwrap();
}

async fn read_all(h: &dyn Handle) -> Vec<u8> {
    h.read(0, 1 << 20).await.unwrap().to_vec()
}

/// The stream `stream` of `path` below `td`, read on the host.
fn host_stream(td: &TempDir, path: &str, stream: &str) -> Option<Vec<u8>> {
    use std::io::Read as _;
    use std::os::windows::fs::OpenOptionsExt as _;
    let mut file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
        .open(td.path().join(format!("{path}:{stream}")))
        .ok()?;
    let mut data = Vec::new();
    file.read_to_end(&mut data).unwrap();
    Some(data)
}

/// The streams of `path` by name, with their sizes, sorted.
async fn streams(backend: &LocalFsBackend, path: &str) -> Vec<(String, u64)> {
    let (h, _) = backend
        .open(&p(path), opts(OpenIntent::Open, false))
        .await
        .unwrap();
    let mut out: Vec<_> = h
        .streams()
        .await
        .unwrap()
        .into_iter()
        .map(|s| (s.name.as_str().to_string(), s.size))
        .collect();
    h.close().await.unwrap();
    out.sort();
    out
}

#[tokio::test]
async fn streams_are_ntfs_streams_under_the_names_clients_send() {
    let (td, backend) = backend();
    let tags = "com.apple.metadata\u{F022}_kMDItemUserTags";
    create(&backend, "f.txt", tags, b"bplist00").await;
    create(&backend, "f.txt", "Zone.Identifier", b"[ZoneTransfer]").await;
    create(&backend, "f.txt", "empty", b"").await;
    create(&backend, "f.txt", "a*b?", b"x").await;
    assert_eq!(host_stream(&td, "f.txt", tags).unwrap(), b"bplist00");
    assert_eq!(
        host_stream(&td, "f.txt", "zone.identifier").unwrap(),
        b"[ZoneTransfer]"
    );
    assert_eq!(std::fs::read(td.path().join("f.txt")).unwrap(), b"");
    assert_eq!(
        streams(&backend, "f.txt").await,
        [
            ("Zone.Identifier".to_string(), 14),
            ("a*b?".to_string(), 1),
            (tags.to_string(), 8),
            ("empty".to_string(), 0),
        ]
    );

    // Made on the host, a stream is listed and read.
    std::fs::write(td.path().join("f.txt:host"), b"from the host").unwrap();
    let (h, _) = open(&backend, "f.txt", "HOST", OpenIntent::Open)
        .await
        .unwrap();
    assert_eq!(read_all(h.as_ref()).await, b"from the host");
    let info = h.stat().await.unwrap();
    assert_eq!(info.end_of_file, 13);
    assert!(info.allocation_size >= 13);
    assert!(!info.is_directory);
    h.close().await.unwrap();
}

#[tokio::test]
async fn dispositions_open_create_and_truncate_streams() {
    let (td, backend) = backend();
    std::fs::write(td.path().join("f.txt"), b"").unwrap();
    for intent in [OpenIntent::Open, OpenIntent::Truncate] {
        assert!(matches!(
            open(&backend, "f.txt", "s", intent).await,
            Err(SmbError::NotFound)
        ));
    }
    let (h, action) = open(&backend, "f.txt", "s", OpenIntent::Create)
        .await
        .unwrap();
    assert_eq!(action, OpenAction::Created);
    h.write(0, b"data").await.unwrap();
    h.close().await.unwrap();
    // Under any case, the stream opens and is not made again.
    let (h, action) = open(&backend, "f.txt", "S", OpenIntent::OpenOrCreate)
        .await
        .unwrap();
    assert_eq!(action, OpenAction::Opened);
    assert_eq!(read_all(h.as_ref()).await, b"data");
    h.close().await.unwrap();
    assert!(matches!(
        open(&backend, "f.txt", "S", OpenIntent::Create).await,
        Err(SmbError::Exists)
    ));
    for intent in [OpenIntent::Truncate, OpenIntent::OverwriteOrCreate] {
        let (h, action) = open(&backend, "f.txt", "s", intent).await.unwrap();
        assert_eq!(action, OpenAction::Overwritten);
        assert_eq!(h.stat().await.unwrap().end_of_file, 0);
        h.write(0, b"data").await.unwrap();
        h.close().await.unwrap();
    }
    let (h, action) = open(&backend, "f.txt", "t", OpenIntent::OverwriteOrCreate)
        .await
        .unwrap();
    assert_eq!(action, OpenAction::Created);
    h.close().await.unwrap();
    assert_eq!(
        streams(&backend, "f.txt").await,
        [("s".to_string(), 4), ("t".to_string(), 0)]
    );
}

#[tokio::test]
async fn writes_extend_with_zeros_and_truncate_cuts() {
    let (_td, backend) = backend();
    let (h, _) = open(&backend, "f.txt", "s", OpenIntent::Create)
        .await
        .unwrap();
    assert_eq!(h.write(4, b"xy").await.unwrap(), 2);
    assert_eq!(read_all(h.as_ref()).await, b"\0\0\0\0xy");
    h.truncate(5).await.unwrap();
    assert_eq!(read_all(h.as_ref()).await, b"\0\0\0\0x");
    h.truncate(7).await.unwrap();
    assert_eq!(read_all(h.as_ref()).await, b"\0\0\0\0x\0\0");
    assert_eq!(h.stat().await.unwrap().end_of_file, 7);
    assert!(h.read(100, 10).await.unwrap().is_empty());
    h.close().await.unwrap();
}

#[tokio::test]
async fn times_set_through_a_stream_are_the_files() {
    let (td, backend) = backend();
    let f = td.path().join("f.txt");
    std::fs::write(&f, b"data").unwrap();
    let old = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000_000);
    let modified = || std::fs::metadata(&f).unwrap().modified().unwrap();

    let (h, _) = open(&backend, "f.txt", "s", OpenIntent::Create)
        .await
        .unwrap();
    h.set_times(FileTimes {
        last_write_time: Some(crate::utils::system_time_to_filetime(old)),
        ..FileTimes::default()
    })
    .await
    .unwrap();
    assert_eq!(modified(), old);
    h.close().await.unwrap();
}

#[tokio::test]
async fn stream_handles_follow_renames_of_the_file_and_the_stream() {
    let (td, backend) = backend();
    if on_refs(&td) {
        eprintln!("skipping: ReFS cannot rename streams");
        return;
    }
    let (h, _) = open(&backend, "f.txt", "s", OpenIntent::Create)
        .await
        .unwrap();
    h.write(0, b"one").await.unwrap();
    std::fs::rename(td.path().join("f.txt"), td.path().join("g.txt")).unwrap();
    h.write(3, b"two").await.unwrap();
    assert_eq!(host_stream(&td, "g.txt", "s").unwrap(), b"onetwo");

    let (other, _) = open(&backend, "g.txt", "S", OpenIntent::Open)
        .await
        .unwrap();
    backend
        .rename_stream(
            &p("g.txt"),
            id(&backend, "g.txt").await,
            Some(&name("S")),
            Some(&name("New")),
            false,
        )
        .await
        .unwrap();
    h.write(6, b"!").await.unwrap();
    assert_eq!(read_all(other.as_ref()).await, b"onetwo!");
    assert_eq!(other.stat().await.unwrap().end_of_file, 7);
    assert_eq!(streams(&backend, "g.txt").await, [("New".to_string(), 7)]);
    h.close().await.unwrap();
    other.close().await.unwrap();
}

#[tokio::test]
async fn renames_between_named_streams() {
    let (td, backend) = backend();
    if on_refs(&td) {
        eprintln!("skipping: ReFS cannot rename streams");
        return;
    }
    create(&backend, "f.txt", "a", b"data").await;
    create(&backend, "f.txt", "b", b"").await;
    let file_id = id(&backend, "f.txt").await;
    let rename = |from: &str, to: &str, replace| {
        let (from, to) = (name(from), name(to));
        let backend = &backend;
        async move {
            backend
                .rename_stream(&p("f.txt"), file_id, Some(&from), Some(&to), replace)
                .await
        }
    };
    assert!(matches!(
        rename("A", "B", false).await,
        Err(SmbError::Exists)
    ));
    assert!(matches!(
        rename("missing", "c", false).await,
        Err(SmbError::NotFound)
    ));
    assert_eq!(
        streams(&backend, "f.txt").await,
        [("a".to_string(), 4), ("b".to_string(), 0)]
    );
    // The replaced stream goes, also under another spelling, and the
    // renamed one takes the new spelling.
    rename("A", "B", true).await.unwrap();
    assert_eq!(streams(&backend, "f.txt").await, [("B".to_string(), 4)]);
    rename("B", "c", false).await.unwrap();
    assert_eq!(host_stream(&td, "f.txt", "c").unwrap(), b"data");
    assert_eq!(streams(&backend, "f.txt").await, [("c".to_string(), 4)]);
}

#[tokio::test]
async fn renames_to_and_from_the_default_stream_move_the_data() {
    let (td, backend) = backend();
    if on_refs(&td) {
        eprintln!("skipping: ReFS cannot rename streams");
        return;
    }
    let f = td.path().join("f.txt");
    std::fs::write(&f, b"contents").unwrap();
    let file_id = id(&backend, "f.txt").await;
    backend
        .rename_stream(&p("f.txt"), file_id, None, Some(&name("s")), false)
        .await
        .unwrap();
    assert_eq!(std::fs::read(&f).unwrap(), b"");
    assert_eq!(host_stream(&td, "f.txt", "s").unwrap(), b"contents");
    backend
        .rename_stream(&p("f.txt"), file_id, Some(&name("S")), None, true)
        .await
        .unwrap();
    assert_eq!(std::fs::read(&f).unwrap(), b"contents");
    assert!(streams(&backend, "f.txt").await.is_empty());

    // Into an empty stream that exists, which it replaces.
    create(&backend, "f.txt", "e", b"").await;
    assert!(matches!(
        backend
            .rename_stream(&p("f.txt"), file_id, None, Some(&name("E")), false)
            .await,
        Err(SmbError::Exists)
    ));
    backend
        .rename_stream(&p("f.txt"), file_id, None, Some(&name("E")), true)
        .await
        .unwrap();
    assert_eq!(streams(&backend, "f.txt").await, [("E".to_string(), 8)]);
}

#[tokio::test]
async fn removing_a_stream_leaves_the_others() {
    let (_td, backend) = backend();
    create(&backend, "f.txt", "Keep", b"1").await;
    create(&backend, "f.txt", "Gone", b"2").await;
    let file_id = id(&backend, "f.txt").await;
    backend
        .remove_stream(&p("f.txt"), file_id, &name("GONE"))
        .await
        .unwrap();
    assert!(matches!(
        backend
            .remove_stream(&p("f.txt"), file_id, &name("gone"))
            .await,
        Err(SmbError::NotFound)
    ));
    assert_eq!(streams(&backend, "f.txt").await, [("Keep".to_string(), 1)]);
}

#[tokio::test]
async fn overwriting_the_file_keeps_its_streams_for_the_server_to_remove() {
    let (_td, backend) = backend();
    create(&backend, "f.txt", "s", b"stream").await;
    for intent in [OpenIntent::Truncate, OpenIntent::OverwriteOrCreate] {
        let (h, action) = backend.open(&p("f.txt"), opts(intent, true)).await.unwrap();
        assert_eq!(action, OpenAction::Overwritten);
        assert_eq!(h.streams().await.unwrap().len(), 1);
        h.close().await.unwrap();
    }
}

#[tokio::test]
async fn directories_and_the_share_root_have_streams() {
    let (td, backend) = backend();
    std::fs::create_dir(td.path().join("dir")).unwrap();
    create(&backend, "dir", "ds", b"dir").await;
    create(&backend, "", "rs", b"root").await;
    assert_eq!(host_stream(&td, "dir", "ds").unwrap(), b"dir");
    let (h, _) = open(&backend, "dir", "ds", OpenIntent::Open).await.unwrap();
    let info = h.stat().await.unwrap();
    assert!(info.is_directory);
    assert_eq!(info.end_of_file, 3);
    // Through a stream, the directory takes the attribute.
    h.set_attributes(FILE_ATTRIBUTE_READONLY).await.unwrap();
    assert!(h.stat().await.unwrap().read_only);
    h.set_attributes(0).await.unwrap();
    assert!(!h.stat().await.unwrap().read_only);
    h.close().await.unwrap();
    // So does a file.
    create(&backend, "f.txt", "s", b"x").await;
    let (h, _) = open(&backend, "f.txt", "s", OpenIntent::Open)
        .await
        .unwrap();
    h.set_attributes(FILE_ATTRIBUTE_HIDDEN).await.unwrap();
    h.close().await.unwrap();
    let md = std::fs::metadata(td.path().join("f.txt")).unwrap();
    let attributes = std::os::windows::fs::MetadataExt::file_attributes(&md);
    assert_ne!(attributes & FILE_ATTRIBUTE_HIDDEN, 0);
    assert_eq!(streams(&backend, "dir").await, [("ds".to_string(), 3)]);
    let (root, _) = backend
        .open(
            &SmbPath::root(),
            OpenOptions {
                directory: true,
                ..opts(OpenIntent::Open, false)
            },
        )
        .await
        .unwrap();
    let listed: Vec<_> = root.streams().await.unwrap();
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].name.as_str(), "rs");
    root.close().await.unwrap();
    std::fs::create_dir(td.path().join("empty")).unwrap();
    assert!(streams(&backend, "empty").await.is_empty());
}

#[tokio::test]
async fn a_read_only_backend_reads_streams_and_changes_none() {
    let (td, backend) = backend();
    create(&backend, "f.txt", "s", b"data").await;
    let file_id = id(&backend, "f.txt").await;
    let backend = LocalFsBackend::new(td.path()).unwrap().read_only();
    assert!(backend.capabilities().named_streams);
    let (file, _) = backend
        .open(&p("f.txt"), opts(OpenIntent::Open, false))
        .await
        .unwrap();
    let (h, _) = backend
        .open_stream(file, &p("f.txt"), &name("s"), opts(OpenIntent::Open, false))
        .await
        .unwrap();
    assert_eq!(read_all(h.as_ref()).await, b"data");
    assert!(matches!(
        h.write(0, b"x").await,
        Err(SmbError::AccessDenied)
    ));
    assert!(matches!(h.truncate(0).await, Err(SmbError::AccessDenied)));
    h.close().await.unwrap();
    assert!(matches!(
        backend
            .remove_stream(&p("f.txt"), file_id, &name("s"))
            .await,
        Err(SmbError::AccessDenied)
    ));
    assert!(matches!(
        backend
            .rename_stream(
                &p("f.txt"),
                file_id,
                Some(&name("s")),
                Some(&name("t")),
                false
            )
            .await,
        Err(SmbError::AccessDenied)
    ));
}

#[tokio::test]
async fn removals_and_renames_leave_a_file_put_in_its_place_alone() {
    let (td, backend) = backend();
    create(&backend, "f.txt", "s", b"old").await;
    let old_id = id(&backend, "f.txt").await;
    std::fs::write(td.path().join("new.txt"), b"").unwrap();
    std::fs::write(td.path().join("new.txt:s"), b"new").unwrap();
    std::fs::rename(td.path().join("new.txt"), td.path().join("f.txt")).unwrap();
    assert!(matches!(
        backend.remove_stream(&p("f.txt"), old_id, &name("s")).await,
        Err(SmbError::NotFound)
    ));
    assert!(matches!(
        backend
            .rename_stream(
                &p("f.txt"),
                old_id,
                Some(&name("s")),
                Some(&name("t")),
                false
            )
            .await,
        Err(SmbError::NotFound)
    ));
    assert_eq!(streams(&backend, "f.txt").await, [("s".to_string(), 3)]);
}

#[test]
fn stream_listings_parse_whole_entries_only() {
    let entry = |name: &str, size: u64, last: bool| {
        let units: Vec<u8> = name.encode_utf16().flat_map(u16::to_le_bytes).collect();
        let len = 24 + units.len();
        let next = if last {
            0
        } else {
            len.next_multiple_of(8) as u32
        };
        let mut out = Vec::new();
        out.extend_from_slice(&next.to_le_bytes());
        out.extend_from_slice(&(units.len() as u32).to_le_bytes());
        out.extend_from_slice(&size.to_le_bytes());
        out.extend_from_slice(&size.next_multiple_of(8).to_le_bytes());
        out.extend_from_slice(&units);
        if !last {
            out.resize(next as usize, 0);
        }
        out
    };
    let mut buf = entry("::$DATA", 4, false);
    buf.extend(entry(":s:$DATA", 3, false));
    buf.extend(entry(":bad:$INDEX_ALLOCATION", 0, false));
    buf.extend(entry(":last:$DATA", 1, true));
    let parsed: Vec<_> = parse_listing(&buf)
        .into_iter()
        .map(|s| (s.name.as_str().to_string(), s.size, s.allocation_size))
        .collect();
    assert_eq!(
        parsed,
        [("s".to_string(), 3, 8), ("last".to_string(), 1, 8)]
    );
    // A list cut short keeps the entries that are whole, and an offset
    // past the end ends it.
    let cut = &buf[..buf.len() - 4];
    assert_eq!(parse_listing(cut).len(), 1);
    let mut far = buf.clone();
    far[..4].copy_from_slice(&u32::MAX.to_le_bytes());
    assert!(parse_listing(&far).is_empty());
}

#[test]
fn names_compare_as_ntfs_compares_them() {
    assert!(same_name(
        &name("Zone.Identifier"),
        &name("zone.IDENTIFIER")
    ));
    assert!(same_name(&name("\u{E9}t\u{E9}"), &name("\u{C9}T\u{C9}")));
    // Final and medial sigma share an uppercase form; sharp s has no
    // one-character uppercase form.
    assert!(same_name(&name("\u{3C2}"), &name("\u{3C3}")));
    assert!(!same_name(&name("\u{DF}"), &name("\u{1E9E}")));
    assert!(!same_name(&name("a"), &name("b")));
}

#[tokio::test]
async fn renames_on_refs_are_refused_before_anything_changes() {
    let (td, backend) = backend();
    create(&backend, "f.txt", "a", b"data").await;
    create(&backend, "f.txt", "b", b"").await;
    let root = Arc::new(Dir::open_ambient_dir(td.path(), ambient_authority()).unwrap());
    let place = Place {
        root,
        root_dev: None,
        read_only: false,
        volume: Volume { refs: true },
    };
    let renamed = place
        .rename_stream(
            PathBuf::from("f.txt"),
            0,
            Some(name("a")),
            Some(name("b")),
            true,
        )
        .await;
    assert!(matches!(renamed, Err(SmbError::InvalidParameter)));
    assert_eq!(
        streams(&backend, "f.txt").await,
        [("a".to_string(), 4), ("b".to_string(), 0)]
    );
}

#[tokio::test]
async fn a_stream_to_replace_that_is_open_elsewhere_fails_the_rename_first() {
    let (td, backend) = backend();
    if on_refs(&td) {
        eprintln!("skipping: ReFS cannot rename streams");
        return;
    }
    create(&backend, "f.txt", "a", b"data").await;
    create(&backend, "f.txt", "b", b"").await;
    let file_id = id(&backend, "f.txt").await;
    let held = std::fs::File::open(td.path().join("f.txt:b")).unwrap();
    assert!(matches!(
        backend
            .rename_stream(
                &p("f.txt"),
                file_id,
                Some(&name("a")),
                Some(&name("B")),
                true
            )
            .await,
        Err(SmbError::InvalidParameter)
    ));
    assert_eq!(
        streams(&backend, "f.txt").await,
        [("a".to_string(), 4), ("b".to_string(), 0)]
    );
    drop(held);
    backend
        .rename_stream(
            &p("f.txt"),
            file_id,
            Some(&name("a")),
            Some(&name("B")),
            true,
        )
        .await
        .unwrap();
    assert_eq!(streams(&backend, "f.txt").await, [("B".to_string(), 4)]);
}

#[tokio::test]
async fn streams_with_the_longest_names_are_all_listed() {
    let (_td, backend) = backend();
    let names: Vec<String> = (0..40)
        .map(|i| format!("{i:02}{}", "\u{E9}".repeat(253)))
        .collect();
    for n in &names {
        create(&backend, "f.txt", n, b"x").await;
    }
    let listed = streams(&backend, "f.txt").await;
    assert_eq!(listed.len(), names.len());
    assert!(
        listed
            .iter()
            .all(|(n, size)| n.encode_utf16().count() == 255 && *size == 1)
    );
}

#[tokio::test]
async fn a_stream_to_replace_goes_while_other_opens_do_not_use_its_data() {
    use std::os::windows::fs::OpenOptionsExt as _;
    let (td, backend) = backend();
    if on_refs(&td) {
        eprintln!("skipping: ReFS cannot rename streams");
        return;
    }
    create(&backend, "f.txt", "a", b"data").await;
    create(&backend, "f.txt", "b", b"").await;
    let file_id = id(&backend, "f.txt").await;
    // An open of the file that may delete it, and one that reads only the
    // attributes of the stream to replace.
    let file = std::fs::OpenOptions::new()
        .access_mode(DELETE | FILE_GENERIC_READ)
        .open(td.path().join("f.txt"))
        .unwrap();
    let attributes = std::fs::OpenOptions::new()
        .access_mode(FILE_READ_ATTRIBUTES)
        .open(td.path().join("f.txt:b"))
        .unwrap();
    backend
        .rename_stream(
            &p("f.txt"),
            file_id,
            Some(&name("a")),
            Some(&name("B")),
            true,
        )
        .await
        .unwrap();
    // The replaced stream is deleted under a name of its own, and goes
    // once the last handle on it closes.
    let listed = streams(&backend, "f.txt").await;
    assert_eq!(listed[0], ("B".to_string(), 4));
    assert_eq!(listed.len(), 2);
    assert!(
        listed[1..]
            .iter()
            .all(|(n, _)| n.starts_with("smb-server-replaced-"))
    );
    drop((file, attributes));
    assert_eq!(streams(&backend, "f.txt").await, [("B".to_string(), 4)]);
}

/// Bytes that differ from one offset to the next.
fn pattern(len: usize) -> Vec<u8> {
    (0..len).map(|i| (i * 7 % 251) as u8).collect()
}

/// What a peek from the share root of `backend` finds of each of
/// `streams` of each of `entries`.
async fn peek(
    backend: &LocalFsBackend,
    entries: &[&str],
    streams: &[(&str, u32)],
) -> Vec<Vec<Option<(u64, Vec<u8>)>>> {
    let dir_opts = crate::backend::OpenOptions {
        directory: true,
        ..opts(OpenIntent::Open, false)
    };
    let (dir, _) = backend.open(&SmbPath::root(), dir_opts).await.unwrap();
    let streams: Vec<_> = streams.iter().map(|&(s, max)| (name(s), max)).collect();
    let asked: Vec<_> = entries.iter().map(|&e| (e, &streams[..])).collect();
    let peeked = dir.peek_streams(&asked).await.unwrap();
    dir.close().await.unwrap();
    peeked
        .into_iter()
        .map(|found| {
            found
                .into_iter()
                .map(|f| f.map(|(size, data)| (size, data.to_vec())))
                .collect()
        })
        .collect()
}

#[tokio::test]
async fn peeks_give_the_size_and_start_of_ntfs_streams() {
    let (td, backend) = backend();
    create(&backend, "f.txt", "AFP_AfpInfo", &pattern(60)).await;
    create(&backend, "f.txt", "AFP_Resource", &pattern(70_000)).await;
    std::fs::create_dir(td.path().join("d")).unwrap();
    create(&backend, "d", "s", b"dir data").await;
    std::fs::write(td.path().join("plain.txt"), b"x").unwrap();
    let streams = [
        ("afp_afpinfo", 60),
        ("AFP_Resource", 0),
        ("AFP_Resource", 100),
        ("S", 100),
    ];
    let peeked = peek(&backend, &["f.txt", "d", "plain.txt"], &streams).await;
    assert_eq!(
        peeked[0],
        [
            Some((60, pattern(60))),
            Some((70_000, Vec::new())),
            Some((70_000, pattern(100))),
            None
        ]
    );
    assert_eq!(
        peeked[1],
        [None, None, None, Some((8, b"dir data".to_vec()))]
    );
    assert_eq!(peeked[2], vec![None; 4]);
}

/// Symlinks are checked where the host lets the test make them.
#[tokio::test]
async fn a_peek_reads_files_and_directories_and_nothing_else() {
    let (td, backend) = backend();
    let outside = tempfile::tempdir_in(td.path().parent().unwrap()).unwrap();
    let outside_backend = LocalFsBackend::new(outside.path()).unwrap();
    create(&outside_backend, "f.txt", "AFP_AfpInfo", &pattern(60)).await;
    create(&backend, "f.txt", "AFP_AfpInfo", &pattern(60)).await;
    std::fs::create_dir(td.path().join("d")).unwrap();
    create(&backend, "d", "AFP_AfpInfo", &pattern(60)).await;
    let links = std::os::windows::fs::symlink_file("f.txt", td.path().join("in.txt")).is_ok()
        && std::os::windows::fs::symlink_file(
            outside.path().join("f.txt"),
            td.path().join("out.txt"),
        )
        .is_ok();
    let mut entries = vec!["f.txt", "d", "gone.txt"];
    if links {
        entries.extend(["in.txt", "out.txt"]);
    } else {
        eprintln!("no symlinks on {}", td.path().display());
    }
    let streams = [("AFP_AfpInfo", 60), ("AFP_Resource", 0)];
    let peeked = peek(&backend, &entries, &streams).await;
    let info = Some((60, pattern(60)));
    let mut expected = vec![
        vec![info.clone(), None],
        vec![info.clone(), None],
        vec![None, None],
    ];
    if links {
        expected.extend([vec![info, None], vec![None, None]]);
    }
    assert_eq!(peeked, expected);
}

#[tokio::test]
async fn a_junction_out_of_the_share_has_no_streams() {
    let (td, backend) = backend();
    let outside = tempfile::tempdir_in(td.path().parent().unwrap()).unwrap();
    std::fs::create_dir(outside.path().join("d")).unwrap();
    let outside_backend = LocalFsBackend::new(outside.path()).unwrap();
    create(&outside_backend, "d", "AFP_AfpInfo", &pattern(60)).await;
    let made = std::process::Command::new("cmd")
        .arg("/C")
        .arg("mklink")
        .arg("/J")
        .arg(td.path().join("j"))
        .arg(outside.path().join("d"))
        .output()
        .unwrap();
    assert!(made.status.success(), "{made:?}");
    assert!(td.path().join("j").is_dir());
    // The junction has a stream of its own, which only a peek that kept
    // the junction itself would find.
    let dir = Dir::open_ambient_dir(td.path(), ambient_authority()).unwrap();
    {
        use std::os::windows::io::AsHandle as _;
        let (junction, _) = nt_open(
            dir.as_handle().as_raw_handle() as HANDLE,
            "j".encode_utf16().collect(),
            FILE_READ_ATTRIBUTES,
            SHARE_ALL,
            FILE_OPEN,
            FILE_SYNCHRONOUS_IO_NONALERT | FILE_OPEN_REPARSE_POINT,
        )
        .unwrap();
        assert!(is_link(&junction).unwrap());
        let (own, _) = open_relative(
            &junction,
            Some(&name("AFP_AfpInfo")),
            FILE_GENERIC_WRITE,
            SHARE_ALL,
            FILE_CREATE,
        )
        .unwrap();
        own.seek_write(&[7; 60], 0).unwrap();
    }
    let opened = open_entry(&dir, "j");
    assert!(opened.is_err(), "{opened:?}");
    let peeked = peek(&backend, &["j"], &[("AFP_AfpInfo", 60)]).await;
    assert_eq!(peeked, [vec![None]]);
}

/// A stream opened through a held file that was renamed on the host, with
/// another file made under its old name, belongs to the held file or fails
/// as not found, and the new file gets no stream.
#[test]
fn a_stream_opened_through_a_renamed_file_leaves_the_new_one_alone() {
    use crate::fs::windows_dir::tests::{Root, on_each_root, reach};
    use crate::tests::util::scratch_dir;

    on_each_root(|root| {
        let td = scratch_dir();
        std::fs::write(td.path().join("f.txt"), b"old").unwrap();
        let dir = Dir::open_ambient_dir(reach(td.path(), root), ambient_authority()).unwrap();
        let mut opts = DirOpenOptions::new();
        opts.read(true)
            .access_mode(FILE_READ_ATTRIBUTES | SYNCHRONIZE)
            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
        let base = dir.open_with("f.txt", &opts).unwrap().into_std();
        std::fs::rename(td.path().join("f.txt"), td.path().join("g.txt")).unwrap();
        std::fs::write(td.path().join("f.txt"), b"new").unwrap();

        for (stream, disposition) in [("made", FILE_CREATE), ("made-if", FILE_OPEN_IF)] {
            let opened = open_relative(
                &base,
                Some(&name(stream)),
                FILE_GENERIC_WRITE,
                SHARE_ALL,
                disposition,
            )
            .map(drop);
            let on = |file: &str| td.path().join(format!("{file}:{stream}")).exists();
            match (root, opened) {
                (_, Ok(())) => assert!(on("g.txt"), "{stream}"),
                (Root::Unc, Err(e)) if e.kind() == io::ErrorKind::NotFound => {
                    assert!(!on("g.txt"), "{stream}");
                }
                (_, Err(e)) => panic!("{stream}: {e}"),
            }
            assert!(!on("f.txt"), "{stream}");
        }
    });
}

/// A named stream written through a share root on a UNC path reads back
/// through it, and is the NTFS stream of the file on the host.
#[tokio::test]
async fn a_stream_round_trips_on_a_unc_root() {
    let td = crate::tests::util::scratch_dir();
    let unc = crate::tests::util::on_admin_share(td.path());
    let backend = LocalFsBackend::new(unc).unwrap();
    assert!(backend.capabilities().named_streams);
    create(&backend, "f.txt", "Zone.Identifier", b"[ZoneTransfer]").await;

    let (h, _) = open(&backend, "f.txt", "zone.identifier", OpenIntent::Open)
        .await
        .unwrap();
    assert_eq!(read_all(h.as_ref()).await, b"[ZoneTransfer]");
    h.close().await.unwrap();
    assert_eq!(
        streams(&backend, "f.txt").await,
        [("Zone.Identifier".to_string(), 14)]
    );
    assert_eq!(
        host_stream(&td, "f.txt", "Zone.Identifier").unwrap(),
        b"[ZoneTransfer]"
    );
    assert_eq!(std::fs::read(td.path().join("f.txt")).unwrap(), b"");
}

/// Named streams made or renamed while another program opens their names
/// in the other case, as a virus scanner does, keep the case they were
/// given.
#[tokio::test]
async fn streams_named_while_another_program_opens_them_in_the_other_case_keep_their_case() {
    use crate::fs::windows_dir::tests::{Opener, on_each_root_async, reach};
    use crate::tests::util::on_admin_share;

    on_each_root_async(|root| async move {
        let td = crate::tests::util::scratch_dir();
        let backend = LocalFsBackend::new(reach(td.path(), root)).unwrap();
        for i in 0..31 {
            let file = format!("b{i}");
            std::fs::write(td.path().join(&file), b"x").unwrap();
            let opener = Opener::start(vec![on_admin_share(td.path()).join(format!("{file}:S"))]);
            if i < 30 {
                let (h, action) = open(&backend, &file, "s", OpenIntent::Create)
                    .await
                    .unwrap();
                assert_eq!(action, OpenAction::Created, "{file}");
                h.close().await.unwrap();
            } else {
                create(&backend, &file, "x", b"data").await;
                let id = id(&backend, &file).await;
                backend
                    .rename_stream(&p(&file), id, Some(&name("x")), Some(&name("s")), false)
                    .await
                    .unwrap();
            }
            opener.stop();
            let host = File::open(td.path().join(&file)).unwrap();
            let names: Vec<String> = list(&host)
                .unwrap()
                .into_iter()
                .map(|s| s.name.as_str().to_string())
                .collect();
            assert_eq!(names, ["s"], "{file}");
        }
    })
    .await;
}