Files
syscall-stream-rs/src/lib.rs
T

128 lines
2.5 KiB
Rust
Raw Normal View History

2025-08-12 22:24:00 -06:00
mod host;
mod syscall_exec;
2025-08-12 17:48:34 -06:00
#[allow(dead_code)]
mod syscall_intercept;
2025-08-12 22:24:00 -06:00
use syscall_lib::syscall_should_proxy;
2025-08-12 17:48:34 -06:00
use libc::exit;
use std::{
cell::Cell,
io::{BufWriter, Write},
net::TcpStream,
sync::Mutex,
};
use syscall_intercept::*;
2025-08-12 22:24:00 -06:00
use crate::host::Host;
static mut HOST: Option<Mutex<Host>> = None;
2025-08-12 17:48:34 -06:00
#[ctor::ctor]
fn start() {
unsafe {
2025-08-12 22:24:00 -06:00
HOST = Some({
match Host::new() {
Ok(host) => Mutex::new(host),
2025-08-12 17:48:34 -06:00
Err(e) => {
eprintln!("Failed to connect to server: {}", e);
exit(1);
}
}
});
}
unsafe { set_hook_fn(hook) };
}
// fn print_direct(str: &str)
thread_local! {
/// A flag indicating whether the current thread is in an intercept context.
static INTERCEPTED: Cell<bool> = Cell::new(false);
}
// lazy_static! {
// }
struct InterceptGuard;
impl InterceptGuard {
fn try_lock() -> Option<Self> {
INTERCEPTED.with(|x| {
if x.get() {
None
} else {
x.set(true);
Some(InterceptGuard)
}
})
}
}
impl Drop for InterceptGuard {
fn drop(&mut self) {
INTERCEPTED.with(|x| x.set(false));
}
}
extern "C" fn hook(
2025-08-12 22:24:00 -06:00
syscall_num: usize,
arg0: usize,
arg1: usize,
arg2: usize,
arg3: usize,
arg4: usize,
arg5: usize,
result: &mut isize,
2025-08-12 17:48:34 -06:00
) -> InterceptResult {
// detect and avoid recursive interception
let _guard = match InterceptGuard::try_lock() {
Some(g) => g,
2025-08-12 22:24:00 -06:00
None => {
println!("Disabled!");
return InterceptResult::Forward;
}
2025-08-12 17:48:34 -06:00
};
2025-08-12 22:24:00 -06:00
// if syscall_should_proxy(syscall_num) {
// return InterceptResult::Forward;
// }
2025-08-12 17:48:34 -06:00
unsafe {
unset_hook_fn();
}
2025-08-12 22:24:00 -06:00
let args = [arg0, arg1, arg2, arg3, arg4, arg5];
let syscall = syscall_lib::create_syscall(syscall_num, args);
if !syscall_should_proxy(&syscall) {
return InterceptResult::Forward;
}
2025-08-12 17:48:34 -06:00
// Return if is print
// if syscall_num == libc::SYS_write as _ && arg0 == 1 {
// return InterceptResult::Forward;
// }
2025-08-12 22:24:00 -06:00
// if syscall_num == libc::SYS_close as _ && arg0 == 1 {
// return InterceptResult::Forward;
// }
// println!("{:?}", desc);
2025-08-12 17:48:34 -06:00
unsafe {
#[allow(static_mut_refs)]
2025-08-12 22:24:00 -06:00
if let Some(host) = HOST.as_ref() {
*result = host.lock().unwrap().execute(&syscall);
2025-08-12 17:48:34 -06:00
}
}
unsafe {
set_hook_fn(hook);
}
2025-08-12 22:24:00 -06:00
InterceptResult::Hook
2025-08-12 17:48:34 -06:00
}