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 #warning "FIXME remove gettext hack"
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.
59 g_shell_error_quark (void)
61 return g_quark_from_static_string ("g-shell-error-quark");
64 /* Single quotes preserve the literal string exactly. escape
65 * sequences are not allowed; not even \' - if you want a '
66 * in the quoted text, you have to do something like 'foo'\''bar'
68 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
69 * Otherwise double quotes preserve things literally.
73 unquote_string_inplace (gchar* str, gchar** end, GError** err)
79 g_return_val_if_fail(end != NULL, FALSE);
80 g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
81 g_return_val_if_fail(str != NULL, FALSE);
87 if (!(*s == '"' || *s == '\''))
89 g_set_error_literal (err,
91 G_SHELL_ERROR_BAD_QUOTING,
92 _("Quoted text doesn't begin with a quotation mark"));
97 /* Skip the initial quote mark */
100 if (quote_char == '"')
104 g_assert(s > dest); /* loop invariant */
109 /* End of the string, return now */
117 /* Possible escaped quote or \ */
132 /* not an escaped char */
135 /* ++s already done. */
147 g_assert(s > dest); /* loop invariant */
154 g_assert(s > dest); /* loop invariant */
158 /* End of the string, return now */
171 g_assert(s > dest); /* loop invariant */
175 /* If we reach here this means the close quote was never encountered */
179 g_set_error_literal (err,
181 G_SHELL_ERROR_BAD_QUOTING,
182 _("Unmatched quotation mark in command line or other shell-quoted text"));
189 * @unquoted_string: a literal string
191 * Quotes a string so that the shell (/bin/sh) will interpret the
192 * quoted string to mean @unquoted_string. If you pass a filename to
193 * the shell, for example, you should first quote it with this
194 * function. The return value must be freed with g_free(). The
195 * quoting style used is undefined (single or double quotes may be
198 * Return value: quoted string
201 g_shell_quote (const gchar *unquoted_string)
203 /* We always use single quotes, because the algorithm is cheesier.
204 * We could use double if we felt like it, that might be more
211 g_return_val_if_fail (unquoted_string != NULL, NULL);
213 dest = g_string_new ("'");
217 /* could speed this up a lot by appending chunks of text at a
222 /* Replace literal ' with a close ', a \', and a open ' */
224 g_string_append (dest, "'\\''");
226 g_string_append_c (dest, *p);
231 /* close the quote */
232 g_string_append_c (dest, '\'');
234 return g_string_free (dest, FALSE);
239 * @quoted_string: shell-quoted string
240 * @error: error return location or NULL
242 * Unquotes a string as the shell (/bin/sh) would. Only handles
243 * quotes; if a string contains file globs, arithmetic operators,
244 * variables, backticks, redirections, or other special-to-the-shell
245 * features, the result will be different from the result a real shell
246 * would produce (the variables, backticks, etc. will be passed
247 * through literally instead of being expanded). This function is
248 * guaranteed to succeed if applied to the result of
249 * g_shell_quote(). If it fails, it returns %NULL and sets the
250 * error. The @quoted_string need not actually contain quoted or
251 * escaped text; g_shell_unquote() simply goes through the string and
252 * unquotes/unescapes anything that the shell would. Both single and
253 * double quotes are handled, as are escapes including escaped
254 * newlines. The return value must be freed with g_free(). Possible
255 * errors are in the #G_SHELL_ERROR domain.
257 * Shell quoting rules are a bit strange. Single quotes preserve the
258 * literal string exactly. escape sequences are not allowed; not even
259 * \' - if you want a ' in the quoted text, you have to do something
260 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
261 * be escaped with backslash. Otherwise double quotes preserve things
264 * Return value: an unquoted string
267 g_shell_unquote (const gchar *quoted_string,
275 g_return_val_if_fail (quoted_string != NULL, NULL);
277 unquoted = g_strdup (quoted_string);
281 retval = g_string_new (NULL);
283 /* The loop allows cases such as
284 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
288 /* Append all non-quoted chars, honoring backslash escape
291 while (*start && !(*start == '"' || *start == '\''))
295 /* all characters can get escaped by backslash,
296 * except newline, which is removed if it follows
297 * a backslash outside of quotes
304 g_string_append_c (retval, *start);
310 g_string_append_c (retval, *start);
317 if (!unquote_string_inplace (start, &end, error))
323 g_string_append (retval, start);
330 return g_string_free (retval, FALSE);
333 g_assert (error == NULL || *error != NULL);
336 g_string_free (retval, TRUE);
340 /* g_parse_argv() does a semi-arbitrary weird subset of the way
341 * the shell parses a command line. We don't do variable expansion,
342 * don't understand that operators are tokens, don't do tilde expansion,
343 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
344 * don't do filename globs, don't remove redirection stuff, etc.
346 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
347 * the behavior of this code.
349 * Steps to parsing the argv string:
351 * - tokenize the string (but since we ignore operators,
352 * our tokenization may diverge from what the shell would do)
353 * note that tokenization ignores the internals of a quoted
354 * word and it always splits on spaces, not on IFS even
355 * if we used IFS. We also ignore "end of input indicator"
356 * (I guess this is control-D?)
358 * Tokenization steps, from UNIX98 with operator stuff removed,
361 * 1) "If the current character is backslash, single-quote or
362 * double-quote (\, ' or ") and it is not quoted, it will affect
363 * quoting for subsequent characters up to the end of the quoted
364 * text. The rules for quoting are as described in Quoting
365 * . During token recognition no substitutions will be actually
366 * performed, and the result token will contain exactly the
367 * characters that appear in the input (except for newline
368 * character joining), unmodified, including any embedded or
369 * enclosing quotes or substitution operators, between the quote
370 * mark and the end of the quoted text. The token will not be
371 * delimited by the end of the quoted field."
373 * 2) "If the current character is an unquoted newline character,
374 * the current token will be delimited."
376 * 3) "If the current character is an unquoted blank character, any
377 * token containing the previous character is delimited and the
378 * current character will be discarded."
380 * 4) "If the previous character was part of a word, the current
381 * character will be appended to that word."
383 * 5) "If the current character is a "#", it and all subsequent
384 * characters up to, but excluding, the next newline character
385 * will be discarded as a comment. The newline character that
386 * ends the line is not considered part of the comment. The
387 * "#" starts a comment only when it is at the beginning of a
388 * token. Since the search for the end-of-comment does not
389 * consider an escaped newline character specially, a comment
390 * cannot be continued to the next line."
392 * 6) "The current character will be used as the start of a new word."
395 * - for each token (word), perform portions of word expansion, namely
396 * field splitting (using default whitespace IFS) and quote
397 * removal. Field splitting may increase the number of words.
398 * Quote removal does not increase the number of words.
400 * "If the complete expansion appropriate for a word results in an
401 * empty field, that empty field will be deleted from the list of
402 * fields that form the completely expanded command, unless the
403 * original word contained single-quote or double-quote characters."
410 ensure_token (GString **token)
413 *token = g_string_new (NULL);
417 delimit_token (GString **token,
423 *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
429 tokenize_command_line (const gchar *command_line,
434 GString *current_token = NULL;
435 GSList *retval = NULL;
438 current_quote = '\0';
444 if (current_quote == '\\')
448 /* we append nothing; backslash-newline become nothing */
452 /* we append the backslash and the current char,
453 * to be interpreted later after tokenization
455 ensure_token (¤t_token);
456 g_string_append_c (current_token, '\\');
457 g_string_append_c (current_token, *p);
460 current_quote = '\0';
462 else if (current_quote == '#')
464 /* Discard up to and including next newline */
465 while (*p && *p != '\n')
468 current_quote = '\0';
473 else if (current_quote)
475 if (*p == current_quote &&
476 /* check that it isn't an escaped double quote */
477 !(current_quote == '"' && quoted))
479 /* close the quote */
480 current_quote = '\0';
483 /* Everything inside quotes, and the close quote,
484 * gets appended literally.
487 ensure_token (¤t_token);
488 g_string_append_c (current_token, *p);
495 delimit_token (¤t_token, &retval);
500 /* If the current token contains the previous char, delimit
501 * the current token. A nonzero length
502 * token should always contain the previous char.
505 current_token->len > 0)
507 delimit_token (¤t_token, &retval);
510 /* discard all unquoted blanks (don't add them to a token) */
514 /* single/double quotes are appended to the token,
515 * escapes are maybe appended next time through the loop,
516 * comment chars are never appended.
521 ensure_token (¤t_token);
522 g_string_append_c (current_token, *p);
532 /* Combines rules 4) and 6) - if we have a token, append to it,
533 * otherwise create a new token.
535 ensure_token (¤t_token);
536 g_string_append_c (current_token, *p);
541 /* We need to count consecutive backslashes mod 2,
542 * to detect escaped doublequotes.
552 delimit_token (¤t_token, &retval);
556 if (current_quote == '\\')
559 G_SHELL_ERROR_BAD_QUOTING,
560 _("Text ended just after a '\\' character."
561 " (The text was '%s')"),
566 G_SHELL_ERROR_BAD_QUOTING,
567 _("Text ended before matching quote was found for %c."
568 " (The text was '%s')"),
569 current_quote, command_line);
576 g_set_error_literal (error,
578 G_SHELL_ERROR_EMPTY_STRING,
579 _("Text was empty (or contained only whitespace)"));
584 /* we appended backward */
585 retval = g_slist_reverse (retval);
590 g_assert (error == NULL || *error != NULL);
594 g_slist_foreach (retval, (GFunc)g_free, NULL);
595 g_slist_free (retval);
602 * g_shell_parse_argv:
603 * @command_line: command line to parse
604 * @argcp: return location for number of args
605 * @argvp: return location for array of args
606 * @error: return location for error
608 * Parses a command line into an argument vector, in much the same way
609 * the shell would, but without many of the expansions the shell would
610 * perform (variable expansion, globs, operators, filename expansion,
611 * etc. are not supported). The results are defined to be the same as
612 * those you would get from a UNIX98 /bin/sh, as long as the input
613 * contains none of the unsupported shell expansions. If the input
614 * does contain such expansions, they are passed through
615 * literally. Possible errors are those from the #G_SHELL_ERROR
616 * domain. Free the returned vector with g_strfreev().
618 * Return value: %TRUE on success, %FALSE if error set
621 g_shell_parse_argv (const gchar *command_line,
626 /* Code based on poptParseArgvString() from libpopt */
629 GSList *tokens = NULL;
633 g_return_val_if_fail (command_line != NULL, FALSE);
635 tokens = tokenize_command_line (command_line, error);
639 /* Because we can't have introduced any new blank space into the
640 * tokens (we didn't do any new expansions), we don't need to
641 * perform field splitting. If we were going to honor IFS or do any
642 * expansions, we would have to do field splitting on each word
643 * here. Also, if we were going to do any expansion we would need to
644 * remove any zero-length words that didn't contain quotes
645 * originally; but since there's no expansion we know all words have
646 * nonzero length, unless they contain quotes.
648 * So, we simply remove quotes, and don't do any field splitting or
649 * empty word removal, since we know there was no way to introduce
653 argc = g_slist_length (tokens);
654 argv = g_new0 (gchar*, argc + 1);
659 argv[i] = g_shell_unquote (tmp_list->data, error);
661 /* Since we already checked that quotes matched up in the
662 * tokenizer, this shouldn't be possible to reach I guess.
667 tmp_list = g_slist_next (tmp_list);
671 g_slist_foreach (tokens, (GFunc)g_free, NULL);
672 g_slist_free (tokens);
686 g_assert (error == NULL || *error != NULL);
688 g_slist_foreach (tokens, (GFunc) g_free, NULL);
689 g_slist_free (tokens);
694 #define __G_SHELL_C__
695 #include "galiasdef.c"