Skip to main content

weirdnet_code_spaces/
host.rs

1//! The host side of the plugin ABI: the table a plugin's run gets, over an application's
2//! [`Host`]. Requests and replies are text (JSON by convention); what the methods are and
3//! what they read and write is the application's.
4use crate::abi::{CALL_ERROR, CALL_OK, WnBuf, WnHost, WnStr};
5use std::ffi::c_void;
6
7/// An application's host methods for one run.
8pub trait Host {
9    /// Handle one call: the method's name and the request text; the reply text, or the
10    /// error message the plugin gets.
11    fn call(&mut self, method: &str, request: &str) -> Result<String, String>;
12}
13
14/// Run `run` (a loaded plugin's run function) with `host` behind a host table that says
15/// `abi_version`. Returns the plugin's code ([`crate::abi::RUN_OK`], `RUN_ERROR`,
16/// `RUN_PANIC`, or anything else it returned).
17///
18/// # Safety
19/// `run` must be a run function the application loaded and approved (see
20/// [`crate::approved`]), of the ABI the table's version says; it runs as native code with
21/// the process's rights.
22pub unsafe fn run_with(abi_version: u32, run: crate::abi::PluginRun, host: &mut dyn Host) -> i32 {
23    let mut h: &mut dyn Host = host;
24    let table = WnHost { abi_version, ctx: &mut h as *mut &mut dyn Host as *mut c_void, call: host_call, free: host_free };
25    // SAFETY: the caller vouches for `run`; `table` and `h` outlive the call.
26    unsafe { run(&table) }
27}
28
29fn reply(out: *mut WnBuf, s: String) {
30    let b = s.into_bytes().into_boxed_slice();
31    let len = b.len();
32    let ptr = Box::into_raw(b) as *mut u8;
33    // SAFETY: `out` is the plugin's buffer for this call.
34    unsafe { *out = WnBuf { ptr, len, cap: len } };
35}
36
37/// `WnHost::call`.
38unsafe extern "C" fn host_call(ctx: *mut c_void, method: WnStr, request: WnStr, out: *mut WnBuf) -> i32 {
39    if ctx.is_null() || out.is_null() {
40        return CALL_ERROR;
41    }
42    // SAFETY: the plugin passes back the ctx we gave it, and lends the strings for this call.
43    let (host, method, request) = unsafe { (&mut *(ctx as *mut &mut dyn Host), method.as_bytes(), request.as_bytes()) };
44    let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<String, String> {
45        let method = std::str::from_utf8(method).map_err(|_| "invalid host method: not UTF-8".to_string())?;
46        let text = std::str::from_utf8(request).map_err(|_| "invalid request: not UTF-8".to_string())?;
47        host.call(method, text)
48    }));
49    match res {
50        Ok(Ok(s)) => {
51            reply(out, s);
52            CALL_OK
53        }
54        Ok(Err(e)) => {
55            reply(out, e);
56            CALL_ERROR
57        }
58        Err(_) => {
59            reply(out, "the host failed on this call".into());
60            CALL_ERROR
61        }
62    }
63}
64
65/// `WnHost::free`.
66unsafe extern "C" fn host_free(_ctx: *mut c_void, buf: WnBuf) {
67    if !buf.ptr.is_null() {
68        // SAFETY: made by `reply` from a boxed slice of exactly `len` bytes.
69        drop(unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(buf.ptr, buf.len)) });
70    }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76    use crate::abi::{RUN_ERROR, RUN_OK};
77
78    struct Echo(Vec<String>);
79    impl Host for Echo {
80        fn call(&mut self, method: &str, request: &str) -> Result<String, String> {
81            self.0.push(format!("{method}:{request}"));
82            match method {
83                "boom" => panic!("no"),
84                "fail" => Err("nope".into()),
85                _ => Ok(format!("[{request}]")),
86            }
87        }
88    }
89
90    fn call(h: &WnHost, m: &[u8], r: &str) -> (i32, String) {
91        let mut out = WnBuf::EMPTY;
92        let m = WnStr { ptr: m.as_ptr(), len: m.len() };
93        // SAFETY: a valid table and strings for the call
94        unsafe {
95            let c = (h.call)(h.ctx, m, WnStr::new(r), &mut out);
96            let t = String::from_utf8(out.as_slice().to_vec()).unwrap();
97            (h.free)(h.ctx, out);
98            (c, t)
99        }
100    }
101
102    impl WnBuf {
103        fn as_slice(&self) -> &[u8] {
104            // SAFETY: test buffers come from `reply`
105            unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
106        }
107    }
108
109    unsafe extern "C" fn plugin(h: *const WnHost) -> i32 {
110        // SAFETY: the table run_with made
111        let h = unsafe { &*h };
112        assert_eq!(h.abi_version, 7);
113        assert_eq!(call(h, b"echo", "{}"), (CALL_OK, "[{}]".into()));
114        assert_eq!(call(h, b"fail", "x"), (CALL_ERROR, "nope".into()));
115        assert_eq!(call(h, b"boom", ""), (CALL_ERROR, "the host failed on this call".into()));
116        assert_eq!(call(h, &[0xff], ""), (CALL_ERROR, "invalid host method: not UTF-8".into()));
117        if h.ctx.is_null() { RUN_ERROR } else { RUN_OK }
118    }
119
120    #[test]
121    fn calls_reach_the_host_and_errors_come_back() {
122        let mut e = Echo(vec![]);
123        std::panic::set_hook(Box::new(|_| {}));
124        // SAFETY: a test plugin
125        let code = unsafe { run_with(7, plugin, &mut e) };
126        let _ = std::panic::take_hook();
127        assert_eq!(code, RUN_OK);
128        assert_eq!(e.0, vec!["echo:{}", "fail:x", "boom:"]);
129    }
130}