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.
31 #warning "FIXME remove gettext hack"
37 g_shell_error_quark (void)
39 static GQuark quark = 0;
41 quark = g_quark_from_static_string ("g-shell-error-quark");
45 /* Single quotes preserve the literal string exactly. escape
46 * sequences are not allowed; not even \' - if you want a '
47 * in the quoted text, you have to do something like 'foo'\''bar'
49 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
50 * Otherwise double quotes preserve things literally.
54 unquote_string_inplace (gchar* str, gchar** end, GError** err)
60 g_return_val_if_fail(end != NULL, FALSE);
61 g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
62 g_return_val_if_fail(str != NULL, FALSE);
68 if (!(*s == '"' || *s == '\''))
71 *err = g_error_new(G_SHELL_ERROR,
72 G_SHELL_ERROR_BAD_QUOTING,
73 _("Quoted text doesn't begin with a quotation mark"));
78 /* Skip the initial quote mark */
81 if (quote_char == '"')
85 g_assert(s > dest); /* loop invariant */
90 /* End of the string, return now */
98 /* Possible escaped quote or \ */
113 /* not an escaped char */
116 /* ++s already done. */
128 g_assert(s > dest); /* loop invariant */
135 g_assert(s > dest); /* loop invariant */
139 /* End of the string, return now */
152 g_assert(s > dest); /* loop invariant */
156 /* If we reach here this means the close quote was never encountered */
161 *err = g_error_new(G_SHELL_ERROR,
162 G_SHELL_ERROR_BAD_QUOTING,
163 _("Unmatched quotation mark in command line or other shell-quoted text"));
170 * @unquoted_string: a literal string
172 * Quotes a string so that the shell (/bin/sh) will interpret the
173 * quoted string to mean @unquoted_string. If you pass a filename to
174 * the shell, for example, you should first quote it with this
175 * function. The return value must be freed with g_free(). The
176 * quoting style used is undefined (single or double quotes may be
179 * Return value: quoted string
182 g_shell_quote (const gchar *unquoted_string)
184 /* We always use single quotes, because the algorithm is cheesier.
185 * We could use double if we felt like it, that might be more
192 g_return_val_if_fail (unquoted_string != NULL, NULL);
194 dest = g_string_new ("'");
198 /* could speed this up a lot by appending chunks of text at a
203 /* Replace literal ' with a close ', a \', and a open ' */
205 g_string_append (dest, "'\\''");
207 g_string_append_c (dest, *p);
212 /* close the quote */
213 g_string_append_c (dest, '\'');
215 return g_string_free (dest, FALSE);
220 * @quoted_string: shell-quoted string
221 * @error: error return location or NULL
223 * Unquotes a string as the shell (/bin/sh) would. Only handles
224 * quotes; if a string contains file globs, arithmetic operators,
225 * variables, backticks, redirections, or other special-to-the-shell
226 * features, the result will be different from the result a real shell
227 * would produce (the variables, backticks, etc. will be passed
228 * through literally instead of being expanded). This function is
229 * guaranteed to succeed if applied to the result of
230 * g_shell_quote(). If it fails, it returns %NULL and sets the
231 * error. The @quoted_string need not actually contain quoted or
232 * escaped text; g_shell_unquote() simply goes through the string and
233 * unquotes/unescapes anything that the shell would. Both single and
234 * double quotes are handled, as are escapes including escaped
235 * newlines. The return value must be freed with g_free(). Possible
236 * errors are in the #G_SHELL_ERROR domain.
238 * Shell quoting rules are a bit strange. Single quotes preserve the
239 * literal string exactly. escape sequences are not allowed; not even
240 * \' - if you want a ' in the quoted text, you have to do something
241 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
242 * be escaped with backslash. Otherwise double quotes preserve things
245 * Return value: an unquoted string
248 g_shell_unquote (const gchar *quoted_string,
256 g_return_val_if_fail (quoted_string != NULL, NULL);
258 unquoted = g_strdup (quoted_string);
262 retval = g_string_new (NULL);
264 /* The loop allows cases such as
265 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
269 /* Append all non-quoted chars, honoring backslash escape
272 while (*start && !(*start == '"' || *start == '\''))
276 /* all characters can get escaped by backslash,
277 * except newline, which is removed if it follows
278 * a backslash outside of quotes
285 g_string_append_c (retval, *start);
291 g_string_append_c (retval, *start);
298 if (!unquote_string_inplace (start, &end, error))
304 g_string_append (retval, start);
311 return g_string_free (retval, FALSE);
314 g_assert (error == NULL || *error != NULL);
317 g_string_free (retval, TRUE);
321 /* g_parse_argv() does a semi-arbitrary weird subset of the way
322 * the shell parses a command line. We don't do variable expansion,
323 * don't understand that operators are tokens, don't do tilde expansion,
324 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
325 * don't do filename globs, don't remove redirection stuff, etc.
327 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
328 * the behavior of this code.
330 * Steps to parsing the argv string:
332 * - tokenize the string (but since we ignore operators,
333 * our tokenization may diverge from what the shell would do)
334 * note that tokenization ignores the internals of a quoted
335 * word and it always splits on spaces, not on IFS even
336 * if we used IFS. We also ignore "end of input indicator"
337 * (I guess this is control-D?)
339 * Tokenization steps, from UNIX98 with operator stuff removed,
342 * 1) "If the current character is backslash, single-quote or
343 * double-quote (\, ' or ") and it is not quoted, it will affect
344 * quoting for subsequent characters up to the end of the quoted
345 * text. The rules for quoting are as described in Quoting
346 * . During token recognition no substitutions will be actually
347 * performed, and the result token will contain exactly the
348 * characters that appear in the input (except for newline
349 * character joining), unmodified, including any embedded or
350 * enclosing quotes or substitution operators, between the quote
351 * mark and the end of the quoted text. The token will not be
352 * delimited by the end of the quoted field."
354 * 2) "If the current character is an unquoted newline character,
355 * the current token will be delimited."
357 * 3) "If the current character is an unquoted blank character, any
358 * token containing the previous character is delimited and the
359 * current character will be discarded."
361 * 4) "If the previous character was part of a word, the current
362 * character will be appended to that word."
364 * 5) "If the current character is a "#", it and all subsequent
365 * characters up to, but excluding, the next newline character
366 * will be discarded as a comment. The newline character that
367 * ends the line is not considered part of the comment. The
368 * "#" starts a comment only when it is at the beginning of a
369 * token. Since the search for the end-of-comment does not
370 * consider an escaped newline character specially, a comment
371 * cannot be continued to the next line."
373 * 6) "The current character will be used as the start of a new word."
376 * - for each token (word), perform portions of word expansion, namely
377 * field splitting (using default whitespace IFS) and quote
378 * removal. Field splitting may increase the number of words.
379 * Quote removal does not increase the number of words.
381 * "If the complete expansion appropriate for a word results in an
382 * empty field, that empty field will be deleted from the list of
383 * fields that form the completely expanded command, unless the
384 * original word contained single-quote or double-quote characters."
391 ensure_token (GString **token)
394 *token = g_string_new (NULL);
398 delimit_token (GString **token,
404 *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
410 tokenize_command_line (const gchar *command_line,
415 GString *current_token = NULL;
416 GSList *retval = NULL;
419 current_quote = '\0';
425 if (current_quote == '\\')
429 /* we append nothing; backslash-newline become nothing */
433 /* we append the backslash and the current char,
434 * to be interpreted later after tokenization
436 ensure_token (¤t_token);
437 g_string_append_c (current_token, '\\');
438 g_string_append_c (current_token, *p);
441 current_quote = '\0';
443 else if (current_quote == '#')
445 /* Discard up to and including next newline */
446 while (*p && *p != '\n')
449 current_quote = '\0';
454 else if (current_quote)
456 if (*p == current_quote &&
457 /* check that it isn't an escaped double quote */
458 !(current_quote == '"' && quoted))
460 /* close the quote */
461 current_quote = '\0';
464 /* Everything inside quotes, and the close quote,
465 * gets appended literally.
468 ensure_token (¤t_token);
469 g_string_append_c (current_token, *p);
476 delimit_token (¤t_token, &retval);
481 /* If the current token contains the previous char, delimit
482 * the current token. A nonzero length
483 * token should always contain the previous char.
486 current_token->len > 0)
488 delimit_token (¤t_token, &retval);
491 /* discard all unquoted blanks (don't add them to a token) */
495 /* single/double quotes are appended to the token,
496 * escapes are maybe appended next time through the loop,
497 * comment chars are never appended.
502 ensure_token (¤t_token);
503 g_string_append_c (current_token, *p);
513 /* Combines rules 4) and 6) - if we have a token, append to it,
514 * otherwise create a new token.
516 ensure_token (¤t_token);
517 g_string_append_c (current_token, *p);
522 /* We need to count consecutive backslashes mod 2,
523 * to detect escaped doublequotes.
533 delimit_token (¤t_token, &retval);
537 if (current_quote == '\\')
540 G_SHELL_ERROR_BAD_QUOTING,
541 _("Text ended just after a '\\' character."
542 " (The text was '%s')"),
547 G_SHELL_ERROR_BAD_QUOTING,
548 _("Text ended before matching quote was found for %c."
549 " (The text was '%s')"),
550 current_quote, command_line);
559 G_SHELL_ERROR_EMPTY_STRING,
560 _("Text was empty (or contained only whitespace)"));
565 /* we appended backward */
566 retval = g_slist_reverse (retval);
571 g_assert (error == NULL || *error != NULL);
575 g_slist_foreach (retval, (GFunc)g_free, NULL);
576 g_slist_free (retval);
583 * g_shell_parse_argv:
584 * @command_line: command line to parse
585 * @argcp: return location for number of args
586 * @argvp: return location for array of args
587 * @error: return location for error
589 * Parses a command line into an argument vector, in much the same way
590 * the shell would, but without many of the expansions the shell would
591 * perform (variable expansion, globs, operators, filename expansion,
592 * etc. are not supported). The results are defined to be the same as
593 * those you would get from a UNIX98 /bin/sh, as long as the input
594 * contains none of the unsupported shell expansions. If the input
595 * does contain such expansions, they are passed through
596 * literally. Possible errors are those from the #G_SHELL_ERROR
597 * domain. Free the returned vector with g_strfreev().
599 * Return value: %TRUE on success, %FALSE if error set
602 g_shell_parse_argv (const gchar *command_line,
607 /* Code based on poptParseArgvString() from libpopt */
610 GSList *tokens = NULL;
614 g_return_val_if_fail (command_line != NULL, FALSE);
616 tokens = tokenize_command_line (command_line, error);
620 /* Because we can't have introduced any new blank space into the
621 * tokens (we didn't do any new expansions), we don't need to
622 * perform field splitting. If we were going to honor IFS or do any
623 * expansions, we would have to do field splitting on each word
624 * here. Also, if we were going to do any expansion we would need to
625 * remove any zero-length words that didn't contain quotes
626 * originally; but since there's no expansion we know all words have
627 * nonzero length, unless they contain quotes.
629 * So, we simply remove quotes, and don't do any field splitting or
630 * empty word removal, since we know there was no way to introduce
634 argc = g_slist_length (tokens);
635 argv = g_new0 (gchar*, argc + 1);
640 argv[i] = g_shell_unquote (tmp_list->data, error);
642 /* Since we already checked that quotes matched up in the
643 * tokenizer, this shouldn't be possible to reach I guess.
648 tmp_list = g_slist_next (tmp_list);
652 g_slist_foreach (tokens, (GFunc)g_free, NULL);
653 g_slist_free (tokens);
667 g_assert (error == NULL || *error != NULL);
669 g_slist_foreach (tokens, (GFunc) g_free, NULL);
670 g_slist_free (tokens);