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
//! Capabilities, the identity of the calling thread, and the names of the
//! system: the part of `process::linux` that is about credentials.

#[cfg(feature = "alloc")]
use crate::ErrorKind;
use crate::{Result, sys};

/// A capability: one of the parts the privilege of root is divided into.
/// `capabilities(7)` says what each one allows; the summaries here name
/// the most common use.
///
/// The numbers are the kernel's ([`number`](Self::number)). A kernel newer
/// than this list has capabilities it does not name: a [`CapabilitySet`]
/// holds them all the same.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
#[repr(u8)]
pub enum Capability {
    /// `CAP_CHOWN`: change the owner and the group of any file.
    Chown = 0,
    /// `CAP_DAC_OVERRIDE`: read, write and execute files whatever their
    /// permissions.
    DacOverride = 1,
    /// `CAP_DAC_READ_SEARCH`: read files and search directories whatever
    /// their permissions.
    DacReadSearch = 2,
    /// `CAP_FOWNER`: do to any file what its owner may (permissions,
    /// times, removal from a sticky directory).
    Fowner = 3,
    /// `CAP_FSETID`: keep set-user-ID and set-group-ID bits when a file is
    /// modified.
    Fsetid = 4,
    /// `CAP_KILL`: send signals to any process.
    Kill = 5,
    /// `CAP_SETGID`: change group identifiers and supplementary groups,
    /// write a group map.
    Setgid = 6,
    /// `CAP_SETUID`: change user identifiers, write a user map.
    Setuid = 7,
    /// `CAP_SETPCAP`: drop capabilities from the bounding set, add any of
    /// it to the inheritable set, change the secure bits.
    Setpcap = 8,
    /// `CAP_LINUX_IMMUTABLE`: set the immutable and append-only attributes
    /// of files.
    LinuxImmutable = 9,
    /// `CAP_NET_BIND_SERVICE`: bind a socket to a port below 1024.
    NetBindService = 10,
    /// `CAP_NET_BROADCAST`: broadcast, and listen to multicast.
    NetBroadcast = 11,
    /// `CAP_NET_ADMIN`: configure the network (interfaces, routes,
    /// firewall).
    NetAdmin = 12,
    /// `CAP_NET_RAW`: open raw and packet sockets.
    NetRaw = 13,
    /// `CAP_IPC_LOCK`: lock memory beyond the limit.
    IpcLock = 14,
    /// `CAP_IPC_OWNER`: bypass the permissions of System V IPC objects.
    IpcOwner = 15,
    /// `CAP_SYS_MODULE`: load and unload kernel modules.
    SysModule = 16,
    /// `CAP_SYS_RAWIO`: access I/O ports and raw memory devices.
    SysRawio = 17,
    /// `CAP_SYS_CHROOT`: `chroot`, and enter mount namespaces.
    SysChroot = 18,
    /// `CAP_SYS_PTRACE`: trace any process.
    SysPtrace = 19,
    /// `CAP_SYS_PACCT`: switch process accounting.
    SysPacct = 20,
    /// `CAP_SYS_ADMIN`: mount, create and enter namespaces, set the host
    /// name, and a great many other things.
    SysAdmin = 21,
    /// `CAP_SYS_BOOT`: reboot, and load a new kernel.
    SysBoot = 22,
    /// `CAP_SYS_NICE`: raise priorities, set the scheduling and the
    /// affinity of any process.
    SysNice = 23,
    /// `CAP_SYS_RESOURCE`: exceed resource limits and quotas.
    SysResource = 24,
    /// `CAP_SYS_TIME`: set the clocks.
    SysTime = 25,
    /// `CAP_SYS_TTY_CONFIG`: configure terminals.
    SysTtyConfig = 26,
    /// `CAP_MKNOD`: create device files.
    Mknod = 27,
    /// `CAP_LEASE`: take leases on any file.
    Lease = 28,
    /// `CAP_AUDIT_WRITE`: write to the audit log.
    AuditWrite = 29,
    /// `CAP_AUDIT_CONTROL`: configure auditing.
    AuditControl = 30,
    /// `CAP_SETFCAP`: set the capabilities of files, and map user 0 in a
    /// user namespace.
    Setfcap = 31,
    /// `CAP_MAC_OVERRIDE`: override mandatory access control.
    MacOverride = 32,
    /// `CAP_MAC_ADMIN`: configure mandatory access control.
    MacAdmin = 33,
    /// `CAP_SYSLOG`: read and clear the kernel log.
    Syslog = 34,
    /// `CAP_WAKE_ALARM`: set alarms that wake the system.
    WakeAlarm = 35,
    /// `CAP_BLOCK_SUSPEND`: keep the system from suspending.
    BlockSuspend = 36,
    /// `CAP_AUDIT_READ`: read the audit log.
    AuditRead = 37,
    /// `CAP_PERFMON`: monitor performance (Linux 5.8).
    Perfmon = 38,
    /// `CAP_BPF`: load BPF programs and create maps (Linux 5.8).
    Bpf = 39,
    /// `CAP_CHECKPOINT_RESTORE`: checkpoint and restore processes
    /// (Linux 5.9).
    CheckpointRestore = 40,
}

impl Capability {
    /// Every capability this version of oscall names, in the order of
    /// their numbers.
    pub const ALL: [Self; 41] = [
        Self::Chown,
        Self::DacOverride,
        Self::DacReadSearch,
        Self::Fowner,
        Self::Fsetid,
        Self::Kill,
        Self::Setgid,
        Self::Setuid,
        Self::Setpcap,
        Self::LinuxImmutable,
        Self::NetBindService,
        Self::NetBroadcast,
        Self::NetAdmin,
        Self::NetRaw,
        Self::IpcLock,
        Self::IpcOwner,
        Self::SysModule,
        Self::SysRawio,
        Self::SysChroot,
        Self::SysPtrace,
        Self::SysPacct,
        Self::SysAdmin,
        Self::SysBoot,
        Self::SysNice,
        Self::SysResource,
        Self::SysTime,
        Self::SysTtyConfig,
        Self::Mknod,
        Self::Lease,
        Self::AuditWrite,
        Self::AuditControl,
        Self::Setfcap,
        Self::MacOverride,
        Self::MacAdmin,
        Self::Syslog,
        Self::WakeAlarm,
        Self::BlockSuspend,
        Self::AuditRead,
        Self::Perfmon,
        Self::Bpf,
        Self::CheckpointRestore,
    ];

    /// The kernel's number for the capability (`CAP_*`).
    #[inline]
    pub const fn number(self) -> u32 {
        self as u32
    }

    /// The capability the kernel gives this number, if oscall names it.
    pub const fn from_number(number: u32) -> Option<Self> {
        if (number as usize) < Self::ALL.len() {
            Some(Self::ALL[number as usize])
        } else {
            None
        }
    }
}

/// A set of capabilities: 64 bits, one per capability number, as the
/// kernel keeps them.
///
/// ```
/// # #[cfg(any(target_os = "linux", target_os = "fullrust"))] {
/// use oscall::process::linux::{Capability, CapabilitySet};
///
/// let set = CapabilitySet::of(&[Capability::NetBindService, Capability::Chown]);
/// assert!(set.contains(Capability::Chown));
/// assert_eq!(set.bits(), 1 << 10 | 1);
/// # }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct CapabilitySet(u64);

impl CapabilitySet {
    /// No capability.
    pub const EMPTY: Self = Self(0);

    /// No capability.
    #[inline]
    pub const fn empty() -> Self {
        Self(0)
    }

    /// The set of `capabilities`.
    pub const fn of(capabilities: &[Capability]) -> Self {
        let mut bits = 0;
        let mut i = 0;
        while i < capabilities.len() {
            bits |= 1 << capabilities[i].number();
            i += 1;
        }
        Self(bits)
    }

    /// The set whose capability numbers are the bits of `bits` that are
    /// set: bit 0 is `CAP_CHOWN`. Numbers this version of oscall has no
    /// name for are kept.
    #[inline]
    pub const fn from_bits(bits: u64) -> Self {
        Self(bits)
    }

    /// The set as bits: see [`from_bits`](Self::from_bits). This is the
    /// number the `Cap*` lines of `/proc/<pid>/status` show in
    /// hexadecimal.
    #[inline]
    pub const fn bits(self) -> u64 {
        self.0
    }

    /// Whether the set has no capability.
    #[inline]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Whether `capability` is in the set.
    #[inline]
    pub const fn contains(self, capability: Capability) -> bool {
        self.0 & 1 << capability.number() != 0
    }

    /// Whether every capability of `other` is in the set.
    #[inline]
    pub const fn is_superset(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    /// The set with `capability` added.
    #[inline]
    #[must_use]
    pub const fn with(self, capability: Capability) -> Self {
        Self(self.0 | 1 << capability.number())
    }

    /// The set with `capability` removed.
    #[inline]
    #[must_use]
    pub const fn without(self, capability: Capability) -> Self {
        Self(self.0 & !(1 << capability.number()))
    }

    /// The capabilities of either set.
    #[inline]
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// The capabilities of both sets.
    #[inline]
    #[must_use]
    pub const fn intersection(self, other: Self) -> Self {
        Self(self.0 & other.0)
    }

    /// The capabilities of the set that are not in `other`.
    #[inline]
    #[must_use]
    pub const fn difference(self, other: Self) -> Self {
        Self(self.0 & !other.0)
    }

    /// Adds `capability` to the set.
    #[inline]
    pub fn insert(&mut self, capability: Capability) {
        *self = self.with(capability);
    }

    /// Removes `capability` from the set.
    #[inline]
    pub fn remove(&mut self, capability: Capability) {
        *self = self.without(capability);
    }

    /// The capabilities of the set that oscall names, in the order of
    /// their numbers.
    pub fn iter(self) -> impl Iterator<Item = Capability> {
        Capability::ALL
            .into_iter()
            .filter(move |&capability| self.contains(capability))
    }
}

impl From<Capability> for CapabilitySet {
    #[inline]
    fn from(capability: Capability) -> Self {
        Self::empty().with(capability)
    }
}

impl FromIterator<Capability> for CapabilitySet {
    fn from_iter<I: IntoIterator<Item = Capability>>(iter: I) -> Self {
        iter.into_iter().fold(Self::empty(), Self::with)
    }
}

impl core::ops::BitOr for CapabilitySet {
    type Output = Self;
    #[inline]
    fn bitor(self, other: Self) -> Self {
        self.union(other)
    }
}

impl core::ops::BitOr<Capability> for CapabilitySet {
    type Output = Self;
    #[inline]
    fn bitor(self, capability: Capability) -> Self {
        self.with(capability)
    }
}

impl core::ops::BitAnd for CapabilitySet {
    type Output = Self;
    #[inline]
    fn bitand(self, other: Self) -> Self {
        self.intersection(other)
    }
}

impl core::ops::Sub for CapabilitySet {
    type Output = Self;
    #[inline]
    fn sub(self, other: Self) -> Self {
        self.difference(other)
    }
}

impl core::fmt::Debug for CapabilitySet {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut set = f.debug_set();
        set.entries(self.iter());
        // What has no name, by its number.
        for number in Capability::ALL.len() as u32..64 {
            if self.0 & 1 << number != 0 {
                set.entry(&number);
            }
        }
        set.finish()
    }
}

/// The three capability sets a thread holds and may change itself: what
/// [`capabilities`] returns and [`set_capabilities`] takes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Capabilities {
    /// What the kernel checks when the thread does something that needs a
    /// capability.
    pub effective: CapabilitySet,
    /// What the thread may put in its effective set, and add to its
    /// inheritable set. A capability removed from it is gone for good.
    pub permitted: CapabilitySet,
    /// What may pass to a program the thread runs, if the file of the
    /// program has it in its own inheritable set, or through the ambient
    /// set.
    pub inheritable: CapabilitySet,
}

impl Capabilities {
    /// The same set as effective, permitted and inheritable.
    pub const fn all_three(set: CapabilitySet) -> Self {
        Self {
            effective: set,
            permitted: set,
            inheritable: set,
        }
    }
}

/// The capability sets of the calling **thread**: `capget` (version 3,
/// sets of 64 bits).
///
/// This is what the thread may use, which is not always what its
/// credentials hold: a security module that denies a process some
/// capabilities takes them out of the answer. Under Ubuntu's AppArmor
/// restriction of user namespaces, the root of a namespace created
/// without privilege gets empty sets here, while `/proc/<pid>/status`
/// shows them full.
pub fn capabilities() -> Result<Capabilities> {
    let [effective, permitted, inheritable] = sys::process::cred::capabilities()?;
    Ok(Capabilities {
        effective: CapabilitySet(effective),
        permitted: CapabilitySet(permitted),
        inheritable: CapabilitySet(inheritable),
    })
}

/// Sets the capability sets of the calling **thread**: `capset`.
///
/// The system call changes one thread. A C library's `capset` is that
/// same call, and `libcap`'s `cap_set_proc` too; only `libpsx` (and Go's
/// runtime) apply it to every thread of a process. A process that means
/// to give up capabilities as a whole does it while it has a single
/// thread, or in each of them; a child of [`spawn`](crate::process::Command::spawn)
/// has one ([`ConfineExt::capabilities`](super::ConfineExt::capabilities)).
///
/// The new permitted set must be within the old one, the effective set
/// within the new permitted set, and the inheritable set within the old
/// inheritable set and the bounding set, or, with `CAP_SETPCAP`, within
/// the old permitted and inheritable sets and the bounding set.
///
/// What a program run afterwards gets is another matter: `execve`
/// computes its sets again, from the inheritable and ambient sets, the
/// bounding set and the capabilities of the file, and gives a program run
/// by user 0 the whole bounding set whatever the caller dropped. To keep
/// capabilities from a program run as root, drop them from the bounding
/// set ([`drop_bounding`]); to give some to a program run as another
/// user, use the ambient set ([`raise_ambient`]).
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) for sets
/// outside of the rules above.
pub fn set_capabilities(capabilities: &Capabilities) -> Result<()> {
    sys::process::cred::set_capabilities([
        capabilities.effective.0,
        capabilities.permitted.0,
        capabilities.inheritable.0,
    ])
}

/// The bounding set of the calling thread: the limit of what a program it
/// runs can gain, by any means. One `prctl(PR_CAPBSET_READ)` per
/// capability the kernel has.
pub fn bounding_set() -> Result<CapabilitySet> {
    sys::process::cred::probe(sys::process::cred::has_bounding).map(CapabilitySet)
}

/// Removes `capability` from the bounding set of the calling **thread**:
/// `prctl(PR_CAPBSET_DROP)`. It cannot be put back; the threads and
/// processes created afterwards by this thread inherit the set.
///
/// The capability stays in the other sets of the thread, if it was there:
/// the bounding set acts when a program is run, and on what may be added
/// to the inheritable set.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SETPCAP` in the effective set;
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for a capability the
/// kernel does not have.
pub fn drop_bounding(capability: Capability) -> Result<()> {
    sys::process::cred::drop_bounding(capability.number())
}

/// The ambient set of the calling thread: the capabilities a program it
/// runs keeps without its file saying anything, provided the program is
/// not set-user-ID, set-group-ID nor has file capabilities. One
/// `prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET)` per capability the
/// kernel has.
pub fn ambient_set() -> Result<CapabilitySet> {
    sys::process::cred::probe(sys::process::cred::has_ambient).map(CapabilitySet)
}

/// Adds `capability` to the ambient set of the calling **thread**:
/// `prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE)`. This is how a process
/// that is not root passes a capability to an ordinary program.
///
/// The capability must be in both the permitted and the inheritable sets
/// of the thread, and leaves the ambient set by itself when it leaves
/// either. The ambient set is emptied when the thread changes user away
/// from root, unless told otherwise
/// ([`SecureBits::NO_SETUID_FIXUP`]).
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) if the
/// capability is not in both sets, or raising is switched off
/// ([`SecureBits::NO_CAP_AMBIENT_RAISE`]).
pub fn raise_ambient(capability: Capability) -> Result<()> {
    sys::process::cred::raise_ambient(capability.number())
}

/// Removes `capability` from the ambient set of the calling **thread**:
/// `prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_LOWER)`.
pub fn lower_ambient(capability: Capability) -> Result<()> {
    sys::process::cred::lower_ambient(capability.number())
}

/// Empties the ambient set of the calling **thread**:
/// `prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL)`.
pub fn clear_ambient() -> Result<()> {
    sys::process::cred::clear_ambient()
}

/// Whether the calling thread keeps its permitted capabilities when it
/// changes all its user identifiers from 0 to something else
/// (`PR_GET_KEEPCAPS`): see [`set_keep_capabilities`].
pub fn keep_capabilities() -> Result<bool> {
    sys::process::cred::keep_capabilities()
}

/// Says whether the calling **thread** keeps its permitted capabilities
/// when its user identifiers all stop being 0:
/// `prctl(PR_SET_KEEPCAPS)`. Without it, a root process that becomes
/// another user loses every capability, which is usually what is wanted.
///
/// The effective set is emptied by such a change all the same:
/// [`set_capabilities`] fills it again from the permitted set. The
/// setting is cleared when a program is run.
pub fn set_keep_capabilities(keep: bool) -> Result<()> {
    sys::process::cred::set_keep_capabilities(keep)
}

crate::macros::flags! {
    /// How the kernel treats user 0 with regard to capabilities, for one
    /// thread: the secure bits (`SECBIT_*`). Each setting has a lock,
    /// which keeps it as it is for good. They are inherited by the
    /// threads and processes created, and survive `execve`, except
    /// [`KEEP_CAPS`](Self::KEEP_CAPS).
    pub struct SecureBits: u32 {
        /// A program run by user 0, or that is set-user-ID root, gets no
        /// capability for that (`SECBIT_NOROOT`).
        const NO_ROOT = 1;
        /// Locks [`NO_ROOT`](Self::NO_ROOT).
        const NO_ROOT_LOCKED = 1 << 1;
        /// Changing user identifiers to and from 0 does not change the
        /// capability sets (`SECBIT_NO_SETUID_FIXUP`).
        const NO_SETUID_FIXUP = 1 << 2;
        /// Locks [`NO_SETUID_FIXUP`](Self::NO_SETUID_FIXUP).
        const NO_SETUID_FIXUP_LOCKED = 1 << 3;
        /// What [`set_keep_capabilities`] sets (`SECBIT_KEEP_CAPS`).
        const KEEP_CAPS = 1 << 4;
        /// Locks [`KEEP_CAPS`](Self::KEEP_CAPS).
        const KEEP_CAPS_LOCKED = 1 << 5;
        /// Nothing may be added to the ambient set
        /// (`SECBIT_NO_CAP_AMBIENT_RAISE`).
        const NO_CAP_AMBIENT_RAISE = 1 << 6;
        /// Locks [`NO_CAP_AMBIENT_RAISE`](Self::NO_CAP_AMBIENT_RAISE).
        const NO_CAP_AMBIENT_RAISE_LOCKED = 1 << 7;
    }
}

/// The secure bits of the calling thread: `prctl(PR_GET_SECUREBITS)`.
/// Bits newer than [`SecureBits`] names are kept in the value, and given
/// back by [`set_secure_bits`].
pub fn secure_bits() -> Result<SecureBits> {
    sys::process::cred::secure_bits().map(SecureBits)
}

/// Sets the secure bits of the calling **thread**:
/// `prctl(PR_SET_SECUREBITS)`. The value replaces them all: start from
/// [`secure_bits`].
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SETPCAP`, and to change a setting that is locked, or to remove a
/// lock.
pub fn set_secure_bits(bits: SecureBits) -> Result<()> {
    sys::process::cred::set_secure_bits(bits.bits())
}

/// The real user of the caller: `getuid`.
pub fn user_id() -> u32 {
    sys::process::cred::ids()[0]
}

/// The effective user of the caller, which is the one its rights are
/// those of: `geteuid`.
pub fn effective_user_id() -> u32 {
    sys::process::cred::ids()[1]
}

/// The real group of the caller: `getgid`.
pub fn group_id() -> u32 {
    sys::process::cred::ids()[2]
}

/// The effective group of the caller: `getegid`.
pub fn effective_group_id() -> u32 {
    sys::process::cred::ids()[3]
}

/// Writes the supplementary groups of the caller into `buf` and returns
/// how many there are: `getgroups`. With an empty `buf`, only the number
/// is returned, for a buffer of that size to be given next.
///
/// # Errors
///
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) if `buf` is not empty
/// and too small.
pub fn groups(buf: &mut [u32]) -> Result<usize> {
    sys::process::cred::groups(buf)
}

/// The supplementary groups of the caller: [`groups`], in a vector of the
/// right size.
#[cfg(feature = "alloc")]
pub fn groups_vec() -> Result<alloc::vec::Vec<u32>> {
    let mut groups = alloc::vec::Vec::new();
    loop {
        let count = sys::process::cred::groups(&mut [])?;
        groups.clear();
        groups
            .try_reserve_exact(count)
            .map_err(|_| ErrorKind::OutOfMemory)?;
        groups.resize(count, 0);
        match sys::process::cred::groups(&mut groups) {
            Ok(count) => {
                groups.truncate(count);
                return Ok(groups);
            }
            // Another thread added groups in between.
            Err(error) if error.kind() == ErrorKind::InvalidInput && count > 0 => {}
            Err(error) => return Err(error),
        }
    }
}

/// Sets the real, effective and saved user of the calling **thread**:
/// `setresuid`. `None` leaves an identifier as it is.
///
/// Without `CAP_SETUID`, each may only be set to one of the three current
/// values. When all three leave 0, the kernel empties the capability
/// sets of the thread (see [`set_keep_capabilities`]); when the effective
/// user changes, it marks the process as not dumpable
/// ([`set_dumpable`](super::set_dumpable)) and clears the parent death
/// signal.
///
/// # One thread, not the process
///
/// The system call changes the calling thread alone. POSIX wants the
/// identity to be that of the process, and the C libraries make it so:
/// glibc and musl interrupt every other thread with a signal to have it
/// make the same call. oscall calls the kernel, and nothing is told to
/// the other threads: after this, they still run as the previous user.
/// Call it while the process has one thread, or in a child (which
/// `unix::CommandExt::uid` does), unless different identities per thread
/// is what is meant.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) by the rule
/// above; [`InvalidInput`](crate::ErrorKind::InvalidInput) for an
/// identifier that has no mapping in the user namespace of the caller,
/// and for `u32::MAX`, which is not an identifier;
/// [`WouldBlock`](crate::ErrorKind::WouldBlock) (`EAGAIN`) when the new
/// real user already has as many processes as its limit allows.
pub fn set_user_ids(real: Option<u32>, effective: Option<u32>, saved: Option<u32>) -> Result<()> {
    sys::process::cred::set_user_ids([real, effective, saved])
}

/// Sets the real, effective and saved group of the calling **thread**:
/// `setresgid`. As [`set_user_ids`], with `CAP_SETGID`, and with the same
/// warning: one thread, not the process.
pub fn set_group_ids(real: Option<u32>, effective: Option<u32>, saved: Option<u32>) -> Result<()> {
    sys::process::cred::set_group_ids([real, effective, saved])
}

/// Sets the supplementary groups of the calling **thread**: `setgroups`.
/// An empty list drops them all. As for [`set_user_ids`], the other
/// threads of the process keep theirs.
///
/// # Errors
///
/// [`PermissionDenied`](crate::ErrorKind::PermissionDenied) without
/// `CAP_SETGID`, and in a user namespace where `setgroups` is denied
/// ([`allow_setgroups`](super::allow_setgroups));
/// [`InvalidInput`](crate::ErrorKind::InvalidInput) for more groups than
/// the system allows (65536).
pub fn set_groups(groups: &[u32]) -> Result<()> {
    sys::process::cred::set_groups(groups)
}

/// The names of the system, as the kernel gives them to the caller: what
/// [`system_name`] returns. Each is a byte string of at most 64 bytes.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct SystemName(sys::process::cred::UtsName);

impl SystemName {
    fn field(&self, index: usize) -> &[u8] {
        let field = &self.0[index];
        let len = field.iter().position(|&byte| byte == 0);
        &field[..len.unwrap_or(field.len())]
    }

    /// The name of the kernel: `Linux`.
    pub fn system(&self) -> &[u8] {
        self.field(0)
    }

    /// The host name, of the UTS namespace of the caller: what
    /// [`set_host_name`](super::set_host_name) sets.
    pub fn host_name(&self) -> &[u8] {
        self.field(1)
    }

    /// The release of the kernel, such as `6.12.9-amd64`.
    pub fn release(&self) -> &[u8] {
        self.field(2)
    }

    /// The version of the kernel: its build number and date.
    pub fn version(&self) -> &[u8] {
        self.field(3)
    }

    /// The architecture the kernel runs the caller as (`x86_64`, `i686`,
    /// `aarch64`, `armv7l`, `riscv64`...): that of the kernel, unless the
    /// process has a personality that says otherwise, or runs under an
    /// emulator, which answers for the machine it emulates.
    pub fn machine(&self) -> &[u8] {
        self.field(4)
    }

    /// The NIS domain name of the UTS namespace of the caller, `(none)`
    /// on most systems. Not the DNS domain.
    pub fn domain_name(&self) -> &[u8] {
        self.field(5)
    }
}

impl core::fmt::Debug for SystemName {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut debug = f.debug_struct("SystemName");
        let fields: [(&str, &[u8]); 6] = [
            ("system", self.system()),
            ("host_name", self.host_name()),
            ("release", self.release()),
            ("version", self.version()),
            ("machine", self.machine()),
            ("domain_name", self.domain_name()),
        ];
        for (name, value) in fields {
            debug.field(name, &format_args!("\"{}\"", value.escape_ascii()));
        }
        debug.finish()
    }
}

/// The names of the system: `uname`. The host name is the one of the UTS
/// namespace the calling thread is in.
pub fn system_name() -> Result<SystemName> {
    sys::process::cred::uname().map(SystemName)
}