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
#[cfg(test)]
mod tests;

use std::ffi::{CStr, CString, OsStr};
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int, c_uint, c_ulong, c_void};
use std::path::{Path, PathBuf};
use std::{io, mem, ptr};

use once_cell::sync::OnceCell;

use crate::errors::{Error, Result};

pub(crate) fn str_to_c_string(s: &str) -> Result<CString> {
    CString::new(s).map_err(|_r| Error::IO1Name {
        operation: "CString::new",
        name: s.into(),
        source: io::ErrorKind::InvalidInput.into(),
    })
}

#[cfg(unix)]
pub(crate) fn os_str_to_c_string(s: &OsStr) -> Result<CString> {
    use std::os::unix::ffi::OsStrExt;

    CString::new(s.as_bytes()).map_err(|_r| Error::PathIsInvalid(PathBuf::from(s)))
}

pub(crate) fn c_str_ptr_to_str<'string>(s: *const c_char) -> Result<&'string str> {
    if s.is_null() {
        let err = io::ErrorKind::InvalidInput.into();
        Err(Error::from_io("utils::c_str_ptr_to_string()", err))
    } else {
        unsafe { CStr::from_ptr(s) }.to_str().map_err(Into::into)
    }
}

#[cfg(unix)]
pub(crate) fn c_str_ptr_to_path<'string>(path_ptr: *const c_char) -> &'string Path {
    use std::os::unix::ffi::OsStrExt;

    let c_path = unsafe { CStr::from_ptr(path_ptr) };
    Path::new(OsStr::from_bytes(c_path.to_bytes()))
}

pub(crate) fn c_str_to_non_null_ptr(s: &CStr) -> ptr::NonNull<c_char> {
    unsafe { ptr::NonNull::new_unchecked(s.as_ptr() as *mut c_char) }
}

pub(crate) fn get_static_path(
    proc: unsafe extern "C" fn() -> *const c_char,
    proc_name: &'static str,
) -> Result<&'static Path> {
    let path_ptr = unsafe { proc() };
    if path_ptr.is_null() {
        Err(Error::from_io(proc_name, io::ErrorKind::InvalidData.into()))
    } else {
        Ok(c_str_ptr_to_path(path_ptr))
    }
}

pub(crate) fn ret_val_to_result(proc_name: &'static str, result: c_int) -> Result<()> {
    if result == -1_i32 {
        Err(Error::last_io_error(proc_name))
    } else {
        Ok(())
    }
}

pub(crate) fn ret_val_to_result_with_path(
    proc_name: &'static str,
    result: c_int,
    path: &Path,
) -> Result<()> {
    if result == -1_i32 {
        let err = io::Error::last_os_error();
        Err(Error::from_io_path(proc_name, path, err))
    } else {
        Ok(())
    }
}

/// An owned block of memory, allocated with [`libc::malloc`].
///
/// Dropping this instance calls [`libc::free`] on the managed pointer.
#[derive(Debug)]
pub struct CAllocatedBlock<T> {
    pub(crate) pointer: ptr::NonNull<T>,
    _phantom_data: PhantomData<T>,
}

/// # Safety
///
/// - [`libc::malloc()`]-allocated memory blocks are accessible from any thread.
/// - [`libc::free()`] supports deallocating memory blocks allocated in
///   a different thread.
unsafe impl<T> Send for CAllocatedBlock<T> {}

impl<T> CAllocatedBlock<T> {
    pub(crate) fn new(pointer: *mut T) -> Option<Self> {
        ptr::NonNull::new(pointer).map(|pointer| Self {
            pointer,
            _phantom_data: PhantomData,
        })
    }

    /// Return the managed raw pointer.
    #[must_use]
    pub fn as_ptr(&self) -> *const T {
        self.pointer.as_ptr()
    }

    /// Return the managed raw pointer.
    #[must_use]
    pub fn as_mut_ptr(&mut self) -> *mut T {
        self.pointer.as_ptr()
    }
}

impl CAllocatedBlock<c_char> {
    /// Return the managed null-terminated C string.
    #[must_use]
    pub fn as_c_str(&self) -> &CStr {
        unsafe { CStr::from_ptr(self.pointer.as_ptr()) }
    }
}

impl<T> Drop for CAllocatedBlock<T> {
    fn drop(&mut self) {
        let pointer = self.pointer.as_ptr();
        self.pointer = ptr::NonNull::dangling();
        unsafe { libc::free(pointer.cast()) };
    }
}

/// Holds addresses of `libselinux`'s optionally-implemented functions.
#[derive(Debug)]
pub(crate) struct OptionalNativeFunctions {
    /// Since version 2.9
    pub(crate) security_reject_unknown: unsafe extern "C" fn() -> c_int,

    /// Since version 3.0
    pub(crate) selabel_get_digests_all_partial_matches: unsafe extern "C" fn(
        rec: *mut selinux_sys::selabel_handle,
        key: *const c_char,
        calculated_digest: *mut *mut u8,
        xattr_digest: *mut *mut u8,
        digest_len: *mut usize,
    ) -> bool,

    /// Since version 3.0
    pub(crate) selabel_hash_all_partial_matches: unsafe extern "C" fn(
        rec: *mut selinux_sys::selabel_handle,
        key: *const c_char,
        digest: *mut u8,
    ) -> bool,

    /// Since version 3.0
    pub(crate) security_validatetrans: unsafe extern "C" fn(
        scon: *const c_char,
        tcon: *const c_char,
        tclass: selinux_sys::security_class_t,
        newcon: *const c_char,
    ) -> c_int,

    /// Since version 3.0
    pub(crate) security_validatetrans_raw: unsafe extern "C" fn(
        scon: *const c_char,
        tcon: *const c_char,
        tclass: selinux_sys::security_class_t,
        newcon: *const c_char,
    ) -> c_int,

    /// Since version 3.1
    pub(crate) selinux_flush_class_cache: unsafe extern "C" fn(),

    /// Since version 3.4
    pub(crate) selinux_restorecon_parallel: unsafe extern "C" fn(
        pathname: *const c_char,
        restorecon_flags: c_uint,
        nthreads: usize,
    ) -> c_int,

    /// Since version 3.4
    pub(crate) selinux_restorecon_get_skipped_errors: unsafe extern "C" fn() -> c_ulong,

    /// Since version 3.5
    pub(crate) getpidprevcon:
        unsafe extern "C" fn(pid: selinux_sys::pid_t, con: *mut *mut c_char) -> c_int,

    /// Since version 3.5
    pub(crate) getpidprevcon_raw:
        unsafe extern "C" fn(pid: selinux_sys::pid_t, con: *mut *mut c_char) -> c_int,
}

/// Addresses of optionally-implemented functions by libselinux.
pub(crate) static OPT_NATIVE_FN: OnceCell<OptionalNativeFunctions> = OnceCell::new();

impl Default for OptionalNativeFunctions {
    fn default() -> Self {
        Self {
            security_reject_unknown: Self::not_impl_security_reject_unknown,
            selabel_get_digests_all_partial_matches:
                Self::not_impl_selabel_get_digests_all_partial_matches,
            selabel_hash_all_partial_matches: Self::not_impl_selabel_hash_all_partial_matches,
            security_validatetrans: Self::not_impl_security_validatetrans,
            security_validatetrans_raw: Self::not_impl_security_validatetrans,
            selinux_flush_class_cache: Self::not_impl_selinux_flush_class_cache,
            selinux_restorecon_parallel: Self::not_impl_selinux_restorecon_parallel,
            selinux_restorecon_get_skipped_errors:
                Self::not_impl_selinux_restorecon_get_skipped_errors,
            getpidprevcon: Self::not_impl_getpidprevcon,
            getpidprevcon_raw: Self::not_impl_getpidprevcon,
        }
    }
}

impl OptionalNativeFunctions {
    pub(crate) fn get() -> &'static Self {
        OPT_NATIVE_FN.get_or_init(Self::initialize)
    }

    fn initialize() -> Self {
        let mut r = Self::default();
        let lib_handle = Self::get_libselinux_handle();
        if !lib_handle.is_null() {
            r.load_functions_addresses(lib_handle);
        }
        Error::clear_errno();
        r
    }

    fn get_libselinux_handle() -> *mut c_void {
        // Ensure libselinux is loaded.
        unsafe { selinux_sys::is_selinux_enabled() };

        // Get a handle to the already-loaded libselinux.
        let flags = libc::RTLD_NOW | libc::RTLD_GLOBAL | libc::RTLD_NOLOAD | libc::RTLD_NODELETE;
        for &lib_name in &[
            "libselinux.so.1\0",
            "libselinux.so\0",
            "libselinux\0",
            "selinux\0",
        ] {
            let lib_handle = unsafe { libc::dlopen(lib_name.as_ptr().cast(), flags) };
            if !lib_handle.is_null() {
                return lib_handle;
            }
        }
        ptr::null_mut()
    }

    fn load_functions_addresses(&mut self, lib_handle: *mut c_void) {
        let f = unsafe { libc::dlsym(lib_handle, "security_reject_unknown\0".as_ptr().cast()) };
        if !f.is_null() {
            self.security_reject_unknown = unsafe { mem::transmute(f) };
        }

        let c_name = "selabel_get_digests_all_partial_matches\0";
        let f = unsafe { libc::dlsym(lib_handle, c_name.as_ptr().cast()) };
        if !f.is_null() {
            self.selabel_get_digests_all_partial_matches = unsafe { mem::transmute(f) };
        }

        let c_name = "selabel_hash_all_partial_matches\0";
        let f = unsafe { libc::dlsym(lib_handle, c_name.as_ptr().cast()) };
        if !f.is_null() {
            self.selabel_hash_all_partial_matches = unsafe { mem::transmute(f) };
        }

        let f = unsafe { libc::dlsym(lib_handle, "security_validatetrans\0".as_ptr().cast()) };
        if !f.is_null() {
            self.security_validatetrans = unsafe { mem::transmute(f) };
        }

        let f = unsafe { libc::dlsym(lib_handle, "security_validatetrans_raw\0".as_ptr().cast()) };
        if !f.is_null() {
            self.security_validatetrans_raw = unsafe { mem::transmute(f) };
        }

        let f = unsafe { libc::dlsym(lib_handle, "selinux_flush_class_cache\0".as_ptr().cast()) };
        if !f.is_null() {
            self.selinux_flush_class_cache = unsafe { mem::transmute(f) };
        }

        let f = unsafe { libc::dlsym(lib_handle, "selinux_restorecon_parallel\0".as_ptr().cast()) };
        if !f.is_null() {
            self.selinux_restorecon_parallel = unsafe { mem::transmute(f) };
        }

        let c_name = "selinux_restorecon_get_skipped_errors\0";
        let f = unsafe { libc::dlsym(lib_handle, c_name.as_ptr().cast()) };
        if !f.is_null() {
            self.selinux_restorecon_get_skipped_errors = unsafe { mem::transmute(f) };
        }

        let f = unsafe { libc::dlsym(lib_handle, "getpidprevcon\0".as_ptr().cast()) };
        if !f.is_null() {
            self.getpidprevcon = unsafe { mem::transmute(f) };
        }

        let f = unsafe { libc::dlsym(lib_handle, "getpidprevcon_raw\0".as_ptr().cast()) };
        if !f.is_null() {
            self.getpidprevcon_raw = unsafe { mem::transmute(f) };
        }
    }

    unsafe extern "C" fn not_impl_security_reject_unknown() -> c_int {
        Error::set_errno(libc::ENOSYS);
        -1_i32
    }

    unsafe extern "C" fn not_impl_selabel_get_digests_all_partial_matches(
        _rec: *mut selinux_sys::selabel_handle,
        _key: *const c_char,
        _calculated_digest: *mut *mut u8,
        _xattr_digest: *mut *mut u8,
        _digest_len: *mut usize,
    ) -> bool {
        Error::set_errno(libc::ENOSYS);
        false
    }

    unsafe extern "C" fn not_impl_selabel_hash_all_partial_matches(
        _rec: *mut selinux_sys::selabel_handle,
        _key: *const c_char,
        _digest: *mut u8,
    ) -> bool {
        Error::set_errno(libc::ENOSYS);
        false
    }

    unsafe extern "C" fn not_impl_security_validatetrans(
        _scon: *const c_char,
        _tcon: *const c_char,
        _tclass: selinux_sys::security_class_t,
        _newcon: *const c_char,
    ) -> c_int {
        Error::set_errno(libc::ENOSYS);
        -1_i32
    }

    unsafe extern "C" fn not_impl_selinux_flush_class_cache() {
        Error::set_errno(libc::ENOSYS);
    }

    unsafe extern "C" fn not_impl_selinux_restorecon_parallel(
        _pathname: *const c_char,
        _restorecon_flags: c_uint,
        _nthreads: usize,
    ) -> c_int {
        Error::set_errno(libc::ENOSYS);
        -1_i32
    }

    unsafe extern "C" fn not_impl_selinux_restorecon_get_skipped_errors() -> c_ulong {
        0
    }

    unsafe extern "C" fn not_impl_getpidprevcon(
        _pid: selinux_sys::pid_t,
        _con: *mut *mut c_char,
    ) -> c_int {
        Error::set_errno(libc::ENOSYS);
        -1_i32
    }
}