diff --git a/src/matcher.rs b/src/matcher.rs index 42405a34..35e9d93a 100644 --- a/src/matcher.rs +++ b/src/matcher.rs @@ -318,12 +318,9 @@ impl CompiledPattern { } if matches!(config.regex_mode, RegexMode::Basic | RegexMode::Extended) - && has_confusing_bracket(pattern.as_bytes()) + && let Err(msg) = check_brackets(pattern.as_bytes()) { - return Err(USimpleError::new( - 2, - "character class syntax is [[:space:]], not [:space:]".to_string(), - )); + return Err(USimpleError::new(2, msg.to_string())); } if config.regex_mode == RegexMode::Extended && has_empty_interval(pattern.as_bytes()) { @@ -600,7 +597,8 @@ fn has_empty_interval(pattern: &[u8]) -> bool { continue; } b'[' => { - i = scan_bracket(pattern, i + 1).1; + // `check_brackets` already accepted every bracket in `pattern`. + i = scan_bracket(pattern, i + 1).unwrap_or(pattern.len()); after_atom = true; continue; } @@ -616,33 +614,54 @@ fn has_empty_interval(pattern: &[u8]) -> bool { false } -/// True when `pattern` holds a bracket expression that looks like a misspelled -/// character class, e.g. `[:space:]` instead of `[[:space:]]`. GNU grep rejects -/// those: a bracket whose first and last characters are colons, that holds at -/// least one other character, and that contains no range, class, equivalence -/// class or collating element. -fn has_confusing_bracket(pattern: &[u8]) -> bool { +const CONFUSING_BRACKET: &str = "character class syntax is [[:space:]], not [:space:]"; +const UNMATCHED_BRACKET: &str = "Unmatched [, [^, [:, [., or [="; +const INVALID_CLASS_NAME: &str = "Invalid character class name"; + +fn is_posix_char_class(name: &[u8]) -> bool { + matches!( + name, + b"alnum" + | b"alpha" + | b"blank" + | b"cntrl" + | b"digit" + | b"graph" + | b"lower" + | b"print" + | b"punct" + | b"space" + | b"upper" + | b"xdigit" + ) +} + +/// Validate bracket expressions in BRE/ERE patterns: +/// - Reject `[:space:]` used without outer `[...]` +/// - Reject non-POSIX `[:name:]` classes +/// - Reject unclosed `[:`, `[.`, `[=` subexpressions inside `[...]` +fn check_brackets(pattern: &[u8]) -> Result<(), &'static str> { let mut i = 0; while i < pattern.len() { match pattern[i] { b'\\' => i += 2, - b'[' => { - let (confusing, next) = scan_bracket(pattern, i + 1); - if confusing { - return true; - } - i = next; - } + b'[' => i = scan_bracket(pattern, i + 1)?, _ => i += 1, } } - false + Ok(()) } /// Scan the body of a bracket expression starting at `start` (just past the -/// `[`). Returns whether it is a misspelled character class and the index just -/// past its closing `]`. -fn scan_bracket(pattern: &[u8], start: usize) -> (bool, usize) { +/// `[`). Returns the index just past its closing `]`, or the diagnostic GNU +/// grep gives for it: +/// - a "confusing" bracket, one that looks like a misspelled character class +/// such as `[:space:]` instead of `[[:space:]]`: its first and last +/// characters are colons, it holds at least one other character, and it +/// contains no range, class, equivalence class or collating element; +/// - an unclosed `[:`, `[.` or `[=` subexpression; +/// - a `[:name:]` whose name is not one of the twelve POSIX classes. +fn scan_bracket(pattern: &[u8], start: usize) -> Result { const FIRST_IS_COLON: u8 = 1; const LAST_IS_COLON: u8 = 2; const HAS_OTHER: u8 = 4; @@ -662,18 +681,24 @@ fn scan_bracket(pattern: &[u8], start: usize) -> (bool, usize) { let c = pattern[i]; // A `]` right at the start of the body is an ordinary character. if c == b']' && i != body_start { - return (state == FIRST_IS_COLON | LAST_IS_COLON | HAS_OTHER, i + 1); + if state == FIRST_IS_COLON | LAST_IS_COLON | HAS_OTHER { + return Err(CONFUSING_BRACKET); + } + return Ok(i + 1); } // Only the character just before the closing `]` counts as the last one. state &= !LAST_IS_COLON; // `[:alpha:]`, `[.a.]` and `[=a=]` inside the bracket. if c == b'[' && matches!(pattern.get(i + 1), Some(b':' | b'.' | b'=')) { let delimiter = pattern[i + 1]; - if let Some(end) = find_bracket_subexpr_end(pattern, i + 2, delimiter) { - state |= HAS_RANGE_OR_CLASS; - i = end; - continue; + let end = + find_bracket_subexpr_end(pattern, i + 2, delimiter).ok_or(UNMATCHED_BRACKET)?; + if delimiter == b':' && !is_posix_char_class(&pattern[i + 2..end - 2]) { + return Err(INVALID_CLASS_NAME); } + state |= HAS_RANGE_OR_CLASS; + i = end; + continue; } // `x-y` is a range, but the `-` of `[x-]` is an ordinary character. if pattern.get(i + 1) == Some(&b'-') @@ -687,7 +712,7 @@ fn scan_bracket(pattern: &[u8], start: usize) -> (bool, usize) { i += 1; } // Unterminated bracket: the regex engine reports that on its own. - (false, pattern.len()) + Ok(pattern.len()) } /// Index just past the `:]`, `.]` or `=]` closing a `[: [. [=` subexpression @@ -700,7 +725,10 @@ fn find_bracket_subexpr_end(pattern: &[u8], start: usize, delimiter: u8) -> Opti #[cfg(test)] mod tests { - use super::{has_confusing_bracket, plain_literal, utf8_char_step}; + use super::{ + CONFUSING_BRACKET, INVALID_CLASS_NAME, UNMATCHED_BRACKET, check_brackets, plain_literal, + utf8_char_step, + }; use crate::RegexMode; #[test] @@ -800,7 +828,11 @@ mod tests { "[:x:]", "ab[:blank:]", ] { - assert!(has_confusing_bracket(p.as_bytes()), "pattern {p:?}"); + assert_eq!( + check_brackets(p.as_bytes()), + Err(CONFUSING_BRACKET), + "pattern {p:?}" + ); } } @@ -820,7 +852,26 @@ mod tests { "[:digit:", // unterminated "[a-z]+[0-9]", // no colons at all ] { - assert!(!has_confusing_bracket(p.as_bytes()), "pattern {p:?}"); + assert!(check_brackets(p.as_bytes()).is_ok(), "pattern {p:?}"); + } + } + + #[test] + fn rejects_invalid_and_unclosed_bracket_subexpressions() { + for p in ["[[:word:]]", "[[:^alpha:]]", "[[::]]"] { + assert_eq!( + check_brackets(p.as_bytes()), + Err(INVALID_CLASS_NAME), + "{p:?}" + ); + } + for p in ["[[:alpha]]", "[x[:]y]", "[[.a]", "[[=a]"] { + assert_eq!( + check_brackets(p.as_bytes()), + Err(UNMATCHED_BRACKET), + "{p:?}" + ); } + assert!(check_brackets(b"[[:alpha:]][[.a.]][[=a=]]").is_ok()); } } diff --git a/tests/test_grep.rs b/tests/test_grep.rs index 51334c5e..dc084104 100644 --- a/tests/test_grep.rs +++ b/tests/test_grep.rs @@ -2764,3 +2764,41 @@ fn files_without_match_with_nothing_selectable() { .stdout_is("trees.txt\n") .stderr_contains("missing.txt: "); } + +#[test] +fn rejects_invalid_character_class_names() { + let cases = [ + ("[[:word:]]", "Invalid character class name"), + ("[[:ascii:]]", "Invalid character class name"), + ("[[:^digit:]]", "Invalid character class name"), + ("[[::]]", "Invalid character class name"), + ("[[:digit]]", "Unmatched [, [^, [:, [., or [="), + ("[x[:]y]", "Unmatched [, [^, [:, [., or [="), + ("[[:]", "Unmatched [, [^, [:, [., or [="), + ("[[:a:b]", "Unmatched [, [^, [:, [., or [="), + ("[[.a]", "Unmatched [, [^, [:, [., or [="), + ("[[=a]", "Unmatched [, [^, [:, [., or [="), + ]; + for (pattern, message) in cases { + for mode in ["-G", "-E"] { + let (scene, mut c) = ucmd(); + scene.fixtures.write("input", "7\n:]\n"); + c.args(&[mode, pattern, "input"]) + .fails_with_code(2) + .no_stdout() + .stderr_contains(message); + } + } + // The twelve POSIX names and valid bracket subexpressions keep working. + let (scene, mut c) = ucmd(); + scene.fixtures.write("valid", "f\nz\n"); + c.args(&["[[:xdigit:]]", "valid"]) + .succeeds() + .stdout_only("f\n"); + + let (scene, mut c) = ucmd(); + scene.fixtures.write("valid2", "a\nb\n"); + c.args(&["[[.a.]][[=b=]]", "valid2"]) + .fails_with_code(1) + .no_stdout(); +}