use std::ffi::CString;
use std::os::raw::c_char;
use eggfetch_core::Client;
pub struct ClientBuilderHandle(pub(crate) Option<eggfetch_core::ClientBuilder>);
pub struct ClientHandle(pub(crate) Client);
pub struct RequestHandle(pub(crate) Option<eggfetch_core::RequestBuilder>);
pub struct ResponseHandle {
pub(crate) status: u16,
pub(crate) url: String,
pub(crate) headers: Vec<(String, String)>,
pub(crate) body: bytes::Bytes,
}
pub struct ErrorHandle {
pub(crate) kind: String,
pub(crate) message: String,
}
#[repr(C)]
pub struct FfiString {
ptr: *mut c_char,
}
impl FfiString {
#[must_use]
pub unsafe fn from_string(s: String) -> Option<Self> {
let c = CString::new(s).ok()?;
Some(Self { ptr: c.into_raw() })
}
#[must_use]
pub unsafe fn from_static(s: &'static str) -> Option<Self> {
Self::from_string(s.to_owned())
}
#[must_use]
pub fn into_raw(self) -> *mut c_char {
let ptr = self.ptr;
let _ = std::mem::ManuallyDrop::new(self);
ptr
}
}
impl Drop for FfiString {
fn drop(&mut self) {
if !self.ptr.is_null() {
unsafe {
drop(CString::from_raw(self.ptr));
}
}
}
}
#[no_mangle]
pub unsafe extern "C" fn eggfetch_string_free(s: *mut c_char) {
crate::ffi_guard!((), {
if !s.is_null() {
drop(CString::from_raw(s));
}
});
}
pub(crate) const MAX_CSTR_LEN: usize = 1024 * 1024;
pub(crate) unsafe fn cstr_to_string(ptr: *const c_char) -> Option<String> {
if ptr.is_null() {
None
} else {
let mut len = 0usize;
while len < MAX_CSTR_LEN {
let byte = unsafe { *ptr.add(len) };
if byte == 0 {
break;
}
len += 1;
}
if len >= MAX_CSTR_LEN {
return None;
}
let slice = unsafe { std::slice::from_raw_parts(ptr.cast::<u8>(), len) };
String::from_utf8(slice.to_vec()).ok()
}
}
#[must_use]
#[allow(clippy::unnecessary_box_returns)]
pub(crate) fn error_to_handle(e: &eggfetch_core::Error) -> Box<ErrorHandle> {
Box::new(ErrorHandle {
kind: e.kind().to_owned(),
message: redact_credentials(&e.to_string()),
})
}
fn redact_credentials(message: &str) -> String {
let mut result = message.to_owned();
let mut search_from = 0;
while let Some(scheme_pos) = result[search_from..].find("://") {
let userinfo_start = search_from + scheme_pos + 3;
let rest = &result[userinfo_start..];
let Some(at_pos) = rest.find('@') else {
break;
};
let terminator = [
rest.find('/'),
rest.find(' '),
rest.find('"'),
rest.find('\''),
]
.into_iter()
.flatten()
.min()
.unwrap_or(rest.len());
if at_pos < terminator {
result.replace_range(userinfo_start..=userinfo_start + at_pos, "<redacted>@");
search_from = userinfo_start + "<redacted>@".len();
} else {
search_from = userinfo_start;
}
if search_from >= result.len() {
break;
}
}
result
}
#[cfg(test)]
mod tests {
use super::{cstr_to_string, MAX_CSTR_LEN};
fn c_buffer(contents: &[u8]) -> Vec<u8> {
let mut buf = contents.to_vec();
buf.push(0);
buf
}
#[test]
fn cstr_scan_is_signedness_agnostic() {
let buf = c_buffer(b"https://example.com/path");
let ptr = buf.as_ptr().cast::<std::os::raw::c_char>();
let decoded = unsafe { cstr_to_string(ptr) };
assert_eq!(decoded.as_deref(), Some("https://example.com/path"));
}
#[test]
fn cstr_scan_stops_at_first_nul() {
let buf = c_buffer(b"");
let ptr = buf.as_ptr().cast::<std::os::raw::c_char>();
let decoded = unsafe { cstr_to_string(ptr) };
assert_eq!(decoded.as_deref(), Some(""));
}
#[test]
fn cstr_scan_rejects_overlong_input() {
let buf = c_buffer(&vec![b'a'; MAX_CSTR_LEN + 1]);
let ptr = buf.as_ptr().cast::<std::os::raw::c_char>();
let decoded = unsafe { cstr_to_string(ptr) };
assert!(decoded.is_none(), "over-long C strings must fail closed");
}
#[test]
fn cstr_scan_rejects_null_pointer() {
let decoded = unsafe { cstr_to_string(std::ptr::null()) };
assert!(decoded.is_none());
}
}