shell_syntax.rs
This file
Path
src/shell_syntax.rs
265 lines · 9.2 KiB · Rust
Last changed by
Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02
History of this fileTake it
1//! Conservative detection of shell syntax in commands run without a shell.23use std::iter::Peekable;4use std::str::CharIndices;56/// Detects the variable assignment at the start of a command like7/// `OMP_NUM_THREADS=8 my_command`.8pub fn starts_with_assignment(command: &str) -> bool {9 let Some(token) = tokenize(command).next() else {10 return false;11 };12 let mut bytes = token.bytes();13 if !bytes14 .next()15 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')16 {17 return false;18 }19 for byte in bytes {20 if byte == b'=' {21 return true;22 }23 if !byte.is_ascii_alphanumeric() && byte != b'_' {24 return false;25 }26 }27 false28}2930/// Find the first standalone operator that is neither quoted nor escaped.31///32/// Operators attached to another word (such as `hello>out`), expansions, and33/// other shell syntax are deliberately outside the scope of this check.34pub fn first_unquoted_operator(command: &str) -> Option<&'static str> {35 tokenize(command).find_map(|token| {36 ["&&", "||", "|", ";", ">", ">>", "<"]37 .iter()38 .copied()39 .find(|operator| {40 // An escaped newline joins lines without quoting either side.41 // All other quotes and escapes remain in the token, preventing42 // it from matching an operator.43 token44 .split("\\\n")45 .flat_map(str::bytes)46 .eq(operator.bytes())47 })48 })49}5051/// Split words while preserving their original quoting and escaping.52///53/// Word boundaries and comments follow the same rules as `shell_words`, which54/// parses commands for direct execution. This tokenizer neither expands shell55/// expressions nor validates balanced quotes; command parsing handles errors.56fn tokenize(command: &str) -> impl Iterator<Item = &str> {57 Tokens {58 command,59 chars: command.char_indices().peekable(),60 }61}6263struct Tokens<'a> {64 command: &'a str,65 chars: Peekable<CharIndices<'a>>,66}6768impl<'a> Iterator for Tokens<'a> {69 type Item = &'a str;7071 fn next(&mut self) -> Option<Self::Item> {72 // Whitespace, comments, and line continuations cannot start a word.73 let start = loop {74 let &(index, character) = self.chars.peek()?;75 match character {76 ' ' | '\t' | '\n' => {77 self.chars.next();78 }79 '#' => {80 for (_, character) in self.chars.by_ref() {81 if character == '\n' {82 break;83 }84 }85 }86 '\\' if self.chars.clone().nth(1).map(|(_, c)| c) == Some('\n') => {87 self.chars.next();88 self.chars.next();89 }90 _ => break index,91 }92 };9394 let mut quote = None;95 while let Some((index, character)) = self.chars.next() {96 match (quote, character) {97 (Some('\''), '\'') | (Some('"'), '"') => quote = None,98 (Some('\''), _) => {}99 (_, '\\') => {100 // Within double quotes, skipping a non-special escaped101 // character is also safe: it cannot end the quoted word.102 self.chars.next();103 }104 (Some('"'), _) => {}105 (None, '\'' | '"') => quote = Some(character),106 (None, ' ' | '\t' | '\n') => return Some(&self.command[start..index]),107 _ => {}108 }109 }110111 Some(&self.command[start..])112 }113}114115#[cfg(test)]116mod tests {117 use super::{first_unquoted_operator, starts_with_assignment, tokenize};118119 #[test]120 fn detects_leading_assignments() {121 assert!(starts_with_assignment("A=1 command"));122 assert!(starts_with_assignment("A=$HOME command"));123 assert!(starts_with_assignment("A= command"));124 assert!(starts_with_assignment("_A2='hello world' B=2 command"));125 assert!(starts_with_assignment("A=1"));126 assert!(starts_with_assignment(" # comment\n A=1 command"));127128 assert!(!starts_with_assignment(""));129 assert!(!starts_with_assignment("# A=1 command"));130 assert!(!starts_with_assignment("command A=1"));131 assert!(!starts_with_assignment("env A=1 command"));132 assert!(!starts_with_assignment("'A=1' command"));133 assert!(!starts_with_assignment("\"A\"=1 command"));134 assert!(!starts_with_assignment(r"A\=1 command"));135 assert!(!starts_with_assignment("./A=1 command"));136 assert!(!starts_with_assignment("1A=1 command"));137 assert!(!starts_with_assignment("A-B=1 command"));138 assert!(!starts_with_assignment("=1 command"));139 assert!(!starts_with_assignment("A"));140 }141142 #[test]143 fn tokenizer_preserves_words_quotes_and_escapes() {144 for (command, expected) in [145 ("", vec![]),146 (" \t\n", vec![]),147 (" echo\thello\nworld ", vec!["echo", "hello", "world"]),148 (149 r#"echo '' "" 'hello world'"#,150 vec!["echo", "''", "\"\"", "'hello world'"],151 ),152 (153 r#"echo pre'quoted part'"more"post"#,154 vec!["echo", r#"pre'quoted part'"more"post"#],155 ),156 (157 r"echo hello\ world \&\&",158 vec!["echo", r"hello\ world", r"\&\&"],159 ),160 (r#"echo "a\" b" 'a\'"#, vec!["echo", r#""a\" b""#, r"'a\'"]),161 ("echo hello>out", vec!["echo", "hello>out"]),162 (163 "echo café\t&&\n日本語",164 vec!["echo", "café", "&&", "日本語"],165 ),166 ("echo a\r\u{a0}b", vec!["echo", "a\r\u{a0}b"]),167 ] {168 assert_eq!(169 tokenize(command).collect::<Vec<_>>(),170 expected,171 "{command:?}"172 );173 }174 }175176 #[test]177 fn tokenizer_handles_comments_and_continuations() {178 for (command, expected) in [179 ("# ignored &&", vec![]),180 (181 "echo # ignored &&\nnext | cat",182 vec!["echo", "next", "|", "cat"],183 ),184 (185 r##"echo a#b \#c "#d" '#e'"##,186 vec!["echo", "a#b", r"\#c", "\"#d\"", "'#e'"],187 ),188 ("\\\n echo \\\n&& more", vec!["echo", "&&", "more"]),189 ("echo hello\\\nworld", vec!["echo", "hello\\\nworld"]),190 ("\\\n# comment\necho", vec!["echo"]),191 ] {192 assert_eq!(193 tokenize(command).collect::<Vec<_>>(),194 expected,195 "{command:?}"196 );197 }198 }199200 #[test]201 fn finds_supported_operators_in_command_order() {202 for operator in ["&&", "||", "|", ";", ">", ">>", "<"] {203 let command = format!("echo café\t{operator}\n日本語");204 assert_eq!(first_unquoted_operator(&command), Some(operator));205 assert_eq!(first_unquoted_operator(operator), Some(operator));206 }207 assert_eq!(first_unquoted_operator("echo a >> out && next"), Some(">>"));208 assert_eq!(first_unquoted_operator("echo \\\n&& next"), Some("&&"));209 assert_eq!(first_unquoted_operator("echo &\\\n& next"), Some("&&"));210 assert_eq!(first_unquoted_operator("echo &&\\\n next"), Some("&&"));211 assert_eq!(first_unquoted_operator("echo # &&\nnext | cat"), Some("|"));212 assert_eq!(first_unquoted_operator(r#"echo "&&" || next"#), Some("||"));213 assert_eq!(first_unquoted_operator(r"echo \&\& | cat"), Some("|"));214 }215216 #[test]217 fn ignores_quoted_escaped_and_attached_operators() {218 for command in [219 r#"echo "&&""#,220 "echo '&&'",221 r"echo \&\&",222 r"echo &\&",223 r#"echo '&'"&""#,224 r#"echo ""&&"#,225 "echo &&''",226 r#"python -c "print(1 > 0)""#,227 "sh -c 'true && false'",228 r#"sh -c "echo 'a | b' && false""#,229 r#"sh -c 'echo "a | b" && false'"#,230 r#"echo "escaped \" && still quoted""#,231 "echo hello>out",232 "true&&false",233 "echo a;",234 "echo 2> out",235 "echo >>> out",236 "echo $VARIABLE *.rs ~/path NAME=value",237 "echo # && ignored",238 "echo foo#bar",239 "echo\u{a0}&&",240 "echo &&\r",241 ] {242 assert_eq!(first_unquoted_operator(command), None, "{command:?}");243 }244 }245246 #[test]247 fn handles_empty_and_malformed_commands_without_panicking() {248 for (command, expected) in [249 ("", vec![]),250 ("\\\n", vec![]),251 ("\\", vec!["\\"]),252 (r"echo \", vec!["echo", r"\"]),253 ("echo 'unclosed &&", vec!["echo", "'unclosed &&"]),254 ("echo \"unclosed &&", vec!["echo", "\"unclosed &&"]),255 ("echo \"unclosed\\", vec!["echo", "\"unclosed\\"]),256 ] {257 assert_eq!(258 tokenize(command).collect::<Vec<_>>(),259 expected,260 "{command:?}"261 );262 assert_eq!(first_unquoted_operator(command), None, "{command:?}");263 }264 }265}