Skip to main content

cpa_plugin/
native.rs

1//! The native C ABI (internal/pluginhost/loader_unix.go, host_callbacks_unix.go).
2//!
3//! ```c
4//! typedef struct { void* ptr; size_t len; } cliproxy_buffer;
5//! typedef struct { uint32_t abi_version; void* host_ctx; host_call_fn call; host_free_fn free_buffer; } cliproxy_host_api;
6//! typedef struct { uint32_t abi_version; plugin_call_fn call; plugin_free_fn free_buffer; plugin_shutdown_fn shutdown; } cliproxy_plugin_api;
7//! int cliproxy_plugin_init(const cliproxy_host_api*, cliproxy_plugin_api*);
8//! ```
9//!
10//! Memory ownership matches Go: the host owns request buffers for the duration of a
11//! call; a response buffer belongs to whoever allocated it and is released through that
12//! side's `free_buffer`. Host callback responses are `malloc`ed and freed with `free`.
13//! The host API table and the `host_ctx` slot are `malloc`ed, stay valid after shutdown
14//! (plugins keep the pointer), and `host_ctx` holds a numeric ID resolved through a
15//! global table, so a stale context can never reach a dropped host. As in Go v8.0.35,
16//! loaded images and their C callback tables stay resident even after failed init;
17//! shutdown removes their callback registrations, not the memory a runtime may retain.
18
19use 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/// `cliproxy_buffer`.
31#[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/// `cliproxy_host_api`.
45#[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/// `cliproxy_plugin_api`.
54#[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
80/// `cliproxyHostCall`. Returns 0 with an error envelope for callback failures and 1 only
81/// for an unusable context.
82unsafe 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            // SAFETY: the plugin passes a valid, writable buffer slot.
92            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        // SAFETY: ctx is the host_ctx slot this module allocated; it holds the ID.
101        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        // SAFETY: method is a NUL-terminated string owned by the plugin for the call.
110        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            // SAFETY: the plugin owns `request_len` readable bytes for the call.
115            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        // SAFETY: plain malloc; released by `host_free`.
125        let ptr = unsafe { libc::malloc(resp.len()) };
126        if ptr.is_null() {
127            return 1;
128        }
129        // SAFETY: ptr has resp.len() bytes; response is valid (checked above).
130        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    // Never unwind into the plugin.
138    std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)).unwrap_or(1)
139}
140
141/// `cliproxyHostFree`.
142unsafe extern "C" fn host_free(ptr: *mut c_void, _len: usize) {
143    if !ptr.is_null() {
144        // SAFETY: allocated by `host_call` with malloc.
145        unsafe { libc::free(ptr) };
146    }
147}
148
149/// A loaded plugin library speaking ABI 1.
150pub struct NativeClient {
151    host_api: *mut HostApi,
152    api: PluginApi,
153    callback_id: usize,
154    instance: Arc<CallbackInstance>,
155    /// `true` once shut down. Calls hold it shared for their whole duration (including
156    /// the response copy and `free_buffer`); shutdown takes it exclusively, so the
157    /// plugin's shutdown entry point cannot run under an in-flight call.
158    gate: RwLock<bool>,
159}
160
161// SAFETY: the raw pointers remain resident, and shutdown runs after every call has
162// returned. Plugin entry points are
163// required to be thread-safe by the ABI (Go calls them from any goroutine).
164unsafe impl Send for NativeClient {}
165unsafe impl Sync for NativeClient {}
166
167impl NativeClient {
168    /// Go `dynamicLibraryLoader.Open`: dlopen, resolve `cliproxy_plugin_init`, hand it the
169    /// host table and validate the plugin table.
170    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        // SAFETY: dlopen with a valid C string.
180        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            // The shadow stays: another open may have just reused it, and unlinking here
184            // would bypass shadow publication. Stale cleanup removes it with this process.
185            // The shadow path shows where a noexec TMPDIR refused the mapping.
186            return Err(format!(
187                "dlopen {} (shadow copy {}): {error}",
188                path.display(),
189                load_path.display()
190            ));
191        }
192        // Go loader_unix.go: dlopen can start a Go c-shared runtime before init.
193        // Never dlclose a mapped image, including on all subsequent failure paths.
194        // SAFETY: handle is live; symbol name is a valid C string.
195        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        // SAFETY: malloc'd tables, initialised before use.
201        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            // SAFETY: init has not seen these allocations; free(NULL) is a no-op.
205            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        // SAFETY: both allocations are valid for writes.
221        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        // SAFETY: `init` is the plugin's exported cliproxy_plugin_init.
238        let init: InitFn = unsafe { std::mem::transmute::<*mut c_void, InitFn>(init) };
239        // SAFETY: both tables are valid; the plugin fills `api`.
240        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    /// Go `dynamicLibraryClient.Call`. A non-zero return with an error envelope is a
262    /// normal RPC failure; any other non-zero return is a transport error.
263    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        // C.CString stops at the first NUL as far as the plugin can see.
272        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        // SAFETY: the plugin's call entry point with host-owned buffers.
283        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            // SAFETY: the plugin returned `len` readable bytes at `ptr`.
286            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            // SAFETY: released through the plugin's own allocator.
292            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    /// Go `dynamicLibraryClient.Shutdown`: logically close the instance and drop the
308    /// callback entry. Images and C callback tables stay mapped. Idempotent.
309    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            // SAFETY: the plugin's shutdown entry point, called once.
318            unsafe { shutdown() };
319        }
320        lock(callbacks()).remove(&self.callback_id);
321        // The resident runtime may still call host_call with the old context. Keep
322        // both allocations valid; its numeric ID now fails lookup without pinning
323        // the callback handler or accessing a dropped Host.
324    }
325}
326
327impl Drop for NativeClient {
328    fn drop(&mut self) {
329        self.shutdown();
330    }
331}
332
333fn dlerror() -> String {
334    // SAFETY: dlerror returns NULL or a thread-local C string.
335    let err = unsafe { libc::dlerror() };
336    if err.is_null() {
337        return String::new();
338    }
339    // SAFETY: non-null C string from dlerror.
340    unsafe { CStr::from_ptr(err) }.to_string_lossy().into_owned()
341}