use libloading::Library;
use std::{
ffi::{c_char, c_int, c_void},
fmt, io,
path::PathBuf,
ptr::NonNull,
};
use crate::MainArgs;
#[derive(Debug)]
pub enum SandboxError {
CurrentExe(io::Error),
Load {
path: PathBuf,
source: libloading::Error,
},
Symbol {
name: &'static str,
source: libloading::Error,
},
Initialize,
AlreadyAttempted,
}
impl fmt::Display for SandboxError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::CurrentExe(_) => f.write_str("cannot locate the running executable"),
Self::Load { path, .. } => {
write!(f, "cannot load the sandbox library {}", path.display())
}
Self::Symbol { name, .. } => write!(f, "the sandbox library has no {name}"),
Self::Initialize => f.write_str("cef_sandbox_initialize returned no sandbox context"),
Self::AlreadyAttempted => f.write_str("the helper tried to enter the sandbox already"),
}
}
}
impl std::error::Error for SandboxError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::CurrentExe(source) => Some(source),
Self::Load { source, .. } | Self::Symbol { source, .. } => Some(source),
Self::Initialize | Self::AlreadyAttempted => None,
}
}
}
type InitializeFn = unsafe extern "C" fn(argc: c_int, argv: *mut *mut c_char) -> *mut c_void;
type DestroyFn = unsafe extern "C" fn(context: *mut c_void);
pub struct Sandbox {
initialize: InitializeFn,
destroy: DestroyFn,
attempted: bool,
context: Option<NonNull<c_void>>,
_lib: Library,
}
unsafe impl Send for Sandbox {}
unsafe impl Sync for Sandbox {}
impl Sandbox {
const LIBCEF_SANDBOX_PATH: &str =
"../../../Chromium Embedded Framework.framework/Libraries/libcef_sandbox.dylib";
pub fn new() -> Result<Self, SandboxError> {
let exe = std::env::current_exe().map_err(SandboxError::CurrentExe)?;
let path = exe.with_file_name(Self::LIBCEF_SANDBOX_PATH);
let lib =
unsafe { Library::new(&path) }.map_err(|source| SandboxError::Load { path, source })?;
let (initialize, destroy) = unsafe {
(
symbol::<InitializeFn>(&lib, "cef_sandbox_initialize")?,
symbol::<DestroyFn>(&lib, "cef_sandbox_destroy")?,
)
};
Ok(Self {
initialize,
destroy,
attempted: false,
context: None,
_lib: lib,
})
}
pub fn initialize(&mut self, args: &MainArgs) -> Result<(), SandboxError> {
if self.attempted {
return Err(SandboxError::AlreadyAttempted);
}
self.attempted = true;
let context = unsafe { (self.initialize)(args.argc, args.argv) };
self.context = Some(NonNull::new(context).ok_or(SandboxError::Initialize)?);
Ok(())
}
}
impl Drop for Sandbox {
fn drop(&mut self) {
if let Some(context) = self.context {
unsafe { (self.destroy)(context.as_ptr()) };
}
}
}
unsafe fn symbol<T: Copy>(lib: &Library, name: &'static str) -> Result<T, SandboxError> {
unsafe { lib.get::<T>(name.as_bytes()) }
.map(|symbol| *symbol)
.map_err(|source| SandboxError::Symbol { name, source })
}