Debian Codegraph @

debian/rust-vendor/shlex/src/bytes.rs

raw
1 // Copyright 2015 Nicholas Allegra (comex).
2 // Licensed under the Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> or
3 // the MIT license <https://opensource.org/licenses/MIT>, at your option. This file may not be
4 // copied, modified, or distributed except according to those terms.
5
6 //! [`Shlex`] and friends for byte strings.
7 //!
8 //! This is used internally by the [outer module](crate), and may be more
9 //! convenient if you are working with byte slices (`[u8]`) or types that are
10 //! wrappers around bytes, such as [`OsStr`](std::ffi::OsStr):
11 //!
12 //! ```rust
13 //! #[cfg(unix)] {
14 //! use shlex::bytes::try_quote;
15 //! use std::ffi::OsStr;
16 //! use std::os::unix::ffi::OsStrExt;
17 //!
18 //! // `\x80` is invalid in UTF-8.
19 //! let os_str = OsStr::from_bytes(b"a\x80b c");
20 //! assert_eq!(try_quote(os_str.as_bytes()).unwrap(), &b"'a\x80b c'"[..]);
21 //! }
22 //! ```
23 //!
24 //! (On Windows, `OsStr` uses 16 bit wide characters so this will not work.)
25
26 extern crate alloc;
27 use alloc::vec::Vec;
28 use alloc::borrow::Cow;
29 #[cfg(test)]
30 use alloc::borrow::ToOwned;
31 #[cfg(all(doc, not(doctest)))]
32 use crate::{self as shlex, quoting_warning};
33
34 use super::QuoteError;
35
36 /// An iterator that takes an input byte string and splits it into the words using the same syntax as
37 /// the POSIX shell.
38 pub struct Shlex<'a> {
39 in_iter: core::slice::Iter<'a, u8>,
40 /// The number of newlines read so far, plus one.
41 pub line_no: usize,
42 /// An input string is erroneous if it ends while inside a quotation or right after an
43 /// unescaped backslash. Since Iterator does not have a mechanism to return an error, if that
44 /// happens, Shlex just throws out the last token, ends the iteration, and sets 'had_error' to
45 /// true; best to check it after you're done iterating.
46 pub had_error: bool,
47 }
48
49 impl<'a> Shlex<'a> {
50 pub fn new(in_bytes: &'a [u8]) -> Self {
51 Shlex {
52 in_iter: in_bytes.iter(),
53 line_no: 1,
54 had_error: false,
55 }
56 }
57
58 fn parse_word(&mut self, mut ch: u8) -> Option<Vec<u8>> {
59 let mut result: Vec<u8> = Vec::new();
60 loop {
61 match ch as char {
62 '"' => if let Err(()) = self.parse_double(&mut result) {
63 self.had_error = true;
64 return None;
65 },
66 '\'' => if let Err(()) = self.parse_single(&mut result) {
67 self.had_error = true;
68 return None;
69 },
70 '\\' => if let Some(ch2) = self.next_char() {
71 if ch2 != b'\n' { result.push(ch2); }
72 } else {
73 self.had_error = true;
74 return None;
75 },
76 ' ' | '\t' | '\n' => { break; },
77 _ => { result.push(ch); },
78 }
79 if let Some(ch2) = self.next_char() { ch = ch2; } else { break; }
80 }
81 Some(result)
82 }
83
84 fn parse_double(&mut self, result: &mut Vec<u8>) -> Result<(), ()> {
85 loop {
86 if let Some(ch2) = self.next_char() {
87 match ch2 as char {
88 '\\' => {
89 if let Some(ch3) = self.next_char() {
90 match ch3 as char {
91 // \$ => $
92 '$' | '`' | '"' | '\\' => { result.push(ch3); },
93 // \<newline> => nothing
94 '\n' => {},
95 // \x => =x
96 _ => { result.push(b'\\'); result.push(ch3); }
97 }
98 } else {
99 return Err(());
100 }
101 },
102 '"' => { return Ok(()); },
103 _ => { result.push(ch2); },
104 }
105 } else {
106 return Err(());
107 }
108 }
109 }
110
111 fn parse_single(&mut self, result: &mut Vec<u8>) -> Result<(), ()> {
112 loop {
113 if let Some(ch2) = self.next_char() {
114 match ch2 as char {
115 '\'' => { return Ok(()); },
116 _ => { result.push(ch2); },
117 }
118 } else {
119 return Err(());
120 }
121 }
122 }
123
124 fn next_char(&mut self) -> Option<u8> {
125 let res = self.in_iter.next().copied();
126 if res == Some(b'\n') { self.line_no += 1; }
127 res
128 }
129 }
130
131 impl Iterator for Shlex<'_> {
132 type Item = Vec<u8>;
133 fn next(&mut self) -> Option<Self::Item> {
134 if let Some(mut ch) = self.next_char() {
135 // skip initial whitespace
136 loop {
137 match ch as char {
138 ' ' | '\t' | '\n' => {},
139 '#' => {
140 while let Some(ch2) = self.next_char() {
141 if ch2 as char == '\n' { break; }
142 }
143 },
144 _ => { break; }
145 }
146 if let Some(ch2) = self.next_char() { ch = ch2; } else { return None; }
147 }
148 self.parse_word(ch)
149 } else { // no initial character
150 None
151 }
152 }
153
154 }
155
156 /// Convenience function that consumes the whole byte string at once. Returns None if the input was
157 /// erroneous.
158 pub fn split(in_bytes: &[u8]) -> Option<Vec<Vec<u8>>> {
159 let mut shl = Shlex::new(in_bytes);
160 let res = shl.by_ref().collect();
161 if shl.had_error { None } else { Some(res) }
162 }
163
164 /// A more configurable interface to quote strings. If you only want the default settings you can
165 /// use the convenience functions [`try_quote`] and [`try_join`].
166 ///
167 /// The string equivalent is [`shlex::Quoter`].
168 #[derive(Default, Debug, Clone)]
169 pub struct Quoter {
170 allow_nul: bool,
171 // TODO: more options
172 }
173
174 impl Quoter {
175 /// Create a new [`Quoter`] with default settings.
176 #[inline]
177 pub fn new() -> Self {
178 Self::default()
179 }
180
181 /// Set whether to allow [nul bytes](quoting_warning#nul-bytes). By default they are not
182 /// allowed and will result in an error of [`QuoteError::Nul`].
183 #[inline]
184 pub fn allow_nul(mut self, allow: bool) -> Self {
185 self.allow_nul = allow;
186 self
187 }
188
189 /// Convenience function that consumes an iterable of words and turns it into a single byte string,
190 /// quoting words when necessary. Consecutive words will be separated by a single space.
191 pub fn join<'a, I: IntoIterator<Item = &'a [u8]>>(&self, words: I) -> Result<Vec<u8>, QuoteError> {
192 Ok(words.into_iter()
193 .map(|word| self.quote(word))
194 .collect::<Result<Vec<Cow<[u8]>>, QuoteError>>()?
195 .join(&b' '))
196 }
197
198 /// Given a single word, return a byte string suitable to encode it as a shell argument.
199 ///
200 /// If given valid UTF-8, this will never produce invalid UTF-8. This is because it only
201 /// ever inserts valid ASCII characters before or after existing ASCII characters (or
202 /// returns two single quotes if the input was an empty string). It will never modify a
203 /// multibyte UTF-8 character.
204 pub fn quote<'a>(&self, mut in_bytes: &'a [u8]) -> Result<Cow<'a, [u8]>, QuoteError> {
205 if in_bytes.is_empty() {
206 // Empty string. Special case that isn't meaningful as only part of a word.
207 return Ok(b"''"[..].into());
208 }
209 if !self.allow_nul && in_bytes.contains(&b'\0') {
210 return Err(QuoteError::Nul);
211 }
212 let mut out: Vec<u8> = Vec::new();
213 while !in_bytes.is_empty() {
214 // Pick a quoting strategy for some prefix of the input. Normally this will cover the
215 // entire input, but in some case we might need to divide the input into multiple chunks
216 // that are quoted differently.
217 let (cur_len, strategy) = quoting_strategy(in_bytes);
218 if cur_len == in_bytes.len() && strategy == QuotingStrategy::Unquoted && out.is_empty() {
219 // Entire string can be represented unquoted. Reuse the allocation.
220 return Ok(in_bytes.into());
221 }
222 let (cur_chunk, rest) = in_bytes.split_at(cur_len);
223 assert!(rest.len() < in_bytes.len()); // no infinite loop
224 in_bytes = rest;
225 append_quoted_chunk(&mut out, cur_chunk, strategy);
226 }
227 Ok(out.into())
228 }
229
230 }
231
232 #[derive(PartialEq)]
233 enum QuotingStrategy {
234 /// No quotes and no backslash escapes. (If backslash escapes would be necessary, we use a
235 /// different strategy instead.)
236 Unquoted,
237 /// Single quoted.
238 SingleQuoted,
239 /// Double quotes, potentially with backslash escapes.
240 DoubleQuoted,
241 // TODO: add $'xxx' and "$(printf 'xxx')" styles
242 }
243
244 /// Is this ASCII byte okay to emit unquoted?
245 const fn unquoted_ok(c: u8) -> bool {
246 match c as char {
247 // Allowed characters:
248 '+' | '-' | '.' | '/' | ':' | '@' | ']' | '_' |
249 '0'..='9' | 'A'..='Z' | 'a'..='z'
250 => true,
251
252 // Non-allowed characters:
253 // From POSIX https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html
254 // "The application shall quote the following characters if they are to represent themselves:"
255 '|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '\\' | '"' | '\'' | ' ' | '\t' | '\n' |
256 // "and the following may need to be quoted under certain circumstances[..]:"
257 '*' | '?' | '[' | '#' | '~' | '=' | '%' |
258 // Brace expansion. These ought to be in the POSIX list but aren't yet;
259 // see: https://www.austingroupbugs.net/view.php?id=1193
260 '{' | '}' |
261 // Also quote comma, just to be safe in the extremely odd case that the user of this crate
262 // is intentionally placing a quoted string inside a brace expansion, e.g.:
263 // format!("echo foo{{a,b,{}}}" | shlex::quote(some_str))
264 ',' |
265 // '\r' is allowed in a word by all real shells I tested, but is treated as a word
266 // separator by Python `shlex` | and might be translated to '\n' in interactive mode.
267 '\r' |
268 // '!' and '^' are treated specially in interactive mode; see quoting_warning.
269 '!' | '^' |
270 // Nul bytes and control characters.
271 '\x00' ..= '\x1f' | '\x7f'
272 => false,
273 '\u{80}' ..= '\u{10ffff}' => {
274 // This is unreachable since `unquoted_ok` is only called for 0..128.
275 // Non-ASCII bytes are handled separately in `quoting_strategy`.
276 // Can't call unreachable!() from `const fn` on old Rust, so...
277 unquoted_ok(c)
278 },
279 }
280 // Note: The logic cited above for quoting comma might suggest that `..` should also be quoted,
281 // it as a special case of brace expansion). But it's not necessary. There are three cases:
282 //
283 // 1. The user wants comma-based brace expansion, but the untrusted string being `quote`d
284 // contains `..`, so they get something like `{foo,bar,3..5}`.
285 // => That's safe; both Bash and Zsh expand this to `foo bar 3..5` rather than
286 // `foo bar 3 4 5`. The presence of commas disables sequence expression expansion.
287 //
288 // 2. The user wants comma-based brace expansion where the contents of the braces are a
289 // variable number of `quote`d strings and nothing else. There happens to be exactly
290 // one string and it contains `..`, so they get something like `{3..5}`.
291 // => Then this will expand as a sequence expression, which is unintended. But I don't mind,
292 // because any such code is already buggy. Suppose the untrusted string *didn't* contain
293 // `,` or `..`, resulting in shell input like `{foo}`. Then the shell would interpret it
294 // as the literal string `{foo}` rather than brace-expanding it into `foo`.
295 //
296 // 3. The user wants a sequence expression and wants to supply an untrusted string as one of
297 // the endpoints or the increment.
298 // => Well, that's just silly, since the endpoints can only be numbers or single letters.
299 }
300
301 /// Optimized version of `unquoted_ok`.
302 fn unquoted_ok_fast(c: u8) -> bool {
303 const UNQUOTED_OK_MASK: u128 = {
304 // Make a mask of all bytes in 0..<0x80 that pass.
305 let mut c = 0u8;
306 let mut mask = 0u128;
307 while c < 0x80 {
308 if unquoted_ok(c) {
309 mask |= 1u128 << c;
310 }
311 c += 1;
312 }
313 mask
314 };
315 ((UNQUOTED_OK_MASK >> c) & 1) != 0
316 }
317
318 /// Is this ASCII byte okay to emit in single quotes?
319 fn single_quoted_ok(c: u8) -> bool {
320 match c {
321 // No single quotes in single quotes.
322 b'\'' => false,
323 // To work around a Bash bug, ^ is only allowed right after an opening single quote; see
324 // quoting_warning.
325 b'^' => false,
326 // Backslashes in single quotes are literal according to POSIX, but Fish treats them as an
327 // escape character. Ban them. Fish doesn't aim to be POSIX-compatible, but we *can*
328 // achieve Fish compatibility using double quotes, so we might as well.
329 b'\\' => false,
330 _ => true
331 }
332 }
333
334 /// Is this ASCII byte okay to emit in double quotes?
335 fn double_quoted_ok(c: u8) -> bool {
336 match c {
337 // Work around Python `shlex` bug where parsing "\`" and "\$" doesn't strip the
338 // backslash, even though POSIX requires it.
339 b'`' | b'$' => false,
340 // '!' and '^' are treated specially in interactive mode; see quoting_warning.
341 b'!' | b'^' => false,
342 _ => true
343 }
344 }
345
346 /// Given an input, return a quoting strategy that can cover some prefix of the string, along with
347 /// the size of that prefix.
348 ///
349 /// Precondition: input size is nonzero. (Empty strings are handled by the caller.)
350 /// Postcondition: returned size is nonzero.
351 #[cfg_attr(manual_codegen_check, inline(never))]
352 fn quoting_strategy(in_bytes: &[u8]) -> (usize, QuotingStrategy) {
353 const UNQUOTED_OK: u8 = 1;
354 const SINGLE_QUOTED_OK: u8 = 2;
355 const DOUBLE_QUOTED_OK: u8 = 4;
356
357 let mut prev_ok = SINGLE_QUOTED_OK | DOUBLE_QUOTED_OK | UNQUOTED_OK;
358 let mut i = 0;
359
360 if in_bytes[0] == b'^' {
361 // To work around a Bash bug, ^ is only allowed right after an opening single quote; see
362 // quoting_warning.
363 prev_ok = SINGLE_QUOTED_OK;
364 i = 1;
365 }
366
367 while i < in_bytes.len() {
368 let c = in_bytes[i];
369 let mut cur_ok = prev_ok;
370
371 if c >= 0x80 {
372 // Normally, non-ASCII characters shouldn't require quoting, but see quoting_warning.md
373 // about \xa0. For now, just treat all non-ASCII characters as requiring quotes. This
374 // also ensures things are safe in the off-chance that you're in a legacy 8-bit locale that
375 // has additional characters satisfying `isblank`.
376 cur_ok &= !UNQUOTED_OK;
377 } else {
378 if !unquoted_ok_fast(c) {
379 cur_ok &= !UNQUOTED_OK;
380 }
381 if !single_quoted_ok(c){
382 cur_ok &= !SINGLE_QUOTED_OK;
383 }
384 if !double_quoted_ok(c) {
385 cur_ok &= !DOUBLE_QUOTED_OK;
386 }
387 }
388
389 if cur_ok == 0 {
390 // There are no quoting strategies that would work for both the previous characters and
391 // this one. So we have to end the chunk before this character. The caller will call
392 // `quoting_strategy` again to handle the rest of the string.
393 break;
394 }
395
396 prev_ok = cur_ok;
397 i += 1;
398 }
399
400 // Pick the best allowed strategy.
401 let strategy = if prev_ok & UNQUOTED_OK != 0 {
402 QuotingStrategy::Unquoted
403 } else if prev_ok & SINGLE_QUOTED_OK != 0 {
404 QuotingStrategy::SingleQuoted
405 } else if prev_ok & DOUBLE_QUOTED_OK != 0 {
406 QuotingStrategy::DoubleQuoted
407 } else {
408 unreachable!()
409 };
410 debug_assert!(i > 0);
411 (i, strategy)
412 }
413
414 fn append_quoted_chunk(out: &mut Vec<u8>, cur_chunk: &[u8], strategy: QuotingStrategy) {
415 match strategy {
416 QuotingStrategy::Unquoted => {
417 out.extend_from_slice(cur_chunk);
418 },
419 QuotingStrategy::SingleQuoted => {
420 out.reserve(cur_chunk.len() + 2);
421 out.push(b'\'');
422 out.extend_from_slice(cur_chunk);
423 out.push(b'\'');
424 },
425 QuotingStrategy::DoubleQuoted => {
426 out.reserve(cur_chunk.len() + 2);
427 out.push(b'"');
428 for &c in cur_chunk.iter() {
429 if let b'$' | b'`' | b'"' | b'\\' = c {
430 // Add a preceding backslash.
431 // Note: We shouldn't actually get here for $ and ` because they don't pass
432 // `double_quoted_ok`.
433 out.push(b'\\');
434 }
435 // Add the character itself.
436 out.push(c);
437 }
438 out.push(b'"');
439 },
440 }
441 }
442
443 /// Convenience function that consumes an iterable of words and turns it into a single byte string,
444 /// quoting words when necessary. Consecutive words will be separated by a single space.
445 ///
446 /// Uses default settings. The only error that can be returned is [`QuoteError::Nul`].
447 ///
448 /// Equivalent to [`Quoter::new().join(words)`](Quoter).
449 ///
450 /// The string equivalent is [shlex::try_join].
451 pub fn try_join<'a, I: IntoIterator<Item = &'a [u8]>>(words: I) -> Result<Vec<u8>, QuoteError> {
452 Quoter::new().join(words)
453 }
454
455 /// Given a single word, return a string suitable to encode it as a shell argument.
456 ///
457 /// Uses default settings. The only error that can be returned is [`QuoteError::Nul`].
458 ///
459 /// Equivalent to [`Quoter::new().quote(in_bytes)`](Quoter).
460 ///
461 /// The string equivalent is [shlex::try_quote].
462 pub fn try_quote(in_bytes: &[u8]) -> Result<Cow<'_, [u8]>, QuoteError> {
463 Quoter::new().quote(in_bytes)
464 }
465
466 #[cfg(test)]
467 const INVALID_UTF8: &[u8] = b"\xa1";
468
469 #[test]
470 #[allow(invalid_from_utf8)]
471 fn test_invalid_utf8() {
472 // Check that our test string is actually invalid UTF-8.
473 assert!(core::str::from_utf8(INVALID_UTF8).is_err());
474 }
475
476 #[cfg(test)]
477 static SPLIT_TEST_ITEMS: &[(&[u8], Option<&[&[u8]]>)] = &[
478 (b"foo$baz", Some(&[b"foo$baz"])),
479 (b"foo baz", Some(&[b"foo", b"baz"])),
480 (b"foo\"bar\"baz", Some(&[b"foobarbaz"])),
481 (b"foo \"bar\"baz", Some(&[b"foo", b"barbaz"])),
482 (b" foo \nbar", Some(&[b"foo", b"bar"])),
483 (b"foo\\\nbar", Some(&[b"foobar"])),
484 (b"\"foo\\\nbar\"", Some(&[b"foobar"])),
485 (b"'baz\\$b'", Some(&[b"baz\\$b"])),
486 (b"'baz\\\''", None),
487 (b"\\", None),
488 (b"\"\\", None),
489 (b"'\\", None),
490 (b"\"", None),
491 (b"'", None),
492 (b"foo #bar\nbaz", Some(&[b"foo", b"baz"])),
493 (b"foo #bar", Some(&[b"foo"])),
494 (b"foo#bar", Some(&[b"foo#bar"])),
495 (b"foo\"#bar", None),
496 (b"'\\n'", Some(&[b"\\n"])),
497 (b"'\\\\n'", Some(&[b"\\\\n"])),
498 (INVALID_UTF8, Some(&[INVALID_UTF8])),
499 ];
500
501 #[test]
502 fn test_split() {
503 for &(input, output) in SPLIT_TEST_ITEMS {
504 assert_eq!(split(input), output.map(|o| o.iter().map(|&x| x.to_owned()).collect()));
505 }
506 }
507
508 #[test]
509 fn test_lineno() {
510 let mut sh = Shlex::new(b"\nfoo\nbar");
511 while let Some(word) = sh.next() {
512 if word == b"bar" {
513 assert_eq!(sh.line_no, 3);
514 }
515 }
516 }