clm-kernel 0.0.5

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! C-ABI Foreign Function Interface for CLM Core Engine.
//!
//! Exposes an opaque, thread-safe C-ABI interface for native C, C++, Go, and
//! dynamic FFI consumers. Adheres to zero-panic invariants by converting all
//! internal errors into status codes and thread-local error message buffers.

#![allow(unsafe_op_in_unsafe_fn)]
#![allow(clippy::missing_safety_doc)]

use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::cell::RefCell;

thread_local! {
    static LAST_ERROR: RefCell<Option<String>> = const { RefCell::new(None) };
}

fn set_last_error(msg: String) {
    LAST_ERROR.with(|e| *e.borrow_mut() = Some(msg));
}

/// Opaque CLM Engine handle for C-ABI consumers.
pub struct ClmEngine {
    #[allow(dead_code)]
    pillar: String,
    #[allow(dead_code)]
    clm_root: String,
}

/// Allocate and initialize a new CLM Engine instance.
///
/// Returns an opaque pointer to `ClmEngine` or NULL on failure.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn clm_engine_create(
    pillar: *const c_char,
    clm_root: *const c_char,
) -> *mut ClmEngine {
    if pillar.is_null() || clm_root.is_null() {
        set_last_error("Null pointer provided to clm_engine_create".to_string());
        return std::ptr::null_mut();
    }

    let p_str = match CStr::from_ptr(pillar).to_str() {
        Ok(s) => s.to_string(),
        Err(e) => {
            set_last_error(format!("Invalid UTF-8 in pillar: {}", e));
            return std::ptr::null_mut();
        }
    };

    let r_str = match CStr::from_ptr(clm_root).to_str() {
        Ok(s) => s.to_string(),
        Err(e) => {
            set_last_error(format!("Invalid UTF-8 in clm_root: {}", e));
            return std::ptr::null_mut();
        }
    };

    Box::into_raw(Box::new(ClmEngine {
        pillar: p_str,
        clm_root: r_str,
    }))
}

/// Free a previously allocated `ClmEngine` handle.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn clm_engine_free(engine: *mut ClmEngine) {
    if !engine.is_null() {
        drop(Box::from_raw(engine));
    }
}

/// Compute raw cryptographic hash over byte buffer, writing null-terminated hex string to `out_hash`.
///
/// Returns 0 on success, or a negative error code on failure.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn clm_hash_bytes(
    data: *const u8,
    len: usize,
    out_hash: *mut c_char,
    out_len: usize,
) -> i32 {
    if data.is_null() || out_hash.is_null() {
        set_last_error("Null pointer provided to clm_hash_bytes".to_string());
        return -1;
    }

    let slice = std::slice::from_raw_parts(data, len);
    let hash = crate::hash::raw_hash_bytes(slice);

    if hash.len() + 1 > out_len {
        set_last_error(format!("Buffer too small: requires {} bytes", hash.len() + 1));
        return -2;
    }

    let c_hash = match CString::new(hash) {
        Ok(s) => s,
        Err(e) => {
            set_last_error(format!("CString creation failure: {}", e));
            return -3;
        }
    };

    std::ptr::copy_nonoverlapping(c_hash.as_ptr(), out_hash, c_hash.as_bytes_with_nul().len());
    0
}

/// Query whether an MCard content hash exists in the active database pillar.
///
/// Returns 1 if card exists, 0 if card does not exist, or negative on error.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn clm_card_exists(
    engine: *mut ClmEngine,
    hash: *const c_char,
) -> i32 {
    if engine.is_null() || hash.is_null() {
        set_last_error("Null pointer provided to clm_card_exists".to_string());
        return -1;
    }

    let eng = &*engine;
    let h_str = match CStr::from_ptr(hash).to_str() {
        Ok(s) => s,
        Err(e) => {
            set_last_error(format!("Invalid UTF-8 in hash: {}", e));
            return -1;
        }
    };

    #[cfg(any(feature = "native", feature = "db"))]
    {
        match crate::db::card_exists(&eng.pillar, &eng.clm_root, h_str) {
            Ok(exists) => if exists { 1 } else { 0 },
            Err(e) => {
                set_last_error(e.to_string());
                -2
            }
        }
    }
    #[cfg(not(any(feature = "native", feature = "db")))]
    {
        let _ = (eng, h_str);
        0
    }
}

/// Retrieve MCard content by hash into a caller-allocated character buffer.
///
/// Returns 0 on success, 1 if not found, or negative error code on failure.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn clm_get_card_content(
    engine: *mut ClmEngine,
    hash: *const c_char,
    out_buf: *mut c_char,
    out_len: usize,
) -> i32 {
    if engine.is_null() || hash.is_null() || out_buf.is_null() {
        set_last_error("Null pointer provided to clm_get_card_content".to_string());
        return -1;
    }

    let eng = &*engine;
    let h_str = match CStr::from_ptr(hash).to_str() {
        Ok(s) => s,
        Err(e) => {
            set_last_error(format!("Invalid UTF-8 in hash: {}", e));
            return -1;
        }
    };

    #[cfg(any(feature = "native", feature = "db"))]
    {
        match crate::db::get_card_content(&eng.pillar, &eng.clm_root, h_str) {
            Ok(Some(content)) => {
                if content.len() + 1 > out_len {
                    set_last_error(format!("Buffer too small: requires {} bytes", content.len() + 1));
                    return -2;
                }
                let c_content = match CString::new(content) {
                    Ok(s) => s,
                    Err(e) => {
                        set_last_error(e.to_string());
                        return -3;
                    }
                };
                std::ptr::copy_nonoverlapping(c_content.as_ptr(), out_buf, c_content.as_bytes_with_nul().len());
                0
            }
            Ok(None) => 1,
            Err(e) => {
                set_last_error(e.to_string());
                -4
            }
        }
    }
    #[cfg(not(any(feature = "native", feature = "db")))]
    {
        let _ = (eng, h_str, out_buf, out_len);
        1
    }
}

/// Copy the last thread-local error message into the caller's buffer.
///
/// Returns 0 on success, or negative error code on failure.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn clm_last_error_message(buf: *mut c_char, len: usize) -> i32 {
    if buf.is_null() || len == 0 {
        return -1;
    }

    let msg = LAST_ERROR.with(|e| e.borrow().clone().unwrap_or_default());
    if msg.is_empty() {
        *buf = 0;
        return 0;
    }

    let c_msg = match CString::new(msg) {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let bytes = c_msg.as_bytes_with_nul();
    let copy_len = std::cmp::min(bytes.len(), len);
    std::ptr::copy_nonoverlapping(bytes.as_ptr() as *const c_char, buf, copy_len);
    *buf.add(copy_len - 1) = 0;
    0
}