Skip to content

Parse misuse resistance #191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 8 additions & 12 deletions examples/html2term.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,21 +269,17 @@ mod top {
Key::Char('k') | Key::Up => {
if inspect_path.is_empty() {
doc_y = doc_y.saturating_sub(1);
} else {
if *inspect_path.last().unwrap() > 1 {
*inspect_path.last_mut().unwrap() -= 1;
annotated = rerender(&dom, &inspect_path, width, &options);
}
} else if *inspect_path.last().unwrap() > 1 {
*inspect_path.last_mut().unwrap() -= 1;
annotated = rerender(&dom, &inspect_path, width, &options);
}
}
Key::Char('h') | Key::Left => {
if inspect_path.is_empty() {
doc_x = doc_x.saturating_sub(1);
} else {
if inspect_path.len() > 1 {
inspect_path.pop();
annotated = rerender(&dom, &inspect_path, width, &options);
}
} else if inspect_path.len() > 1 {
inspect_path.pop();
annotated = rerender(&dom, &inspect_path, width, &options);
}
}
Key::Char('l') | Key::Right => {
Expand Down Expand Up @@ -378,7 +374,7 @@ mod top {
};
if inspect_path.is_empty() {
let render_tree = config
.dom_to_render_tree(&dom)
.dom_to_render_tree(dom)
.expect("Failed to build render tree");
config
.render_to_lines(render_tree, width)
Expand All @@ -405,7 +401,7 @@ mod top {
)
.expect("Invalid CSS");
let render_tree = config
.dom_to_render_tree(&dom)
.dom_to_render_tree(dom)
.expect("Failed to build render tree");
config
.render_to_lines(render_tree, width)
Expand Down
16 changes: 3 additions & 13 deletions src/ansi_colours.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
//! can be achieved using inline characters sent to the terminal such as
//! underlining in some terminals).

use crate::{parse, RichAnnotation, RichDecorator};
use crate::RichAnnotation;
use std::io;

/// Reads HTML from `input`, and returns text wrapped to `width` columns.
///
/// The text is returned as a `Vec<TaggedLine<_>>`; the annotations are vectors
/// of `RichAnnotation`. The "outer" annotation comes first in the `Vec`.
///
Expand All @@ -24,16 +25,5 @@ where
R: io::Read,
FMap: Fn(&[RichAnnotation], &str) -> String,
{
let lines = parse(input)?
.render(width, RichDecorator::new())?
.into_lines()?;

let mut result = String::new();
for line in lines {
for ts in line.tagged_strings() {
result.push_str(&colour_map(&ts.tag, &ts.s));
}
result.push('\n');
}
Ok(result)
super::config::rich().coloured(input, width, colour_map)
}
24 changes: 11 additions & 13 deletions src/css.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::{

use self::parser::Importance;

#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SelectorComponent {
Class(String),
Element(String),
Expand Down Expand Up @@ -46,7 +46,7 @@ impl std::fmt::Display for SelectorComponent {
}
}

#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Selector {
// List of components, right first so we match from the leaf.
components: Vec<SelectorComponent>,
Expand Down Expand Up @@ -132,10 +132,8 @@ impl Selector {
if Rc::ptr_eq(child, node) {
break;
}
} else {
if Rc::ptr_eq(child, node) {
return false;
}
} else if Rc::ptr_eq(child, node) {
return false;
}
}
}
Expand All @@ -148,14 +146,14 @@ impl Selector {
*/
let idx_offset = idx - b;
if *a == 0 {
return idx_offset == 0 && Self::do_matches(&comps[1..], &node);
return idx_offset == 0 && Self::do_matches(&comps[1..], node);
}
if (idx_offset % a) != 0 {
// Not a multiple
return false;
}
let n = idx_offset / a;
n >= 0 && Self::do_matches(&comps[1..], &node)
n >= 0 && Self::do_matches(&comps[1..], node)
}
},
}
Expand Down Expand Up @@ -191,7 +189,7 @@ impl Selector {
}
}

#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Display {
/// display: none
None,
Expand All @@ -200,15 +198,15 @@ pub(crate) enum Display {
ExtRawDom,
}

#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Style {
Colour(Colour),
BgColour(Colour),
Display(Display),
WhiteSpace(WhiteSpace),
}

#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StyleDecl {
style: Style,
importance: Importance,
Expand All @@ -232,7 +230,7 @@ impl std::fmt::Display for StyleDecl {
}
}

#[derive(Debug, Clone)]
#[derive(Debug, Clone, PartialEq, Eq)]
struct Ruleset {
selector: Selector,
styles: Vec<StyleDecl>,
Expand All @@ -250,7 +248,7 @@ impl std::fmt::Display for Ruleset {
}

/// Stylesheet data which can be used while building the render tree.
#[derive(Clone, Default, Debug)]
#[derive(Clone, Default, Debug, PartialEq, Eq)]
pub(crate) struct StyleData {
agent_rules: Vec<Ruleset>,
user_rules: Vec<Ruleset>,
Expand Down
18 changes: 10 additions & 8 deletions src/css/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,20 +390,22 @@ pub(crate) fn parse_color_attribute(
parse_color(&value.tokens).or_else(|e| parse_faulty_color(e, text))
}

fn parse_color_part(text: &str, index: std::ops::Range<usize>) -> Option<u8> {
u8::from_str_radix(text.get(index)?, 16).ok()
}

// Both Firefox and Chromium accept "00aabb" as a bgcolor - I'm not sure this has ever been legal,
// but regrettably I've had e-mails which were unreadable without doing this.
fn parse_faulty_color(
e: nom::Err<nom::error::Error<&'static str>>,
text: &str,
) -> Result<Colour, nom::Err<nom::error::Error<&'static str>>> {
let text = text.trim();
if text.chars().all(|c| c.is_hex_digit()) {
if text.len() == 6 {
let r = u8::from_str_radix(&text[0..2], 16).unwrap();
let g = u8::from_str_radix(&text[2..4], 16).unwrap();
let b = u8::from_str_radix(&text[4..6], 16).unwrap();
return Ok(Colour::Rgb(r, g, b));
}
let r = parse_color_part(text, 0..2);
let g = parse_color_part(text, 2..4);
let b = parse_color_part(text, 4..6);
if let (Some(r), Some(g), Some(b)) = (r, g, b) {
return Ok(Colour::Rgb(r, g, b));
}
Err(e)
}
Expand Down Expand Up @@ -620,7 +622,7 @@ fn parse_string_token(text: &str) -> IResult<&str, Token> {

loop {
match chars.next() {
None => return Ok((&text[text.len()..], Token::String(s.into()))),
None => return Ok(("", Token::String(s.into()))),
Some((i, c)) if c == end_char => {
return Ok((&text[i + 1..], Token::String(s.into())));
}
Expand Down
Loading
Loading