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
// SPDX-License-Identifier: AGPL-3.0-or-later
use btfproto::{
    local_fs::{LocalFs, ModeAuthorizer},
    msg::{GrantAccess, SpecInodes},
    server::FsProvider,
};
use btlib::{
    crypto::{Creds, CredsPriv, CredsPub},
    AuthzAttrs, BlockError, BlockPath, IssuedProcRec,
};
use std::{
    net::{IpAddr, Ipv6Addr},
    path::PathBuf,
    sync::Arc,
};
use tempdir::TempDir;

pub fn bind_path<C: CredsPriv>(creds: C) -> BlockPath {
    let writecap = creds
        .writecap()
        .ok_or(btlib::BlockError::MissingWritecap)
        .unwrap();
    writecap.bind_path()
}

pub type ConcreteFs = LocalFs<ModeAuthorizer>;

pub struct LocalFsTest {
    dir: TempDir,
    fs: ConcreteFs,
    node_bind_path: Arc<BlockPath>,
}

fn node_creds() -> Arc<dyn Creds> {
    Arc::new(super::node_creds())
}

fn root_creds() -> Arc<dyn Creds> {
    Arc::new(super::root_creds())
}

impl LocalFsTest {
    pub const NODE_UID: u32 = 1000;
    pub const NODE_GID: u32 = 1000;

    pub async fn new_empty() -> LocalFsTest {
        let dir = TempDir::new("fuse").expect("failed to create temp dir");
        let node_creds = node_creds();
        Self::grant_node_access(dir.path().to_owned()).await;
        let node_writecap = node_creds
            .writecap()
            .ok_or(BlockError::MissingWritecap)
            .unwrap();
        let node_bind_path = Arc::new(node_writecap.bind_path());
        let fs = LocalFs::new_existing(dir.path().to_owned(), node_creds, ModeAuthorizer)
            .expect("failed to create empty blocktree");
        LocalFsTest {
            dir,
            fs,
            node_bind_path,
        }
    }

    pub fn new_existing(dir: TempDir) -> LocalFsTest {
        let fs = LocalFs::new_existing(dir.path().to_owned(), node_creds(), ModeAuthorizer)
            .expect("failed to create blocktree from existing directory");
        let from = Arc::new(bind_path(node_creds()));
        LocalFsTest {
            dir,
            fs,
            node_bind_path: from,
        }
    }

    async fn grant_node_access(path: PathBuf) {
        let root_creds = root_creds();
        let root_writecap = root_creds
            .writecap()
            .ok_or(BlockError::MissingWritecap)
            .unwrap();
        let root_bind_path = Arc::new(root_writecap.bind_path());
        let node_creds = node_creds();
        let node_writecap = node_creds
            .writecap()
            .ok_or(BlockError::MissingWritecap)
            .unwrap();
        let fs = LocalFs::new_empty(path, 0, root_creds, ModeAuthorizer)
            .await
            .unwrap();

        let proc_rec = IssuedProcRec {
            addr: IpAddr::V6(Ipv6Addr::LOCALHOST),
            pub_creds: node_creds.concrete_pub(),
            writecap: node_writecap.to_owned(),
            authz_attrs: AuthzAttrs {
                uid: Self::NODE_UID,
                gid: Self::NODE_GID,
                supp_gids: Vec::new(),
            },
        };
        let msg = GrantAccess {
            inode: SpecInodes::RootDir.into(),
            record: proc_rec,
        };
        fs.grant_access(&root_bind_path, msg).await.unwrap();
    }

    pub fn into_parts(self) -> (TempDir, ConcreteFs, Arc<BlockPath>) {
        (self.dir, self.fs, self.node_bind_path)
    }

    pub fn fs(&self) -> &ConcreteFs {
        &self.fs
    }

    pub fn from(&self) -> &Arc<BlockPath> {
        &self.node_bind_path
    }
}

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

    use btfproto::{local_fs::Error, msg::*};
    use btlib::{Inode, Result, SECTOR_SZ_DEFAULT};
    use btlib_tests::fs_queries::num_files;
    use std::{
        fs::read_dir,
        io::{self, Cursor, Write as IoWrite},
        ops::Deref,
        sync::Arc,
    };

    /// Tests that a new file can be created, written to and the written data can be read from it.
    #[tokio::test]
    async fn create_write_read() {
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let from = case.from();
        let name = "README.md";
        let flags = Flags::new(libc::O_RDWR);

        let create_msg = Create {
            parent: SpecInodes::RootDir.into(),
            name,
            flags,
            mode: libc::S_IFREG | 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();

        const LEN: usize = 32;
        let expected = [1u8; LEN];
        let write_msg = Write {
            inode,
            handle,
            offset: 0,
            data: expected.as_slice(),
        };
        let WriteReply { written, .. } = bt.write(from, write_msg).await.unwrap();
        assert_eq!(LEN as u64, written);

        let read_msg = Read {
            inode,
            handle,
            offset: 0,
            size: LEN as u64,
        };
        let guard = bt.read(from, read_msg).await.unwrap();

        assert_eq!(expected, guard.deref())
    }

    #[tokio::test]
    async fn lookup() {
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let from = case.from();

        let name = "README.md";
        let create_msg = Create {
            parent: SpecInodes::RootDir.into(),
            name,
            flags: Flags::default(),
            mode: 0,
            umask: 0,
        };
        let create_reply = bt.create(from, create_msg).await.unwrap();

        let lookup_msg = Lookup {
            parent: SpecInodes::RootDir.into(),
            name,
        };
        let lookup_reply = bt.lookup(from, lookup_msg).await.unwrap();

        assert_eq!(create_reply.inode, lookup_reply.inode);
    }

    /// Tests that data written by one instance of [Blocktree] can be read by a subsequent
    /// instance.
    #[tokio::test]
    async fn new_existing() {
        const EXPECTED: &[u8] = b"cool as cucumbers";
        let name = "RESIGNATION.docx";
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let from = case.from();
        let flags = Flags::new(libc::O_RDWR);

        {
            let create_msg = Create {
                parent: SpecInodes::RootDir.into(),
                name,
                mode: libc::S_IFREG | 0o644,
                flags,
                umask: 0,
            };
            let CreateReply { handle, inode, .. } = bt.create(from, create_msg).await.unwrap();

            let write_msg = Write {
                inode,
                handle,
                offset: 0,
                data: EXPECTED,
            };
            let WriteReply { written, .. } = bt.write(from, write_msg).await.unwrap();
            assert_eq!(EXPECTED.len() as u64, written);

            let close_msg = Close { inode, handle };
            bt.close(from, close_msg).await.unwrap();
        }

        let case = LocalFsTest::new_existing(case.dir);
        let from = case.from();
        let bt = &case.fs;

        let lookup_msg = Lookup {
            parent: SpecInodes::RootDir.into(),
            name,
        };
        let LookupReply { inode, .. } = bt.lookup(from, lookup_msg).await.unwrap();

        let open_msg = Open {
            inode,
            flags: Flags::new(libc::O_RDONLY),
        };
        let OpenReply { handle, .. } = bt.open(from, open_msg).await.unwrap();

        let read_msg = Read {
            inode,
            handle,
            offset: 0,
            size: EXPECTED.len() as u64,
        };
        let guard = bt.read(from, read_msg).await.unwrap();

        assert_eq!(EXPECTED, guard.deref())
    }

    /// Tests that an error is returned by the `Blocktree::write` method if the file was opened
    /// read-only.
    #[tokio::test]
    async fn open_read_only_write_is_error() {
        let name = "books.ods";
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let from = case.from();

        let create_msg = Create {
            parent: SpecInodes::RootDir.into(),
            name,
            flags: Flags::default(),
            mode: libc::S_IFREG | 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();

        let close_msg = Close { inode, handle };
        bt.close(from, close_msg).await.unwrap();

        let open_msg = Open {
            inode,
            flags: libc::O_RDONLY.into(),
        };
        let OpenReply { handle, .. } = bt.open(from, open_msg).await.unwrap();

        let data = [1u8; 32];
        let write_msg = Write {
            inode,
            handle,
            offset: 0,
            data: data.as_slice(),
        };
        let result = bt.write(from, write_msg).await;

        let err = result.err().unwrap();
        let err = err.downcast::<Error>().unwrap();
        let actual_handle = if let Error::ReadOnlyHandle(actual_handle) = err {
            Some(actual_handle)
        } else {
            None
        };
        assert_eq!(Some(handle), actual_handle);
    }

    /// Asserts that the given [Result] is an [Err] and that it contains an [io::Error] which
    /// corresponds to the [libc::ENOENT] error code.
    fn assert_enoent<T>(result: Result<T>) {
        let err = result.err().unwrap().downcast::<io::Error>().unwrap();
        assert_eq!(libc::ENOENT, err.raw_os_error().unwrap());
    }

    /// Tests that multiple handles see consistent metadata associated with a block.
    #[tokio::test]
    async fn ensure_metadata_consistency() {
        let case = LocalFsTest::new_empty().await;
        let from = case.from();
        let trash = ".Trash";
        let file = "file.txt";
        let bt = &case.fs;
        let root = SpecInodes::RootDir.into();

        let open_msg = Open {
            inode: root,
            flags: libc::O_DIRECTORY.into(),
        };
        let OpenReply { handle, .. } = bt.open(from, open_msg).await.unwrap();

        // Because the directory is open, this will cause a new handle for this block to be opened.
        let lookup_msg = Lookup {
            parent: root,
            name: trash,
        };
        let result = bt.lookup(from, lookup_msg).await;
        assert_enoent(result);

        let close_msg = Close {
            inode: root,
            handle,
        };
        bt.close(from, close_msg).await.unwrap();

        let create_msg = Create {
            parent: root,
            name: file,
            flags: Flags::default(),
            mode: libc::S_IFREG | 0o644,
            umask: 0,
        };
        bt.create(from, create_msg).await.unwrap();

        let open_msg = Open {
            inode: root,
            flags: libc::O_DIRECTORY.into(),
        };
        bt.open(from, open_msg).await.unwrap();

        // Since the directory is open, the second handle will be used for this lookup.
        let lookup_msg = Lookup {
            parent: root,
            name: trash,
        };
        let result = bt.lookup(from, lookup_msg).await;
        assert!(result.is_err());
    }

    /// Tests that the `size` parameter actually limits the number of read bytes.
    #[tokio::test]
    async fn read_with_smaller_size() {
        const DATA: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
        let case = LocalFsTest::new_empty().await;
        let from = case.from();
        let file = "file.txt";
        let bt = &case.fs;
        let root: Inode = SpecInodes::RootDir.into();

        let create_msg = Create {
            parent: root,
            name: file,
            flags: libc::O_RDWR.into(),
            mode: libc::S_IFREG | 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();
        let write_msg = Write {
            inode,
            handle,
            offset: 0,
            data: DATA.as_slice(),
        };
        let WriteReply { written, .. } = bt.write(from, write_msg).await.unwrap();
        assert_eq!(DATA.len() as u64, written);
        const SIZE: usize = DATA.len() / 2;
        let read_msg = Read {
            inode,
            handle,
            offset: 0,
            size: SIZE as u64,
        };
        let guard = bt.read(from, read_msg).await.unwrap();

        assert_eq!(&[0, 1, 2, 3], guard.deref());
    }

    /// Returns an integer array starting at the given value and increasing by one for each
    /// subsequent entry.
    pub const fn integer_array<const N: usize>(start: u8) -> [u8; N] {
        let mut array = [0u8; N];
        let mut k = 0usize;
        while k < N {
            array[k] = start.wrapping_add(k as u8);
            k += 1;
        }
        array
    }

    #[tokio::test]
    async fn concurrent_reads() {
        // The size of each of the reads.
        const SIZE: usize = 4;
        // The number of concurrent reads.
        const NREADS: usize = 32;
        const DATA_LEN: usize = SIZE * NREADS;
        const DATA: [u8; DATA_LEN] = integer_array::<DATA_LEN>(0);
        let case = LocalFsTest::new_empty().await;
        let from = case.from();
        let file = "file.txt";
        let bt = &case.fs;
        let root: Inode = SpecInodes::RootDir.into();
        let mode = libc::S_IFREG | 0o644;

        let create_msg = Create {
            parent: root,
            name: file,
            flags: libc::O_RDWR.into(),
            mode,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();
        let write_msg = Write {
            inode,
            handle,
            offset: 0,
            data: DATA.as_slice(),
        };
        let WriteReply { written, .. } = bt.write(from, write_msg).await.unwrap();
        assert_eq!(DATA.len() as u64, written);
        let case = Arc::new(case);

        let mut handles = Vec::with_capacity(NREADS);
        for offset in (0..NREADS).map(|e| e * SIZE) {
            let case = case.clone();
            handles.push(tokio::spawn(async move {
                // Notice that we have concurrent reads to different offsets using the same handle.
                // Without proper synchronization, this shouldn't work.
                let read_msg = Read {
                    inode,
                    handle,
                    offset: offset as u64,
                    size: SIZE as u64,
                };
                let guard = case.fs.read(case.from(), read_msg).await.unwrap();
                let expected = integer_array::<SIZE>(offset as u8);
                assert_eq!(&expected, guard.deref());
            }));
        }
        for handle in handles {
            handle.await.unwrap();
        }
    }

    #[tokio::test]
    async fn link_in_same_directory() {
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let from = case.from();
        let root: Inode = SpecInodes::RootDir.into();
        let src_name = "src";
        let dst_name = "dst";

        let create_msg = Create {
            parent: root,
            name: src_name,
            flags: Flags::default(),
            mode: libc::S_IFREG | 0o644,
            umask: 0,
        };
        let CreateReply { inode, .. } = bt.create(from, create_msg).await.unwrap();
        let link_msg = Link {
            inode,
            new_parent: root,
            name: dst_name,
        };
        bt.link(from, link_msg).await.unwrap();
        let unlink_msg = Unlink {
            parent: root,
            name: src_name,
        };
        bt.unlink(from, unlink_msg).await.unwrap();

        let lookup_msg = Lookup {
            parent: root,
            name: dst_name,
        };
        let LookupReply {
            inode: actual_inode,
            ..
        } = bt.lookup(from, lookup_msg).await.unwrap();
        assert_eq!(inode, actual_inode);
        let lookup_msg = Lookup {
            parent: root,
            name: src_name,
        };
        let result = bt.lookup(from, lookup_msg).await;
        assert_enoent(result);
    }

    #[tokio::test]
    async fn link_in_different_directory() {
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let from = case.from();
        let root = SpecInodes::RootDir.into();
        let dir_name = "dir";
        let file_name = "file";

        let create_msg = Create {
            parent: root,
            name: dir_name,
            flags: libc::O_DIRECTORY.into(),
            mode: libc::S_IFDIR | 0o755,
            umask: 0,
        };
        let CreateReply { inode: dir, .. } = bt.create(from, create_msg).await.unwrap();
        let create_msg = Create {
            parent: root,
            name: file_name,
            flags: Flags::default(),
            mode: libc::S_IFREG | 0o644,
            umask: 0,
        };
        let CreateReply { inode: file, .. } = bt.create(from, create_msg).await.unwrap();
        let link_msg = Link {
            inode: file,
            new_parent: dir,
            name: file_name,
        };
        bt.link(from, link_msg).await.unwrap();
        let unlink_msg = Unlink {
            parent: root,
            name: file_name,
        };
        bt.unlink(from, unlink_msg).await.unwrap();

        let lookup_msg = Lookup {
            parent: dir,
            name: file_name,
        };
        let LookupReply {
            inode: actual_inode,
            ..
        } = bt.lookup(from, lookup_msg).await.unwrap();
        assert_eq!(file, actual_inode);
        let lookup_msg = Lookup {
            parent: root,
            name: file_name,
        };
        let result = bt.lookup(from, lookup_msg).await;
        assert_enoent(result);
    }

    /// Tests that link can be used to overwrite a file in the same directory.
    #[tokio::test]
    async fn link_replace_same_directory() {
        const EXPECTED: &[u8] = b"got 'em";
        let case = LocalFsTest::new_empty().await;
        let block_dir = case.dir.path();
        let bt = &case.fs;
        let from = case.from();
        let root: Inode = SpecInodes::RootDir.into();
        let oldname = "old";
        let newname = "new";

        let create_msg = Create {
            parent: root,
            name: oldname,
            flags: FlagValue::ReadWrite.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();
        let write_msg = Write {
            inode,
            handle,
            offset: 0,
            data: EXPECTED,
        };
        bt.write(from, write_msg).await.unwrap();
        let close_msg = Close { inode, handle };
        bt.close(from, close_msg).await.unwrap();
        let create_msg = Create {
            parent: root,
            name: newname,
            flags: Flags::default(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply {
            inode: newname_inode,
            ..
        } = bt.create(from, create_msg).await.unwrap();
        let before = num_files(block_dir).unwrap();

        let link_msg = Link {
            inode,
            new_parent: root,
            name: newname,
        };
        bt.link(from, link_msg).await.unwrap();
        let forget_msg = Forget {
            inode: newname_inode,
            count: 1,
        };
        bt.forget(from, forget_msg).await.unwrap();

        let open_msg = Open {
            inode,
            flags: FlagValue::ReadOnly.into(),
        };
        let OpenReply { handle, .. } = bt.open(from, open_msg).await.unwrap();
        let read_msg = Read {
            inode,
            handle,
            offset: 0,
            size: 2 * EXPECTED.len() as u64,
        };
        let buf_guard = bt.read(from, read_msg).await.unwrap();
        assert_eq!(EXPECTED, buf_guard.deref());
        // Check that the old block file was deleted.
        let actual = num_files(block_dir).unwrap();
        assert_eq!(actual, before - 1);
    }

    /// Tests that `link` can be used to overwrite a file in a different directory.
    #[tokio::test]
    async fn link_replace_different_directory() {
        const EXPECTED: &[u8] = b"got 'em";
        let case = LocalFsTest::new_empty().await;
        let block_dir = case.dir.path();
        let bt = &case.fs;
        let from = case.from();
        let root = SpecInodes::RootDir.into();
        let dir_name = "dir";
        let file_name = "file";

        let create_msg = Create {
            parent: root,
            name: dir_name,
            flags: libc::O_DIRECTORY.into(),
            mode: 0o755,
            umask: 0,
        };
        let CreateReply { inode: dir, .. } = bt.create(from, create_msg).await.unwrap();
        let create_msg = Create {
            parent: root,
            name: file_name,
            flags: FlagValue::ReadWrite.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();
        let write_msg = Write {
            inode,
            handle,
            offset: 0,
            data: EXPECTED,
        };
        bt.write(from, write_msg).await.unwrap();
        let close_msg = Close { inode, handle };
        bt.close(from, close_msg).await.unwrap();
        let create_msg = Create {
            parent: dir,
            name: file_name,
            flags: Flags::default(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply {
            inode: newdir_inode,
            ..
        } = bt.create(from, create_msg).await.unwrap();
        let before = num_files(block_dir).unwrap();

        let link_msg = Link {
            inode,
            new_parent: dir,
            name: file_name,
        };
        bt.link(from, link_msg).await.unwrap();
        let forget_msg = Forget {
            inode: newdir_inode,
            count: 1,
        };
        bt.forget(from, forget_msg).await.unwrap();

        let open_msg = Open {
            inode,
            flags: FlagValue::ReadOnly.into(),
        };
        let OpenReply { handle, .. } = bt.open(from, open_msg).await.unwrap();
        let read_msg = Read {
            inode,
            handle,
            offset: 0,
            size: 2 * EXPECTED.len() as u64,
        };
        let buf_guard = bt.read(from, read_msg).await.unwrap();
        assert_eq!(EXPECTED, buf_guard.deref());
        // Check that the old block file was deleted.
        let actual = num_files(block_dir).unwrap();
        assert_eq!(actual, before - 1);
    }

    #[tokio::test]
    async fn read_from_non_owner_is_err() {
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let name = "file.txt";
        let owner = case.from();
        let mut other = owner.as_ref().clone();
        other.push_component("subdir");
        let other = Arc::new(other);

        let create_msg = Create {
            parent: SpecInodes::RootDir.into(),
            name,
            flags: libc::O_RDWR.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(owner, create_msg).await.unwrap();
        let write_msg = Write {
            inode,
            handle,
            offset: 0,
            data: [1, 2, 3].as_slice(),
        };
        let result = bt.write(&other, write_msg).await;

        let err = result.err().unwrap().downcast::<Error>().unwrap();
        let matched = if let Error::WrongOwner = err {
            true
        } else {
            false
        };
        assert!(matched)
    }

    #[tokio::test]
    async fn allocate_full_sectors_zero_remain_non_zero() {
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let name = "file.txt";
        let from = case.from();

        let create_msg = Create {
            parent: SpecInodes::RootDir.into(),
            name,
            flags: libc::O_RDWR.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();
        const LEN: u64 = 8;
        let alloc_msg = Allocate {
            inode,
            handle,
            offset: None,
            size: LEN,
        };
        bt.allocate(from, alloc_msg).await.unwrap();
        let read_meta_msg = ReadMeta {
            inode,
            handle: Some(handle),
        };
        let ReadMetaReply { attrs, .. } = bt.read_meta(from, read_meta_msg).await.unwrap();
        let read_msg = Read {
            inode,
            handle,
            offset: 0,
            size: LEN,
        };
        let guard = bt.read(from, read_msg).await.unwrap();

        assert_eq!([0u8; 8], guard.deref());
        assert_eq!(guard.len() as u64, attrs.size);
    }

    #[tokio::test]
    async fn allocate_full_sectors_non_zero_remain_non_zero() {
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let name = "file.txt";
        let from = case.from();

        let create_msg = Create {
            parent: SpecInodes::RootDir.into(),
            name,
            flags: libc::O_RDWR.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();
        const LEN: usize = SECTOR_SZ_DEFAULT + 1;
        let mut size = LEN as u64;
        let alloc_msg = Allocate {
            inode,
            handle,
            offset: None,
            size,
        };
        bt.allocate(from, alloc_msg).await.unwrap();
        let mut actual = Cursor::new(Vec::with_capacity(LEN));
        while size > 0 {
            let read_msg = Read {
                inode,
                handle,
                offset: 0,
                size,
            };
            let guard = bt.read(from, read_msg).await.unwrap();
            let data = guard.deref();
            actual.write(data).unwrap();
            size -= data.len() as u64;
        }
        let read_meta_msg = ReadMeta {
            inode,
            handle: Some(handle),
        };
        let ReadMetaReply { attrs, .. } = bt.read_meta(from, read_meta_msg).await.unwrap();

        assert!(vec![0u8; LEN].eq(&actual.into_inner()));
        assert_eq!(LEN as u64, attrs.size);
    }

    #[tokio::test]
    async fn allocate_full_sectors_non_zero_remain_zero() {
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let name = "file.txt";
        let from = case.from();

        let create_msg = Create {
            parent: SpecInodes::RootDir.into(),
            name,
            flags: libc::O_RDWR.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();
        const LEN: usize = SECTOR_SZ_DEFAULT;
        let size = LEN as u64;
        let alloc_msg = Allocate {
            inode,
            handle,
            offset: None,
            size,
        };
        bt.allocate(from, alloc_msg).await.unwrap();
        let read_meta_msg = ReadMeta {
            inode,
            handle: Some(handle),
        };
        let ReadMetaReply { attrs, .. } = bt.read_meta(from, read_meta_msg).await.unwrap();
        let read_msg = Read {
            inode,
            handle,
            offset: 0,
            size,
        };
        let guard = bt.read(from, read_msg).await.unwrap();

        assert_eq!(vec![0u8; LEN], guard.deref());
        assert_eq!(LEN as u64, attrs.size);
    }

    /// Tests that when the new_size of the block is not greater than the current size of the block,
    /// then no change to the block occurs.
    #[tokio::test]
    async fn allocate_new_size_not_greater_than_curr_size() {
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let name = "file.txt";
        let from = case.from();

        let create_msg = Create {
            parent: SpecInodes::RootDir.into(),
            name,
            flags: libc::O_RDWR.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, create_msg).await.unwrap();
        const LEN: usize = 8;
        let write_msg = Write {
            inode,
            handle,
            offset: 0,
            data: [1u8; LEN].as_slice(),
        };
        let WriteReply { written, .. } = bt.write(from, write_msg).await.unwrap();
        assert_eq!(LEN as u64, written);
        let alloc_msg = Allocate {
            inode,
            handle,
            offset: None,
            size: (LEN / 2) as u64,
        };
        bt.allocate(from, alloc_msg).await.unwrap();
        let read_meta_msg = ReadMeta {
            inode,
            handle: Some(handle),
        };
        let ReadMetaReply { attrs, .. } = bt.read_meta(from, read_meta_msg).await.unwrap();
        let read_msg = Read {
            inode,
            handle,
            offset: 0,
            size: LEN as u64,
        };
        let actual = bt.read(from, read_msg).await.unwrap();

        assert_eq!([1u8; LEN], actual.deref());
        assert_eq!(LEN as u64, attrs.size);
    }

    #[tokio::test]
    async fn read_at_non_current_position() {
        const FILENAME: &str = "MANIFESTO.rtf";
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let from = case.from();

        let msg = Create {
            parent: SpecInodes::RootDir.into(),
            name: FILENAME,
            flags: FlagValue::ReadWrite.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply {
            inode,
            handle,
            entry,
            ..
        } = bt.create(from, msg).await.unwrap();
        let sect_sz64 = entry.attr.sect_sz;
        let sect_sz: usize = sect_sz64.try_into().unwrap();
        let mut data = vec![1u8; sect_sz];
        let msg = Write {
            inode,
            handle,
            offset: 0,
            data: data.as_slice(),
        };
        let WriteReply { written, .. } = bt.write(from, msg).await.unwrap();
        assert_eq!(sect_sz64, written);
        data.truncate(0);
        data.extend(std::iter::repeat(2).take(sect_sz));
        let msg = Write {
            inode,
            handle,
            offset: sect_sz64,
            data: data.as_slice(),
        };
        let WriteReply { written, .. } = bt.write(from, msg).await.unwrap();
        assert_eq!(sect_sz64, written);
        // The Accessor for  this block should now have the second sector loaded, so it will have to
        // seek back to the first in order to respond to this read request.
        let msg = Read {
            inode,
            handle,
            offset: 0,
            size: sect_sz64,
        };
        let guard = bt.read(from, msg).await.unwrap();

        assert!(guard
            .deref()
            .iter()
            .map(|e| *e)
            .eq(std::iter::repeat(1u8).take(sect_sz)));
    }

    #[tokio::test]
    async fn unlink_after_forget_file_is_deleted() {
        const FILENAME: &str = "file";
        let case = LocalFsTest::new_empty().await;
        let block_dir = case.dir.path();
        let bt = &case.fs;
        let from = case.from();
        let expected = num_files(block_dir).unwrap();

        let msg = Create {
            parent: SpecInodes::RootDir.into(),
            name: FILENAME,
            flags: FlagValue::ReadWrite.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, msg).await.unwrap();
        const DATA: [u8; 8] = [1u8; 8];
        let msg = Write {
            inode,
            handle,
            offset: 0,
            data: DATA.as_slice(),
        };
        bt.write(from, msg).await.unwrap();
        let msg = Close { inode, handle };
        bt.close(from, msg).await.unwrap();
        let more = num_files(block_dir).unwrap();
        assert!(more > expected);
        let msg = Forget { inode, count: 1 };
        bt.forget(from, msg).await.unwrap();
        let msg = Unlink {
            parent: SpecInodes::RootDir.into(),
            name: FILENAME,
        };
        bt.unlink(from, msg).await.unwrap();

        let actual = num_files(block_dir).unwrap();
        assert_eq!(expected, actual);
    }

    #[tokio::test]
    async fn forget_after_unlink_file_is_deleted() {
        const FILENAME: &str = "file";
        let case = LocalFsTest::new_empty().await;
        let block_dir = case.dir.path();
        let bt = &case.fs;
        let from = case.from();
        let expected = num_files(block_dir).unwrap();

        let msg = Create {
            parent: SpecInodes::RootDir.into(),
            name: FILENAME,
            flags: FlagValue::ReadWrite.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, msg).await.unwrap();
        const DATA: [u8; 8] = [1u8; 8];
        let msg = Write {
            inode,
            handle,
            offset: 0,
            data: DATA.as_slice(),
        };
        bt.write(from, msg).await.unwrap();
        let msg = Close { inode, handle };
        bt.close(from, msg).await.unwrap();
        let more = num_files(block_dir).unwrap();
        let msg = Unlink {
            parent: SpecInodes::RootDir.into(),
            name: FILENAME,
        };
        bt.unlink(from, msg).await.unwrap();
        assert!(more > expected);
        let msg = Forget { inode, count: 1 };
        bt.forget(from, msg).await.unwrap();

        let actual = num_files(block_dir).unwrap();
        assert_eq!(expected, actual);
    }

    #[tokio::test]
    async fn after_unlink_no_empty_directories() {
        const FILENAME: &str = "file";
        let case = LocalFsTest::new_empty().await;
        let bt = &case.fs;
        let from = case.from();

        let msg = Create {
            parent: SpecInodes::RootDir.into(),
            name: FILENAME,
            flags: FlagValue::ReadWrite.into(),
            mode: 0o644,
            umask: 0,
        };
        let CreateReply { inode, handle, .. } = bt.create(from, msg).await.unwrap();
        const DATA: [u8; 8] = [1u8; 8];
        let msg = Write {
            inode,
            handle,
            offset: 0,
            data: DATA.as_slice(),
        };
        bt.write(from, msg).await.unwrap();
        let msg = Close { inode, handle };
        bt.close(from, msg).await.unwrap();
        let msg = Forget { inode, count: 1 };
        bt.forget(from, msg).await.unwrap();
        let msg = Unlink {
            parent: SpecInodes::RootDir.into(),
            name: FILENAME,
        };
        bt.unlink(from, msg).await.unwrap();

        let mut path = case.dir.path().to_owned();
        let entries = read_dir(&path).unwrap();
        path.push("x");
        for entry in entries {
            let entry = entry.unwrap();
            if !entry.file_type().unwrap().is_dir() {
                continue;
            }
            path.pop();
            path.push(entry.file_name());
            let empty = read_dir(&path).unwrap().next().is_none();
            assert!(!empty);
        }
    }
}