syd 3.56.0

rock-solid application kernel
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
/*!
A pure-Rust library to work with Linux capabilities.

It provides support for manipulating capabilities available on modern Linux
kernels. It supports traditional POSIX sets (Effective, Inheritable, Permitted)
as well as Linux-specific Ambient and Bounding capabilities sets.

```rust
type ExResult<T> = Result<T, Box<dyn std::error::Error + 'static>>;

fn manipulate_caps() -> ExResult<()> {
    use syd::caps::{Capability, Capabilities, CapSet};

    if syd::caps::has_cap(None, CapSet::Permitted, Capability::CAP_SYS_NICE)? {
        syd::caps::drop(None, CapSet::Effective, Capability::CAP_SYS_NICE)?;
        let effective = syd::caps::read(None, CapSet::Effective)?;
        assert_eq!(effective.contains(Capabilities::CAP_SYS_NICE), false);

        syd::caps::clear(None, CapSet::Effective)?;
        let cleared = syd::caps::read(None, CapSet::Effective)?;
        assert_eq!(cleared.is_empty(), true);
    };

    Ok(())
}
```
!*/

pub mod errors;
pub mod runtime;
pub mod securebits;

// Implementation of Bounding set.
mod ambient;
// Implementation of POSIX sets.
mod base;
// Implementation of Bounding set.
mod bounding;
// All kernel-related constants.
mod nr;

use nix::errno::Errno;

use crate::caps::errors::CapsError;

/// Linux capabilities sets.
///
/// All capabilities sets supported by Linux, including standard
/// POSIX and custom ones. See `capabilities(7)`.
#[derive(Debug, Clone, Copy)]
pub enum CapSet {
    /// Ambient capabilities set (from Linux 4.3).
    Ambient,
    /// Bounding capabilities set (from Linux 2.6.25)
    Bounding,
    /// Effective capabilities set (from POSIX)
    Effective,
    /// Inheritable capabilities set (from POSIX)
    Inheritable,
    /// Permitted capabilities set (from POSIX)
    Permitted,
}

#[cfg(feature = "oci")]
use oci_spec::runtime::Capability as SpecCapability;

/// Linux capabilities.
///
/// All capabilities supported by Linux, including standard
/// POSIX and custom ones. See `capabilities(7)`.
#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
pub struct Capability(u8);

impl Capability {
    /// `CAP_CHOWN` (from POSIX)
    pub const CAP_CHOWN: Self = Self(nr::CAP_CHOWN);
    /// `CAP_DAC_OVERRIDE` (from POSIX)
    pub const CAP_DAC_OVERRIDE: Self = Self(nr::CAP_DAC_OVERRIDE);
    /// `CAP_DAC_READ_SEARCH` (from POSIX)
    pub const CAP_DAC_READ_SEARCH: Self = Self(nr::CAP_DAC_READ_SEARCH);
    /// `CAP_FOWNER` (from POSIX)
    pub const CAP_FOWNER: Self = Self(nr::CAP_FOWNER);
    /// `CAP_FSETID` (from POSIX)
    pub const CAP_FSETID: Self = Self(nr::CAP_FSETID);
    /// `CAP_KILL` (from POSIX)
    pub const CAP_KILL: Self = Self(nr::CAP_KILL);
    /// `CAP_SETGID` (from POSIX)
    pub const CAP_SETGID: Self = Self(nr::CAP_SETGID);
    /// `CAP_SETUID` (from POSIX)
    pub const CAP_SETUID: Self = Self(nr::CAP_SETUID);
    /// `CAP_SETPCAP` (from Linux)
    pub const CAP_SETPCAP: Self = Self(nr::CAP_SETPCAP);
    pub const CAP_LINUX_IMMUTABLE: Self = Self(nr::CAP_LINUX_IMMUTABLE);
    pub const CAP_NET_BIND_SERVICE: Self = Self(nr::CAP_NET_BIND_SERVICE);
    pub const CAP_NET_BROADCAST: Self = Self(nr::CAP_NET_BROADCAST);
    pub const CAP_NET_ADMIN: Self = Self(nr::CAP_NET_ADMIN);
    pub const CAP_NET_RAW: Self = Self(nr::CAP_NET_RAW);
    pub const CAP_IPC_LOCK: Self = Self(nr::CAP_IPC_LOCK);
    pub const CAP_IPC_OWNER: Self = Self(nr::CAP_IPC_OWNER);
    /// `CAP_SYS_MODULE` (from Linux)
    pub const CAP_SYS_MODULE: Self = Self(nr::CAP_SYS_MODULE);
    /// `CAP_SYS_RAWIO` (from Linux)
    pub const CAP_SYS_RAWIO: Self = Self(nr::CAP_SYS_RAWIO);
    /// `CAP_SYS_CHROOT` (from Linux)
    pub const CAP_SYS_CHROOT: Self = Self(nr::CAP_SYS_CHROOT);
    /// `CAP_SYS_PTRACE` (from Linux)
    pub const CAP_SYS_PTRACE: Self = Self(nr::CAP_SYS_PTRACE);
    /// `CAP_SYS_PACCT` (from Linux)
    pub const CAP_SYS_PACCT: Self = Self(nr::CAP_SYS_PACCT);
    /// `CAP_SYS_ADMIN` (from Linux)
    pub const CAP_SYS_ADMIN: Self = Self(nr::CAP_SYS_ADMIN);
    /// `CAP_SYS_BOOT` (from Linux)
    pub const CAP_SYS_BOOT: Self = Self(nr::CAP_SYS_BOOT);
    /// `CAP_SYS_NICE` (from Linux)
    pub const CAP_SYS_NICE: Self = Self(nr::CAP_SYS_NICE);
    /// `CAP_SYS_RESOURCE` (from Linux)
    pub const CAP_SYS_RESOURCE: Self = Self(nr::CAP_SYS_RESOURCE);
    /// `CAP_SYS_TIME` (from Linux)
    pub const CAP_SYS_TIME: Self = Self(nr::CAP_SYS_TIME);
    /// `CAP_SYS_TTY_CONFIG` (from Linux)
    pub const CAP_SYS_TTY_CONFIG: Self = Self(nr::CAP_SYS_TTY_CONFIG);
    /// `CAP_SYS_MKNOD` (from Linux, >= 2.4)
    pub const CAP_MKNOD: Self = Self(nr::CAP_MKNOD);
    /// `CAP_LEASE` (from Linux, >= 2.4)
    pub const CAP_LEASE: Self = Self(nr::CAP_LEASE);
    pub const CAP_AUDIT_WRITE: Self = Self(nr::CAP_AUDIT_WRITE);
    /// `CAP_AUDIT_CONTROL` (from Linux, >= 2.6.11)
    pub const CAP_AUDIT_CONTROL: Self = Self(nr::CAP_AUDIT_CONTROL);
    pub const CAP_SETFCAP: Self = Self(nr::CAP_SETFCAP);
    pub const CAP_MAC_OVERRIDE: Self = Self(nr::CAP_MAC_OVERRIDE);
    pub const CAP_MAC_ADMIN: Self = Self(nr::CAP_MAC_ADMIN);
    /// `CAP_SYSLOG` (from Linux, >= 2.6.37)
    pub const CAP_SYSLOG: Self = Self(nr::CAP_SYSLOG);
    /// `CAP_WAKE_ALARM` (from Linux, >= 3.0)
    pub const CAP_WAKE_ALARM: Self = Self(nr::CAP_WAKE_ALARM);
    pub const CAP_BLOCK_SUSPEND: Self = Self(nr::CAP_BLOCK_SUSPEND);
    /// `CAP_AUDIT_READ` (from Linux, >= 3.16).
    pub const CAP_AUDIT_READ: Self = Self(nr::CAP_AUDIT_READ);
    /// `CAP_PERFMON` (from Linux, >= 5.8).
    pub const CAP_PERFMON: Self = Self(nr::CAP_PERFMON);
    /// `CAP_BPF` (from Linux, >= 5.8).
    pub const CAP_BPF: Self = Self(nr::CAP_BPF);
    /// `CAP_CHECKPOINT_RESTORE` (from Linux, >= 5.9).
    pub const CAP_CHECKPOINT_RESTORE: Self = Self(nr::CAP_CHECKPOINT_RESTORE);

    /// Create a capability from its raw index.
    pub const fn from_index(index: u8) -> Self {
        Self(index)
    }
}

impl std::fmt::Display for Capability {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let name = match *self {
            Capability::CAP_CHOWN => "cap_chown",
            Capability::CAP_DAC_OVERRIDE => "cap_dac_override",
            Capability::CAP_DAC_READ_SEARCH => "cap_dac_read_search",
            Capability::CAP_FOWNER => "cap_fowner",
            Capability::CAP_FSETID => "cap_fsetid",
            Capability::CAP_KILL => "cap_kill",
            Capability::CAP_SETGID => "cap_setgid",
            Capability::CAP_SETUID => "cap_setuid",
            Capability::CAP_SETPCAP => "cap_setpcap",
            Capability::CAP_LINUX_IMMUTABLE => "cap_linux_immutable",
            Capability::CAP_NET_BIND_SERVICE => "cap_net_bind_service",
            Capability::CAP_NET_BROADCAST => "cap_net_broadcast",
            Capability::CAP_NET_ADMIN => "cap_net_admin",
            Capability::CAP_NET_RAW => "cap_net_raw",
            Capability::CAP_IPC_LOCK => "cap_ipc_lock",
            Capability::CAP_IPC_OWNER => "cap_ipc_owner",
            Capability::CAP_SYS_MODULE => "cap_sys_module",
            Capability::CAP_SYS_RAWIO => "cap_sys_rawio",
            Capability::CAP_SYS_CHROOT => "cap_sys_chroot",
            Capability::CAP_SYS_PTRACE => "cap_sys_ptrace",
            Capability::CAP_SYS_PACCT => "cap_sys_pacct",
            Capability::CAP_SYS_ADMIN => "cap_sys_admin",
            Capability::CAP_SYS_BOOT => "cap_sys_boot",
            Capability::CAP_SYS_NICE => "cap_sys_nice",
            Capability::CAP_SYS_RESOURCE => "cap_sys_resource",
            Capability::CAP_SYS_TIME => "cap_sys_time",
            Capability::CAP_SYS_TTY_CONFIG => "cap_sys_tty_config",
            Capability::CAP_MKNOD => "cap_mknod",
            Capability::CAP_LEASE => "cap_lease",
            Capability::CAP_AUDIT_WRITE => "cap_audit_write",
            Capability::CAP_AUDIT_CONTROL => "cap_audit_control",
            Capability::CAP_SETFCAP => "cap_setfcap",
            Capability::CAP_MAC_OVERRIDE => "cap_mac_override",
            Capability::CAP_MAC_ADMIN => "cap_mac_admin",
            Capability::CAP_SYSLOG => "cap_syslog",
            Capability::CAP_WAKE_ALARM => "cap_wake_alarm",
            Capability::CAP_BLOCK_SUSPEND => "cap_block_suspend",
            Capability::CAP_AUDIT_READ => "cap_audit_read",
            Capability::CAP_PERFMON => "cap_perfmon",
            Capability::CAP_BPF => "cap_bpf",
            Capability::CAP_CHECKPOINT_RESTORE => "cap_checkpoint_restore",
            _ => return write!(f, "cap_{}", self.0),
        };
        write!(f, "{name}")
    }
}

impl std::str::FromStr for Capability {
    type Err = CapsError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "cap_chown" => Ok(Capability::CAP_CHOWN),
            "cap_dac_override" => Ok(Capability::CAP_DAC_OVERRIDE),
            "cap_dac_read_search" => Ok(Capability::CAP_DAC_READ_SEARCH),
            "cap_fowner" => Ok(Capability::CAP_FOWNER),
            "cap_fsetid" => Ok(Capability::CAP_FSETID),
            "cap_kill" => Ok(Capability::CAP_KILL),
            "cap_setgid" => Ok(Capability::CAP_SETGID),
            "cap_setuid" => Ok(Capability::CAP_SETUID),
            "cap_setpcap" => Ok(Capability::CAP_SETPCAP),
            "cap_linux_immutable" => Ok(Capability::CAP_LINUX_IMMUTABLE),
            "cap_net_bind_service" => Ok(Capability::CAP_NET_BIND_SERVICE),
            "cap_net_broadcast" => Ok(Capability::CAP_NET_BROADCAST),
            "cap_net_admin" => Ok(Capability::CAP_NET_ADMIN),
            "cap_net_raw" => Ok(Capability::CAP_NET_RAW),
            "cap_ipc_lock" => Ok(Capability::CAP_IPC_LOCK),
            "cap_ipc_owner" => Ok(Capability::CAP_IPC_OWNER),
            "cap_sys_module" => Ok(Capability::CAP_SYS_MODULE),
            "cap_sys_rawio" => Ok(Capability::CAP_SYS_RAWIO),
            "cap_sys_chroot" => Ok(Capability::CAP_SYS_CHROOT),
            "cap_sys_ptrace" => Ok(Capability::CAP_SYS_PTRACE),
            "cap_sys_pacct" => Ok(Capability::CAP_SYS_PACCT),
            "cap_sys_admin" => Ok(Capability::CAP_SYS_ADMIN),
            "cap_sys_boot" => Ok(Capability::CAP_SYS_BOOT),
            "cap_sys_nice" => Ok(Capability::CAP_SYS_NICE),
            "cap_sys_resource" => Ok(Capability::CAP_SYS_RESOURCE),
            "cap_sys_time" => Ok(Capability::CAP_SYS_TIME),
            "cap_sys_tty_config" => Ok(Capability::CAP_SYS_TTY_CONFIG),
            "cap_mknod" => Ok(Capability::CAP_MKNOD),
            "cap_lease" => Ok(Capability::CAP_LEASE),
            "cap_audit_write" => Ok(Capability::CAP_AUDIT_WRITE),
            "cap_audit_control" => Ok(Capability::CAP_AUDIT_CONTROL),
            "cap_setfcap" => Ok(Capability::CAP_SETFCAP),
            "cap_mac_override" => Ok(Capability::CAP_MAC_OVERRIDE),
            "cap_mac_admin" => Ok(Capability::CAP_MAC_ADMIN),
            "cap_syslog" => Ok(Capability::CAP_SYSLOG),
            "cap_wake_alarm" => Ok(Capability::CAP_WAKE_ALARM),
            "cap_block_suspend" => Ok(Capability::CAP_BLOCK_SUSPEND),
            "cap_audit_read" => Ok(Capability::CAP_AUDIT_READ),
            "cap_perfmon" => Ok(Capability::CAP_PERFMON),
            "cap_bpf" => Ok(Capability::CAP_BPF),
            "cap_checkpoint_restore" => Ok(Capability::CAP_CHECKPOINT_RESTORE),
            _ => Err(CapsError(Errno::EINVAL)),
        }
    }
}

#[cfg(feature = "oci")]
impl Capability {
    pub fn spec(&self) -> SpecCapability {
        match *self {
            Self::CAP_CHOWN => SpecCapability::Chown,
            Self::CAP_DAC_OVERRIDE => SpecCapability::DacOverride,
            Self::CAP_DAC_READ_SEARCH => SpecCapability::DacReadSearch,
            Self::CAP_FOWNER => SpecCapability::Fowner,
            Self::CAP_FSETID => SpecCapability::Fsetid,
            Self::CAP_KILL => SpecCapability::Kill,
            Self::CAP_SETGID => SpecCapability::Setgid,
            Self::CAP_SETUID => SpecCapability::Setuid,
            Self::CAP_SETPCAP => SpecCapability::Setpcap,
            Self::CAP_LINUX_IMMUTABLE => SpecCapability::LinuxImmutable,
            Self::CAP_NET_BIND_SERVICE => SpecCapability::NetBindService,
            Self::CAP_NET_BROADCAST => SpecCapability::NetBroadcast,
            Self::CAP_NET_ADMIN => SpecCapability::NetAdmin,
            Self::CAP_NET_RAW => SpecCapability::NetRaw,
            Self::CAP_IPC_LOCK => SpecCapability::IpcLock,
            Self::CAP_IPC_OWNER => SpecCapability::IpcOwner,
            Self::CAP_SYS_MODULE => SpecCapability::SysModule,
            Self::CAP_SYS_RAWIO => SpecCapability::SysRawio,
            Self::CAP_SYS_CHROOT => SpecCapability::SysChroot,
            Self::CAP_SYS_PTRACE => SpecCapability::SysPtrace,
            Self::CAP_SYS_PACCT => SpecCapability::SysPacct,
            Self::CAP_SYS_ADMIN => SpecCapability::SysAdmin,
            Self::CAP_SYS_BOOT => SpecCapability::SysBoot,
            Self::CAP_SYS_NICE => SpecCapability::SysNice,
            Self::CAP_SYS_RESOURCE => SpecCapability::SysResource,
            Self::CAP_SYS_TIME => SpecCapability::SysTime,
            Self::CAP_SYS_TTY_CONFIG => SpecCapability::SysTtyConfig,
            Self::CAP_MKNOD => SpecCapability::Mknod,
            Self::CAP_LEASE => SpecCapability::Lease,
            Self::CAP_AUDIT_WRITE => SpecCapability::AuditWrite,
            Self::CAP_AUDIT_CONTROL => SpecCapability::AuditControl,
            Self::CAP_SETFCAP => SpecCapability::Setfcap,
            Self::CAP_MAC_OVERRIDE => SpecCapability::MacOverride,
            Self::CAP_MAC_ADMIN => SpecCapability::MacAdmin,
            Self::CAP_SYSLOG => SpecCapability::Syslog,
            Self::CAP_WAKE_ALARM => SpecCapability::WakeAlarm,
            Self::CAP_BLOCK_SUSPEND => SpecCapability::BlockSuspend,
            Self::CAP_AUDIT_READ => SpecCapability::AuditRead,
            Self::CAP_PERFMON => SpecCapability::Perfmon,
            Self::CAP_BPF => SpecCapability::Bpf,
            Self::CAP_CHECKPOINT_RESTORE => SpecCapability::CheckpointRestore,
            _ => unreachable!("BUG: Undefined capability CAP_{}, report a bug!", self.0),
        }
    }
}

impl TryFrom<Capabilities> for Capability {
    type Error = CapsError;

    fn try_from(caps: Capabilities) -> Result<Self, Self::Error> {
        let bits = caps.bits();

        // Capabilities must have exactly one bit set.
        if bits == 0 || (bits & (bits - 1)) != 0 {
            return Err(CapsError(Errno::EINVAL));
        }

        let idx = u8::try_from(bits.trailing_zeros()).or(Err(CapsError(Errno::EINVAL)))?;

        Ok(Capability(idx))
    }
}

impl From<Capability> for Capabilities {
    #[inline]
    fn from(c: Capability) -> Self {
        Capabilities::from_bits_retain(c.bitmask())
    }
}

impl Capability {
    /// Returns the bitmask corresponding to this capability value.
    pub const fn bitmask(self) -> u64 {
        1u64 << self.0
    }

    /// Returns the index of this capability, i.e. its kernel-defined value.
    pub const fn index(self) -> u8 {
        self.0
    }
}

/// A compact bitmask of Linux capabilities.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub struct Capabilities {
    val: u64,
}

impl Capabilities {
    pub const CAP_CHOWN: Self = Self {
        val: Capability::CAP_CHOWN.bitmask(),
    };
    pub const CAP_DAC_OVERRIDE: Self = Self {
        val: Capability::CAP_DAC_OVERRIDE.bitmask(),
    };
    pub const CAP_DAC_READ_SEARCH: Self = Self {
        val: Capability::CAP_DAC_READ_SEARCH.bitmask(),
    };
    pub const CAP_FOWNER: Self = Self {
        val: Capability::CAP_FOWNER.bitmask(),
    };
    pub const CAP_FSETID: Self = Self {
        val: Capability::CAP_FSETID.bitmask(),
    };
    pub const CAP_KILL: Self = Self {
        val: Capability::CAP_KILL.bitmask(),
    };
    pub const CAP_SETGID: Self = Self {
        val: Capability::CAP_SETGID.bitmask(),
    };
    pub const CAP_SETUID: Self = Self {
        val: Capability::CAP_SETUID.bitmask(),
    };
    pub const CAP_SETPCAP: Self = Self {
        val: Capability::CAP_SETPCAP.bitmask(),
    };
    pub const CAP_LINUX_IMMUTABLE: Self = Self {
        val: Capability::CAP_LINUX_IMMUTABLE.bitmask(),
    };
    pub const CAP_NET_BIND_SERVICE: Self = Self {
        val: Capability::CAP_NET_BIND_SERVICE.bitmask(),
    };
    pub const CAP_NET_BROADCAST: Self = Self {
        val: Capability::CAP_NET_BROADCAST.bitmask(),
    };
    pub const CAP_NET_ADMIN: Self = Self {
        val: Capability::CAP_NET_ADMIN.bitmask(),
    };
    pub const CAP_NET_RAW: Self = Self {
        val: Capability::CAP_NET_RAW.bitmask(),
    };
    pub const CAP_IPC_LOCK: Self = Self {
        val: Capability::CAP_IPC_LOCK.bitmask(),
    };
    pub const CAP_IPC_OWNER: Self = Self {
        val: Capability::CAP_IPC_OWNER.bitmask(),
    };
    pub const CAP_SYS_MODULE: Self = Self {
        val: Capability::CAP_SYS_MODULE.bitmask(),
    };
    pub const CAP_SYS_RAWIO: Self = Self {
        val: Capability::CAP_SYS_RAWIO.bitmask(),
    };
    pub const CAP_SYS_CHROOT: Self = Self {
        val: Capability::CAP_SYS_CHROOT.bitmask(),
    };
    pub const CAP_SYS_PTRACE: Self = Self {
        val: Capability::CAP_SYS_PTRACE.bitmask(),
    };
    pub const CAP_SYS_PACCT: Self = Self {
        val: Capability::CAP_SYS_PACCT.bitmask(),
    };
    pub const CAP_SYS_ADMIN: Self = Self {
        val: Capability::CAP_SYS_ADMIN.bitmask(),
    };
    pub const CAP_SYS_BOOT: Self = Self {
        val: Capability::CAP_SYS_BOOT.bitmask(),
    };
    pub const CAP_SYS_NICE: Self = Self {
        val: Capability::CAP_SYS_NICE.bitmask(),
    };
    pub const CAP_SYS_RESOURCE: Self = Self {
        val: Capability::CAP_SYS_RESOURCE.bitmask(),
    };
    pub const CAP_SYS_TIME: Self = Self {
        val: Capability::CAP_SYS_TIME.bitmask(),
    };
    pub const CAP_SYS_TTY_CONFIG: Self = Self {
        val: Capability::CAP_SYS_TTY_CONFIG.bitmask(),
    };
    pub const CAP_MKNOD: Self = Self {
        val: Capability::CAP_MKNOD.bitmask(),
    };
    pub const CAP_LEASE: Self = Self {
        val: Capability::CAP_LEASE.bitmask(),
    };
    pub const CAP_AUDIT_WRITE: Self = Self {
        val: Capability::CAP_AUDIT_WRITE.bitmask(),
    };
    pub const CAP_AUDIT_CONTROL: Self = Self {
        val: Capability::CAP_AUDIT_CONTROL.bitmask(),
    };
    pub const CAP_SETFCAP: Self = Self {
        val: Capability::CAP_SETFCAP.bitmask(),
    };
    pub const CAP_MAC_OVERRIDE: Self = Self {
        val: Capability::CAP_MAC_OVERRIDE.bitmask(),
    };
    pub const CAP_MAC_ADMIN: Self = Self {
        val: Capability::CAP_MAC_ADMIN.bitmask(),
    };
    pub const CAP_SYSLOG: Self = Self {
        val: Capability::CAP_SYSLOG.bitmask(),
    };
    pub const CAP_WAKE_ALARM: Self = Self {
        val: Capability::CAP_WAKE_ALARM.bitmask(),
    };
    pub const CAP_BLOCK_SUSPEND: Self = Self {
        val: Capability::CAP_BLOCK_SUSPEND.bitmask(),
    };
    pub const CAP_AUDIT_READ: Self = Self {
        val: Capability::CAP_AUDIT_READ.bitmask(),
    };
    pub const CAP_PERFMON: Self = Self {
        val: Capability::CAP_PERFMON.bitmask(),
    };
    pub const CAP_BPF: Self = Self {
        val: Capability::CAP_BPF.bitmask(),
    };
    pub const CAP_CHECKPOINT_RESTORE: Self = Self {
        val: Capability::CAP_CHECKPOINT_RESTORE.bitmask(),
    };
}

impl Capabilities {
    /// Returns empty set.
    pub const fn empty() -> Self {
        Self { val: 0 }
    }

    /// Returns set of all capabilities supported by the running Linux kernel.
    pub fn all() -> Result<Self, CapsError> {
        runtime::procfs_all_supported(None).or_else(|_| runtime::thread_all_supported())
    }

    /// Returns the raw capability value.
    pub const fn bits(self) -> u64 {
        self.val
    }

    /// Builds a set from raw bits.
    pub const fn from_bits_retain(bits: u64) -> Self {
        Self { val: bits }
    }

    /// Returns true if the set is empty.
    pub const fn is_empty(self) -> bool {
        self.val == 0
    }

    /// Returns true if `self` contains every capability in `other`.
    pub const fn contains(self, other: Self) -> bool {
        self.val & other.val == other.val
    }

    /// Returns true if `self` and `other` share any capability.
    pub const fn intersects(self, other: Self) -> bool {
        self.val & other.val != 0
    }

    /// Adds the capabilities in `other`.
    pub fn insert(&mut self, other: Self) {
        self.val |= other.val;
    }

    /// Removes the capabilities in `other`.
    pub fn remove(&mut self, other: Self) {
        self.val &= !other.val;
    }

    /// Iterates individual capabilities in the set.
    pub fn iter(self) -> CapabilitiesIter {
        CapabilitiesIter { val: self.val }
    }
}

/// Iterator over individual capabilities of a [`Capabilities`] set.
pub struct CapabilitiesIter {
    val: u64,
}

impl Iterator for CapabilitiesIter {
    type Item = Capabilities;

    fn next(&mut self) -> Option<Capabilities> {
        if self.val == 0 {
            return None;
        }
        let bit = self.val & self.val.wrapping_neg();
        self.val &= !bit;
        Some(Capabilities { val: bit })
    }
}

impl IntoIterator for Capabilities {
    type Item = Capabilities;
    type IntoIter = CapabilitiesIter;

    fn into_iter(self) -> CapabilitiesIter {
        self.iter()
    }
}

impl std::ops::BitAnd for Capabilities {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self {
        Self {
            val: self.val & rhs.val,
        }
    }
}

impl std::ops::BitOr for Capabilities {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self {
        Self {
            val: self.val | rhs.val,
        }
    }
}

impl std::ops::BitXor for Capabilities {
    type Output = Self;
    fn bitxor(self, rhs: Self) -> Self {
        Self {
            val: self.val ^ rhs.val,
        }
    }
}

impl std::ops::Not for Capabilities {
    type Output = Self;
    fn not(self) -> Self {
        Self { val: !self.val }
    }
}

impl std::ops::BitOrAssign for Capabilities {
    fn bitor_assign(&mut self, rhs: Self) {
        self.val |= rhs.val;
    }
}

impl std::ops::BitAndAssign for Capabilities {
    fn bitand_assign(&mut self, rhs: Self) {
        self.val &= rhs.val;
    }
}

/// Check if a thread contains a capability in a set.
///
/// Check if set `cset` for thread `tid` contains capability `cap`.
/// If `tid` is `None`, this operates on current thread (tid=0).
/// It cannot check Ambient or Bounding capabilities of other processes.
pub fn has_cap(tid: Option<i32>, cset: CapSet, cap: Capability) -> Result<bool, CapsError> {
    let t = tid.unwrap_or(0);
    match cset {
        CapSet::Ambient if t == 0 => ambient::has_cap(cap),
        CapSet::Bounding if t == 0 => bounding::has_cap(cap),
        CapSet::Effective | CapSet::Inheritable | CapSet::Permitted => base::has_cap(t, cset, cap),
        _ => Err(CapsError(Errno::EOPNOTSUPP)),
    }
}

/// Return all capabilities in a set for a thread.
///
/// Return current content of set `cset` for thread `tid`.
/// If `tid` is `None`, this operates on current thread (tid=0).
/// It cannot read Ambient or Bounding capabilities of other processes.
pub fn read(tid: Option<i32>, cset: CapSet) -> Result<Capabilities, CapsError> {
    let t = tid.unwrap_or(0);
    match cset {
        CapSet::Ambient if t == 0 => ambient::read(),
        CapSet::Bounding if t == 0 => bounding::read(),
        CapSet::Effective | CapSet::Inheritable | CapSet::Permitted => base::read(t, cset),
        _ => Err(CapsError(Errno::EOPNOTSUPP)),
    }
}

/// Set a capability set for a thread to a new value.
///
/// All and only capabilities in `value` will be set for set `cset` for thread `tid`.
/// If `tid` is `None`, this operates on current thread (tid=0).
/// It cannot manipulate Ambient set of other processes.
/// Capabilities cannot be set in Bounding set.
pub fn set(tid: Option<i32>, cset: CapSet, value: Capabilities) -> Result<(), CapsError> {
    let t = tid.unwrap_or(0);
    match cset {
        CapSet::Ambient if t == 0 => ambient::set(value),
        CapSet::Effective | CapSet::Inheritable | CapSet::Permitted => base::set(t, cset, value),
        _ => Err(CapsError(Errno::EOPNOTSUPP)),
    }
}

/// Set effective, permitted and inheritable capabilities at once.
pub fn set_all(
    tid: Option<i32>,
    eff: Capabilities,
    perm: Capabilities,
    inh: Capabilities,
) -> Result<(), CapsError> {
    base::set_epi(tid.unwrap_or(0), eff, perm, inh)
}

/// Clear all capabilities in a set for a thread.
///
/// All capabilities will be cleared from set `cset` for thread `tid`.
/// If `tid` is `None`, this operates on current thread (tid=0).
/// It cannot manipulate Ambient or Bounding set of other processes.
pub fn clear(tid: Option<i32>, cset: CapSet) -> Result<(), CapsError> {
    let t = tid.unwrap_or(0);
    match cset {
        CapSet::Ambient if t == 0 => ambient::clear(),
        CapSet::Bounding if t == 0 => bounding::clear(),
        CapSet::Effective | CapSet::Permitted | CapSet::Inheritable => base::clear(t, cset),
        _ => Err(CapsError(Errno::EOPNOTSUPP)),
    }
}

/// Raise a single capability in a set for a thread.
///
/// Capabilities `cap` will be raised from set `cset` of thread `tid`.
/// If `tid` is `None`, this operates on current thread (tid=0).
/// It cannot manipulate Ambient set of other processes.
/// Capabilities cannot be raised in Bounding set.
pub fn raise(tid: Option<i32>, cset: CapSet, cap: Capability) -> Result<(), CapsError> {
    let t = tid.unwrap_or(0);
    match cset {
        CapSet::Ambient if t == 0 => ambient::raise(cap),
        CapSet::Effective | CapSet::Permitted | CapSet::Inheritable => base::raise(t, cset, cap),
        _ => Err(CapsError(Errno::EOPNOTSUPP)),
    }
}

/// Drop a single capability from a set for a thread.
///
/// Capabilities `cap` will be dropped from set `cset` of thread `tid`.
/// If `tid` is `None`, this operates on current thread (tid=0).
/// It cannot manipulate Ambient and Bounding sets of other processes.
pub fn drop(tid: Option<i32>, cset: CapSet, cap: Capability) -> Result<(), CapsError> {
    let t = tid.unwrap_or(0);
    match cset {
        CapSet::Ambient if t == 0 => ambient::drop(cap),
        CapSet::Bounding if t == 0 => bounding::drop(cap),
        CapSet::Effective | CapSet::Permitted | CapSet::Inheritable => base::drop(t, cset, cap),
        _ => Err(CapsError(Errno::EOPNOTSUPP)),
    }
}

/// Convert an informal capability name into a canonical form.
///
/// This converts the input string to uppercase and ensures that it starts with
/// `CAP_`, prepending it if necessary. It performs no validity checks so the
/// output may not represent an actual capability. To check if it is, pass it
/// to [`from_str`].
///
/// [`from_str`]: enum.Capability.html#method.from_str
pub fn to_canonical(name: &str) -> String {
    let uppername = name.to_ascii_uppercase();
    if uppername.starts_with("CAP_") {
        uppername
    } else {
        ["CAP_", &uppername].concat()
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;

    #[test]
    fn test_caps_1() {
        let last = Capability::CAP_CHECKPOINT_RESTORE.index();
        assert!(last > 0);
        for idx in 0..=last {
            let cap = Capability::from_index(idx);
            let name = cap.to_string();
            let parsed: Capability = name.parse().unwrap();
            assert_eq!(cap, parsed);
        }
    }

    #[test]
    fn test_caps_2() {
        let mut caps = Capabilities::empty();
        assert!(caps.is_empty());
        assert!(!caps.contains(Capabilities::CAP_CHOWN));

        caps.insert(Capabilities::CAP_CHOWN);
        caps.insert(Capabilities::CAP_NET_RAW);
        assert!(!caps.is_empty());
        assert!(caps.contains(Capabilities::CAP_CHOWN));
        assert!(caps.contains(Capabilities::CAP_CHOWN | Capabilities::CAP_NET_RAW));
        assert!(!caps.contains(Capabilities::CAP_SYS_ADMIN));
        assert!(caps.intersects(Capabilities::CAP_CHOWN | Capabilities::CAP_SYS_ADMIN));

        caps.remove(Capabilities::CAP_CHOWN);
        assert!(!caps.contains(Capabilities::CAP_CHOWN));
        assert!(caps.contains(Capabilities::CAP_NET_RAW));
    }

    #[test]
    fn test_caps_3() {
        let a = Capabilities::CAP_CHOWN | Capabilities::CAP_KILL;
        let b = Capabilities::CAP_KILL | Capabilities::CAP_SYS_ADMIN;

        assert_eq!((a & b).bits(), Capabilities::CAP_KILL.bits());
        assert_eq!((a ^ b).bits(), a.bits() ^ b.bits());
        assert_eq!((a & !b).bits(), Capabilities::CAP_CHOWN.bits());
        assert_eq!(Capabilities::from_bits_retain(a.bits()), a);

        let mut got: Vec<u8> = a
            .iter()
            .filter_map(|c| Capability::try_from(c).ok())
            .map(|c| c.index())
            .collect();
        got.sort_unstable();
        assert_eq!(
            got,
            vec![Capability::CAP_CHOWN.index(), Capability::CAP_KILL.index()]
        );
        assert_eq!(Capabilities::empty().iter().count(), 0);
    }

    #[test]
    fn test_caps_4() {
        let p1 = Capability::from_str("CAP_FOO");
        let p1_err = p1.unwrap_err();
        assert_eq!(p1_err.0, Errno::EINVAL);
        let p2: Result<Capability, CapsError> = "CAP_BAR".parse();
        assert!(p2.is_err());
    }

    #[test]
    fn test_caps_5() {
        let p1 = "foo";
        assert!(Capability::from_str(&to_canonical(p1)).is_err());
        let p2 = "sys_admin";
        assert!(Capability::from_str(&to_canonical(p2)).is_ok());
        let p3 = "CAP_SYS_CHROOT";
        assert!(Capability::from_str(&to_canonical(p3)).is_ok());
    }

    #[test]
    fn test_caps_6() {
        assert_eq!(to_canonical("net_admin"), "CAP_NET_ADMIN");
    }

    #[test]
    fn test_caps_7() {
        assert_eq!(to_canonical("CAP_NET_ADMIN"), "CAP_NET_ADMIN");
    }

    #[test]
    fn test_caps_8() {
        assert_eq!(to_canonical("cap_sys_chroot"), "CAP_SYS_CHROOT");
    }

    #[test]
    fn test_caps_9() {
        assert_eq!(
            Capability::from_str("CAP_CHOWN").unwrap(),
            Capability::CAP_CHOWN
        );
    }

    #[test]
    fn test_caps_10() {
        assert_eq!(
            Capability::from_str("CAP_NET_RAW").unwrap(),
            Capability::CAP_NET_RAW
        );
    }

    #[test]
    fn test_caps_11() {
        assert!(Capability::from_str("INVALID").is_err());
    }

    #[test]
    fn test_caps_12() {
        assert_eq!(Capability::CAP_CHOWN.to_string(), "cap_chown");
    }

    #[test]
    fn test_caps_13() {
        assert_eq!(Capability::CAP_NET_RAW.to_string(), "cap_net_raw");
    }

    #[test]
    fn test_caps_14() {
        assert_eq!(Capability::CAP_SYS_ADMIN.to_string(), "cap_sys_admin");
    }

    #[test]
    fn test_caps_15() {
        assert_eq!(Capability::CAP_CHOWN.bitmask(), 1u64 << 0);
    }

    #[test]
    fn test_caps_16() {
        assert_eq!(Capability::CAP_DAC_OVERRIDE.bitmask(), 1u64 << 1);
    }

    #[test]
    fn test_caps_17() {
        assert_eq!(Capability::CAP_KILL.bitmask(), 1u64 << 5);
    }

    #[test]
    fn test_caps_18() {
        assert_eq!(Capability::CAP_CHOWN.index(), 0u8);
    }

    #[test]
    fn test_caps_19() {
        assert_eq!(Capability::CAP_NET_RAW.index(), 13u8);
    }

    #[test]
    fn test_caps_20() {
        assert_eq!(Capability::CAP_SYS_ADMIN.index(), 21u8);
    }

    #[test]
    fn test_caps_21() {
        let caps = Capabilities::CAP_CHOWN;
        let cap: Capability = caps.try_into().unwrap();
        assert_eq!(cap, Capability::CAP_CHOWN);
    }

    #[test]
    fn test_caps_22() {
        let caps = Capabilities::empty();
        let result: Result<Capability, _> = caps.try_into();
        assert!(result.is_err());
    }

    #[test]
    fn test_caps_23() {
        let caps = Capabilities::CAP_CHOWN | Capabilities::CAP_DAC_OVERRIDE;
        let result: Result<Capability, _> = caps.try_into();
        assert!(result.is_err());
    }

    #[test]
    fn test_caps_24() {
        let caps: Capabilities = Capability::CAP_SYS_ADMIN.into();
        assert!(caps.contains(Capabilities::CAP_SYS_ADMIN));
    }
}