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 * GLib is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2 of the
10 * License, or (at your option) any later version.
12 * GLib is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with GLib; see the file COPYING.LIB. If not, write
19 * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
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. Errors in this domain will be from
54 * the #GShellError enumeration. See #GError for information on error
60 * @G_SHELL_ERROR_BAD_QUOTING: Mismatched or otherwise mangled quoting.
61 * @G_SHELL_ERROR_EMPTY_STRING: String to be parsed was empty.
62 * @G_SHELL_ERROR_FAILED: Some other error.
64 * Error codes returned by shell functions.
66 G_DEFINE_QUARK (g-shell-error-quark, g_shell_error)
68 /* Single quotes preserve the literal string exactly. escape
69 * sequences are not allowed; not even \' - if you want a '
70 * in the quoted text, you have to do something like 'foo'\''bar'
72 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
73 * Otherwise double quotes preserve things literally.
77 unquote_string_inplace (gchar* str, gchar** end, GError** err)
83 g_return_val_if_fail(end != NULL, FALSE);
84 g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
85 g_return_val_if_fail(str != NULL, FALSE);
91 if (!(*s == '"' || *s == '\''))
93 g_set_error_literal (err,
95 G_SHELL_ERROR_BAD_QUOTING,
96 _("Quoted text doesn't begin with a quotation mark"));
101 /* Skip the initial quote mark */
104 if (quote_char == '"')
108 g_assert(s > dest); /* loop invariant */
113 /* End of the string, return now */
121 /* Possible escaped quote or \ */
136 /* not an escaped char */
139 /* ++s already done. */
151 g_assert(s > dest); /* loop invariant */
158 g_assert(s > dest); /* loop invariant */
162 /* End of the string, return now */
175 g_assert(s > dest); /* loop invariant */
179 /* If we reach here this means the close quote was never encountered */
183 g_set_error_literal (err,
185 G_SHELL_ERROR_BAD_QUOTING,
186 _("Unmatched quotation mark in command line or other shell-quoted text"));
193 * @unquoted_string: a literal string
195 * Quotes a string so that the shell (/bin/sh) will interpret the
196 * quoted string to mean @unquoted_string. If you pass a filename to
197 * the shell, for example, you should first quote it with this
198 * function. The return value must be freed with g_free(). The
199 * quoting style used is undefined (single or double quotes may be
202 * Returns: quoted string
205 g_shell_quote (const gchar *unquoted_string)
207 /* We always use single quotes, because the algorithm is cheesier.
208 * We could use double if we felt like it, that might be more
215 g_return_val_if_fail (unquoted_string != NULL, NULL);
217 dest = g_string_new ("'");
221 /* could speed this up a lot by appending chunks of text at a
226 /* Replace literal ' with a close ', a \', and a open ' */
228 g_string_append (dest, "'\\''");
230 g_string_append_c (dest, *p);
235 /* close the quote */
236 g_string_append_c (dest, '\'');
238 return g_string_free (dest, FALSE);
243 * @quoted_string: shell-quoted string
244 * @error: error return location or NULL
246 * Unquotes a string as the shell (/bin/sh) would. Only handles
247 * quotes; if a string contains file globs, arithmetic operators,
248 * variables, backticks, redirections, or other special-to-the-shell
249 * features, the result will be different from the result a real shell
250 * would produce (the variables, backticks, etc. will be passed
251 * through literally instead of being expanded). This function is
252 * guaranteed to succeed if applied to the result of
253 * g_shell_quote(). If it fails, it returns %NULL and sets the
254 * error. The @quoted_string need not actually contain quoted or
255 * escaped text; g_shell_unquote() simply goes through the string and
256 * unquotes/unescapes anything that the shell would. Both single and
257 * double quotes are handled, as are escapes including escaped
258 * newlines. The return value must be freed with g_free(). Possible
259 * errors are in the #G_SHELL_ERROR domain.
261 * Shell quoting rules are a bit strange. Single quotes preserve the
262 * literal string exactly. escape sequences are not allowed; not even
263 * \' - if you want a ' in the quoted text, you have to do something
264 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
265 * be escaped with backslash. Otherwise double quotes preserve things
268 * Returns: an unquoted string
271 g_shell_unquote (const gchar *quoted_string,
279 g_return_val_if_fail (quoted_string != NULL, NULL);
281 unquoted = g_strdup (quoted_string);
285 retval = g_string_new (NULL);
287 /* The loop allows cases such as
288 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
292 /* Append all non-quoted chars, honoring backslash escape
295 while (*start && !(*start == '"' || *start == '\''))
299 /* all characters can get escaped by backslash,
300 * except newline, which is removed if it follows
301 * a backslash outside of quotes
308 g_string_append_c (retval, *start);
314 g_string_append_c (retval, *start);
321 if (!unquote_string_inplace (start, &end, error))
327 g_string_append (retval, start);
334 return g_string_free (retval, FALSE);
337 g_assert (error == NULL || *error != NULL);
340 g_string_free (retval, TRUE);
344 /* g_parse_argv() does a semi-arbitrary weird subset of the way
345 * the shell parses a command line. We don't do variable expansion,
346 * don't understand that operators are tokens, don't do tilde expansion,
347 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
348 * don't do filename globs, don't remove redirection stuff, etc.
350 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
351 * the behavior of this code.
353 * Steps to parsing the argv string:
355 * - tokenize the string (but since we ignore operators,
356 * our tokenization may diverge from what the shell would do)
357 * note that tokenization ignores the internals of a quoted
358 * word and it always splits on spaces, not on IFS even
359 * if we used IFS. We also ignore "end of input indicator"
360 * (I guess this is control-D?)
362 * Tokenization steps, from UNIX98 with operator stuff removed,
365 * 1) "If the current character is backslash, single-quote or
366 * double-quote (\, ' or ") and it is not quoted, it will affect
367 * quoting for subsequent characters up to the end of the quoted
368 * text. The rules for quoting are as described in Quoting
369 * . During token recognition no substitutions will be actually
370 * performed, and the result token will contain exactly the
371 * characters that appear in the input (except for newline
372 * character joining), unmodified, including any embedded or
373 * enclosing quotes or substitution operators, between the quote
374 * mark and the end of the quoted text. The token will not be
375 * delimited by the end of the quoted field."
377 * 2) "If the current character is an unquoted newline character,
378 * the current token will be delimited."
380 * 3) "If the current character is an unquoted blank character, any
381 * token containing the previous character is delimited and the
382 * current character will be discarded."
384 * 4) "If the previous character was part of a word, the current
385 * character will be appended to that word."
387 * 5) "If the current character is a "#", it and all subsequent
388 * characters up to, but excluding, the next newline character
389 * will be discarded as a comment. The newline character that
390 * ends the line is not considered part of the comment. The
391 * "#" starts a comment only when it is at the beginning of a
392 * token. Since the search for the end-of-comment does not
393 * consider an escaped newline character specially, a comment
394 * cannot be continued to the next line."
396 * 6) "The current character will be used as the start of a new word."
399 * - for each token (word), perform portions of word expansion, namely
400 * field splitting (using default whitespace IFS) and quote
401 * removal. Field splitting may increase the number of words.
402 * Quote removal does not increase the number of words.
404 * "If the complete expansion appropriate for a word results in an
405 * empty field, that empty field will be deleted from the list of
406 * fields that form the completely expanded command, unless the
407 * original word contained single-quote or double-quote characters."
414 ensure_token (GString **token)
417 *token = g_string_new (NULL);
421 delimit_token (GString **token,
427 *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
433 tokenize_command_line (const gchar *command_line,
438 GString *current_token = NULL;
439 GSList *retval = NULL;
442 current_quote = '\0';
448 if (current_quote == '\\')
452 /* we append nothing; backslash-newline become nothing */
456 /* we append the backslash and the current char,
457 * to be interpreted later after tokenization
459 ensure_token (¤t_token);
460 g_string_append_c (current_token, '\\');
461 g_string_append_c (current_token, *p);
464 current_quote = '\0';
466 else if (current_quote == '#')
468 /* Discard up to and including next newline */
469 while (*p && *p != '\n')
472 current_quote = '\0';
477 else if (current_quote)
479 if (*p == current_quote &&
480 /* check that it isn't an escaped double quote */
481 !(current_quote == '"' && quoted))
483 /* close the quote */
484 current_quote = '\0';
487 /* Everything inside quotes, and the close quote,
488 * gets appended literally.
491 ensure_token (¤t_token);
492 g_string_append_c (current_token, *p);
499 delimit_token (¤t_token, &retval);
504 /* If the current token contains the previous char, delimit
505 * the current token. A nonzero length
506 * token should always contain the previous char.
509 current_token->len > 0)
511 delimit_token (¤t_token, &retval);
514 /* discard all unquoted blanks (don't add them to a token) */
518 /* single/double quotes are appended to the token,
519 * escapes are maybe appended next time through the loop,
520 * comment chars are never appended.
525 ensure_token (¤t_token);
526 g_string_append_c (current_token, *p);
534 if (p == command_line)
535 { /* '#' was the first char */
547 ensure_token (¤t_token);
548 g_string_append_c (current_token, *p);
554 /* Combines rules 4) and 6) - if we have a token, append to it,
555 * otherwise create a new token.
557 ensure_token (¤t_token);
558 g_string_append_c (current_token, *p);
563 /* We need to count consecutive backslashes mod 2,
564 * to detect escaped doublequotes.
574 delimit_token (¤t_token, &retval);
578 if (current_quote == '\\')
581 G_SHELL_ERROR_BAD_QUOTING,
582 _("Text ended just after a '\\' character."
583 " (The text was '%s')"),
588 G_SHELL_ERROR_BAD_QUOTING,
589 _("Text ended before matching quote was found for %c."
590 " (The text was '%s')"),
591 current_quote, command_line);
598 g_set_error_literal (error,
600 G_SHELL_ERROR_EMPTY_STRING,
601 _("Text was empty (or contained only whitespace)"));
606 /* we appended backward */
607 retval = g_slist_reverse (retval);
612 g_assert (error == NULL || *error != NULL);
614 g_slist_free_full (retval, g_free);
620 * g_shell_parse_argv:
621 * @command_line: command line to parse
622 * @argcp: (out) (optional): return location for number of args, or %NULL
623 * @argvp: (out) (optional) (array length=argcp zero-terminated=1): return
624 * location for array of args, or %NULL
625 * @error: (optional): return location for error, or %NULL
627 * Parses a command line into an argument vector, in much the same way
628 * the shell would, but without many of the expansions the shell would
629 * perform (variable expansion, globs, operators, filename expansion,
630 * etc. are not supported). The results are defined to be the same as
631 * those you would get from a UNIX98 /bin/sh, as long as the input
632 * contains none of the unsupported shell expansions. If the input
633 * does contain such expansions, they are passed through
634 * literally. Possible errors are those from the #G_SHELL_ERROR
635 * domain. Free the returned vector with g_strfreev().
637 * Returns: %TRUE on success, %FALSE if error set
640 g_shell_parse_argv (const gchar *command_line,
645 /* Code based on poptParseArgvString() from libpopt */
648 GSList *tokens = NULL;
652 g_return_val_if_fail (command_line != NULL, FALSE);
654 tokens = tokenize_command_line (command_line, error);
658 /* Because we can't have introduced any new blank space into the
659 * tokens (we didn't do any new expansions), we don't need to
660 * perform field splitting. If we were going to honor IFS or do any
661 * expansions, we would have to do field splitting on each word
662 * here. Also, if we were going to do any expansion we would need to
663 * remove any zero-length words that didn't contain quotes
664 * originally; but since there's no expansion we know all words have
665 * nonzero length, unless they contain quotes.
667 * So, we simply remove quotes, and don't do any field splitting or
668 * empty word removal, since we know there was no way to introduce
672 argc = g_slist_length (tokens);
673 argv = g_new0 (gchar*, argc + 1);
678 argv[i] = g_shell_unquote (tmp_list->data, error);
680 /* Since we already checked that quotes matched up in the
681 * tokenizer, this shouldn't be possible to reach I guess.
686 tmp_list = g_slist_next (tmp_list);
690 g_slist_free_full (tokens, g_free);
704 g_assert (error == NULL || *error != NULL);
706 g_slist_free_full (tokens, g_free);