1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
mod handlers_dispatcher;
mod rewrite_controller;
#[macro_use]
mod settings;
use self::handlers_dispatcher::ContentHandlersDispatcher;
use self::rewrite_controller::*;
use crate::base::SharedEncoding;
use crate::memory::MemoryLimitExceededError;
use crate::memory::MemoryLimiter;
use crate::parser::ParsingAmbiguityError;
use crate::selectors_vm::{self, SelectorMatchingVm};
use crate::transform_stream::*;
use encoding_rs::Encoding;
use mime::Mime;
use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt::{self, Debug};
use std::rc::Rc;
use thiserror::Error;
pub use self::settings::*;
/// This is an encoding known to be ASCII-compatible.
///
/// Non-ASCII-compatible encodings (`UTF-16LE`, `UTF-16BE`, `ISO-2022-JP` and
/// `replacement`) are not supported by lol_html.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct AsciiCompatibleEncoding(&'static Encoding);
impl AsciiCompatibleEncoding {
/// Returns `Some` if `Encoding` is ascii-compatible, or `None` otherwise.
pub fn new(encoding: &'static Encoding) -> Option<Self> {
if encoding.is_ascii_compatible() {
Some(Self(encoding))
} else {
None
}
}
fn from_mimetype(mime: &Mime) -> Option<AsciiCompatibleEncoding> {
mime.get_param("charset")
.and_then(|cs| Encoding::for_label_no_replacement(cs.as_str().as_bytes()))
.and_then(AsciiCompatibleEncoding::new)
}
/// Returns the most commonly used UTF-8 encoding.
pub fn utf_8() -> AsciiCompatibleEncoding {
Self(encoding_rs::UTF_8)
}
}
impl From<AsciiCompatibleEncoding> for &'static Encoding {
fn from(ascii_enc: AsciiCompatibleEncoding) -> &'static Encoding {
ascii_enc.0
}
}
impl std::convert::TryFrom<&'static Encoding> for AsciiCompatibleEncoding {
type Error = ();
fn try_from(enc: &'static Encoding) -> Result<Self, ()> {
Self::new(enc).ok_or(())
}
}
/// A compound error type that can be returned by [`write`] and [`end`] methods of the rewriter.
///
/// # Note
/// This error is unrecoverable. The rewriter instance will panic on attempt to use it after such an
/// error.
///
/// [`write`]: ../struct.HtmlRewriter.html#method.write
/// [`end`]: ../struct.HtmlRewriter.html#method.end
#[derive(Error, Debug)]
pub enum RewritingError {
/// See [`MemoryLimitExceededError`].
///
/// [`MemoryLimitExceededError`]: struct.MemoryLimitExceededError.html
#[error("{0}")]
MemoryLimitExceeded(MemoryLimitExceededError),
/// See [`ParsingAmbiguityError`].
///
/// [`ParsingAmbiguityError`]: struct.ParsingAmbiguityError.html
#[error("{0}")]
ParsingAmbiguity(ParsingAmbiguityError),
/// An error that was propagated from one of the content handlers.
#[error("{0}")]
ContentHandlerError(Box<dyn StdError + Send + Sync>),
}
/// A streaming HTML rewriter.
///
/// # Example
/// ```
/// use lol_html::{element, HtmlRewriter, Settings};
///
/// let mut output = vec![];
///
/// {
/// let mut rewriter = HtmlRewriter::new(
/// Settings {
/// element_content_handlers: vec![
/// // Rewrite insecure hyperlinks
/// element!("a[href]", |el| {
/// let href = el
/// .get_attribute("href")
/// .unwrap()
/// .replace("http:", "https:");
///
/// el.set_attribute("href", &href).unwrap();
///
/// Ok(())
/// })
/// ],
/// ..Settings::default()
/// },
/// |c: &[u8]| output.extend_from_slice(c)
/// );
///
/// rewriter.write(b"<div><a href=").unwrap();
/// rewriter.write(b"http://example.com>").unwrap();
/// rewriter.write(b"</a></div>").unwrap();
/// rewriter.end().unwrap();
/// }
///
/// assert_eq!(
/// String::from_utf8(output).unwrap(),
/// r#"<div><a href="https://example.com"></a></div>"#
/// );
/// ```
pub struct HtmlRewriter<'h, O: OutputSink> {
stream: TransformStream<HtmlRewriteController<'h>, O>,
poisoned: bool,
}
macro_rules! guarded {
($self:ident, $expr:expr) => {{
assert!(
!$self.poisoned,
"Attempt to use the HtmlRewriter after a fatal error."
);
let res = $expr;
if res.is_err() {
$self.poisoned = true;
}
res
}};
}
impl<'h, O: OutputSink> HtmlRewriter<'h, O> {
/// Constructs a new rewriter with the provided `settings` that writes
/// the output to the `output_sink`.
///
/// # Note
///
/// For the convenience the [`OutputSink`] trait is implemented for closures.
///
/// [`OutputSink`]: trait.OutputSink.html
pub fn new<'s>(settings: Settings<'h, 's>, output_sink: O) -> Self {
let encoding = SharedEncoding::new(settings.encoding);
let mut selectors_ast = selectors_vm::Ast::default();
let mut dispatcher = ContentHandlersDispatcher::default();
let has_selectors =
!settings.element_content_handlers.is_empty() || settings.adjust_charset_on_meta_tag;
let charset_adjust_handler = if settings.adjust_charset_on_meta_tag {
let encoding = SharedEncoding::clone(&encoding);
Some(handler_adjust_charset_on_meta_tag(encoding))
} else {
None
};
let element_content_handlers = charset_adjust_handler
.into_iter()
.chain(settings.element_content_handlers);
for (selector, handlers) in element_content_handlers {
let locator = dispatcher.add_selector_associated_handlers(handlers);
selectors_ast.add_selector(&selector, locator);
}
for handlers in settings.document_content_handlers {
dispatcher.add_document_content_handlers(handlers);
}
let memory_limiter =
MemoryLimiter::new_shared(settings.memory_settings.max_allowed_memory_usage);
let selector_matching_vm = if has_selectors {
Some(SelectorMatchingVm::new(
selectors_ast,
settings.encoding.into(),
Rc::clone(&memory_limiter),
settings.enable_esi_tags,
))
} else {
None
};
let controller = HtmlRewriteController::new(dispatcher, selector_matching_vm);
let stream = TransformStream::new(TransformStreamSettings {
transform_controller: controller,
output_sink,
preallocated_parsing_buffer_size: settings
.memory_settings
.preallocated_parsing_buffer_size,
memory_limiter,
encoding,
strict: settings.strict,
});
HtmlRewriter {
stream,
poisoned: false,
}
}
/// Writes a chunk of input data to the rewriter.
///
/// # Panics
/// * If previous invocation of the method returned a [`RewritingError`]
/// (these errors are unrecovarable).
///
/// [`RewritingError`]: errors/enum.RewritingError.html
/// [`end`]: struct.HtmlRewriter.html#method.end
#[inline]
pub fn write(&mut self, data: &[u8]) -> Result<(), RewritingError> {
guarded!(self, self.stream.write(data))
}
/// Finalizes the rewriting process.
///
/// Should be called once the last chunk of the input is written.
///
/// # Panics
/// * If previous invocation of [`write`] returned a [`RewritingError`] (these errors
/// are unrecovarable).
///
/// [`RewritingError`]: errors/enum.RewritingError.html
/// [`write`]: struct.HtmlRewriter.html#method.write
#[inline]
pub fn end(mut self) -> Result<(), RewritingError> {
guarded!(self, self.stream.end())
}
}
// NOTE: this opaque Debug implementation is required to make
// `.unwrap()` and `.expect()` methods available on Result
// returned by the `HtmlRewriterBuilder.build()` method.
impl<O: OutputSink> Debug for HtmlRewriter<'_, O> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "HtmlRewriter")
}
}
fn handler_adjust_charset_on_meta_tag(
encoding: SharedEncoding,
) -> (
Cow<'static, crate::Selector>,
ElementContentHandlers<'static>,
) {
element!("meta", move |el| {
let attr_charset = el
.get_attribute("charset")
.and_then(|cs| Encoding::for_label_no_replacement(cs.as_bytes()))
.and_then(AsciiCompatibleEncoding::new);
let attr_http_equiv = el
.get_attribute("http-equiv")
.filter(|http_equiv| http_equiv.eq_ignore_ascii_case("Content-Type"))
.and_then(|_| el.get_attribute("content"))
.and_then(|ct| ct.parse::<Mime>().ok())
.as_ref()
.and_then(AsciiCompatibleEncoding::from_mimetype);
if let Some(charset) = attr_charset.or(attr_http_equiv) {
encoding.set(charset)
}
Ok(())
})
}
/// Rewrites given `html` string with the provided `settings`.
///
/// # Example
///
/// ```
/// use lol_html::{rewrite_str, element, RewriteStrSettings};
///
/// let element_content_handlers = vec![
/// // Rewrite insecure hyperlinks
/// element!("a[href]", |el| {
/// let href = el
/// .get_attribute("href")
/// .unwrap()
/// .replace("http:", "https:");
///
/// el.set_attribute("href", &href).unwrap();
///
/// Ok(())
/// })
/// ];
/// let output = rewrite_str(
/// r#"<div><a href="http://example.com"></a></div>"#,
/// RewriteStrSettings {
/// element_content_handlers,
/// ..RewriteStrSettings::default()
/// }
/// ).unwrap();
///
/// assert_eq!(output, r#"<div><a href="https://example.com"></a></div>"#);
/// ```
pub fn rewrite_str<'h, 's>(
html: &str,
settings: impl Into<Settings<'h, 's>>,
) -> Result<String, RewritingError> {
let mut output = vec![];
let mut rewriter = HtmlRewriter::new(settings.into(), |c: &[u8]| {
output.extend_from_slice(c);
});
rewriter.write(html.as_bytes())?;
rewriter.end()?;
// NOTE: it's ok to unwrap here as we guarantee encoding validity of the output
Ok(String::from_utf8(output).unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::html_content::ContentType;
use crate::test_utils::{Output, ASCII_COMPATIBLE_ENCODINGS, NON_ASCII_COMPATIBLE_ENCODINGS};
use encoding_rs::Encoding;
use itertools::Itertools;
use std::cell::RefCell;
use std::convert::TryInto;
use std::rc::Rc;
fn write_chunks<O: OutputSink>(
mut rewriter: HtmlRewriter<O>,
encoding: &'static Encoding,
chunks: &[&str],
) {
for chunk in chunks {
let (chunk, _, _) = encoding.encode(chunk);
rewriter.write(&chunk).unwrap();
}
rewriter.end().unwrap();
}
fn rewrite_html_bytes(html: &[u8], settings: Settings) -> Vec<u8> {
let mut out: Vec<u8> = Vec::with_capacity(html.len());
let mut rewriter = HtmlRewriter::new(settings, |c: &[u8]| out.extend_from_slice(c));
rewriter.write(html).unwrap();
rewriter.end().unwrap();
out
}
#[test]
fn rewrite_html_str() {
let res = rewrite_str(
"<!-- 42 --><div><!--hi--></div>",
RewriteStrSettings {
element_content_handlers: vec![
element!("div", |el| {
el.set_tag_name("span").unwrap();
Ok(())
}),
comments!("div", |c| {
c.set_text("hello").unwrap();
Ok(())
}),
],
..RewriteStrSettings::default()
},
)
.unwrap();
assert_eq!(res, "<!-- 42 --><span><!--hello--></span>");
}
#[test]
fn rewrite_arbitrary_settings() {
let res = rewrite_str("<span>Some text</span>", Settings::default()).unwrap();
assert_eq!(res, "<span>Some text</span>");
}
#[test]
fn non_ascii_compatible_encoding() {
for encoding in &NON_ASCII_COMPATIBLE_ENCODINGS {
assert_eq!(AsciiCompatibleEncoding::new(encoding), None);
}
}
#[test]
fn doctype_info() {
for &enc in ASCII_COMPATIBLE_ENCODINGS.iter() {
let mut doctypes = Vec::default();
{
let rewriter = HtmlRewriter::new(
Settings {
document_content_handlers: vec![doctype!(|d| {
doctypes.push((d.name(), d.public_id(), d.system_id()));
Ok(())
})],
// NOTE: unwrap() here is intentional; it also tests `Ascii::new`.
encoding: enc.try_into().unwrap(),
..Settings::default()
},
|_: &[u8]| {},
);
write_chunks(
rewriter,
enc,
&[
"<!doctype html1>",
"<!-- test --><div>",
r#"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "#,
r#""http://www.w3.org/TR/html4/strict.dtd">"#,
"</div><!DoCtYPe ",
],
);
}
assert_eq!(
doctypes,
&[
(Some("html1".into()), None, None),
(
Some("html".into()),
Some("-//W3C//DTD HTML 4.01//EN".into()),
Some("http://www.w3.org/TR/html4/strict.dtd".into())
),
(None, None, None),
]
);
}
}
#[test]
fn rewrite_start_tags() {
for &enc in ASCII_COMPATIBLE_ENCODINGS.iter() {
let actual: String = {
let mut output = Output::new(enc);
let rewriter = HtmlRewriter::new(
Settings {
element_content_handlers: vec![element!("*", |el| {
el.set_attribute("foo", "bar").unwrap();
el.prepend("<test></test>", ContentType::Html);
Ok(())
})],
encoding: enc.try_into().unwrap(),
..Settings::default()
},
|c: &[u8]| output.push(c),
);
write_chunks(
rewriter,
enc,
&[
"<!doctype html>\n",
"<html>\n",
" <head></head>\n",
" <body>\n",
" <div>Test</div>\n",
" </body>\n",
"</html>",
],
);
output.into()
};
assert_eq!(
actual,
concat!(
"<!doctype html>\n",
"<html foo=\"bar\"><test></test>\n",
" <head foo=\"bar\"><test></test></head>\n",
" <body foo=\"bar\"><test></test>\n",
" <div foo=\"bar\"><test></test>Test</div>\n",
" </body>\n",
"</html>",
)
);
}
}
#[test]
fn rewrite_document_content() {
for &enc in ASCII_COMPATIBLE_ENCODINGS.iter() {
let actual: String = {
let mut output = Output::new(enc);
let rewriter = HtmlRewriter::new(
Settings {
element_content_handlers: vec![],
document_content_handlers: vec![
doc_comments!(|c| {
c.set_text(&(c.text() + "1337")).unwrap();
Ok(())
}),
doc_text!(|c| {
if c.last_in_text_node() {
c.after("BAZ", ContentType::Text);
}
Ok(())
}),
],
encoding: enc.try_into().unwrap(),
..Settings::default()
},
|c: &[u8]| output.push(c),
);
write_chunks(
rewriter,
enc,
&[
"<!doctype html>\n",
"<!-- hey -->\n",
"<html>\n",
" <head><!-- aloha --></head>\n",
" <body>\n",
" <div>Test</div>\n",
" </body>\n",
" <!-- bonjour -->\n",
"</html>Pshhh",
],
);
output.into()
};
assert_eq!(
actual,
concat!(
"<!doctype html>\nBAZ",
"<!-- hey 1337-->\nBAZ",
"<html>\n",
" BAZ<head><!-- aloha 1337--></head>\n",
" BAZ<body>\n",
" BAZ<div>TestBAZ</div>\n",
" BAZ</body>\n",
" BAZ<!-- bonjour 1337-->\nBAZ",
"</html>PshhhBAZ",
)
);
}
}
#[test]
fn handler_invocation_order() {
let handlers_executed = Rc::new(RefCell::new(Vec::default()));
macro_rules! create_handlers {
($sel:expr, $idx:expr) => {
element!($sel, {
let handlers_executed = Rc::clone(&handlers_executed);
move |_| {
handlers_executed.borrow_mut().push($idx);
Ok(())
}
})
};
}
let _res = rewrite_str(
"<div><span foo></span></div>",
RewriteStrSettings {
element_content_handlers: vec![
create_handlers!("div span", 0),
create_handlers!("div > span", 1),
create_handlers!("span", 2),
create_handlers!("[foo]", 3),
create_handlers!("div span[foo]", 4),
],
..RewriteStrSettings::default()
},
)
.unwrap();
assert_eq!(*handlers_executed.borrow(), vec![0, 1, 2, 3, 4]);
}
#[test]
fn write_esi_tags() {
let res = rewrite_str(
"<span><esi:include src=a></span>",
RewriteStrSettings {
element_content_handlers: vec![element!("esi\\:include", |el| {
el.replace("?", ContentType::Text);
Ok(())
})],
enable_esi_tags: true,
..RewriteStrSettings::default()
},
)
.unwrap();
assert_eq!(res, "<span>?</span>");
}
#[test]
fn test_rewrite_adjust_charset_on_meta_tag_attribute_charset() {
use crate::html_content::{ContentType, TextChunk};
let enthusiastic_text_handler = || {
doc_text!(move |text: &mut TextChunk| {
let new_text = text.as_str().replace('!', "!!!");
text.replace(&new_text, ContentType::Text);
Ok(())
})
};
let html: Vec<u8> = [
r#"<meta charset="windows-1251"><html><head></head><body>I love "#
.as_bytes()
.to_vec(),
vec![0xd5, 0xec, 0xb3, 0xcb, 0xdc],
r#"!</body></html>"#.as_bytes().to_vec(),
]
.into_iter()
.concat();
let expected: Vec<u8> = html
.iter()
.copied()
.flat_map(|c| match c {
b'!' => vec![b'!', b'!', b'!'],
c => vec![c],
})
.collect();
let transformed_no_charset_adjustment: Vec<u8> = rewrite_html_bytes(
&html,
Settings {
document_content_handlers: vec![enthusiastic_text_handler()],
..Settings::default()
},
);
// Without charset adjustment the response has to be corrupted:
assert_ne!(transformed_no_charset_adjustment, expected);
let transformed_charset_adjustment: Vec<u8> = rewrite_html_bytes(
&html,
Settings {
document_content_handlers: vec![enthusiastic_text_handler()],
adjust_charset_on_meta_tag: true,
..Settings::default()
},
);
// If it adapts the charset according to the meta tag everything will be correctly
// encoded in windows-1251:
assert_eq!(transformed_charset_adjustment, expected);
}
#[test]
fn test_rewrite_adjust_charset_on_meta_tag_attribute_content_type() {
use crate::html_content::{ContentType, TextChunk};
let enthusiastic_text_handler = || {
doc_text!(move |text: &mut TextChunk| {
let new_text = text.as_str().replace('!', "!!!");
text.replace(&new_text, ContentType::Text);
Ok(())
})
};
let html: Vec<u8> = [
r#"<meta http-equiv="content-type" content="text/html; charset=windows-1251"><html><head></head><body>I love "#.as_bytes().to_vec(),
vec![0xd5, 0xec, 0xb3, 0xcb, 0xdc],
r#"!</body></html>"#.as_bytes().to_vec(),
].into_iter().concat();
let expected: Vec<u8> = html
.iter()
.copied()
.flat_map(|c| match c {
b'!' => vec![b'!', b'!', b'!'],
c => vec![c],
})
.collect();
let transformed_no_charset_adjustment: Vec<u8> = rewrite_html_bytes(
&html,
Settings {
document_content_handlers: vec![enthusiastic_text_handler()],
..Settings::default()
},
);
// Without charset adjustment the response has to be corrupted:
assert_ne!(transformed_no_charset_adjustment, expected);
let transformed_charset_adjustment: Vec<u8> = rewrite_html_bytes(
&html,
Settings {
document_content_handlers: vec![enthusiastic_text_handler()],
adjust_charset_on_meta_tag: true,
..Settings::default()
},
);
// If it adapts the charset according to the meta tag everything will be correctly
// encoded in windows-1251:
assert_eq!(transformed_charset_adjustment, expected);
}
mod fatal_errors {
use super::*;
use crate::errors::MemoryLimitExceededError;
fn create_rewriter<O: OutputSink>(
max_allowed_memory_usage: usize,
output_sink: O,
) -> HtmlRewriter<'static, O> {
HtmlRewriter::new(
Settings {
element_content_handlers: vec![element!("*", |_| Ok(()))],
memory_settings: MemorySettings {
max_allowed_memory_usage,
preallocated_parsing_buffer_size: 0,
},
..Settings::default()
},
output_sink,
)
}
#[test]
fn buffer_capacity_limit() {
const MAX: usize = 100;
let mut rewriter = create_rewriter(MAX, |_: &[u8]| {});
// Use two chunks for the stream to force the usage of the buffer and
// make sure to overflow it.
let chunk_1 = format!("<img alt=\"{}", "l".repeat(MAX / 2));
let chunk_2 = format!("{}\" />", "r".repeat(MAX / 2));
rewriter.write(chunk_1.as_bytes()).unwrap();
let write_err = rewriter.write(chunk_2.as_bytes()).unwrap_err();
match write_err {
RewritingError::MemoryLimitExceeded(e) => assert_eq!(e, MemoryLimitExceededError),
_ => panic!("{}", write_err),
}
}
#[test]
#[should_panic(expected = "Attempt to use the HtmlRewriter after a fatal error.")]
fn poisoning_after_fatal_error() {
const MAX: usize = 10;
let mut rewriter = create_rewriter(MAX, |_: &[u8]| {});
let chunk = format!("<img alt=\"{}", "l".repeat(MAX));
rewriter.write(chunk.as_bytes()).unwrap_err();
rewriter.end().unwrap_err();
}
#[test]
fn content_handler_error_propagation() {
fn assert_err(
element_handlers: ElementContentHandlers,
document_handlers: DocumentContentHandlers,
expected_err: &'static str,
) {
use std::borrow::Cow;
let mut rewriter = HtmlRewriter::new(
Settings {
element_content_handlers: vec![(
Cow::Owned("*".parse().unwrap()),
element_handlers,
)],
document_content_handlers: vec![document_handlers],
..Settings::default()
},
|_: &[u8]| {},
);
let chunks = [
"<!--doc comment--> Doc text",
"<div><!--el comment-->El text</div>",
];
let mut err = None;
for chunk in chunks.iter() {
match rewriter.write(chunk.as_bytes()) {
Ok(_) => (),
Err(e) => {
err = Some(e);
break;
}
}
}
if err.is_none() {
match rewriter.end() {
Ok(_) => (),
Err(e) => err = Some(e),
}
}
let err = format!("{}", err.expect("Error expected"));
assert_eq!(err, expected_err);
}
assert_err(
ElementContentHandlers::default(),
doc_comments!(|_| Err("Error in doc comment handler".into())),
"Error in doc comment handler",
);
assert_err(
ElementContentHandlers::default(),
doc_text!(|_| Err("Error in doc text handler".into())),
"Error in doc text handler",
);
assert_err(
ElementContentHandlers::default(),
doc_text!(|_| Err("Error in doctype handler".into())),
"Error in doctype handler",
);
assert_err(
ElementContentHandlers::default()
.element(|_| Err("Error in element handler".into())),
DocumentContentHandlers::default(),
"Error in element handler",
);
assert_err(
ElementContentHandlers::default()
.comments(|_| Err("Error in element comment handler".into())),
DocumentContentHandlers::default(),
"Error in element comment handler",
);
assert_err(
ElementContentHandlers::default()
.text(|_| Err("Error in element text handler".into())),
DocumentContentHandlers::default(),
"Error in element text handler",
);
}
}
}