1 /* gshell.c - Shell-related utilities
3 * Copyright 2000 Red Hat, Inc.
4 * g_execvpe implementation based on GNU libc execvp:
5 * Copyright 1991, 92, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
7 * SPDX-License-Identifier: LGPL-2.1-or-later
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with this library; if not, see <http://www.gnu.org/licenses/>.
30 #include "gstrfuncs.h"
32 #include "gtestutils.h"
38 * @title: Shell-related Utilities
39 * @short_description: shell-like commandline handling
41 * GLib provides the functions g_shell_quote() and g_shell_unquote()
42 * to handle shell-like quoting in strings. The function g_shell_parse_argv()
43 * parses a string similar to the way a POSIX shell (/bin/sh) would.
45 * Note that string handling in shells has many obscure and historical
46 * corner-cases which these functions do not necessarily reproduce. They
47 * are good enough in practice, though.
53 * Error domain for shell functions.
55 * Errors in this domain will be from the #GShellError enumeration.
57 * See #GError for information on error domains.
62 * @G_SHELL_ERROR_BAD_QUOTING: Mismatched or otherwise mangled quoting.
63 * @G_SHELL_ERROR_EMPTY_STRING: String to be parsed was empty.
64 * @G_SHELL_ERROR_FAILED: Some other error.
66 * Error codes returned by shell functions.
68 G_DEFINE_QUARK (g-shell-error-quark, g_shell_error)
70 /* Single quotes preserve the literal string exactly. escape
71 * sequences are not allowed; not even \' - if you want a '
72 * in the quoted text, you have to do something like 'foo'\''bar'
74 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
75 * Otherwise double quotes preserve things literally.
79 unquote_string_inplace (gchar* str, gchar** end, GError** err)
85 g_return_val_if_fail(end != NULL, FALSE);
86 g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
87 g_return_val_if_fail(str != NULL, FALSE);
93 if (!(*s == '"' || *s == '\''))
95 g_set_error_literal (err,
97 G_SHELL_ERROR_BAD_QUOTING,
98 _("Quoted text doesn’t begin with a quotation mark"));
103 /* Skip the initial quote mark */
106 if (quote_char == '"')
110 g_assert(s > dest); /* loop invariant */
115 /* End of the string, return now */
123 /* Possible escaped quote or \ */
138 /* not an escaped char */
141 /* ++s already done. */
153 g_assert(s > dest); /* loop invariant */
160 g_assert(s > dest); /* loop invariant */
164 /* End of the string, return now */
177 g_assert(s > dest); /* loop invariant */
181 /* If we reach here this means the close quote was never encountered */
185 g_set_error_literal (err,
187 G_SHELL_ERROR_BAD_QUOTING,
188 _("Unmatched quotation mark in command line or other shell-quoted text"));
195 * @unquoted_string: (type filename): a literal string
197 * Quotes a string so that the shell (/bin/sh) will interpret the
198 * quoted string to mean @unquoted_string.
200 * If you pass a filename to the shell, for example, you should first
201 * quote it with this function.
203 * The return value must be freed with g_free().
205 * The quoting style used is undefined (single or double quotes may be
208 * Returns: (type filename) (transfer full): quoted string
211 g_shell_quote (const gchar *unquoted_string)
213 /* We always use single quotes, because the algorithm is cheesier.
214 * We could use double if we felt like it, that might be more
221 g_return_val_if_fail (unquoted_string != NULL, NULL);
223 dest = g_string_new ("'");
227 /* could speed this up a lot by appending chunks of text at a
232 /* Replace literal ' with a close ', a \', and an open ' */
234 g_string_append (dest, "'\\''");
236 g_string_append_c (dest, *p);
241 /* close the quote */
242 g_string_append_c (dest, '\'');
244 return g_string_free (dest, FALSE);
249 * @quoted_string: (type filename): shell-quoted string
250 * @error: error return location or NULL
252 * Unquotes a string as the shell (/bin/sh) would.
254 * This function only handles quotes; if a string contains file globs,
255 * arithmetic operators, variables, backticks, redirections, or other
256 * special-to-the-shell features, the result will be different from the
257 * result a real shell would produce (the variables, backticks, etc.
258 * will be passed through literally instead of being expanded).
260 * This function is guaranteed to succeed if applied to the result of
261 * g_shell_quote(). If it fails, it returns %NULL and sets the
264 * The @quoted_string need not actually contain quoted or escaped text;
265 * g_shell_unquote() simply goes through the string and unquotes/unescapes
266 * anything that the shell would. Both single and double quotes are
267 * handled, as are escapes including escaped newlines.
269 * The return value must be freed with g_free().
271 * Possible errors are in the %G_SHELL_ERROR domain.
273 * Shell quoting rules are a bit strange. Single quotes preserve the
274 * literal string exactly. escape sequences are not allowed; not even
275 * `\'` - if you want a `'` in the quoted text, you have to do something
276 * like `'foo'\''bar'`. Double quotes allow `$`, ```, `"`, `\`, and
277 * newline to be escaped with backslash. Otherwise double quotes
278 * preserve things literally.
280 * Returns: (type filename): an unquoted string
283 g_shell_unquote (const gchar *quoted_string,
291 g_return_val_if_fail (quoted_string != NULL, NULL);
293 unquoted = g_strdup (quoted_string);
297 retval = g_string_new (NULL);
299 /* The loop allows cases such as
300 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
304 /* Append all non-quoted chars, honoring backslash escape
307 while (*start && !(*start == '"' || *start == '\''))
311 /* all characters can get escaped by backslash,
312 * except newline, which is removed if it follows
313 * a backslash outside of quotes
320 g_string_append_c (retval, *start);
326 g_string_append_c (retval, *start);
333 if (!unquote_string_inplace (start, &end, error))
339 g_string_append (retval, start);
346 return g_string_free (retval, FALSE);
349 g_assert (error == NULL || *error != NULL);
352 g_string_free (retval, TRUE);
356 /* g_parse_argv() does a semi-arbitrary weird subset of the way
357 * the shell parses a command line. We don't do variable expansion,
358 * don't understand that operators are tokens, don't do tilde expansion,
359 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
360 * don't do filename globs, don't remove redirection stuff, etc.
362 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
363 * the behavior of this code.
365 * Steps to parsing the argv string:
367 * - tokenize the string (but since we ignore operators,
368 * our tokenization may diverge from what the shell would do)
369 * note that tokenization ignores the internals of a quoted
370 * word and it always splits on spaces, not on IFS even
371 * if we used IFS. We also ignore "end of input indicator"
372 * (I guess this is control-D?)
374 * Tokenization steps, from UNIX98 with operator stuff removed,
377 * 1) "If the current character is backslash, single-quote or
378 * double-quote (\, ' or ") and it is not quoted, it will affect
379 * quoting for subsequent characters up to the end of the quoted
380 * text. The rules for quoting are as described in Quoting
381 * . During token recognition no substitutions will be actually
382 * performed, and the result token will contain exactly the
383 * characters that appear in the input (except for newline
384 * character joining), unmodified, including any embedded or
385 * enclosing quotes or substitution operators, between the quote
386 * mark and the end of the quoted text. The token will not be
387 * delimited by the end of the quoted field."
389 * 2) "If the current character is an unquoted newline character,
390 * the current token will be delimited."
392 * 3) "If the current character is an unquoted blank character, any
393 * token containing the previous character is delimited and the
394 * current character will be discarded."
396 * 4) "If the previous character was part of a word, the current
397 * character will be appended to that word."
399 * 5) "If the current character is a "#", it and all subsequent
400 * characters up to, but excluding, the next newline character
401 * will be discarded as a comment. The newline character that
402 * ends the line is not considered part of the comment. The
403 * "#" starts a comment only when it is at the beginning of a
404 * token. Since the search for the end-of-comment does not
405 * consider an escaped newline character specially, a comment
406 * cannot be continued to the next line."
408 * 6) "The current character will be used as the start of a new word."
411 * - for each token (word), perform portions of word expansion, namely
412 * field splitting (using default whitespace IFS) and quote
413 * removal. Field splitting may increase the number of words.
414 * Quote removal does not increase the number of words.
416 * "If the complete expansion appropriate for a word results in an
417 * empty field, that empty field will be deleted from the list of
418 * fields that form the completely expanded command, unless the
419 * original word contained single-quote or double-quote characters."
426 ensure_token (GString **token)
429 *token = g_string_new (NULL);
433 delimit_token (GString **token,
439 *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
445 tokenize_command_line (const gchar *command_line,
450 GString *current_token = NULL;
451 GSList *retval = NULL;
454 current_quote = '\0';
460 if (current_quote == '\\')
464 /* we append nothing; backslash-newline become nothing */
468 /* we append the backslash and the current char,
469 * to be interpreted later after tokenization
471 ensure_token (¤t_token);
472 g_string_append_c (current_token, '\\');
473 g_string_append_c (current_token, *p);
476 current_quote = '\0';
478 else if (current_quote == '#')
480 /* Discard up to and including next newline */
481 while (*p && *p != '\n')
484 current_quote = '\0';
489 else if (current_quote)
491 if (*p == current_quote &&
492 /* check that it isn't an escaped double quote */
493 !(current_quote == '"' && quoted))
495 /* close the quote */
496 current_quote = '\0';
499 /* Everything inside quotes, and the close quote,
500 * gets appended literally.
503 ensure_token (¤t_token);
504 g_string_append_c (current_token, *p);
511 delimit_token (¤t_token, &retval);
516 /* If the current token contains the previous char, delimit
517 * the current token. A nonzero length
518 * token should always contain the previous char.
521 current_token->len > 0)
523 delimit_token (¤t_token, &retval);
526 /* discard all unquoted blanks (don't add them to a token) */
530 /* single/double quotes are appended to the token,
531 * escapes are maybe appended next time through the loop,
532 * comment chars are never appended.
537 ensure_token (¤t_token);
538 g_string_append_c (current_token, *p);
546 if (p == command_line)
547 { /* '#' was the first char */
559 ensure_token (¤t_token);
560 g_string_append_c (current_token, *p);
566 /* Combines rules 4) and 6) - if we have a token, append to it,
567 * otherwise create a new token.
569 ensure_token (¤t_token);
570 g_string_append_c (current_token, *p);
575 /* We need to count consecutive backslashes mod 2,
576 * to detect escaped doublequotes.
586 delimit_token (¤t_token, &retval);
590 if (current_quote == '\\')
593 G_SHELL_ERROR_BAD_QUOTING,
594 _("Text ended just after a “\\” character."
595 " (The text was “%s”)"),
600 G_SHELL_ERROR_BAD_QUOTING,
601 _("Text ended before matching quote was found for %c."
602 " (The text was “%s”)"),
603 current_quote, command_line);
610 g_set_error_literal (error,
612 G_SHELL_ERROR_EMPTY_STRING,
613 _("Text was empty (or contained only whitespace)"));
618 /* we appended backward */
619 retval = g_slist_reverse (retval);
624 g_assert (error == NULL || *error != NULL);
626 g_slist_free_full (retval, g_free);
632 * g_shell_parse_argv:
633 * @command_line: (type filename): command line to parse
634 * @argcp: (out) (optional): return location for number of args
635 * @argvp: (out) (optional) (array length=argcp zero-terminated=1) (element-type filename):
636 * return location for array of args
637 * @error: (optional): return location for error
639 * Parses a command line into an argument vector, in much the same way
640 * the shell would, but without many of the expansions the shell would
641 * perform (variable expansion, globs, operators, filename expansion,
642 * etc. are not supported).
644 * The results are defined to be the same as those you would get from
645 * a UNIX98 `/bin/sh`, as long as the input contains none of the
646 * unsupported shell expansions. If the input does contain such expansions,
647 * they are passed through literally.
649 * Possible errors are those from the %G_SHELL_ERROR domain.
651 * In particular, if @command_line is an empty string (or a string containing
652 * only whitespace), %G_SHELL_ERROR_EMPTY_STRING will be returned. It’s
653 * guaranteed that @argvp will be a non-empty array if this function returns
656 * Free the returned vector with g_strfreev().
658 * Returns: %TRUE on success, %FALSE if error set
661 g_shell_parse_argv (const gchar *command_line,
666 /* Code based on poptParseArgvString() from libpopt */
669 GSList *tokens = NULL;
673 g_return_val_if_fail (command_line != NULL, FALSE);
675 tokens = tokenize_command_line (command_line, error);
679 /* Because we can't have introduced any new blank space into the
680 * tokens (we didn't do any new expansions), we don't need to
681 * perform field splitting. If we were going to honor IFS or do any
682 * expansions, we would have to do field splitting on each word
683 * here. Also, if we were going to do any expansion we would need to
684 * remove any zero-length words that didn't contain quotes
685 * originally; but since there's no expansion we know all words have
686 * nonzero length, unless they contain quotes.
688 * So, we simply remove quotes, and don't do any field splitting or
689 * empty word removal, since we know there was no way to introduce
693 argc = g_slist_length (tokens);
694 argv = g_new0 (gchar*, argc + 1);
699 argv[i] = g_shell_unquote (tmp_list->data, error);
701 /* Since we already checked that quotes matched up in the
702 * tokenizer, this shouldn't be possible to reach I guess.
707 tmp_list = g_slist_next (tmp_list);
711 g_slist_free_full (tokens, g_free);
714 g_assert (argv != NULL && argv[0] != NULL);
728 g_assert (error == NULL || *error != NULL);
730 g_slist_free_full (tokens, g_free);