//! Manipulate securebits flags
//!
//! This module exposes methods to get and set per-thread securebits
//! flags, which can be used to disable special handling of capabilities
//! for UID 0 (root).

use nix::errno::Errno;

use crate::caps::{errors::CapsError, nr};

/// Return whether the current thread's "keep capabilities" flag is set.
pub fn has_keepcaps() -> Result<bool, CapsError> {
    let ret = Errno::result(unsafe { nix::libc::prctl(nr::PR_GET_KEEPCAPS, 0, 0, 0) })
        .map_err(CapsError)?;

    match ret {
        0 => Ok(false),
        _ => Ok(true),
    }
}

/// Set the value of the current thread's "keep capabilities" flag.
pub fn set_keepcaps(keep_caps: bool) -> Result<(), CapsError> {
    let flag = if keep_caps { 1 } else { 0 };

    Errno::result(unsafe { nix::libc::prctl(nr::PR_SET_KEEPCAPS, flag, 0, 0) })
        .map(drop)
        .map_err(CapsError)
}
