1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-shell.c Shell command line utility functions.
4 * Copyright (C) 2002, 2003 Red Hat, Inc.
5 * Copyright (C) 2003 CodeFactory AB
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #include "dbus-internals.h"
27 #include "dbus-list.h"
28 #include "dbus-memory.h"
29 #include "dbus-protocol.h"
30 #include "dbus-shell.h"
31 #include "dbus-string.h"
33 /* Single quotes preserve the literal string exactly. escape
34 * sequences are not allowed; not even \' - if you want a '
35 * in the quoted text, you have to do something like 'foo'\''bar'
37 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
38 * Otherwise double quotes preserve things literally.
42 unquote_string_inplace (char* str, char** end)
52 if (!(*s == '"' || *s == '\''))
58 /* Skip the initial quote mark */
61 if (quote_char == '"')
65 _dbus_assert(s > dest); /* loop invariant */
70 /* End of the string, return now */
77 /* Possible escaped quote or \ */
92 /* not an escaped char */
95 /* ++s already done. */
107 _dbus_assert(s > dest); /* loop invariant */
114 _dbus_assert(s > dest); /* loop invariant */
118 /* End of the string, return now */
131 _dbus_assert(s > dest); /* loop invariant */
135 /* If we reach here this means the close quote was never encountered */
144 * Quotes a string so that the shell (/bin/sh) will interpret the
145 * quoted string to mean @unquoted_string. If you pass a filename to
146 * the shell, for example, you should first quote it with this
147 * function. The return value must be freed with dbus_free(). The
148 * quoting style used is undefined (single or double quotes may be
151 * @unquoted_string: a literal string
154 _dbus_shell_quote (const char *unquoted_string)
156 /* We always use single quotes, because the algorithm is cheesier.
157 * We could use double if we felt like it, that might be more
165 _dbus_string_init (&dest);
169 /* could speed this up a lot by appending chunks of text at a
174 /* Replace literal ' with a close ', a \', and a open ' */
177 if (!_dbus_string_append (&dest, "'\\''"))
179 _dbus_string_free (&dest);
185 if (!_dbus_string_append_byte (&dest, *p))
187 _dbus_string_free (&dest);
195 /* close the quote */
196 if (_dbus_string_append_byte (&dest, '\''))
198 ret = _dbus_strdup (_dbus_string_get_data (&dest));
199 _dbus_string_free (&dest);
204 _dbus_string_free (&dest);
210 * Unquotes a string as the shell (/bin/sh) would. Only handles
211 * quotes; if a string contains file globs, arithmetic operators,
212 * variables, backticks, redirections, or other special-to-the-shell
213 * features, the result will be different from the result a real shell
214 * would produce (the variables, backticks, etc. will be passed
215 * through literally instead of being expanded). This function is
216 * guaranteed to succeed if applied to the result of
217 * _dbus_shell_quote(). If it fails, it returns %NULL.
218 * The @quoted_string need not actually contain quoted or
219 * escaped text; _dbus_shell_unquote() simply goes through the string and
220 * unquotes/unescapes anything that the shell would. Both single and
221 * double quotes are handled, as are escapes including escaped
222 * newlines. The return value must be freed with dbus_free().
224 * Shell quoting rules are a bit strange. Single quotes preserve the
225 * literal string exactly. escape sequences are not allowed; not even
226 * \' - if you want a ' in the quoted text, you have to do something
227 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
228 * be escaped with backslash. Otherwise double quotes preserve things
231 * @quoted_string: shell-quoted string
234 _dbus_shell_unquote (const char *quoted_string)
242 unquoted = _dbus_strdup (quoted_string);
243 if (unquoted == NULL)
248 if (!_dbus_string_init (&retval))
250 dbus_free (unquoted);
254 /* The loop allows cases such as
255 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
259 /* Append all non-quoted chars, honoring backslash escape
262 while (*start && !(*start == '"' || *start == '\''))
266 /* all characters can get escaped by backslash,
267 * except newline, which is removed if it follows
268 * a backslash outside of quotes
276 if (!_dbus_string_append_byte (&retval, *start))
284 if (!_dbus_string_append_byte (&retval, *start))
292 if (!unquote_string_inplace (start, &end))
296 if (!_dbus_string_append (&retval, start))
303 ret = _dbus_strdup (_dbus_string_get_data (&retval));
307 dbus_free (unquoted);
308 _dbus_string_free (&retval);
313 dbus_free (unquoted);
314 _dbus_string_free (&retval);
318 /* _dbus_shell_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 delimit_token (DBusString *token,
394 str = _dbus_strdup (_dbus_string_get_data (token));
397 _DBUS_SET_OOM (error);
401 if (!_dbus_list_append (retval, str))
404 _DBUS_SET_OOM (error);
412 tokenize_command_line (const char *command_line, DBusError *error)
416 DBusString current_token;
417 DBusList *retval = NULL;
420 current_quote = '\0';
424 if (!_dbus_string_init (¤t_token))
426 _DBUS_SET_OOM (error);
432 if (current_quote == '\\')
436 /* we append nothing; backslash-newline become nothing */
440 if (!_dbus_string_append_byte (¤t_token, '\\') ||
441 !_dbus_string_append_byte (¤t_token, *p))
443 _DBUS_SET_OOM (error);
448 current_quote = '\0';
450 else if (current_quote == '#')
452 /* Discard up to and including next newline */
453 while (*p && *p != '\n')
456 current_quote = '\0';
461 else if (current_quote)
463 if (*p == current_quote &&
464 /* check that it isn't an escaped double quote */
465 !(current_quote == '"' && quoted))
467 /* close the quote */
468 current_quote = '\0';
471 /* Everything inside quotes, and the close quote,
472 * gets appended literally.
475 if (!_dbus_string_append_byte (¤t_token, *p))
477 _DBUS_SET_OOM (error);
486 if (!delimit_token (¤t_token, &retval, error))
489 _dbus_string_free (¤t_token);
491 if (!_dbus_string_init (¤t_token))
493 _DBUS_SET_OOM (error);
501 /* If the current token contains the previous char, delimit
502 * the current token. A nonzero length
503 * token should always contain the previous char.
505 if (_dbus_string_get_length (¤t_token) > 0)
507 if (!delimit_token (¤t_token, &retval, error))
510 _dbus_string_free (¤t_token);
512 if (!_dbus_string_init (¤t_token))
514 _DBUS_SET_OOM (error);
520 /* discard all unquoted blanks (don't add them to a token) */
524 /* single/double quotes are appended to the token,
525 * escapes are maybe appended next time through the loop,
526 * comment chars are never appended.
531 if (!_dbus_string_append_byte (¤t_token, *p))
533 _DBUS_SET_OOM (error);
545 /* Combines rules 4) and 6) - if we have a token, append to it,
546 * otherwise create a new token.
548 if (!_dbus_string_append_byte (¤t_token, *p))
550 _DBUS_SET_OOM (error);
557 /* We need to count consecutive backslashes mod 2,
558 * to detect escaped doublequotes.
568 if (!delimit_token (¤t_token, &retval, error))
573 dbus_set_error_const (error, DBUS_ERROR_INVALID_ARGS, "Unclosed quotes in command line");
579 dbus_set_error_const (error, DBUS_ERROR_INVALID_ARGS, "No tokens found in command line");
583 _dbus_string_free (¤t_token);
588 _dbus_string_free (¤t_token);
593 _dbus_list_foreach (&retval, (DBusForeachFunction) dbus_free, NULL);
594 _dbus_list_clear (&retval);
601 * _dbus_shell_parse_argv:
603 * Parses a command line into an argument vector, in much the same way
604 * the shell would, but without many of the expansions the shell would
605 * perform (variable expansion, globs, operators, filename expansion,
606 * etc. are not supported). The results are defined to be the same as
607 * those you would get from a UNIX98 /bin/sh, as long as the input
608 * contains none of the unsupported shell expansions. If the input
609 * does contain such expansions, they are passed through
610 * literally. Free the returned vector with dbus_free_string_array().
612 * @command_line: command line to parse
613 * @argcp: return location for number of args
614 * @argvp: return location for array of args
615 * @error: error information
618 _dbus_shell_parse_argv (const char *command_line,
623 /* Code based on poptParseArgvString() from libpopt */
626 DBusList *tokens = NULL;
632 _dbus_verbose ("Command line is NULL\n");
636 tokens = tokenize_command_line (command_line, error);
639 _dbus_verbose ("No tokens for command line '%s'\n", command_line);
643 /* Because we can't have introduced any new blank space into the
644 * tokens (we didn't do any new expansions), we don't need to
645 * perform field splitting. If we were going to honor IFS or do any
646 * expansions, we would have to do field splitting on each word
647 * here. Also, if we were going to do any expansion we would need to
648 * remove any zero-length words that didn't contain quotes
649 * originally; but since there's no expansion we know all words have
650 * nonzero length, unless they contain quotes.
652 * So, we simply remove quotes, and don't do any field splitting or
653 * empty word removal, since we know there was no way to introduce
657 argc = _dbus_list_get_length (&tokens);
658 argv = dbus_new (char *, argc + 1);
661 _DBUS_SET_OOM (error);
669 argv[i] = _dbus_shell_unquote (tmp_list->data);
674 for (j = 0; j < i; j++)
678 _DBUS_SET_OOM (error);
682 tmp_list = _dbus_list_get_next_link (&tokens, tmp_list);
687 _dbus_list_foreach (&tokens, (DBusForeachFunction) dbus_free, NULL);
688 _dbus_list_clear (&tokens);
696 dbus_free_string_array (argv);
701 _dbus_list_foreach (&tokens, (DBusForeachFunction) dbus_free, NULL);
702 _dbus_list_clear (&tokens);