Debian Codegraph @

src/tree/document.rs

raw symbols SCIP
1 //! Document feature set
2 //!
3 use libc::{c_char, c_int};
4 use std::cell::RefCell;
5 use std::collections::HashMap;
6 use std::ffi::{CStr, CString};
7 use std::fmt;
8 use std::ptr;
9 use std::rc::{Rc, Weak};
10 use std::str;
11
12 use crate::bindings::*;
13 use crate::readonly::RoNode;
14 use crate::tree::node::Node;
15
16 pub(crate) type DocumentRef = Rc<RefCell<_Document>>;
17 pub(crate) type DocumentWeak = Weak<RefCell<_Document>>;
18
19 #[derive(Debug, Copy, Clone, Default)]
20 /// Save Options for Document
21 pub struct SaveOptions {
22 /// format save output
23 pub format: bool,
24 /// drop the xml declaration
25 pub no_declaration: bool,
26 /// no empty tags
27 pub no_empty_tags: bool,
28 /// disable XHTML1 specific rules
29 pub no_xhtml: bool,
30 /// force XHTML1 specific rules
31 pub xhtml: bool,
32 /// force XML serialization on HTML doc
33 pub as_xml: bool,
34 /// force HTML serialization on XML doc
35 pub as_html: bool,
36 /// format with non-significant whitespace
37 pub non_significant_whitespace: bool,
38 }
39
40 #[derive(Debug)]
41 pub(crate) struct _Document {
42 /// pointer to a libxml document
43 pub(crate) doc_ptr: xmlDocPtr,
44 /// hashed pointer-to-Node bookkeeping table
45 nodes: HashMap<xmlNodePtr, Node>,
46 }
47
48 impl _Document {
49 /// Internal bookkeeping function, so far only used by `Node::wrap`
50 pub(crate) fn insert_node(&mut self, node_ptr: xmlNodePtr, node: Node) {
51 self.nodes.insert(node_ptr, node);
52 }
53 /// Internal bookkeeping function, so far only used by `Node::wrap`
54 pub(crate) fn get_node(&self, node_ptr: xmlNodePtr) -> Option<&Node> {
55 self.nodes.get(&node_ptr)
56 }
57 /// Internal bookkeeping function
58 pub(crate) fn forget_node(&mut self, node_ptr: xmlNodePtr) {
59 self.nodes.remove(&node_ptr);
60 }
61 }
62
63 /// A libxml2 Document
64 #[derive(Clone)]
65 pub struct Document(pub(crate) DocumentRef);
66
67 impl Drop for _Document {
68 ///Free document when it goes out of scope
69 fn drop(&mut self) {
70 unsafe {
71 if !self.doc_ptr.is_null() {
72 xmlFreeDoc(self.doc_ptr);
73 }
74 }
75 }
76 }
77
78 impl fmt::Display for Document {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 write!(f, "{}", self.to_string_with_options(SaveOptions::default()))
81 }
82 }
83
84 impl Document {
85 /// Creates a new empty libxml2 document
86 pub fn new() -> Result<Self, ()> {
87 unsafe {
88 let c_version = CString::new("1.0").unwrap();
89 let c_version_bytes = c_version.as_bytes();
90 let doc_ptr = xmlNewDoc(c_version_bytes.as_ptr());
91 if doc_ptr.is_null() {
92 Err(())
93 } else {
94 let doc = _Document {
95 doc_ptr,
96 nodes: HashMap::new(),
97 };
98 Ok(Document(Rc::new(RefCell::new(doc))))
99 }
100 }
101 }
102
103 /// Obtain the underlying libxml2 `xmlDocPtr` for this Document
104 pub fn doc_ptr(&self) -> xmlDocPtr {
105 self.0.borrow().doc_ptr
106 }
107
108 /// Creates a new `Document` from an existing libxml2 pointer
109 pub fn new_ptr(doc_ptr: xmlDocPtr) -> Self {
110 let doc = _Document {
111 doc_ptr,
112 nodes: HashMap::new(),
113 };
114 Document(Rc::new(RefCell::new(doc)))
115 }
116
117 pub(crate) fn null_ref() -> DocumentRef {
118 Rc::new(RefCell::new(_Document {
119 doc_ptr: ptr::null_mut(),
120 nodes: HashMap::new(),
121 }))
122 }
123
124 /// Write document to `filename`
125 pub fn save_file(&self, filename: &str) -> Result<c_int, ()> {
126 let c_filename = CString::new(filename).unwrap();
127 unsafe {
128 let retval = xmlSaveFile(c_filename.as_ptr(), self.doc_ptr());
129 if retval < 0 {
130 return Err(());
131 }
132 Ok(retval)
133 }
134 }
135
136 pub(crate) fn register_node(&self, node_ptr: xmlNodePtr) -> Node {
137 Node::wrap(node_ptr, &self.0)
138 }
139
140 /// Get the root element of the document
141 pub fn get_root_element(&self) -> Option<Node> {
142 unsafe {
143 let node_ptr = xmlDocGetRootElement(self.doc_ptr());
144 if node_ptr.is_null() {
145 None
146 } else {
147 Some(self.register_node(node_ptr))
148 }
149 }
150 }
151
152 /// Get the root element of the document (read-only)
153 pub fn get_root_readonly(&self) -> Option<RoNode> {
154 unsafe {
155 let node_ptr = xmlDocGetRootElement(self.doc_ptr());
156 if node_ptr.is_null() {
157 None
158 } else {
159 Some(RoNode(node_ptr))
160 }
161 }
162 }
163
164 /// Sets the root element of the document
165 pub fn set_root_element(&mut self, root: &Node) {
166 unsafe {
167 xmlDocSetRootElement(self.doc_ptr(), root.node_ptr());
168 }
169 root.set_linked();
170 }
171
172 /// Remove the internal DTD subset (the `<!DOCTYPE …>` declaration)
173 /// from this document, if any. Mirrors XML::LibXML's
174 /// `Document::removeInternalSubset` (Perl) and the effect of
175 /// libxml2's `xmlSetIntSubset(doc, NULL)` — subsequent
176 /// serialisation no longer emits the DOCTYPE preamble.
177 ///
178 /// Safe to call on a document with no internal subset (no-op).
179 /// Unlinks the DTD node from the document and frees it via
180 /// `xmlFreeDtd`.
181 pub fn remove_internal_subset(&mut self) {
182 unsafe {
183 let dtd = xmlGetIntSubset(self.doc_ptr());
184 if !dtd.is_null() {
185 xmlUnlinkNode(dtd as xmlNodePtr);
186 xmlFreeDtd(dtd);
187 }
188 }
189 }
190
191 fn ptr_as_result(&mut self, node_ptr: xmlNodePtr) -> Result<Node, ()> {
192 if node_ptr.is_null() {
193 Err(())
194 } else {
195 let node = self.register_node(node_ptr);
196 Ok(node)
197 }
198 }
199
200 /// Import a `Node` from another `Document`
201 ///
202 /// The source `node` must be `Unlinked` (detached from its origin
203 /// document tree). Calling on a `Linked` source returns `Err(())`,
204 /// matching the long-standing contract of this method. Calling on a
205 /// `RustOwned` source also returns `Err(())`: the source has been
206 /// claimed by the Rust wrapper and re-linking it would set up a
207 /// double-free. Drop the source's wrapper first if you genuinely
208 /// want to discard it.
209 pub fn import_node(&mut self, node: &mut Node) -> Result<Node, ()> {
210 if !node.is_unlinked() || node.is_rust_owned() {
211 return Err(());
212 }
213 // Also remove this node from the prior document hash
214 node
215 .get_docref()
216 .upgrade()
217 .unwrap()
218 .borrow_mut()
219 .forget_node(node.node_ptr());
220
221 let node_ptr = unsafe { xmlDocCopyNode(node.node_ptr(), self.doc_ptr(), 1) };
222 node.set_linked();
223 self.ptr_as_result(node_ptr)
224 }
225
226 /// Build a fresh `Document` whose root is a deep copy of `node`'s subtree.
227 ///
228 /// Unlike [`Document::import_node`], this does not require the source
229 /// node to be unlinked and does not mutate the source node's wrapper
230 /// state. It is suitable for code that repeatedly extracts subtrees
231 /// from a single source document and needs each extracted subtree as
232 /// its own independently-owned `Document` — a pattern that the older
233 /// `import_node` route handles poorly:
234 ///
235 /// * `import_node` gates on `Node::is_unlinked()`, a wrapper-side flag
236 /// with no public setter; the gate flips to `false` as a side
237 /// effect of a previous successful import (`set_linked()` mutates
238 /// the borrowed wrapper Rc), so every subsequent extract errors.
239 /// * A bare `xmlDocCopyNode(src, dst, 1)` returns NULL on the second
240 /// sibling in the same source document, because the recursive
241 /// descent relies on dictionary state that the first copy has
242 /// marked dirty.
243 ///
244 /// This method works as follows:
245 /// 1. `xmlNewDoc` — fresh empty target document.
246 /// 2. `xmlDocCopyNode(node, target, 1)` — recursive copy of the
247 /// source subtree into the target, with libxml2 handling
248 /// namespace inheritance (`xmlNewReconciliedNs`) during the copy.
249 /// 3. `xmlDocSetRootElement` + `xmlSetTreeDoc` — plant the copy as
250 /// the new root and retarget every doc pointer in the subtree.
251 /// 4. `xmlReconciliateNs` — final pass that lifts any remaining
252 /// namespace declarations into the new document so it owns 100%
253 /// of its ns nodes.
254 ///
255 /// The returned `Document` shares no C-side state with the source —
256 /// dropping either is independent of the other.
257 ///
258 /// Returns `Err(())` if any of the underlying libxml2 calls returns
259 /// NULL (typically OOM, or `node` is itself NULL).
260 pub fn dup_node_into_new_doc(node: &Node) -> Result<Document, ()> {
261 let copy_ptr = unsafe { xmlCopyNode(node.node_ptr(), 1) };
262 if copy_ptr.is_null() {
263 return Err(());
264 }
265 let doc_ptr = unsafe {
266 let c_version = CString::new("1.0").unwrap();
267 xmlNewDoc(c_version.as_bytes().as_ptr())
268 };
269 if doc_ptr.is_null() {
270 unsafe { xmlFreeNode(copy_ptr) };
271 return Err(());
272 }
273 unsafe {
274 xmlDocSetRootElement(doc_ptr, copy_ptr);
275 // DEBUG: omit xmlSetTreeDoc + xmlReconciliateNs.
276 }
277 // The source node's wrapper state is left untouched. The new
278 // `_Node::drop` rules already prevent a UAF on the source: a
279 // detached subtree whose `node->doc` still points at the source
280 // document is treated as doc-owned and not freed by the wrapper.
281 // If a caller wants the source node's C allocation reclaimed
282 // (because the source doc tree-walk won't reach an unlinked
283 // subtree), they should call `Node::set_rust_owned` on the
284 // source after this returns.
285 Ok(Document::new_ptr(doc_ptr))
286 }
287 /// Serializes the `Document` with options
288 pub fn to_string_with_options(&self, options: SaveOptions) -> String {
289 unsafe {
290 // allocate a buffer to dump into
291 let buf = xmlBufferCreate();
292 let c_utf8 = CString::new("UTF-8").unwrap();
293 let mut xml_options = 0;
294
295 if options.format {
296 xml_options += xmlSaveOption_XML_SAVE_FORMAT;
297 }
298 if options.no_declaration {
299 xml_options += xmlSaveOption_XML_SAVE_NO_DECL;
300 }
301 if options.no_empty_tags {
302 xml_options += xmlSaveOption_XML_SAVE_NO_EMPTY;
303 }
304 if options.no_xhtml {
305 xml_options += xmlSaveOption_XML_SAVE_NO_XHTML;
306 }
307 if options.xhtml {
308 xml_options += xmlSaveOption_XML_SAVE_XHTML;
309 }
310 if options.as_xml {
311 xml_options += xmlSaveOption_XML_SAVE_AS_XML;
312 }
313 if options.as_html {
314 xml_options += xmlSaveOption_XML_SAVE_AS_HTML;
315 }
316 if options.non_significant_whitespace {
317 xml_options += xmlSaveOption_XML_SAVE_WSNONSIG;
318 }
319
320 let save_ctx = xmlSaveToBuffer(buf, c_utf8.as_ptr(), xml_options as i32);
321 let _size = xmlSaveDoc(save_ctx, self.doc_ptr());
322 let _size = xmlSaveClose(save_ctx);
323
324 let result = xmlBufferContent(buf);
325 let c_string = CStr::from_ptr(result as *const c_char);
326 let node_string = c_string.to_string_lossy().into_owned();
327 xmlBufferFree(buf);
328
329 node_string
330 }
331 }
332
333 /// Serializes a `Node` owned by this `Document`
334 pub fn node_to_string(&self, node: &Node) -> String {
335 unsafe {
336 // allocate a buffer to dump into
337 let buf = xmlBufferCreate();
338
339 // dump the node
340 xmlNodeDump(
341 buf,
342 self.doc_ptr(),
343 node.node_ptr(),
344 1, // level of indentation
345 0, /* disable formatting */
346 );
347 let result = xmlBufferContent(buf);
348 let c_string = CStr::from_ptr(result as *const c_char);
349 let node_string = c_string.to_string_lossy().into_owned();
350 xmlBufferFree(buf);
351
352 node_string
353 }
354 }
355 /// Serializes a `RoNode` owned by this `Document`
356 pub fn ronode_to_string(&self, node: &RoNode) -> String {
357 unsafe {
358 // allocate a buffer to dump into
359 let buf = xmlBufferCreate();
360
361 // dump the node
362 xmlNodeDump(
363 buf,
364 self.doc_ptr(),
365 node.node_ptr(),
366 1, // level of indentation
367 0, /* disable formatting */
368 );
369 let result = xmlBufferContent(buf);
370 let c_string = CStr::from_ptr(result as *const c_char);
371 let node_string = c_string.to_string_lossy().into_owned();
372 xmlBufferFree(buf);
373
374 node_string
375 }
376 }
377
378 /// Creates a node for an XML processing instruction
379 pub fn create_processing_instruction(&mut self, name: &str, content: &str) -> Result<Node, ()> {
380 unsafe {
381 let c_name = CString::new(name).unwrap();
382 let c_name_bytes = c_name.as_bytes();
383 let c_content = CString::new(content).unwrap();
384 let c_content_bytes = c_content.as_bytes();
385
386 let node_ptr: xmlNodePtr = xmlNewDocPI(
387 self.doc_ptr(),
388 c_name_bytes.as_ptr(),
389 c_content_bytes.as_ptr(),
390 );
391 if node_ptr.is_null() {
392 Err(())
393 } else {
394 Ok(self.register_node(node_ptr))
395 }
396 }
397 }
398
399 /// Cast the document as a libxml Node
400 pub fn as_node(&self) -> Node {
401 // Note: this method is important to keep, as it enables certain low-level libxml2 idioms
402 // In particular, method dispatch based on NodeType is only possible when the document can be cast as a Node
403 //
404 // Memory management is not an issue, as a document node can not be unbound/removed, and does not require
405 // any additional deallocation than the Drop of a Document object.
406 self.register_node(self.doc_ptr() as xmlNodePtr)
407 }
408
409 /// Duplicates the libxml2 Document into a new instance
410 pub fn dup(&self) -> Result<Self, ()> {
411 let doc_ptr = unsafe { xmlCopyDoc(self.doc_ptr(), 1) };
412 if doc_ptr.is_null() {
413 Err(())
414 } else {
415 let doc = _Document {
416 doc_ptr,
417 nodes: HashMap::new(),
418 };
419 Ok(Document(Rc::new(RefCell::new(doc))))
420 }
421 }
422
423 /// Duplicates a source libxml2 Document into the empty Document self
424 pub fn dup_from(&mut self, source: &Self) -> Result<(), ()> {
425 if !self.doc_ptr().is_null() {
426 return Err(());
427 }
428
429 let doc_ptr = unsafe { xmlCopyDoc(source.doc_ptr(), 1) };
430 if doc_ptr.is_null() {
431 return Err(());
432 }
433 self.0.borrow_mut().doc_ptr = doc_ptr;
434 Ok(())
435 }
436 }
437
438 mod c14n;