Debian Codegraph @

debian/rust-vendor/shlex/src/lib.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 //! Parse strings like, and escape strings for, POSIX shells.
7 //!
8 //! Same idea as (but implementation not directly based on) the Python shlex module.
9 //!
10 //! Disabling the `std` feature (which is enabled by default) will allow the crate to work in
11 //! `no_std` environments, where the `alloc` crate, and a global allocator, are available.
12 //!
13 //! ## <span style="color:red">Warning</span>
14 //!
15 //! The [`try_quote`]/[`try_join`] family of APIs does not quote control characters (because they
16 //! cannot be quoted portably).
17 //!
18 //! This is fully safe in noninteractive contexts, like shell scripts and `sh -c` arguments (or
19 //! even scripts `source`d from interactive shells).
20 //!
21 //! But if you are quoting for human consumption, you should keep in mind that ugly inputs produce
22 //! ugly outputs (which may not be copy-pastable).
23 //!
24 //! And if by chance you are piping the output of [`try_quote`]/[`try_join`] directly to the stdin
25 //! of an interactive shell, you should stop, because control characters can lead to arbitrary
26 //! command injection.
27 //!
28 //! For more information, and for information about more minor issues, please see [quoting_warning].
29 //!
30 //! ## Compatibility
31 //!
32 //! This crate's quoting functionality tries to be compatible with **any POSIX-compatible shell**;
33 //! it's tested against `bash`, `zsh`, `dash`, Busybox `ash`, and `mksh`, plus `fish` (which is not
34 //! POSIX-compatible but close enough).
35 //!
36 //! It also aims to be compatible with Python `shlex` and C `wordexp`.
37
38 #![cfg_attr(not(feature = "std"), no_std)]
39
40 extern crate alloc;
41 use alloc::vec::Vec;
42 use alloc::borrow::Cow;
43 use alloc::string::String;
44 #[cfg(test)]
45 use alloc::vec;
46 #[cfg(test)]
47 use alloc::borrow::ToOwned;
48
49 pub mod bytes;
50 #[cfg(all(doc, not(doctest)))]
51 #[path = "quoting_warning.md"]
52 pub mod quoting_warning;
53
54 /// An iterator that takes an input string and splits it into the words using the same syntax as
55 /// the POSIX shell.
56 ///
57 /// See [`bytes::Shlex`].
58 pub struct Shlex<'a>(bytes::Shlex<'a>);
59
60 impl<'a> Shlex<'a> {
61 pub fn new(in_str: &'a str) -> Self {
62 Self(bytes::Shlex::new(in_str.as_bytes()))
63 }
64
65 /// # Safety
66 ///
67 /// The parameter must have been constructed from valid UTF-8.
68 pub unsafe fn from_bytes(bytes: bytes::Shlex<'a>) -> Self {
69 Self(bytes)
70 }
71
72 /// # Safety
73 ///
74 /// If the returned reference is reassigned, the new [`bytes::Shlex`] must have been constructed from valid UTF-8.
75 pub unsafe fn as_bytes_mut(&mut self) -> &mut bytes::Shlex<'a> {
76 &mut self.0
77 }
78 }
79
80 impl Iterator for Shlex<'_> {
81 type Item = String;
82 fn next(&mut self) -> Option<String> {
83 self.0.next().map(|byte_word| {
84 // Safety: given valid UTF-8, bytes::Shlex will always return valid UTF-8.
85 unsafe { String::from_utf8_unchecked(byte_word) }
86 })
87 }
88 }
89
90 impl<'a> core::ops::Deref for Shlex<'a> {
91 type Target = bytes::Shlex<'a>;
92
93 fn deref(&self) -> &Self::Target {
94 &self.0
95 }
96 }
97
98 /// Convenience function that consumes the whole string at once. Returns None if the input was
99 /// erroneous.
100 pub fn split(in_str: &str) -> Option<Vec<String>> {
101 let mut shl = Shlex::new(in_str);
102 let res = shl.by_ref().collect();
103 if shl.had_error { None } else { Some(res) }
104 }
105
106 /// Errors from [`Quoter::quote`], [`Quoter::join`], etc. (and their [`bytes`] counterparts).
107 ///
108 /// By default, the only error that can be returned is [`QuoteError::Nul`]. If you call
109 /// `allow_nul(true)`, then no errors can be returned at all. Any error variants added in the
110 /// future will not be enabled by default; they will be enabled through corresponding non-default
111 /// [`Quoter`] options.
112 ///
113 /// ...In theory. In the unlikely event that additional classes of inputs are discovered that,
114 /// like nul bytes, are fundamentally unsafe to quote even for non-interactive shells, the risk
115 /// will be mitigated by adding corresponding [`QuoteError`] variants that *are* enabled by
116 /// default.
117 #[non_exhaustive]
118 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
119 pub enum QuoteError {
120 /// The input contained a nul byte. In most cases, shells fundamentally [cannot handle strings
121 /// containing nul bytes](quoting_warning#nul-bytes), no matter how they are quoted. But if
122 /// you're sure you can handle nul bytes, you can call `allow_nul(true)` on the `Quoter` to let
123 /// them pass through.
124 Nul,
125 }
126
127 impl core::fmt::Display for QuoteError {
128 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
129 match self {
130 QuoteError::Nul => f.write_str("cannot shell-quote string containing nul byte"),
131 }
132 }
133 }
134
135 #[cfg(feature = "std")]
136 impl std::error::Error for QuoteError {}
137
138 /// A more configurable interface to quote strings. If you only want the default settings you can
139 /// use the convenience functions [`try_quote`] and [`try_join`].
140 ///
141 /// The bytes equivalent is [`bytes::Quoter`].
142 #[derive(Default, Debug, Clone)]
143 pub struct Quoter {
144 inner: bytes::Quoter,
145 }
146
147 impl Quoter {
148 /// Create a new [`Quoter`] with default settings.
149 #[inline]
150 pub fn new() -> Self {
151 Self::default()
152 }
153
154 /// Set whether to allow [nul bytes](quoting_warning#nul-bytes). By default they are not
155 /// allowed and will result in an error of [`QuoteError::Nul`].
156 #[inline]
157 pub fn allow_nul(mut self, allow: bool) -> Self {
158 self.inner = self.inner.allow_nul(allow);
159 self
160 }
161
162 /// Convenience function that consumes an iterable of words and turns it into a single string,
163 /// quoting words when necessary. Consecutive words will be separated by a single space.
164 pub fn join<'a, I: IntoIterator<Item = &'a str>>(&self, words: I) -> Result<String, QuoteError> {
165 // Safety: given valid UTF-8, bytes::join() will always return valid UTF-8.
166 self.inner.join(words.into_iter().map(|s| s.as_bytes()))
167 .map(|bytes| unsafe { String::from_utf8_unchecked(bytes) })
168 }
169
170 /// Given a single word, return a string suitable to encode it as a shell argument.
171 pub fn quote<'a>(&self, in_str: &'a str) -> Result<Cow<'a, str>, QuoteError> {
172 Ok(match self.inner.quote(in_str.as_bytes())? {
173 Cow::Borrowed(out) => {
174 // Safety: given valid UTF-8, bytes::quote() will always return valid UTF-8.
175 unsafe { core::str::from_utf8_unchecked(out) }.into()
176 }
177 Cow::Owned(out) => {
178 // Safety: given valid UTF-8, bytes::quote() will always return valid UTF-8.
179 unsafe { String::from_utf8_unchecked(out) }.into()
180 }
181 })
182 }
183 }
184
185 impl From<bytes::Quoter> for Quoter {
186 fn from(inner: bytes::Quoter) -> Quoter {
187 Quoter { inner }
188 }
189 }
190
191 impl From<Quoter> for bytes::Quoter {
192 fn from(quoter: Quoter) -> bytes::Quoter {
193 quoter.inner
194 }
195 }
196
197 /// Convenience function that consumes an iterable of words and turns it into a single string,
198 /// quoting words when necessary. Consecutive words will be separated by a single space.
199 ///
200 /// Uses default settings. The only error that can be returned is [`QuoteError::Nul`].
201 ///
202 /// Equivalent to [`Quoter::new().join(words)`](Quoter).
203 ///
204 /// The bytes equivalent is [bytes::try_join].
205 pub fn try_join<'a, I: IntoIterator<Item = &'a str>>(words: I) -> Result<String, QuoteError> {
206 Quoter::new().join(words)
207 }
208
209 /// Given a single word, return a string suitable to encode it as a shell argument.
210 ///
211 /// Uses default settings. The only error that can be returned is [`QuoteError::Nul`].
212 ///
213 /// Equivalent to [`Quoter::new().quote(in_str)`](Quoter).
214 ///
215 /// The bytes equivalent is [bytes::try_quote].
216 pub fn try_quote(in_str: &str) -> Result<Cow<'_, str>, QuoteError> {
217 Quoter::new().quote(in_str)
218 }
219
220 #[cfg(test)]
221 static SPLIT_TEST_ITEMS: &[(&str, Option<&[&str]>)] = &[
222 ("foo$baz", Some(&["foo$baz"])),
223 ("foo baz", Some(&["foo", "baz"])),
224 ("foo\"bar\"baz", Some(&["foobarbaz"])),
225 ("foo \"bar\"baz", Some(&["foo", "barbaz"])),
226 (" foo \nbar", Some(&["foo", "bar"])),
227 ("foo\\\nbar", Some(&["foobar"])),
228 ("\"foo\\\nbar\"", Some(&["foobar"])),
229 ("'baz\\$b'", Some(&["baz\\$b"])),
230 ("'baz\\\''", None),
231 ("\\", None),
232 ("\"\\", None),
233 ("'\\", None),
234 ("\"", None),
235 ("'", None),
236 ("foo #bar\nbaz", Some(&["foo", "baz"])),
237 ("foo #bar", Some(&["foo"])),
238 ("foo#bar", Some(&["foo#bar"])),
239 ("foo\"#bar", None),
240 ("'\\n'", Some(&["\\n"])),
241 ("'\\\\n'", Some(&["\\\\n"])),
242 ];
243
244 #[test]
245 fn test_split() {
246 for &(input, output) in SPLIT_TEST_ITEMS {
247 assert_eq!(split(input), output.map(|o| o.iter().map(|&x| x.to_owned()).collect()));
248 }
249 }
250
251 #[test]
252 fn test_lineno() {
253 let mut sh = Shlex::new("\nfoo\nbar");
254 while let Some(word) = sh.next() {
255 if word == "bar" {
256 assert_eq!(sh.line_no, 3);
257 }
258 }
259 }
260
261 #[test]
262 #[cfg_attr(not(feature = "std"), allow(unreachable_code, unused_mut))]
263 fn test_quote() {
264 // This is a list of (unquoted, quoted) pairs.
265 // But it's using a single long (raw) string literal with an ad-hoc format, just because it's
266 // hard to read if we have to put the test strings through Rust escaping on top of the escaping
267 // being tested. (Even raw string literals are noisy for short strings).
268 // Ad-hoc: "NL" is replaced with a literal newline; no other escape sequences.
269 let tests = r#"
270 <> => <''>
271 <foobar> => <foobar>
272 <foo bar> => <'foo bar'>
273 <"foo bar'"> => <"\"foo bar'\"">
274 <'foo bar'> => <"'foo bar'">
275 <"> => <'"'>
276 <"'> => <"\"'">
277 <hello!world> => <'hello!world'>
278 <'hello!world> => <"'hello"'!world'>
279 <'hello!> => <"'hello"'!'>
280 <hello ^ world> => <'hello ''^ world'>
281 <hello^> => <hello'^'>
282 <!world'> => <'!world'"'">
283 <{a, b}> => <'{a, b}'>
284 <NL> => <'NL'>
285 <^> => <'^'>
286 <foo^bar> => <foo'^bar'>
287 <NLx^> => <'NLx''^'>
288 <NL^x> => <'NL''^x'>
289 <NL ^x> => <'NL ''^x'>
290 <{a,b}> => <'{a,b}'>
291 <a,b> => <'a,b'>
292 <a..b => <a..b>
293 <'$> => <"'"'$'>
294 <"^> => <'"''^'>
295 "#;
296 let mut ok = true;
297 for test in tests.trim().split('\n') {
298 let parts: Vec<String> = test
299 .replace("NL", "\n")
300 .split("=>")
301 .map(|part| part.trim().trim_start_matches('<').trim_end_matches('>').to_owned())
302 .collect();
303 assert!(parts.len() == 2);
304 let unquoted = &*parts[0];
305 let quoted_expected = &*parts[1];
306 let quoted_actual = try_quote(&parts[0]).unwrap();
307 if quoted_expected != quoted_actual {
308 #[cfg(not(feature = "std"))]
309 panic!("FAIL: for input <{}>, expected <{}>, got <{}>",
310 unquoted, quoted_expected, quoted_actual);
311 #[cfg(feature = "std")]
312 println!("FAIL: for input <{}>, expected <{}>, got <{}>",
313 unquoted, quoted_expected, quoted_actual);
314 ok = false;
315 }
316 }
317 assert!(ok);
318 }
319
320 #[test]
321 fn test_fallible() {
322 assert_eq!(try_join(vec!["\0"]), Err(QuoteError::Nul));
323 assert_eq!(try_quote("\0"), Err(QuoteError::Nul));
324 }