Debian Codegraph @

src/parser.rs

raw symbols SCIP
1 //! The parser functionality
2
3 use crate::bindings::*;
4 use crate::c_helpers::*;
5 use crate::tree::*;
6
7 use std::convert::AsRef;
8 use std::error::Error;
9 use std::ffi::c_void;
10 use std::ffi::{CStr, CString};
11 use std::fmt;
12 use std::fs;
13 use std::io;
14 use std::os::raw::{c_char, c_int};
15 use std::ptr;
16 use std::slice;
17 use std::str;
18
19 enum XmlParserOption {
20 Recover = 1,
21 Nodefdtd = 4,
22 Noerror = 32,
23 Nowarning = 64,
24 Pedantic = 128,
25 Noblanks = 256,
26 Nonet = 2048,
27 Noimplied = 8192,
28 Compact = 65_536,
29 Huge = 524_288,
30 Ignoreenc = 2_097_152,
31 }
32
33 enum HtmlParserOption {
34 Recover = 1,
35 Nodefdtd = 4,
36 Noerror = 32,
37 Nowarning = 64,
38 Pedantic = 128,
39 Noblanks = 256,
40 Nonet = 2048,
41 Noimplied = 8192,
42 Huge = 524_288,
43 Compact = 65_536,
44 Ignoreenc = 2_097_152,
45 }
46
47 /// Parser Options
48 pub struct ParserOptions<'a> {
49 /// Relaxed parsing
50 pub recover: bool,
51 /// do not default a doctype if not found
52 pub no_def_dtd: bool,
53 /// do not default a doctype if not found
54 pub no_error: bool,
55 /// suppress warning reports
56 pub no_warning: bool,
57 /// pedantic error reporting
58 pub pedantic: bool,
59 /// remove blank nodes
60 pub no_blanks: bool,
61 /// Forbid network access
62 pub no_net: bool,
63 /// Do not add implied html/body... elements
64 pub no_implied: bool,
65 /// relax any hardcoded limit from the parser
66 pub huge: bool,
67 /// compact small text nodes
68 pub compact: bool,
69 /// ignore internal document encoding hint
70 pub ignore_enc: bool,
71 /// manually-specified encoding
72 pub encoding: Option<&'a str>,
73 }
74
75 impl ParserOptions<'_> {
76 pub(crate) fn to_flags(&self, format: &ParseFormat) -> i32 {
77 macro_rules! to_option_flag {
78 (
79 $condition:expr => $variant:ident
80 ) => {
81 if $condition {
82 match format {
83 ParseFormat::HTML => HtmlParserOption::$variant as i32,
84 ParseFormat::XML => XmlParserOption::$variant as i32,
85 }
86 } else {
87 0
88 }
89 };
90 }
91 // return the combined flags
92 to_option_flag!(self.recover => Recover)
93 + to_option_flag!(self.no_def_dtd => Nodefdtd)
94 + to_option_flag!(self.no_error => Noerror)
95 + to_option_flag!(self.no_warning => Nowarning)
96 + to_option_flag!(self.pedantic => Pedantic)
97 + to_option_flag!(self.no_blanks => Noblanks)
98 + to_option_flag!(self.no_net => Nonet)
99 + to_option_flag!(self.no_implied => Noimplied)
100 + to_option_flag!(self.huge => Huge)
101 + to_option_flag!(self.compact => Compact)
102 + to_option_flag!(self.ignore_enc => Ignoreenc)
103 }
104 }
105
106 impl Default for ParserOptions<'_> {
107 fn default() -> Self {
108 ParserOptions {
109 recover: true,
110 no_def_dtd: false,
111 no_error: true,
112 no_warning: true,
113 pedantic: false,
114 no_blanks: false,
115 no_net: false,
116 no_implied: false,
117 huge: false,
118 compact: false,
119 ignore_enc: false,
120 encoding: None,
121 }
122 }
123 }
124
125 ///Parser Errors
126 pub enum XmlParseError {
127 ///Parsing returned a null pointer as document pointer
128 GotNullPointer,
129 ///Could not open file error.
130 FileOpenError,
131 ///Document too large for libxml2.
132 DocumentTooLarge,
133 }
134
135 impl Error for XmlParseError {}
136
137 impl fmt::Debug for XmlParseError {
138 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139 write!(f, "{self}")
140 }
141 }
142
143 impl fmt::Display for XmlParseError {
144 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
145 write!(
146 f,
147 "{}",
148 match self {
149 XmlParseError::GotNullPointer => "Got a Null pointer",
150 XmlParseError::FileOpenError => "Unable to open path to file.",
151 XmlParseError::DocumentTooLarge => "Document too large for i32.",
152 }
153 )
154 }
155 }
156
157 /// Default encoding when not provided.
158 const DEFAULT_ENCODING: *const c_char = ptr::null();
159
160 /// Default URL when not provided.
161 const DEFAULT_URL: *const c_char = ptr::null();
162
163 /// Open file function.
164 fn xml_open(filename: &str) -> io::Result<*mut c_void> {
165 let ptr = Box::into_raw(Box::new(fs::File::open(filename)?));
166 Ok(ptr as *mut c_void)
167 }
168
169 /// Read callback for an FS file.
170 unsafe extern "C" fn xml_read(context: *mut c_void, buffer: *mut c_char, len: c_int) -> c_int { unsafe {
171 // Len is always positive, typically 40-4000 bytes.
172 let file = context as *mut fs::File;
173 let buf = slice::from_raw_parts_mut(buffer as *mut u8, len as usize);
174 match io::Read::read(&mut *file, buf) {
175 Ok(v) => v as c_int,
176 Err(_) => -1,
177 }
178 }}
179
180 type XmlReadCallback = unsafe extern "C" fn(*mut c_void, *mut c_char, c_int) -> c_int;
181
182 /// Close callback for an FS file.
183 unsafe extern "C" fn xml_close(context: *mut c_void) -> c_int { unsafe {
184 // Take rust ownership of the context and then drop it.
185 let file = context as *mut fs::File;
186 let _ = Box::from_raw(file);
187 0
188 }}
189
190 type XmlCloseCallback = unsafe extern "C" fn(*mut c_void) -> c_int;
191
192 ///Convert usize to i32 safely.
193 fn try_usize_to_i32(value: usize) -> Result<i32, XmlParseError> {
194 if cfg!(target_pointer_width = "16") || (value < i32::MAX as usize) {
195 // Cannot safely use our value comparison, but the conversion if always safe.
196 // Or, if the value can be safely represented as a 32-bit signed integer.
197 Ok(value as i32)
198 } else {
199 // Document too large, cannot parse using libxml2.
200 Err(XmlParseError::DocumentTooLarge)
201 }
202 }
203
204 #[derive(Debug, PartialEq, Eq)]
205 /// Enum for the parse formats supported by libxml2
206 pub enum ParseFormat {
207 /// Strict parsing for XML
208 XML,
209 /// Relaxed parsing for HTML
210 HTML,
211 }
212 /// Parsing API wrapper for libxml2
213 pub struct Parser {
214 /// The `ParseFormat` for this parser
215 pub format: ParseFormat,
216 }
217 impl Default for Parser {
218 /// Create a parser for XML documents
219 fn default() -> Self {
220 // avoid deadlocks from using multiple parsers
221 crate::init_parser();
222 Parser {
223 format: ParseFormat::XML,
224 }
225 }
226 }
227 impl Parser {
228 /// Create a parser for HTML documents
229 pub fn default_html() -> Self {
230 // avoid deadlocks from using multiple parsers
231 crate::init_parser();
232 Parser {
233 format: ParseFormat::HTML,
234 }
235 }
236
237 /// Parses the XML/HTML file `filename` to generate a new `Document`
238 pub fn parse_file(&self, filename: &str) -> Result<Document, XmlParseError> {
239 self.parse_file_with_options(filename, ParserOptions::default())
240 }
241
242 /// Parses the XML/HTML file `filename` with a manually-specified parser-options
243 /// to generate a new `Document`
244 pub fn parse_file_with_options(
245 &self,
246 filename: &str,
247 parser_options: ParserOptions,
248 ) -> Result<Document, XmlParseError> {
249 // Create extern C callbacks for to read and close a Rust file through
250 // a void pointer.
251 let ioread: Option<XmlReadCallback> = Some(xml_read);
252 let ioclose: Option<XmlCloseCallback> = Some(xml_close);
253 let ioctx = match xml_open(filename) {
254 Ok(v) => v,
255 Err(_) => return Err(XmlParseError::FileOpenError),
256 };
257
258 // Process encoding.
259 let encoding_cstring: Option<CString> =
260 parser_options.encoding.map(|v| CString::new(v).unwrap());
261 let encoding_ptr = match encoding_cstring {
262 Some(v) => v.as_ptr(),
263 None => DEFAULT_ENCODING,
264 };
265
266 // Process url.
267 let url_ptr = DEFAULT_URL;
268
269 unsafe {
270 xmlKeepBlanksDefault(1);
271 }
272
273 let options = parser_options.to_flags(&self.format);
274
275 match self.format {
276 ParseFormat::XML => unsafe {
277 let doc_ptr = xmlReadIO(ioread, ioclose, ioctx, url_ptr, encoding_ptr, options);
278 if doc_ptr.is_null() {
279 Err(XmlParseError::GotNullPointer)
280 } else {
281 Ok(Document::new_ptr(doc_ptr))
282 }
283 },
284 ParseFormat::HTML => unsafe {
285 let doc_ptr = htmlReadIO(ioread, ioclose, ioctx, url_ptr, encoding_ptr, options);
286 if doc_ptr.is_null() {
287 Err(XmlParseError::GotNullPointer)
288 } else {
289 Ok(Document::new_ptr(doc_ptr))
290 }
291 },
292 }
293 }
294
295 ///Parses the XML/HTML bytes `input` to generate a new `Document`
296 pub fn parse_string<Bytes: AsRef<[u8]>>(&self, input: Bytes) -> Result<Document, XmlParseError> {
297 self.parse_string_with_options(input, ParserOptions::default())
298 }
299
300 ///Parses the XML/HTML bytes `input` with a manually-specified
301 ///parser-options to generate a new `Document`
302 pub fn parse_string_with_options<Bytes: AsRef<[u8]>>(
303 &self,
304 input: Bytes,
305 parser_options: ParserOptions,
306 ) -> Result<Document, XmlParseError> {
307 // Process input bytes.
308 let input_bytes = input.as_ref();
309 let input_ptr = input_bytes.as_ptr() as *const c_char;
310 let input_len = try_usize_to_i32(input_bytes.len())?;
311
312 // Process encoding.
313 let encoding_cstring: Option<CString> =
314 parser_options.encoding.map(|v| CString::new(v).unwrap());
315 let encoding_ptr = match encoding_cstring {
316 Some(v) => v.as_ptr(),
317 None => DEFAULT_ENCODING,
318 };
319
320 // Process url.
321 let url_ptr = DEFAULT_URL;
322
323 let options = parser_options.to_flags(&self.format);
324
325 match self.format {
326 ParseFormat::XML => unsafe {
327 let docptr = xmlReadMemory(input_ptr, input_len, url_ptr, encoding_ptr, options);
328 if docptr.is_null() {
329 Err(XmlParseError::GotNullPointer)
330 } else {
331 Ok(Document::new_ptr(docptr))
332 }
333 },
334 ParseFormat::HTML => unsafe {
335 let docptr = htmlReadMemory(input_ptr, input_len, url_ptr, encoding_ptr, options);
336 if docptr.is_null() {
337 Err(XmlParseError::GotNullPointer)
338 } else {
339 Ok(Document::new_ptr(docptr))
340 }
341 },
342 }
343 }
344
345 /// Checks a string for well-formedness.
346 pub fn is_well_formed_html<Bytes: AsRef<[u8]>>(&self, input: Bytes) -> bool {
347 self.is_well_formed_html_with_encoding(input, None)
348 }
349
350 /// Checks a string for well-formedness with manually-specified encoding.
351 /// IMPORTANT: This function is currently implemented in a HACKY way, to ignore invalid errors for HTML5 elements (such as <math>)
352 /// this means you should NEVER USE IT WHILE THREADING, it is CERTAIN TO BREAK
353 ///
354 /// Help is welcome in implementing it correctly.
355 pub fn is_well_formed_html_with_encoding<Bytes: AsRef<[u8]>>(
356 &self,
357 input: Bytes,
358 encoding: Option<&str>,
359 ) -> bool {
360 // Process input string.
361 let input_bytes = input.as_ref();
362 if input_bytes.is_empty() {
363 return false;
364 }
365 let input_ptr = input_bytes.as_ptr() as *const c_char;
366 let input_len = match try_usize_to_i32(input_bytes.len()) {
367 Ok(v) => v,
368 Err(_) => return false,
369 };
370
371 // Process encoding.
372 let encoding_cstring: Option<CString> = encoding.map(|v| CString::new(v).unwrap());
373 let encoding_ptr = match encoding_cstring {
374 Some(v) => v.as_ptr(),
375 None => DEFAULT_ENCODING,
376 };
377
378 // Process url.
379 let url_ptr = DEFAULT_URL;
380 // disable generic error lines from libxml2
381 match self.format {
382 ParseFormat::XML => false, // TODO: Add support for XML at some point
383 ParseFormat::HTML => unsafe {
384 let ctxt = htmlNewParserCtxt();
385 setWellFormednessHandler(ctxt);
386 let docptr = htmlCtxtReadMemory(ctxt, input_ptr, input_len, url_ptr, encoding_ptr, 10_596); // htmlParserOption = 4+32+64+256+2048+8192
387 let well_formed_final = if htmlWellFormed(ctxt) {
388 // Basic well-formedness passes, let's check if we have an <html> element as root too
389 if !docptr.is_null() {
390 let node_ptr = xmlDocGetRootElement(docptr);
391 if node_ptr.is_null() {
392 return false
393 }
394 let name_ptr = xmlNodeGetName(node_ptr);
395 if name_ptr.is_null() {
396 false
397 }
398 //empty string
399 else {
400 let c_root_name = CStr::from_ptr(name_ptr);
401 let root_name = str::from_utf8(c_root_name.to_bytes()).unwrap().to_owned();
402 root_name == "html"
403 }
404 } else {
405 false
406 }
407 } else {
408 false
409 };
410
411 if !ctxt.is_null() {
412 htmlFreeParserCtxt(ctxt);
413 }
414 if !docptr.is_null() {
415 xmlFreeDoc(docptr);
416 }
417 well_formed_final
418 },
419 }
420 }
421 }