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
45 * Error domain for shell functions. Errors in this domain will be from
46 * the #GShellError enumeration. See #GError for information on error
52 * @G_SHELL_ERROR_BAD_QUOTING: Mismatched or otherwise mangled quoting.
53 * @G_SHELL_ERROR_EMPTY_STRING: String to be parsed was empty.
54 * @G_SHELL_ERROR_FAILED: Some other error.
56 * Error codes returned by shell functions.
58 G_DEFINE_QUARK ("g-shell-error-quark", g_shell_error)
60 /* Single quotes preserve the literal string exactly. escape
61 * sequences are not allowed; not even \' - if you want a '
62 * in the quoted text, you have to do something like 'foo'\''bar'
64 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
65 * Otherwise double quotes preserve things literally.
69 unquote_string_inplace (gchar* str, gchar** end, GError** err)
75 g_return_val_if_fail(end != NULL, FALSE);
76 g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
77 g_return_val_if_fail(str != NULL, FALSE);
83 if (!(*s == '"' || *s == '\''))
85 g_set_error_literal (err,
87 G_SHELL_ERROR_BAD_QUOTING,
88 _("Quoted text doesn't begin with a quotation mark"));
93 /* Skip the initial quote mark */
96 if (quote_char == '"')
100 g_assert(s > dest); /* loop invariant */
105 /* End of the string, return now */
113 /* Possible escaped quote or \ */
128 /* not an escaped char */
131 /* ++s already done. */
143 g_assert(s > dest); /* loop invariant */
150 g_assert(s > dest); /* loop invariant */
154 /* End of the string, return now */
167 g_assert(s > dest); /* loop invariant */
171 /* If we reach here this means the close quote was never encountered */
175 g_set_error_literal (err,
177 G_SHELL_ERROR_BAD_QUOTING,
178 _("Unmatched quotation mark in command line or other shell-quoted text"));
185 * @unquoted_string: a literal string
187 * Quotes a string so that the shell (/bin/sh) will interpret the
188 * quoted string to mean @unquoted_string. If you pass a filename to
189 * the shell, for example, you should first quote it with this
190 * function. The return value must be freed with g_free(). The
191 * quoting style used is undefined (single or double quotes may be
194 * Return value: quoted string
197 g_shell_quote (const gchar *unquoted_string)
199 /* We always use single quotes, because the algorithm is cheesier.
200 * We could use double if we felt like it, that might be more
207 g_return_val_if_fail (unquoted_string != NULL, NULL);
209 dest = g_string_new ("'");
213 /* could speed this up a lot by appending chunks of text at a
218 /* Replace literal ' with a close ', a \', and a open ' */
220 g_string_append (dest, "'\\''");
222 g_string_append_c (dest, *p);
227 /* close the quote */
228 g_string_append_c (dest, '\'');
230 return g_string_free (dest, FALSE);
235 * @quoted_string: shell-quoted string
236 * @error: error return location or NULL
238 * Unquotes a string as the shell (/bin/sh) would. Only handles
239 * quotes; if a string contains file globs, arithmetic operators,
240 * variables, backticks, redirections, or other special-to-the-shell
241 * features, the result will be different from the result a real shell
242 * would produce (the variables, backticks, etc. will be passed
243 * through literally instead of being expanded). This function is
244 * guaranteed to succeed if applied to the result of
245 * g_shell_quote(). If it fails, it returns %NULL and sets the
246 * error. The @quoted_string need not actually contain quoted or
247 * escaped text; g_shell_unquote() simply goes through the string and
248 * unquotes/unescapes anything that the shell would. Both single and
249 * double quotes are handled, as are escapes including escaped
250 * newlines. The return value must be freed with g_free(). Possible
251 * errors are in the #G_SHELL_ERROR domain.
253 * Shell quoting rules are a bit strange. Single quotes preserve the
254 * literal string exactly. escape sequences are not allowed; not even
255 * \' - if you want a ' in the quoted text, you have to do something
256 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
257 * be escaped with backslash. Otherwise double quotes preserve things
260 * Return value: an unquoted string
263 g_shell_unquote (const gchar *quoted_string,
271 g_return_val_if_fail (quoted_string != NULL, NULL);
273 unquoted = g_strdup (quoted_string);
277 retval = g_string_new (NULL);
279 /* The loop allows cases such as
280 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
284 /* Append all non-quoted chars, honoring backslash escape
287 while (*start && !(*start == '"' || *start == '\''))
291 /* all characters can get escaped by backslash,
292 * except newline, which is removed if it follows
293 * a backslash outside of quotes
300 g_string_append_c (retval, *start);
306 g_string_append_c (retval, *start);
313 if (!unquote_string_inplace (start, &end, error))
319 g_string_append (retval, start);
326 return g_string_free (retval, FALSE);
329 g_assert (error == NULL || *error != NULL);
332 g_string_free (retval, TRUE);
336 /* g_parse_argv() does a semi-arbitrary weird subset of the way
337 * the shell parses a command line. We don't do variable expansion,
338 * don't understand that operators are tokens, don't do tilde expansion,
339 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
340 * don't do filename globs, don't remove redirection stuff, etc.
342 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
343 * the behavior of this code.
345 * Steps to parsing the argv string:
347 * - tokenize the string (but since we ignore operators,
348 * our tokenization may diverge from what the shell would do)
349 * note that tokenization ignores the internals of a quoted
350 * word and it always splits on spaces, not on IFS even
351 * if we used IFS. We also ignore "end of input indicator"
352 * (I guess this is control-D?)
354 * Tokenization steps, from UNIX98 with operator stuff removed,
357 * 1) "If the current character is backslash, single-quote or
358 * double-quote (\, ' or ") and it is not quoted, it will affect
359 * quoting for subsequent characters up to the end of the quoted
360 * text. The rules for quoting are as described in Quoting
361 * . During token recognition no substitutions will be actually
362 * performed, and the result token will contain exactly the
363 * characters that appear in the input (except for newline
364 * character joining), unmodified, including any embedded or
365 * enclosing quotes or substitution operators, between the quote
366 * mark and the end of the quoted text. The token will not be
367 * delimited by the end of the quoted field."
369 * 2) "If the current character is an unquoted newline character,
370 * the current token will be delimited."
372 * 3) "If the current character is an unquoted blank character, any
373 * token containing the previous character is delimited and the
374 * current character will be discarded."
376 * 4) "If the previous character was part of a word, the current
377 * character will be appended to that word."
379 * 5) "If the current character is a "#", it and all subsequent
380 * characters up to, but excluding, the next newline character
381 * will be discarded as a comment. The newline character that
382 * ends the line is not considered part of the comment. The
383 * "#" starts a comment only when it is at the beginning of a
384 * token. Since the search for the end-of-comment does not
385 * consider an escaped newline character specially, a comment
386 * cannot be continued to the next line."
388 * 6) "The current character will be used as the start of a new word."
391 * - for each token (word), perform portions of word expansion, namely
392 * field splitting (using default whitespace IFS) and quote
393 * removal. Field splitting may increase the number of words.
394 * Quote removal does not increase the number of words.
396 * "If the complete expansion appropriate for a word results in an
397 * empty field, that empty field will be deleted from the list of
398 * fields that form the completely expanded command, unless the
399 * original word contained single-quote or double-quote characters."
406 ensure_token (GString **token)
409 *token = g_string_new (NULL);
413 delimit_token (GString **token,
419 *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
425 tokenize_command_line (const gchar *command_line,
430 GString *current_token = NULL;
431 GSList *retval = NULL;
434 current_quote = '\0';
440 if (current_quote == '\\')
444 /* we append nothing; backslash-newline become nothing */
448 /* we append the backslash and the current char,
449 * to be interpreted later after tokenization
451 ensure_token (¤t_token);
452 g_string_append_c (current_token, '\\');
453 g_string_append_c (current_token, *p);
456 current_quote = '\0';
458 else if (current_quote == '#')
460 /* Discard up to and including next newline */
461 while (*p && *p != '\n')
464 current_quote = '\0';
469 else if (current_quote)
471 if (*p == current_quote &&
472 /* check that it isn't an escaped double quote */
473 !(current_quote == '"' && quoted))
475 /* close the quote */
476 current_quote = '\0';
479 /* Everything inside quotes, and the close quote,
480 * gets appended literally.
483 ensure_token (¤t_token);
484 g_string_append_c (current_token, *p);
491 delimit_token (¤t_token, &retval);
496 /* If the current token contains the previous char, delimit
497 * the current token. A nonzero length
498 * token should always contain the previous char.
501 current_token->len > 0)
503 delimit_token (¤t_token, &retval);
506 /* discard all unquoted blanks (don't add them to a token) */
510 /* single/double quotes are appended to the token,
511 * escapes are maybe appended next time through the loop,
512 * comment chars are never appended.
517 ensure_token (¤t_token);
518 g_string_append_c (current_token, *p);
528 /* Combines rules 4) and 6) - if we have a token, append to it,
529 * otherwise create a new token.
531 ensure_token (¤t_token);
532 g_string_append_c (current_token, *p);
537 /* We need to count consecutive backslashes mod 2,
538 * to detect escaped doublequotes.
548 delimit_token (¤t_token, &retval);
552 if (current_quote == '\\')
555 G_SHELL_ERROR_BAD_QUOTING,
556 _("Text ended just after a '\\' character."
557 " (The text was '%s')"),
562 G_SHELL_ERROR_BAD_QUOTING,
563 _("Text ended before matching quote was found for %c."
564 " (The text was '%s')"),
565 current_quote, command_line);
572 g_set_error_literal (error,
574 G_SHELL_ERROR_EMPTY_STRING,
575 _("Text was empty (or contained only whitespace)"));
580 /* we appended backward */
581 retval = g_slist_reverse (retval);
586 g_assert (error == NULL || *error != NULL);
588 g_slist_free_full (retval, g_free);
594 * g_shell_parse_argv:
595 * @command_line: command line to parse
596 * @argcp: (out): return location for number of args
597 * @argvp: (out) (array length=argcp zero-terminated=1): return location for array of args
598 * @error: return location for error
600 * Parses a command line into an argument vector, in much the same way
601 * the shell would, but without many of the expansions the shell would
602 * perform (variable expansion, globs, operators, filename expansion,
603 * etc. are not supported). The results are defined to be the same as
604 * those you would get from a UNIX98 /bin/sh, as long as the input
605 * contains none of the unsupported shell expansions. If the input
606 * does contain such expansions, they are passed through
607 * literally. Possible errors are those from the #G_SHELL_ERROR
608 * domain. Free the returned vector with g_strfreev().
610 * Return value: %TRUE on success, %FALSE if error set
613 g_shell_parse_argv (const gchar *command_line,
618 /* Code based on poptParseArgvString() from libpopt */
621 GSList *tokens = NULL;
625 g_return_val_if_fail (command_line != NULL, FALSE);
627 tokens = tokenize_command_line (command_line, error);
631 /* Because we can't have introduced any new blank space into the
632 * tokens (we didn't do any new expansions), we don't need to
633 * perform field splitting. If we were going to honor IFS or do any
634 * expansions, we would have to do field splitting on each word
635 * here. Also, if we were going to do any expansion we would need to
636 * remove any zero-length words that didn't contain quotes
637 * originally; but since there's no expansion we know all words have
638 * nonzero length, unless they contain quotes.
640 * So, we simply remove quotes, and don't do any field splitting or
641 * empty word removal, since we know there was no way to introduce
645 argc = g_slist_length (tokens);
646 argv = g_new0 (gchar*, argc + 1);
651 argv[i] = g_shell_unquote (tmp_list->data, error);
653 /* Since we already checked that quotes matched up in the
654 * tokenizer, this shouldn't be possible to reach I guess.
659 tmp_list = g_slist_next (tmp_list);
663 g_slist_free_full (tokens, g_free);
677 g_assert (error == NULL || *error != NULL);
679 g_slist_free_full (tokens, g_free);