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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Definitions of messages passed between filesystem clients and servers.
use super::{Handle, Inode};

use btlib::{
    bterr, crypto::ConcretePub, BlockMetaSecrets, DirEntry, DirEntryKind, Epoch, IssuedProcRec,
};
use bttp::CallMsg;
use core::time::Duration;
use paste::paste;
use serde::{Deserialize, Serialize};
use std::{
    fmt::Display,
    io,
    ops::{BitOr, BitOrAssign},
};

/// Top-level message type for the filesystem protocol.
/// All messages passed from clients to servers are of this type.
#[derive(Serialize, Deserialize)]
pub enum FsMsg<'a> {
    #[serde(borrow)]
    Lookup(Lookup<'a>),
    #[serde(borrow)]
    Create(Create<'a>),
    Open(Open),
    Read(Read),
    #[serde(borrow)]
    Write(Write<&'a [u8]>),
    Flush(Flush),
    ReadDir(ReadDir),
    #[serde(borrow)]
    Link(Link<'a>),
    #[serde(borrow)]
    Unlink(Unlink<'a>),
    ReadMeta(ReadMeta),
    WriteMeta(WriteMeta),
    Allocate(Allocate),
    Close(Close),
    Forget(Forget),
    Lock(Lock),
    Unlock(Unlock),
    AddReadcap(AddReadcap),
    GrantAccess(GrantAccess),
}

/// The type for every reply sent from servers to clients.
#[derive(Serialize, Deserialize)]
pub enum FsReply<'a> {
    /// Indicates a message was received successfully but does not provide any additional data.
    Ack(()),
    Lookup(LookupReply),
    Create(CreateReply),
    Open(OpenReply),
    #[serde(borrow)]
    Read(ReadReply<'a>),
    Write(WriteReply),
    ReadDir(ReadDirReply),
    Link(LinkReply),
    ReadMeta(ReadMetaReply),
    WriteMeta(WriteMetaReply),
}

impl<'a> CallMsg<'a> for FsMsg<'a> {
    type Reply<'b> = FsReply<'b>;
}

#[repr(u64)]
/// An enumeration of special Inodes.
pub enum SpecInodes {
    RootDir = 1,
    Sb = 2,
    FirstFree = 11,
}

impl SpecInodes {
    pub fn value(self) -> Inode {
        self as Inode
    }
}

impl From<SpecInodes> for Inode {
    fn from(special: SpecInodes) -> Self {
        special.value()
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u32)] // This type needs to match `libc::mode_t`.
/// The type of a file (regular, directory, etc).
pub enum FileType {
    /// Directory.
    Dir = libc::S_IFDIR,
    /// Regular file.
    Reg = libc::S_IFREG,
}

impl FileType {
    /// Returns the underlying mode bits for this file type.
    pub fn value(self) -> libc::mode_t {
        self as libc::mode_t
    }

    /// Attempts to convert the given mode bits into a `FileType` enum value.
    pub fn from_value(value: libc::mode_t) -> btlib::Result<Self> {
        if (value & libc::S_IFDIR) != 0 {
            return Ok(FileType::Dir);
        }
        if (value & libc::S_IFREG) != 0 {
            return Ok(FileType::Reg);
        }
        Err(bterr!("unknown file type: 0o{value:0o}"))
    }

    pub fn dir_entry_kind(self) -> DirEntryKind {
        match self {
            Self::Dir => DirEntryKind::Directory,
            Self::Reg => DirEntryKind::File,
        }
    }
}

impl From<FileType> for libc::mode_t {
    fn from(file_type: FileType) -> Self {
        file_type.value()
    }
}

impl TryFrom<libc::mode_t> for FileType {
    type Error = btlib::Error;
    fn try_from(value: libc::mode_t) -> btlib::Result<Self> {
        Self::from_value(value)
    }
}

impl From<FileType> for DirEntryKind {
    fn from(value: FileType) -> Self {
        value.dir_entry_kind()
    }
}

impl BitOr<libc::mode_t> for FileType {
    type Output = libc::mode_t;
    fn bitor(self, rhs: libc::mode_t) -> Self::Output {
        self.value() | rhs
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[repr(i32)]
/// The generators for the group of [Flags].
/// 
/// These are mostly values from libc, save for several custom values. Note that the presence of a
/// flag in this enum does not guarantee it's supported.
/// The standard libc `O_*` value which corresponds to each variant is given in the variant's
/// comment.
/// Consult your libc documentation for an explanation of what these means.
pub enum FlagValue {
    // Standard flags.
    /// `O_RDONLY`
    ReadOnly = libc::O_RDONLY,
    /// `O_WRONLY`
    WriteOnly = libc::O_WRONLY,
    /// `O_RDWR`
    ReadWrite = libc::O_RDWR,
    /// `O_ACCMODE`
    AccMode = libc::O_ACCMODE,
    /// `O_CREAT`
    Create = libc::O_CREAT,
    /// `O_EXCL`
    Exclusive = libc::O_EXCL,
    /// `O_NOCTTY`
    NoCtty = libc::O_NOCTTY,
    /// `O_TRUNC`
    Truncate = libc::O_TRUNC,
    /// `O_APPEND`
    Append = libc::O_APPEND,
    /// `O_NONBLOCK`
    NonBlock = libc::O_NONBLOCK,
    /// `O_DSYNC`
    Dsync = libc::O_DSYNC,
    /// `O_ASYNC`
    Async = libc::O_ASYNC,
    /// `O_DIRECT`
    Direct = libc::O_DIRECT,
    /// `O_DIRECTORY`
    Directory = libc::O_DIRECTORY,
    /// `O_NOFOLLOW`
    NoFollow = libc::O_NOFOLLOW,
    /// `O_NOATIME`
    NoAtime = libc::O_NOATIME,
    /// `O_CLOEXEC`
    CloseExec = libc::O_CLOEXEC,
    /// `O_RSYNC`
    Rsync = libc::O_RSYNC,
    /// `O_PATH`
    Path = libc::O_PATH,
    /// `O_TMPFILE`
    TmpFile = libc::O_TMPFILE,
    // Custom flags.
    /// Indicates that a process block should be created.
    Process = 0x01000000,
    /// Indicates that a server block should be created.
    Server = 0x02000000,
}

impl FlagValue {
    /// Returns the underlying [i32] value.
    pub const fn value(self) -> i32 {
        self as i32
    }
}

impl Copy for FlagValue {}

impl From<FlagValue> for i32 {
    fn from(flag_value: FlagValue) -> Self {
        flag_value.value()
    }
}

impl BitOr for FlagValue {
    type Output = Flags;
    fn bitor(self, rhs: Self) -> Self::Output {
        Flags::new(self.value() | rhs.value())
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
/// A wrapper type around [i32] with convenience methods for checking if `libc::O_*`
/// flags have been set.
pub struct Flags(i32);

impl Copy for Flags {}

impl Flags {
    /// Wraps the given [i32] value.
    pub const fn new(value: i32) -> Self {
        Self(value)
    }

    /// Returns the inner [i32] value.
    pub const fn value(self) -> i32 {
        self.0
    }

    /// Returns true if these flags allow the file to be written to.
    pub const fn writeable(self) -> bool {
        const MASK: i32 = FlagValue::ReadWrite.value() | FlagValue::WriteOnly.value();
        self.0 & MASK != 0
    }

    /// Returns true if these flags allow the file to be read from.
    pub const fn readable(self) -> bool {
        !self.write_only()
    }

    /// Returns true if the file was opened readonly.
    pub const fn read_only(self) -> bool {
        self.0 == FlagValue::ReadOnly.value()
    }

    /// Returns true if the file was opened writeonly
    pub const fn write_only(self) -> bool {
        self.0 & FlagValue::WriteOnly.value() != 0
    }

    /// Returns true if these flags are for a directory.
    pub const fn directory(self) -> bool {
        self.0 & FlagValue::Directory.value() != 0
    }

    /// Returns true if these flags are for a process.
    pub const fn process(self) -> bool {
        self.0 & FlagValue::Process.value() != 0
    }

    /// Returns true if these flags are for a server.
    pub const fn server(self) -> bool {
        self.0 & FlagValue::Server.value() != 0
    }

    /// Asserts that these flags allow a file to be read.
    /// 
    /// If the assertion fails then an [io::Error] with the errno [libc::EACCES] is returned.
    pub fn assert_readable(self) -> Result<(), io::Error> {
        if !self.readable() {
            Err(io::Error::from_raw_os_error(libc::EACCES))
        } else {
            Ok(())
        }
    }

    /// Asserts that these flags allow a file to be written.
    /// 
    /// If the assertion fails then an [io::Error] with the errno [libc::EACCES] is returned.
    pub fn assert_writeable(self) -> Result<(), io::Error> {
        if !self.writeable() {
            Err(io::Error::from_raw_os_error(libc::EACCES))
        } else {
            Ok(())
        }
    }
}

impl From<i32> for Flags {
    fn from(value: i32) -> Self {
        Self::new(value)
    }
}

impl From<Flags> for i32 {
    fn from(flags: Flags) -> Self {
        flags.value()
    }
}

impl From<FlagValue> for Flags {
    fn from(flag_value: FlagValue) -> Self {
        Self::new(flag_value.value())
    }
}

impl BitOr<Flags> for Flags {
    type Output = Flags;
    fn bitor(self, rhs: Flags) -> Self::Output {
        Self::new(self.value() | rhs.value())
    }
}

impl BitOr<FlagValue> for Flags {
    type Output = Flags;
    fn bitor(self, rhs: FlagValue) -> Self::Output {
        Self::new(self.value() | rhs.value())
    }
}

impl Display for Flags {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value().fmt(f)
    }
}

impl Default for Flags {
    fn default() -> Self {
        Self::new(0)
    }
}

/// Attributes of a file.
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Hash, Default)]
pub struct Attrs {
    pub mode: u32,
    pub uid: u32,
    pub gid: u32,
    pub atime: Epoch,
    pub mtime: Epoch,
    pub ctime: Epoch,
    pub tags: Vec<(String, Vec<u8>)>,
}

#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Hash)]
/// A type for indicating which fields in [Attrs] have been set and which should be ignored.
/// 
/// This method was chosen over using [Option] for greater efficiency on the wire.
pub struct AttrsSet(u16);

macro_rules! field {
    ($index:expr, $name:ident) => {
        pub const $name: AttrsSet = AttrsSet::new(1 << $index);

        paste! {
            pub fn [<$name:lower>](self) -> bool {
                const MASK: u16 = 1 << $index;
                self.0 & MASK != 0
            }
        }
    };
}

impl AttrsSet {
    field!(0, MODE);
    field!(1, UID);
    field!(2, GID);
    field!(3, ATIME);
    field!(4, MTIME);
    field!(5, CTIME);

    pub const ALL: Self = Self::new(
        Self::MODE.0 | Self::UID.0 | Self::GID.0 | Self::ATIME.0 | Self::MTIME.0 | Self::CTIME.0,
    );

    pub const fn new(value: u16) -> Self {
        Self(value)
    }

    pub const fn none() -> Self {
        Self(0)
    }

    pub const fn value(self) -> u16 {
        self.0
    }
}

impl Copy for AttrsSet {}

impl From<u16> for AttrsSet {
    fn from(value: u16) -> Self {
        Self::new(value)
    }
}

impl From<AttrsSet> for u16 {
    fn from(attr: AttrsSet) -> Self {
        attr.value()
    }
}

impl BitOr<Self> for AttrsSet {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self::Output {
        AttrsSet::new(self.value() | rhs.value())
    }
}

impl BitOrAssign<Self> for AttrsSet {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0
    }
}

/// A filesystem entry.
/// 
/// This struct includes attributes of a file as well as cache control
/// information for how long it may be cached.
#[derive(Debug, Serialize, Deserialize)]
pub struct Entry {
    pub attr: BlockMetaSecrets,
    pub attr_timeout: Duration,
    pub entry_timeout: Duration,
}

/// A request to lookup a name in a directory.
#[derive(Serialize, Deserialize)]
pub struct Lookup<'a> {
    pub parent: Inode,
    pub name: &'a str,
}

/// A reply containing the [Entry] stored under a name in a directory.
#[derive(Debug, Serialize, Deserialize)]
pub struct LookupReply {
    pub inode: Inode,
    pub generation: u64,
    pub entry: Entry,
}

/// A request to create a file in a directory under a given name.
#[derive(Serialize, Deserialize)]
pub struct Create<'a> {
    pub parent: Inode,
    pub name: &'a str,
    pub flags: Flags,
    pub mode: u32,
    pub umask: u32,
}

/// A reply containing information about a newly created file.
#[derive(Serialize, Deserialize)]
pub struct CreateReply {
    pub inode: Inode,
    pub handle: Handle,
    pub entry: Entry,
}

/// A request to hope a file.
#[derive(Serialize, Deserialize)]
pub struct Open {
    pub inode: Inode,
    pub flags: Flags,
}

/// A reply which contains a handle to an open file.
#[derive(Serialize, Deserialize)]
pub struct OpenReply {
    pub handle: Handle,
}

/// A request to read data at a particular offset from an open file.
#[derive(Serialize, Deserialize)]
pub struct Read {
    pub inode: Inode,
    pub handle: Handle,
    pub offset: u64,
    pub size: u64,
}

/// A reply containing data read from a file.
#[derive(Serialize, Deserialize)]
pub struct ReadReply<'a> {
    pub data: &'a [u8],
}

/// A request to write data to a particular offset in an open file.
#[derive(Serialize, Deserialize)]
pub struct Write<R> {
    pub inode: Inode,
    pub handle: Handle,
    pub offset: u64,
    pub data: R,
}

/// A reply containing the number of bytes written to a file.
#[derive(Serialize, Deserialize)]
pub struct WriteReply {
    pub written: u64,
}

/// A request to flush all data cached for an open file to durable storage.
#[derive(Serialize, Deserialize)]
pub struct Flush {
    pub inode: Inode,
    pub handle: Handle,
}

/// A request to read the contents of a directory.
#[derive(Serialize, Deserialize)]
pub struct ReadDir {
    pub inode: Inode,
    pub handle: Handle,
    /// The maximum number of directory entries to return in a single response. A value of 0
    /// indicates there is no limit. Note that the server may impose it's own limit.
    pub limit: u32,
    /// An opaque value which the server uses to keep track of the client's position in reading
    /// the directory. A value of 0 indicates the directory is to be iterated from the beginning.
    pub state: u64,
}

/// A reply containing the contents of a directory.
#[derive(Serialize, Deserialize)]
pub struct ReadDirReply {
    pub entries: Vec<(String, DirEntry)>,
    /// This is the value to pass in a subsequent [ReadDir] message to continue reading this
    /// directory. A value of 0 indicates that all entries have been returned.
    pub new_state: u64,
}

/// A request to create a new hard link to a file.
#[derive(Serialize, Deserialize)]
pub struct Link<'a> {
    pub inode: Inode,
    pub new_parent: Inode,
    pub name: &'a str,
}

/// A reply containing the [Entry] of the newly created hard link.
#[derive(Serialize, Deserialize)]
pub struct LinkReply {
    pub entry: Entry,
}

/// A request to remove a name referring to an inode.
/// 
/// If the inode becomes orphaned, it is removed from durable storage.
#[derive(Serialize, Deserialize)]
pub struct Unlink<'a> {
    pub parent: Inode,
    pub name: &'a str,
}

/// A request to read a file's metadata.
#[derive(Serialize, Deserialize)]
pub struct ReadMeta {
    pub inode: Inode,
    pub handle: Option<Handle>,
}

/// A reply containing the metadata of a file.
#[derive(Serialize, Deserialize)]
pub struct ReadMetaReply {
    pub attrs: BlockMetaSecrets,
    pub valid_for: Duration,
}

/// A request to write the metadata of a file.
#[derive(Serialize, Deserialize)]
pub struct WriteMeta {
    pub inode: Inode,
    pub handle: Option<Handle>,
    pub attrs: Attrs,
    /// The bits in this value indicate which fields in `attrs` have been initialized.
    pub attrs_set: AttrsSet,
}

/// A reply containing the newly written file metadata.
#[derive(Serialize, Deserialize)]
pub struct WriteMetaReply {
    pub attrs: BlockMetaSecrets,
    pub valid_for: Duration,
}

/// A request to pre-allocate a given amount of space from durable storage for a file.
#[derive(Serialize, Deserialize)]
pub struct Allocate {
    pub inode: Inode,
    pub handle: Handle,
    pub offset: Option<u64>,
    pub size: u64,
}

/// A request to close an open file.
#[derive(Serialize, Deserialize)]
pub struct Close {
    pub inode: Inode,
    pub handle: Handle,
}

/// A request to forget about an inode which was previously referenced.
/// 
/// This message must be sent
/// so the server knows when it can free resources associated with the inode.
/// If `N` [Entry] structs are sent in a reply to [Lookup] messages, then the caller must send one
/// or more [Forget] messages such that their `count` fields add up to `N`.
#[derive(Serialize, Deserialize)]
pub struct Forget {
    pub inode: Inode,
    pub count: u64,
}

/// The description of a region in a file to lock.
#[derive(Serialize, Deserialize)]
pub struct LockDesc {
    pub offset: u64,
    pub size: u64,
    pub exclusive: bool,
}

/// A request to lock a region of a file.
#[derive(Serialize, Deserialize)]
pub struct Lock {
    pub inode: Inode,
    pub handle: Handle,
    pub desc: LockDesc,
}

/// A request to unlock a region of a file.
#[derive(Serialize, Deserialize)]
pub struct Unlock {
    pub inode: Inode,
    pub handle: Handle,
}

/// A request to add a [btlib::Readcap] to a file.
#[derive(Serialize, Deserialize)]
pub struct AddReadcap {
    pub inode: Inode,
    pub handle: Handle,
    pub pub_creds: ConcretePub,
}

/// A request to give a process access to an inode.
#[derive(Serialize, Deserialize)]
pub struct GrantAccess {
    pub inode: Inode,
    pub record: IssuedProcRec,
}