1use std::collections::HashMap;
20use std::ffi::{CStr, CString, c_char, c_int, c_void};
21use std::path::Path;
22use std::sync::atomic::{AtomicUsize, Ordering};
23use std::sync::{Arc, Mutex, OnceLock, RwLock};
24
25use bytes::Bytes;
26
27use crate::abi;
28use crate::client::{CallbackHandler, CallbackInstance};
29
30#[repr(C)]
32pub struct Buffer {
33 pub ptr: *mut c_void,
34 pub len: usize,
35}
36
37type HostCallFn = unsafe extern "C" fn(*mut c_void, *const c_char, *const u8, usize, *mut Buffer) -> c_int;
38type HostFreeFn = unsafe extern "C" fn(*mut c_void, usize);
39type PluginCallFn = unsafe extern "C" fn(*const c_char, *const u8, usize, *mut Buffer) -> c_int;
40type PluginFreeFn = unsafe extern "C" fn(*mut c_void, usize);
41type PluginShutdownFn = unsafe extern "C" fn();
42type InitFn = unsafe extern "C" fn(*const HostApi, *mut PluginApi) -> c_int;
43
44#[repr(C)]
46pub struct HostApi {
47 pub abi_version: u32,
48 pub host_ctx: *mut c_void,
49 pub call: Option<HostCallFn>,
50 pub free_buffer: Option<HostFreeFn>,
51}
52
53#[repr(C)]
55#[derive(Default)]
56pub struct PluginApi {
57 pub abi_version: u32,
58 pub call: Option<PluginCallFn>,
59 pub free_buffer: Option<PluginFreeFn>,
60 pub shutdown: Option<PluginShutdownFn>,
61}
62
63struct CallbackEntry {
64 handler: Arc<dyn CallbackHandler>,
65 plugin_id: String,
66 instance: Arc<CallbackInstance>,
67}
68
69fn callbacks() -> &'static Mutex<HashMap<usize, CallbackEntry>> {
70 static ENTRIES: OnceLock<Mutex<HashMap<usize, CallbackEntry>>> = OnceLock::new();
71 ENTRIES.get_or_init(Default::default)
72}
73
74static NEXT_CALLBACK_ID: AtomicUsize = AtomicUsize::new(0);
75
76fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
77 m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
78}
79
80unsafe extern "C" fn host_call(
83 ctx: *mut c_void,
84 method: *const c_char,
85 request: *const u8,
86 request_len: usize,
87 response: *mut Buffer,
88) -> c_int {
89 let run = || -> c_int {
90 if !response.is_null() {
91 unsafe {
93 (*response).ptr = std::ptr::null_mut();
94 (*response).len = 0;
95 }
96 }
97 if ctx.is_null() || method.is_null() {
98 return 1;
99 }
100 let id = unsafe { *(ctx as *const usize) };
102 let (handler, plugin_id, instance) = {
103 let entries = lock(callbacks());
104 let Some(entry) = entries.get(&id) else {
105 return 1;
106 };
107 (entry.handler.clone(), entry.plugin_id.clone(), entry.instance.clone())
108 };
109 let method = unsafe { CStr::from_ptr(method) }.to_string_lossy().into_owned();
111 let request = if request.is_null() || request_len == 0 {
112 Bytes::new()
113 } else {
114 Bytes::copy_from_slice(unsafe { std::slice::from_raw_parts(request, request_len) })
116 };
117 let resp = match handler.call_from_plugin(&plugin_id, &instance, &method, request) {
118 Ok(resp) => resp,
119 Err(e) => abi::error_envelope("host_call_failed", &e.message, e.status),
120 };
121 if resp.is_empty() || response.is_null() {
122 return 0;
123 }
124 let ptr = unsafe { libc::malloc(resp.len()) };
126 if ptr.is_null() {
127 return 1;
128 }
129 unsafe {
131 std::ptr::copy_nonoverlapping(resp.as_ptr(), ptr.cast::<u8>(), resp.len());
132 (*response).ptr = ptr;
133 (*response).len = resp.len();
134 }
135 0
136 };
137 std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)).unwrap_or(1)
139}
140
141unsafe extern "C" fn host_free(ptr: *mut c_void, _len: usize) {
143 if !ptr.is_null() {
144 unsafe { libc::free(ptr) };
146 }
147}
148
149pub struct NativeClient {
151 host_api: *mut HostApi,
152 api: PluginApi,
153 callback_id: usize,
154 instance: Arc<CallbackInstance>,
155 gate: RwLock<bool>,
159}
160
161unsafe impl Send for NativeClient {}
165unsafe impl Sync for NativeClient {}
166
167impl NativeClient {
168 pub fn open(
171 path: &Path,
172 plugin_id: &str,
173 handler: Arc<dyn CallbackHandler>,
174 instance: Arc<CallbackInstance>,
175 ) -> Result<Self, String> {
176 let load_path = crate::shadow::copy(path, plugin_id)?;
177 let c_path = CString::new(load_path.as_os_str().as_encoded_bytes())
178 .map_err(|_| format!("dlopen {}: path contains NUL", path.display()))?;
179 let handle = unsafe { libc::dlopen(c_path.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
181 if handle.is_null() {
182 let error = dlerror();
183 return Err(format!(
187 "dlopen {} (shadow copy {}): {error}",
188 path.display(),
189 load_path.display()
190 ));
191 }
192 let init = unsafe { libc::dlsym(handle, c"cliproxy_plugin_init".as_ptr()) };
196 if init.is_null() {
197 let err = dlerror();
198 return Err(format!("missing cliproxy_plugin_init: {err}"));
199 }
200 let host_api = unsafe { libc::malloc(std::mem::size_of::<HostApi>()) }.cast::<HostApi>();
202 let host_ctx = unsafe { libc::malloc(std::mem::size_of::<usize>()) }.cast::<usize>();
203 if host_api.is_null() || host_ctx.is_null() {
204 unsafe {
206 libc::free(host_api.cast());
207 libc::free(host_ctx.cast());
208 }
209 return Err("allocate host api".into());
210 }
211 let callback_id = NEXT_CALLBACK_ID.fetch_add(1, Ordering::SeqCst) + 1;
212 lock(callbacks()).insert(
213 callback_id,
214 CallbackEntry {
215 handler,
216 plugin_id: plugin_id.to_owned(),
217 instance: instance.clone(),
218 },
219 );
220 unsafe {
222 host_ctx.write(callback_id);
223 host_api.write(HostApi {
224 abi_version: abi::ABI_VERSION,
225 host_ctx: host_ctx.cast(),
226 call: Some(host_call),
227 free_buffer: Some(host_free),
228 });
229 }
230 let mut client = NativeClient {
231 host_api,
232 api: PluginApi::default(),
233 callback_id,
234 instance,
235 gate: RwLock::new(false),
236 };
237 let init: InitFn = unsafe { std::mem::transmute::<*mut c_void, InitFn>(init) };
239 let rc = unsafe { init(client.host_api, &mut client.api) };
241 if rc != 0 {
242 client.shutdown();
243 return Err(format!("cliproxy_plugin_init returned {rc}"));
244 }
245 if client.api.abi_version != abi::ABI_VERSION {
246 let version = client.api.abi_version;
247 client.shutdown();
248 return Err(format!("plugin ABI version {version} is not supported"));
249 }
250 if client.api.call.is_none() || client.api.free_buffer.is_none() {
251 client.shutdown();
252 return Err("plugin function table is incomplete".into());
253 }
254 Ok(client)
255 }
256
257 pub fn instance(&self) -> &Arc<CallbackInstance> {
258 &self.instance
259 }
260
261 pub fn call(&self, method: &str, request: &[u8]) -> Result<Bytes, String> {
264 let gate = self.gate.read().unwrap_or_else(std::sync::PoisonError::into_inner);
265 if *gate {
266 return Err("plugin client is closed".into());
267 }
268 let (Some(call), Some(free)) = (self.api.call, self.api.free_buffer) else {
269 return Err("plugin client is closed".into());
270 };
271 let method_c = CString::new(method.split('\0').next().unwrap_or_default()).unwrap_or_default();
273 let mut response = Buffer {
274 ptr: std::ptr::null_mut(),
275 len: 0,
276 };
277 let req_ptr = if request.is_empty() {
278 std::ptr::null()
279 } else {
280 request.as_ptr()
281 };
282 let rc = unsafe { call(method_c.as_ptr(), req_ptr, request.len(), &mut response) };
284 let out = if !response.ptr.is_null() && response.len > 0 {
285 Bytes::copy_from_slice(unsafe { std::slice::from_raw_parts(response.ptr.cast::<u8>(), response.len) })
287 } else {
288 Bytes::new()
289 };
290 if !response.ptr.is_null() {
291 unsafe { free(response.ptr, response.len) };
293 }
294 drop(gate);
295 if rc != 0 {
296 if abi::Envelope::is_error(&out) {
297 return Ok(out);
298 }
299 return Err(format!(
300 "plugin call {method} returned {rc}: {}",
301 String::from_utf8_lossy(&out)
302 ));
303 }
304 Ok(out)
305 }
306
307 pub fn shutdown(&self) {
310 let mut shut = self.gate.write().unwrap_or_else(std::sync::PoisonError::into_inner);
311 if *shut {
312 return;
313 }
314 *shut = true;
315 self.instance.close();
316 if let Some(shutdown) = self.api.shutdown {
317 unsafe { shutdown() };
319 }
320 lock(callbacks()).remove(&self.callback_id);
321 }
325}
326
327impl Drop for NativeClient {
328 fn drop(&mut self) {
329 self.shutdown();
330 }
331}
332
333fn dlerror() -> String {
334 let err = unsafe { libc::dlerror() };
336 if err.is_null() {
337 return String::new();
338 }
339 unsafe { CStr::from_ptr(err) }.to_string_lossy().into_owned()
341}