Cotton code
143 lines · 5.8 KB · RustRaw
//! The C ABI the Mac app Cotton links: three functions, JSON in and out.//!//! * `cotton_mac_open(config_json)` opens the one global [`App`] over//!   [`cotton_mac::app::importers`] and answers `{ ok: true }` or//!   `{ ok: false, error, code }`.//! * `cotton_mac_call(method, args_json)` is [`App::call`].//! * `cotton_mac_free(ptr)` releases a string either of the two answered.//!//! Every answer is a heap C string the caller frees with `cotton_mac_free`.//! A panic never crosses the boundary: it is caught and answered as//! `{ ok: false, code: "panic" }`. Calls may come from any thread; the App is//! thread-safe, and the global lock is held only to find it, never across a//! call, so a slow `askCode` does not hold up `status`.use std::ffi::{c_char, CStr, CString};use std::panic::{catch_unwind, AssertUnwindSafe};use std::sync::{Arc, Mutex};use cotton_mac::app::{importers, App, Config};use serde_json::{json, Value};static APP: Mutex<Option<Arc<App>>> = Mutex::new(None);fn failure(error: impl Into<String>, code: &str) -> Value {    json!({ "ok": false, "error": error.into(), "code": code })}fn answer(value: Value) -> *mut c_char {    let text = value.to_string();    // serde_json escapes NUL inside strings, so the text holds none; the    // fallback is there so this function can never fail.    CString::new(text)        .unwrap_or_else(|_| CString::new(r#"{"ok":false,"error":"answer held a NUL","code":"panic"}"#).unwrap())        .into_raw()}/// A C string argument as `&str`; `None` for a null pointer or invalid UTF-8.unsafe fn read<'a>(ptr: *const c_char) -> Option<&'a str> {    if ptr.is_null() {        return None;    }    CStr::from_ptr(ptr).to_str().ok()}fn guarded(f: impl FnOnce() -> Value) -> *mut c_char {    let value = catch_unwind(AssertUnwindSafe(f)).unwrap_or_else(|panic| {        let message = panic            .downcast_ref::<&str>()            .map(|s| s.to_string())            .or_else(|| panic.downcast_ref::<String>().cloned())            .unwrap_or_else(|| "the core panicked".to_string());        failure(message, "panic")    });    answer(value)}fn current() -> Option<Arc<App>> {    APP.lock().unwrap_or_else(|p| p.into_inner()).clone()}/// Open the one App from `config_json` (camelCase `Config`). Opening again/// stops the App already open and replaces it.////// # Safety/// `config_json` is null or a NUL-terminated string valid for the call.#[no_mangle]pub unsafe extern "C" fn cotton_mac_open(config_json: *const c_char) -> *mut c_char {    let text = read(config_json);    guarded(move || {        let Some(text) = text else {            return failure("open needs the config as UTF-8 JSON", "bad_request");        };        let mut config: Config = match serde_json::from_str(text) {            Ok(config) => config,            Err(error) => return failure(format!("config: {error}"), "bad_request"),        };        let previous = APP.lock().unwrap_or_else(|p| p.into_inner()).take();        if let Some(previous) = previous {            previous.stop();        }        // This Mac's device key: its public half is the device id every sign-in, device row and vault row names        // (cotton_mac::approval), so a phone can approve it. Swift's install id is no longer its identity.        // A flavour of the app (its own data folder, `Cotton (dev)`) keeps a device key of its own beside the person's.        let folder = config.data_dir.file_name().and_then(|n| n.to_str()).unwrap_or("Cotton");        let account = if folder == "Cotton" { "device".to_string() } else { format!("device:{folder}") };        let device = match cotton_mac::approval::DeviceKey::load_or_mint(cotton_mac::approval::system_device_keyring(&account).as_ref()) {            Ok(device) => device,            Err(error) => return failure(format!("this Mac's device key: {error}"), "open_failed"),        };        config.device_id = device.id();        let built = importers(&config);        let keyring = cotton_mac::vault::system_keyring(&config.device_id);        match App::open_as(config, built, keyring, Some(device)) {            Ok(app) => {                *APP.lock().unwrap_or_else(|p| p.into_inner()) = Some(Arc::new(app));                json!({ "ok": true })            }            Err(error) => failure(error, "open_failed"),        }    })}/// One method on the open App. `args_json` may be null (no arguments).////// # Safety/// Both arguments are null or NUL-terminated strings valid for the call.#[no_mangle]pub unsafe extern "C" fn cotton_mac_call(method: *const c_char, args_json: *const c_char) -> *mut c_char {    let method = read(method);    let args_null = args_json.is_null();    let args = read(args_json);    guarded(move || {        let Some(method) = method else {            return failure("call needs a method name", "bad_request");        };        let args: Value = match (args_null, args) {            (true, _) => Value::Null,            (false, None) => return failure("arguments are not UTF-8", "bad_request"),            (false, Some(text)) if text.trim().is_empty() => Value::Null,            (false, Some(text)) => match serde_json::from_str(text) {                Ok(value) => value,                Err(error) => return failure(format!("arguments: {error}"), "bad_request"),            },        };        let Some(app) = current() else {            return failure("the core is not open", "not_open");        };        app.call(method, &args)    })}/// Release a string `cotton_mac_open` or `cotton_mac_call` answered. Null is/// accepted and ignored.////// # Safety/// `ptr` is null or a pointer one of the two functions above returned, freed/// at most once.#[no_mangle]pub unsafe extern "C" fn cotton_mac_free(ptr: *mut c_char) {    if !ptr.is_null() {        drop(CString::from_raw(ptr));    }}