Skip to main content

libsimplex_rs/
ffi.rs

1//! Safe Rust facade for the official SimpleX Chat Haskell library.
2//!
3//! The ABI is exported by `Simplex.Chat.Mobile`, the same interface used by the
4//! official mobile, desktop and Node.js clients. All domain commands and events
5//! cross the boundary as JSON; protocol and persistence logic remain in Haskell.
6
7use std::{
8    ffi::{CStr, CString, NulError, c_char, c_int, c_void},
9    mem::ManuallyDrop,
10    path::{Path, PathBuf},
11    ptr,
12    sync::{Arc, Mutex, OnceLock},
13    time::Duration,
14};
15
16use libloading::Library;
17use serde_json::Value;
18use thiserror::Error;
19
20type ChatCtrl = *mut c_void;
21type HsInit = unsafe extern "C" fn(*mut c_int, *mut *mut *mut c_char);
22type ChatMigrateInit =
23    unsafe extern "C" fn(*const c_char, *const c_char, *const c_char, *mut ChatCtrl) -> *mut c_char;
24#[cfg(test)]
25type ChatCtrlCall = unsafe extern "C" fn(ChatCtrl) -> *mut c_char;
26type ChatSendCmd = unsafe extern "C" fn(ChatCtrl, *const c_char) -> *mut c_char;
27type ChatRecvWait = unsafe extern "C" fn(ChatCtrl, c_int) -> *mut c_char;
28
29static HASKELL_RUNTIME: OnceLock<()> = OnceLock::new();
30
31#[derive(Debug, Error)]
32pub enum SimplexError {
33    #[error("could not load SimpleX library {path}: {source}")]
34    LoadLibrary {
35        path: PathBuf,
36        #[source]
37        source: libloading::Error,
38    },
39    #[error("SimpleX library is missing symbol {symbol}: {source}")]
40    MissingSymbol {
41        symbol: &'static str,
42        #[source]
43        source: libloading::Error,
44    },
45    #[error("input contains a NUL byte")]
46    InvalidInput(#[from] NulError),
47    #[error("SimpleX returned a null pointer from {0}")]
48    NullResult(&'static str),
49    #[error("SimpleX returned invalid UTF-8: {0}")]
50    InvalidUtf8(#[from] std::str::Utf8Error),
51    #[error("SimpleX returned invalid JSON: {0}")]
52    InvalidJson(#[from] serde_json::Error),
53    #[error("SimpleX controller lock was poisoned")]
54    ControllerPoisoned,
55    #[error("receive timeout exceeds the SimpleX ABI limit")]
56    TimeoutOverflow,
57}
58
59/// Locations owned by simplex-tui. No user-editable configuration file is used.
60#[derive(Clone, Debug, Eq, PartialEq)]
61pub struct SimplexPaths {
62    pub root: PathBuf,
63    pub database_prefix: PathBuf,
64}
65
66impl SimplexPaths {
67    pub fn at(root: impl Into<PathBuf>) -> Self {
68        let root = root.into();
69        let database_prefix = root.join("simplex");
70        Self {
71            root,
72            database_prefix,
73        }
74    }
75
76    pub fn create(&self) -> std::io::Result<()> {
77        std::fs::create_dir_all(&self.root)?;
78        #[cfg(unix)]
79        {
80            use std::os::unix::fs::PermissionsExt;
81            std::fs::set_permissions(&self.root, std::fs::Permissions::from_mode(0o700))?;
82        }
83        Ok(())
84    }
85}
86
87struct Symbols {
88    migrate_init: ChatMigrateInit,
89    #[cfg(test)]
90    close_store: ChatCtrlCall,
91    send_cmd: ChatSendCmd,
92    recv_wait: ChatRecvWait,
93}
94
95/// Loaded official Haskell library. Keep this alive as long as any controller exists.
96pub struct SimplexApi {
97    // A live GHC runtime must never be dlclosed. The OS reclaims it at process exit.
98    _library: ManuallyDrop<Library>,
99    symbols: Symbols,
100}
101
102impl SimplexApi {
103    /// Load the native SimpleX library built by the official desktop build script.
104    ///
105    /// # Safety
106    /// `path` must point to an ABI-compatible official SimpleX Chat library and
107    /// its GHC runtime dependencies must be discoverable by the dynamic loader.
108    pub unsafe fn load(path: impl AsRef<Path>) -> Result<Arc<Self>, SimplexError> {
109        let path = path.as_ref();
110        // GHC's dynamically linked RTS requires its symbols in the global namespace.
111        // SAFETY: the caller guarantees this is a compatible SimpleX library.
112        #[cfg(unix)]
113        let library: Library = unsafe {
114            libloading::os::unix::Library::open(Some(path), libc::RTLD_NOW | libc::RTLD_GLOBAL)
115        }
116        .map(Into::into)
117        .map_err(|source| SimplexError::LoadLibrary {
118            path: path.to_path_buf(),
119            source,
120        })?;
121        #[cfg(not(unix))]
122        let library =
123            unsafe { Library::new(path) }.map_err(|source| SimplexError::LoadLibrary {
124                path: path.to_path_buf(),
125                source,
126            })?;
127
128        // Copying function pointers lets the symbols borrow no longer than this scope;
129        // `_library` keeps their code loaded for the lifetime of `SimplexApi`.
130        let hs_init: HsInit =
131            unsafe { symbol(&library, b"hs_init_with_rtsopts\0", "hs_init_with_rtsopts")? };
132        let symbols = Symbols {
133            migrate_init: unsafe { symbol(&library, b"chat_migrate_init\0", "chat_migrate_init")? },
134            #[cfg(test)]
135            close_store: unsafe { symbol(&library, b"chat_close_store\0", "chat_close_store")? },
136            send_cmd: unsafe { symbol(&library, b"chat_send_cmd\0", "chat_send_cmd")? },
137            recv_wait: unsafe { symbol(&library, b"chat_recv_msg_wait\0", "chat_recv_msg_wait")? },
138        };
139
140        HASKELL_RUNTIME.get_or_init(|| {
141            // GHC 9.6.3's non-moving collector (-xn) crashes in evacuate when
142            // this library is embedded in the Rust process. Use the standard
143            // moving collector; allocation and initial heap sizes still match
144            // the official desktop wrapper.
145            let arguments = [
146                "simplex",
147                "+RTS",
148                "-A64m",
149                "-H64m",
150                "--install-signal-handlers=no",
151            ];
152            let c_arguments: Vec<CString> = arguments
153                .iter()
154                .map(|argument| CString::new(*argument).expect("static RTS argument contains NUL"))
155                .collect();
156            let mut pointers: Vec<*mut c_char> = c_arguments
157                .iter()
158                .map(|argument| argument.as_ptr().cast_mut())
159                .chain(std::iter::once(ptr::null_mut()))
160                .collect();
161            let mut argc = arguments.len() as c_int;
162            let mut argv = pointers.as_mut_ptr();
163            // SAFETY: argv is writable, NUL-terminated, and remains alive for the call.
164            unsafe { hs_init(&mut argc, &mut argv) };
165        });
166
167        Ok(Arc::new(Self {
168            _library: ManuallyDrop::new(library),
169            symbols,
170        }))
171    }
172
173    pub fn open(
174        self: &Arc<Self>,
175        database_prefix: &Path,
176        database_key: &str,
177        migration_confirmation: &str,
178    ) -> Result<(SimplexController, Value), SimplexError> {
179        let path = cstring_path(database_prefix)?;
180        let key = CString::new(database_key)?;
181        let confirmation = CString::new(migration_confirmation)?;
182        let mut controller = ptr::null_mut();
183        // SAFETY: strings are valid for the call and controller is a writable out pointer.
184        let result = unsafe {
185            (self.symbols.migrate_init)(
186                path.as_ptr(),
187                key.as_ptr(),
188                confirmation.as_ptr(),
189                &mut controller,
190            )
191        };
192        let migration = unsafe { take_json(result, "chat_migrate_init")? };
193        if controller.is_null() {
194            return Err(SimplexError::NullResult("chat_migrate_init controller"));
195        }
196        Ok((
197            SimplexController {
198                api: Arc::clone(self),
199                raw: Mutex::new(controller),
200            },
201            migration,
202        ))
203    }
204}
205
206/// Thread-safe owner of a Haskell `ChatController` stable pointer.
207pub struct SimplexController {
208    api: Arc<SimplexApi>,
209    raw: Mutex<ChatCtrl>,
210}
211
212// The mutex serializes access to the opaque stable pointer. SimpleX itself owns
213// its worker threads and communicates through its command/event queues.
214unsafe impl Send for SimplexController {}
215unsafe impl Sync for SimplexController {}
216
217impl SimplexController {
218    /// Execute any command supported by the official SimpleX chat command API.
219    pub fn command(&self, command: &str) -> Result<Value, SimplexError> {
220        let command = CString::new(command)?;
221        let ctrl = *self
222            .raw
223            .lock()
224            .map_err(|_| SimplexError::ControllerPoisoned)?;
225        // SAFETY: the controller remains owned by self and command lives through the call.
226        unsafe {
227            take_json(
228                (self.api.symbols.send_cmd)(ctrl, command.as_ptr()),
229                "chat_send_cmd",
230            )
231        }
232    }
233
234    /// Wait for the next asynchronous SimpleX event. An empty string means timeout.
235    pub fn recv(&self, timeout: Duration) -> Result<Option<Value>, SimplexError> {
236        let micros: c_int = timeout
237            .as_micros()
238            .try_into()
239            .map_err(|_| SimplexError::TimeoutOverflow)?;
240        let ctrl = *self
241            .raw
242            .lock()
243            .map_err(|_| SimplexError::ControllerPoisoned)?;
244        // SAFETY: the controller remains owned by self for the duration of the call.
245        unsafe {
246            take_optional_json(
247                (self.api.symbols.recv_wait)(ctrl, micros),
248                "chat_recv_msg_wait",
249            )
250        }
251    }
252
253    #[cfg(test)]
254    pub fn close_store(&self) -> Result<String, SimplexError> {
255        self.store_call(self.api.symbols.close_store, "chat_close_store")
256    }
257
258    #[cfg(test)]
259    fn store_call(&self, call: ChatCtrlCall, name: &'static str) -> Result<String, SimplexError> {
260        let ctrl = *self
261            .raw
262            .lock()
263            .map_err(|_| SimplexError::ControllerPoisoned)?;
264        // SAFETY: the controller remains owned by self for the duration of the call.
265        unsafe { take_string(call(ctrl), name) }
266    }
267}
268
269unsafe fn symbol<T: Copy>(
270    library: &Library,
271    name: &[u8],
272    display_name: &'static str,
273) -> Result<T, SimplexError> {
274    // SAFETY: callers provide the exact function type defined by the upstream C ABI.
275    unsafe { library.get::<T>(name) }
276        .map(|symbol| *symbol)
277        .map_err(|source| SimplexError::MissingSymbol {
278            symbol: display_name,
279            source,
280        })
281}
282
283fn cstring_path(path: &Path) -> Result<CString, SimplexError> {
284    CString::new(path.to_string_lossy().as_bytes()).map_err(Into::into)
285}
286
287unsafe fn take_string(pointer: *mut c_char, name: &'static str) -> Result<String, SimplexError> {
288    if pointer.is_null() {
289        return Err(SimplexError::NullResult(name));
290    }
291    // SAFETY: upstream returns a malloc-allocated, NUL-terminated CString.
292    let result = unsafe { CStr::from_ptr(pointer) }
293        .to_str()
294        .map(str::to_owned);
295    // SAFETY: upstream's official Node.js binding frees these results with libc free.
296    unsafe { libc::free(pointer.cast()) };
297    Ok(result?)
298}
299
300unsafe fn take_json(pointer: *mut c_char, name: &'static str) -> Result<Value, SimplexError> {
301    let value = unsafe { take_string(pointer, name)? };
302    Ok(serde_json::from_str(&value)?)
303}
304
305unsafe fn take_optional_json(
306    pointer: *mut c_char,
307    name: &'static str,
308) -> Result<Option<Value>, SimplexError> {
309    let value = unsafe { take_string(pointer, name)? };
310    if value.is_empty() {
311        Ok(None)
312    } else {
313        Ok(Some(serde_json::from_str(&value)?))
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    fn bundled_library_path() -> PathBuf {
322        let name = if cfg!(target_os = "linux") {
323            "libsimplex.so"
324        } else if cfg!(target_os = "macos") {
325            "libsimplex.dylib"
326        } else {
327            "libsimplex.dll"
328        };
329        Path::new(env!("CARGO_MANIFEST_DIR"))
330            .join("../..")
331            .join("vendor/libsimplex")
332            .join(name)
333    }
334
335    #[test]
336    fn app_data_lives_under_one_root() {
337        let paths = SimplexPaths::at("/tmp/example-home/.simplex-tui");
338        assert_eq!(
339            paths.database_prefix,
340            PathBuf::from("/tmp/example-home/.simplex-tui/simplex")
341        );
342    }
343
344    #[test]
345    #[ignore = "requires the separately built official Haskell library"]
346    fn loads_official_haskell_runtime() {
347        let library = std::env::var_os("SIMPLEX_LIBRARY")
348            .map(PathBuf::from)
349            .unwrap_or_else(bundled_library_path);
350        // SAFETY: this test explicitly targets the pinned library built by our bootstrap script.
351        let api = unsafe { SimplexApi::load(library) };
352        assert!(api.is_ok(), "{:#}", api.err().expect("error exists"));
353    }
354
355    #[test]
356    #[ignore = "requires the separately built official Haskell library"]
357    fn opens_database_and_calls_chat_api() {
358        let library = std::env::var_os("SIMPLEX_LIBRARY")
359            .map(PathBuf::from)
360            .unwrap_or_else(bundled_library_path);
361        // SAFETY: this test explicitly targets the pinned library built by our bootstrap script.
362        let api = unsafe { SimplexApi::load(library) }.expect("load SimpleX library");
363        let temp = tempfile::tempdir().expect("create temporary data directory");
364        let (controller, migration) = api
365            .open(&temp.path().join("simplex"), "", "yesUp")
366            .expect("initialize SimpleX database");
367        assert_eq!(migration.get("type").and_then(Value::as_str), Some("ok"));
368        controller.command("/u").expect("query active user");
369        controller.close_store().expect("close SimpleX database");
370    }
371
372    #[test]
373    #[ignore = "requires the separately built official Haskell library"]
374    fn creates_lists_and_activates_profile() {
375        let library = bundled_library_path();
376        // SAFETY: this test explicitly targets the pinned library built by our bootstrap script.
377        let api = unsafe { SimplexApi::load(library) }.expect("load SimpleX library");
378        let temp = tempfile::tempdir().expect("create temporary data directory");
379        let (controller, _) = api
380            .open(&temp.path().join("simplex"), "", "yesUp")
381            .expect("initialize SimpleX database");
382        let created = controller
383            .command(
384                "/_create user {\"profile\":{\"displayName\":\"Test User\",\"fullName\":\"\"},\"pastTimestamp\":false}",
385            )
386            .expect("create profile");
387        let user_id = created
388            .pointer("/result/user/userId")
389            .and_then(Value::as_i64)
390            .expect("created user id");
391        controller.command("/_start").expect("start chat");
392        let users = controller.command("/users").expect("list profiles");
393        assert_eq!(
394            users.pointer("/result/type").and_then(Value::as_str),
395            Some("usersList")
396        );
397        controller
398            .command(&format!("/_user {user_id}"))
399            .expect("activate profile");
400        controller.close_store().expect("close SimpleX database");
401    }
402}