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"
37 * @title: Shell-related Utilities
38 * @short_description: shell-like commandline handling
44 * Error domain for shell functions. Errors in this domain will be from
45 * the #GShellError enumeration. See #GError for information on error
51 * @G_SHELL_ERROR_BAD_QUOTING: Mismatched or otherwise mangled quoting.
52 * @G_SHELL_ERROR_EMPTY_STRING: String to be parsed was empty.
53 * @G_SHELL_ERROR_FAILED: Some other error.
55 * Error codes returned by shell functions.
57 G_DEFINE_QUARK ("g-shell-error-quark", g_shell_error)
59 /* Single quotes preserve the literal string exactly. escape
60 * sequences are not allowed; not even \' - if you want a '
61 * in the quoted text, you have to do something like 'foo'\''bar'
63 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
64 * Otherwise double quotes preserve things literally.
68 unquote_string_inplace (gchar* str, gchar** end, GError** err)
74 g_return_val_if_fail(end != NULL, FALSE);
75 g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
76 g_return_val_if_fail(str != NULL, FALSE);
82 if (!(*s == '"' || *s == '\''))
84 g_set_error_literal (err,
86 G_SHELL_ERROR_BAD_QUOTING,
87 _("Quoted text doesn't begin with a quotation mark"));
92 /* Skip the initial quote mark */
95 if (quote_char == '"')
99 g_assert(s > dest); /* loop invariant */
104 /* End of the string, return now */
112 /* Possible escaped quote or \ */
127 /* not an escaped char */
130 /* ++s already done. */
142 g_assert(s > dest); /* loop invariant */
149 g_assert(s > dest); /* loop invariant */
153 /* End of the string, return now */
166 g_assert(s > dest); /* loop invariant */
170 /* If we reach here this means the close quote was never encountered */
174 g_set_error_literal (err,
176 G_SHELL_ERROR_BAD_QUOTING,
177 _("Unmatched quotation mark in command line or other shell-quoted text"));
184 * @unquoted_string: a literal string
186 * Quotes a string so that the shell (/bin/sh) will interpret the
187 * quoted string to mean @unquoted_string. If you pass a filename to
188 * the shell, for example, you should first quote it with this
189 * function. The return value must be freed with g_free(). The
190 * quoting style used is undefined (single or double quotes may be
193 * Return value: quoted string
196 g_shell_quote (const gchar *unquoted_string)
198 /* We always use single quotes, because the algorithm is cheesier.
199 * We could use double if we felt like it, that might be more
206 g_return_val_if_fail (unquoted_string != NULL, NULL);
208 dest = g_string_new ("'");
212 /* could speed this up a lot by appending chunks of text at a
217 /* Replace literal ' with a close ', a \', and a open ' */
219 g_string_append (dest, "'\\''");
221 g_string_append_c (dest, *p);
226 /* close the quote */
227 g_string_append_c (dest, '\'');
229 return g_string_free (dest, FALSE);
234 * @quoted_string: shell-quoted string
235 * @error: error return location or NULL
237 * Unquotes a string as the shell (/bin/sh) would. Only handles
238 * quotes; if a string contains file globs, arithmetic operators,
239 * variables, backticks, redirections, or other special-to-the-shell
240 * features, the result will be different from the result a real shell
241 * would produce (the variables, backticks, etc. will be passed
242 * through literally instead of being expanded). This function is
243 * guaranteed to succeed if applied to the result of
244 * g_shell_quote(). If it fails, it returns %NULL and sets the
245 * error. The @quoted_string need not actually contain quoted or
246 * escaped text; g_shell_unquote() simply goes through the string and
247 * unquotes/unescapes anything that the shell would. Both single and
248 * double quotes are handled, as are escapes including escaped
249 * newlines. The return value must be freed with g_free(). Possible
250 * errors are in the #G_SHELL_ERROR domain.
252 * Shell quoting rules are a bit strange. Single quotes preserve the
253 * literal string exactly. escape sequences are not allowed; not even
254 * \' - if you want a ' in the quoted text, you have to do something
255 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
256 * be escaped with backslash. Otherwise double quotes preserve things
259 * Return value: an unquoted string
262 g_shell_unquote (const gchar *quoted_string,
270 g_return_val_if_fail (quoted_string != NULL, NULL);
272 unquoted = g_strdup (quoted_string);
276 retval = g_string_new (NULL);
278 /* The loop allows cases such as
279 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
283 /* Append all non-quoted chars, honoring backslash escape
286 while (*start && !(*start == '"' || *start == '\''))
290 /* all characters can get escaped by backslash,
291 * except newline, which is removed if it follows
292 * a backslash outside of quotes
299 g_string_append_c (retval, *start);
305 g_string_append_c (retval, *start);
312 if (!unquote_string_inplace (start, &end, error))
318 g_string_append (retval, start);
325 return g_string_free (retval, FALSE);
328 g_assert (error == NULL || *error != NULL);
331 g_string_free (retval, TRUE);
335 /* g_parse_argv() does a semi-arbitrary weird subset of the way
336 * the shell parses a command line. We don't do variable expansion,
337 * don't understand that operators are tokens, don't do tilde expansion,
338 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
339 * don't do filename globs, don't remove redirection stuff, etc.
341 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
342 * the behavior of this code.
344 * Steps to parsing the argv string:
346 * - tokenize the string (but since we ignore operators,
347 * our tokenization may diverge from what the shell would do)
348 * note that tokenization ignores the internals of a quoted
349 * word and it always splits on spaces, not on IFS even
350 * if we used IFS. We also ignore "end of input indicator"
351 * (I guess this is control-D?)
353 * Tokenization steps, from UNIX98 with operator stuff removed,
356 * 1) "If the current character is backslash, single-quote or
357 * double-quote (\, ' or ") and it is not quoted, it will affect
358 * quoting for subsequent characters up to the end of the quoted
359 * text. The rules for quoting are as described in Quoting
360 * . During token recognition no substitutions will be actually
361 * performed, and the result token will contain exactly the
362 * characters that appear in the input (except for newline
363 * character joining), unmodified, including any embedded or
364 * enclosing quotes or substitution operators, between the quote
365 * mark and the end of the quoted text. The token will not be
366 * delimited by the end of the quoted field."
368 * 2) "If the current character is an unquoted newline character,
369 * the current token will be delimited."
371 * 3) "If the current character is an unquoted blank character, any
372 * token containing the previous character is delimited and the
373 * current character will be discarded."
375 * 4) "If the previous character was part of a word, the current
376 * character will be appended to that word."
378 * 5) "If the current character is a "#", it and all subsequent
379 * characters up to, but excluding, the next newline character
380 * will be discarded as a comment. The newline character that
381 * ends the line is not considered part of the comment. The
382 * "#" starts a comment only when it is at the beginning of a
383 * token. Since the search for the end-of-comment does not
384 * consider an escaped newline character specially, a comment
385 * cannot be continued to the next line."
387 * 6) "The current character will be used as the start of a new word."
390 * - for each token (word), perform portions of word expansion, namely
391 * field splitting (using default whitespace IFS) and quote
392 * removal. Field splitting may increase the number of words.
393 * Quote removal does not increase the number of words.
395 * "If the complete expansion appropriate for a word results in an
396 * empty field, that empty field will be deleted from the list of
397 * fields that form the completely expanded command, unless the
398 * original word contained single-quote or double-quote characters."
405 ensure_token (GString **token)
408 *token = g_string_new (NULL);
412 delimit_token (GString **token,
418 *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
424 tokenize_command_line (const gchar *command_line,
429 GString *current_token = NULL;
430 GSList *retval = NULL;
433 current_quote = '\0';
439 if (current_quote == '\\')
443 /* we append nothing; backslash-newline become nothing */
447 /* we append the backslash and the current char,
448 * to be interpreted later after tokenization
450 ensure_token (¤t_token);
451 g_string_append_c (current_token, '\\');
452 g_string_append_c (current_token, *p);
455 current_quote = '\0';
457 else if (current_quote == '#')
459 /* Discard up to and including next newline */
460 while (*p && *p != '\n')
463 current_quote = '\0';
468 else if (current_quote)
470 if (*p == current_quote &&
471 /* check that it isn't an escaped double quote */
472 !(current_quote == '"' && quoted))
474 /* close the quote */
475 current_quote = '\0';
478 /* Everything inside quotes, and the close quote,
479 * gets appended literally.
482 ensure_token (¤t_token);
483 g_string_append_c (current_token, *p);
490 delimit_token (¤t_token, &retval);
495 /* If the current token contains the previous char, delimit
496 * the current token. A nonzero length
497 * token should always contain the previous char.
500 current_token->len > 0)
502 delimit_token (¤t_token, &retval);
505 /* discard all unquoted blanks (don't add them to a token) */
509 /* single/double quotes are appended to the token,
510 * escapes are maybe appended next time through the loop,
511 * comment chars are never appended.
516 ensure_token (¤t_token);
517 g_string_append_c (current_token, *p);
527 /* Combines rules 4) and 6) - if we have a token, append to it,
528 * otherwise create a new token.
530 ensure_token (¤t_token);
531 g_string_append_c (current_token, *p);
536 /* We need to count consecutive backslashes mod 2,
537 * to detect escaped doublequotes.
547 delimit_token (¤t_token, &retval);
551 if (current_quote == '\\')
554 G_SHELL_ERROR_BAD_QUOTING,
555 _("Text ended just after a '\\' character."
556 " (The text was '%s')"),
561 G_SHELL_ERROR_BAD_QUOTING,
562 _("Text ended before matching quote was found for %c."
563 " (The text was '%s')"),
564 current_quote, command_line);
571 g_set_error_literal (error,
573 G_SHELL_ERROR_EMPTY_STRING,
574 _("Text was empty (or contained only whitespace)"));
579 /* we appended backward */
580 retval = g_slist_reverse (retval);
585 g_assert (error == NULL || *error != NULL);
587 g_slist_free_full (retval, g_free);
593 * g_shell_parse_argv:
594 * @command_line: command line to parse
595 * @argcp: (out): return location for number of args
596 * @argvp: (out) (array length=argcp zero-terminated=1): return location for array of args
597 * @error: return location for error
599 * Parses a command line into an argument vector, in much the same way
600 * the shell would, but without many of the expansions the shell would
601 * perform (variable expansion, globs, operators, filename expansion,
602 * etc. are not supported). The results are defined to be the same as
603 * those you would get from a UNIX98 /bin/sh, as long as the input
604 * contains none of the unsupported shell expansions. If the input
605 * does contain such expansions, they are passed through
606 * literally. Possible errors are those from the #G_SHELL_ERROR
607 * domain. Free the returned vector with g_strfreev().
609 * Return value: %TRUE on success, %FALSE if error set
612 g_shell_parse_argv (const gchar *command_line,
617 /* Code based on poptParseArgvString() from libpopt */
620 GSList *tokens = NULL;
624 g_return_val_if_fail (command_line != NULL, FALSE);
626 tokens = tokenize_command_line (command_line, error);
630 /* Because we can't have introduced any new blank space into the
631 * tokens (we didn't do any new expansions), we don't need to
632 * perform field splitting. If we were going to honor IFS or do any
633 * expansions, we would have to do field splitting on each word
634 * here. Also, if we were going to do any expansion we would need to
635 * remove any zero-length words that didn't contain quotes
636 * originally; but since there's no expansion we know all words have
637 * nonzero length, unless they contain quotes.
639 * So, we simply remove quotes, and don't do any field splitting or
640 * empty word removal, since we know there was no way to introduce
644 argc = g_slist_length (tokens);
645 argv = g_new0 (gchar*, argc + 1);
650 argv[i] = g_shell_unquote (tmp_list->data, error);
652 /* Since we already checked that quotes matched up in the
653 * tokenizer, this shouldn't be possible to reach I guess.
658 tmp_list = g_slist_next (tmp_list);
662 g_slist_free_full (tokens, g_free);
676 g_assert (error == NULL || *error != NULL);
678 g_slist_free_full (tokens, g_free);