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.
29 #warning "FIXME remove gettext hack"
35 g_shell_error_quark (void)
37 static GQuark quark = 0;
39 quark = g_quark_from_static_string ("g-shell-error-quark");
43 /* Single quotes preserve the literal string exactly. escape
44 * sequences are not allowed; not even \' - if you want a '
45 * in the quoted text, you have to do something like 'foo'\''bar'
47 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
48 * Otherwise double quotes preserve things literally.
52 unquote_string_inplace (gchar* str, gchar** end, GError** err)
58 g_return_val_if_fail(end != NULL, FALSE);
59 g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
60 g_return_val_if_fail(str != NULL, FALSE);
66 if (!(*s == '"' || *s == '\''))
69 *err = g_error_new(G_SHELL_ERROR,
70 G_SHELL_ERROR_BAD_QUOTING,
71 _("Quoted text doesn't begin with a quotation mark"));
76 /* Skip the initial quote mark */
79 if (quote_char == '"')
83 g_assert(s > dest); /* loop invariant */
88 /* End of the string, return now */
96 /* Possible escaped quote or \ */
111 /* not an escaped char */
114 /* ++s already done. */
126 g_assert(s > dest); /* loop invariant */
133 g_assert(s > dest); /* loop invariant */
137 /* End of the string, return now */
150 g_assert(s > dest); /* loop invariant */
154 /* If we reach here this means the close quote was never encountered */
159 *err = g_error_new(G_SHELL_ERROR,
160 G_SHELL_ERROR_BAD_QUOTING,
161 _("Unmatched quotation mark in command line or other shell-quoted text"));
168 * @unquoted_string: a literal string
170 * Quotes a string so that the shell (/bin/sh) will interpret the
171 * quoted string to mean @unquoted_string. If you pass a filename to
172 * the shell, for example, you should first quote it with this
173 * function. The return value must be freed with g_free(). The
174 * quoting style used is undefined (single or double quotes may be
177 * Return value: quoted string
180 g_shell_quote (const gchar *unquoted_string)
182 /* We always use single quotes, because the algorithm is cheesier.
183 * We could use double if we felt like it, that might be more
190 g_return_val_if_fail (unquoted_string != NULL, NULL);
192 dest = g_string_new ("'");
196 /* could speed this up a lot by appending chunks of text at a
201 /* Replace literal ' with a close ', a \', and a open ' */
203 g_string_append (dest, "'\\''");
205 g_string_append_c (dest, *p);
210 /* close the quote */
211 g_string_append_c (dest, '\'');
213 return g_string_free (dest, FALSE);
218 * @quoted_string: shell-quoted string
219 * @error: error return location or NULL
221 * Unquotes a string as the shell (/bin/sh) would. Only handles
222 * quotes; if a string contains file globs, arithmetic operators,
223 * variables, backticks, redirections, or other special-to-the-shell
224 * features, the result will be different from the result a real shell
225 * would produce (the variables, backticks, etc. will be passed
226 * through literally instead of being expanded). This function is
227 * guaranteed to succeed if applied to the result of
228 * g_shell_quote(). If it fails, it returns %NULL and sets the
229 * error. The @quoted_string need not actually contain quoted or
230 * escaped text; g_shell_unquote() simply goes through the string and
231 * unquotes/unescapes anything that the shell would. Both single and
232 * double quotes are handled, as are escapes including escaped
233 * newlines. The return value must be freed with g_free(). Possible
234 * errors are in the #G_SHELL_ERROR domain.
236 * Shell quoting rules are a bit strange. Single quotes preserve the
237 * literal string exactly. escape sequences are not allowed; not even
238 * \' - if you want a ' in the quoted text, you have to do something
239 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
240 * be escaped with backslash. Otherwise double quotes preserve things
243 * Return value: an unquoted string
246 g_shell_unquote (const gchar *quoted_string,
254 g_return_val_if_fail (quoted_string != NULL, NULL);
256 unquoted = g_strdup (quoted_string);
260 retval = g_string_new ("");
262 /* The loop allows cases such as
263 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
267 /* Append all non-quoted chars, honoring backslash escape
270 while (*start && !(*start == '"' || *start == '\''))
274 /* all characters can get escaped by backslash,
275 * except newline, which is removed if it follows
276 * a backslash outside of quotes
283 g_string_append_c (retval, *start);
289 g_string_append_c (retval, *start);
296 if (!unquote_string_inplace (start, &end, error))
302 g_string_append (retval, start);
308 return g_string_free (retval, FALSE);
311 g_assert (error == NULL || *error != NULL);
314 g_string_free (retval, TRUE);
318 /* g_parse_argv() does a semi-arbitrary weird subset of the way
319 * the shell parses a command line. We don't do variable expansion,
320 * don't understand that operators are tokens, don't do tilde expansion,
321 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
322 * don't do filename globs, don't remove redirection stuff, etc.
324 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
325 * the behavior of this code.
327 * Steps to parsing the argv string:
329 * - tokenize the string (but since we ignore operators,
330 * our tokenization may diverge from what the shell would do)
331 * note that tokenization ignores the internals of a quoted
332 * word and it always splits on spaces, not on IFS even
333 * if we used IFS. We also ignore "end of input indicator"
334 * (I guess this is control-D?)
336 * Tokenization steps, from UNIX98 with operator stuff removed,
339 * 1) "If the current character is backslash, single-quote or
340 * double-quote (\, ' or ") and it is not quoted, it will affect
341 * quoting for subsequent characters up to the end of the quoted
342 * text. The rules for quoting are as described in Quoting
343 * . During token recognition no substitutions will be actually
344 * performed, and the result token will contain exactly the
345 * characters that appear in the input (except for newline
346 * character joining), unmodified, including any embedded or
347 * enclosing quotes or substitution operators, between the quote
348 * mark and the end of the quoted text. The token will not be
349 * delimited by the end of the quoted field."
351 * 2) "If the current character is an unquoted newline character,
352 * the current token will be delimited."
354 * 3) "If the current character is an unquoted blank character, any
355 * token containing the previous character is delimited and the
356 * current character will be discarded."
358 * 4) "If the previous character was part of a word, the current
359 * character will be appended to that word."
361 * 5) "If the current character is a "#", it and all subsequent
362 * characters up to, but excluding, the next newline character
363 * will be discarded as a comment. The newline character that
364 * ends the line is not considered part of the comment. The
365 * "#" starts a comment only when it is at the beginning of a
366 * token. Since the search for the end-of-comment does not
367 * consider an escaped newline character specially, a comment
368 * cannot be continued to the next line."
370 * 6) "The current character will be used as the start of a new word."
373 * - for each token (word), perform portions of word expansion, namely
374 * field splitting (using default whitespace IFS) and quote
375 * removal. Field splitting may increase the number of words.
376 * Quote removal does not increase the number of words.
378 * "If the complete expansion appropriate for a word results in an
379 * empty field, that empty field will be deleted from the list of
380 * fields that form the completely expanded command, unless the
381 * original word contained single-quote or double-quote characters."
388 ensure_token (GString **token)
391 *token = g_string_new ("");
395 delimit_token (GString **token,
401 *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
407 tokenize_command_line (const gchar *command_line,
412 GString *current_token = NULL;
413 GSList *retval = NULL;
415 current_quote = '\0';
420 if (current_quote == '\\')
424 /* we append nothing; backslash-newline become nothing */
428 /* we append the backslash and the current char,
429 * to be interpreted later after tokenization
431 ensure_token (¤t_token);
432 g_string_append_c (current_token, '\\');
433 g_string_append_c (current_token, *p);
436 current_quote = '\0';
438 else if (current_quote == '#')
440 /* Discard up to and including next newline */
441 while (*p && *p != '\n')
444 current_quote = '\0';
449 else if (current_quote)
451 if (*p == current_quote &&
452 /* check that it isn't an escaped double quote */
453 !(current_quote == '"' && p != command_line && *(p - 1) == '\\'))
455 /* close the quote */
456 current_quote = '\0';
459 /* Everything inside quotes, and the close quote,
460 * gets appended literally.
463 ensure_token (¤t_token);
464 g_string_append_c (current_token, *p);
471 delimit_token (¤t_token, &retval);
476 /* If the current token contains the previous char, delimit
477 * the current token. A nonzero length
478 * token should always contain the previous char.
481 current_token->len > 0)
483 delimit_token (¤t_token, &retval);
486 /* discard all unquoted blanks (don't add them to a token) */
490 /* single/double quotes are appended to the token,
491 * escapes are maybe appended next time through the loop,
492 * comment chars are never appended.
497 ensure_token (¤t_token);
498 g_string_append_c (current_token, *p);
508 /* Combines rules 4) and 6) - if we have a token, append to it,
509 * otherwise create a new token.
511 ensure_token (¤t_token);
512 g_string_append_c (current_token, *p);
520 delimit_token (¤t_token, &retval);
524 if (current_quote == '\\')
527 G_SHELL_ERROR_BAD_QUOTING,
528 _("Text ended just after a '\\' character."
529 " (The text was '%s')"),
534 G_SHELL_ERROR_BAD_QUOTING,
535 _("Text ended before matching quote was found for %c."
536 " (The text was '%s')"),
537 current_quote, command_line);
546 G_SHELL_ERROR_EMPTY_STRING,
547 _("Text was empty (or contained only whitespace)"));
552 /* we appended backward */
553 retval = g_slist_reverse (retval);
558 g_assert (error == NULL || *error != NULL);
562 g_slist_foreach (retval, (GFunc)g_free, NULL);
563 g_slist_free (retval);
570 * g_shell_parse_argv:
571 * @command_line: command line to parse
572 * @argcp: return location for number of args
573 * @argvp: return location for array of args
574 * @error: return location for error
576 * Parses a command line into an argument vector, in much the same way
577 * the shell would, but without many of the expansions the shell would
578 * perform (variable expansion, globs, operators, filename expansion,
579 * etc. are not supported). The results are defined to be the same as
580 * those you would get from a UNIX98 /bin/sh, as long as the input
581 * contains none of the unsupported shell expansions. If the input
582 * does contain such expansions, they are passed through
583 * literally. Possible errors are those from the #G_SHELL_ERROR
584 * domain. Free the returned vector with g_strfreev().
586 * Return value: %TRUE on success, %FALSE if error set
589 g_shell_parse_argv (const gchar *command_line,
594 /* Code based on poptParseArgvString() from libpopt */
597 GSList *tokens = NULL;
601 g_return_val_if_fail (command_line != NULL, FALSE);
603 tokens = tokenize_command_line (command_line, error);
607 /* Because we can't have introduced any new blank space into the
608 * tokens (we didn't do any new expansions), we don't need to
609 * perform field splitting. If we were going to honor IFS or do any
610 * expansions, we would have to do field splitting on each word
611 * here. Also, if we were going to do any expansion we would need to
612 * remove any zero-length words that didn't contain quotes
613 * originally; but since there's no expansion we know all words have
614 * nonzero length, unless they contain quotes.
616 * So, we simply remove quotes, and don't do any field splitting or
617 * empty word removal, since we know there was no way to introduce
621 argc = g_slist_length (tokens);
622 argv = g_new0 (gchar*, argc + 1);
627 argv[i] = g_shell_unquote (tmp_list->data, error);
629 /* Since we already checked that quotes matched up in the
630 * tokenizer, this shouldn't be possible to reach I guess.
635 tmp_list = g_slist_next (tmp_list);
639 g_slist_foreach (tokens, (GFunc)g_free, NULL);
640 g_slist_free (tokens);
654 g_assert (error == NULL || *error != NULL);
656 g_slist_foreach (tokens, (GFunc) g_free, NULL);
657 g_slist_free (tokens);