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
#[cfg(not(unix))]
compile_error!("This crate is unix only");
mod libcfn;
use std::{
collections::HashSet,
io::{self, Write},
sync::Mutex,
};
use once_cell::sync::Lazy;
use std::process::{Command, Stdio};
use std::io::Result;
static HOOKS: Lazy<Mutex<HashSet<Hook>>> = Lazy::new(|| Mutex::new(HashSet::new()));
#[non_exhaustive]
#[derive(Hash, Eq, PartialEq)]
pub enum Hook {
Open(&'static str),
OpenDir(&'static str),
Recv(&'static str),
RecvMsg(&'static str),
Read(&'static str),
GetEnv(&'static str),
}
pub trait RunHook {
fn add_hook(&mut self, hook: Hook) -> &mut Self {
HOOKS.lock().expect("There is only one thread").insert(hook);
self
}
fn add_hooks(&mut self, hooks: Vec<Hook>) -> &mut Self {
for hook in hooks {
self.add_hook(hook);
}
self
}
fn set_hooks(&mut self) -> Result<&mut Self>;
}
impl RunHook for Command {
fn set_hooks(&mut self) -> Result<&mut Self> {
prepare()?;
for hook in HOOKS.lock().expect("There is only one thread").drain() {
match hook {
Hook::Open(fun) => {
append(libcfn::open(fun))?;
}
Hook::OpenDir(fun) => {
append(libcfn::opendir(fun))?;
}
Hook::Recv(fun) => {
append(libcfn::recv(fun))?;
}
Hook::RecvMsg(fun) => {
append(libcfn::recv_msg(fun))?;
}
Hook::Read(fun) => {
append(libcfn::read(fun))?;
}
Hook::GetEnv(fun) => {
append(libcfn::getenv(fun))?;
}
}
}
build_dylib()?;
Ok(self.env("LD_PRELOAD", "/tmp/rhookdyl/target/debug/librhookdyl.so"))
}
}
fn prepare() -> Result<()> {
const CARGO_TOML: &str = r#"[package]
name = "rhookdyl"
version = "0.1.0"
edition = "2018"
[lib]
crate-type = ["dylib"]
[dependencies]
libc = "0.2.92""#;
Command::new("cargo")
.arg("new")
.arg("rhookdyl")
.arg("--lib")
.current_dir("/tmp")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?
.wait()?;
std::fs::write("/tmp/rhookdyl/Cargo.toml", CARGO_TOML)?;
std::fs::write("/tmp/rhookdyl/src/lib.rs", include_str!("scaffold.rs"))?;
Ok(())
}
fn append(fun: String) -> Result<()> {
std::fs::OpenOptions::new()
.append(true)
.open("/tmp/rhookdyl/src/lib.rs")?
.write_all(fun.as_bytes())?;
Ok(())
}
fn build_dylib() -> Result<()> {
let status = Command::new("cargo")
.arg("b")
.current_dir("/tmp/rhookdyl")
.env("CARGO_TARGET_DIR", "/tmp/rhookdyl/target")
.spawn()?
.wait()?;
if status.success() {
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::Other,
"failed to compile the dynamic library",
))
}
}