Skip to main content

clm_rust_core/layer4/
c_abi.rs

1//! C-ABI Foreign Function Interface for CLM Core Engine.
2//!
3//! Exposes an opaque, thread-safe C-ABI interface for native C, C++, Go, and
4//! dynamic FFI consumers. Adheres to zero-panic invariants by converting all
5//! internal errors into status codes and thread-local error message buffers.
6
7#![allow(unsafe_op_in_unsafe_fn)]
8#![allow(clippy::missing_safety_doc)]
9
10use std::ffi::{CStr, CString};
11use std::os::raw::c_char;
12use std::cell::RefCell;
13
14thread_local! {
15    static LAST_ERROR: RefCell<Option<String>> = const { RefCell::new(None) };
16}
17
18fn set_last_error(msg: String) {
19    LAST_ERROR.with(|e| *e.borrow_mut() = Some(msg));
20}
21
22/// Opaque CLM Engine handle for C-ABI consumers.
23pub struct ClmEngine {
24    #[allow(dead_code)]
25    pillar: String,
26    #[allow(dead_code)]
27    clm_root: String,
28}
29
30/// Allocate and initialize a new CLM Engine instance.
31///
32/// Returns an opaque pointer to `ClmEngine` or NULL on failure.
33#[unsafe(no_mangle)]
34pub unsafe extern "C" fn clm_engine_create(
35    pillar: *const c_char,
36    clm_root: *const c_char,
37) -> *mut ClmEngine {
38    if pillar.is_null() || clm_root.is_null() {
39        set_last_error("Null pointer provided to clm_engine_create".to_string());
40        return std::ptr::null_mut();
41    }
42
43    let p_str = match CStr::from_ptr(pillar).to_str() {
44        Ok(s) => s.to_string(),
45        Err(e) => {
46            set_last_error(format!("Invalid UTF-8 in pillar: {}", e));
47            return std::ptr::null_mut();
48        }
49    };
50
51    let r_str = match CStr::from_ptr(clm_root).to_str() {
52        Ok(s) => s.to_string(),
53        Err(e) => {
54            set_last_error(format!("Invalid UTF-8 in clm_root: {}", e));
55            return std::ptr::null_mut();
56        }
57    };
58
59    Box::into_raw(Box::new(ClmEngine {
60        pillar: p_str,
61        clm_root: r_str,
62    }))
63}
64
65/// Free a previously allocated `ClmEngine` handle.
66#[unsafe(no_mangle)]
67pub unsafe extern "C" fn clm_engine_free(engine: *mut ClmEngine) {
68    if !engine.is_null() {
69        drop(Box::from_raw(engine));
70    }
71}
72
73/// Compute raw cryptographic hash over byte buffer, writing null-terminated hex string to `out_hash`.
74///
75/// Returns 0 on success, or a negative error code on failure.
76#[unsafe(no_mangle)]
77pub unsafe extern "C" fn clm_hash_bytes(
78    data: *const u8,
79    len: usize,
80    out_hash: *mut c_char,
81    out_len: usize,
82) -> i32 {
83    if data.is_null() || out_hash.is_null() {
84        set_last_error("Null pointer provided to clm_hash_bytes".to_string());
85        return -1;
86    }
87
88    let slice = std::slice::from_raw_parts(data, len);
89    let hash = crate::hash::raw_hash_bytes(slice);
90
91    if hash.len() + 1 > out_len {
92        set_last_error(format!("Buffer too small: requires {} bytes", hash.len() + 1));
93        return -2;
94    }
95
96    let c_hash = match CString::new(hash) {
97        Ok(s) => s,
98        Err(e) => {
99            set_last_error(format!("CString creation failure: {}", e));
100            return -3;
101        }
102    };
103
104    std::ptr::copy_nonoverlapping(c_hash.as_ptr(), out_hash, c_hash.as_bytes_with_nul().len());
105    0
106}
107
108/// Query whether an MCard content hash exists in the active database pillar.
109///
110/// Returns 1 if card exists, 0 if card does not exist, or negative on error.
111#[unsafe(no_mangle)]
112pub unsafe extern "C" fn clm_card_exists(
113    engine: *mut ClmEngine,
114    hash: *const c_char,
115) -> i32 {
116    if engine.is_null() || hash.is_null() {
117        set_last_error("Null pointer provided to clm_card_exists".to_string());
118        return -1;
119    }
120
121    let eng = &*engine;
122    let h_str = match CStr::from_ptr(hash).to_str() {
123        Ok(s) => s,
124        Err(e) => {
125            set_last_error(format!("Invalid UTF-8 in hash: {}", e));
126            return -1;
127        }
128    };
129
130    #[cfg(any(feature = "native", feature = "db"))]
131    {
132        match crate::db::card_exists(&eng.pillar, &eng.clm_root, h_str) {
133            Ok(exists) => if exists { 1 } else { 0 },
134            Err(e) => {
135                set_last_error(e.to_string());
136                -2
137            }
138        }
139    }
140    #[cfg(not(any(feature = "native", feature = "db")))]
141    {
142        let _ = (eng, h_str);
143        0
144    }
145}
146
147/// Retrieve MCard content by hash into a caller-allocated character buffer.
148///
149/// Returns 0 on success, 1 if not found, or negative error code on failure.
150#[unsafe(no_mangle)]
151pub unsafe extern "C" fn clm_get_card_content(
152    engine: *mut ClmEngine,
153    hash: *const c_char,
154    out_buf: *mut c_char,
155    out_len: usize,
156) -> i32 {
157    if engine.is_null() || hash.is_null() || out_buf.is_null() {
158        set_last_error("Null pointer provided to clm_get_card_content".to_string());
159        return -1;
160    }
161
162    let eng = &*engine;
163    let h_str = match CStr::from_ptr(hash).to_str() {
164        Ok(s) => s,
165        Err(e) => {
166            set_last_error(format!("Invalid UTF-8 in hash: {}", e));
167            return -1;
168        }
169    };
170
171    #[cfg(any(feature = "native", feature = "db"))]
172    {
173        match crate::db::get_card_content(&eng.pillar, &eng.clm_root, h_str) {
174            Ok(Some(content)) => {
175                if content.len() + 1 > out_len {
176                    set_last_error(format!("Buffer too small: requires {} bytes", content.len() + 1));
177                    return -2;
178                }
179                let c_content = match CString::new(content) {
180                    Ok(s) => s,
181                    Err(e) => {
182                        set_last_error(e.to_string());
183                        return -3;
184                    }
185                };
186                std::ptr::copy_nonoverlapping(c_content.as_ptr(), out_buf, c_content.as_bytes_with_nul().len());
187                0
188            }
189            Ok(None) => 1,
190            Err(e) => {
191                set_last_error(e.to_string());
192                -4
193            }
194        }
195    }
196    #[cfg(not(any(feature = "native", feature = "db")))]
197    {
198        let _ = (eng, h_str, out_buf, out_len);
199        1
200    }
201}
202
203/// Copy the last thread-local error message into the caller's buffer.
204///
205/// Returns 0 on success, or negative error code on failure.
206#[unsafe(no_mangle)]
207pub unsafe extern "C" fn clm_last_error_message(buf: *mut c_char, len: usize) -> i32 {
208    if buf.is_null() || len == 0 {
209        return -1;
210    }
211
212    let msg = LAST_ERROR.with(|e| e.borrow().clone().unwrap_or_default());
213    if msg.is_empty() {
214        *buf = 0;
215        return 0;
216    }
217
218    let c_msg = match CString::new(msg) {
219        Ok(s) => s,
220        Err(_) => return -2,
221    };
222
223    let bytes = c_msg.as_bytes_with_nul();
224    let copy_len = std::cmp::min(bytes.len(), len);
225    std::ptr::copy_nonoverlapping(bytes.as_ptr() as *const c_char, buf, copy_len);
226    *buf.add(copy_len - 1) = 0;
227    0
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233    use std::ffi::CString;
234
235    #[test]
236    fn test_c_abi_engine_lifecycle() {
237        unsafe {
238            let pillar = CString::new("test_pillar").unwrap();
239            let root = CString::new("/tmp/test_clm").unwrap();
240            let engine = clm_engine_create(pillar.as_ptr(), root.as_ptr());
241            assert!(!engine.is_null());
242            clm_engine_free(engine);
243
244            // Null pointer safety
245            let null_engine = clm_engine_create(std::ptr::null(), root.as_ptr());
246            assert!(null_engine.is_null());
247
248            let mut err_buf = [0 as c_char; 256];
249            let rc = clm_last_error_message(err_buf.as_mut_ptr(), err_buf.len());
250            assert_eq!(rc, 0);
251            let err_str = CStr::from_ptr(err_buf.as_ptr()).to_str().unwrap();
252            assert!(err_str.contains("Null pointer"));
253        }
254    }
255
256    #[test]
257    fn test_c_abi_hash_and_card_exists() {
258        unsafe {
259            let data = b"hello world";
260            let mut out_hash = [0 as c_char; 128];
261            let res = clm_hash_bytes(data.as_ptr(), data.len(), out_hash.as_mut_ptr(), out_hash.len());
262            assert_eq!(res, 0);
263            let hash_str = CStr::from_ptr(out_hash.as_ptr()).to_str().unwrap();
264            assert_eq!(hash_str.len(), 64);
265
266            let pillar = CString::new("test_pillar").unwrap();
267            let root = CString::new("/tmp/test_clm").unwrap();
268            let engine = clm_engine_create(pillar.as_ptr(), root.as_ptr());
269            assert!(!engine.is_null());
270
271            let exists = clm_card_exists(engine, out_hash.as_ptr());
272            assert_eq!(exists, 0); // Not found in empty /tmp DB
273
274            clm_engine_free(engine);
275        }
276    }
277}
278