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