f9628e5fa743e43f5c2d69cc03c69337c7afae5f
[gnulib.git] / lib / quotearg.c
1 /* quotearg.c - quote arguments for output
2
3    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006, 2007,
4    2008 Free Software Foundation, Inc.
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 /* Written by Paul Eggert <eggert@twinsun.com> */
20
21 #include <config.h>
22
23 #include "quotearg.h"
24
25 #include "xalloc.h"
26
27 #include <ctype.h>
28 #include <errno.h>
29 #include <limits.h>
30 #include <stdbool.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <wchar.h>
34 #include <wctype.h>
35
36 #include "gettext.h"
37 #define _(msgid) gettext (msgid)
38 #define N_(msgid) msgid
39
40 #if !HAVE_MBRTOWC
41 /* Disable multibyte processing entirely.  Since MB_CUR_MAX is 1, the
42    other macros are defined only for documentation and to satisfy C
43    syntax.  */
44 # undef MB_CUR_MAX
45 # define MB_CUR_MAX 1
46 # undef mbstate_t
47 # define mbstate_t int
48 # define mbrtowc(pwc, s, n, ps) ((*(pwc) = *(s)) != 0)
49 # define iswprint(wc) isprint ((unsigned char) (wc))
50 # undef HAVE_MBSINIT
51 #endif
52
53 #if !defined mbsinit && !HAVE_MBSINIT
54 # define mbsinit(ps) 1
55 #endif
56
57 #ifndef SIZE_MAX
58 # define SIZE_MAX ((size_t) -1)
59 #endif
60
61 #define INT_BITS (sizeof (int) * CHAR_BIT)
62
63 struct quoting_options
64 {
65   /* Basic quoting style.  */
66   enum quoting_style style;
67
68   /* Additional flags.  Behavior is altered according to these bits:
69      0x01: Elide null bytes rather than embed them unquoted.
70    */
71   int flags;
72
73   /* Quote the characters indicated by this bit vector even if the
74      quoting style would not normally require them to be quoted.  */
75   unsigned int quote_these_too[(UCHAR_MAX / INT_BITS) + 1];
76 };
77
78 /* Names of quoting styles.  */
79 char const *const quoting_style_args[] =
80 {
81   "literal",
82   "shell",
83   "shell-always",
84   "c",
85   "escape",
86   "locale",
87   "clocale",
88   0
89 };
90
91 /* Correspondences to quoting style names.  */
92 enum quoting_style const quoting_style_vals[] =
93 {
94   literal_quoting_style,
95   shell_quoting_style,
96   shell_always_quoting_style,
97   c_quoting_style,
98   escape_quoting_style,
99   locale_quoting_style,
100   clocale_quoting_style
101 };
102
103 /* The default quoting options.  */
104 static struct quoting_options default_quoting_options;
105
106 /* Allocate a new set of quoting options, with contents initially identical
107    to O if O is not null, or to the default if O is null.
108    It is the caller's responsibility to free the result.  */
109 struct quoting_options *
110 clone_quoting_options (struct quoting_options *o)
111 {
112   int e = errno;
113   struct quoting_options *p = xmemdup (o ? o : &default_quoting_options,
114                                        sizeof *o);
115   errno = e;
116   return p;
117 }
118
119 /* Get the value of O's quoting style.  If O is null, use the default.  */
120 enum quoting_style
121 get_quoting_style (struct quoting_options *o)
122 {
123   return (o ? o : &default_quoting_options)->style;
124 }
125
126 /* In O (or in the default if O is null),
127    set the value of the quoting style to S.  */
128 void
129 set_quoting_style (struct quoting_options *o, enum quoting_style s)
130 {
131   (o ? o : &default_quoting_options)->style = s;
132 }
133
134 /* In O (or in the default if O is null),
135    set the value of the quoting options for character C to I.
136    Return the old value.  Currently, the only values defined for I are
137    0 (the default) and 1 (which means to quote the character even if
138    it would not otherwise be quoted).  */
139 int
140 set_char_quoting (struct quoting_options *o, char c, int i)
141 {
142   unsigned char uc = c;
143   unsigned int *p =
144     (o ? o : &default_quoting_options)->quote_these_too + uc / INT_BITS;
145   int shift = uc % INT_BITS;
146   int r = (*p >> shift) & 1;
147   *p ^= ((i & 1) ^ r) << shift;
148   return r;
149 }
150
151 /* In O (or in the default if O is null),
152    set the value of the quoting options flag to I.
153    Return the old value.  Currently, the only values defined for I are
154    0 (the default) and 1 (which means to elide null bytes from styles
155    that would otherwise output them unquoted).  */
156 int
157 set_quoting_flags (struct quoting_options *o, int i)
158 {
159   int r;
160   if (!o)
161     o = &default_quoting_options;
162   r = o->flags;
163   o->flags = i;
164   return r;
165 }
166
167 /* MSGID approximates a quotation mark.  Return its translation if it
168    has one; otherwise, return either it or "\"", depending on S.  */
169 static char const *
170 gettext_quote (char const *msgid, enum quoting_style s)
171 {
172   char const *translation = _(msgid);
173   if (translation == msgid && s == clocale_quoting_style)
174     translation = "\"";
175   return translation;
176 }
177
178 /* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of
179    argument ARG (of size ARGSIZE), using QUOTING_STYLE, FLAGS, and the
180    remaining part of O to control quoting.
181    Terminate the output with a null character, and return the written
182    size of the output, not counting the terminating null.
183    If BUFFERSIZE is too small to store the output string, return the
184    value that would have been returned had BUFFERSIZE been large enough.
185    If ARGSIZE is SIZE_MAX, use the string length of the argument for ARGSIZE.
186
187    This function acts like quotearg_buffer (BUFFER, BUFFERSIZE, ARG,
188    ARGSIZE, O), except it uses QUOTING_STYLE and FLAGS instead of the
189    quoting style specified by O, and O may not be null.  */
190
191 static size_t
192 quotearg_buffer_restyled (char *buffer, size_t buffersize,
193                           char const *arg, size_t argsize,
194                           enum quoting_style quoting_style, int flags,
195                           struct quoting_options const *o)
196 {
197   size_t i;
198   size_t len = 0;
199   char const *quote_string = 0;
200   size_t quote_string_len = 0;
201   bool backslash_escapes = false;
202   bool unibyte_locale = MB_CUR_MAX == 1;
203
204 #define STORE(c) \
205     do \
206       { \
207         if (len < buffersize) \
208           buffer[len] = (c); \
209         len++; \
210       } \
211     while (0)
212
213   switch (quoting_style)
214     {
215     case c_quoting_style:
216       STORE ('"');
217       backslash_escapes = true;
218       quote_string = "\"";
219       quote_string_len = 1;
220       break;
221
222     case escape_quoting_style:
223       backslash_escapes = true;
224       break;
225
226     case locale_quoting_style:
227     case clocale_quoting_style:
228       {
229         /* TRANSLATORS:
230            Get translations for open and closing quotation marks.
231
232            The message catalog should translate "`" to a left
233            quotation mark suitable for the locale, and similarly for
234            "'".  If the catalog has no translation,
235            locale_quoting_style quotes `like this', and
236            clocale_quoting_style quotes "like this".
237
238            For example, an American English Unicode locale should
239            translate "`" to U+201C (LEFT DOUBLE QUOTATION MARK), and
240            should translate "'" to U+201D (RIGHT DOUBLE QUOTATION
241            MARK).  A British English Unicode locale should instead
242            translate these to U+2018 (LEFT SINGLE QUOTATION MARK) and
243            U+2019 (RIGHT SINGLE QUOTATION MARK), respectively.
244
245            If you don't know what to put here, please see
246            <http://en.wikipedia.org/wiki/Quotation_mark#Glyphs>
247            and use glyphs suitable for your language.  */
248
249         char const *left = gettext_quote (N_("`"), quoting_style);
250         char const *right = gettext_quote (N_("'"), quoting_style);
251         for (quote_string = left; *quote_string; quote_string++)
252           STORE (*quote_string);
253         backslash_escapes = true;
254         quote_string = right;
255         quote_string_len = strlen (quote_string);
256       }
257       break;
258
259     case shell_always_quoting_style:
260       STORE ('\'');
261       quote_string = "'";
262       quote_string_len = 1;
263       break;
264
265     default:
266       break;
267     }
268
269   for (i = 0;  ! (argsize == SIZE_MAX ? arg[i] == '\0' : i == argsize);  i++)
270     {
271       unsigned char c;
272       unsigned char esc;
273
274       if (backslash_escapes
275           && quote_string_len
276           && i + quote_string_len <= argsize
277           && memcmp (arg + i, quote_string, quote_string_len) == 0)
278         STORE ('\\');
279
280       c = arg[i];
281       switch (c)
282         {
283         case '\0':
284           if (backslash_escapes)
285             {
286               STORE ('\\');
287               STORE ('0');
288               STORE ('0');
289               c = '0';
290             }
291           else if (flags & 0x1)
292             continue;
293           break;
294
295         case '?':
296           switch (quoting_style)
297             {
298             case shell_quoting_style:
299               goto use_shell_always_quoting_style;
300
301             case c_quoting_style:
302               if (i + 2 < argsize && arg[i + 1] == '?')
303                 switch (arg[i + 2])
304                   {
305                   case '!': case '\'':
306                   case '(': case ')': case '-': case '/':
307                   case '<': case '=': case '>':
308                     /* Escape the second '?' in what would otherwise be
309                        a trigraph.  */
310                     c = arg[i + 2];
311                     i += 2;
312                     STORE ('?');
313                     STORE ('\\');
314                     STORE ('?');
315                     break;
316
317                   default:
318                     break;
319                   }
320               break;
321
322             default:
323               break;
324             }
325           break;
326
327         case '\a': esc = 'a'; goto c_escape;
328         case '\b': esc = 'b'; goto c_escape;
329         case '\f': esc = 'f'; goto c_escape;
330         case '\n': esc = 'n'; goto c_and_shell_escape;
331         case '\r': esc = 'r'; goto c_and_shell_escape;
332         case '\t': esc = 't'; goto c_and_shell_escape;
333         case '\v': esc = 'v'; goto c_escape;
334         case '\\': esc = c; goto c_and_shell_escape;
335
336         c_and_shell_escape:
337           if (quoting_style == shell_quoting_style)
338             goto use_shell_always_quoting_style;
339         c_escape:
340           if (backslash_escapes)
341             {
342               c = esc;
343               goto store_escape;
344             }
345           break;
346
347         case '{': case '}': /* sometimes special if isolated */
348           if (! (argsize == SIZE_MAX ? arg[1] == '\0' : argsize == 1))
349             break;
350           /* Fall through.  */
351         case '#': case '~':
352           if (i != 0)
353             break;
354           /* Fall through.  */
355         case ' ':
356         case '!': /* special in bash */
357         case '"': case '$': case '&':
358         case '(': case ')': case '*': case ';':
359         case '<':
360         case '=': /* sometimes special in 0th or (with "set -k") later args */
361         case '>': case '[':
362         case '^': /* special in old /bin/sh, e.g. SunOS 4.1.4 */
363         case '`': case '|':
364           /* A shell special character.  In theory, '$' and '`' could
365              be the first bytes of multibyte characters, which means
366              we should check them with mbrtowc, but in practice this
367              doesn't happen so it's not worth worrying about.  */
368           if (quoting_style == shell_quoting_style)
369             goto use_shell_always_quoting_style;
370           break;
371
372         case '\'':
373           switch (quoting_style)
374             {
375             case shell_quoting_style:
376               goto use_shell_always_quoting_style;
377
378             case shell_always_quoting_style:
379               STORE ('\'');
380               STORE ('\\');
381               STORE ('\'');
382               break;
383
384             default:
385               break;
386             }
387           break;
388
389         case '%': case '+': case ',': case '-': case '.': case '/':
390         case '0': case '1': case '2': case '3': case '4': case '5':
391         case '6': case '7': case '8': case '9': case ':':
392         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
393         case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
394         case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
395         case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
396         case 'Y': case 'Z': case ']': case '_': case 'a': case 'b':
397         case 'c': case 'd': case 'e': case 'f': case 'g': case 'h':
398         case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
399         case 'o': case 'p': case 'q': case 'r': case 's': case 't':
400         case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
401           /* These characters don't cause problems, no matter what the
402              quoting style is.  They cannot start multibyte sequences.  */
403           break;
404
405         default:
406           /* If we have a multibyte sequence, copy it until we reach
407              its end, find an error, or come back to the initial shift
408              state.  For C-like styles, if the sequence has
409              unprintable characters, escape the whole sequence, since
410              we can't easily escape single characters within it.  */
411           {
412             /* Length of multibyte sequence found so far.  */
413             size_t m;
414
415             bool printable;
416
417             if (unibyte_locale)
418               {
419                 m = 1;
420                 printable = isprint (c) != 0;
421               }
422             else
423               {
424                 mbstate_t mbstate;
425                 memset (&mbstate, 0, sizeof mbstate);
426
427                 m = 0;
428                 printable = true;
429                 if (argsize == SIZE_MAX)
430                   argsize = strlen (arg);
431
432                 do
433                   {
434                     wchar_t w;
435                     size_t bytes = mbrtowc (&w, &arg[i + m],
436                                             argsize - (i + m), &mbstate);
437                     if (bytes == 0)
438                       break;
439                     else if (bytes == (size_t) -1)
440                       {
441                         printable = false;
442                         break;
443                       }
444                     else if (bytes == (size_t) -2)
445                       {
446                         printable = false;
447                         while (i + m < argsize && arg[i + m])
448                           m++;
449                         break;
450                       }
451                     else
452                       {
453                         /* Work around a bug with older shells that "see" a '\'
454                            that is really the 2nd byte of a multibyte character.
455                            In practice the problem is limited to ASCII
456                            chars >= '@' that are shell special chars.  */
457                         if ('[' == 0x5b && quoting_style == shell_quoting_style)
458                           {
459                             size_t j;
460                             for (j = 1; j < bytes; j++)
461                               switch (arg[i + m + j])
462                                 {
463                                 case '[': case '\\': case '^':
464                                 case '`': case '|':
465                                   goto use_shell_always_quoting_style;
466
467                                 default:
468                                   break;
469                                 }
470                           }
471
472                         if (! iswprint (w))
473                           printable = false;
474                         m += bytes;
475                       }
476                   }
477                 while (! mbsinit (&mbstate));
478               }
479
480             if (1 < m || (backslash_escapes && ! printable))
481               {
482                 /* Output a multibyte sequence, or an escaped
483                    unprintable unibyte character.  */
484                 size_t ilim = i + m;
485
486                 for (;;)
487                   {
488                     if (backslash_escapes && ! printable)
489                       {
490                         STORE ('\\');
491                         STORE ('0' + (c >> 6));
492                         STORE ('0' + ((c >> 3) & 7));
493                         c = '0' + (c & 7);
494                       }
495                     if (ilim <= i + 1)
496                       break;
497                     STORE (c);
498                     c = arg[++i];
499                   }
500
501                 goto store_c;
502               }
503           }
504         }
505
506       if (! (backslash_escapes
507              && o->quote_these_too[c / INT_BITS] & (1 << (c % INT_BITS))))
508         goto store_c;
509
510     store_escape:
511       STORE ('\\');
512
513     store_c:
514       STORE (c);
515     }
516
517   if (i == 0 && quoting_style == shell_quoting_style)
518     goto use_shell_always_quoting_style;
519
520   if (quote_string)
521     for (; *quote_string; quote_string++)
522       STORE (*quote_string);
523
524   if (len < buffersize)
525     buffer[len] = '\0';
526   return len;
527
528  use_shell_always_quoting_style:
529   return quotearg_buffer_restyled (buffer, buffersize, arg, argsize,
530                                    shell_always_quoting_style, flags, o);
531 }
532
533 /* Place into buffer BUFFER (of size BUFFERSIZE) a quoted version of
534    argument ARG (of size ARGSIZE), using O to control quoting.
535    If O is null, use the default.
536    Terminate the output with a null character, and return the written
537    size of the output, not counting the terminating null.
538    If BUFFERSIZE is too small to store the output string, return the
539    value that would have been returned had BUFFERSIZE been large enough.
540    If ARGSIZE is SIZE_MAX, use the string length of the argument for
541    ARGSIZE.  */
542 size_t
543 quotearg_buffer (char *buffer, size_t buffersize,
544                  char const *arg, size_t argsize,
545                  struct quoting_options const *o)
546 {
547   struct quoting_options const *p = o ? o : &default_quoting_options;
548   int e = errno;
549   size_t r = quotearg_buffer_restyled (buffer, buffersize, arg, argsize,
550                                        p->style, p->flags, p);
551   errno = e;
552   return r;
553 }
554
555 /* Equivalent to quotearg_alloc (ARG, ARGSIZE, NULL, O).  */
556 char *
557 quotearg_alloc (char const *arg, size_t argsize,
558                 struct quoting_options const *o)
559 {
560   return quotearg_alloc_mem (arg, argsize, NULL, o);
561 }
562
563 /* Like quotearg_buffer (..., ARG, ARGSIZE, O), except return newly
564    allocated storage containing the quoted string, and store the
565    resulting size into *SIZE, if non-NULL.  The result can contain
566    embedded null bytes only if ARGSIZE is not SIZE_MAX, SIZE is not
567    NULL, and set_quoting_flags has not set the null byte elision
568    flag.  */
569 char *
570 quotearg_alloc_mem (char const *arg, size_t argsize, size_t *size,
571                     struct quoting_options const *o)
572 {
573   struct quoting_options const *p = o ? o : &default_quoting_options;
574   int e = errno;
575   /* Elide embedded null bytes if we can't return a size.  */
576   int flags = p->flags | (size ? 0 : 0x1);
577   size_t bufsize = quotearg_buffer_restyled (0, 0, arg, argsize, p->style,
578                                              flags, p) + 1;
579   char *buf = xcharalloc (bufsize);
580   quotearg_buffer_restyled (buf, bufsize, arg, argsize, p->style, flags, p);
581   errno = e;
582   if (size)
583     *size = bufsize - 1;
584   return buf;
585 }
586
587 /* A storage slot with size and pointer to a value.  */
588 struct slotvec
589 {
590   size_t size;
591   char *val;
592 };
593
594 /* Preallocate a slot 0 buffer, so that the caller can always quote
595    one small component of a "memory exhausted" message in slot 0.  */
596 static char slot0[256];
597 static unsigned int nslots = 1;
598 static struct slotvec slotvec0 = {sizeof slot0, slot0};
599 static struct slotvec *slotvec = &slotvec0;
600
601 void
602 quotearg_free (void)
603 {
604   struct slotvec *sv = slotvec;
605   unsigned int i;
606   for (i = 1; i < nslots; i++)
607     free (sv[i].val);
608   if (sv[0].val != slot0)
609     {
610       free (sv[0].val);
611       slotvec0.size = sizeof slot0;
612       slotvec0.val = slot0;
613     }
614   if (sv != &slotvec0)
615     {
616       free (sv);
617       slotvec = &slotvec0;
618     }
619   nslots = 1;
620 }
621
622 /* Use storage slot N to return a quoted version of argument ARG.
623    ARG is of size ARGSIZE, but if that is SIZE_MAX, ARG is a
624    null-terminated string.
625    OPTIONS specifies the quoting options.
626    The returned value points to static storage that can be
627    reused by the next call to this function with the same value of N.
628    N must be nonnegative.  N is deliberately declared with type "int"
629    to allow for future extensions (using negative values).  */
630 static char *
631 quotearg_n_options (int n, char const *arg, size_t argsize,
632                     struct quoting_options const *options)
633 {
634   int e = errno;
635
636   unsigned int n0 = n;
637   struct slotvec *sv = slotvec;
638
639   if (n < 0)
640     abort ();
641
642   if (nslots <= n0)
643     {
644       /* FIXME: technically, the type of n1 should be `unsigned int',
645          but that evokes an unsuppressible warning from gcc-4.0.1 and
646          older.  If gcc ever provides an option to suppress that warning,
647          revert to the original type, so that the test in xalloc_oversized
648          is once again performed only at compile time.  */
649       size_t n1 = n0 + 1;
650       bool preallocated = (sv == &slotvec0);
651
652       if (xalloc_oversized (n1, sizeof *sv))
653         xalloc_die ();
654
655       slotvec = sv = xrealloc (preallocated ? NULL : sv, n1 * sizeof *sv);
656       if (preallocated)
657         *sv = slotvec0;
658       memset (sv + nslots, 0, (n1 - nslots) * sizeof *sv);
659       nslots = n1;
660     }
661
662   {
663     size_t size = sv[n].size;
664     char *val = sv[n].val;
665     /* Elide embedded null bytes since we don't return a size.  */
666     size_t qsize = quotearg_buffer_restyled (val, size, arg, argsize,
667                                              options->style,
668                                              options->flags | 0x1, options);
669
670     if (size <= qsize)
671       {
672         sv[n].size = size = qsize + 1;
673         if (val != slot0)
674           free (val);
675         sv[n].val = val = xcharalloc (size);
676         quotearg_buffer_restyled (val, size, arg, argsize, options->style,
677                                   options->flags | 0x1, options);
678       }
679
680     errno = e;
681     return val;
682   }
683 }
684
685 char *
686 quotearg_n (int n, char const *arg)
687 {
688   return quotearg_n_options (n, arg, SIZE_MAX, &default_quoting_options);
689 }
690
691 char *
692 quotearg_n_mem (int n, char const *arg, size_t argsize)
693 {
694   return quotearg_n_options (n, arg, argsize, &default_quoting_options);
695 }
696
697 char *
698 quotearg (char const *arg)
699 {
700   return quotearg_n (0, arg);
701 }
702
703 char *
704 quotearg_mem (char const *arg, size_t argsize)
705 {
706   return quotearg_n_mem (0, arg, argsize);
707 }
708
709 /* Return quoting options for STYLE, with no extra quoting.  */
710 static struct quoting_options
711 quoting_options_from_style (enum quoting_style style)
712 {
713   struct quoting_options o;
714   o.style = style;
715   o.flags = 0;
716   memset (o.quote_these_too, 0, sizeof o.quote_these_too);
717   return o;
718 }
719
720 char *
721 quotearg_n_style (int n, enum quoting_style s, char const *arg)
722 {
723   struct quoting_options const o = quoting_options_from_style (s);
724   return quotearg_n_options (n, arg, SIZE_MAX, &o);
725 }
726
727 char *
728 quotearg_n_style_mem (int n, enum quoting_style s,
729                       char const *arg, size_t argsize)
730 {
731   struct quoting_options const o = quoting_options_from_style (s);
732   return quotearg_n_options (n, arg, argsize, &o);
733 }
734
735 char *
736 quotearg_style (enum quoting_style s, char const *arg)
737 {
738   return quotearg_n_style (0, s, arg);
739 }
740
741 char *
742 quotearg_style_mem (enum quoting_style s, char const *arg, size_t argsize)
743 {
744   return quotearg_n_style_mem (0, s, arg, argsize);
745 }
746
747 char *
748 quotearg_char_mem (char const *arg, size_t argsize, char ch)
749 {
750   struct quoting_options options;
751   options = default_quoting_options;
752   set_char_quoting (&options, ch, 1);
753   return quotearg_n_options (0, arg, argsize, &options);
754 }
755
756 char *
757 quotearg_char (char const *arg, char ch)
758 {
759   return quotearg_char_mem (arg, SIZE_MAX, ch);
760 }
761
762 char *
763 quotearg_colon (char const *arg)
764 {
765   return quotearg_char (arg, ':');
766 }
767
768 char *
769 quotearg_colon_mem (char const *arg, size_t argsize)
770 {
771   return quotearg_char_mem (arg, argsize, ':');
772 }