Merge branch 'fd-passing'
[platform/upstream/dbus.git] / dbus / dbus-shell.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-shell.c Shell command line utility functions.
3  *
4  * Copyright (C) 2002, 2003  Red Hat, Inc.
5  * Copyright (C) 2003 CodeFactory AB
6  *
7  * Licensed under the Academic Free License version 2.1
8  *
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.
13  *
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.
18  *
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
22  *
23  */
24
25 #include <string.h>
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"
32
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'
36  *
37  * Double quotes allow $ ` " \ and newline to be escaped with backslash.
38  * Otherwise double quotes preserve things literally.
39  */
40
41 static dbus_bool_t
42 unquote_string_inplace (char* str, char** end)
43 {
44   char* dest;
45   char* s;
46   char quote_char;
47   
48   dest = s = str;
49
50   quote_char = *s;
51   
52   if (!(*s == '"' || *s == '\''))
53     {
54       *end = str;
55       return FALSE;
56     }
57
58   /* Skip the initial quote mark */
59   ++s;
60
61   if (quote_char == '"')
62     {
63       while (*s)
64         {
65           _dbus_assert(s > dest); /* loop invariant */
66       
67           switch (*s)
68             {
69             case '"':
70               /* End of the string, return now */
71               *dest = '\0';
72               ++s;
73               *end = s;
74               return TRUE;
75
76             case '\\':
77               /* Possible escaped quote or \ */
78               ++s;
79               switch (*s)
80                 {
81                 case '"':
82                 case '\\':
83                 case '`':
84                 case '$':
85                 case '\n':
86                   *dest = *s;
87                   ++s;
88                   ++dest;
89                   break;
90
91                 default:
92                   /* not an escaped char */
93                   *dest = '\\';
94                   ++dest;
95                   /* ++s already done. */
96                   break;
97                 }
98               break;
99
100             default:
101               *dest = *s;
102               ++dest;
103               ++s;
104               break;
105             }
106
107           _dbus_assert(s > dest); /* loop invariant */
108         }
109     }
110   else
111     {
112       while (*s)
113         {
114           _dbus_assert(s > dest); /* loop invariant */
115           
116           if (*s == '\'')
117             {
118               /* End of the string, return now */
119               *dest = '\0';
120               ++s;
121               *end = s;
122               return TRUE;
123             }
124           else
125             {
126               *dest = *s;
127               ++dest;
128               ++s;
129             }
130
131           _dbus_assert(s > dest); /* loop invariant */
132         }
133     }
134   
135   /* If we reach here this means the close quote was never encountered */
136
137   *dest = '\0';
138   
139   *end = s;
140   return FALSE;
141 }
142
143 /** 
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().
157  * 
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
163  * literally.
164  *
165  * @quoted_string: shell-quoted string
166  **/
167 char*
168 _dbus_shell_unquote (const char *quoted_string)
169 {
170   char *unquoted;
171   char *end;
172   char *start;
173   char *ret;
174   DBusString retval;
175
176   unquoted = _dbus_strdup (quoted_string);
177   if (unquoted == NULL)
178     return NULL;
179
180   start = unquoted;
181   end = unquoted;
182   if (!_dbus_string_init (&retval))
183     {
184       dbus_free (unquoted);
185       return NULL;
186     }
187
188   /* The loop allows cases such as
189    * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
190    */
191   while (*start)
192     {
193       /* Append all non-quoted chars, honoring backslash escape
194        */
195       
196       while (*start && !(*start == '"' || *start == '\''))
197         {
198           if (*start == '\\')
199             {
200               /* all characters can get escaped by backslash,
201                * except newline, which is removed if it follows
202                * a backslash outside of quotes
203                */
204               
205               ++start;
206               if (*start)
207                 {
208                   if (*start != '\n')
209                     {
210                       if (!_dbus_string_append_byte (&retval, *start))
211                         goto error;
212                     }
213                   ++start;
214                 }
215             }
216           else
217             {
218               if (!_dbus_string_append_byte (&retval, *start))
219                 goto error;
220               ++start;
221             }
222         }
223
224       if (*start)
225         {
226           if (!unquote_string_inplace (start, &end))
227             goto error;
228           else
229             {
230               if (!_dbus_string_append (&retval, start))
231                 goto error;
232               start = end;
233             }
234         }
235     }
236
237   ret = _dbus_strdup (_dbus_string_get_data (&retval));
238   if (!ret)
239     goto error;
240
241   dbus_free (unquoted);
242   _dbus_string_free (&retval);
243   
244   return ret;
245   
246  error:
247   dbus_free (unquoted);
248   _dbus_string_free (&retval);
249   return NULL;
250 }
251
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.
257  *
258  * READ THE UNIX98 SPEC on "Shell Command Language" before changing
259  * the behavior of this code.
260  *
261  * Steps to parsing the argv string:
262  *
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?)
269  *
270  *    Tokenization steps, from UNIX98 with operator stuff removed,
271  *    are:
272  * 
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."
284  *
285  *    2) "If the current character is an unquoted newline character,
286  *        the current token will be delimited."
287  *
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."
291  *
292  *    4) "If the previous character was part of a word, the current
293  *        character will be appended to that word."
294  *
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."
303  *
304  *    6) "The current character will be used as the start of a new word."
305  *
306  *
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.
311  *
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."
316  *    - UNIX98 spec
317  *
318  *
319  */
320
321 static dbus_bool_t
322 delimit_token (DBusString *token,
323                DBusList **retval,
324                DBusError *error)
325 {
326   char *str;
327
328   str = _dbus_strdup (_dbus_string_get_data (token));
329   if (!str)
330     {
331       _DBUS_SET_OOM (error);
332       return FALSE;
333     }
334
335   if (!_dbus_list_append (retval, str))
336     {
337       dbus_free (str);
338       _DBUS_SET_OOM (error);
339       return FALSE;
340     }
341
342   return TRUE;
343 }
344
345 static DBusList*
346 tokenize_command_line (const char *command_line, DBusError *error)
347 {
348   char current_quote;
349   const char *p;
350   DBusString current_token;
351   DBusList *retval = NULL;
352   dbus_bool_t quoted;;
353
354   current_quote = '\0';
355   quoted = FALSE;
356   p = command_line;
357
358   if (!_dbus_string_init (&current_token))
359     {
360       _DBUS_SET_OOM (error);
361       return NULL;
362     }
363
364   while (*p)
365     {
366       if (current_quote == '\\')
367         {
368           if (*p == '\n')
369             {
370               /* we append nothing; backslash-newline become nothing */
371             }
372           else
373             {
374               if (!_dbus_string_append_byte (&current_token, '\\') || 
375                   !_dbus_string_append_byte (&current_token, *p))
376                 {
377                   _DBUS_SET_OOM (error);
378                   goto error;
379                 }
380             }
381
382           current_quote = '\0';
383         }
384       else if (current_quote == '#')
385         {
386           /* Discard up to and including next newline */
387           while (*p && *p != '\n')
388             ++p;
389
390           current_quote = '\0';
391           
392           if (*p == '\0')
393             break;
394         }
395       else if (current_quote)
396         {
397           if (*p == current_quote &&
398               /* check that it isn't an escaped double quote */
399               !(current_quote == '"' && quoted))
400             {
401               /* close the quote */
402               current_quote = '\0';
403             }
404
405           /* Everything inside quotes, and the close quote,
406            * gets appended literally.
407            */
408
409           if (!_dbus_string_append_byte (&current_token, *p))
410             {
411               _DBUS_SET_OOM (error);
412               goto error;
413             }
414         }
415       else
416         {
417           switch (*p)
418             {
419             case '\n':
420               if (!delimit_token (&current_token, &retval, error))
421                 goto error;
422
423                 _dbus_string_free (&current_token);
424
425                 if (!_dbus_string_init (&current_token))
426                   {
427                     _DBUS_SET_OOM (error);
428                     goto init_error;
429                   }
430
431               break;
432
433             case ' ':
434             case '\t':
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.
438                */
439               if (_dbus_string_get_length (&current_token) > 0)
440                 {
441                   if (!delimit_token (&current_token, &retval, error))
442                     goto error;
443
444                   _dbus_string_free (&current_token);
445
446                   if (!_dbus_string_init (&current_token))
447                     {
448                       _DBUS_SET_OOM (error);
449                       goto init_error;
450                     }
451
452                 }
453               
454               /* discard all unquoted blanks (don't add them to a token) */
455               break;
456
457
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.
461                */
462               
463             case '\'':
464             case '"':
465               if (!_dbus_string_append_byte (&current_token, *p))
466                 {
467                   _DBUS_SET_OOM (error);
468                   goto error;
469                 }
470
471               /* FALL THRU */
472               
473             case '#':
474             case '\\':
475               current_quote = *p;
476               break;
477
478             default:
479               /* Combines rules 4) and 6) - if we have a token, append to it,
480                * otherwise create a new token.
481                */
482               if (!_dbus_string_append_byte (&current_token, *p))
483                 {
484                   _DBUS_SET_OOM (error);
485                   goto error;
486                 }
487               break;
488             }
489         }
490
491       /* We need to count consecutive backslashes mod 2, 
492        * to detect escaped doublequotes.
493        */
494       if (*p != '\\')
495         quoted = FALSE;
496       else
497         quoted = !quoted;
498
499       ++p;
500     }
501
502   if (!delimit_token (&current_token, &retval, error))
503     goto error;
504
505   if (current_quote)
506     {
507       dbus_set_error_const (error, DBUS_ERROR_INVALID_ARGS, "Unclosed quotes in command line");
508       goto error;
509     }
510
511   if (retval == NULL)
512     {
513       dbus_set_error_const (error, DBUS_ERROR_INVALID_ARGS, "No tokens found in command line");
514       goto error;
515     }
516  
517   _dbus_string_free (&current_token);
518  
519   return retval;
520
521  error:
522   _dbus_string_free (&current_token);
523
524  init_error:
525   if (retval)
526     {
527       _dbus_list_foreach (&retval, (DBusForeachFunction) dbus_free, NULL);
528       _dbus_list_clear (&retval);
529     }
530
531   return NULL;
532 }
533
534 /**
535  * _dbus_shell_parse_argv:
536  * 
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().
545  * 
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
550  **/
551 dbus_bool_t
552 _dbus_shell_parse_argv (const char *command_line,
553                         int        *argcp,
554                         char     ***argvp,
555                         DBusError  *error)
556 {
557   /* Code based on poptParseArgvString() from libpopt */
558   int argc = 0;
559   char **argv = NULL;
560   DBusList *tokens = NULL;
561   int i;
562   DBusList *tmp_list;
563   
564   if (!command_line)
565     {
566       _dbus_verbose ("Command line is NULL\n");
567       return FALSE;
568     }
569
570   tokens = tokenize_command_line (command_line, error);
571   if (tokens == NULL)
572     {
573       _dbus_verbose ("No tokens for command line '%s'\n", command_line);
574       return FALSE;
575     }
576
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.
585    * 
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
588    * such things.
589    */
590
591   argc = _dbus_list_get_length (&tokens);
592   argv = dbus_new (char *, argc + 1);
593   if (!argv)
594     {
595       _DBUS_SET_OOM (error);
596       goto error;
597     }
598
599   i = 0;
600   tmp_list = tokens;
601   while (tmp_list)
602     {
603       argv[i] = _dbus_shell_unquote (tmp_list->data);
604
605       if (!argv[i])
606         {
607           int j;
608           for (j = 0; j < i; j++)
609             dbus_free(argv[j]);
610
611           dbus_free (argv);
612           _DBUS_SET_OOM (error);
613           goto error;
614         }
615
616       tmp_list = _dbus_list_get_next_link (&tokens, tmp_list);
617       ++i;
618     }
619   argv[argc] = NULL;
620   
621   _dbus_list_foreach (&tokens, (DBusForeachFunction) dbus_free, NULL);
622   _dbus_list_clear (&tokens);
623   
624   if (argcp)
625     *argcp = argc;
626
627   if (argvp)
628     *argvp = argv;
629   else
630     dbus_free_string_array (argv);
631
632   return TRUE;
633
634  error:
635   _dbus_list_foreach (&tokens, (DBusForeachFunction) dbus_free, NULL);
636   _dbus_list_clear (&tokens);
637
638   return FALSE;
639
640 }