1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "dbus-internals.h"
28 #include "dbus-list.h"
29 #include "dbus-memory.h"
30 #include "dbus-protocol.h"
31 #include "dbus-shell.h"
32 #include "dbus-string.h"
34 /* Single quotes preserve the literal string exactly. escape
35 * sequences are not allowed; not even \' - if you want a '
36 * in the quoted text, you have to do something like 'foo'\''bar'
38 * Double quotes allow $ ` " \ and newline to be escaped with backslash.
39 * Otherwise double quotes preserve things literally.
43 unquote_string_inplace (char* str, char** end)
53 if (!(*s == '"' || *s == '\''))
59 /* Skip the initial quote mark */
62 if (quote_char == '"')
66 _dbus_assert(s > dest); /* loop invariant */
71 /* End of the string, return now */
78 /* Possible escaped quote or \ */
93 /* not an escaped char */
96 /* ++s already done. */
108 _dbus_assert(s > dest); /* loop invariant */
115 _dbus_assert(s > dest); /* loop invariant */
119 /* End of the string, return now */
132 _dbus_assert(s > dest); /* loop invariant */
136 /* If we reach here this means the close quote was never encountered */
145 * Unquotes a string as the shell (/bin/sh) would. Only handles
146 * quotes; if a string contains file globs, arithmetic operators,
147 * variables, backticks, redirections, or other special-to-the-shell
148 * features, the result will be different from the result a real shell
149 * would produce (the variables, backticks, etc. will be passed
150 * through literally instead of being expanded). This function is
151 * guaranteed to succeed if applied to the result of
152 * _dbus_shell_quote(). If it fails, it returns %NULL.
153 * The @quoted_string need not actually contain quoted or
154 * escaped text; _dbus_shell_unquote() simply goes through the string and
155 * unquotes/unescapes anything that the shell would. Both single and
156 * double quotes are handled, as are escapes including escaped
157 * newlines. The return value must be freed with dbus_free().
159 * Shell quoting rules are a bit strange. Single quotes preserve the
160 * literal string exactly. escape sequences are not allowed; not even
161 * \' - if you want a ' in the quoted text, you have to do something
162 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
163 * be escaped with backslash. Otherwise double quotes preserve things
166 * @quoted_string: shell-quoted string
169 _dbus_shell_unquote (const char *quoted_string)
177 unquoted = _dbus_strdup (quoted_string);
178 if (unquoted == NULL)
183 if (!_dbus_string_init (&retval))
185 dbus_free (unquoted);
189 /* The loop allows cases such as
190 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
194 /* Append all non-quoted chars, honoring backslash escape
197 while (*start && !(*start == '"' || *start == '\''))
201 /* all characters can get escaped by backslash,
202 * except newline, which is removed if it follows
203 * a backslash outside of quotes
211 if (!_dbus_string_append_byte (&retval, *start))
219 if (!_dbus_string_append_byte (&retval, *start))
227 if (!unquote_string_inplace (start, &end))
231 if (!_dbus_string_append (&retval, start))
238 ret = _dbus_strdup (_dbus_string_get_data (&retval));
242 dbus_free (unquoted);
243 _dbus_string_free (&retval);
248 dbus_free (unquoted);
249 _dbus_string_free (&retval);
253 /* _dbus_shell_parse_argv() does a semi-arbitrary weird subset of the way
254 * the shell parses a command line. We don't do variable expansion,
255 * don't understand that operators are tokens, don't do tilde expansion,
256 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
257 * don't do filename globs, don't remove redirection stuff, etc.
259 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
260 * the behavior of this code.
262 * Steps to parsing the argv string:
264 * - tokenize the string (but since we ignore operators,
265 * our tokenization may diverge from what the shell would do)
266 * note that tokenization ignores the internals of a quoted
267 * word and it always splits on spaces, not on IFS even
268 * if we used IFS. We also ignore "end of input indicator"
269 * (I guess this is control-D?)
271 * Tokenization steps, from UNIX98 with operator stuff removed,
274 * 1) "If the current character is backslash, single-quote or
275 * double-quote (\, ' or ") and it is not quoted, it will affect
276 * quoting for subsequent characters up to the end of the quoted
277 * text. The rules for quoting are as described in Quoting
278 * . During token recognition no substitutions will be actually
279 * performed, and the result token will contain exactly the
280 * characters that appear in the input (except for newline
281 * character joining), unmodified, including any embedded or
282 * enclosing quotes or substitution operators, between the quote
283 * mark and the end of the quoted text. The token will not be
284 * delimited by the end of the quoted field."
286 * 2) "If the current character is an unquoted newline character,
287 * the current token will be delimited."
289 * 3) "If the current character is an unquoted blank character, any
290 * token containing the previous character is delimited and the
291 * current character will be discarded."
293 * 4) "If the previous character was part of a word, the current
294 * character will be appended to that word."
296 * 5) "If the current character is a "#", it and all subsequent
297 * characters up to, but excluding, the next newline character
298 * will be discarded as a comment. The newline character that
299 * ends the line is not considered part of the comment. The
300 * "#" starts a comment only when it is at the beginning of a
301 * token. Since the search for the end-of-comment does not
302 * consider an escaped newline character specially, a comment
303 * cannot be continued to the next line."
305 * 6) "The current character will be used as the start of a new word."
308 * - for each token (word), perform portions of word expansion, namely
309 * field splitting (using default whitespace IFS) and quote
310 * removal. Field splitting may increase the number of words.
311 * Quote removal does not increase the number of words.
313 * "If the complete expansion appropriate for a word results in an
314 * empty field, that empty field will be deleted from the list of
315 * fields that form the completely expanded command, unless the
316 * original word contained single-quote or double-quote characters."
323 delimit_token (DBusString *token,
329 str = _dbus_strdup (_dbus_string_get_data (token));
332 _DBUS_SET_OOM (error);
336 if (!_dbus_list_append (retval, str))
339 _DBUS_SET_OOM (error);
347 tokenize_command_line (const char *command_line, DBusError *error)
351 DBusString current_token;
352 DBusList *retval = NULL;
355 current_quote = '\0';
359 if (!_dbus_string_init (¤t_token))
361 _DBUS_SET_OOM (error);
367 if (current_quote == '\\')
371 /* we append nothing; backslash-newline become nothing */
375 if (!_dbus_string_append_byte (¤t_token, '\\') ||
376 !_dbus_string_append_byte (¤t_token, *p))
378 _DBUS_SET_OOM (error);
383 current_quote = '\0';
385 else if (current_quote == '#')
387 /* Discard up to and including next newline */
388 while (*p && *p != '\n')
391 current_quote = '\0';
396 else if (current_quote)
398 if (*p == current_quote &&
399 /* check that it isn't an escaped double quote */
400 !(current_quote == '"' && quoted))
402 /* close the quote */
403 current_quote = '\0';
406 /* Everything inside quotes, and the close quote,
407 * gets appended literally.
410 if (!_dbus_string_append_byte (¤t_token, *p))
412 _DBUS_SET_OOM (error);
421 if (!delimit_token (¤t_token, &retval, error))
424 _dbus_string_free (¤t_token);
426 if (!_dbus_string_init (¤t_token))
428 _DBUS_SET_OOM (error);
436 /* If the current token contains the previous char, delimit
437 * the current token. A nonzero length
438 * token should always contain the previous char.
440 if (_dbus_string_get_length (¤t_token) > 0)
442 if (!delimit_token (¤t_token, &retval, error))
445 _dbus_string_free (¤t_token);
447 if (!_dbus_string_init (¤t_token))
449 _DBUS_SET_OOM (error);
455 /* discard all unquoted blanks (don't add them to a token) */
459 /* single/double quotes are appended to the token,
460 * escapes are maybe appended next time through the loop,
461 * comment chars are never appended.
466 if (!_dbus_string_append_byte (¤t_token, *p))
468 _DBUS_SET_OOM (error);
480 /* Combines rules 4) and 6) - if we have a token, append to it,
481 * otherwise create a new token.
483 if (!_dbus_string_append_byte (¤t_token, *p))
485 _DBUS_SET_OOM (error);
492 /* We need to count consecutive backslashes mod 2,
493 * to detect escaped doublequotes.
503 if (!delimit_token (¤t_token, &retval, error))
508 dbus_set_error_const (error, DBUS_ERROR_INVALID_ARGS, "Unclosed quotes in command line");
514 dbus_set_error_const (error, DBUS_ERROR_INVALID_ARGS, "No tokens found in command line");
518 _dbus_string_free (¤t_token);
523 _dbus_string_free (¤t_token);
528 _dbus_list_foreach (&retval, (DBusForeachFunction) dbus_free, NULL);
529 _dbus_list_clear (&retval);
536 * _dbus_shell_parse_argv:
538 * Parses a command line into an argument vector, in much the same way
539 * the shell would, but without many of the expansions the shell would
540 * perform (variable expansion, globs, operators, filename expansion,
541 * etc. are not supported). The results are defined to be the same as
542 * those you would get from a UNIX98 /bin/sh, as long as the input
543 * contains none of the unsupported shell expansions. If the input
544 * does contain such expansions, they are passed through
545 * literally. Free the returned vector with dbus_free_string_array().
547 * @command_line: command line to parse
548 * @argcp: return location for number of args
549 * @argvp: return location for array of args
550 * @error: error information
553 _dbus_shell_parse_argv (const char *command_line,
558 /* Code based on poptParseArgvString() from libpopt */
561 DBusList *tokens = NULL;
567 _dbus_verbose ("Command line is NULL\n");
571 tokens = tokenize_command_line (command_line, error);
574 _dbus_verbose ("No tokens for command line '%s'\n", command_line);
578 /* Because we can't have introduced any new blank space into the
579 * tokens (we didn't do any new expansions), we don't need to
580 * perform field splitting. If we were going to honor IFS or do any
581 * expansions, we would have to do field splitting on each word
582 * here. Also, if we were going to do any expansion we would need to
583 * remove any zero-length words that didn't contain quotes
584 * originally; but since there's no expansion we know all words have
585 * nonzero length, unless they contain quotes.
587 * So, we simply remove quotes, and don't do any field splitting or
588 * empty word removal, since we know there was no way to introduce
592 argc = _dbus_list_get_length (&tokens);
593 argv = dbus_new (char *, argc + 1);
596 _DBUS_SET_OOM (error);
604 argv[i] = _dbus_shell_unquote (tmp_list->data);
609 for (j = 0; j < i; j++)
613 _DBUS_SET_OOM (error);
617 tmp_list = _dbus_list_get_next_link (&tokens, tmp_list);
622 _dbus_list_foreach (&tokens, (DBusForeachFunction) dbus_free, NULL);
623 _dbus_list_clear (&tokens);
631 dbus_free_string_array (argv);
636 _dbus_list_foreach (&tokens, (DBusForeachFunction) dbus_free, NULL);
637 _dbus_list_clear (&tokens);