Skip to main content

clm_rust_core/
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
9use std::ffi::{CStr, CString};
10use std::os::raw::c_char;
11use std::cell::RefCell;
12
13thread_local! {
14    static LAST_ERROR: RefCell<Option<String>> = const { RefCell::new(None) };
15}
16
17fn set_last_error(msg: String) {
18    LAST_ERROR.with(|e| *e.borrow_mut() = Some(msg));
19}
20
21/// Opaque CLM Engine handle for C-ABI consumers.
22pub struct ClmEngine {
23    #[allow(dead_code)]
24    pillar: String,
25    #[allow(dead_code)]
26    clm_root: String,
27}
28
29/// Allocate and initialize a new CLM Engine instance.
30///
31/// Returns an opaque pointer to `ClmEngine` or NULL on failure.
32#[unsafe(no_mangle)]
33pub unsafe extern "C" fn clm_engine_create(
34    pillar: *const c_char,
35    clm_root: *const c_char,
36) -> *mut ClmEngine {
37    if pillar.is_null() || clm_root.is_null() {
38        set_last_error("Null pointer provided to clm_engine_create".to_string());
39        return std::ptr::null_mut();
40    }
41
42    let p_str = match CStr::from_ptr(pillar).to_str() {
43        Ok(s) => s.to_string(),
44        Err(e) => {
45            set_last_error(format!("Invalid UTF-8 in pillar: {}", e));
46            return std::ptr::null_mut();
47        }
48    };
49
50    let r_str = match CStr::from_ptr(clm_root).to_str() {
51        Ok(s) => s.to_string(),
52        Err(e) => {
53            set_last_error(format!("Invalid UTF-8 in clm_root: {}", e));
54            return std::ptr::null_mut();
55        }
56    };
57
58    Box::into_raw(Box::new(ClmEngine {
59        pillar: p_str,
60        clm_root: r_str,
61    }))
62}
63
64/// Free a previously allocated `ClmEngine` handle.
65#[unsafe(no_mangle)]
66pub unsafe extern "C" fn clm_engine_free(engine: *mut ClmEngine) {
67    if !engine.is_null() {
68        drop(Box::from_raw(engine));
69    }
70}
71
72/// Compute raw cryptographic hash over byte buffer, writing null-terminated hex string to `out_hash`.
73///
74/// Returns 0 on success, or a negative error code on failure.
75#[unsafe(no_mangle)]
76pub unsafe extern "C" fn clm_hash_bytes(
77    data: *const u8,
78    len: usize,
79    out_hash: *mut c_char,
80    out_len: usize,
81) -> i32 {
82    if data.is_null() || out_hash.is_null() {
83        set_last_error("Null pointer provided to clm_hash_bytes".to_string());
84        return -1;
85    }
86
87    let slice = std::slice::from_raw_parts(data, len);
88    let hash = crate::hash::raw_hash_bytes(slice);
89
90    if hash.len() + 1 > out_len {
91        set_last_error(format!("Buffer too small: requires {} bytes", hash.len() + 1));
92        return -2;
93    }
94
95    let c_hash = match CString::new(hash) {
96        Ok(s) => s,
97        Err(e) => {
98            set_last_error(format!("CString creation failure: {}", e));
99            return -3;
100        }
101    };
102
103    std::ptr::copy_nonoverlapping(c_hash.as_ptr(), out_hash, c_hash.as_bytes_with_nul().len());
104    0
105}
106
107/// Query whether an MCard content hash exists in the active database pillar.
108///
109/// Returns 1 if card exists, 0 if card does not exist, or negative on error.
110#[unsafe(no_mangle)]
111pub unsafe extern "C" fn clm_card_exists(
112    engine: *mut ClmEngine,
113    hash: *const c_char,
114) -> i32 {
115    if engine.is_null() || hash.is_null() {
116        set_last_error("Null pointer provided to clm_card_exists".to_string());
117        return -1;
118    }
119
120    let eng = &*engine;
121    let h_str = match CStr::from_ptr(hash).to_str() {
122        Ok(s) => s,
123        Err(e) => {
124            set_last_error(format!("Invalid UTF-8 in hash: {}", e));
125            return -1;
126        }
127    };
128
129    #[cfg(any(feature = "native", feature = "db"))]
130    {
131        match crate::db::card_exists(&eng.pillar, &eng.clm_root, h_str) {
132            Ok(exists) => if exists { 1 } else { 0 },
133            Err(e) => {
134                set_last_error(e.to_string());
135                -2
136            }
137        }
138    }
139    #[cfg(not(any(feature = "native", feature = "db")))]
140    {
141        let _ = (eng, h_str);
142        0
143    }
144}
145
146/// Retrieve MCard content by hash into a caller-allocated character buffer.
147///
148/// Returns 0 on success, 1 if not found, or negative error code on failure.
149#[unsafe(no_mangle)]
150pub unsafe extern "C" fn clm_get_card_content(
151    engine: *mut ClmEngine,
152    hash: *const c_char,
153    out_buf: *mut c_char,
154    out_len: usize,
155) -> i32 {
156    if engine.is_null() || hash.is_null() || out_buf.is_null() {
157        set_last_error("Null pointer provided to clm_get_card_content".to_string());
158        return -1;
159    }
160
161    let eng = &*engine;
162    let h_str = match CStr::from_ptr(hash).to_str() {
163        Ok(s) => s,
164        Err(e) => {
165            set_last_error(format!("Invalid UTF-8 in hash: {}", e));
166            return -1;
167        }
168    };
169
170    #[cfg(any(feature = "native", feature = "db"))]
171    {
172        match crate::db::get_card_content(&eng.pillar, &eng.clm_root, h_str) {
173            Ok(Some(content)) => {
174                if content.len() + 1 > out_len {
175                    set_last_error(format!("Buffer too small: requires {} bytes", content.len() + 1));
176                    return -2;
177                }
178                let c_content = match CString::new(content) {
179                    Ok(s) => s,
180                    Err(e) => {
181                        set_last_error(e.to_string());
182                        return -3;
183                    }
184                };
185                std::ptr::copy_nonoverlapping(c_content.as_ptr(), out_buf, c_content.as_bytes_with_nul().len());
186                0
187            }
188            Ok(None) => 1,
189            Err(e) => {
190                set_last_error(e.to_string());
191                -4
192            }
193        }
194    }
195    #[cfg(not(any(feature = "native", feature = "db")))]
196    {
197        let _ = (eng, h_str, out_buf, out_len);
198        1
199    }
200}
201
202/// Copy the last thread-local error message into the caller's buffer.
203///
204/// Returns 0 on success, or negative error code on failure.
205#[unsafe(no_mangle)]
206pub unsafe extern "C" fn clm_last_error_message(buf: *mut c_char, len: usize) -> i32 {
207    if buf.is_null() || len == 0 {
208        return -1;
209    }
210
211    let msg = LAST_ERROR.with(|e| e.borrow().clone().unwrap_or_default());
212    if msg.is_empty() {
213        *buf = 0;
214        return 0;
215    }
216
217    let c_msg = match CString::new(msg) {
218        Ok(s) => s,
219        Err(_) => return -2,
220    };
221
222    let bytes = c_msg.as_bytes_with_nul();
223    let copy_len = std::cmp::min(bytes.len(), len);
224    std::ptr::copy_nonoverlapping(bytes.as_ptr() as *const c_char, buf, copy_len);
225    *buf.add(copy_len - 1) = 0;
226    0
227}