Skip to main content

eggfetch_ffi/
handle.rs

1//! Opaque handle types for FFI.
2
3use std::ffi::CString;
4use std::os::raw::c_char;
5
6use eggfetch_core::Client;
7
8use crate::protocol::MissingProtocolCapability;
9
10/// Opaque handle to a client builder.
11///
12/// Single-thread, single-use. Must be consumed by building a client or freed.
13pub struct ClientBuilderHandle {
14    pub(crate) builder: Option<eggfetch_core::ClientBuilder>,
15    /// Protocol capability a strict HTTP-version policy requires that this
16    /// build does not provide.
17    ///
18    /// The gap is recorded when the policy is set so the request can be
19    /// rejected with a named cause before any connection is attempted.
20    pub(crate) missing_capability: Option<MissingProtocolCapability>,
21}
22
23/// Opaque handle to an HTTP client.
24///
25/// Thread-safe: may be shared across threads.
26pub struct ClientHandle {
27    pub(crate) client: Client,
28    /// Protocol capability a strict HTTP-version policy requires that this
29    /// build does not provide.
30    ///
31    /// Requests through such a client are rejected before any connection is
32    /// attempted.
33    pub(crate) missing_capability: Option<MissingProtocolCapability>,
34}
35
36/// Opaque handle to a request builder.
37///
38/// Single-thread, single-use. Must be freed after use.
39pub struct RequestHandle(pub(crate) Option<eggfetch_core::RequestBuilder>);
40
41/// Opaque handle to a completed response.
42///
43/// Single-thread, single-use. Must be freed after body is consumed.
44pub struct ResponseHandle {
45    pub(crate) status: u16,
46    pub(crate) url: String,
47    pub(crate) headers: Vec<(String, String)>,
48    pub(crate) body: bytes::Bytes,
49}
50
51/// Opaque handle to an error.
52///
53/// Single-thread, single-use. Must be freed after inspection.
54pub struct ErrorHandle {
55    pub(crate) kind: String,
56    pub(crate) message: String,
57}
58
59/// Owned C string returned by FFI. Must be freed with [`eggfetch_string_free`].
60#[repr(C)]
61pub struct FfiString {
62    ptr: *mut c_char,
63}
64
65impl FfiString {
66    /// Create an owned C string from a Rust [`String`].
67    ///
68    /// Returns `None` if the string contains an interior null byte. Callers
69    /// must surface that case as a null pointer or error code; silently
70    /// substituting placeholder content would corrupt the reported value.
71    ///
72    /// # Safety
73    ///
74    /// Caller must free the returned [`FfiString`] with [`eggfetch_string_free`].
75    #[must_use]
76    pub unsafe fn from_string(s: String) -> Option<Self> {
77        let c = CString::new(s).ok()?;
78        Some(Self { ptr: c.into_raw() })
79    }
80
81    /// Create an owned C string from a static str.
82    ///
83    /// Returns `None` if the string contains an interior null byte.
84    ///
85    /// # Safety
86    ///
87    /// Caller must free the returned [`FfiString`] with [`eggfetch_string_free`].
88    #[must_use]
89    pub unsafe fn from_static(s: &'static str) -> Option<Self> {
90        Self::from_string(s.to_owned())
91    }
92
93    /// Return the raw pointer. Caller takes ownership.
94    #[must_use]
95    pub fn into_raw(self) -> *mut c_char {
96        let ptr = self.ptr;
97        // Safety: We intentionally do not drop self here — the caller owns the pointer.
98        let _ = std::mem::ManuallyDrop::new(self);
99        ptr
100    }
101}
102
103impl Drop for FfiString {
104    fn drop(&mut self) {
105        if !self.ptr.is_null() {
106            // Safety: ptr was created by CString::into_raw, so it's valid to reconstruct.
107            unsafe {
108                drop(CString::from_raw(self.ptr));
109            }
110        }
111    }
112}
113
114/// Free a string returned by an eggfetch FFI function.
115///
116/// # Safety
117///
118/// `s` must have been returned by an eggfetch FFI function and not freed yet.
119/// Passing a null pointer is a no-op.
120#[no_mangle]
121pub unsafe extern "C" fn eggfetch_string_free(s: *mut c_char) {
122    crate::ffi_guard!((), {
123        if !s.is_null() {
124            drop(CString::from_raw(s));
125        }
126    });
127}
128
129/// Read a C string from a pointer, returning an owned copy (`None` if null).
130///
131/// Returns owned data because a raw pointer carries no lifetime to borrow
132/// against; every caller immediately consumes the value into owned state.
133/// Maximum C-string scan length (1 MiB) to bound `cstr_to_string`.
134///
135/// The C ABI requires scanning for NUL, but an unterminated pointer must not
136/// read unbounded memory: fail closed past this limit. `MAX_FFI_BODY_LEN`
137/// (256 MiB) covers only `request_body` byte buffers, not NUL-terminated strings.
138pub(crate) const MAX_CSTR_LEN: usize = 1024 * 1024;
139///
140/// # Safety
141///
142/// `ptr` must be null or point to a valid null-terminated C string.
143/// This performs a bounded scan for the terminator (up to `MAX_CSTR_LEN`);
144/// unterminated or over-long inputs return `None` instead of reading OOB.
145pub(crate) unsafe fn cstr_to_string(ptr: *const c_char) -> Option<String> {
146    if ptr.is_null() {
147        None
148    } else {
149        // Bounded `strnlen`: stop at NUL or MAX_CSTR_LEN.
150        let mut len = 0usize;
151        while len < MAX_CSTR_LEN {
152            // `c_char` is `i8` on most targets but `u8` on aarch64 Linux, so
153            // compare the C character against 0 directly instead of going
154            // through a signed-only conversion.
155            let byte = unsafe { *ptr.add(len) };
156            if byte == 0 {
157                break;
158            }
159            len += 1;
160        }
161        if len >= MAX_CSTR_LEN {
162            return None;
163        }
164        let slice = unsafe { std::slice::from_raw_parts(ptr.cast::<u8>(), len) };
165        String::from_utf8(slice.to_vec()).ok()
166    }
167}
168
169/// Convert an eggfetch error into an owned error handle.
170///
171/// Returns a `Box<ErrorHandle>` suitable for FFI raw-pointer return.
172#[must_use]
173#[allow(
174    clippy::unnecessary_box_returns,
175    reason = "the boxed handle is the ownership token the C caller releases through `eggfetch_error_free`, so the allocation has to stay boxed"
176)]
177pub(crate) fn error_to_handle(e: &eggfetch_core::Error) -> Box<ErrorHandle> {
178    Box::new(ErrorHandle {
179        kind: e.kind().to_owned(),
180        // Redact `user:pass@` userinfo: core messages may echo the request
181        // URL, and the C string crosses the ABI verbatim otherwise.
182        message: redact_credentials(&e.to_string()),
183    })
184}
185
186/// Reject a request whose client was built with a strict HTTP-version policy
187/// that this build cannot honor.
188///
189/// Returns `true` when the request must be rejected. The reason is written to
190/// `err_out` (when it is not null) as an `unsupported` error whose message
191/// names the missing capability, so the C consumer can report it through the
192/// ordinary error channel. No connection is attempted for a rejected request.
193pub(crate) fn reject_missing_capability(
194    client: *const ClientHandle,
195    err_out: *mut *mut ErrorHandle,
196) -> bool {
197    // SAFETY: `as_ref` returns `None` for a null pointer and otherwise
198    // borrows the handle for the duration of the call; the caller keeps the
199    // handle alive across the call.
200    let capability = unsafe { client.as_ref().and_then(|c| c.missing_capability) };
201    let Some(capability) = capability else {
202        return false;
203    };
204    if !err_out.is_null() {
205        let err = capability.error();
206        // SAFETY: `err_out` is non-null and the caller owns the slot; it is
207        // written with a freshly allocated error handle that the caller frees
208        // with `eggfetch_error_free`.
209        unsafe {
210            *err_out = Box::into_raw(error_to_handle(&err));
211        }
212    }
213    true
214}
215
216/// Redact `user:pass@` userinfo from error strings.
217///
218/// Replaces every `://<userinfo>@` with `://<redacted>@` (mirrors the
219/// Python binding's redaction so C callers get the same guarantee).
220fn redact_credentials(message: &str) -> String {
221    let mut result = message.to_owned();
222    let mut search_from = 0;
223    while let Some(scheme_pos) = result[search_from..].find("://") {
224        let userinfo_start = search_from + scheme_pos + 3;
225        let rest = &result[userinfo_start..];
226        let Some(at_pos) = rest.find('@') else {
227            break;
228        };
229        let terminator = [
230            rest.find('/'),
231            rest.find(' '),
232            rest.find('"'),
233            rest.find('\''),
234        ]
235        .into_iter()
236        .flatten()
237        .min()
238        .unwrap_or(rest.len());
239        if at_pos < terminator {
240            result.replace_range(userinfo_start..=userinfo_start + at_pos, "<redacted>@");
241            search_from = userinfo_start + "<redacted>@".len();
242        } else {
243            search_from = userinfo_start;
244        }
245        if search_from >= result.len() {
246            break;
247        }
248    }
249    result
250}
251
252#[cfg(test)]
253mod tests {
254    use super::{cstr_to_string, MAX_CSTR_LEN};
255
256    /// Build a genuine NUL-terminated C buffer, as the ABI requires.
257    fn c_buffer(contents: &[u8]) -> Vec<u8> {
258        let mut buf = contents.to_vec();
259        buf.push(0);
260        buf
261    }
262
263    /// Pin the bounded-scan contract on both `c_char` signedness variants:
264    /// `c_char` is `i8` on most targets but `u8` on aarch64 Linux, so the
265    /// scan must not rely on a signed-only integer conversion.
266    #[test]
267    fn cstr_scan_is_signedness_agnostic() {
268        let buf = c_buffer(b"https://example.com/path");
269        let ptr = buf.as_ptr().cast::<std::os::raw::c_char>();
270        // SAFETY: `ptr` points at `buf`, which is NUL-terminated.
271        let decoded = unsafe { cstr_to_string(ptr) };
272        assert_eq!(decoded.as_deref(), Some("https://example.com/path"));
273    }
274
275    /// A leading NUL yields the empty string rather than scanning past it.
276    #[test]
277    fn cstr_scan_stops_at_first_nul() {
278        let buf = c_buffer(b"");
279        let ptr = buf.as_ptr().cast::<std::os::raw::c_char>();
280        // SAFETY: `ptr` points at `buf`, which is NUL-terminated.
281        let decoded = unsafe { cstr_to_string(ptr) };
282        assert_eq!(decoded.as_deref(), Some(""));
283    }
284
285    #[test]
286    fn cstr_scan_rejects_overlong_input() {
287        let buf = c_buffer(&vec![b'a'; MAX_CSTR_LEN + 1]);
288        let ptr = buf.as_ptr().cast::<std::os::raw::c_char>();
289        // SAFETY: `ptr` points at `buf`, which is NUL-terminated.
290        let decoded = unsafe { cstr_to_string(ptr) };
291        assert!(decoded.is_none(), "over-long C strings must fail closed");
292    }
293
294    #[test]
295    fn cstr_scan_rejects_null_pointer() {
296        // SAFETY: a null pointer is an explicitly handled input.
297        let decoded = unsafe { cstr_to_string(std::ptr::null()) };
298        assert!(decoded.is_none());
299    }
300}