moved warning to error pragmas to their own file to not force 'good
[platform/upstream/glib.git] / glib / gshell.c
1 /* gshell.c - Shell-related utilities
2  *
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.
6  *
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.
11  *
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.
16  *
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.
21  */
22
23 #include "glib.h"
24 #include <string.h>
25
26 #ifdef _
27 #warning "FIXME remove gettext hack"
28 #endif
29
30 #include "glibintl.h"
31
32 GQuark
33 g_shell_error_quark (void)
34 {
35   static GQuark quark = 0;
36   if (quark == 0)
37     quark = g_quark_from_static_string ("g-shell-error-quark");
38   return quark;
39 }
40
41 /* Single quotes preserve the literal string exactly. escape
42  * sequences are not allowed; not even \' - if you want a '
43  * in the quoted text, you have to do something like 'foo'\''bar'
44  *
45  * Double quotes allow $ ` " \ and newline to be escaped with backslash.
46  * Otherwise double quotes preserve things literally.
47  */
48
49 static gboolean 
50 unquote_string_inplace (gchar* str, gchar** end, GError** err)
51 {
52   gchar* dest;
53   gchar* s;
54   gchar quote_char;
55   
56   g_return_val_if_fail(end != NULL, FALSE);
57   g_return_val_if_fail(err == NULL || *err == NULL, FALSE);
58   g_return_val_if_fail(str != NULL, FALSE);
59   
60   dest = s = str;
61
62   quote_char = *s;
63   
64   if (!(*s == '"' || *s == '\''))
65     {
66       if (err)
67         *err = g_error_new(G_SHELL_ERROR,
68                            G_SHELL_ERROR_BAD_QUOTING,
69                            _("Quoted text doesn't begin with a quotation mark"));
70       *end = str;
71       return FALSE;
72     }
73
74   /* Skip the initial quote mark */
75   ++s;
76
77   if (quote_char == '"')
78     {
79       while (*s)
80         {
81           g_assert(s > dest); /* loop invariant */
82       
83           switch (*s)
84             {
85             case '"':
86               /* End of the string, return now */
87               *dest = '\0';
88               ++s;
89               *end = s;
90               return TRUE;
91               break;
92
93             case '\\':
94               /* Possible escaped quote or \ */
95               ++s;
96               switch (*s)
97                 {
98                 case '"':
99                 case '\\':
100                 case '`':
101                 case '$':
102                 case '\n':
103                   *dest = *s;
104                   ++s;
105                   ++dest;
106                   break;
107
108                 default:
109                   /* not an escaped char */
110                   *dest = '\\';
111                   ++dest;
112                   /* ++s already done. */
113                   break;
114                 }
115               break;
116
117             default:
118               *dest = *s;
119               ++dest;
120               ++s;
121               break;
122             }
123
124           g_assert(s > dest); /* loop invariant */
125         }
126     }
127   else
128     {
129       while (*s)
130         {
131           g_assert(s > dest); /* loop invariant */
132           
133           if (*s == '\'')
134             {
135               /* End of the string, return now */
136               *dest = '\0';
137               ++s;
138               *end = s;
139               return TRUE;
140             }
141           else
142             {
143               *dest = *s;
144               ++dest;
145               ++s;
146             }
147
148           g_assert(s > dest); /* loop invariant */
149         }
150     }
151   
152   /* If we reach here this means the close quote was never encountered */
153
154   *dest = '\0';
155   
156   if (err)
157     *err = g_error_new(G_SHELL_ERROR,
158                        G_SHELL_ERROR_BAD_QUOTING,
159                        _("Unmatched quotation mark in command line or other shell-quoted text"));
160   *end = s;
161   return FALSE;
162 }
163
164 /**
165  * g_shell_quote:
166  * @unquoted_string: a literal string
167  * 
168  * Quotes a string so that the shell (/bin/sh) will interpret the
169  * quoted string to mean @unquoted_string. If you pass a filename to
170  * the shell, for example, you should first quote it with this
171  * function.  The return value must be freed with g_free(). The
172  * quoting style used is undefined (single or double quotes may be
173  * used).
174  * 
175  * Return value: quoted string
176  **/
177 gchar*
178 g_shell_quote (const gchar *unquoted_string)
179 {
180   /* We always use single quotes, because the algorithm is cheesier.
181    * We could use double if we felt like it, that might be more
182    * human-readable.
183    */
184
185   const gchar *p;
186   GString *dest;
187
188   g_return_val_if_fail (unquoted_string != NULL, NULL);
189   
190   dest = g_string_new ("'");
191
192   p = unquoted_string;
193
194   /* could speed this up a lot by appending chunks of text at a
195    * time.
196    */
197   while (*p)
198     {
199       /* Replace literal ' with a close ', a \', and a open ' */
200       if (*p == '\'')
201         g_string_append (dest, "'\\''");
202       else
203         g_string_append_c (dest, *p);
204
205       ++p;
206     }
207
208   /* close the quote */
209   g_string_append_c (dest, '\'');
210   
211   return g_string_free (dest, FALSE);
212 }
213
214 /**
215  * g_shell_unquote:
216  * @quoted_string: shell-quoted string
217  * @error: error return location or NULL
218  * 
219  * Unquotes a string as the shell (/bin/sh) would. Only handles
220  * quotes; if a string contains file globs, arithmetic operators,
221  * variables, backticks, redirections, or other special-to-the-shell
222  * features, the result will be different from the result a real shell
223  * would produce (the variables, backticks, etc. will be passed
224  * through literally instead of being expanded). This function is
225  * guaranteed to succeed if applied to the result of
226  * g_shell_quote(). If it fails, it returns %NULL and sets the
227  * error. The @quoted_string need not actually contain quoted or
228  * escaped text; g_shell_unquote() simply goes through the string and
229  * unquotes/unescapes anything that the shell would. Both single and
230  * double quotes are handled, as are escapes including escaped
231  * newlines. The return value must be freed with g_free(). Possible
232  * errors are in the #G_SHELL_ERROR domain.
233  * 
234  * Shell quoting rules are a bit strange. Single quotes preserve the
235  * literal string exactly. escape sequences are not allowed; not even
236  * \' - if you want a ' in the quoted text, you have to do something
237  * like 'foo'\''bar'.  Double quotes allow $, `, ", \, and newline to
238  * be escaped with backslash. Otherwise double quotes preserve things
239  * literally.
240  *
241  * Return value: an unquoted string
242  **/
243 gchar*
244 g_shell_unquote (const gchar *quoted_string,
245                  GError     **error)
246 {
247   gchar *unquoted;
248   gchar *end;
249   gchar *start;
250   GString *retval;
251   
252   g_return_val_if_fail (quoted_string != NULL, NULL);
253   
254   unquoted = g_strdup (quoted_string);
255
256   start = unquoted;
257   end = unquoted;
258   retval = g_string_new ("");
259
260   /* The loop allows cases such as
261    * "foo"blah blah'bar'woo foo"baz"la la la\'\''foo'
262    */
263   while (*start)
264     {
265       /* Append all non-quoted chars, honoring backslash escape
266        */
267       
268       while (*start && !(*start == '"' || *start == '\''))
269         {
270           if (*start == '\\')
271             {
272               /* all characters can get escaped by backslash,
273                * except newline, which is removed if it follows
274                * a backslash outside of quotes
275                */
276               
277               ++start;
278               if (*start)
279                 {
280                   if (*start != '\n')
281                     g_string_append_c (retval, *start);
282                   ++start;
283                 }
284             }
285           else
286             {
287               g_string_append_c (retval, *start);
288               ++start;
289             }
290         }
291
292       if (*start)
293         {
294           if (!unquote_string_inplace (start, &end, error))
295             {
296               goto error;
297             }
298           else
299             {
300               g_string_append (retval, start);
301               start = end;
302             }
303         }
304     }
305
306   return g_string_free (retval, FALSE);
307   
308  error:
309   g_assert (error == NULL || *error != NULL);
310   
311   g_free (unquoted);
312   g_string_free (retval, TRUE);
313   return NULL;
314 }
315
316 /* g_parse_argv() does a semi-arbitrary weird subset of the way
317  * the shell parses a command line. We don't do variable expansion,
318  * don't understand that operators are tokens, don't do tilde expansion,
319  * don't do command substitution, no arithmetic expansion, IFS gets ignored,
320  * don't do filename globs, don't remove redirection stuff, etc.
321  *
322  * READ THE UNIX98 SPEC on "Shell Command Language" before changing
323  * the behavior of this code.
324  *
325  * Steps to parsing the argv string:
326  *
327  *  - tokenize the string (but since we ignore operators,
328  *    our tokenization may diverge from what the shell would do)
329  *    note that tokenization ignores the internals of a quoted
330  *    word and it always splits on spaces, not on IFS even
331  *    if we used IFS. We also ignore "end of input indicator"
332  *    (I guess this is control-D?)
333  *
334  *    Tokenization steps, from UNIX98 with operator stuff removed,
335  *    are:
336  * 
337  *    1) "If the current character is backslash, single-quote or
338  *        double-quote (\, ' or ") and it is not quoted, it will affect
339  *        quoting for subsequent characters up to the end of the quoted
340  *        text. The rules for quoting are as described in Quoting
341  *        . During token recognition no substitutions will be actually
342  *        performed, and the result token will contain exactly the
343  *        characters that appear in the input (except for newline
344  *        character joining), unmodified, including any embedded or
345  *        enclosing quotes or substitution operators, between the quote
346  *        mark and the end of the quoted text. The token will not be
347  *        delimited by the end of the quoted field."
348  *
349  *    2) "If the current character is an unquoted newline character,
350  *        the current token will be delimited."
351  *
352  *    3) "If the current character is an unquoted blank character, any
353  *        token containing the previous character is delimited and the
354  *        current character will be discarded."
355  *
356  *    4) "If the previous character was part of a word, the current
357  *        character will be appended to that word."
358  *
359  *    5) "If the current character is a "#", it and all subsequent
360  *        characters up to, but excluding, the next newline character
361  *        will be discarded as a comment. The newline character that
362  *        ends the line is not considered part of the comment. The
363  *        "#" starts a comment only when it is at the beginning of a
364  *        token. Since the search for the end-of-comment does not
365  *        consider an escaped newline character specially, a comment
366  *        cannot be continued to the next line."
367  *
368  *    6) "The current character will be used as the start of a new word."
369  *
370  *
371  *  - for each token (word), perform portions of word expansion, namely
372  *    field splitting (using default whitespace IFS) and quote
373  *    removal.  Field splitting may increase the number of words.
374  *    Quote removal does not increase the number of words.
375  *
376  *   "If the complete expansion appropriate for a word results in an
377  *   empty field, that empty field will be deleted from the list of
378  *   fields that form the completely expanded command, unless the
379  *   original word contained single-quote or double-quote characters."
380  *    - UNIX98 spec
381  *
382  *
383  */
384
385 static inline void
386 ensure_token (GString **token)
387 {
388   if (*token == NULL)
389     *token = g_string_new ("");
390 }
391
392 static void
393 delimit_token (GString **token,
394                GSList **retval)
395 {
396   if (*token == NULL)
397     return;
398
399   *retval = g_slist_prepend (*retval, g_string_free (*token, FALSE));
400
401   *token = NULL;
402 }
403
404 static GSList*
405 tokenize_command_line (const gchar *command_line,
406                        GError **error)
407 {
408   gchar current_quote;
409   const gchar *p;
410   GString *current_token = NULL;
411   GSList *retval = NULL;
412   
413   current_quote = '\0';
414   p = command_line;
415
416   while (*p)
417     {
418       if (current_quote == '\\')
419         {
420           if (*p == '\n')
421             {
422               /* we append nothing; backslash-newline become nothing */
423             }
424           else
425             {
426               /* we append the backslash and the current char,
427                * to be interpreted later after tokenization
428                */
429               ensure_token (&current_token);
430               g_string_append_c (current_token, '\\');
431               g_string_append_c (current_token, *p);
432             }
433
434           current_quote = '\0';
435         }
436       else if (current_quote == '#')
437         {
438           /* Discard up to and including next newline */
439           while (*p && *p != '\n')
440             ++p;
441
442           current_quote = '\0';
443           
444           if (*p == '\0')
445             break;
446         }
447       else if (current_quote)
448         {
449           if (*p == current_quote &&
450               /* check that it isn't an escaped double quote */
451               !(current_quote == '"' && p != command_line && *(p - 1) == '\\'))
452             {
453               /* close the quote */
454               current_quote = '\0';
455             }
456
457           /* Everything inside quotes, and the close quote,
458            * gets appended literally.
459            */
460
461           ensure_token (&current_token);
462           g_string_append_c (current_token, *p);
463         }
464       else
465         {
466           switch (*p)
467             {
468             case '\n':
469               delimit_token (&current_token, &retval);
470               break;
471
472             case ' ':
473             case '\t':
474               /* If the current token contains the previous char, delimit
475                * the current token. A nonzero length
476                * token should always contain the previous char.
477                */
478               if (current_token &&
479                   current_token->len > 0)
480                 {
481                   delimit_token (&current_token, &retval);
482                 }
483               
484               /* discard all unquoted blanks (don't add them to a token) */
485               break;
486
487
488               /* single/double quotes are appended to the token,
489                * escapes are maybe appended next time through the loop,
490                * comment chars are never appended.
491                */
492               
493             case '\'':
494             case '"':
495               ensure_token (&current_token);
496               g_string_append_c (current_token, *p);
497
498               /* FALL THRU */
499               
500             case '#':
501             case '\\':
502               current_quote = *p;
503               break;
504
505             default:
506               /* Combines rules 4) and 6) - if we have a token, append to it,
507                * otherwise create a new token.
508                */
509               ensure_token (&current_token);
510               g_string_append_c (current_token, *p);
511               break;
512             }
513         }
514
515       ++p;
516     }
517
518   delimit_token (&current_token, &retval);
519
520   if (current_quote)
521     {
522       if (current_quote == '\\')
523         g_set_error (error,
524                      G_SHELL_ERROR,
525                      G_SHELL_ERROR_BAD_QUOTING,
526                      _("Text ended just after a '\' character."
527                        " (The text was '%s')"),
528                      command_line);
529       else
530         g_set_error (error,
531                      G_SHELL_ERROR,
532                      G_SHELL_ERROR_BAD_QUOTING,
533                      _("Text ended before matching quote was found for %c."
534                        " (The text was '%s')"),
535                      current_quote, command_line);
536       
537       goto error;
538     }
539
540   if (retval == NULL)
541     {
542       g_set_error (error,
543                    G_SHELL_ERROR,
544                    G_SHELL_ERROR_EMPTY_STRING,
545                    _("Text was empty (or contained only whitespace)"));
546
547       goto error;
548     }
549   
550   /* we appended backward */
551   retval = g_slist_reverse (retval);
552
553   return retval;
554
555  error:
556   g_assert (error == NULL || *error != NULL);
557   
558   if (retval)
559     {
560       g_slist_foreach (retval, (GFunc)g_free, NULL);
561       g_slist_free (retval);
562     }
563
564   return NULL;
565 }
566
567 /**
568  * g_shell_parse_argv:
569  * @command_line: command line to parse
570  * @argcp: return location for number of args
571  * @argvp: return location for array of args
572  * @error: return location for error
573  * 
574  * Parses a command line into an argument vector, in much the same way
575  * the shell would, but without many of the expansions the shell would
576  * perform (variable expansion, globs, operators, filename expansion,
577  * etc. are not supported). The results are defined to be the same as
578  * those you would get from a UNIX98 /bin/sh, as long as the input
579  * contains none of the unsupported shell expansions. If the input
580  * does contain such expansions, they are passed through
581  * literally. Possible errors are those from the #G_SHELL_ERROR
582  * domain. Free the returned vector with g_strfreev().
583  * 
584  * Return value: %TRUE on success, %FALSE if error set
585  **/
586 gboolean
587 g_shell_parse_argv (const gchar *command_line,
588                     gint        *argcp,
589                     gchar     ***argvp,
590                     GError     **error)
591 {
592   /* Code based on poptParseArgvString() from libpopt */
593   gint argc = 0;
594   gchar **argv = NULL;
595   GSList *tokens = NULL;
596   gint i;
597   GSList *tmp_list;
598   
599   g_return_val_if_fail (command_line != NULL, FALSE);
600
601   tokens = tokenize_command_line (command_line, error);
602   if (tokens == NULL)
603     return FALSE;
604
605   /* Because we can't have introduced any new blank space into the
606    * tokens (we didn't do any new expansions), we don't need to
607    * perform field splitting. If we were going to honor IFS or do any
608    * expansions, we would have to do field splitting on each word
609    * here. Also, if we were going to do any expansion we would need to
610    * remove any zero-length words that didn't contain quotes
611    * originally; but since there's no expansion we know all words have
612    * nonzero length, unless they contain quotes.
613    * 
614    * So, we simply remove quotes, and don't do any field splitting or
615    * empty word removal, since we know there was no way to introduce
616    * such things.
617    */
618
619   argc = g_slist_length (tokens);
620   argv = g_new0 (gchar*, argc + 1);
621   i = 0;
622   tmp_list = tokens;
623   while (tmp_list)
624     {
625       argv[i] = g_shell_unquote (tmp_list->data, error);
626
627       /* Since we already checked that quotes matched up in the
628        * tokenizer, this shouldn't be possible to reach I guess.
629        */
630       if (argv[i] == NULL)
631         goto failed;
632
633       tmp_list = g_slist_next (tmp_list);
634       ++i;
635     }
636   
637   g_slist_foreach (tokens, (GFunc)g_free, NULL);
638   g_slist_free (tokens);
639   
640   if (argcp)
641     *argcp = argc;
642
643   if (argvp)
644     *argvp = argv;
645   else
646     g_strfreev (argv);
647
648   return TRUE;
649
650  failed:
651
652   g_assert (error == NULL || *error != NULL);
653   g_strfreev (argv);
654   g_slist_foreach (tokens, (GFunc) g_free, NULL);
655   g_slist_free (tokens);
656   
657   return FALSE;
658 }