oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
//! What only Linux has: mounting filesystems, and changing the root
//! directory. With the namespaces of
//! [`process::linux`](crate::process::linux), this is what the root of a
//! container is built from.
//!
//! # Mounts
//!
//! A mount attaches a filesystem, or a directory tree that is already
//! attached somewhere, to a directory: the *mount point*. The functions
//! here are the uses of the one `mount` system call:
//!
//! - [`mount`] attaches a filesystem by the name of its type: `proc`,
//!   `sysfs`, `tmpfs`, `devpts`, `cgroup2`, or one that is on a device
//!   (`ext4`...).
//! - [`bind`] attaches a tree that is already visible at another place.
//! - [`remount`] changes the flags and options of a mounted filesystem,
//!   [`remount_bind`] those of one mount point: read-only, for one.
//! - [`set_propagation`] says whether what is mounted under a mount point
//!   later shows in its copies in other namespaces, and the reverse.
//! - [`move_mount`] moves a mount point.
//!
//! [`unmount`] detaches, [`pivot_root`] and [`chroot`] change what `/` is.
//!
//! # Mounts as handles
//!
//! Linux 5.2 has a second set of calls, which do the same in steps, on
//! handles instead of paths, and a few things the first set cannot:
//!
//! - [`fsopen`] starts the configuration of a filesystem of a type,
//!   [`fsconfig`] gives it its options one at a time and then creates it,
//!   and [`fsmount`] makes a mount of it that is attached nowhere yet.
//!   Each option is refused or accepted by itself, and the handle can be
//!   read for what the filesystem had to say about one it refused.
//! - [`open_tree`] opens a mount point as a handle, or, with
//!   [`OpenTreeFlags::CLONE`], makes a detached copy of the tree there:
//!   what [`bind`] does, without attaching it.
//! - [`move_mount_at`] attaches a detached mount to a directory, or moves
//!   an attached one.
//! - [`mount_setattr`] (Linux 5.12) changes the settings of a mount point,
//!   and of every mount point under it in one call that changes all or
//!   none: a tree made read-only *recursively*, which [`remount_bind`]
//!   cannot do. It also gives a detached mount a map of identifiers
//!   ([`MountSetAttr::id_map`]): the files of the tree then show, through
//!   that mount alone, as owned by other users.
//! - [`fspick`] opens the filesystem mounted somewhere for
//!   reconfiguration: what [`remount`] does, one option at a time.
//!
//! A detached mount is a handle like another: the files under it are
//! reached with the functions of [`fs`](crate::fs) that take a directory
//! handle ([`open_at`](crate::fs::open_at)...), before it shows anywhere,
//! and it goes away with its last handle if it was never attached.
//!
//! These calls need the same capability as the others. An emulator may
//! lack them, or some of them
//! ([`Unsupported`](crate::ErrorKind::Unsupported): measured with
//! qemu-user, of which one version opens a tree and configures nothing),
//! as does a kernel older than the call.
//!
//! All of it needs `CAP_SYS_ADMIN` in the user namespace that owns the
//! mount namespace of the caller ([`chroot`]: `CAP_SYS_CHROOT`). A process
//! has that without being root of the system once it is root of a user
//! namespace and in a mount namespace created there
//! ([`Namespaces::USER`](crate::process::linux::Namespaces::USER) with
//! [`MOUNT`](crate::process::linux::Namespaces::MOUNT)); the kernel then
//! lets it bind, and mount the few types that are safe for that (`tmpfs`,
//! `proc`, `sysfs`, `devpts`, `cgroup2`...), and keeps it from removing
//! the restrictions (read-only, no set-user-ID...) of the mounts it
//! inherited. Without the capability everything fails with
//! [`PermissionDenied`](crate::ErrorKind::PermissionDenied), as it does
//! under the default system call filter of a container runtime.
//!
//! **The mount namespace is shared by default.** What a process mounts
//! shows for every process of its mount namespace: the whole system, for
//! one that has not left the initial namespace. A program that builds a
//! root for something does it in a mount namespace of its own.
//!
//! # A root for a child
//!
//! oscall has no option of [`Command`](crate::process::Command) for this:
//! a root is built by a sequence of calls, which depends on what is being
//! built and can fail half-way, and the child of a `spawn` can only make a
//! fixed list of system calls before it runs its program. The pattern is a
//! program that sets itself up, then runs what it contains: spawn a helper
//! in new namespaces
//! ([`CommandExt::namespaces`](crate::process::linux::CommandExt::namespaces)),
//! which does, in order:
//!
//! 1. `set_propagation("/", Propagation::Private, true)`: nothing done
//!    from here on reaches the namespace it came from. (A new mount
//!    namespace is a copy, and on most systems its mount points still
//!    propagate to their origin.)
//! 2. `bind(root, root, true)`: the new root must be a mount point.
//! 3. [`mount`] and [`bind`] what the root needs, under it: `proc` (in a
//!    new process namespace, for the processes it shows to be those of
//!    the namespace), `tmpfs` on `/tmp` and `/dev`, the devices...
//! 4. [`set_current_dir`](crate::fs::set_current_dir) to the new root,
//!    `pivot_root(".", ".")`, `unmount(".", UnmountFlags::DETACH)` for
//!    the old root, and `set_current_dir("/")`. What the old root held
//!    can no longer be reached, which [`chroot`] alone does not promise.
//! 5. Drop what is no longer needed
//!    ([`process::linux`](crate::process::linux): capabilities, a system
//!    call filter), and run the program.
//!
//! # What is mounted
//!
//! Linux 6.8 answers that without a file to read: [`mounts`] and
//! [`listmount`] list the mounts of the mount namespace of the caller by
//! their identifiers, [`statmount`] says of one what a line of
//! `/proc/self/mountinfo` says, and [`mount_id`] is the identifier of the
//! mount a path is on. They need no privilege for what the caller can
//! reach. On an older kernel they fail with
//! [`Unsupported`](crate::ErrorKind::Unsupported), and the file is what
//! there is: [`fs`](crate::fs) reads it.
//!
//! # Not covered
//!
//! The mounts of another mount namespace (`statmount` and `listmount`
//! take the identifier of one since Linux 6.11, or a handle of one), and
//! being told when what is mounted changes (`fanotify`):
//! [`raw::linux`](crate::raw::linux) makes those calls.

mod list;

pub use list::*;

use crate::{AsHandle, AsPath, BorrowedHandle, OwnedHandle, Result, sys};

crate::macros::flags! {
    /// How a filesystem is mounted, or what a mount point allows: the
    /// `MS_*` flags that are settings.
    pub struct MountFlags: u32 {
        /// Nothing may be written (`MS_RDONLY`).
        const READ_ONLY = 1;
        /// Set-user-ID and set-group-ID bits and file capabilities are
        /// ignored when a program is run from it (`MS_NOSUID`).
        const NO_SUID = 1 << 1;
        /// Device files are not devices there (`MS_NODEV`).
        const NO_DEV = 1 << 2;
        /// No program may be run from it (`MS_NOEXEC`).
        const NO_EXEC = 1 << 3;
        /// Every write is synchronous, as if each file were opened so
        /// (`MS_SYNCHRONOUS`).
        const SYNCHRONOUS = 1 << 4;
        /// Changes to directories are synchronous (`MS_DIRSYNC`).
        const DIR_SYNC = 1 << 5;
        /// Symbolic links are not followed (`MS_NOSYMFOLLOW`, Linux 5.10).
        const NO_SYMLINK_FOLLOW = 1 << 6;
        /// Reading a file does not update its access time (`MS_NOATIME`).
        const NO_ATIME = 1 << 7;
        /// Reading a directory does not update its access time
        /// (`MS_NODIRATIME`).
        const NO_DIR_ATIME = 1 << 8;
        /// The access time is updated when it is older than the
        /// modification time, or than a day (`MS_RELATIME`): what the
        /// kernel does when nothing is said.
        const REL_ATIME = 1 << 9;
        /// The access time is updated at every access (`MS_STRICTATIME`).
        const STRICT_ATIME = 1 << 10;
        /// Times are only kept in memory until something else of the file
        /// is written (`MS_LAZYTIME`).
        const LAZY_TIME = 1 << 11;
        /// The kernel logs less of what goes wrong with the mount
        /// (`MS_SILENT`).
        const SILENT = 1 << 12;
    }
}

crate::macros::flags! {
    /// How to unmount: the flags of `umount2`.
    pub struct UnmountFlags: u32 {
        /// Abandons the requests in progress, for the filesystems that can
        /// (network ones): `MNT_FORCE`. Data may be lost.
        const FORCE = 1;
        /// Detaches the mount point at once, for no new access, and
        /// unmounts when the last use of it ends: `MNT_DETACH`. This is
        /// how a busy tree, the old root after [`pivot_root`] among them,
        /// is let go.
        const DETACH = 1 << 1;
        /// Marks the mount point as expired if it is not in use, and
        /// unmounts it if it was marked already and was not used since:
        /// `MNT_EXPIRE`. The first call fails with
        /// [`WouldBlock`](crate::ErrorKind::WouldBlock) (`EAGAIN`). Not
        /// with `FORCE` or `DETACH`.
        const EXPIRE = 1 << 2;
        /// Fails if the target is a symbolic link, instead of following
        /// it: `UMOUNT_NOFOLLOW`.
        const NO_FOLLOW = 1 << 3;
    }
}

/// How mount and unmount events travel between a mount point and its
/// copies (its *peers*, in the same namespace or in others): what
/// [`set_propagation`] sets.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Propagation {
    /// Nothing is received and nothing is sent (`MS_PRIVATE`).
    Private,
    /// What happens in the peers it was copied from is received; nothing
    /// is sent back (`MS_SLAVE`).
    Slave,
    /// Events go both ways within the peer group (`MS_SHARED`).
    Shared,
    /// Private, and it cannot be the source of a bind mount
    /// (`MS_UNBINDABLE`).
    Unbindable,
}

/// Mounts a filesystem of the type `fstype` on the directory `target`:
/// `mount`.
///
/// `source` is what the type makes of it: a block device for the
/// filesystems that live on one, and a name of no consequence, which
/// shows in `/proc/self/mounts`, for those that do not (`proc`, `tmpfs`,
/// `sysfs`, `devpts`...). `data` is the type's own options, as text
/// separated by commas (`"size=16m,mode=755"` for `tmpfs`,
/// `"newinstance,ptmxmode=0666"` for `devpts`), or empty. An empty
/// `source` or `data` is not passed at all (a null pointer).
///
/// The types the running kernel knows are listed in `/proc/filesystems`.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without the
/// capability (see the [module documentation](self#mounts)), and for a
/// type that may not be mounted from a user namespace; `ENODEV` for a type
/// the kernel does not have; [`InvalidInput`](crate::ErrorKind::InvalidInput)
/// for an empty type, and for options the type refuses;
/// [`NotFound`](crate::ErrorKind::NotFound) or
/// [`NotADirectory`](crate::ErrorKind::NotADirectory) for the target.
pub fn mount<S, T>(
    source: &S,
    target: &T,
    fstype: &str,
    flags: MountFlags,
    data: &str,
) -> Result<()>
where
    S: AsPath + ?Sized,
    T: AsPath + ?Sized,
{
    sys::fs::mount::mount(
        source.as_path_bytes(),
        target.as_path_bytes(),
        fstype.as_bytes(),
        flags,
        data.as_bytes(),
    )
}

/// Makes the tree at `source` visible at `target` as well: a bind mount
/// (`MS_BIND`). Both are directories, or both are files.
///
/// Only the mount `source` is in is bound; with `recursive`, so is every
/// mount point under it (`MS_REC`). The new mount point has the flags of
/// the one it copies: [`remount_bind`] changes them, which is how a bind
/// mount is made read-only. Binding a directory to itself turns it into a
/// mount point, which [`pivot_root`] wants of the new root.
pub fn bind<S, T>(source: &S, target: &T, recursive: bool) -> Result<()>
where
    S: AsPath + ?Sized,
    T: AsPath + ?Sized,
{
    sys::fs::mount::bind(source.as_path_bytes(), target.as_path_bytes(), recursive)
}

/// Changes the flags and the options of the filesystem mounted at
/// `target`, for every place it is mounted at: `MS_REMOUNT`.
///
/// `flags` and `data` replace those the filesystem was mounted with: give
/// the ones to keep along with the ones to change.
pub fn remount<T: AsPath + ?Sized>(target: &T, flags: MountFlags, data: &str) -> Result<()> {
    sys::fs::mount::remount(target.as_path_bytes(), flags, data.as_bytes())
}

/// Changes the flags of the mount point `target` alone, leaving the
/// filesystem and its other mount points as they are:
/// `MS_REMOUNT | MS_BIND`. With [`MountFlags::READ_ONLY`], a tree that can
/// be read through this mount point and still be written through another.
///
/// `flags` replaces the flags of the mount point. In a user namespace, the
/// restrictions a mount point came with (`READ_ONLY`, `NO_SUID`, `NO_DEV`,
/// `NO_EXEC`, the access time setting) cannot be removed: leaving one out
/// fails with [`PermissionDenied`](crate::ErrorKind::PermissionDenied).
///
/// It applies to one mount point: those under it are not changed
/// ([`mount_setattr`] is the recursive form).
pub fn remount_bind<T: AsPath + ?Sized>(target: &T, flags: MountFlags) -> Result<()> {
    sys::fs::mount::remount_bind(target.as_path_bytes(), flags)
}

/// Sets how mount events propagate to and from the mount point `target`,
/// and with `recursive` every mount point under it: `MS_PRIVATE`,
/// `MS_SLAVE`, `MS_SHARED` or `MS_UNBINDABLE`, with `MS_REC`.
///
/// `set_propagation("/", Propagation::Private, true)` is the first thing
/// to do in a new mount namespace that is to be changed without the
/// changes showing outside of it: see the
/// [module documentation](self#a-root-for-a-child).
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if `target` is not a
/// mount point.
pub fn set_propagation<T: AsPath + ?Sized>(
    target: &T,
    propagation: Propagation,
    recursive: bool,
) -> Result<()> {
    sys::fs::mount::set_propagation(target.as_path_bytes(), propagation, recursive)
}

/// Moves the mount point `from`, with what is mounted under it, to the
/// directory `to`: `mount` with `MS_MOVE`.
///
/// [`move_mount_at`] is the system call of that name, which also attaches
/// a mount that is attached nowhere; this one is in every kernel and
/// under every emulator.
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if `from` is not a
/// mount point, or is under a mount point that is shared
/// ([`Propagation::Shared`]).
pub fn move_mount<S, T>(from: &S, to: &T) -> Result<()>
where
    S: AsPath + ?Sized,
    T: AsPath + ?Sized,
{
    sys::fs::mount::move_mount(from.as_path_bytes(), to.as_path_bytes())
}

crate::macros::flags! {
    /// What a mount point allows, as the calls on handles say it: the
    /// `MOUNT_ATTR_*` flags of [`fsmount`] and [`mount_setattr`]. They are
    /// the settings of a mount point among [`MountFlags`], without those
    /// that belong to the filesystem.
    pub struct MountAttributes: u32 {
        /// Nothing may be written through it (`MOUNT_ATTR_RDONLY`).
        const READ_ONLY = 1;
        /// Set-user-ID and set-group-ID bits and file capabilities are
        /// ignored when a program is run from it (`MOUNT_ATTR_NOSUID`).
        const NO_SUID = 1 << 1;
        /// Device files are not devices there (`MOUNT_ATTR_NODEV`).
        const NO_DEV = 1 << 2;
        /// No program may be run from it (`MOUNT_ATTR_NOEXEC`).
        const NO_EXEC = 1 << 3;
        /// Reading a file does not update its access time
        /// (`MOUNT_ATTR_NOATIME`).
        const NO_ATIME = 1 << 4;
        /// The access time is updated at every access
        /// (`MOUNT_ATTR_STRICTATIME`).
        const STRICT_ATIME = 1 << 5;
        /// The access time is updated when it is older than the
        /// modification time, or than a day (`MOUNT_ATTR_RELATIME`): what
        /// a mount point does when neither of the two above is said.
        /// The three are one setting; give one of them at most.
        const REL_ATIME = 1 << 6;
        /// Reading a directory does not update its access time
        /// (`MOUNT_ATTR_NODIRATIME`).
        const NO_DIR_ATIME = 1 << 7;
        /// Symbolic links are not followed (`MOUNT_ATTR_NOSYMFOLLOW`,
        /// Linux 5.14 for these calls).
        const NO_SYMLINK_FOLLOW = 1 << 8;
    }
}

/// One step of the configuration of a filesystem: what [`fsconfig`] does.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum FsConfig<'a> {
    /// Sets the option of this name, which has no value: `ro`,
    /// `noswap`... (`FSCONFIG_SET_FLAG`).
    SetFlag(&'a str),
    /// Sets the option named first to the text given second: `size` to
    /// `16m`, `source` to the device or the name the filesystem is
    /// mounted from (`FSCONFIG_SET_STRING`).
    SetString(&'a str, &'a str),
    /// Sets the option named first to bytes that are no text
    /// (`FSCONFIG_SET_BINARY`).
    SetBinary(&'a str, &'a [u8]),
    /// Sets the option named first to an open file
    /// (`FSCONFIG_SET_FD`): for the filesystems that take one, as
    /// `fuse` does of its device.
    SetHandle(&'a str, BorrowedHandle<'a>),
    /// Creates the filesystem from what was set, or finds the one that
    /// exists already for the same source (`FSCONFIG_CMD_CREATE`). After
    /// it, [`fsmount`].
    Create,
    /// Applies what was set to the filesystem [`fspick`] opened
    /// (`FSCONFIG_CMD_RECONFIGURE`).
    Reconfigure,
    /// Sets the option named first to the file a path names
    /// (`FSCONFIG_SET_PATH`): the path, last, is looked up by the kernel,
    /// relative to the directory handle or to the current directory
    /// without one, for the filesystems whose option is a file or a
    /// device rather than its name. Few have one: a filesystem that does
    /// not refuses with [`InvalidInput`](crate::ErrorKind::InvalidInput),
    /// `source` included, which is text
    /// ([`SetString`](Self::SetString)).
    SetPath(&'a str, Option<BorrowedHandle<'a>>, &'a [u8]),
    /// Sets the option named first to the file a handle is open on, as a
    /// path would name it (`FSCONFIG_SET_PATH_EMPTY`): what
    /// [`SetPath`](Self::SetPath) does with an empty path and the handle
    /// for directory.
    SetPathEmpty(&'a str, BorrowedHandle<'a>),
    /// Creates the filesystem as [`Create`](Self::Create) does, and fails
    /// with [`ResourceBusy`](crate::ErrorKind::ResourceBusy) where
    /// `Create` would have found one that exists already
    /// (`FSCONFIG_CMD_CREATE_EXCL`, Linux 6.6): the options set were then
    /// those of a filesystem of one's own, and not ignored in favour of
    /// those of whoever mounted it first. A configuration that was
    /// refused so is over, and takes no other step: [`fsopen`] starts
    /// another.
    CreateExclusive,
}

/// Starts the configuration of a new filesystem of the type `fstype`
/// (`tmpfs`, `proc`, `ext4`...): `fsopen` (Linux 5.2).
///
/// The handle is for [`fsconfig`], then [`fsmount`]. Nothing exists until
/// [`FsConfig::Create`]. When the filesystem refuses a step, it may leave
/// a line saying why, which [`io::read`](crate::io::read) on the handle
/// returns: `e`, `w` or `i` (error, warning, information), a space, and
/// the message. Reading fails with `ENODATA` when there is none.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SYS_ADMIN` (see the [module documentation](self#mounts)); `ENODEV`
/// for a type the kernel does not have;
/// [`Unsupported`](crate::ErrorKind::Unsupported) under an emulator that
/// lacks the call.
pub fn fsopen(fstype: &str) -> Result<OwnedHandle> {
    sys::fs::mount::fsopen(fstype.as_bytes())
}

/// Does one step of the configuration `fs`, a handle of [`fsopen`] or
/// [`fspick`]: `fsconfig`.
///
/// The options are those the type takes in the text of [`mount`], one per
/// call, and those every type has: `source`, and the flags `ro`, `rw`,
/// `sync`, `dirsync`, `lazytime`...
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for an option the
/// filesystem does not have, a value it refuses, and a handle that is no
/// configuration ([`BadHandle`](crate::ErrorKind::BadHandle) for a mount
/// or a tree, which are handles of a path alone); [`ResourceBusy`](crate::ErrorKind::ResourceBusy) for a
/// step that comes at the wrong time (an option, or a second
/// [`Create`](FsConfig::Create), after the filesystem was created);
/// [`BadHandle`](crate::ErrorKind::BadHandle) for a handle given as a
/// value that is not open.
pub fn fsconfig<H: AsHandle + ?Sized>(fs: &H, command: FsConfig<'_>) -> Result<()> {
    sys::fs::mount::fsconfig(fs.as_handle(), &command)
}

/// Makes a mount of the filesystem the configuration `fs` created, with
/// the settings `attributes`: `fsmount`. The mount is attached nowhere:
/// [`move_mount_at`] attaches it, and it can be used through its handle
/// before that (see the [module documentation](self#mounts-as-handles)).
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a configuration
/// that has not created its filesystem;
/// [`ResourceBusy`](crate::ErrorKind::ResourceBusy) for one that was
/// mounted already.
pub fn fsmount<H: AsHandle + ?Sized>(fs: &H, attributes: MountAttributes) -> Result<OwnedHandle> {
    sys::fs::mount::fsmount(fs.as_handle(), attributes)
}

crate::macros::flags! {
    /// How [`fspick`] looks its path up.
    pub struct FsPickFlags: u32 {
        /// Does not follow a symbolic link in the last component
        /// (`FSPICK_SYMLINK_NOFOLLOW`).
        const NO_FOLLOW = 1;
        /// Does not trigger an automount (`FSPICK_NO_AUTOMOUNT`).
        const NO_AUTOMOUNT = 1 << 1;
        /// An empty path names the handle itself (`FSPICK_EMPTY_PATH`).
        const EMPTY_PATH = 1 << 2;
    }
}

/// Opens the filesystem mounted at `path` for reconfiguration: `fspick`.
/// `path` is relative to the directory `dir`, or to the current directory
/// without one, and must name a mount point (the root of a mount):
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a directory under
/// one.
///
/// The handle is for [`fsconfig`]: options, then
/// [`FsConfig::Reconfigure`], which changes the filesystem for every
/// place it is mounted at, as [`remount`] does.
pub fn fspick<P: AsPath + ?Sized>(
    dir: Option<BorrowedHandle<'_>>,
    path: &P,
    flags: FsPickFlags,
) -> Result<OwnedHandle> {
    sys::fs::mount::fspick(dir, path.as_path_bytes(), flags)
}

crate::macros::flags! {
    /// What [`open_tree`] opens, and how it looks its path up.
    pub struct OpenTreeFlags: u32 {
        /// Makes a copy of the mount, attached nowhere, instead of
        /// opening the one that is there (`OPEN_TREE_CLONE`): a bind
        /// mount without a place yet. It takes `CAP_SYS_ADMIN`.
        const CLONE = 1;
        /// With [`CLONE`](Self::CLONE), copies every mount under it as
        /// well (`AT_RECURSIVE`).
        const RECURSIVE = 1 << 1;
        /// An empty path names the handle itself (`AT_EMPTY_PATH`).
        const EMPTY_PATH = 1 << 2;
        /// Does not follow a symbolic link in the last component
        /// (`AT_SYMLINK_NOFOLLOW`).
        const NO_FOLLOW = 1 << 3;
        /// Does not trigger an automount (`AT_NO_AUTOMOUNT`).
        const NO_AUTOMOUNT = 1 << 4;
    }
}

/// Opens what is at `path` as a handle to give [`move_mount_at`] or
/// [`mount_setattr`]: `open_tree` (Linux 5.2). `path` is relative to the
/// directory `dir`, or to the current directory without one.
///
/// Without [`OpenTreeFlags::CLONE`] the handle names the place itself, as
/// one opened with `O_PATH` does, and anyone may have it. With it, the
/// handle is a copy of the tree there (of the mount, or of the directory
/// and what is under it in its mount), which is attached nowhere, and
/// which goes away with the handle unless it is attached.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) for a copy
/// without `CAP_SYS_ADMIN`;
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for
/// [`RECURSIVE`](OpenTreeFlags::RECURSIVE) without
/// [`CLONE`](OpenTreeFlags::CLONE), and for a copy of a tree that may not
/// be bound ([`Propagation::Unbindable`]).
pub fn open_tree<P: AsPath + ?Sized>(
    dir: Option<BorrowedHandle<'_>>,
    path: &P,
    flags: OpenTreeFlags,
) -> Result<OwnedHandle> {
    sys::fs::mount::open_tree(dir, path.as_path_bytes(), flags)
}

crate::macros::flags! {
    /// How [`move_mount_at`] looks its two paths up, and what it does:
    /// the `MOVE_MOUNT_*` flags.
    pub struct MoveMountFlags: u32 {
        /// Follows a symbolic link at the end of the source path
        /// (`MOVE_MOUNT_F_SYMLINKS`): it is not followed otherwise.
        const FROM_SYMLINKS = 1;
        /// Triggers an automount at the source
        /// (`MOVE_MOUNT_F_AUTOMOUNTS`).
        const FROM_AUTOMOUNTS = 1 << 1;
        /// An empty source path names the source handle itself
        /// (`MOVE_MOUNT_F_EMPTY_PATH`): the way to give a mount that
        /// [`fsmount`] or [`open_tree`] returned.
        const FROM_EMPTY_PATH = 1 << 2;
        /// Follows a symbolic link at the end of the target path
        /// (`MOVE_MOUNT_T_SYMLINKS`).
        const TO_SYMLINKS = 1 << 3;
        /// Triggers an automount at the target
        /// (`MOVE_MOUNT_T_AUTOMOUNTS`).
        const TO_AUTOMOUNTS = 1 << 4;
        /// An empty target path names the target handle itself
        /// (`MOVE_MOUNT_T_EMPTY_PATH`).
        const TO_EMPTY_PATH = 1 << 5;
        /// Moves nothing: makes the target mount a peer of the source
        /// one, in its propagation group (`MOVE_MOUNT_SET_GROUP`, Linux
        /// 5.15).
        const SET_GROUP = 1 << 6;
        /// Attaches the mount under the one that is on top at the
        /// target, instead of over it (`MOVE_MOUNT_BENEATH`, Linux 6.5).
        const BENEATH = 1 << 7;
    }
}

/// Attaches the mount `from` names to the directory `to` names, or moves
/// it there if it was attached: `move_mount` (Linux 5.2). Each path is
/// relative to its directory handle, or to the current directory without
/// one.
///
/// A mount [`fsmount`] or [`open_tree`] made is given as the source
/// handle, with an empty path and [`MoveMountFlags::FROM_EMPTY_PATH`]:
///
/// ```no_run
/// # #[cfg(any(target_os = "linux", target_os = "fullrust"))] {
/// use oscall::AsHandle;
/// use oscall::fs::linux::{self, FsConfig, MountAttributes, MoveMountFlags};
///
/// let fs = linux::fsopen("tmpfs")?;
/// linux::fsconfig(&fs, FsConfig::SetString("size", "16m"))?;
/// linux::fsconfig(&fs, FsConfig::Create)?;
/// let mount = linux::fsmount(&fs, MountAttributes::NO_SUID | MountAttributes::NO_DEV)?;
/// let from = Some(mount.as_handle());
/// linux::move_mount_at(from, "", None, "/mnt", MoveMountFlags::FROM_EMPTY_PATH)?;
/// # }
/// # Ok::<(), oscall::Error>(())
/// ```
///
/// [`move_mount`] is the same for two paths and an attached mount, by the
/// older call.
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if the source is not
/// a mount point or a detached mount, or is under a mount point that is
/// shared ([`Propagation::Shared`]);
/// [`NotFound`](crate::ErrorKind::NotFound) for an empty path without the
/// flag that allows it.
pub fn move_mount_at<S, T>(
    from_dir: Option<BorrowedHandle<'_>>,
    from: &S,
    to_dir: Option<BorrowedHandle<'_>>,
    to: &T,
    flags: MoveMountFlags,
) -> Result<()>
where
    S: AsPath + ?Sized,
    T: AsPath + ?Sized,
{
    sys::fs::mount::move_mount_at(
        from_dir,
        from.as_path_bytes(),
        to_dir,
        to.as_path_bytes(),
        flags,
    )
}

crate::macros::flags! {
    /// What [`mount_setattr`] changes, and how it looks its path up.
    pub struct MountSetAttrFlags: u32 {
        /// Changes every mount under the one named as well
        /// (`AT_RECURSIVE`): all of them, or none if one refuses.
        const RECURSIVE = 1;
        /// An empty path names the handle itself (`AT_EMPTY_PATH`).
        const EMPTY_PATH = 1 << 1;
        /// Does not follow a symbolic link in the last component
        /// (`AT_SYMLINK_NOFOLLOW`).
        const NO_FOLLOW = 1 << 2;
        /// Does not trigger an automount (`AT_NO_AUTOMOUNT`).
        const NO_AUTOMOUNT = 1 << 3;
    }
}

/// A change to the settings of a mount point: what [`mount_setattr`]
/// applies (`struct mount_attr`). It starts empty, and changes nothing.
///
/// ```
/// # #[cfg(any(target_os = "linux", target_os = "fullrust"))] {
/// use oscall::fs::linux::{MountAttributes, MountSetAttr, Propagation};
///
/// // Read-only, programs allowed again, and nothing propagated.
/// let change = MountSetAttr::new()
///     .set(MountAttributes::READ_ONLY)
///     .clear(MountAttributes::NO_EXEC)
///     .propagation(Propagation::Private);
/// # let _ = change;
/// # }
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct MountSetAttr<'a> {
    pub(crate) set: MountAttributes,
    pub(crate) clear: MountAttributes,
    pub(crate) propagation: Option<Propagation>,
    pub(crate) id_map: Option<BorrowedHandle<'a>>,
}

impl<'a> MountSetAttr<'a> {
    /// A change of nothing.
    pub const fn new() -> Self {
        Self {
            set: MountAttributes::empty(),
            clear: MountAttributes::empty(),
            propagation: None,
            id_map: None,
        }
    }

    /// Switches these settings on. How access times are kept is one
    /// setting of three values ([`NO_ATIME`](MountAttributes::NO_ATIME),
    /// [`STRICT_ATIME`](MountAttributes::STRICT_ATIME),
    /// [`REL_ATIME`](MountAttributes::REL_ATIME)): setting one replaces
    /// the one there was.
    pub const fn set(mut self, attributes: MountAttributes) -> Self {
        self.set = attributes;
        self
    }

    /// Switches these settings off. Clearing a value of the access time
    /// setting puts it back to [`REL_ATIME`](MountAttributes::REL_ATIME).
    pub const fn clear(mut self, attributes: MountAttributes) -> Self {
        self.clear = attributes;
        self
    }

    /// Sets how mount events propagate, as [`set_propagation`] does.
    pub const fn propagation(mut self, propagation: Propagation) -> Self {
        self.propagation = Some(propagation);
        self
    }

    /// Maps the owners of the files, through this mount alone, by the
    /// maps of the user namespace `user_namespace`
    /// (`MOUNT_ATTR_IDMAP`): an open `/proc/<pid>/ns/user` of a process
    /// in a user namespace whose maps were written
    /// ([`write_uid_map`](crate::process::linux::write_uid_map)). The
    /// namespace is only a way to say a map; nothing has to stay in it.
    ///
    /// A file the filesystem has as owned by the user `inside` of a range
    /// of that map shows through the mount as owned by the matching
    /// `outside` user, and a file created through the mount by that
    /// `outside` user is stored as owned by `inside`. Users the map does
    /// not have show as the overflow user (`nobody`), and may create
    /// nothing. This is how one tree of files serves containers whose
    /// users are different ranges of the system's.
    ///
    /// The mount must be a detached one that was never attached
    /// ([`open_tree`] with [`OpenTreeFlags::CLONE`], [`fsmount`]), of a
    /// filesystem that supports it (ext4, xfs, btrfs; `tmpfs` since
    /// Linux 6.3), and the caller needs `CAP_SYS_ADMIN` in the user
    /// namespace the filesystem was mounted in: the initial one for
    /// those on disks. The namespace may be neither that one nor the
    /// initial one.
    pub const fn id_map(mut self, user_namespace: BorrowedHandle<'a>) -> Self {
        self.id_map = Some(user_namespace);
        self
    }
}

/// Changes the settings of the mount `path` is on, and with
/// [`MountSetAttrFlags::RECURSIVE`] of every mount under it:
/// `mount_setattr` (Linux 5.12). `path` is relative to the directory
/// `dir`, or to the current directory without one; a mount that is
/// attached nowhere is given as `dir`, with an empty path and
/// [`MountSetAttrFlags::EMPTY_PATH`].
///
/// Unlike [`remount_bind`], which replaces every setting of one mount
/// point, this changes the settings named and leaves the others, and does
/// it to a whole tree or not at all.
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if `path` is not a
/// mount point, for two values of the access time setting at once, and
/// for a map of identifiers on a mount that cannot have one (see
/// [`MountSetAttr::id_map`]);
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without the
/// capability, and to remove a restriction a mount point of a user
/// namespace came with; [`Unsupported`](crate::ErrorKind::Unsupported)
/// before Linux 5.12.
pub fn mount_setattr<P: AsPath + ?Sized>(
    dir: Option<BorrowedHandle<'_>>,
    path: &P,
    flags: MountSetAttrFlags,
    change: &MountSetAttr<'_>,
) -> Result<()> {
    sys::fs::mount::mount_setattr(dir, path.as_path_bytes(), flags, change)
}

/// Opens what is at `path` as [`open_tree`] does, and applies `change` to
/// the mount the handle is of, in the same call: `open_tree_attr` (Linux
/// 6.15). With [`OpenTreeFlags::CLONE`] this is a copy of a tree that is
/// read-only, or maps the owners of its files
/// ([`MountSetAttr::id_map`]), from the moment it exists; and a copy can
/// be given a map of identifiers when the tree it is made from has one
/// already, which [`mount_setattr`] refuses.
///
/// With [`OpenTreeFlags::RECURSIVE`] the change is applied to every mount
/// of the copy. Without [`OpenTreeFlags::CLONE`] nothing is copied: the
/// change is made to the mount that is at `path`, as [`mount_setattr`]
/// makes it, and the handle is of the place (measured on Linux 6.18). A
/// change of nothing makes this [`open_tree`].
///
/// # Errors
///
/// As [`open_tree`] and [`mount_setattr`];
/// [`Unsupported`](crate::ErrorKind::Unsupported) before Linux 6.15.
pub fn open_tree_attr<P: AsPath + ?Sized>(
    dir: Option<BorrowedHandle<'_>>,
    path: &P,
    flags: OpenTreeFlags,
    change: &MountSetAttr<'_>,
) -> Result<OwnedHandle> {
    sys::fs::mount::open_tree_attr(dir, path.as_path_bytes(), flags, change)
}

/// Detaches what is mounted at `target`, the topmost mount if several are
/// stacked there: `umount2`.
///
/// # Errors
///
/// [`ResourceBusy`](crate::ErrorKind::ResourceBusy) while something is in
/// use under the mount point (an open file, a current directory, another
/// mount), unless [`UnmountFlags::DETACH`] is given;
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if `target` is not a
/// mount point, or is one the caller's namespace holds locked (inherited
/// from a namespace with more privilege).
pub fn unmount<T: AsPath + ?Sized>(target: &T, flags: UnmountFlags) -> Result<()> {
    sys::fs::mount::unmount(target.as_path_bytes(), flags)
}

/// Makes `new_root` the root of the mount namespace of the caller, and
/// moves the old root to `put_old`, which must be `new_root` or a
/// directory under it: `pivot_root`.
///
/// Every process of the mount namespace whose root or current directory
/// was the old root has it changed to the new one; the caller should
/// still `set_current_dir("/")` afterwards. With `put_old` equal to
/// `new_root` (`pivot_root(".", ".")` with the new root as the current
/// directory), the old root ends up mounted over the new one, at the same
/// place: `unmount(".", UnmountFlags::DETACH)` then lets the old one go,
/// without any directory needed for it (the current directory is in the
/// new root, and what is unmounted is what is stacked on it).
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if `new_root` is not a
/// mount point, if `put_old` is not at or under it, if the current root
/// is not a mount point (a process in a [`chroot`]) or is the initial
/// file system of the kernel (the one an initramfs is unpacked into,
/// which nothing can be moved away from), or if either the current
/// root's parent mount or `new_root` is shared ([`Propagation::Shared`]);
/// [`ResourceBusy`](crate::ErrorKind::ResourceBusy) if `new_root` or
/// `put_old` is the current root.
pub fn pivot_root<N, O>(new_root: &N, put_old: &O) -> Result<()>
where
    N: AsPath + ?Sized,
    O: AsPath + ?Sized,
{
    sys::fs::mount::pivot_root(new_root.as_path_bytes(), put_old.as_path_bytes())
}

/// Makes the directory `path` the root directory of the calling process:
/// `chroot`. Paths that start with `/` are looked up from there, by this
/// process and by those it creates afterwards.
///
/// The current directory is not changed: follow with
/// `set_current_dir("/")`, or the process keeps a way out through it.
/// This is not a confinement by itself: a process that keeps
/// `CAP_SYS_CHROOT`, or an open directory outside, leaves. [`pivot_root`]
/// in a mount namespace is what removes the rest of the system from
/// view.
///
/// The root directory belongs to the whole process, every thread of it
/// (unless a thread was created without sharing it, which neither `std`
/// nor a libc does).
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SYS_CHROOT` in the user namespace of the caller.
pub fn chroot<P: AsPath + ?Sized>(path: &P) -> Result<()> {
    sys::fs::mount::chroot(path.as_path_bytes())
}