Debian Codegraph @

examples/manipulate_sys_nice.rs

raw symbols SCIP
1 //! A simple example showing how to manipulate capabilities.
2 //!
3 //! It drops and raises `CAP_SYS_NICE` to show its interaction
4 //! with `getpriority(2)`.
5 //!
6 //! This is an example ONLY: do NOT panic/unwrap/assert
7 //! in production code!
8
9 type ExResult<T> = Result<T, Box<dyn std::error::Error + 'static>>;
10
11 fn main() -> ExResult<()> {
12 use caps::{CapSet, Capability};
13
14 // Any process can lower its own priority.
15 println!("-> Current process priority is {}.", proc_nice());
16 let r = renice(19);
17 assert_eq!(r, 0);
18 println!("Lowered priority to +19.");
19 println!("-> Current process priority is {}.", proc_nice());
20
21 // Without `CAP_SYS_NICE` increasing priority is not possible.
22 let r = caps::drop(None, CapSet::Effective, Capability::CAP_SYS_NICE);
23 assert!(r.is_ok());
24 println!("Dropped CAP_SYS_NICE.");
25 let has_sys_nice = caps::has_cap(None, CapSet::Effective, Capability::CAP_SYS_NICE);
26 assert!(has_sys_nice.is_ok());
27 assert_eq!(has_sys_nice.unwrap_or(true), false);
28 let r = renice(-20);
29 assert_eq!(r, -1);
30 println!("Unprivileged, unable to raise priority to -20.");
31
32 // If `CAP_SYS_NICE` is still in permitted set, it can be raised again.
33 let perm_sys_nice = caps::has_cap(None, CapSet::Permitted, Capability::CAP_SYS_NICE);
34 assert!(perm_sys_nice.is_ok());
35 if !perm_sys_nice? {
36 return Err(
37 "Try running this again as root/sudo or with CAP_SYS_NICE file capability!".into(),
38 );
39 }
40 let r = caps::raise(None, CapSet::Effective, Capability::CAP_SYS_NICE);
41 assert!(r.is_ok());
42 println!("Raised CAP_SYS_NICE.");
43
44 // With CAP_SYS_NICE, priority can be raised further.
45 let r = renice(-20);
46 assert_eq!(r, 0);
47 println!("Privileged, raised priority to -20.");
48 println!("-> Current process priority is {}.", proc_nice());
49
50 Ok(())
51 }
52
53 #[cfg(target_env = "musl")]
54 const PRIO_PROCESS: i32 = libc::PRIO_PROCESS;
55 #[cfg(not(target_env = "musl"))]
56 const PRIO_PROCESS: u32 = libc::PRIO_PROCESS as u32;
57
58 fn renice(prio: libc::c_int) -> libc::c_int {
59 // This is not proper logic, as it does not record errno value on error.
60 unsafe { libc::setpriority(PRIO_PROCESS, 0, prio) }
61 }
62
63 fn proc_nice() -> libc::c_int {
64 // This is not proper logic, as it does not special-case -1 nor record errno.
65 let r = unsafe { libc::getpriority(PRIO_PROCESS as u32, 0) };
66 if r == -1 {
67 panic!("getpriority failed.");
68 }
69 r
70 }