Debian Codegraph @

src/io.rs

raw symbols SCIP
1 //! Custom I/O callbacks for libxml2.
2 //!
3 //! libxml2 routes every URL it loads (XML documents, `xsl:import` /
4 //! `xsl:include` targets, RelaxNG `<include>`, DTD external subsets,
5 //! etc.) through a chain of registered "input callback" handlers. The
6 //! default chain handles `file://`, `http://`, `ftp://`, etc.; an
7 //! application can prepend its own handler for a custom URL scheme via
8 //! `xmlRegisterInputCallbacks`.
9 //!
10 //! This module wraps that C API in a safe, closure-friendly surface.
11 //! The motivating use case is shipping a single-binary CLI that bundles
12 //! XSLT stylesheets / RNG schemas via `include_bytes!` and serves them
13 //! through a synthetic scheme (e.g. `embed:///foo.xsl`), so `xsl:import`
14 //! chains resolve without ever touching the disk.
15 //!
16 //! ```no_run
17 //! use libxml::io;
18 //!
19 //! static MAIN: &[u8] = b"<?xml version=\"1.0\"?>\n<root/>";
20 //!
21 //! io::register_input_callback(
22 //! |url| url.starts_with("embed:///"),
23 //! |url| match url.strip_prefix("embed:///") {
24 //! Some("main.xml") => Some(MAIN.to_vec()),
25 //! _ => None,
26 //! },
27 //! );
28 //! ```
29 //!
30 //! ## Lifetime, threading, order
31 //!
32 //! Closures live for the process lifetime — libxml2 has no per-handler
33 //! unregister API. They may run on any thread (hence `Send + Sync`) and
34 //! **must not panic**: unwinding across the `extern "C"` trampoline
35 //! aborts on Rust 2024+. libxml2 walks callbacks newest-first; the
36 //! trampolines snapshot the registry and drop the lock before invoking
37 //! a user closure, so a closure that re-enters libxml2 won't
38 //! self-deadlock. If `open` returns `None`, libxml2 falls through to
39 //! the next handler — including its default file/HTTP loaders.
40
41 use std::ffi::{CStr, c_char, c_int, c_void};
42 use std::sync::{Arc, Mutex, OnceLock};
43
44 use crate::bindings::xmlRegisterInputCallbacks;
45
46 type MatchFn = Box<dyn Fn(&str) -> bool + Send + Sync + 'static>;
47 type OpenFn = Box<dyn Fn(&str) -> Option<Vec<u8>> + Send + Sync + 'static>;
48
49 struct Callback {
50 match_url: MatchFn,
51 open: OpenFn,
52 }
53
54 fn callbacks() -> &'static Mutex<Vec<Arc<Callback>>> {
55 static CALLBACKS: OnceLock<Mutex<Vec<Arc<Callback>>>> = OnceLock::new();
56 CALLBACKS.get_or_init(|| Mutex::new(Vec::new()))
57 }
58
59 /// Clone the registry under the lock and return with the guard
60 /// dropped. Cloning is a cheap refcount bump per entry. The lock is
61 /// not held across user closures, so a closure that re-enters libxml2
62 /// can't self-deadlock on the registry mutex.
63 fn snapshot() -> Vec<Arc<Callback>> {
64 callbacks().lock().unwrap().clone()
65 }
66
67 /// Register a custom input callback with libxml2.
68 ///
69 /// `match_url` is consulted for every URL libxml2 considers loading.
70 /// Return `true` to claim the URL; the same callback's `open` is then
71 /// invoked. Either function can defer: `match_url` returning `false`
72 /// skips the callback; `open` returning `None` falls through to the
73 /// next registered handler, including libxml2's defaults.
74 ///
75 /// Closures are `Send + Sync + 'static` because libxml2 may invoke
76 /// them from any thread. They are appended to a process-static
77 /// registry; there is no per-handler unregister.
78 ///
79 /// # Example
80 ///
81 /// Most commonly used to resolve `xsl:import` / `xsl:include` via
82 /// libxslt, or RelaxNG `<include>` via `xmlRelaxNGParse`. Note that
83 /// this crate's own `Parser::parse_file` uses Rust file I/O directly
84 /// and bypasses libxml2's URL machinery, so it does *not* trigger
85 /// these callbacks — wire them up via libxslt's `parse_bytes` or
86 /// libxml2's `xmlReadFile`.
87 ///
88 /// ```no_run
89 /// use libxml::io;
90 ///
91 /// static HELLO: &[u8] = b"<?xml version=\"1.0\"?>\n<hello>world</hello>";
92 ///
93 /// io::register_input_callback(
94 /// |url| url.starts_with("embed:///"),
95 /// |url| (url == "embed:///hello.xml").then(|| HELLO.to_vec()),
96 /// );
97 /// ```
98 pub fn register_input_callback<M, O>(match_url: M, open: O)
99 where
100 M: Fn(&str) -> bool + Send + Sync + 'static,
101 O: Fn(&str) -> Option<Vec<u8>> + Send + Sync + 'static,
102 {
103 callbacks().lock().unwrap().push(Arc::new(Callback {
104 match_url: Box::new(match_url),
105 open: Box::new(open),
106 }));
107
108 // libxml2 records the trampoline pointers in a static table;
109 // registering twice would push duplicate entries that delegate to
110 // the same Rust registry. The OnceLock avoids that.
111 static REGISTERED: OnceLock<()> = OnceLock::new();
112 REGISTERED.get_or_init(|| {
113 crate::init_parser();
114 unsafe {
115 xmlRegisterInputCallbacks(
116 Some(trampoline_match),
117 Some(trampoline_open),
118 Some(trampoline_read),
119 Some(trampoline_close),
120 );
121 }
122 });
123 }
124
125 /// Per-open state owned by libxml2 via `*mut c_void` until
126 /// `trampoline_close` reclaims and drops it.
127 struct OpenState {
128 bytes: Vec<u8>,
129 position: usize,
130 }
131
132 unsafe extern "C" fn trampoline_match(filename: *const c_char) -> c_int {
133 if filename.is_null() {
134 return 0;
135 }
136 // SAFETY: libxml2 guarantees `filename` is a NUL-terminated C string
137 // for the call's lifetime. Non-UTF-8 URLs can't match anyway.
138 let url = match unsafe { CStr::from_ptr(filename) }.to_str() {
139 Ok(s) => s,
140 Err(_) => return 0,
141 };
142 // Newest-first, mirroring `trampoline_open`'s walk.
143 for cb in snapshot().iter().rev() {
144 if (cb.match_url)(url) {
145 return 1;
146 }
147 }
148 0
149 }
150
151 unsafe extern "C" fn trampoline_open(filename: *const c_char) -> *mut c_void {
152 if filename.is_null() {
153 return std::ptr::null_mut();
154 }
155 // SAFETY: see `trampoline_match`.
156 let url = match unsafe { CStr::from_ptr(filename) }.to_str() {
157 Ok(s) => s,
158 Err(_) => return std::ptr::null_mut(),
159 };
160 // Newest-first — the most recent registration wins.
161 for cb in snapshot().iter().rev() {
162 if !(cb.match_url)(url) {
163 continue;
164 }
165 if let Some(bytes) = (cb.open)(url) {
166 return Box::into_raw(Box::new(OpenState { bytes, position: 0 })) as *mut c_void;
167 }
168 }
169 std::ptr::null_mut()
170 }
171
172 unsafe extern "C" fn trampoline_read(
173 context: *mut c_void,
174 buffer: *mut c_char,
175 len: c_int,
176 ) -> c_int {
177 if context.is_null() || buffer.is_null() || len <= 0 {
178 return -1;
179 }
180 // SAFETY: `context` came from `Box::into_raw` in `trampoline_open`
181 // and is not yet reclaimed; libxml2 holds one reference per handle.
182 let state = unsafe { &mut *(context as *mut OpenState) };
183 let remaining = state.bytes.len().saturating_sub(state.position);
184 let n = remaining.min(len as usize);
185 if n == 0 {
186 return 0;
187 }
188 // SAFETY: bounds checked above; src and dst are disjoint allocations.
189 unsafe {
190 std::ptr::copy_nonoverlapping(
191 state.bytes.as_ptr().add(state.position),
192 buffer as *mut u8,
193 n,
194 );
195 }
196 state.position += n;
197 n as c_int
198 }
199
200 unsafe extern "C" fn trampoline_close(context: *mut c_void) -> c_int {
201 if context.is_null() {
202 return -1;
203 }
204 // SAFETY: unique reclamation site for the box from `trampoline_open`.
205 let _state = unsafe { Box::from_raw(context as *mut OpenState) };
206 0
207 }
208
209 #[cfg(test)]
210 mod tests {
211 use super::*;
212 use crate::bindings::{xmlFreeDoc, xmlReadFile};
213 use std::ffi::CString;
214 use std::sync::atomic::{AtomicUsize, Ordering};
215
216 static SAMPLE_XML: &[u8] = br#"<?xml version="1.0"?>
217 <root attr="ok"><child/></root>"#;
218
219 /// `Parser::parse_file` bypasses the input-callback machinery (it
220 /// reads via Rust file I/O), so the test must call `xmlReadFile`
221 /// directly — the same entry point libxslt uses for `xsl:import`.
222 fn read_file_via_libxml2(url: &str) -> bool {
223 let c = CString::new(url).unwrap();
224 unsafe {
225 let doc = xmlReadFile(c.as_ptr(), std::ptr::null(), 0);
226 if doc.is_null() {
227 return false;
228 }
229 xmlFreeDoc(doc);
230 true
231 }
232 }
233
234 /// Scenarios share one `#[test]` so they run sequentially. libxml2
235 /// < 2.13 has a thread-safety bug in the input-callback path that
236 /// deadlocks concurrent `xmlReadFile` calls under cargo's default
237 /// parallel test runner.
238 #[test]
239 fn input_callback_scenarios() {
240 register_input_callback(
241 |url| url.starts_with("embed:///"),
242 |url| (url == "embed:///sample.xml").then(|| SAMPLE_XML.to_vec()),
243 );
244
245 // 1. Happy path.
246 assert!(read_file_via_libxml2("embed:///sample.xml"));
247
248 // 2. `open` returning `None` declines this match; libxml2 falls
249 // through to the default file loader, which also fails.
250 assert!(!read_file_via_libxml2("embed:///unknown.xml"));
251
252 // 3. Unrelated URLs aren't claimed by our match — they reach the
253 // default file handler and fail there.
254 assert!(!read_file_via_libxml2("/nonexistent/definitely/missing.xml"));
255
256 // 4. Re-entrancy: an `open` closure that calls into libxml2 must
257 // not self-deadlock on the registry mutex.
258 register_input_callback(
259 |url| url == "reentrant:///outer",
260 |_url| {
261 let _ = read_file_via_libxml2("embed:///sample.xml");
262 Some(SAMPLE_XML.to_vec())
263 },
264 );
265 assert!(read_file_via_libxml2("reentrant:///outer"));
266
267 // 5. Newest-wins ordering: two callbacks claim the same URL; only
268 // the most recent registration runs and produces the bytes.
269 static FIRST_OPENED: AtomicUsize = AtomicUsize::new(0);
270 static SECOND_OPENED: AtomicUsize = AtomicUsize::new(0);
271 register_input_callback(
272 |url| url == "ordered:///x",
273 |_| {
274 FIRST_OPENED.fetch_add(1, Ordering::SeqCst);
275 Some(b"<a>first</a>".to_vec())
276 },
277 );
278 register_input_callback(
279 |url| url == "ordered:///x",
280 |_| {
281 SECOND_OPENED.fetch_add(1, Ordering::SeqCst);
282 Some(SAMPLE_XML.to_vec())
283 },
284 );
285 assert!(read_file_via_libxml2("ordered:///x"));
286 assert_eq!(
287 SECOND_OPENED.load(Ordering::SeqCst),
288 1,
289 "newest registration should run",
290 );
291 assert_eq!(
292 FIRST_OPENED.load(Ordering::SeqCst),
293 0,
294 "older registration should not be consulted",
295 );
296 }
297 }