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
#[cfg(feature = "hooks")]
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[cfg(feature = "hooks")]
use std::sync::Mutex;
#[cfg(feature = "hooks")]
use extism::{Error as ExtismError, Manifest, Plugin, Wasm};
#[cfg(feature = "hooks")]
use std::path::Path;
/// Input data for the hook_client_query_received function
#[cfg(feature = "hooks")]
#[derive(Serialize, Deserialize)]
struct QueryInput<'a> {
query_name: &'a str,
qtype: u16,
qclass: u16,
client_ip: &'a str,
}
/// Hooks structure for customizing DNS query processing
///
/// This structure will be initialized when the program starts and
/// will be accessible by the query manager's submit_query function.
/// It is designed to be thread-safe.
#[derive(Debug, Clone)]
pub struct Hooks {
/// WebAssembly plugin for hook implementations
#[cfg(feature = "hooks")]
wasm_plugin: Option<Arc<Mutex<Plugin>>>,
}
impl Default for Hooks {
fn default() -> Self {
Self::new()
}
}
impl Hooks {
/// Create a new Hooks instance
pub fn new() -> Self {
Self {
#[cfg(feature = "hooks")]
wasm_plugin: None,
}
}
/// Create a new Hooks instance with a WebAssembly plugin
///
/// # Arguments
///
/// * `wasm_file_path` - Path to the WebAssembly file
/// * `enable_wasi` - Whether to enable WASI for the WebAssembly plugin
///
/// # Returns
///
/// A Result containing the Hooks instance or an error
#[cfg(feature = "hooks")]
pub fn with_wasm_file<P: AsRef<Path>>(
wasm_file_path: P,
enable_wasi: bool,
) -> Result<Self, ExtismError> {
// Create a Wasm object from the file path
let wasm = Wasm::file(wasm_file_path);
// Create a manifest with the Wasm object
let manifest = Manifest::new([wasm]);
// Create the plugin from the manifest
// The third parameter controls whether WASI is enabled
let plugin = Plugin::new(manifest, vec![], enable_wasi)?;
// Return the Hooks instance with the plugin
Ok(Self {
wasm_plugin: Some(Arc::new(Mutex::new(plugin))),
})
}
/// Create a new Hooks instance with a WebAssembly plugin
///
/// This is a stub implementation when the hooks feature is disabled.
/// It always returns an error.
#[cfg(not(feature = "hooks"))]
pub fn with_wasm_file<P>(_wasm_file_path: P, _enable_wasi: bool) -> Result<Self, &'static str> {
Err("WebAssembly hooks support is not enabled. Recompile with the 'hooks' feature.")
}
/// Hook called when a client query is received
///
/// # Arguments
///
/// * `query_name` - The domain name being queried
/// * `qtype` - The query type (e.g., A, AAAA, MX)
/// * `qclass` - The query class (usually IN for Internet)
/// * `client_ip` - The client IP address (without port)
/// * `query_data` - The raw query data
///
/// # Returns
///
/// An integer code:
/// * 0 - Continue normal processing
/// * -1 - Return a minimal response with REFUSED rcode
/// * Other values may be defined in the future
pub fn hook_client_query_received(
&self,
#[cfg(feature = "hooks")] query_name: &str,
#[cfg(not(feature = "hooks"))] _query_name: &str,
#[cfg(feature = "hooks")] qtype: u16,
#[cfg(not(feature = "hooks"))] _qtype: u16,
#[cfg(feature = "hooks")] qclass: u16,
#[cfg(not(feature = "hooks"))] _qclass: u16,
#[cfg(feature = "hooks")] client_ip: &str,
#[cfg(not(feature = "hooks"))] _client_ip: &str,
_query_data: &[u8],
) -> i32 {
// If hooks are enabled and we have a WebAssembly plugin, call it
#[cfg(feature = "hooks")]
{
if let Some(plugin_arc) = &self.wasm_plugin {
// Create input data for the WebAssembly function
let input = QueryInput {
query_name,
qtype,
qclass,
client_ip,
};
let input_json = serde_json::to_string(&input).unwrap_or_else(|e| {
log::warn!("Failed to serialize query input: {e}");
String::new()
});
// Try to lock the plugin
if let Ok(mut plugin) = plugin_arc.lock() {
// Call the WebAssembly function
match plugin.call::<&str, &str>("hook_client_query_received", &input_json) {
Ok(result_str) => {
// Try to parse the result as an i32
if let Ok(result_code) = result_str.parse::<i32>() {
log::debug!(
"WebAssembly hook_client_query_received for {query_name} returned: {result_code}"
);
return result_code;
} else {
log::warn!(
"WebAssembly hook_client_query_received returned invalid result: {result_str}"
);
}
}
Err(e) => {
log::warn!("Error calling WebAssembly hook_client_query_received: {e}");
}
}
} else {
log::warn!("Failed to lock WebAssembly plugin");
}
}
}
// For now, just return 0 to continue normal processing
0
}
}
/// Thread-safe wrapper for Hooks
#[derive(Debug, Clone)]
pub struct SharedHooks {
inner: Arc<Hooks>,
}
impl SharedHooks {
/// Create a new SharedHooks instance
pub fn new() -> Self {
Self {
inner: Arc::new(Hooks::new()),
}
}
/// Create a new SharedHooks instance with the given Hooks
pub fn with_hooks(hooks: Hooks) -> Self {
Self {
inner: Arc::new(hooks),
}
}
/// Get a reference to the inner Hooks
#[allow(dead_code)]
pub fn inner(&self) -> &Arc<Hooks> {
&self.inner
}
/// Hook called when a client query is received
///
/// # Arguments
///
/// * `query_name` - The domain name being queried
/// * `qtype` - The query type (e.g., A, AAAA, MX)
/// * `qclass` - The query class (usually IN for Internet)
/// * `client_ip` - The client IP address (without port)
/// * `query_data` - The raw query data
///
/// # Returns
///
/// An integer code:
/// * 0 - Continue normal processing
/// * -1 - Return a minimal response with REFUSED rcode
/// * Other values may be defined in the future
pub fn hook_client_query_received(
&self,
query_name: &str,
qtype: u16,
qclass: u16,
client_ip: &str,
query_data: &[u8],
) -> i32 {
self.inner
.hook_client_query_received(query_name, qtype, qclass, client_ip, query_data)
}
}
impl Default for SharedHooks {
fn default() -> Self {
Self::new()
}
}