### CapState Initialization Examples Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capstate.rs.html Demonstrates various ways to initialize a `CapState` struct with different combinations of permitted, effective, and inheritable capabilities. Includes examples of empty sets, single capabilities, multiple capabilities, and the negation of capability sets. ```rust CapState { permitted: capset!(Cap::SYSLOG), effective: capset!(Cap::CHOWN), inheritable: capset!(Cap::CHOWN), }, CapState { permitted: capset!(Cap::SYSLOG, Cap::CHOWN), effective: capset!(Cap::CHOWN), inheritable: capset!(Cap::CHOWN), }, CapState { permitted: capset!(Cap::SYSLOG, Cap::CHOWN), effective: capset!(Cap::SYSLOG, Cap::CHOWN), inheritable: capset!(Cap::SYSLOG, Cap::CHOWN), }, CapState { permitted: capset!(), effective: capset!(), inheritable: capset!(Cap::SYSLOG, Cap::CHOWN), }, CapState { permitted: !capset!(), effective: !capset!(), inheritable: capset!(Cap::CHOWN), }, CapState { permitted: !capset!(), effective: capset!(Cap::CHOWN), inheritable: !capset!(), }, CapState { permitted: !capset!(), effective: capset!(Cap::CHOWN), inheritable: capset!(), }, CapState { permitted: !capset!(), effective: !capset!(), inheritable: capset!( Cap::CHOWN, Cap::DAC_OVERRIDE, Cap::DAC_READ_SEARCH, Cap::FOWNER, Cap::FSETID, Cap::KILL, Cap::SETGID, Cap::SETUID, Cap::SETPCAP, Cap::LINUX_IMMUTABLE, Cap::NET_BIND_SERVICE, Cap::NET_BROADCAST, Cap::NET_ADMIN, Cap::NET_RAW, ), } ``` -------------------------------- ### Statically define CapSet Source: https://docs.rs/capctl/0.2.4/capctl/macro.capset.html Example of defining a CapSet statically using the capset macro. ```rust const CAPS: CapSet = capset!(Cap::CHOWN); ``` -------------------------------- ### Get File Capabilities for a Subdirectory Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/file.rs.html Demonstrates retrieving capabilities for a subdirectory, expecting an ENOTDIR error. ```rust assert_eq!( FileCaps::get_for_file(current_exe.join("sub")) .unwrap_err() .raw_os_error(), Some(libc::ENOTDIR) ); ``` -------------------------------- ### Create Empty CapSet Source: https://docs.rs/capctl/0.2.4/capctl/caps/struct.CapSet.html Creates a new, empty capability set. This is the starting point for managing capabilities. ```rust pub const fn empty() -> Self ``` -------------------------------- ### CapSet Initialization and Basic Operations Source: https://docs.rs/capctl/latest/src/capctl/caps/capset.rs.html Demonstrates creating an empty CapSet, clearing it, checking if it's empty, and getting its size. Useful for initializing and managing capability sets. ```rust use core::fmt; use core::iter::FromIterator; use core::ops::{ BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Sub, SubAssign, }; use super::{Cap, CAP_BITMASK, NUM_CAPS}; /// Represents a set of capabilities. /// /// Internally, this stores the set of capabilities as a bitmask, which is much more efficient than /// a `HashSet`. #[derive(Copy, Clone, Eq, Hash, PartialEq)] pub struct CapSet { pub(super) bits: u64, } impl CapSet { /// Create an empty capability set. #[inline] pub const fn empty() -> Self { Self { bits: 0 } } /// Clear all capabilities from this set. /// /// After this call, `set.is_empty()` will return `true`. #[inline] pub fn clear(&mut self) { self.bits = 0; } /// Check if this capability set is empty. #[inline] pub fn is_empty(&self) -> bool { self.bits == 0 } /// Returns the number of capabilities in this capability set. #[inline] pub fn size(&self) -> usize { self.bits.count_ones() as usize } /// Checks if a given capability is present in this set. #[inline] pub fn has(&self, cap: Cap) -> bool { self.bits & cap.to_single_bitfield() != 0 } /// Adds the given capability to this set. #[inline] pub fn add(&mut self, cap: Cap) { self.bits |= cap.to_single_bitfield(); } /// Removes the given capability from this set. #[inline] pub fn drop(&mut self, cap: Cap) { self.bits &= !cap.to_single_bitfield(); } /// If `val` is `true` the given capability is added; otherwise it is removed. pub fn set_state(&mut self, cap: Cap, val: bool) { if val { self.add(cap); } else { self.drop(cap); } } /// Adds all of the capabilities yielded by the given iterator to this set. /// /// If you want to add all the capabilities in another `CapSet`, you should use /// `set1 = set1.union(set2)` or `set1 |= set2`, NOT `set1.add_all(set2)`. pub fn add_all>(&mut self, t: T) { for cap in t.into_iter() { self.add(cap); } } /// Removes all of the capabilities yielded by the given iterator from this set. /// /// If you want to remove all the capabilities in another `CapSet`, you should use /// `set1 = set1.intersection(!set2)`, `set1 &= !set2`, or `set1 -= set2`, NOT /// `set1.drop_all(set2)`. pub fn drop_all>(&mut self, t: T) { for cap in t.into_iter() { self.drop(cap); } } /// Returns an iterator over all of the capabilities in this set. #[inline] pub fn iter(&self) -> CapSetIterator { self.into_iter() } /// Returns the union of this set and another capability set (i.e. all the capabilities that /// are in either set). #[inline] pub const fn union(&self, other: Self) -> Self { Self { bits: self.bits | other.bits, } } /// Returns the intersection of this set and another capability set (i.e. all the capabilities /// that are in both sets). #[inline] pub const fn intersection(&self, other: Self) -> Self { Self { bits: self.bits & other.bits, } } /// Return whether this set is a subset of another capability set. /// /// This returns `true` if all of the capabilities in `self` are present in `other`. #[inline] pub const fn issubset(&self, other: Self) -> bool { (self.bits & !other.bits) == 0 } /// Return whether this set is a superset of another capability set. /// /// This returns `true` if all of the capabilities in `other` are present in `self`. #[inline] pub const fn issuperset(&self, other: Self) -> bool { other.issubset(*self) } /// WARNING: This is an internal method and its signature may change in the future. Use [the /// `capset!()` macro] instead. /// /// [the `capset!()` macro]: ../macro.capset.html #[doc(hidden)] #[inline] pub const fn from_bitmask_truncate(bitmask: u64) -> Self { Self { bits: bitmask & CAP_BITMASK, } } #[inline] pub(crate) fn from_bitmasks_u32(lower: u32, upper: u32) -> Self { Self::from_bitmask_truncate(((upper as u64) << 32) | (lower as u64)) } } impl Default for CapSet { #[inline] fn default() -> Self { // This is the same as CapSet::empty() Self { bits: 0 } } } ``` -------------------------------- ### Probe Bounding Capability Set Source: https://docs.rs/capctl/0.2.4/capctl/caps/bounding/fn.probe.html Call this function to get a `CapSet` representing the capabilities currently raised in the thread's bounding set. No setup or imports are required beyond the function's own module. ```rust pub fn probe() -> CapSet ``` -------------------------------- ### Creating Capsets with the capset! Macro Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capset.rs.html Demonstrates the creation of capability sets using the `capset!` macro, including single capabilities, multiple capabilities, and empty sets. These examples are used for testing equality with collected iterators. ```rust assert_eq!(capset!(Cap::CHOWN,), [Cap::CHOWN].iter().cloned().collect()); ``` ```rust for cap in Cap::iter() { assert_eq!(capset!(cap), [cap].iter().cloned().collect()); assert_eq!(capset!(cap,), [cap].iter().cloned().collect()); } ``` ```rust assert_eq!( capset!(Cap::CHOWN, Cap::SYSLOG), [Cap::CHOWN, Cap::SYSLOG].iter().cloned().collect() ); ``` ```rust assert_eq!( capset!(Cap::CHOWN, Cap::SYSLOG,), [Cap::CHOWN, Cap::SYSLOG].iter().cloned().collect() ); ``` ```rust assert_eq!( capset!(Cap::CHOWN, Cap::SYSLOG, Cap::FOWNER), [Cap::CHOWN, Cap::SYSLOG, Cap::FOWNER] .iter() .cloned() .collect() ); ``` ```rust assert_eq!( capset!(Cap::CHOWN, Cap::SYSLOG, Cap::FOWNER,), [Cap::CHOWN, Cap::SYSLOG, Cap::FOWNER] .iter() .cloned() .collect() ); ``` ```rust const EMPTY_SET: CapSet = capset!(); assert_eq!(EMPTY_SET, CapSet::empty()); ``` ```rust const CHOWN_SET: CapSet = capset!(Cap::CHOWN); assert_eq!(CHOWN_SET, [Cap::CHOWN].iter().cloned().collect()); ``` ```rust const CHOWN_SYSLOG_SET: CapSet = capset!(Cap::CHOWN, Cap::SYSLOG,); assert_eq!( CHOWN_SYSLOG_SET, [Cap::CHOWN, Cap::SYSLOG].iter().cloned().collect() ); ``` -------------------------------- ### Example of prctl usage with error handling Source: https://docs.rs/capctl/0.2.4/src/capctl/prctl.rs.html Demonstrates how to use the prctl function and handle potential errors, specifically checking for EINVAL. ```rust match prctl::set_name("new_name") { Ok(_) => println!("Process name set successfully."), Err(e) if e.code() == libc::EINVAL => println!("Invalid argument provided."), Err(e) => panic!("Failed to set process name: {}", e), } ``` -------------------------------- ### Getting file capabilities by path Source: https://docs.rs/capctl/0.2.4/capctl/caps/struct.FileCaps.html Retrieves the capabilities associated with a file specified by its path. Returns Ok(None) if the file has no capabilities, or an error if retrieval fails. ```rust let caps = FileCaps::get_for_file("/path/to/file").unwrap(); ``` -------------------------------- ### Get and Set Current Capability State Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capstate.rs.html Retrieves the current process's capability state and demonstrates setting it. Assumes the `std` feature is enabled. ```rust let state = CapState::get_current().unwrap(); assert_eq!(state, CapState::get_for_pid(0).unwrap()); assert_eq!( state, CapState::get_for_pid(unsafe { libc::getpid() }).unwrap() ); state.set_current().unwrap(); ``` -------------------------------- ### Get File Capabilities by Path Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/file.rs.html Retrieves the capabilities associated with a file specified by its path. Returns `Ok(Some(FileCaps))` if capabilities are found, `Ok(None)` if no capabilities are attached, or `Err` on error. ```rust pub fn get_for_file>(path: P) -> io::Result> { let mut data = [0; sys::XATTR_CAPS_MAX_SIZE]; let path = CString::new(path.as_ref().as_bytes())?; let ret = unsafe { libc::getxattr( path.as_ptr(), sys::XATTR_NAME_CAPS.as_ptr() as *const libc::c_char, data.as_mut_ptr() as *mut libc::c_void, data.len(), ) }; Self::extract_attr_or_error(&data, ret) } ``` -------------------------------- ### last_path! Macro Usage Example Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/mod.rs.html Demonstrates the usage of the `last_path!` macro for testing purposes. This macro is used to assert the correct behavior of path-related operations. ```Rust assert_eq!(last_path!(Cap::CHOWN), Cap::CHOWN); assert_eq!(last_path!(Cap::CHOWN, Cap::SETUID), Cap::SETUID); assert_eq!( last_path!(Cap::CHOWN, CAP::SETUID, Cap::SETGID,), Cap::SETGID ); ``` -------------------------------- ### Getting File Capabilities for a File Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/file.rs.html Retrieves the capabilities of a file specified by its path. This is a test function and assumes the current executable exists. ```rust use std::env; use capctl::caps::FileCaps; let current_exe = env::current_exe().unwrap(); FileCaps::get_for_file(¤t_exe).unwrap(); ``` -------------------------------- ### Iterating and Constructing Capability Names Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/mod.rs.html Iterates through capabilities and constructs their full names by prepending 'cap_'. This example shows efficient string concatenation without extra allocations. ```rust let mut full_name = [0u8; 30]; full_name[..4].copy_from_slice(b"cap_"); full_name[4..name.len() + 4].copy_from_slice(name.as_bytes()); assert_eq!( Cap::from_str(core::str::from_utf8(&full_name[..name.len() + 4]).unwrap()), Ok(cap) ); ``` -------------------------------- ### Test Get and Set Current CapState Source: https://docs.rs/capctl/latest/src/capctl/caps/capstate.rs.html Verifies the functionality of getting the current process's capability state and setting it. It also checks getting the state for a specific PID, including the current process's PID. ```rust #[test] fn test_capstate_getset_current() { let state = CapState::get_current().unwrap(); assert_eq!(state, CapState::get_for_pid(0).unwrap()); assert_eq!( state, CapState::get_for_pid(unsafe { libc::getpid() }).unwrap() ); state.set_current().unwrap(); } ``` -------------------------------- ### Get File Capabilities for a File Descriptor Source: https://docs.rs/capctl/latest/src/capctl/caps/file.rs.html Retrieves the file capabilities for an open file using its file descriptor. This is a test function that opens the current executable and then gets its capabilities. ```rust let f = std::fs::File::open(¤t_exe).unwrap(); FileCaps::get_for_fd(f.as_raw_fd()).unwrap(); ``` -------------------------------- ### Creating Capsets with Single and Multiple Capabilities Source: https://docs.rs/capctl/latest/src/capctl/caps/capset.rs.html Demonstrates the creation of capability sets using the capset! macro, including single capabilities, multiple capabilities, and trailing commas. ```rust assert_eq!(capset!(Cap::CHOWN,), [Cap::CHOWN].iter().cloned().collect()); for cap in Cap::iter() { assert_eq!(capset!(cap), [cap].iter().cloned().collect()); assert_eq!(capset!(cap,), [cap].iter().cloned().collect()); } assert_eq!( capset!(Cap::CHOWN, Cap::SYSLOG), [Cap::CHOWN, Cap::SYSLOG].iter().cloned().collect() ); assert_eq!( capset!(Cap::CHOWN, Cap::SYSLOG,), [Cap::CHOWN, Cap::SYSLOG].iter().cloned().collect() ); assert_eq!( capset!(Cap::CHOWN, Cap::SYSLOG, Cap::FOWNER), [Cap::CHOWN, Cap::SYSLOG, Cap::FOWNER] .iter() .cloned() .collect() ); assert_eq!( capset!(Cap::CHOWN, Cap::SYSLOG, Cap::FOWNER,), [Cap::CHOWN, Cap::SYSLOG, Cap::FOWNER] .iter() .cloned() .collect() ); ``` -------------------------------- ### Iterator Implementation for CapSetIterator - Core Methods Source: https://docs.rs/capctl/0.2.4/capctl/caps/struct.CapSetIterator.html Core methods for the Iterator trait implementation, including getting the next item, consuming the iterator to get the last element, counting elements, and providing size hints. ```rust type Item = Cap ``` ```rust fn next(&mut self) -> Option ``` ```rust fn last(self) -> Option ``` ```rust fn count(self) -> usize ``` ```rust fn size_hint(&self) -> (usize, Option) ``` -------------------------------- ### Creating Empty and Predefined Capsets Source: https://docs.rs/capctl/latest/src/capctl/caps/capset.rs.html Shows how to create an empty capability set using capset!() and predefined capability sets for testing. ```rust const EMPTY_SET: CapSet = capset!(); assert_eq!(EMPTY_SET, CapSet::empty()); const CHOWN_SET: CapSet = capset!(Cap::CHOWN); assert_eq!(CHOWN_SET, [Cap::CHOWN].iter().cloned().collect()); const CHOWN_SYSLOG_SET: CapSet = capset!(Cap::CHOWN, Cap::SYSLOG,); assert_eq!( CHOWN_SYSLOG_SET, [Cap::CHOWN, Cap::SYSLOG].iter().cloned().collect() ); ``` -------------------------------- ### Get FullCapState for a Specific PID Source: https://docs.rs/capctl/0.2.4/capctl/caps/struct.FullCapState.html Retrieves the capability state for a given process ID (PID) or thread ID (TID) by examining files in `/proc`. If PID is 0, it gets the current thread's state. ```rust pub fn get_for_pid(pid: pid_t) -> Result ``` -------------------------------- ### Create CapSet with multiple capabilities Source: https://docs.rs/capctl/0.2.4/capctl/macro.capset.html Illustrates creating a CapSet with multiple capabilities using the capset macro. ```rust assert_eq!(capset!(Cap::CHOWN, Cap::SYSLOG), [Cap::CHOWN, Cap::SYSLOG].iter().cloned().collect()); ``` -------------------------------- ### get_timerslack Source: https://docs.rs/capctl/latest/capctl/prctl/index.html Get the current timer slack value. ```APIDOC ## get_timerslack ### Description Get the current timer slack value. ### Method APICALL ### Endpoint prctl::get_timerslack ``` -------------------------------- ### Create an empty CapSet Source: https://docs.rs/capctl/0.2.4/capctl/macro.capset.html Demonstrates creating an empty CapSet using the capset macro. ```rust assert_eq!(capset!(), CapSet::empty()); ``` -------------------------------- ### impl Any for T Source: https://docs.rs/capctl/0.2.4/capctl/caps/enum.Cap.html Provides the `type_id` method to get the `TypeId` of a type. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method N/A (Method within a trait implementation) ### Endpoint N/A ### Parameters None ### Request Example None ### Response #### Success Response - **TypeId**: The unique identifier for the type of `self`. ``` -------------------------------- ### Initialize and Format Capabilities Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/cap_text.rs.html Initializes the drop state and calls `format_part` and `format_part_drop` to construct the full capability string representation. ```rust let mut drop_state = CapState::empty(); format_part( f, &orig_state, &mut state, &mut drop_state, &mut first, true, true, true, )?; format_part_drop(f, &mut drop_state, true, true, true)?; format_part( f, &orig_state, &mut state, &mut drop_state, &mut first, true, true, false, )?; format_part( f, &orig_state, &mut state, &mut drop_state, &mut first, false, true, true, )?; format_part( f, &orig_state, &mut state, &mut drop_state, &mut first, true, false, true, )?; format_part_drop(f, &mut drop_state, true, true, false)?; format_part_drop(f, &mut drop_state, false, true, true)?; format_part_drop(f, &mut drop_state, true, false, true)?; format_part( f, &orig_state, &mut state, &mut drop_state, &mut first, true, false, false, )?; ``` -------------------------------- ### Getting FullCapState for a Specific PID Source: https://docs.rs/capctl/latest/src/capctl/caps/fullcapstate.rs.html Retrieves the full capability state of a process or thread by its PID using /proc filesystem. If pid is 0, it gets the current thread's state. Handles errors like PID not found (ESRCH) or invalid PID (EINVAL). ```rust pub fn get_for_pid(pid: libc::pid_t) -> io::Result { let file_res = match pid.cmp(&0) { core::cmp::Ordering::Less => return Err(io::Error::from_raw_os_error(libc::EINVAL)), core::cmp::Ordering::Equal => fs::File::open("/proc/thread-self/status"), core::cmp::Ordering::Greater => fs::File::open(format!("/proc/{}/status", pid)), }; let f = match file_res { Ok(f) => f, Err(e) if e.raw_os_error() == Some(libc::ENOENT) => { return Err(io::Error::from_raw_os_error(libc::ESRCH)); } Err(e) => return Err(e), }; let mut reader = io::BufReader::new(f); let mut line = String::new(); let mut res = Self::empty(); while reader.read_line(&mut line)? > 0 { if line.ends_with(' ') { line.pop(); } if let Some(i) = line.find(":\t") { let value = &line[i + 2..]; let set = match &line[..i] { "CapPrm" => Some(&mut res.permitted), "CapEff" => Some(&mut res.effective), "CapInh" => Some(&mut res.inheritable), "CapBnd" => Some(&mut res.bounding), "CapAmb" => Some(&mut res.ambient), "NoNewPrivs" => { res.no_new_privs = value == "1"; None } _ => None, }; if let Some(set) = set { match u64::from_str_radix(value, 16) { Ok(bitmask) => *set = CapSet::from_bitmask_truncate(bitmask), Err(e) => { return Err(io::Error::new(io::ErrorKind::Other, e.to_string())); } } } } line.clear(); } Ok(res) } ``` -------------------------------- ### Create CapSet with single capability Source: https://docs.rs/capctl/0.2.4/capctl/macro.capset.html Shows how to create a CapSet containing a single capability using the capset macro. ```rust assert_eq!(capset!(Cap::CHOWN), [Cap::CHOWN].iter().cloned().collect()); ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/capctl/latest/capctl/prctl/struct.SpecFlags.html Provides the `type_id` method for getting the `TypeId` of an object. ```APIDOC ## fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. ``` -------------------------------- ### Set File Capabilities for a Subdirectory (Error) Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/file.rs.html Demonstrates attempting to set capabilities for a subdirectory, expecting an ENOTDIR error. ```rust assert_eq!( FileCaps::empty() .set_for_file(current_exe.join("sub")) .unwrap_err() .raw_os_error(), Some(libc::ENOTDIR) ); ``` -------------------------------- ### get_dumpable Source: https://docs.rs/capctl/latest/capctl/prctl/index.html Get the “dumpable” flag for the current process. ```APIDOC ## get_dumpable ### Description Get the “dumpable” flag for the current process. ### Method APICALL ### Endpoint prctl::get_dumpable ``` -------------------------------- ### Get Error Code Source: https://docs.rs/capctl/latest/capctl/struct.Error.html Retrieves the `errno` code represented by this `Error` object. ```APIDOC ## pub fn code(&self) -> i32 Get the `errno` code represented by this `Error` object. ``` -------------------------------- ### CapSet::empty Source: https://docs.rs/capctl/latest/capctl/caps/struct.CapSet.html Creates a new, empty capability set. ```APIDOC ## CapSet::empty ### Description Creates an empty capability set. ### Signature `pub const fn empty() -> Self` ``` -------------------------------- ### Get CapSet Size Source: https://docs.rs/capctl/0.2.4/capctl/caps/struct.CapSet.html Returns the total number of capabilities currently present in the set. ```rust pub fn size(&self) -> usize ``` -------------------------------- ### Iterator Adapter for CapIter - Step By Source: https://docs.rs/capctl/0.2.4/capctl/caps/struct.CapIter.html Demonstrates the step_by adapter for CapIter, which creates an iterator that steps by a specified amount. ```rust fn step_by(self, step: usize) -> StepBy ``` -------------------------------- ### CapSet Methods Source: https://docs.rs/capctl/0.2.4/capctl/caps/struct.CapSet.html Provides documentation for the public methods available on the CapSet struct, allowing users to manage and query capability sets. ```APIDOC ## CapSet Represents a set of capabilities. Internally, this stores the set of capabilities as a bitmask, which is much more efficient than a `HashSet`. ### Methods #### `empty()` Create an empty capability set. - **Returns**: An empty `CapSet`. #### `clear()` Clear all capabilities from this set. After this call, `set.is_empty()` will return `true`. #### `is_empty()` Check if this capability set is empty. - **Returns**: `true` if the set is empty, `false` otherwise. #### `size()` Returns the number of capabilities in this capability set. - **Returns**: The count of capabilities in the set. #### `has(cap: Cap)` Checks if a given capability is present in this set. - **Parameters**: - `cap` (Cap): The capability to check for. - **Returns**: `true` if the capability is present, `false` otherwise. #### `add(cap: Cap)` Adds the given capability to this set. - **Parameters**: - `cap` (Cap): The capability to add. #### `drop(cap: Cap)` Removes the given capability from this set. - **Parameters**: - `cap` (Cap): The capability to remove. #### `set_state(cap: Cap, val: bool)` If `val` is `true` the given capability is added; otherwise it is removed. - **Parameters**: - `cap` (Cap): The capability to set. - `val` (bool): `true` to add the capability, `false` to remove it. #### `add_all>(t: T)` Adds all of the capabilities yielded by the given iterator to this set. If you want to add all the capabilities in another `CapSet`, you should use `set1 = set1.union(set2)` or `set1 |= set2`, NOT `set1.add_all(set2)`. - **Parameters**: - `t` (T): An iterator yielding capabilities to add. #### `drop_all>(t: T)` Removes all of the capabilities yielded by the given iterator from this set. If you want to remove all the capabilities in another `CapSet`, you should use `set1 = set1.intersection(!set2)`, `set1 &= !set2`, or `set1 -= set2`, NOT `set1.drop_all(set2)`. - **Parameters**: - `t` (T): An iterator yielding capabilities to remove. #### `iter()` Returns an iterator over all of the capabilities in this set. - **Returns**: An iterator over the capabilities in the set. #### `union(other: Self)` Returns the union of this set and another capability set (i.e. all the capabilities that are in either set). - **Parameters**: - `other` (CapSet): The other capability set. - **Returns**: A new `CapSet` representing the union. #### `intersection(other: Self)` Returns the intersection of this set and another capability set (i.e. all the capabilities that are in both sets). - **Parameters**: - `other` (CapSet): The other capability set. - **Returns**: A new `CapSet` representing the intersection. #### `issubset(other: Self)` Return whether this set is a subset of another capability set. This returns `true` if all of the capabilities in `self` are present in `other`. - **Parameters**: - `other` (CapSet): The other capability set. - **Returns**: `true` if `self` is a subset of `other`, `false` otherwise. #### `issuperset(other: Self)` Return whether this set is a superset of another capability set. This returns `true` if all of the capabilities in `other` are present in `self`. - **Parameters**: - `other` (CapSet): The other capability set. - **Returns**: `true` if `self` is a superset of `other`, `false` otherwise. ``` -------------------------------- ### Display Various Capability States Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capstate.rs.html Demonstrates the string representation for a variety of `CapState` configurations, including empty, all flags set, and specific capabilities. Assumes the `std` feature is enabled. ```rust for state in [ CapState::empty(), CapState { permitted: !capset!(), effective: !capset!(), inheritable: !capset!(), }, CapState { permitted: !capset!(), effective: capset!(), inheritable: capset!(), }, CapState { permitted: !capset!(Cap::CHOWN), effective: capset!(), inheritable: capset!(), }, CapState { permitted: capset!(), effective: !capset!(Cap::CHOWN), inheritable: capset!(), }, CapState { permitted: capset!(), effective: capset!(), inheritable: !capset!(Cap::CHOWN), }, CapState { permitted: !capset!(Cap::CHOWN), effective: capset!(Cap::CHOWN), inheritable: capset!(), }, CapState { permitted: capset!(Cap::CHOWN), effective: capset!(Cap::CHOWN), inheritable: capset!(Cap::CHOWN), }, ] { // ... assertions would follow here in a real test } ``` -------------------------------- ### Get Memory-Deny-Write-Execute Flags Source: https://docs.rs/capctl/0.2.4/capctl/prctl/fn.get_mdwe.html Retrieves the current memory-deny-write-execute flags. Refer to `set_mdwe` for more details on these flags. ```rust pub fn get_mdwe() -> Result ``` -------------------------------- ### IO Flusher Constants Source: https://docs.rs/capctl/0.2.4/src/capctl/sys.rs.html Defines constants for setting and getting the IO flusher state using `prctl`. ```rust pub const PR_SET_IO_FLUSHER: libc::c_int = 57; ``` ```rust pub const PR_GET_IO_FLUSHER: libc::c_int = 58; ``` -------------------------------- ### Secbits Comparison Methods Source: https://docs.rs/capctl/0.2.4/capctl/prctl/struct.Secbits.html Provides methods for comparing Secbits instances, including equality, ordering, and clamping values within a range. ```APIDOC ## Secbits Comparison Operations ### Description Methods for comparing `Secbits` instances. ### Methods - `cmp(&self, other: &Secbits) -> Ordering` Compares `self` and `other` and returns an `Ordering`. - `max(self, other: Self) -> Self` Compares two `Secbits` values and returns the maximum. - `min(self, other: Self) -> Self` Compares two `Secbits` values and returns the minimum. - `clamp(self, min: Self, max: Self) -> Self` Restricts a `Secbits` value to a specified interval [`min`, `max`]. - `eq(&self, other: &Secbits) -> bool` Tests if `self` and `other` are equal (`==`). - `ne(&self, other: &Rhs) -> bool` Tests if `self` and `other` are not equal (`!=`). - `partial_cmp(&self, other: &Secbits) -> Option` Returns an ordering between `self` and `other` if one exists. - `lt(&self, other: &Rhs) -> bool` Tests if `self` is less than `other` (`<`). - `le(&self, other: &Rhs) -> bool` Tests if `self` is less than or equal to `other` (`<=`). - `gt(&self, other: &Rhs) -> bool` Tests if `self` is greater than `other` (`>`). - `ge(&self, other: &Rhs) -> bool` Tests if `self` is greater than or equal to `other` (`>=`). ``` -------------------------------- ### Get No New Privileges Flag Source: https://docs.rs/capctl/0.2.4/capctl/prctl/fn.get_no_new_privs.html Retrieves the no-new-privileges flag for the current thread. See `set_no_new_privs()` for more details. ```rust pub fn get_no_new_privs() -> Result ``` -------------------------------- ### impl CloneToUninit for T Source: https://docs.rs/capctl/0.2.4/capctl/prctl/struct.SpecFlags.html Provides the experimental `clone_to_uninit` method for cloning to uninitialized memory. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit` ### Parameters - `dest` (*mut u8): A mutable pointer to the uninitialized memory location. ### Safety This function is unsafe and requires `T: Clone`. ``` -------------------------------- ### CapSet::add_all Source: https://docs.rs/capctl/latest/capctl/caps/struct.CapSet.html Adds all capabilities from an iterator to the set. ```APIDOC ## CapSet::add_all ### Description Adds all of the capabilities yielded by the given iterator to this set. If you want to add all the capabilities in another `CapSet`, you should use `set1 = set1.union(set2)` or `set1 |= set2`, NOT `set1.add_all(set2)`. ### Signature `pub fn add_all>(&mut self, t: T)` ``` -------------------------------- ### Get Securebits Flags Source: https://docs.rs/capctl/0.2.4/capctl/prctl/fn.get_securebits.html Retrieves the securebits flags for the current thread. Refer to `set_securebits()` for additional information. ```rust pub fn get_securebits() -> Result ``` -------------------------------- ### Get Dumpable Flag Source: https://docs.rs/capctl/0.2.4/capctl/prctl/fn.get_dumpable.html Retrieves the 'dumpable' flag for the current process. Refer to `set_dumpable()` for more details on this flag. ```rust pub fn get_dumpable() -> Result ``` -------------------------------- ### Test CapSet Creation from Iterator Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capset.rs.html Demonstrates how to create a CapSet by collecting an iterator of capabilities. Asserts that the resulting set contains the expected capabilities. ```rust let set = [Cap::CHOWN, Cap::FOWNER] .iter() .cloned() .collect::(); assert!(set.iter().eq([Cap::CHOWN, Cap::FOWNER].iter().cloned())); ``` -------------------------------- ### Get Memory-Deny-Write-Execute Flags Source: https://docs.rs/capctl/latest/src/capctl/prctl.rs.html Retrieves the memory-deny-write-execute (MDWE) flags for the current process. See `set_mdwe()` for more details on the flags. ```APIDOC ## get_mdwe ### Description Gets the memory-deny-write execute flags. ### Method `prctl(PR_GET_MDWE, ...)` ### Returns `Ok(MDWEFlags)` containing the current flags, or a `crate::Result` error on failure. ``` -------------------------------- ### CapSet Macro Usage Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capset.rs.html Shows the usage of the `capset!` macro for creating CapSets. It covers creating an empty CapSet and a CapSet with a single capability. ```rust assert_eq!(capset!(), CapSet::empty()); assert_eq!(capset!(Cap::CHOWN), [Cap::CHOWN].iter().cloned().collect()); ``` -------------------------------- ### Get TID Address Source: https://docs.rs/capctl/0.2.4/src/capctl/prctl.rs.html Calls the get_tid_address function. The specific usage and implications of the returned address are not verified in this test. ```rust #[test] fn test_get_tid_address() { // We don't know for sure how the clear_child_tid address is being used, so we can't check // it get_tid_address().unwrap(); } ``` -------------------------------- ### Get Last OS Error Source: https://docs.rs/capctl/latest/capctl/struct.Error.html Retrieves the last OS error that occurred, equivalent to the current `errno` value. ```APIDOC ## pub fn last() -> Self Get the last OS error that occured (i.e. the current `errno` value). ``` -------------------------------- ### CloneToUninit Trait Implementation (Nightly Only) Source: https://docs.rs/capctl/latest/capctl/prctl/struct.SpecFlags.html Provides the `clone_to_uninit` method for copy-assignment to uninitialized memory. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) Performs copy-assignment from `self` to `dest`. ``` -------------------------------- ### impl CloneToUninit for T Source: https://docs.rs/capctl/0.2.4/capctl/caps/enum.Cap.html Provides the experimental `clone_to_uninit` method for copy-assignment to uninitialized memory. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description 🔬This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. ### Method N/A (Method within a trait implementation) ### Endpoint N/A ### Parameters - **dest** (*mut u8) - Required - A mutable pointer to the destination memory location. ### Request Example None ### Response None (This is an unsafe operation that modifies memory directly). ``` -------------------------------- ### Get Raw Bits of MDWEFlags Source: https://docs.rs/capctl/0.2.4/capctl/prctl/struct.MDWEFlags.html Returns the raw integer representation of the flags currently stored in the MDWEFlags instance. ```rust pub const fn bits(&self) -> c_int ``` -------------------------------- ### Probe All Capabilities in Bounding Set Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/bounding.rs.html Scans the bounding capability set and returns a `CapSet` containing all capabilities that are currently raised. Stops probing if an unsupported capability is encountered. ```rust /// "Probes" the current thread's bounding capability set and returns a `CapSet` representing all /// the capabilities that are currently raised. pub fn probe() -> CapSet { let mut set = CapSet::empty(); for cap in Cap::iter() { match read(cap) { Some(true) => set.add(cap), Some(false) => (), // Unsupported capability encountered; none of the remaining ones will be supported // either _ => break, } } set } ``` -------------------------------- ### Get Subreaper Flag Source: https://docs.rs/capctl/0.2.4/capctl/prctl/fn.get_subreaper.html Retrieves the child subreaper flag for the current process. Refer to set_subreaper() for more details on its functionality. ```rust pub fn get_subreaper() -> Result ``` -------------------------------- ### Get Current Thread Name Source: https://docs.rs/capctl/0.2.4/src/capctl/prctl.rs.html Retrieves the name of the current thread. The returned OsString is truncated at the first null byte. ```rust /// Get the name of the current thread. #[cfg_attr(docsrs, doc(cfg(feature = "std")))] #[cfg(feature = "std")] pub fn get_name() -> crate::Result { use std::os::unix::ffi::OsStringExt; let mut name_vec = vec![0; 16]; unsafe { crate::raw_prctl( libc::PR_GET_NAME, name_vec.as_ptr() as libc::c_ulong, 0, 0, 0, )?; } name_vec.truncate(name_vec.iter().position(|x| *x == 0).unwrap()); Ok(std::ffi::OsString::from_vec(name_vec)) } ``` -------------------------------- ### Error Cause (Deprecated) Source: https://docs.rs/capctl/0.2.4/capctl/struct.Error.html Provides a deprecated method to get the cause of the error. It has been replaced by `Error::source` which supports downcasting. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### capset! Macro for Static CapSet Construction Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capset.rs.html A macro to statically construct a CapSet from a list of capabilities. It supports empty construction and construction with one or more Cap variants. ```rust macro_rules! capset { () => { $crate::caps::CapSet::empty() }; ($($caps:expr),+ $(,)?) => { $crate::caps::CapSet::from_bitmask_truncate( 0 $(| (1u64 << ($caps as $crate::caps::Cap as u8)))* ) }; } ``` -------------------------------- ### Get Current Thread Name Source: https://docs.rs/capctl/0.2.4/capctl/prctl/fn.get_name.html Use this function to obtain the name of the current thread. Requires the 'std' feature to be enabled. ```rust pub fn get_name() -> Result ``` -------------------------------- ### Get Speculation Control Function Signature Source: https://docs.rs/capctl/0.2.4/capctl/prctl/fn.get_speculation_ctrl.html This is the function signature for get_speculation_ctrl. It takes a SpecVariant and returns a Result containing SpecFlags. ```rust pub fn get_speculation_ctrl(variant: SpecVariant) -> Result ``` -------------------------------- ### Test Adding and Dropping Individual Capabilities Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capset.rs.html Demonstrates the basic add, has, and drop operations for individual capabilities within a CapSet. Also tests the `set_state` method. ```rust let mut set = CapSet::empty(); set.add(Cap::CHOWN); assert!(set.has(Cap::CHOWN)); assert!(!set.is_empty()); set.drop(Cap::CHOWN); assert!(!set.has(Cap::CHOWN)); assert!(set.is_empty()); set.set_state(Cap::CHOWN, true); assert!(set.has(Cap::CHOWN)); assert!(!set.is_empty()); set.set_state(Cap::CHOWN, false); assert!(!set.has(Cap::CHOWN)); assert!(set.is_empty()); ``` -------------------------------- ### get_io_flusher Source: https://docs.rs/capctl/0.2.4/capctl/prctl/fn.get_io_flusher.html Gets the "I/O flusher" flag for the current process. This flag influences how I/O operations are flushed. ```APIDOC ## Function get_io_flusher ### Description Get the “I/O flusher” flag for the current process. See `set_io_flusher()` for more details. ### Signature ```rust pub fn get_io_flusher() -> Result ``` ### Returns A `Result` containing a boolean value. `true` if the I/O flusher flag is set, `false` otherwise. An error may be returned if the operation fails. ``` -------------------------------- ### Test CapSet Initialization and Empty State Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capset.rs.html Verifies that an empty CapSet can be created, cleared, and correctly identified as empty. It also checks that no capabilities are present initially. ```rust let mut set = Cap::iter().collect::(); for cap in Cap::iter() { set.drop(cap); } assert_eq!(set.bits, 0); assert!(set.is_empty()); set = CapSet::empty(); assert_eq!(set.bits, 0); assert!(set.is_empty()); assert_eq!(set, CapSet::default()); set = Cap::iter().collect::(); set.clear(); assert_eq!(set.bits, 0); assert!(set.is_empty()); assert!(!Cap::iter().any(|c| set.has(c))); ``` -------------------------------- ### Result Termination Report Method Source: https://docs.rs/capctl/latest/capctl/type.Result.html The `report` function is called to get the representation of the value as a status code, which is then returned to the operating system. ```rust fn report(self) -> ExitCode ``` -------------------------------- ### Parsing a Capability Set String Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/cap_text.rs.html Parses a string into a CapSet. Handles 'all', 'ALL', and comma-separated capabilities. Returns an error for unknown capabilities. ```rust assert_eq!(parse_capset("").unwrap(), !CapSet::empty()); assert_eq!(parse_capset("all").unwrap(), !CapSet::empty()); assert_eq!(parse_capset("ALL").unwrap(), !CapSet::empty()); assert_eq!(parse_capset("cap_chown").unwrap(), capset!(Cap::CHOWN)); assert_eq!(parse_capset("CAP_CHOWN").unwrap(), capset!(Cap::CHOWN)); assert_eq!( parse_capset("cap_chown,cap_syslog").unwrap(), capset!(Cap::CHOWN, Cap::SYSLOG), ); assert_eq!( parse_capset("cap_noexist").unwrap_err().to_string(), "Unknown capability" ); assert_eq!( parse_capset(",").unwrap_err().to_string(), "Unknown capability" ); ``` -------------------------------- ### Get I/O Flusher Flag Source: https://docs.rs/capctl/0.2.4/src/capctl/prctl.rs.html Retrieves the "I/O flusher" flag for the current process. See `set_io_flusher()` for more details. ```rust /// Get the "I/O flusher" flag for the current process. /// /// See [`set_io_flusher()`] for more details. #[inline] pub fn get_io_flusher() -> crate::Result { let res = unsafe { crate::raw_prctl(crate::sys::PR_GET_IO_FLUSHER, 0, 0, 0, 0) }?; Ok(res != 0) } ``` -------------------------------- ### CapSet::empty() - Create an empty capability set Source: https://docs.rs/capctl/0.2.4/src/capctl/caps/capset.rs.html Use this function to create a new, empty capability set. It initializes the internal bitmask to zero. ```rust pub const fn empty() -> Self { Self { bits: 0 } } ``` -------------------------------- ### Get THP Disable Flag in Rust Source: https://docs.rs/capctl/0.2.4/src/capctl/prctl.rs.html Retrieves the current status of the transparent huge pages (THP) disable flag for the process. ```rust pub fn get_thp_disable() -> crate::Result { let res = unsafe { crate::raw_prctl(libc::PR_GET_THP_DISABLE, 0, 0, 0, 0) }?; Ok(res != 0) } ```