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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
//! Opens, unlinks and renames for a share that stores names as clients
//! spell them. The inner backend resolves the names. This module reserves
//! the marker in the root and keeps the nodes of the open files in step with
//! what the inner backend does.

use std::sync::Arc;

use super::backend::EncryptedBackend;
use super::format::MARKER_NAME;
use super::handle::{EncryptedHandle, OpenResult};
use super::inner::close_after_reading;
use super::locks::acquire_some;
use super::node::{Found, HeaderState, NameMatch, Node, Origin, path_key};
use crate::backend::{FileInfo, Handle, OpenAction, OpenIntent, OpenOptions, ShareBackend};
use crate::error::{SmbError, SmbResult};
use crate::path::SmbPath;

/// True if `name` is the name of the marker, compared the way the inner
/// backend compares names.
pub(super) fn is_marker_name(name: &str, names: NameMatch) -> bool {
    match names {
        NameMatch::Exact => name == MARKER_NAME,
        NameMatch::Folded => name.to_lowercase() == MARKER_NAME,
    }
}

/// True if `path` is the marker.
fn is_marker(path: &SmbPath, names: NameMatch) -> bool {
    matches!(path.components(), [name] if is_marker_name(name, names))
}

/// The intent creates an entry that may not exist yet.
pub(super) fn creates(intent: OpenIntent) -> bool {
    matches!(
        intent,
        OpenIntent::Create | OpenIntent::OpenOrCreate | OpenIntent::OverwriteOrCreate
    )
}

/// The intent empties an existing file.
fn truncates(intent: OpenIntent) -> bool {
    matches!(intent, OpenIntent::Truncate | OpenIntent::OverwriteOrCreate)
}

/// The options of the open in the inner backend. Files are opened for
/// reading whatever the client asked, since a write that covers part of a
/// block reads the block first, and an open that empties a file also asks to
/// write.
fn inner_options(opts: OpenOptions) -> OpenOptions {
    OpenOptions {
        read: true,
        write: opts.write || truncates(opts.intent),
        ..opts
    }
}

impl<B: ShareBackend> EncryptedBackend<B> {
    /// Opens or creates `path`. The call holds the tree lock shared from here
    /// to the end, and nothing below it takes the lock again.
    pub(super) async fn open_handle(&self, path: &SmbPath, opts: OpenOptions) -> OpenResult<B> {
        let encrypt_names = self.shared.settings.encrypt_names;
        if encrypt_names && let (Some(parent), Some(name)) = (path.parent(), path.file_name()) {
            let _tree = self.shared.locks.tree.read().await;
            return self.open_entry(&parent, name, opts).await;
        }
        let names = self.shared.name_match();
        if !encrypt_names && is_marker(path, names) {
            return Err(match opts.intent {
                OpenIntent::Open | OpenIntent::Truncate => SmbError::NotFound,
                _ => SmbError::AccessDenied,
            });
        }
        let _tree = self.shared.locks.tree.read().await;
        let dir = path
            .parent()
            .map(|parent| self.shared.locks.directory(path_key(&parent, names)));
        let _held = acquire_some(dir.as_deref(), |dir| dir.acquire(creates(opts.intent))).await;
        self.open_at(path, opts, names).await
    }

    /// Opens the entry at the stored path `path`, whose directory lock the
    /// caller holds.
    pub(super) async fn open_at(
        &self,
        path: &SmbPath,
        opts: OpenOptions,
        names: NameMatch,
    ) -> OpenResult<B> {
        if !path.is_root() && truncates(opts.intent) {
            return self.overwrite(path, opts, names).await;
        }
        self.open_new(path, opts, names).await
    }

    /// Opens the entry at the stored path `path` in the inner backend as
    /// `opts` say, which may create it, and wraps the handle.
    pub(super) async fn open_new(
        &self,
        path: &SmbPath,
        opts: OpenOptions,
        names: NameMatch,
    ) -> OpenResult<B> {
        let (inner, action) = self.shared.inner.open(path, inner_options(opts)).await?;
        let handle = self.wrap(inner, path, action, names).await?;
        Ok((handle, action))
    }

    /// Opens an entry that is not the root with an intent that empties an
    /// existing file. The node of the file takes its lock before the inner
    /// backend empties the file, so no read or write of another handle is
    /// under way.
    async fn overwrite(
        &self,
        path: &SmbPath,
        opts: OpenOptions,
        names: NameMatch,
    ) -> OpenResult<B> {
        let inner = &self.shared.inner;
        let existing = OpenOptions {
            directory: opts.directory,
            non_directory: opts.non_directory,
            ..OpenOptions::default()
        };
        let check = match inner.open(path, existing).await {
            Ok((check, _)) => check,
            Err(SmbError::NotFound) if opts.intent == OpenIntent::OverwriteOrCreate => {
                return self.open_new(path, opts, names).await;
            }
            Err(error) => return Err(error),
        };
        let info = match check.stat().await {
            Ok(info) => info,
            Err(error) => {
                close_after_reading(check).await;
                return Err(error);
            }
        };
        if info.is_directory {
            close_after_reading(check).await;
            let (handle, action) = inner.open(path, inner_options(opts)).await?;
            return Ok((self.wrap(handle, path, action, names).await?, action));
        }
        let node = self.node_of(path, &info, Origin::Opened, names);
        let mut file = acquire_some(node.file(), |file| file.write()).await;
        let opened = inner.open(path, inner_options(opts)).await;
        if opened.is_ok()
            && let Some(file) = &mut file
        {
            file.header = HeaderState::Absent;
        }
        close_after_reading(check).await;
        let (handle, action) = opened?;
        drop(file);
        Ok((
            EncryptedHandle::new(handle, node, Arc::clone(&self.shared)),
            action,
        ))
    }

    /// Wraps `inner`, opened at `path` with `action`, in a handle that holds
    /// the node of its file.
    async fn wrap(
        &self,
        inner: Box<dyn Handle>,
        path: &SmbPath,
        action: OpenAction,
        names: NameMatch,
    ) -> SmbResult<EncryptedHandle<B>> {
        let info = match inner.stat().await {
            Ok(info) => info,
            Err(error) => {
                let _ = inner.close().await;
                return Err(error);
            }
        };
        let origin = if action == OpenAction::Created {
            Origin::Created
        } else {
            Origin::Opened
        };
        let node = self.node_of(path, &info, origin, names);
        if action == OpenAction::Overwritten {
            node.forget_header().await;
        }
        Ok(EncryptedHandle::new(inner, node, Arc::clone(&self.shared)))
    }

    fn node_of(
        &self,
        path: &SmbPath,
        info: &FileInfo,
        origin: Origin,
        names: NameMatch,
    ) -> Arc<Node> {
        self.shared.nodes.attach(&Found {
            path,
            file_index: info.file_index,
            directory: info.is_directory,
            origin,
            names,
        })
    }

    /// Deletes the file or empty directory at `path`. The call holds the tree
    /// lock shared from here to the end, and nothing below it takes the lock
    /// again.
    pub(super) async fn unlink_path(&self, path: &SmbPath) -> SmbResult<()> {
        let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else {
            return Err(SmbError::AccessDenied);
        };
        if self.shared.settings.encrypt_names {
            let _tree = self.shared.locks.tree.read().await;
            return self.unlink_entry(&parent, name).await;
        }
        let names = self.shared.name_match();
        if is_marker(path, names) {
            return Err(SmbError::NotFound);
        }
        let _tree = self.shared.locks.tree.read().await;
        let dir = self.shared.locks.directory(path_key(&parent, names));
        let _held = dir.acquire(true).await;
        self.shared.inner.unlink(path).await?;
        self.shared.nodes.unlinked(path, names);
        Ok(())
    }

    /// Renames `from` to `to`. The call holds the tree lock exclusively from
    /// here to the end, and nothing below it takes the lock again.
    pub(super) async fn rename_path(
        &self,
        from: &SmbPath,
        to: &SmbPath,
        replace_if_exists: bool,
    ) -> SmbResult<()> {
        let (Some(from_parent), Some(from_name), Some(to_parent), Some(to_name)) =
            (from.parent(), from.file_name(), to.parent(), to.file_name())
        else {
            return Err(SmbError::AccessDenied);
        };
        if self.shared.settings.encrypt_names {
            let _tree = self.shared.locks.tree.write().await;
            return self
                .rename_entry(
                    &from_parent,
                    from_name,
                    &to_parent,
                    to_name,
                    replace_if_exists,
                )
                .await;
        }
        let names = self.shared.name_match();
        if is_marker(from, names) {
            return Err(SmbError::NotFound);
        }
        if is_marker(to, names) {
            return Err(SmbError::AccessDenied);
        }
        let _tree = self.shared.locks.tree.write().await;
        self.shared
            .inner
            .rename(from, to, replace_if_exists)
            .await?;
        self.shared.nodes.renamed(from, to, names);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::super::node::HeaderKind;
    use super::super::testing::{
        clear_over, clear_settings, exact_names, key_schedule, marker_bytes, open, open_dir,
        open_file, settle, shares_node, spawn_open,
    };
    use super::*;
    use crate::tests::file_ids::FileIds;
    use crate::tests::folding::Folding;
    use crate::tests::gated::{Gated, Op};
    use crate::tests::memfs::MemFsBackend;
    use crate::tests::recorder::Recorder;
    use crate::tests::util::{dir_opts, opts, path};

    /// Waits until a request for the exclusive lock of the file of `node`
    /// is queued behind the holders of the lock.
    async fn wait_for_a_writer(node: &Node) {
        let file = node.file().expect("a file node");
        for _ in 0..1000 {
            if file.try_read().is_err() {
                return;
            }
            tokio::task::yield_now().await;
        }
        panic!("no request waits for the lock of the file");
    }

    async fn two_handles_of_one_file_share_a_node<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_file("f", b"").with_file("g", b"");
        let (a, _) = open(layer, "f", OpenIntent::Open).await;
        let (b, _) = open(layer, "f", OpenIntent::Open).await;
        let (c, _) = open(layer, "g", OpenIntent::Open).await;
        assert!(shares_node(&a, &b));
        assert!(!shares_node(&a, &c));
        assert_eq!(layer.node_count(), 2);

        Box::new(a).close().await.unwrap();
        assert_eq!(layer.node_count(), 2, "the second handle still holds it");
        Box::new(b).close().await.unwrap();
        assert_eq!(layer.node_count(), 1);
        Box::new(c).close().await.unwrap();
        assert_eq!(layer.node_count(), 0);
    }

    async fn a_truncating_open_takes_the_exclusive_lock_and_resets_the_header<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_file("f", b"abc");
        let (reader, _) = open(layer, "f", OpenIntent::Open).await;
        let node = Arc::clone(reader.node());
        assert_eq!(node.header().await, Some(HeaderKind::Unknown));

        let in_flight = node.file().expect("a file node").read().await;
        let truncating = spawn_open(layer, "f", OpenIntent::Truncate);
        wait_for_a_writer(&node).await;
        assert!(!truncating.is_finished());
        assert_eq!(files.contents("f"), Some(b"abc".to_vec()));

        drop(in_flight);
        let (truncated, action) = truncating.await.unwrap().unwrap();
        assert_eq!(action, OpenAction::Overwritten);
        assert_eq!(files.contents("f"), Some(Vec::new()));
        assert!(shares_node(&reader, &truncated));
        assert_eq!(node.header().await, Some(HeaderKind::Absent));
        assert!(!node.is_detached());
    }

    async fn an_unlink_and_a_create_at_one_path_give_a_new_node<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_file("f", b"abc");
        let (old, _) = open(layer, "f", OpenIntent::Open).await;
        layer.unlink(&path("f")).await.unwrap();
        assert!(old.node().is_detached());
        assert_eq!(layer.node_count(), 0);

        let (new, action) = open(layer, "f", OpenIntent::Create).await;
        assert_eq!(action, OpenAction::Created);
        assert!(!shares_node(&old, &new));
        assert!(!new.node().is_detached());
        assert_eq!(old.node().header().await, Some(HeaderKind::Unknown));
        assert_eq!(new.node().header().await, Some(HeaderKind::Absent));
        assert_eq!(layer.node_count(), 1);
    }

    async fn a_rename_keeps_the_node_of_an_open_file<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files
            .clone()
            .with_dir("d")
            .with_dir("d\\sub")
            .with_file("d\\sub\\f", b"")
            .with_file("a", b"")
            .with_file("b", b"");
        let (deep, _) = open(layer, "d\\sub\\f", OpenIntent::Open).await;
        let (a, _) = open(layer, "a", OpenIntent::Open).await;
        let (b, _) = open(layer, "b", OpenIntent::Open).await;

        layer.rename(&path("d"), &path("e"), false).await.unwrap();
        assert_eq!(deep.node().path(), path("e\\sub\\f"));
        let (again, _) = open(layer, "e\\sub\\f", OpenIntent::Open).await;
        assert!(shares_node(&deep, &again));
        assert!(matches!(
            layer
                .open_handle(&path("d\\sub\\f"), opts(OpenIntent::Open))
                .await,
            Err(SmbError::PathNotFound)
        ));

        layer.rename(&path("a"), &path("b"), true).await.unwrap();
        assert!(b.node().is_detached());
        assert!(!a.node().is_detached());
        assert_eq!(a.node().path(), path("b"));
        let (at_target, _) = open(layer, "b", OpenIntent::Open).await;
        assert!(shares_node(&a, &at_target));
        assert!(matches!(
            layer.open_handle(&path("a"), opts(OpenIntent::Open)).await,
            Err(SmbError::NotFound)
        ));
        assert_eq!(layer.node_count(), 2);
    }

    async fn a_handle_dropped_without_close_leaves_no_table_entry<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_file("f", b"").with_dir("d");
        let (file, _) = open(layer, "f", OpenIntent::Open).await;
        let dir = open_dir(layer, "d").await;
        let root = open_dir(layer, "").await;
        assert_eq!(layer.node_count(), 3);
        drop((file, dir, root));
        assert_eq!(layer.node_count(), 0);
    }

    async fn a_create_of_a_name_in_use_fails_and_leaves_the_node<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_file("f", b"");
        let (held, _) = open(layer, "f", OpenIntent::Open).await;
        assert!(matches!(
            layer
                .open_handle(&path("f"), opts(OpenIntent::Create))
                .await,
            Err(SmbError::Exists)
        ));
        let (again, _) = open(layer, "f", OpenIntent::Open).await;
        assert!(shares_node(&held, &again));
        assert!(!held.node().is_detached());
    }

    async fn a_refused_unlink_or_rename_leaves_the_nodes<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_file("a", b"").with_file("b", b"");
        let (a, _) = open(layer, "a", OpenIntent::Open).await;
        let (b, _) = open(layer, "b", OpenIntent::Open).await;
        assert!(matches!(
            layer.rename(&path("a"), &path("b"), false).await,
            Err(SmbError::Exists)
        ));
        assert!(matches!(
            layer.rename(&path("zz"), &path("y"), false).await,
            Err(SmbError::NotFound)
        ));
        assert!(matches!(
            layer.unlink(&path("zz")).await,
            Err(SmbError::NotFound)
        ));
        assert_eq!(a.node().path(), path("a"));
        assert_eq!(b.node().path(), path("b"));
        assert!(!a.node().is_detached() && !b.node().is_detached());
        assert_eq!(layer.node_count(), 2);
    }

    async fn open_or_create_sets_the_header_by_what_it_did<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_file("old", b"abc");
        let (made, action) = open(layer, "new", OpenIntent::OpenOrCreate).await;
        assert_eq!(action, OpenAction::Created);
        assert_eq!(made.node().header().await, Some(HeaderKind::Absent));
        let (found, action) = open(layer, "old", OpenIntent::OpenOrCreate).await;
        assert_eq!(action, OpenAction::Opened);
        assert_eq!(found.node().header().await, Some(HeaderKind::Unknown));
        let (again, action) = open(layer, "new", OpenIntent::OpenOrCreate).await;
        assert_eq!(action, OpenAction::Opened);
        assert!(shares_node(&made, &again));
    }

    async fn an_overwriting_open_of_a_file_empties_it_and_resets_the_header<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_file("f", b"abc").with_file("g", b"abc");
        for (name, intent) in [
            ("f", OpenIntent::OverwriteOrCreate),
            ("g", OpenIntent::Truncate),
        ] {
            let (handle, action) = open(layer, name, intent).await;
            assert_eq!(action, OpenAction::Overwritten, "{intent:?}");
            assert_eq!(files.contents(name), Some(Vec::new()));
            assert_eq!(handle.node().header().await, Some(HeaderKind::Absent));
        }
        assert_eq!(
            files.open_handles(),
            2,
            "the open that stats the file first is closed"
        );
    }

    async fn an_overwriting_open_of_a_missing_file_creates_it_or_fails<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        let (made, action) = open(layer, "n", OpenIntent::OverwriteOrCreate).await;
        assert_eq!(action, OpenAction::Created);
        assert_eq!(files.contents("n"), Some(Vec::new()));
        assert_eq!(made.node().header().await, Some(HeaderKind::Absent));

        assert!(matches!(
            layer
                .open_handle(&path("m"), opts(OpenIntent::Truncate))
                .await,
            Err(SmbError::NotFound)
        ));
        for intent in [OpenIntent::Truncate, OpenIntent::OverwriteOrCreate] {
            assert!(
                matches!(
                    layer.open_handle(&path("x\\m"), opts(intent)).await,
                    Err(SmbError::PathNotFound)
                ),
                "{intent:?}"
            );
        }
        assert_eq!(files.contents("m"), None);
        assert_eq!(files.open_handles(), 1);
        assert_eq!(layer.node_count(), 1);
    }

    async fn an_overwriting_open_of_a_directory_is_the_inner_backends_to_answer<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_dir("d");
        for intent in [OpenIntent::Truncate, OpenIntent::OverwriteOrCreate] {
            assert!(
                matches!(
                    layer.open_handle(&path("d"), opts(intent)).await,
                    Err(SmbError::IsDirectory)
                ),
                "{intent:?}"
            );
        }
        assert_eq!(
            files.open_handles(),
            0,
            "the open that stats the file first is closed"
        );
        assert_eq!(layer.node_count(), 0);
    }

    async fn a_failed_overwriting_open_keeps_the_header_state<B: ShareBackend>(
        files: &MemFsBackend,
        layer: &EncryptedBackend<B>,
    ) {
        files.clone().with_file("f", b"abc");
        let (opened, _) = open(layer, "f", OpenIntent::Open).await;
        let (made, _) = open(layer, "n", OpenIntent::Create).await;
        files.clone().failing_overwrites();

        for name in ["f", "n"] {
            for intent in [OpenIntent::Truncate, OpenIntent::OverwriteOrCreate] {
                assert!(
                    matches!(
                        layer.open_handle(&path(name), opts(intent)).await,
                        Err(SmbError::AccessDenied)
                    ),
                    "{name} {intent:?}"
                );
            }
        }
        assert_eq!(opened.node().header().await, Some(HeaderKind::Unknown));
        assert_eq!(made.node().header().await, Some(HeaderKind::Absent));
        assert_eq!(files.contents("f"), Some(b"abc".to_vec()));
        assert_eq!(
            files.open_handles(),
            2,
            "the open that stats the file first is closed"
        );
        assert!(opened.node().file().unwrap().try_write().is_ok());
    }

    macro_rules! over_both_inner_backends {
        ($($scenario:ident),+ $(,)?) => {
            mod over_memfs {
                use super::*;
                $(
                    #[tokio::test]
                    async fn $scenario() {
                        let files = MemFsBackend::new();
                        let layer = clear_over(files.clone()).await;
                        super::$scenario(&files, &layer).await;
                    }
                )+
            }

            mod over_file_ids {
                use super::*;
                $(
                    #[tokio::test]
                    async fn $scenario() {
                        let files = MemFsBackend::new();
                        let layer = clear_over(FileIds::new(files.clone())).await;
                        super::$scenario(&files, &layer).await;
                    }
                )+
            }
        };
    }

    over_both_inner_backends!(
        two_handles_of_one_file_share_a_node,
        a_truncating_open_takes_the_exclusive_lock_and_resets_the_header,
        an_unlink_and_a_create_at_one_path_give_a_new_node,
        a_rename_keeps_the_node_of_an_open_file,
        a_handle_dropped_without_close_leaves_no_table_entry,
        a_create_of_a_name_in_use_fails_and_leaves_the_node,
        a_refused_unlink_or_rename_leaves_the_nodes,
        open_or_create_sets_the_header_by_what_it_did,
        an_overwriting_open_of_a_file_empties_it_and_resets_the_header,
        an_overwriting_open_of_a_missing_file_creates_it_or_fails,
        an_overwriting_open_of_a_directory_is_the_inner_backends_to_answer,
        a_failed_overwriting_open_keeps_the_header_state,
    );

    #[tokio::test]
    async fn a_create_over_a_file_deleted_outside_the_backend_takes_the_node_over() {
        let files = MemFsBackend::new();
        let layer = clear_over(files.clone()).await;
        files.clone().with_file("f", b"abc");
        let (old, _) = open(&layer, "f", OpenIntent::Open).await;
        files.remove("f");

        let (new, action) = open(&layer, "f", OpenIntent::Create).await;
        assert_eq!(action, OpenAction::Created);
        assert!(!shares_node(&old, &new));
        assert!(old.node().is_detached());
        assert_eq!(new.node().header().await, Some(HeaderKind::Absent));
        assert_eq!(layer.node_count(), 1);
        drop(old);
        assert_eq!(layer.node_count(), 1);
    }

    #[tokio::test]
    async fn an_overwriting_open_that_finds_the_file_created_meanwhile_resets_the_header() {
        let files = MemFsBackend::new();
        let gated = Gated::new(files.clone());
        let layer = clear_over(gated.clone()).await;
        let gate = gated.arm_after_at(Op::Open, "f");
        let opening = spawn_open(&layer, "f", OpenIntent::OverwriteOrCreate);
        gate.reached().await;
        files.clone().with_file("f", b"abc");
        gate.release();

        let (handle, action) = opening.await.unwrap().unwrap();
        assert_eq!(action, OpenAction::Overwritten);
        assert_eq!(files.contents("f"), Some(Vec::new()));
        assert_eq!(handle.node().header().await, Some(HeaderKind::Absent));
    }

    #[tokio::test]
    async fn the_root_opens_and_forwards_what_the_inner_backend_answers() {
        let files = MemFsBackend::new();
        let layer = clear_over(files.clone()).await;
        let root = SmbPath::root();
        let (first, action) = layer
            .open_handle(&root, dir_opts(OpenIntent::Open))
            .await
            .unwrap();
        assert_eq!(action, OpenAction::Opened);
        let second = open_dir(&layer, "").await;
        assert!(shares_node(&first, &second));
        assert!(first.node().is_directory());
        assert_eq!(layer.node_count(), 1);
        assert!(matches!(
            layer.open_handle(&root, opts(OpenIntent::Truncate)).await,
            Err(SmbError::IsDirectory)
        ));
        assert!(matches!(
            layer.open_handle(&root, opts(OpenIntent::Create)).await,
            Err(SmbError::Exists)
        ));
    }

    #[tokio::test]
    async fn the_marker_is_reserved_in_the_root() {
        let files = MemFsBackend::new();
        let layer = clear_over(files.clone()).await;
        files.clone().with_dir("d");
        let marker = marker_bytes(&files);
        let at_marker = path(MARKER_NAME);

        for intent in [OpenIntent::Open, OpenIntent::Truncate] {
            assert!(
                matches!(
                    layer.open_handle(&at_marker, opts(intent)).await,
                    Err(SmbError::NotFound)
                ),
                "{intent:?}"
            );
        }
        for intent in [
            OpenIntent::Create,
            OpenIntent::OpenOrCreate,
            OpenIntent::OverwriteOrCreate,
        ] {
            assert!(
                matches!(
                    layer.open_handle(&at_marker, opts(intent)).await,
                    Err(SmbError::AccessDenied)
                ),
                "{intent:?}"
            );
        }
        assert!(matches!(
            layer
                .open_handle(&at_marker, dir_opts(OpenIntent::Open))
                .await,
            Err(SmbError::NotFound)
        ));
        assert!(matches!(
            layer.unlink(&at_marker).await,
            Err(SmbError::NotFound)
        ));
        assert!(matches!(
            layer.rename(&at_marker, &path("x"), true).await,
            Err(SmbError::NotFound)
        ));
        assert!(matches!(
            layer.rename(&path("d"), &at_marker, true).await,
            Err(SmbError::AccessDenied)
        ));
        assert!(matches!(
            layer.rename(&at_marker, &at_marker, true).await,
            Err(SmbError::NotFound)
        ));
        assert_eq!(marker_bytes(&files), marker);
        assert_eq!(layer.node_count(), 0);

        let (below, action) = open(&layer, "d\\.smb-encryption", OpenIntent::Create).await;
        assert_eq!(
            action,
            OpenAction::Created,
            "only the root holds the marker"
        );
        drop(below);
    }

    #[tokio::test]
    async fn the_marker_follows_the_case_rule_of_the_inner_backend() {
        let files = MemFsBackend::new();
        let folded = clear_over(files.clone()).await;
        let spelled = path(".SMB-Encryption");
        assert!(matches!(
            folded.open_handle(&spelled, opts(OpenIntent::Open)).await,
            Err(SmbError::NotFound)
        ));
        assert!(matches!(
            folded.open_handle(&spelled, opts(OpenIntent::Create)).await,
            Err(SmbError::AccessDenied)
        ));
        assert!(matches!(
            folded.unlink(&spelled).await,
            Err(SmbError::NotFound)
        ));
        assert!(matches!(
            folded.rename(&spelled, &path("x"), false).await,
            Err(SmbError::NotFound)
        ));

        let files = MemFsBackend::new();
        let exact = clear_over(exact_names(&files)).await;
        let (made, action) = open(&exact, ".SMB-Encryption", OpenIntent::Create).await;
        assert_eq!(action, OpenAction::Created);
        assert_eq!(files.contents(".SMB-Encryption"), Some(Vec::new()));
        drop(made);
        exact.unlink(&spelled).await.unwrap();
        assert_eq!(files.contents(".SMB-Encryption"), None);
    }

    #[tokio::test]
    async fn the_root_cannot_be_unlinked_or_renamed() {
        let files = MemFsBackend::new();
        let layer = clear_over(files.clone()).await;
        files.clone().with_file("f", b"");
        let root = SmbPath::root();
        assert!(matches!(
            layer.unlink(&root).await,
            Err(SmbError::AccessDenied)
        ));
        assert!(matches!(
            layer.rename(&root, &path("x"), true).await,
            Err(SmbError::AccessDenied)
        ));
        assert!(matches!(
            layer.rename(&path("f"), &root, true).await,
            Err(SmbError::AccessDenied)
        ));
        assert_eq!(files.contents("f"), Some(Vec::new()));
    }

    #[tokio::test]
    async fn exact_names_that_differ_in_case_are_two_files() {
        let files = MemFsBackend::new();
        let layer = clear_over(exact_names(&files)).await;
        let (lower, _) = open(&layer, "report", OpenIntent::Create).await;
        let (upper, _) = open(&layer, "Report", OpenIntent::Create).await;
        assert!(!shares_node(&lower, &upper));
        layer.unlink(&path("REPORT")).await.unwrap_err();
        assert!(!lower.node().is_detached());
        layer.unlink(&path("Report")).await.unwrap();
        assert!(upper.node().is_detached());
        assert!(!lower.node().is_detached());
    }

    #[tokio::test]
    async fn case_variants_of_an_open_file_share_one_file_lock() {
        let files = MemFsBackend::new();
        let layer = clear_over(Folding::new(files.clone())).await;
        let (upper, _) = open(&layer, "Report.docx", OpenIntent::Create).await;
        let lower = Arc::new(open_file(&layer, "report.docx").await);
        assert!(shares_node(&upper, &lower));
        assert_eq!(layer.node_count(), 1);

        let writer = upper.node().file().expect("a file node").write().await;
        let reading = tokio::spawn({
            let lower = Arc::clone(&lower);
            async move { lower.stat().await }
        });
        settle().await;
        assert!(!reading.is_finished(), "the other spelling waits");

        drop(writer);
        reading.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn an_overwriting_open_through_another_spelling_resets_the_header_for_every_handle() {
        let files = MemFsBackend::new();
        let layer = clear_over(Folding::new(files.clone())).await;
        files
            .clone()
            .with_file("report.docx", b"abc")
            .with_file("memo.txt", b"abc");
        for (first, second, intent) in [
            ("Report.docx", "REPORT.DOCX", OpenIntent::Truncate),
            ("Memo.txt", "memo.TXT", OpenIntent::OverwriteOrCreate),
        ] {
            let (held, _) = open(&layer, first, OpenIntent::Open).await;
            assert_eq!(held.node().header().await, Some(HeaderKind::Unknown));

            let (overwriting, action) = open(&layer, second, intent).await;
            assert_eq!(action, OpenAction::Overwritten, "{second} {intent:?}");
            assert!(shares_node(&held, &overwriting), "{second} {intent:?}");
            assert_eq!(held.node().header().await, Some(HeaderKind::Absent));
            assert_eq!(files.contents(&first.to_lowercase()), Some(Vec::new()));
            assert_eq!(layer.node_count(), 1);
        }
    }

    #[tokio::test]
    async fn an_unlink_through_another_spelling_detaches_the_node_and_a_create_starts_a_new_one() {
        let files = MemFsBackend::new();
        let layer = clear_over(Folding::new(files.clone())).await;
        let (first, _) = open(&layer, "Report.docx", OpenIntent::Create).await;

        layer.unlink(&path("report.docx")).await.unwrap();
        assert!(first.node().is_detached());
        assert_eq!(layer.node_count(), 0);

        let (second, action) = open(&layer, "Report.docx", OpenIntent::Create).await;
        assert_eq!(action, OpenAction::Created);
        assert!(!shares_node(&first, &second));
        assert!(!second.node().is_detached());

        layer.unlink(&path("REPORT.DOCX")).await.unwrap();
        assert!(second.node().is_detached());
        let (third, action) = open(&layer, "report.docx", OpenIntent::Create).await;
        assert_eq!(action, OpenAction::Created);
        assert!(!shares_node(&second, &third));
        assert!(!shares_node(&first, &third));
        assert!(!third.node().is_detached());
        assert_eq!(third.node().header().await, Some(HeaderKind::Absent));
        assert_eq!(layer.node_count(), 1);

        let (found, _) = open(&layer, "REPORT.docx", OpenIntent::Open).await;
        assert!(shares_node(&third, &found));
    }

    #[tokio::test]
    async fn a_rename_through_another_spelling_moves_the_node_of_an_open_file() {
        let files = MemFsBackend::new();
        let layer = clear_over(Folding::new(files.clone())).await;
        let (held, _) = open(&layer, "Report.docx", OpenIntent::Create).await;

        layer
            .rename(&path("REPORT.DOCX"), &path("Final.docx"), false)
            .await
            .unwrap();
        assert_eq!(held.node().path(), path("Final.docx"));
        assert_eq!(files.contents("report.docx"), None);
        assert!(files.contents("final.docx").is_some());
        let (moved, _) = open(&layer, "final.docx", OpenIntent::Open).await;
        assert!(shares_node(&held, &moved));
        assert!(matches!(
            layer
                .open_handle(&path("Report.docx"), opts(OpenIntent::Open))
                .await,
            Err(SmbError::NotFound)
        ));

        layer
            .rename(&path("fINAL.DOCX"), &path("Done.docx"), false)
            .await
            .unwrap();
        let (again, _) = open(&layer, "DONE.docx", OpenIntent::Open).await;
        assert!(shares_node(&held, &again));
        assert!(!held.node().is_detached());
        assert_eq!(layer.node_count(), 1);
    }

    #[tokio::test]
    async fn a_rename_over_a_case_variant_of_an_open_file_detaches_its_node() {
        let files = MemFsBackend::new();
        let layer = clear_over(Folding::new(files.clone())).await;
        files
            .clone()
            .with_file("a.txt", b"")
            .with_file("b.txt", b"");
        let (source, _) = open(&layer, "A.txt", OpenIntent::Open).await;
        let (target, _) = open(&layer, "B.txt", OpenIntent::Open).await;
        assert!(!shares_node(&source, &target));

        layer
            .rename(&path("a.TXT"), &path("b.txt"), true)
            .await
            .unwrap();
        assert!(target.node().is_detached());
        assert!(!source.node().is_detached());
        assert_eq!(source.node().path(), path("b.txt"));
        let (at_target, _) = open(&layer, "B.TXT", OpenIntent::Open).await;
        assert!(shares_node(&source, &at_target));
        assert_eq!(layer.node_count(), 1);
    }

    #[tokio::test]
    async fn a_directory_rename_through_another_spelling_moves_the_nodes_below_it() {
        let files = MemFsBackend::new();
        let layer = clear_over(Folding::new(files.clone())).await;
        files
            .clone()
            .with_dir("dir")
            .with_dir("dir\\sub")
            .with_file("dir\\f", b"")
            .with_file("dir\\sub\\g", b"");
        let (file, _) = open(&layer, "dir\\f", OpenIntent::Open).await;
        let (deep, _) = open(&layer, "Dir\\Sub\\g", OpenIntent::Open).await;
        let dir = open_dir(&layer, "Dir").await;

        layer
            .rename(&path("DIR"), &path("Moved"), false)
            .await
            .unwrap();
        assert_eq!(file.node().path(), path("Moved\\f"));
        assert_eq!(deep.node().path(), path("Moved\\Sub\\g"));
        assert_eq!(dir.node().path(), path("Moved"));
        let (file_again, _) = open(&layer, "MOVED\\F", OpenIntent::Open).await;
        let (deep_again, _) = open(&layer, "moved\\SUB\\G", OpenIntent::Open).await;
        assert!(shares_node(&file, &file_again));
        assert!(shares_node(&deep, &deep_again));
        let dir_again = open_dir(&layer, "moved").await;
        assert!(shares_node(&dir, &dir_again));
        assert!(matches!(
            layer
                .open_handle(&path("dir\\f"), opts(OpenIntent::Open))
                .await,
            Err(SmbError::PathNotFound)
        ));
        assert_eq!(layer.node_count(), 3);
    }

    #[tokio::test]
    async fn an_open_waits_for_a_create_in_its_directory_spelled_another_way() {
        let files = MemFsBackend::new();
        let gated = Gated::new(Folding::new(files.clone()));
        let layer = clear_over(gated.clone()).await;
        files.clone().with_dir("dir");
        let gate = gated.arm_after_at(Op::Open, "Dir\\x");
        let creating = spawn_open(&layer, "Dir\\x", OpenIntent::Create);
        gate.reached().await;
        assert_eq!(files.contents("dir\\x"), Some(Vec::new()));
        assert_eq!(layer.node_count(), 0, "the create has no node yet");

        let opening = spawn_open(&layer, "dir\\x", OpenIntent::Open);
        settle().await;
        assert!(!opening.is_finished());
        assert_eq!(layer.node_count(), 0);

        gate.release();
        let (created, action) = creating.await.unwrap().unwrap();
        assert_eq!(action, OpenAction::Created);
        let (opened, action) = opening.await.unwrap().unwrap();
        assert_eq!(action, OpenAction::Opened);
        assert!(shares_node(&created, &opened));
        assert_eq!(created.node().header().await, Some(HeaderKind::Absent));
        assert_eq!(layer.node_count(), 1);
    }

    #[tokio::test]
    async fn creates_in_one_directory_spelled_two_ways_run_one_at_a_time() {
        let files = MemFsBackend::new();
        let gated = Gated::new(Folding::new(files.clone()));
        let layer = clear_over(gated.clone()).await;
        files.clone().with_dir("dir");
        let gate = gated.arm_at(Op::Open, "Dir\\x");
        let first = spawn_open(&layer, "Dir\\x", OpenIntent::Create);
        gate.reached().await;

        let second = spawn_open(&layer, "dir\\y", OpenIntent::Create);
        settle().await;
        assert!(!second.is_finished());
        assert_eq!(files.contents("dir\\y"), None);
        assert_eq!(layer.shared.locks.directory_count(), 1);

        gate.release();
        let (x, action) = first.await.unwrap().unwrap();
        assert_eq!(action, OpenAction::Created);
        let (y, action) = second.await.unwrap().unwrap();
        assert_eq!(action, OpenAction::Created);
        assert!(!shares_node(&x, &y));
        assert_eq!(files.contents("dir\\x"), Some(Vec::new()));
        assert_eq!(files.contents("dir\\y"), Some(Vec::new()));
        assert_eq!(layer.node_count(), 2);
    }

    #[tokio::test]
    async fn an_unlink_waits_for_a_create_in_its_directory_spelled_another_way() {
        let files = MemFsBackend::new();
        let gated = Gated::new(Folding::new(files.clone()));
        let layer = clear_over(gated.clone()).await;
        files.clone().with_dir("dir").with_file("dir\\y", b"");
        let gate = gated.arm_at(Op::Open, "Dir\\x");
        let creating = spawn_open(&layer, "Dir\\x", OpenIntent::Create);
        gate.reached().await;

        let unlinking = tokio::spawn({
            let layer = layer.clone();
            async move { layer.unlink(&path("DIR\\y")).await }
        });
        settle().await;
        assert!(!unlinking.is_finished());
        assert!(files.contents("dir\\y").is_some());

        gate.release();
        let (_, action) = creating.await.unwrap().unwrap();
        assert_eq!(action, OpenAction::Created);
        unlinking.await.unwrap().unwrap();
        assert_eq!(files.contents("dir\\y"), None);
        assert!(files.contents("dir\\x").is_some());
    }

    #[tokio::test]
    async fn files_are_opened_in_the_inner_backend_for_reading() {
        let recorder = Recorder::default();
        let layer = EncryptedBackend::new(recorder.clone(), key_schedule(), clear_settings());
        let asked = OpenOptions {
            read: false,
            write_attributes: true,
            intent: OpenIntent::OpenOrCreate,
            non_directory: true,
            delete_on_close: true,
            ..OpenOptions::default()
        };
        layer.open_handle(&path("f"), asked).await.unwrap();
        let sent = OpenOptions {
            read: true,
            ..asked
        };
        assert_eq!(
            recorder.calls(),
            [
                "capabilities".to_string(),
                format!("open f {sent:?}"),
                "stat".to_string(),
            ]
        );
    }

    #[tokio::test]
    async fn an_overwriting_open_checks_the_file_before_the_inner_backend_empties_it() {
        let recorder = Recorder::default();
        let layer = EncryptedBackend::new(recorder.clone(), key_schedule(), clear_settings());
        let asked = OpenOptions {
            write_attributes: true,
            intent: OpenIntent::Truncate,
            non_directory: true,
            ..OpenOptions::default()
        };
        layer.open_handle(&path("f"), asked).await.unwrap();
        let check = OpenOptions {
            non_directory: true,
            ..OpenOptions::default()
        };
        let emptying = OpenOptions {
            write: true,
            ..asked
        };
        assert_eq!(
            recorder.calls(),
            [
                "capabilities".to_string(),
                format!("open f {check:?}"),
                "stat".to_string(),
                format!("open f {emptying:?}"),
                "close".to_string(),
            ]
        );
    }

    #[tokio::test]
    async fn every_open_that_creates_holds_its_directory_exclusively() {
        for intent in [
            OpenIntent::Create,
            OpenIntent::OpenOrCreate,
            OpenIntent::OverwriteOrCreate,
        ] {
            let files = MemFsBackend::new();
            let gated = Gated::new(files.clone());
            let layer = clear_over(gated.clone()).await;
            let gate = gated.arm_at(Op::Open, "f");
            let after_create =
                (intent == OpenIntent::Create).then(|| gated.arm_after_at(Op::Open, "f"));
            let creating = spawn_open(&layer, "f", intent);
            gate.reached().await;
            assert!(
                layer.shared.locks.directory(String::new()).is_exclusive(),
                "{intent:?}"
            );
            assert!(layer.shared.locks.tree.try_write().is_err(), "{intent:?}");

            let opening = spawn_open(&layer, "f", OpenIntent::Open);
            settle().await;
            assert!(!opening.is_finished(), "{intent:?}");

            gate.release();
            if let Some(after_create) = after_create {
                after_create.reached().await;
                assert_eq!(files.contents("f"), Some(Vec::new()), "{intent:?}");
                assert!(
                    layer.shared.locks.directory(String::new()).is_exclusive(),
                    "{intent:?} after the inner create"
                );
                assert!(
                    layer.shared.locks.tree.try_write().is_err(),
                    "{intent:?} after the inner create"
                );
                settle().await;
                assert!(!opening.is_finished(), "{intent:?} after the inner create");
                after_create.release();
            }
            let (created, action) = creating.await.unwrap().unwrap();
            assert_eq!(action, OpenAction::Created, "{intent:?}");
            let (opened, action) = opening.await.unwrap().unwrap();
            assert_eq!(action, OpenAction::Opened, "{intent:?}");
            assert!(shares_node(&created, &opened), "{intent:?}");
        }
    }

    #[tokio::test]
    async fn a_truncating_open_holds_its_directory_shared() {
        let files = MemFsBackend::new();
        let gated = Gated::new(files.clone());
        let layer = clear_over(gated.clone()).await;
        files.clone().with_file("f", b"abc").with_file("g", b"");
        let gate = gated.arm_at(Op::Open, "f");
        let truncating = spawn_open(&layer, "f", OpenIntent::Truncate);
        gate.reached().await;
        let directory = layer.shared.locks.directory(String::new());
        assert!(!directory.is_free() && !directory.is_exclusive());

        let opening = spawn_open(&layer, "g", OpenIntent::Open);
        settle().await;
        assert!(opening.is_finished());
        opening.await.unwrap().unwrap();

        gate.release();
        let (_, action) = truncating.await.unwrap().unwrap();
        assert_eq!(action, OpenAction::Overwritten);
    }

    #[tokio::test]
    async fn a_rename_waits_for_an_unlink_in_progress() {
        let files = MemFsBackend::new();
        let gated = Gated::new(files.clone());
        let layer = clear_over(gated.clone()).await;
        files.clone().with_file("f", b"").with_file("a", b"");
        let gate = gated.arm_at(Op::Unlink, "f");
        let unlinking = tokio::spawn({
            let layer = layer.clone();
            async move { layer.unlink(&path("f")).await }
        });
        gate.reached().await;

        let renaming = tokio::spawn({
            let layer = layer.clone();
            async move { layer.rename(&path("a"), &path("b"), false).await }
        });
        settle().await;
        assert!(!renaming.is_finished());
        assert!(files.contents("a").is_some());

        gate.release();
        unlinking.await.unwrap().unwrap();
        renaming.await.unwrap().unwrap();
        assert_eq!(files.contents("f"), None);
        assert_eq!(files.contents("a"), None);
        assert!(files.contents("b").is_some());
    }

    #[tokio::test]
    async fn an_open_waits_for_a_rename_in_progress() {
        let files = MemFsBackend::new();
        let gated = Gated::new(files.clone());
        let layer = clear_over(gated.clone()).await;
        files.clone().with_file("a", b"").with_file("g", b"");
        let gate = gated.arm_at(Op::Rename, "a");
        let renaming = tokio::spawn({
            let layer = layer.clone();
            async move { layer.rename(&path("a"), &path("b"), false).await }
        });
        gate.reached().await;

        let opening = spawn_open(&layer, "g", OpenIntent::Open);
        settle().await;
        assert!(!opening.is_finished());
        assert!(files.contents("a").is_some());

        gate.release();
        renaming.await.unwrap().unwrap();
        opening.await.unwrap().unwrap();
        assert_eq!(files.contents("a"), None);
        assert!(files.contents("b").is_some());
    }

    #[tokio::test]
    async fn opens_of_different_directories_do_not_wait_for_each_other() {
        let files = MemFsBackend::new();
        let gated = Gated::new(files.clone());
        let layer = clear_over(gated.clone()).await;
        files
            .clone()
            .with_dir("a")
            .with_dir("b")
            .with_file("a\\f", b"")
            .with_file("b\\g", b"");
        let gate = gated.arm_at(Op::Stat, "a\\f");
        let parked = spawn_open(&layer, "a\\f", OpenIntent::Open);
        gate.reached().await;

        let (other, _) = open(&layer, "b\\g", OpenIntent::OpenOrCreate).await;
        assert_eq!(other.node().path(), path("b\\g"));

        gate.release();
        parked.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn a_failed_stat_after_the_inner_open_closes_the_inner_handle() {
        let files = MemFsBackend::new();
        let gated = Gated::new(files.clone());
        let layer = clear_over(gated.clone()).await;
        files.clone().with_file("f", b"");
        let gate = gated.arm_at(Op::Stat, "f");
        let opening = spawn_open(&layer, "f", OpenIntent::Open);
        gate.reached().await;
        files.remove("f");
        gate.release();

        assert!(matches!(opening.await.unwrap(), Err(SmbError::NotFound)));
        assert_eq!(files.open_handles(), 0);
        assert_eq!(layer.node_count(), 0);
    }
}