liteboxfs 0.2.0

A modern POSIX filesystem in a SQLite database
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
use std::collections::HashMap;
use std::ffi::{OsStr, OsString};
use std::fmt::{self, Debug, Display};
use std::iter::FusedIterator;
use std::path::PathBuf;
use std::time::SystemTime;

use bitflags::bitflags;

#[cfg(all(feature = "fs", target_family = "unix"))]
use nix::unistd;

use crate::sql::FileDiscriminant;
use crate::util::system_time_from_nanos;

/// The name of the extended attribute (xattr) used to store the "access" ACL.
pub const ACCESS_ACL_XATTR_NAME: &str = "system.posix_acl_access";

/// The name of the extended attribute (xattr) used to store the "default" ACL.
pub const DEFAULT_ACL_XATTR_NAME: &str = "system.posix_acl_default";

/// An identifier for a block or character device.
///
/// A device is identified by its "major" and "minor" device numbers.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Device {
    major: u64,
    minor: u64,
}

impl Device {
    /// Create a new [`Device`] from its "major" and "minor" device numbers.
    pub const fn new(major: u64, minor: u64) -> Self {
        Self { major, minor }
    }

    /// The "major" device number.
    pub const fn major(&self) -> u64 {
        self.major
    }

    /// The "minor" device number.
    pub const fn minor(&self) -> u64 {
        self.minor
    }
}

/// A kind of regular file, directory, or special file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileKind {
    /// Regular file (`S_IFREG`).
    Regular,

    /// Directory (`S_IFDIR`).
    Dir,

    /// Symbolic link (`S_IFLNK`).
    Symlink {
        /// The path the symlink points to.
        target: PathBuf,
    },

    /// Block device (`S_IFBLK`).
    Block {
        /// The device identifier.
        dev: Device,
    },

    /// Character device (`S_IFCHR`).
    Char {
        /// The device identifier.
        dev: Device,
    },

    /// Named pipe (`S_IFIFO`).
    Pipe,
}

/// A user ID.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Uid {
    uid: u32,
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl Display for Uid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.uid)
    }
}

impl Uid {
    /// The root user.
    pub const ROOT: Self = Self { uid: 0 };

    /// The ID of the current user.
    #[cfg(all(feature = "fs", target_family = "unix"))]
    pub fn current() -> Self {
        Self {
            uid: unistd::getuid().as_raw(),
        }
    }

    /// Creates a [`Uid`] from a raw `u32`.
    pub const fn from_raw(uid: u32) -> Self {
        Self { uid }
    }

    /// Convert to a raw `u32`.
    pub const fn as_raw(self) -> u32 {
        self.uid
    }
}

impl From<u32> for Uid {
    fn from(uid: u32) -> Self {
        Self::from_raw(uid)
    }
}

impl From<Uid> for u32 {
    fn from(uid: Uid) -> Self {
        uid.as_raw()
    }
}

/// A group ID.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Gid {
    gid: u32,
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl Display for Gid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.gid)
    }
}

impl Gid {
    /// The group of the root user.
    pub const ROOT: Self = Self { gid: 0 };

    /// The ID of the current group.
    #[cfg(all(feature = "fs", target_family = "unix"))]
    pub fn current() -> Self {
        Self {
            gid: unistd::getgid().as_raw(),
        }
    }

    /// Creates a [`Gid`] from a raw `u32`.
    pub const fn from_raw(gid: u32) -> Self {
        Self { gid }
    }

    /// Convert to a raw `u32`.
    pub const fn as_raw(self) -> u32 {
        self.gid
    }
}

impl From<u32> for Gid {
    fn from(gid: u32) -> Self {
        Self::from_raw(gid)
    }
}

impl From<Gid> for u32 {
    fn from(gid: Gid) -> Self {
        gid.as_raw()
    }
}

/// The user and group that own a file.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Owner {
    /// The user that owns the file.
    pub user: Uid,

    /// The group that owns the file.
    pub group: Gid,
}

impl Owner {
    /// The root user and group.
    pub const ROOT: Self = Self {
        user: Uid::ROOT,
        group: Gid::ROOT,
    };

    /// The current user and group.
    #[cfg(all(feature = "fs", target_family = "unix"))]
    pub fn current() -> Self {
        Self {
            user: Uid::current(),
            group: Gid::current(),
        }
    }
}

bitflags! {
    /// A file mode.
    #[derive(Clone, Copy, PartialEq, Eq, Hash)]
    pub struct FileMode: u32 {
        /// Read for owner (`S_IRUSR`).
        const OWNER_R = 0o400;

        /// Write for owner (`S_IWUSR`).
        const OWNER_W = 0o200;

        /// Execute for owner (`S_IXUSR`).
        const OWNER_X = 0o100;

        /// Read, write, and execute for owner (`S_IRWXU`).
        const OWNER_RWX = 0o700;

        /// Read for group (`S_IRGRP`).
        const GROUP_R = 0o040;

        /// Write for group (`S_IWGRP`).
        const GROUP_W = 0o020;

        /// Execute for group (`S_IXGRP`).
        const GROUP_X = 0o010;

        /// Read, write, and execute for group (`S_IRWXG`).
        const GROUP_RWX = 0o070;

        /// Read for others (`S_IROTH`).
        const OTHER_R = 0o004;

        /// Write for others (`S_IWOTH`).
        const OTHER_W = 0o002;

        /// Execute for others (`S_IXOTH`).
        const OTHER_X = 0o001;

        /// Read, write, and execute for others (`S_IRWXO`).
        const OTHER_RWX = 0o007;

        /// Set user ID on execution (`S_ISUID`).
        const SUID = 0o4000;

        /// Set group ID on execution (`S_ISGID`).
        const SGID = 0o2000;

        /// The sticky bit (`S_ISVTX`).
        const STICKY = 0o1000;
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
impl Debug for FileMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut output = String::with_capacity(9);

        if self.contains(FileMode::OWNER_R) {
            output.push('r');
        } else {
            output.push('-');
        }

        if self.contains(FileMode::OWNER_W) {
            output.push('w');
        } else {
            output.push('-');
        }

        if self.contains(FileMode::OWNER_X) {
            output.push('x');
        } else {
            output.push('-');
        }

        if self.contains(FileMode::GROUP_R) {
            output.push('r');
        } else {
            output.push('-');
        }

        if self.contains(FileMode::GROUP_W) {
            output.push('w');
        } else {
            output.push('-');
        }

        if self.contains(FileMode::GROUP_X) {
            output.push('x');
        } else {
            output.push('-');
        }

        if self.contains(FileMode::OTHER_R) {
            output.push('r');
        } else {
            output.push('-');
        }

        if self.contains(FileMode::OTHER_W) {
            output.push('w');
        } else {
            output.push('-');
        }

        if self.contains(FileMode::OTHER_X) {
            output.push('x');
        } else {
            output.push('-');
        }

        write!(f, "{}", output)
    }
}

bitflags! {
    /// The permission mode for an access control list.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct AclMode: u16 {
        /// Read permissions.
        const R = 0o4;

        /// Write permissions.
        const W = 0o2;

        /// Execute permissions.
        const X = 0o1;

        /// Read, write, and execute permissions.
        const RWX = Self::R.bits() | Self::W.bits() | Self::X.bits();
    }
}

/// A qualifier which determines who is granted a set of permissions in an ACL.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AclQualifier {
    /// The user with a given UID (`ACL_USER`).
    User(Uid),

    /// The group with a given GID (`ACL_USER`).
    Group(Gid),

    /// The user that owns the file (`ACL_USER_OBJ`).
    OwningUser,

    /// The group that owns the file (`ACL_GROUP_OBJ`).
    OwningGroup,

    /// Everyone else (`ACL_OTHER`).
    Other,

    /// The ACL mask (`ACL_MASK`).
    Mask,
}

/// A borrowing iterator over the permissions in an [`Acl`].
#[derive(Debug)]
pub struct AclIter<'a> {
    inner: std::collections::hash_map::Iter<'a, AclQualifier, AclMode>,
}

impl<'a> Iterator for AclIter<'a> {
    type Item = (&'a AclQualifier, &'a AclMode);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl<'a> FusedIterator for AclIter<'a> {}

impl<'a> ExactSizeIterator for AclIter<'a> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

/// An owned iterator over the permissions in an [`Acl`].
#[derive(Debug)]
pub struct AclIntoIter {
    inner: std::collections::hash_map::IntoIter<AclQualifier, AclMode>,
}

impl Iterator for AclIntoIter {
    type Item = (AclQualifier, AclMode);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl FusedIterator for AclIntoIter {}

impl ExactSizeIterator for AclIntoIter {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

/// An access control list for a file.
///
/// This maps qualifiers to their associated permissions.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Acl {
    acl: HashMap<AclQualifier, AclMode>,
}

impl Acl {
    /// Create a new empty ACL.
    pub fn new() -> Self {
        Self {
            acl: HashMap::new(),
        }
    }

    /// Get an ACL permission.
    pub fn get(&self, qualifier: AclQualifier) -> Option<AclMode> {
        self.acl.get(&qualifier).copied()
    }

    /// Get a mutable reference to an ACL permission.
    pub fn get_mut(&mut self, qualifier: AclQualifier) -> Option<&mut AclMode> {
        self.acl.get_mut(&qualifier)
    }

    /// Set an ACL permission.
    pub fn set(&mut self, qualifier: AclQualifier, mode: AclMode) {
        self.acl.insert(qualifier, mode);
    }

    /// Remove an ACL permission.
    pub fn remove(&mut self, qualifier: AclQualifier) {
        self.acl.remove(&qualifier);
    }

    /// Clear all ACL permissions.
    pub fn clear(&mut self) {
        self.acl.clear();
    }

    /// An iterator over the ACL permissions in arbitrary order.
    pub fn iter(&self) -> AclIter<'_> {
        AclIter {
            inner: self.acl.iter(),
        }
    }
}

impl FromIterator<(AclQualifier, AclMode)> for Acl {
    fn from_iter<T: IntoIterator<Item = (AclQualifier, AclMode)>>(iter: T) -> Self {
        Self {
            acl: HashMap::from_iter(iter),
        }
    }
}

impl IntoIterator for Acl {
    type Item = (AclQualifier, AclMode);
    type IntoIter = AclIntoIter;

    fn into_iter(self) -> Self::IntoIter {
        AclIntoIter {
            inner: self.acl.into_iter(),
        }
    }
}

impl<'a> IntoIterator for &'a Acl {
    type Item = (&'a AclQualifier, &'a AclMode);
    type IntoIter = AclIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// A borrowing iterator over an [`Xattrs`].
#[derive(Debug)]
pub struct XattrsIter<'a> {
    inner: std::collections::hash_map::Iter<'a, OsString, Vec<u8>>,
}

impl<'a> Iterator for XattrsIter<'a> {
    type Item = (&'a OsStr, &'a [u8]);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner
            .next()
            .map(|(k, v)| (k.as_os_str(), v.as_slice()))
    }
}

impl<'a> FusedIterator for XattrsIter<'a> {}

impl<'a> ExactSizeIterator for XattrsIter<'a> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

/// An owned iterator over an [`Xattrs`].
#[derive(Debug)]
pub struct XattrsIntoIter {
    inner: std::collections::hash_map::IntoIter<OsString, Vec<u8>>,
}

impl Iterator for XattrsIntoIter {
    type Item = (OsString, Vec<u8>);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl FusedIterator for XattrsIntoIter {}

impl ExactSizeIterator for XattrsIntoIter {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

/// Extended attributes for a file.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Xattrs {
    xattrs: HashMap<OsString, Vec<u8>>,
}

impl Xattrs {
    /// Create a new empty set of extended attributes.
    pub fn new() -> Self {
        Self {
            xattrs: HashMap::new(),
        }
    }

    /// Get an attribute by name.
    pub fn get<S: AsRef<OsStr> + ?Sized>(&self, name: &S) -> Option<&[u8]> {
        self.xattrs.get(name.as_ref()).map(|v| v.as_slice())
    }

    /// Get a mutable reference to an attribute by name.
    pub fn get_mut<S: AsRef<OsStr> + ?Sized>(&mut self, name: &S) -> Option<&mut Vec<u8>> {
        self.xattrs.get_mut(name.as_ref())
    }

    /// Set the value of an attribute.
    pub fn set(&mut self, name: OsString, value: Vec<u8>) {
        self.xattrs.insert(name, value);
    }

    /// Remove an attribute.
    pub fn remove<S: AsRef<OsStr> + ?Sized>(&mut self, name: &S) {
        self.xattrs.remove(name.as_ref());
    }

    /// Clear all attributes.
    pub fn clear(&mut self) {
        self.xattrs.clear();
    }

    /// An iterator over the extended attributes in arbitrary order.
    pub fn iter(&self) -> XattrsIter<'_> {
        XattrsIter {
            inner: self.xattrs.iter(),
        }
    }
}

impl FromIterator<(OsString, Vec<u8>)> for Xattrs {
    fn from_iter<T: IntoIterator<Item = (OsString, Vec<u8>)>>(iter: T) -> Self {
        Self {
            xattrs: HashMap::from_iter(iter),
        }
    }
}

impl IntoIterator for Xattrs {
    type Item = (OsString, Vec<u8>);
    type IntoIter = XattrsIntoIter;

    fn into_iter(self) -> Self::IntoIter {
        XattrsIntoIter {
            inner: self.xattrs.into_iter(),
        }
    }
}

impl<'a> IntoIterator for &'a Xattrs {
    type Item = (&'a OsStr, &'a [u8]);
    type IntoIter = XattrsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RawMetadata {
    pub discriminant: FileDiscriminant,
    pub mode: FileMode,
    pub uid: Uid,
    pub gid: Gid,
    pub atime: i128,
    pub mtime: i128,
    pub ctime: i128,
    pub btime: Option<i128>,
}

/// Metadata for a file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileMetadata {
    mode: FileMode,
    uid: Uid,
    gid: Gid,
    atime: SystemTime,
    mtime: SystemTime,
    ctime: SystemTime,
    btime: Option<SystemTime>,
}

impl FileMetadata {
    pub(crate) fn for_new_file(
        discriminant: FileDiscriminant,
        umask: FileMode,
        owner: Owner,
    ) -> Self {
        let now = SystemTime::now();

        let default_mode = match discriminant {
            FileDiscriminant::Dir => {
                FileMode::OWNER_RWX | FileMode::GROUP_RWX | FileMode::OTHER_RWX
            }
            _ => {
                FileMode::OWNER_R
                    | FileMode::OWNER_W
                    | FileMode::GROUP_R
                    | FileMode::GROUP_W
                    | FileMode::OTHER_R
                    | FileMode::OTHER_W
            }
        };

        Self {
            mode: default_mode & !umask,
            uid: owner.user,
            gid: owner.group,
            atime: now,
            mtime: now,
            ctime: now,
            btime: Some(now),
        }
    }

    pub(crate) fn from_raw(raw: RawMetadata) -> Self {
        Self {
            mode: raw.mode,
            uid: raw.uid,
            gid: raw.gid,
            atime: system_time_from_nanos(raw.atime),
            mtime: system_time_from_nanos(raw.mtime),
            ctime: system_time_from_nanos(raw.ctime),
            btime: raw.btime.map(system_time_from_nanos),
        }
    }

    /// File mode (`st_mode`).
    pub fn mode(&self) -> FileMode {
        self.mode
    }

    /// Owning user of the file (`st_uid`).
    pub fn user(&self) -> Uid {
        self.uid
    }

    /// Owning group of the file (`st_gid`).
    pub fn group(&self) -> Gid {
        self.gid
    }

    /// Time the file was last accessed (`st_atime`).
    pub fn accessed(&self) -> SystemTime {
        self.atime
    }

    /// Time the file's contents were last changed (`st_mtime`).
    pub fn modified(&self) -> SystemTime {
        self.mtime
    }

    /// Time the file's metadata was last changed (`st_ctime`).
    pub fn changed(&self) -> SystemTime {
        self.ctime
    }

    /// Time the file was originally created (`stx_btime`).
    ///
    /// This may not be supported on all host filesystems.
    pub fn created(&self) -> Option<SystemTime> {
        self.btime
    }
}