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