df6b6878430435a48d435830a6bf7e574ec3549d
[platform/upstream/gpg2.git] / common / miscellaneous.c
1 /* miscellaneous.c - Stuff not fitting elsewhere
2  *      Copyright (C) 2003, 2006 Free Software Foundation, Inc.
3  *
4  * This file is part of GnuPG.
5  *
6  * This file is free software; you can redistribute it and/or modify
7  * it under the terms of either
8  *
9  *   - the GNU Lesser General Public License as published by the Free
10  *     Software Foundation; either version 3 of the License, or (at
11  *     your option) any later version.
12  *
13  * or
14  *
15  *   - the GNU General Public License as published by the Free
16  *     Software Foundation; either version 2 of the License, or (at
17  *     your option) any later version.
18  *
19  * or both in parallel, as here.
20  *
21  * This file is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program; if not, see <https://www.gnu.org/licenses/>.
28  */
29
30 #include <config.h>
31 #include <stdlib.h>
32 #include <limits.h>
33 #include <errno.h>
34
35 #include "util.h"
36 #include "iobuf.h"
37 #include "i18n.h"
38
39 /* Used by libgcrypt for logging.  */
40 static void
41 my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr)
42 {
43   (void)dummy;
44
45   /* Map the log levels.  */
46   switch (level)
47     {
48     case GCRY_LOG_CONT: level = GPGRT_LOGLVL_CONT; break;
49     case GCRY_LOG_INFO: level = GPGRT_LOGLVL_INFO; break;
50     case GCRY_LOG_WARN: level = GPGRT_LOGLVL_WARN; break;
51     case GCRY_LOG_ERROR:level = GPGRT_LOGLVL_ERROR; break;
52     case GCRY_LOG_FATAL:level = GPGRT_LOGLVL_FATAL; break;
53     case GCRY_LOG_BUG:  level = GPGRT_LOGLVL_BUG; break;
54     case GCRY_LOG_DEBUG:level = GPGRT_LOGLVL_DEBUG; break;
55     default:            level = GPGRT_LOGLVL_ERROR; break;
56     }
57   log_logv (level, fmt, arg_ptr);
58 }
59
60
61 /* This function is called by libgcrypt on a fatal error.  */
62 static void
63 my_gcry_fatalerror_handler (void *opaque, int rc, const char *text)
64 {
65   (void)opaque;
66
67   log_fatal ("libgcrypt problem: %s\n", text ? text : gpg_strerror (rc));
68   abort ();
69 }
70
71
72 /* This function is called by libgcrypt if it ran out of core and
73    there is no way to return that error to the caller.  We do our own
74    function here to make use of our logging functions. */
75 static int
76 my_gcry_outofcore_handler (void *opaque, size_t req_n, unsigned int flags)
77 {
78   static int been_here;  /* Used to protect against recursive calls. */
79
80   (void)opaque;
81
82   if (!been_here)
83     {
84       been_here = 1;
85       if ( (flags & 1) )
86         log_fatal (_("out of core in secure memory "
87                      "while allocating %lu bytes"), (unsigned long)req_n);
88       else
89         log_fatal (_("out of core while allocating %lu bytes"),
90                    (unsigned long)req_n);
91     }
92   return 0; /* Let libgcrypt call its own fatal error handler.
93                Actually this will turn out to be
94                my_gcry_fatalerror_handler. */
95 }
96
97
98 /* Setup libgcrypt to use our own logging functions.  Should be used
99    early at startup. */
100 void
101 setup_libgcrypt_logging (void)
102 {
103   gcry_set_log_handler (my_gcry_logger, NULL);
104   gcry_set_fatalerror_handler (my_gcry_fatalerror_handler, NULL);
105   gcry_set_outofcore_handler (my_gcry_outofcore_handler, NULL);
106 }
107
108
109 /* Print an out of core message and let the process die.  The printed
110  * error is taken from ERRNO.  */
111 void
112 xoutofcore (void)
113 {
114   gpg_error_t err = gpg_error_from_syserror ();
115   log_fatal (_("error allocating enough memory: %s\n"), gpg_strerror (err));
116   abort (); /* Never called; just to make the compiler happy.  */
117 }
118
119
120 /* Wrapper around gpgrt_reallocarray.   */
121 void *
122 xreallocarray (void *a, size_t oldnmemb, size_t nmemb, size_t size)
123 {
124   void *p = gpgrt_reallocarray (a, oldnmemb, nmemb, size);
125   if (!p)
126     xoutofcore ();
127   return p;
128 }
129
130
131 /* A wrapper around gcry_cipher_algo_name to return the string
132    "AES-128" instead of "AES".  Given that we have an alias in
133    libgcrypt for it, it does not harm to too much to return this other
134    string.  Some users complained that we print "AES" but "AES192"
135    and "AES256".  We can't fix that in libgcrypt but it is pretty
136    safe to do it in an application. */
137 const char *
138 gnupg_cipher_algo_name (int algo)
139 {
140   const char *s;
141
142   s = gcry_cipher_algo_name (algo);
143   if (!strcmp (s, "AES"))
144     s = "AES128";
145   return s;
146 }
147
148
149 void
150 obsolete_option (const char *configname, unsigned int configlineno,
151                  const char *name)
152 {
153   if (configname)
154     log_info (_("%s:%u: obsolete option \"%s\" - it has no effect\n"),
155               configname, configlineno, name);
156   else
157     log_info (_("WARNING: \"%s%s\" is an obsolete option - it has no effect\n"),
158               "--", name);
159 }
160
161
162 /* Decide whether the filename is stdout or a real filename and return
163  * an appropriate string.  */
164 const char *
165 print_fname_stdout (const char *s)
166 {
167     if( !s || (*s == '-' && !s[1]) )
168         return "[stdout]";
169     return s;
170 }
171
172
173 /* Decide whether the filename is stdin or a real filename and return
174  * an appropriate string.  */
175 const char *
176 print_fname_stdin (const char *s)
177 {
178     if( !s || (*s == '-' && !s[1]) )
179         return "[stdin]";
180     return s;
181 }
182
183
184 static int
185 do_print_utf8_buffer (estream_t stream,
186                       const void *buffer, size_t length,
187                       const char *delimiters, size_t *bytes_written)
188 {
189   const char *p = buffer;
190   size_t i;
191
192   /* We can handle plain ascii simpler, so check for it first. */
193   for (i=0; i < length; i++ )
194     {
195       if ( (p[i] & 0x80) )
196         break;
197     }
198   if (i < length)
199     {
200       int delim = delimiters? *delimiters : 0;
201       char *buf;
202       int ret;
203
204       /*(utf8 conversion already does the control character quoting). */
205       buf = utf8_to_native (p, length, delim);
206       if (bytes_written)
207         *bytes_written = strlen (buf);
208       ret = es_fputs (buf, stream);
209       xfree (buf);
210       return ret == EOF? ret : (int)i;
211     }
212   else
213     return es_write_sanitized (stream, p, length, delimiters, bytes_written);
214 }
215
216
217 void
218 print_utf8_buffer3 (estream_t stream, const void *p, size_t n,
219                     const char *delim)
220 {
221   do_print_utf8_buffer (stream, p, n, delim, NULL);
222 }
223
224
225 void
226 print_utf8_buffer2 (estream_t stream, const void *p, size_t n, int delim)
227 {
228   char tmp[2];
229
230   tmp[0] = delim;
231   tmp[1] = 0;
232   do_print_utf8_buffer (stream, p, n, tmp, NULL);
233 }
234
235
236 void
237 print_utf8_buffer (estream_t stream, const void *p, size_t n)
238 {
239   do_print_utf8_buffer (stream, p, n, NULL, NULL);
240 }
241
242
243 void
244 print_utf8_string (estream_t stream, const char *p)
245 {
246   if (!p)
247     p = "";
248   do_print_utf8_buffer (stream, p, strlen (p), NULL, NULL);
249 }
250
251
252 /* Write LENGTH bytes of BUFFER to FP as a hex encoded string.
253    RESERVED must be 0. */
254 void
255 print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved)
256 {
257 #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A'))
258   const unsigned char *s;
259
260   (void)reserved;
261
262   for (s = buffer; length; s++, length--)
263     {
264       putc ( tohex ((*s>>4)&15), fp);
265       putc ( tohex (*s&15), fp);
266     }
267 #undef tohex
268 }
269
270
271 /* Create a string from the buffer P_ARG of length N which is suitable
272  * for printing.  Caller must release the created string using xfree.
273  * On error ERRNO is set and NULL returned.  Errors are only possible
274  * due to malloc failure.  */
275 char *
276 try_make_printable_string (const void *p_arg, size_t n, int delim)
277 {
278   const unsigned char *p = p_arg;
279   size_t save_n, buflen;
280   const unsigned char *save_p;
281   char *buffer, *d;
282
283   /* First count length. */
284   for (save_n = n, save_p = p, buflen=1 ; n; n--, p++ )
285     {
286       if ( *p < 0x20 || *p == 0x7f || *p == delim  || (delim && *p=='\\'))
287         {
288           if ( *p=='\n' || *p=='\r' || *p=='\f'
289                || *p=='\v' || *p=='\b' || !*p )
290             buflen += 2;
291           else
292             buflen += 5;
293         }
294       else
295         buflen++;
296     }
297   p = save_p;
298   n = save_n;
299   /* And now make the string */
300   d = buffer = xtrymalloc (buflen);
301   for ( ; n; n--, p++ )
302     {
303       if (*p < 0x20 || *p == 0x7f || *p == delim || (delim && *p=='\\')) {
304         *d++ = '\\';
305         if( *p == '\n' )
306           *d++ = 'n';
307         else if( *p == '\r' )
308           *d++ = 'r';
309         else if( *p == '\f' )
310           *d++ = 'f';
311         else if( *p == '\v' )
312           *d++ = 'v';
313         else if( *p == '\b' )
314           *d++ = 'b';
315         else if( !*p )
316           *d++ = '0';
317         else {
318           sprintf(d, "x%02x", *p );
319           d += 3;
320         }
321       }
322       else
323         *d++ = *p;
324     }
325   *d = 0;
326   return buffer;
327 }
328
329
330 /* Same as try_make_printable_string but terminates the process on
331  * memory shortage.  */
332 char *
333 make_printable_string (const void *p, size_t n, int delim )
334 {
335   char *string = try_make_printable_string (p, n, delim);
336   if (!string)
337     xoutofcore ();
338   return string;
339 }
340
341
342 /* Decode the C formatted string SRC and return the result in a newly
343  * allocated buffer.  In error returns NULL and sets ERRNO. */
344 char *
345 decode_c_string (const char *src)
346 {
347   char *buffer, *dst;
348   int val;
349
350   /* The converted string will never be larger than the original
351      string.  */
352   buffer = dst = xtrymalloc (strlen (src) + 1);
353   if (!buffer)
354     return NULL;
355
356   while (*src)
357     {
358       if (*src != '\\')
359         {
360           *dst++ = *src++;
361           continue;
362         }
363
364 #define DECODE_ONE(_m,_r) case _m: src += 2; *dst++ = _r; break;
365
366       switch (src[1])
367         {
368           DECODE_ONE ('n', '\n');
369           DECODE_ONE ('r', '\r');
370           DECODE_ONE ('f', '\f');
371           DECODE_ONE ('v', '\v');
372           DECODE_ONE ('b', '\b');
373           DECODE_ONE ('t', '\t');
374           DECODE_ONE ('\\', '\\');
375           DECODE_ONE ('\'', '\'');
376           DECODE_ONE ('\"', '\"');
377
378         case 'x':
379           val = hextobyte (src+2);
380           if (val == -1)  /* Bad coding, keep as is. */
381             {
382               *dst++ = *src++;
383               *dst++ = *src++;
384               if (*src)
385                 *dst++ = *src++;
386               if (*src)
387                 *dst++ = *src++;
388             }
389           else if (!val)
390             {
391               /* A binary zero is not representable in a C string thus
392                * we keep the C-escaping.  Note that this will also
393                * never be larger than the source string.  */
394               *dst++ = '\\';
395               *dst++ = '0';
396               src += 4;
397             }
398           else
399             {
400               *(unsigned char *)dst++ = val;
401               src += 4;
402             }
403           break;
404
405         default: /* Bad coding; keep as is..  */
406           *dst++ = *src++;
407           *dst++ = *src++;
408           break;
409         }
410 #undef DECODE_ONE
411     }
412   *dst++ = 0;
413
414   return buffer;
415 }
416
417
418 /* Check whether (BUF,LEN) is valid header for an OpenPGP compressed
419  * packet.  LEN should be at least 6.  */
420 static int
421 is_openpgp_compressed_packet (unsigned char *buf, size_t len)
422 {
423   int c, ctb, pkttype;
424   int lenbytes;
425
426   ctb = *buf++; len--;
427   if (!(ctb & 0x80))
428     return 0; /* Invalid packet.  */
429
430   if ((ctb & 0x40)) /* New style (OpenPGP) CTB.  */
431     {
432       pkttype = (ctb & 0x3f);
433       if (!len)
434         return 0; /* Expected first length octet missing.  */
435       c = *buf++; len--;
436       if (c < 192)
437         ;
438       else if (c < 224)
439         {
440           if (!len)
441             return 0; /* Expected second length octet missing. */
442         }
443       else if (c == 255)
444         {
445           if (len < 4)
446             return 0; /* Expected length octets missing */
447         }
448     }
449   else /* Old style CTB.  */
450     {
451       pkttype = (ctb>>2)&0xf;
452       lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3));
453       if (len < lenbytes)
454         return 0; /* Not enough length bytes.  */
455     }
456
457   return (pkttype == 8);
458 }
459
460
461
462 /*
463  * Check if the file is compressed.
464  */
465 int
466 is_file_compressed (const char *s, int *ret_rc)
467 {
468     iobuf_t a;
469     byte buf[6];
470     int i;
471     int rc = 0;
472     int overflow;
473
474     struct magic_compress_s {
475         size_t len;
476         byte magic[4];
477     } magic[] = {
478         { 3, { 0x42, 0x5a, 0x68, 0x00 } }, /* bzip2 */
479         { 3, { 0x1f, 0x8b, 0x08, 0x00 } }, /* gzip */
480         { 4, { 0x50, 0x4b, 0x03, 0x04 } }, /* (pk)zip */
481     };
482
483     if ( iobuf_is_pipe_filename (s) || !ret_rc )
484         return 0; /* We can't check stdin or no file was given */
485
486     a = iobuf_open( s );
487     if ( a == NULL ) {
488         *ret_rc = gpg_error_from_syserror ();
489         return 0;
490     }
491     iobuf_ioctl (a, IOBUF_IOCTL_NO_CACHE, 1, NULL);
492
493     if ( iobuf_get_filelength( a, &overflow ) < 6 && !overflow) {
494         *ret_rc = 0;
495         goto leave;
496     }
497
498     if ( iobuf_read( a, buf, 6 ) == -1 ) {
499         *ret_rc = a->error;
500         goto leave;
501     }
502
503     for ( i = 0; i < DIM( magic ); i++ ) {
504         if ( !memcmp( buf, magic[i].magic, magic[i].len ) ) {
505             *ret_rc = 0;
506             rc = 1;
507             goto leave;
508         }
509     }
510
511     if (is_openpgp_compressed_packet (buf, 6))
512       {
513         *ret_rc = 0;
514         rc = 1;
515       }
516
517  leave:
518     iobuf_close( a );
519     return rc;
520 }
521
522
523 /* Try match against each substring of multistr, delimited by | */
524 int
525 match_multistr (const char *multistr,const char *match)
526 {
527   do
528     {
529       size_t seglen = strcspn (multistr,"|");
530       if (!seglen)
531         break;
532       /* Using the localized strncasecmp! */
533       if (strncasecmp(multistr,match,seglen)==0)
534         return 1;
535       multistr += seglen;
536       if (*multistr == '|')
537         multistr++;
538     }
539   while (*multistr);
540
541   return 0;
542 }
543
544
545 \f
546 /* Parse the first portion of the version number S and store it at
547    NUMBER.  On success, the function returns a pointer into S starting
548    with the first character, which is not part of the initial number
549    portion; on failure, NULL is returned.  */
550 static const char*
551 parse_version_number (const char *s, int *number)
552 {
553   int val = 0;
554
555   if (*s == '0' && digitp (s+1))
556     return NULL; /* Leading zeros are not allowed.  */
557   for (; digitp (s); s++ )
558     {
559       val *= 10;
560       val += *s - '0';
561     }
562   *number = val;
563   return val < 0? NULL : s;
564 }
565
566 /* Break up the complete string representation of the version number S,
567    which is expected to have this format:
568
569       <major number>.<minor number>.<micro number><patch level>.
570
571    The major, minor and micro number components will be stored at
572    MAJOR, MINOR and MICRO. On success, a pointer to the last
573    component, the patch level, will be returned; on failure, NULL will
574    be returned.  */
575 static const char *
576 parse_version_string (const char *s, int *major, int *minor, int *micro)
577 {
578   s = parse_version_number (s, major);
579   if (!s || *s != '.')
580     return NULL;
581   s++;
582   s = parse_version_number (s, minor);
583   if (!s || *s != '.')
584     return NULL;
585   s++;
586   s = parse_version_number (s, micro);
587   if (!s)
588     return NULL;
589   return s; /* Patchlevel.  */
590 }
591
592 /* Return true if version string is at least version B. */
593 int
594 gnupg_compare_version (const char *a, const char *b)
595 {
596   int a_major, a_minor, a_micro;
597   int b_major, b_minor, b_micro;
598   const char *a_plvl, *b_plvl;
599
600   if (!a || !b)
601     return 0;
602
603   /* Parse version A.  */
604   a_plvl = parse_version_string (a, &a_major, &a_minor, &a_micro);
605   if (!a_plvl )
606     return 0; /* Invalid version number.  */
607
608   /* Parse version B.  */
609   b_plvl = parse_version_string (b, &b_major, &b_minor, &b_micro);
610   if (!b_plvl )
611     return 0; /* Invalid version number.  */
612
613   /* Compare version numbers.  */
614   return (a_major > b_major
615           || (a_major == b_major && a_minor > b_minor)
616           || (a_major == b_major && a_minor == b_minor
617               && a_micro > b_micro)
618           || (a_major == b_major && a_minor == b_minor
619               && a_micro == b_micro
620               && strcmp (a_plvl, b_plvl) >= 0));
621 }
622
623
624 \f
625 /* Parse an --debug style argument.  We allow the use of number values
626  * in the usual C notation or a string with comma separated keywords.
627  *
628  * Returns: 0 on success or -1 and ERRNO set on error.  On success the
629  *          supplied variable is updated by the parsed flags.
630  *
631  * If STRING is NULL the enabled debug flags are printed.
632  *
633  * See doc/DETAILS for a summary of used debug options.
634  */
635 int
636 parse_debug_flag (const char *string, unsigned int *debugvar,
637                   const struct debug_flags_s *flags)
638
639 {
640   unsigned long result = 0;
641   int i, j;
642
643   if (!string)
644     {
645       if (debugvar)
646         {
647           log_info ("enabled debug flags:");
648           for (i=0; flags[i].name; i++)
649             if ((*debugvar & flags[i].flag))
650               log_printf (" %s", flags[i].name);
651           log_printf ("\n");
652         }
653       return 0;
654     }
655
656   while (spacep (string))
657     string++;
658   if (*string == '-')
659     {
660       errno = EINVAL;
661       return -1;
662     }
663
664   if (!strcmp (string, "?") || !strcmp (string, "help"))
665     {
666       log_info ("available debug flags:\n");
667       for (i=0; flags[i].name; i++)
668         log_info (" %5u %s\n", flags[i].flag, flags[i].name);
669       if (flags[i].flag != 77)
670         exit (0);
671     }
672   else if (digitp (string))
673     {
674       errno = 0;
675       result = strtoul (string, NULL, 0);
676       if (result == ULONG_MAX && errno == ERANGE)
677         return -1;
678     }
679   else
680     {
681       char **words;
682       words = strtokenize (string, ",");
683       if (!words)
684         return -1;
685       for (i=0; words[i]; i++)
686         {
687           if (*words[i])
688             {
689               for (j=0; flags[j].name; j++)
690                 if (!strcmp (words[i], flags[j].name))
691                   {
692                     result |= flags[j].flag;
693                     break;
694                   }
695               if (!flags[j].name)
696                 {
697                   if (!strcmp (words[i], "none"))
698                     {
699                       *debugvar = 0;
700                       result = 0;
701                     }
702                   else if (!strcmp (words[i], "all"))
703                     result = ~0;
704                   else
705                     log_info (_("unknown debug flag '%s' ignored\n"), words[i]);
706                 }
707             }
708         }
709       xfree (words);
710     }
711
712   *debugvar |= result;
713   return 0;
714 }
715
716
717 \f
718 /* Parse an --comaptibility_flags style argument consisting of comma
719  * separated strings.
720  *
721  * Returns: 0 on success or -1 and ERRNO set on error.  On success the
722  *          supplied variable is updated by the parsed flags.
723  *
724  * If STRING is NULL the enabled flags are printed.
725  */
726 int
727 parse_compatibility_flags (const char *string, unsigned int *flagvar,
728                            const struct compatibility_flags_s *flags)
729
730 {
731   unsigned long result = 0;
732   int i, j;
733
734   if (!string)
735     {
736       if (flagvar)
737         {
738           log_info ("enabled compatibility flags:");
739           for (i=0; flags[i].name; i++)
740             if ((*flagvar & flags[i].flag))
741               log_printf (" %s", flags[i].name);
742           log_printf ("\n");
743         }
744       return 0;
745     }
746
747   while (spacep (string))
748     string++;
749
750   if (!strcmp (string, "?") || !strcmp (string, "help"))
751     {
752       log_info ("available compatibility flags:\n");
753       for (i=0; flags[i].name; i++)
754         log_info (" %s\n", flags[i].name);
755       if (flags[i].flag != 77)
756         exit (0);
757     }
758   else
759     {
760       char **words;
761       words = strtokenize (string, ",");
762       if (!words)
763         return -1;
764       for (i=0; words[i]; i++)
765         {
766           if (*words[i])
767             {
768               for (j=0; flags[j].name; j++)
769                 if (!strcmp (words[i], flags[j].name))
770                   {
771                     result |= flags[j].flag;
772                     break;
773                   }
774               if (!flags[j].name)
775                 {
776                   if (!strcmp (words[i], "none"))
777                     {
778                       *flagvar = 0;
779                       result = 0;
780                     }
781                   else if (!strcmp (words[i], "all"))
782                     result = ~0;
783                   else
784                     log_info ("unknown compatibility flag '%s' ignored\n",
785                               words[i]);
786                 }
787             }
788         }
789       xfree (words);
790     }
791
792   *flagvar |= result;
793   return 0;
794 }