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
//! What is mounted: `statmount` and `listmount`.

use super::{MountAttributes, MountFlags, Propagation};
use crate::{AsPath, BorrowedHandle, ErrorKind, Result, sys};

/// What stands for the root of the mount namespace of the caller where
/// the identifier of a mount is asked for (`LSMT_ROOT`): [`listmount`]
/// then lists every mount of the namespace.
pub const ROOT_MOUNT: u64 = sys::fs::mount::LSMT_ROOT;

crate::macros::flags! {
    /// What [`statmount`] is asked for, and what it answered: the
    /// `STATMOUNT_*` bits. A kernel leaves out what it does not know, and
    /// what the mount does not have.
    pub struct StatMountFields: u64 {
        /// The filesystem: [`device`](MountInfo::device),
        /// [`magic`](MountInfo::magic) and
        /// [`filesystem_flags`](MountInfo::filesystem_flags)
        /// (`STATMOUNT_SB_BASIC`).
        const FILESYSTEM = 1;
        /// The mount: its identifiers, its parent's, its
        /// [`attributes`](MountInfo::attributes), and how it propagates
        /// (`STATMOUNT_MNT_BASIC`).
        const MOUNT = 1 << 1;
        /// [`propagate_from`](MountInfo::propagate_from)
        /// (`STATMOUNT_PROPAGATE_FROM`).
        const PROPAGATE_FROM = 1 << 2;
        /// [`root`](MountInfo::root) (`STATMOUNT_MNT_ROOT`).
        const ROOT = 1 << 3;
        /// [`point`](MountInfo::point) (`STATMOUNT_MNT_POINT`).
        const POINT = 1 << 4;
        /// [`fs_type`](MountInfo::fs_type) (`STATMOUNT_FS_TYPE`).
        const FS_TYPE = 1 << 5;
        /// [`namespace_id`](MountInfo::namespace_id)
        /// (`STATMOUNT_MNT_NS_ID`, Linux 6.11).
        const NAMESPACE_ID = 1 << 6;
        /// [`options`](MountInfo::options) (`STATMOUNT_MNT_OPTS`, Linux
        /// 6.11).
        const OPTIONS = 1 << 7;
        /// [`fs_subtype`](MountInfo::fs_subtype)
        /// (`STATMOUNT_FS_SUBTYPE`, Linux 6.13).
        const FS_SUBTYPE = 1 << 8;
        /// [`source`](MountInfo::source) (`STATMOUNT_SB_SOURCE`, Linux
        /// 6.13).
        const SOURCE = 1 << 9;
        /// [`option_list`](MountInfo::option_list)
        /// (`STATMOUNT_OPT_ARRAY`, Linux 6.13).
        const OPTION_LIST = 1 << 10;
        /// [`security_options`](MountInfo::security_options)
        /// (`STATMOUNT_OPT_SEC_ARRAY`, Linux 6.13).
        const SECURITY_OPTIONS = 1 << 11;
        /// [`supported`](MountInfo::supported)
        /// (`STATMOUNT_SUPPORTED_MASK`, Linux 6.15).
        const SUPPORTED = 1 << 12;
        /// [`uid_map`](MountInfo::uid_map) (`STATMOUNT_MNT_UIDMAP`,
        /// Linux 6.15).
        const UID_MAP = 1 << 13;
        /// [`gid_map`](MountInfo::gid_map) (`STATMOUNT_MNT_GIDMAP`,
        /// Linux 6.15).
        const GID_MAP = 1 << 14;
    }
}

impl StatMountFields {
    /// Everything there is to ask for.
    pub const ALL: Self = Self((1 << 15) - 1);
}

/// A list of strings of a [`MountInfo`], as the kernel wrote them one
/// after the other: an iterator over them.
#[derive(Clone, Copy, Default)]
pub struct Strings<'a> {
    data: &'a [u8],
    left: u32,
}

impl core::fmt::Debug for Strings<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut list = f.debug_list();
        for item in *self {
            list.entry(&format_args!("\"{}\"", item.escape_ascii()));
        }
        list.finish()
    }
}

impl<'a> Iterator for Strings<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<&'a [u8]> {
        if self.left == 0 {
            return None;
        }
        self.left -= 1;
        let end = self.data.iter().position(|&byte| byte == 0);
        let (item, rest) = match end {
            Some(end) => (&self.data[..end], &self.data[end + 1..]),
            None => (self.data, &[][..]),
        };
        self.data = rest;
        Some(item)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.left as usize, Some(self.left as usize))
    }
}

impl ExactSizeIterator for Strings<'_> {}

/// What the kernel says of a mount: the answer of [`statmount`]
/// (`struct statmount`). The strings are in the buffer the call was given.
///
/// Only what [`fields`](Self::fields) names was written; the rest is zero,
/// `None` or empty. A string that was written and is empty is `Some` of
/// nothing.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct MountInfo<'a> {
    /// What the kernel wrote: what was asked for, less what it does not
    /// know or the mount does not have.
    pub fields: StatMountFields,
    /// What the running kernel can be asked
    /// ([`StatMountFields::SUPPORTED`]). Bits oscall has no name for are
    /// left out.
    pub supported: StatMountFields,
    /// The identifier of the mount: unique since the system started, and
    /// never given to another ([`StatMountFields::MOUNT`], as the next
    /// nine).
    pub id: u64,
    /// The identifier of the mount it is attached to; its own for the
    /// root of the namespace.
    pub parent_id: u64,
    /// The short identifier `/proc/self/mountinfo` shows first, which is
    /// given again once the mount is gone.
    pub old_id: u32,
    /// The short identifier of the parent, the second number there.
    pub old_parent_id: u32,
    /// The settings of the mount point. One of
    /// [`NO_ATIME`](MountAttributes::NO_ATIME),
    /// [`STRICT_ATIME`](MountAttributes::STRICT_ATIME) and
    /// [`REL_ATIME`](MountAttributes::REL_ATIME) is always there.
    pub attributes: MountAttributes,
    /// Whether the mount maps the owners of files
    /// ([`MountSetAttr::id_map`](super::MountSetAttr::id_map)).
    pub id_mapped: bool,
    /// How mount events propagate. A mount can both be shared and receive
    /// from a master: this then says [`Propagation::Shared`], and
    /// [`master`](Self::master) is not 0.
    pub propagation: Propagation,
    /// The identifier of its peer group, when it is shared; 0 otherwise.
    pub peer_group: u64,
    /// The identifier of the peer group it receives from; 0 if none.
    pub master: u64,
    /// The peer group, among those of the namespace of the caller, that
    /// events reach it from when [`master`](Self::master) is not one of
    /// them ([`StatMountFields::PROPAGATE_FROM`]).
    pub propagate_from: u64,
    /// The device of the filesystem, major and minor
    /// ([`StatMountFields::FILESYSTEM`], as the next two).
    pub device: (u32, u32),
    /// The number that names the type of the filesystem
    /// (`..._SUPER_MAGIC`: `0x0102_1994` for `tmpfs`, `0x9fa0` for
    /// `proc`).
    pub magic: u64,
    /// What the filesystem itself is, wherever it is mounted: of
    /// [`MountFlags`], [`READ_ONLY`](MountFlags::READ_ONLY),
    /// [`SYNCHRONOUS`](MountFlags::SYNCHRONOUS),
    /// [`DIR_SYNC`](MountFlags::DIR_SYNC) and
    /// [`LAZY_TIME`](MountFlags::LAZY_TIME).
    pub filesystem_flags: MountFlags,
    /// The identifier of the mount namespace the mount is in
    /// ([`StatMountFields::NAMESPACE_ID`]).
    pub namespace_id: u64,
    /// The name of the type of the filesystem: `tmpfs`, `ext4`
    /// ([`StatMountFields::FS_TYPE`]).
    pub fs_type: Option<&'a [u8]>,
    /// What the type calls its kind, after the dot of `fuse.sshfs`
    /// ([`StatMountFields::FS_SUBTYPE`]); only for a filesystem that has
    /// one.
    pub fs_subtype: Option<&'a [u8]>,
    /// What the filesystem was mounted from: a device, or the name given
    /// ([`StatMountFields::SOURCE`]).
    pub source: Option<&'a [u8]>,
    /// The directory of the filesystem that the mount shows, `/` unless
    /// it is a bind mount of part of one ([`StatMountFields::ROOT`]).
    pub root: Option<&'a [u8]>,
    /// Where the mount is attached, from the root directory of the
    /// caller ([`StatMountFields::POINT`]).
    pub point: Option<&'a [u8]>,
    /// The options of the filesystem, as the text
    /// `/proc/self/mountinfo` ends its lines with: separated by commas,
    /// with the escapes of that file ([`StatMountFields::OPTIONS`]).
    pub options: Option<&'a [u8]>,
    /// The same options, one by one and without escapes, less those of
    /// security modules ([`StatMountFields::OPTION_LIST`]).
    pub option_list: Strings<'a>,
    /// The options that belong to security modules
    /// ([`StatMountFields::SECURITY_OPTIONS`]).
    pub security_options: Strings<'a>,
    /// The user map of a mount that maps identifiers, as lines of a
    /// `uid_map` seen from the user namespace of the caller
    /// ([`StatMountFields::UID_MAP`]).
    pub uid_map: Strings<'a>,
    /// Its group map ([`StatMountFields::GID_MAP`]).
    pub gid_map: Strings<'a>,
}

/// The string at `offset` of `strings`, up to its end.
fn string_at(strings: &[u8], offset: u32) -> &[u8] {
    let rest = strings.get(offset as usize..).unwrap_or_default();
    let end = rest.iter().position(|&byte| byte == 0);
    &rest[..end.unwrap_or(rest.len())]
}

/// Asks the kernel about the mount `id`: `statmount` (Linux 6.8). `id` is
/// the unique identifier of a mount of the mount namespace of the caller:
/// what [`listmount`] and [`mounts`] list, and what [`mount_id`] returns
/// for a path.
///
/// `fields` says what to answer, and `buf` is where the answer is
/// written: [`MountInfo::MIN_BUFFER`] bytes for the numbers, and room
/// after them for the strings asked for. The call asks nothing of the
/// filesystem itself, and does not wait for one that hangs.
///
/// This is what a line of `/proc/self/mountinfo` says, for one mount and
/// without a file to read and parse; it needs no `/proc`.
///
/// # Errors
///
/// [`BufferTooSmall`](crate::ErrorKind::BufferTooSmall) when the answer
/// does not fit (`EOVERFLOW`): call again with more;
/// [`NotFound`](crate::ErrorKind::NotFound) for an identifier that names
/// no mount of the namespace, a mount that is attached nowhere among
/// them; [`InvalidInput`](crate::ErrorKind::InvalidInput) for a number
/// that is no unique identifier (they start above 2³¹; the short ones of
/// `/proc/self/mountinfo` are not these);
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) for a mount
/// that cannot be reached from the root directory of the caller (a
/// process in a `chroot`), without `CAP_SYS_ADMIN`;
/// [`Unsupported`](crate::ErrorKind::Unsupported) before Linux 6.8, and
/// under an emulator that lacks the call.
pub fn statmount(id: u64, fields: StatMountFields, buf: &mut [u8]) -> Result<MountInfo<'_>> {
    let (stat, strings) = sys::fs::mount::statmount(id, fields, buf)?;
    let written = StatMountFields(stat.mask & StatMountFields::ALL.0);
    let has = |field: StatMountFields| written.contains(field);
    let string = |field: StatMountFields, offset: u32| {
        if has(field) {
            Some(string_at(strings, offset))
        } else {
            None
        }
    };
    let list = |field: StatMountFields, offset: u32, count: u32| {
        if has(field) {
            Strings {
                data: strings.get(offset as usize..).unwrap_or_default(),
                left: count,
            }
        } else {
            Strings::default()
        }
    };
    let (attributes, id_mapped) = if has(StatMountFields::MOUNT) {
        sys::fs::mount::attributes_from(stat.mnt_attr)
    } else {
        (MountAttributes::empty(), false)
    };
    Ok(MountInfo {
        fields: written,
        supported: if has(StatMountFields::SUPPORTED) {
            StatMountFields(stat.supported_mask & StatMountFields::ALL.0)
        } else {
            StatMountFields::empty()
        },
        id: stat.mnt_id,
        parent_id: stat.mnt_parent_id,
        old_id: stat.mnt_id_old,
        old_parent_id: stat.mnt_parent_id_old,
        attributes,
        id_mapped,
        propagation: sys::fs::mount::propagation_from(stat.mnt_propagation),
        peer_group: stat.mnt_peer_group,
        master: stat.mnt_master,
        propagate_from: stat.propagate_from,
        device: (stat.sb_dev_major, stat.sb_dev_minor),
        magic: stat.sb_magic,
        filesystem_flags: if has(StatMountFields::FILESYSTEM) {
            sys::fs::mount::filesystem_flags_from(stat.sb_flags)
        } else {
            MountFlags::empty()
        },
        namespace_id: stat.mnt_ns_id,
        fs_type: string(StatMountFields::FS_TYPE, stat.fs_type),
        fs_subtype: string(StatMountFields::FS_SUBTYPE, stat.fs_subtype),
        source: string(StatMountFields::SOURCE, stat.sb_source),
        root: string(StatMountFields::ROOT, stat.mnt_root),
        point: string(StatMountFields::POINT, stat.mnt_point),
        options: string(StatMountFields::OPTIONS, stat.mnt_opts),
        option_list: list(StatMountFields::OPTION_LIST, stat.opt_array, stat.opt_num),
        security_options: list(
            StatMountFields::SECURITY_OPTIONS,
            stat.opt_sec_array,
            stat.opt_sec_num,
        ),
        uid_map: list(
            StatMountFields::UID_MAP,
            stat.mnt_uidmap,
            stat.mnt_uidmap_num,
        ),
        gid_map: list(
            StatMountFields::GID_MAP,
            stat.mnt_gidmap,
            stat.mnt_gidmap_num,
        ),
    })
}

impl MountInfo<'_> {
    /// The least [`statmount`] takes for a buffer: the size of the
    /// kernel's structure, with no room for a string.
    pub const MIN_BUFFER: usize = sys::fs::mount::STATMOUNT_SIZE;
}

crate::macros::flags! {
    /// How [`listmount`] lists.
    pub struct ListMountFlags: u32 {
        /// The mounts made last come first (`LISTMOUNT_REVERSE`, Linux
        /// 6.11).
        const REVERSE = 1;
    }
}

/// Lists the mounts under the mount `parent`, at any depth, into `ids`,
/// and returns how many were written: `listmount` (Linux 6.8).
/// [`ROOT_MOUNT`] for `parent` lists every mount of the mount namespace of
/// the caller, the one at its root included.
///
/// The identifiers are the unique ones [`statmount`] takes, in the order
/// the mounts were made. `after` is where to go on from: 0 to start, then
/// the last identifier the previous call wrote; a call that writes fewer
/// identifiers than `ids` holds has reached the end. [`mounts`] does that.
///
/// Mounts the caller cannot reach from its root directory are left out
/// (all of them, for a caller with `CAP_SYS_ADMIN`, are listed).
///
/// # Errors
///
/// [`NotFound`](crate::ErrorKind::NotFound) for a parent that names no
/// mount of the namespace;
/// [`Unsupported`](crate::ErrorKind::Unsupported) before Linux 6.8, and
/// under an emulator that lacks the call;
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a `parent` or an
/// `after` that is no unique identifier, and for
/// [`ListMountFlags::REVERSE`] on a kernel older than it.
pub fn listmount(parent: u64, after: u64, flags: ListMountFlags, ids: &mut [u64]) -> Result<usize> {
    let count = sys::fs::mount::listmount(parent, after, flags, ids)?;
    if count > ids.len() {
        return Err(ErrorKind::Other.into());
    }
    Ok(count)
}

/// The mounts under a mount: what [`mounts`] returns. An iterator over
/// their identifiers, which calls [`listmount`] for a few of them at a
/// time and holds nothing of the system.
#[derive(Clone, Debug)]
pub struct Mounts {
    parent: u64,
    ids: [u64; 32],
    at: usize,
    len: usize,
    last: u64,
    done: bool,
}

/// The mounts under the mount `parent`, or of the whole mount namespace
/// of the caller for [`ROOT_MOUNT`]: an iterator over their identifiers,
/// in the order they were made.
///
/// The list is not a snapshot: a mount made while it is read may show or
/// not, and one that goes away may make [`statmount`] fail with
/// [`NotFound`](crate::ErrorKind::NotFound) for an identifier just read.
///
/// ```no_run
/// # #[cfg(any(target_os = "linux", target_os = "fullrust"))] {
/// use oscall::fs::linux::{self, StatMountFields};
///
/// let mut buf = [0u8; 4096];
/// for id in linux::mounts(linux::ROOT_MOUNT) {
///     let fields = StatMountFields::FS_TYPE | StatMountFields::POINT;
///     let mount = linux::statmount(id?, fields, &mut buf)?;
///     // `mount.fs_type`, `mount.point`...
/// }
/// # }
/// # Ok::<(), oscall::Error>(())
/// ```
pub fn mounts(parent: u64) -> Mounts {
    Mounts {
        parent,
        ids: [0; 32],
        at: 0,
        len: 0,
        last: 0,
        done: false,
    }
}

impl Iterator for Mounts {
    type Item = Result<u64>;

    fn next(&mut self) -> Option<Result<u64>> {
        if self.at == self.len {
            if self.done {
                return None;
            }
            let flags = ListMountFlags::empty();
            match listmount(self.parent, self.last, flags, &mut self.ids) {
                Ok(count) => {
                    self.at = 0;
                    self.len = count;
                    // A list that was not filled is the end of it.
                    self.done = count < self.ids.len();
                    if count == 0 {
                        return None;
                    }
                }
                Err(error) => {
                    self.done = true;
                    return Some(Err(error));
                }
            }
        }
        let id = self.ids[self.at];
        self.at += 1;
        self.last = id;
        Some(Ok(id))
    }
}

/// The unique identifier of the mount that `path` is on, for
/// [`statmount`] and [`listmount`]: `statx` with `STATX_MNT_ID_UNIQUE`
/// (Linux 6.8). `path` is relative to the directory `dir`, or to the
/// current directory without one; an empty path names `dir` itself, which
/// may then be any handle: a detached mount, a file.
///
/// With `follow`, a symbolic link at the end of the path is followed.
///
/// # Errors
///
/// [`Unsupported`](crate::ErrorKind::Unsupported) on a kernel that has no
/// such identifiers, and under an emulator that does not pass them on.
pub fn mount_id<P: AsPath + ?Sized>(
    dir: Option<BorrowedHandle<'_>>,
    path: &P,
    follow: bool,
) -> Result<u64> {
    sys::fs::mount::mount_id(dir, path.as_path_bytes(), follow)
}