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
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 * Unquotes a string as the shell (/bin/sh) would. Only handles
145 * quotes; if a string contains file globs, arithmetic operators,
146 * variables, backticks, redirections, or other special-to-the-shell
147 * features, the result will be different from the result a real shell
148 * would produce (the variables, backticks, etc. will be passed
149 * through literally instead of being expanded). This function is
150 * guaranteed to succeed if applied to the result of
151 * _dbus_shell_quote(). If it fails, it returns %NULL.
152 * The @quoted_string need not actually contain quoted or
153 * escaped text; _dbus_shell_unquote() simply goes through the string and
154 * unquotes/unescapes anything that the shell would. Both single and
155 * double quotes are handled, as are escapes including escaped
156 * newlines. The return value must be freed with dbus_free().
158 * Shell quoting rules are a bit strange. Single quotes preserve the
159 * literal string exactly. escape sequences are not allowed; not even
160 * \' - if you want a ' in the quoted text, you have to do something
161 * like 'foo'\''bar'. Double quotes allow $, `, ", \, and newline to
162 * be escaped with backslash. Otherwise double quotes preserve things
165 * @quoted_string: shell-quoted string
168 _dbus_shell_unquote (const char *quoted_string)
176 unquoted = _dbus_strdup (quoted_string);
177 if (unquoted == NULL)
182 if (!_dbus_string_init (&retval))
184 dbus_free (unquoted);
188 /* The loop allows cases such as
189 * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
193 /* Append all non-quoted chars, honoring backslash escape
196 while (*start && !(*start == '"' || *start == '\''))
200 /* all characters can get escaped by backslash,
201 * except newline, which is removed if it follows
202 * a backslash outside of quotes
210 if (!_dbus_string_append_byte (&retval, *start))
218 if (!_dbus_string_append_byte (&retval, *start))
226 if (!unquote_string_inplace (start, &end))
230 if (!_dbus_string_append (&retval, start))
237 ret = _dbus_strdup (_dbus_string_get_data (&retval));
241 dbus_free (unquoted);
242 _dbus_string_free (&retval);
247 dbus_free (unquoted);
248 _dbus_string_free (&retval);
252 /* _dbus_shell_parse_argv() does a semi-arbitrary weird subset of the way
253 * the shell parses a command line. We don't do variable expansion,
254 * don't understand that operators are tokens, don't do tilde expansion,
255 * don't do command substitution, no arithmetic expansion, IFS gets ignored,
256 * don't do filename globs, don't remove redirection stuff, etc.
258 * READ THE UNIX98 SPEC on "Shell Command Language" before changing
259 * the behavior of this code.
261 * Steps to parsing the argv string:
263 * - tokenize the string (but since we ignore operators,
264 * our tokenization may diverge from what the shell would do)
265 * note that tokenization ignores the internals of a quoted
266 * word and it always splits on spaces, not on IFS even
267 * if we used IFS. We also ignore "end of input indicator"
268 * (I guess this is control-D?)
270 * Tokenization steps, from UNIX98 with operator stuff removed,
273 * 1) "If the current character is backslash, single-quote or
274 * double-quote (\, ' or ") and it is not quoted, it will affect
275 * quoting for subsequent characters up to the end of the quoted
276 * text. The rules for quoting are as described in Quoting
277 * . During token recognition no substitutions will be actually
278 * performed, and the result token will contain exactly the
279 * characters that appear in the input (except for newline
280 * character joining), unmodified, including any embedded or
281 * enclosing quotes or substitution operators, between the quote
282 * mark and the end of the quoted text. The token will not be
283 * delimited by the end of the quoted field."
285 * 2) "If the current character is an unquoted newline character,
286 * the current token will be delimited."
288 * 3) "If the current character is an unquoted blank character, any
289 * token containing the previous character is delimited and the
290 * current character will be discarded."
292 * 4) "If the previous character was part of a word, the current
293 * character will be appended to that word."
295 * 5) "If the current character is a "#", it and all subsequent
296 * characters up to, but excluding, the next newline character
297 * will be discarded as a comment. The newline character that
298 * ends the line is not considered part of the comment. The
299 * "#" starts a comment only when it is at the beginning of a
300 * token. Since the search for the end-of-comment does not
301 * consider an escaped newline character specially, a comment
302 * cannot be continued to the next line."
304 * 6) "The current character will be used as the start of a new word."
307 * - for each token (word), perform portions of word expansion, namely
308 * field splitting (using default whitespace IFS) and quote
309 * removal. Field splitting may increase the number of words.
310 * Quote removal does not increase the number of words.
312 * "If the complete expansion appropriate for a word results in an
313 * empty field, that empty field will be deleted from the list of
314 * fields that form the completely expanded command, unless the
315 * original word contained single-quote or double-quote characters."
322 delimit_token (DBusString *token,
328 str = _dbus_strdup (_dbus_string_get_data (token));
331 _DBUS_SET_OOM (error);
335 if (!_dbus_list_append (retval, str))
338 _DBUS_SET_OOM (error);
346 tokenize_command_line (const char *command_line, DBusError *error)
350 DBusString current_token;
351 DBusList *retval = NULL;
354 current_quote = '\0';
358 if (!_dbus_string_init (¤t_token))
360 _DBUS_SET_OOM (error);
366 if (current_quote == '\\')
370 /* we append nothing; backslash-newline become nothing */
374 if (!_dbus_string_append_byte (¤t_token, '\\') ||
375 !_dbus_string_append_byte (¤t_token, *p))
377 _DBUS_SET_OOM (error);
382 current_quote = '\0';
384 else if (current_quote == '#')
386 /* Discard up to and including next newline */
387 while (*p && *p != '\n')
390 current_quote = '\0';
395 else if (current_quote)
397 if (*p == current_quote &&
398 /* check that it isn't an escaped double quote */
399 !(current_quote == '"' && quoted))
401 /* close the quote */
402 current_quote = '\0';
405 /* Everything inside quotes, and the close quote,
406 * gets appended literally.
409 if (!_dbus_string_append_byte (¤t_token, *p))
411 _DBUS_SET_OOM (error);
420 if (!delimit_token (¤t_token, &retval, error))
423 _dbus_string_free (¤t_token);
425 if (!_dbus_string_init (¤t_token))
427 _DBUS_SET_OOM (error);
435 /* If the current token contains the previous char, delimit
436 * the current token. A nonzero length
437 * token should always contain the previous char.
439 if (_dbus_string_get_length (¤t_token) > 0)
441 if (!delimit_token (¤t_token, &retval, error))
444 _dbus_string_free (¤t_token);
446 if (!_dbus_string_init (¤t_token))
448 _DBUS_SET_OOM (error);
454 /* discard all unquoted blanks (don't add them to a token) */
458 /* single/double quotes are appended to the token,
459 * escapes are maybe appended next time through the loop,
460 * comment chars are never appended.
465 if (!_dbus_string_append_byte (¤t_token, *p))
467 _DBUS_SET_OOM (error);
479 /* Combines rules 4) and 6) - if we have a token, append to it,
480 * otherwise create a new token.
482 if (!_dbus_string_append_byte (¤t_token, *p))
484 _DBUS_SET_OOM (error);
491 /* We need to count consecutive backslashes mod 2,
492 * to detect escaped doublequotes.
502 if (!delimit_token (¤t_token, &retval, error))
507 dbus_set_error_const (error, DBUS_ERROR_INVALID_ARGS, "Unclosed quotes in command line");
513 dbus_set_error_const (error, DBUS_ERROR_INVALID_ARGS, "No tokens found in command line");
517 _dbus_string_free (¤t_token);
522 _dbus_string_free (¤t_token);
527 _dbus_list_foreach (&retval, (DBusForeachFunction) dbus_free, NULL);
528 _dbus_list_clear (&retval);
535 * _dbus_shell_parse_argv:
537 * Parses a command line into an argument vector, in much the same way
538 * the shell would, but without many of the expansions the shell would
539 * perform (variable expansion, globs, operators, filename expansion,
540 * etc. are not supported). The results are defined to be the same as
541 * those you would get from a UNIX98 /bin/sh, as long as the input
542 * contains none of the unsupported shell expansions. If the input
543 * does contain such expansions, they are passed through
544 * literally. Free the returned vector with dbus_free_string_array().
546 * @command_line: command line to parse
547 * @argcp: return location for number of args
548 * @argvp: return location for array of args
549 * @error: error information
552 _dbus_shell_parse_argv (const char *command_line,
557 /* Code based on poptParseArgvString() from libpopt */
560 DBusList *tokens = NULL;
566 _dbus_verbose ("Command line is NULL\n");
570 tokens = tokenize_command_line (command_line, error);
573 _dbus_verbose ("No tokens for command line '%s'\n", command_line);
577 /* Because we can't have introduced any new blank space into the
578 * tokens (we didn't do any new expansions), we don't need to
579 * perform field splitting. If we were going to honor IFS or do any
580 * expansions, we would have to do field splitting on each word
581 * here. Also, if we were going to do any expansion we would need to
582 * remove any zero-length words that didn't contain quotes
583 * originally; but since there's no expansion we know all words have
584 * nonzero length, unless they contain quotes.
586 * So, we simply remove quotes, and don't do any field splitting or
587 * empty word removal, since we know there was no way to introduce
591 argc = _dbus_list_get_length (&tokens);
592 argv = dbus_new (char *, argc + 1);
595 _DBUS_SET_OOM (error);
603 argv[i] = _dbus_shell_unquote (tmp_list->data);
608 for (j = 0; j < i; j++)
612 _DBUS_SET_OOM (error);
616 tmp_list = _dbus_list_get_next_link (&tokens, tmp_list);
621 _dbus_list_foreach (&tokens, (DBusForeachFunction) dbus_free, NULL);
622 _dbus_list_clear (&tokens);
630 dbus_free_string_array (argv);
635 _dbus_list_foreach (&tokens, (DBusForeachFunction) dbus_free, NULL);
636 _dbus_list_clear (&tokens);