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.
58 g_shell_error_quark (void)
60 return g_quark_from_static_string ("g-shell-error-quark");
63 /* Single quotes preserve the literal string exactly. escape
64 * sequences are not allowed; not even \' - if you want a '
65 * in the quoted text, you have to do something like 'foo'\''bar'
67 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
68 * Otherwise double quotes preserve things literally.
72 unquote_string_inplace (gchar* str, gchar** end, GError** err)
78 g_return_val_if_fail(end != NULL, FALSE);
79 g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
80 g_return_val_if_fail(str != NULL, FALSE);
86 if (!(*s == '"' || *s == '\''))
88 g_set_error_literal (err,
90 G_SHELL_ERROR_BAD_QUOTING,
91 _("Quoted text doesn't begin with a quotation mark"));
96 /* Skip the initial quote mark */
99 if (quote_char == '"')
103 g_assert(s > dest); /* loop invariant */
108 /* End of the string, return now */
116 /* Possible escaped quote or \ */
131 /* not an escaped char */
134 /* ++s already done. */
146 g_assert(s > dest); /* loop invariant */
153 g_assert(s > dest); /* loop invariant */
157 /* End of the string, return now */
170 g_assert(s > dest); /* loop invariant */
174 /* If we reach here this means the close quote was never encountered */
178 g_set_error_literal (err,
180 G_SHELL_ERROR_BAD_QUOTING,
181 _("Unmatched quotation mark in command line or other shell-quoted text"));
188 * @unquoted_string: a literal string
190 * Quotes a string so that the shell (/bin/sh) will interpret the
191 * quoted string to mean @unquoted_string. If you pass a filename to
192 * the shell, for example, you should first quote it with this
193 * function. The return value must be freed with g_free(). The
194 * quoting style used is undefined (single or double quotes may be
197 * Return value: quoted string
200 g_shell_quote (const gchar *unquoted_string)
202 /* We always use single quotes, because the algorithm is cheesier.
203 * We could use double if we felt like it, that might be more
210 g_return_val_if_fail (unquoted_string != NULL, NULL);
212 dest = g_string_new ("'");
216 /* could speed this up a lot by appending chunks of text at a
221 /* Replace literal ' with a close ', a \', and a open ' */
223 g_string_append (dest, "'\\''");
225 g_string_append_c (dest, *p);
230 /* close the quote */
231 g_string_append_c (dest, '\'');
233 return g_string_free (dest, FALSE);
238 * @quoted_string: shell-quoted string
239 * @error: error return location or NULL
241 * Unquotes a string as the shell (/bin/sh) would. Only handles
242 * quotes; if a string contains file globs, arithmetic operators,
243 * variables, backticks, redirections, or other special-to-the-shell
244 * features, the result will be different from the result a real shell
245 * would produce (the variables, backticks, etc. will be passed
246 * through literally instead of being expanded). This function is
247 * guaranteed to succeed if applied to the result of
248 * g_shell_quote(). If it fails, it returns %NULL and sets the
249 * error. The @quoted_string need not actually contain quoted or
250 * escaped text; g_shell_unquote() simply goes through the string and
251 * unquotes/unescapes anything that the shell would. Both single and
252 * double quotes are handled, as are escapes including escaped
253 * newlines. The return value must be freed with g_free(). Possible
254 * errors are in the #G_SHELL_ERROR domain.
256 * Shell quoting rules are a bit strange. Single quotes preserve the
257 * literal string exactly. escape sequences are not allowed; not even
258 * \' - if you want a ' in the quoted text, you have to do something
259 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
260 * be escaped with backslash. Otherwise double quotes preserve things
263 * Return value: an unquoted string
266 g_shell_unquote (const gchar *quoted_string,
274 g_return_val_if_fail (quoted_string != NULL, NULL);
276 unquoted = g_strdup (quoted_string);
280 retval = g_string_new (NULL);
282 /* The loop allows cases such as
283 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
287 /* Append all non-quoted chars, honoring backslash escape
290 while (*start && !(*start == '"' || *start == '\''))
294 /* all characters can get escaped by backslash,
295 * except newline, which is removed if it follows
296 * a backslash outside of quotes
303 g_string_append_c (retval, *start);
309 g_string_append_c (retval, *start);
316 if (!unquote_string_inplace (start, &end, error))
322 g_string_append (retval, start);
329 return g_string_free (retval, FALSE);
332 g_assert (error == NULL || *error != NULL);
335 g_string_free (retval, TRUE);
339 /* g_parse_argv() does a semi-arbitrary weird subset of the way
340 * the shell parses a command line. We don't do variable expansion,
341 * don't understand that operators are tokens, don't do tilde expansion,
342 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
343 * don't do filename globs, don't remove redirection stuff, etc.
345 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
346 * the behavior of this code.
348 * Steps to parsing the argv string:
350 * - tokenize the string (but since we ignore operators,
351 * our tokenization may diverge from what the shell would do)
352 * note that tokenization ignores the internals of a quoted
353 * word and it always splits on spaces, not on IFS even
354 * if we used IFS. We also ignore "end of input indicator"
355 * (I guess this is control-D?)
357 * Tokenization steps, from UNIX98 with operator stuff removed,
360 * 1) "If the current character is backslash, single-quote or
361 * double-quote (\, ' or ") and it is not quoted, it will affect
362 * quoting for subsequent characters up to the end of the quoted
363 * text. The rules for quoting are as described in Quoting
364 * . During token recognition no substitutions will be actually
365 * performed, and the result token will contain exactly the
366 * characters that appear in the input (except for newline
367 * character joining), unmodified, including any embedded or
368 * enclosing quotes or substitution operators, between the quote
369 * mark and the end of the quoted text. The token will not be
370 * delimited by the end of the quoted field."
372 * 2) "If the current character is an unquoted newline character,
373 * the current token will be delimited."
375 * 3) "If the current character is an unquoted blank character, any
376 * token containing the previous character is delimited and the
377 * current character will be discarded."
379 * 4) "If the previous character was part of a word, the current
380 * character will be appended to that word."
382 * 5) "If the current character is a "#", it and all subsequent
383 * characters up to, but excluding, the next newline character
384 * will be discarded as a comment. The newline character that
385 * ends the line is not considered part of the comment. The
386 * "#" starts a comment only when it is at the beginning of a
387 * token. Since the search for the end-of-comment does not
388 * consider an escaped newline character specially, a comment
389 * cannot be continued to the next line."
391 * 6) "The current character will be used as the start of a new word."
394 * - for each token (word), perform portions of word expansion, namely
395 * field splitting (using default whitespace IFS) and quote
396 * removal. Field splitting may increase the number of words.
397 * Quote removal does not increase the number of words.
399 * "If the complete expansion appropriate for a word results in an
400 * empty field, that empty field will be deleted from the list of
401 * fields that form the completely expanded command, unless the
402 * original word contained single-quote or double-quote characters."
409 ensure_token (GString **token)
412 *token = g_string_new (NULL);
416 delimit_token (GString **token,
422 *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
428 tokenize_command_line (const gchar *command_line,
433 GString *current_token = NULL;
434 GSList *retval = NULL;
437 current_quote = '\0';
443 if (current_quote == '\\')
447 /* we append nothing; backslash-newline become nothing */
451 /* we append the backslash and the current char,
452 * to be interpreted later after tokenization
454 ensure_token (¤t_token);
455 g_string_append_c (current_token, '\\');
456 g_string_append_c (current_token, *p);
459 current_quote = '\0';
461 else if (current_quote == '#')
463 /* Discard up to and including next newline */
464 while (*p && *p != '\n')
467 current_quote = '\0';
472 else if (current_quote)
474 if (*p == current_quote &&
475 /* check that it isn't an escaped double quote */
476 !(current_quote == '"' && quoted))
478 /* close the quote */
479 current_quote = '\0';
482 /* Everything inside quotes, and the close quote,
483 * gets appended literally.
486 ensure_token (¤t_token);
487 g_string_append_c (current_token, *p);
494 delimit_token (¤t_token, &retval);
499 /* If the current token contains the previous char, delimit
500 * the current token. A nonzero length
501 * token should always contain the previous char.
504 current_token->len > 0)
506 delimit_token (¤t_token, &retval);
509 /* discard all unquoted blanks (don't add them to a token) */
513 /* single/double quotes are appended to the token,
514 * escapes are maybe appended next time through the loop,
515 * comment chars are never appended.
520 ensure_token (¤t_token);
521 g_string_append_c (current_token, *p);
531 /* Combines rules 4) and 6) - if we have a token, append to it,
532 * otherwise create a new token.
534 ensure_token (¤t_token);
535 g_string_append_c (current_token, *p);
540 /* We need to count consecutive backslashes mod 2,
541 * to detect escaped doublequotes.
551 delimit_token (¤t_token, &retval);
555 if (current_quote == '\\')
558 G_SHELL_ERROR_BAD_QUOTING,
559 _("Text ended just after a '\\' character."
560 " (The text was '%s')"),
565 G_SHELL_ERROR_BAD_QUOTING,
566 _("Text ended before matching quote was found for %c."
567 " (The text was '%s')"),
568 current_quote, command_line);
575 g_set_error_literal (error,
577 G_SHELL_ERROR_EMPTY_STRING,
578 _("Text was empty (or contained only whitespace)"));
583 /* we appended backward */
584 retval = g_slist_reverse (retval);
589 g_assert (error == NULL || *error != NULL);
593 g_slist_foreach (retval, (GFunc)g_free, NULL);
594 g_slist_free (retval);
601 * g_shell_parse_argv:
602 * @command_line: command line to parse
603 * @argcp: return location for number of args
604 * @argvp: return location for array of args
605 * @error: return location for error
607 * Parses a command line into an argument vector, in much the same way
608 * the shell would, but without many of the expansions the shell would
609 * perform (variable expansion, globs, operators, filename expansion,
610 * etc. are not supported). The results are defined to be the same as
611 * those you would get from a UNIX98 /bin/sh, as long as the input
612 * contains none of the unsupported shell expansions. If the input
613 * does contain such expansions, they are passed through
614 * literally. Possible errors are those from the #G_SHELL_ERROR
615 * domain. Free the returned vector with g_strfreev().
617 * Return value: %TRUE on success, %FALSE if error set
620 g_shell_parse_argv (const gchar *command_line,
625 /* Code based on poptParseArgvString() from libpopt */
628 GSList *tokens = NULL;
632 g_return_val_if_fail (command_line != NULL, FALSE);
634 tokens = tokenize_command_line (command_line, error);
638 /* Because we can't have introduced any new blank space into the
639 * tokens (we didn't do any new expansions), we don't need to
640 * perform field splitting. If we were going to honor IFS or do any
641 * expansions, we would have to do field splitting on each word
642 * here. Also, if we were going to do any expansion we would need to
643 * remove any zero-length words that didn't contain quotes
644 * originally; but since there's no expansion we know all words have
645 * nonzero length, unless they contain quotes.
647 * So, we simply remove quotes, and don't do any field splitting or
648 * empty word removal, since we know there was no way to introduce
652 argc = g_slist_length (tokens);
653 argv = g_new0 (gchar*, argc + 1);
658 argv[i] = g_shell_unquote (tmp_list->data, error);
660 /* Since we already checked that quotes matched up in the
661 * tokenizer, this shouldn't be possible to reach I guess.
666 tmp_list = g_slist_next (tmp_list);
670 g_slist_foreach (tokens, (GFunc)g_free, NULL);
671 g_slist_free (tokens);
685 g_assert (error == NULL || *error != NULL);
687 g_slist_foreach (tokens, (GFunc) g_free, NULL);
688 g_slist_free (tokens);