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