caeb66f8120439ad45385793856b7d704a14d916
[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_LOG_CONT; break;
49     case GCRY_LOG_INFO: level = GPGRT_LOG_INFO; break;
50     case GCRY_LOG_WARN: level = GPGRT_LOG_WARN; break;
51     case GCRY_LOG_ERROR:level = GPGRT_LOG_ERROR; break;
52     case GCRY_LOG_FATAL:level = GPGRT_LOG_FATAL; break;
53     case GCRY_LOG_BUG:  level = GPGRT_LOG_BUG; break;
54     case GCRY_LOG_DEBUG:level = GPGRT_LOG_DEBUG; break;
55     default:            level = GPGRT_LOG_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 /* A wrapper around gcry_cipher_algo_name to return the string
121    "AES-128" instead of "AES".  Given that we have an alias in
122    libgcrypt for it, it does not harm to too much to return this other
123    string.  Some users complained that we print "AES" but "AES192"
124    and "AES256".  We can't fix that in libgcrypt but it is pretty
125    safe to do it in an application. */
126 const char *
127 gnupg_cipher_algo_name (int algo)
128 {
129   const char *s;
130
131   s = gcry_cipher_algo_name (algo);
132   if (!strcmp (s, "AES"))
133     s = "AES128";
134   return s;
135 }
136
137
138 void
139 obsolete_option (const char *configname, unsigned int configlineno,
140                  const char *name)
141 {
142   if (configname)
143     log_info (_("%s:%u: obsolete option \"%s\" - it has no effect\n"),
144               configname, configlineno, name);
145   else
146     log_info (_("WARNING: \"%s%s\" is an obsolete option - it has no effect\n"),
147               "--", name);
148 }
149
150
151 /* Decide whether the filename is stdout or a real filename and return
152  * an appropriate string.  */
153 const char *
154 print_fname_stdout (const char *s)
155 {
156     if( !s || (*s == '-' && !s[1]) )
157         return "[stdout]";
158     return s;
159 }
160
161
162 /* Decide whether the filename is stdin or a real filename and return
163  * an appropriate string.  */
164 const char *
165 print_fname_stdin (const char *s)
166 {
167     if( !s || (*s == '-' && !s[1]) )
168         return "[stdin]";
169     return s;
170 }
171
172
173 static int
174 do_print_utf8_buffer (estream_t stream,
175                       const void *buffer, size_t length,
176                       const char *delimiters, size_t *bytes_written)
177 {
178   const char *p = buffer;
179   size_t i;
180
181   /* We can handle plain ascii simpler, so check for it first. */
182   for (i=0; i < length; i++ )
183     {
184       if ( (p[i] & 0x80) )
185         break;
186     }
187   if (i < length)
188     {
189       int delim = delimiters? *delimiters : 0;
190       char *buf;
191       int ret;
192
193       /*(utf8 conversion already does the control character quoting). */
194       buf = utf8_to_native (p, length, delim);
195       if (bytes_written)
196         *bytes_written = strlen (buf);
197       ret = es_fputs (buf, stream);
198       xfree (buf);
199       return ret == EOF? ret : (int)i;
200     }
201   else
202     return es_write_sanitized (stream, p, length, delimiters, bytes_written);
203 }
204
205
206 void
207 print_utf8_buffer3 (estream_t stream, const void *p, size_t n,
208                     const char *delim)
209 {
210   do_print_utf8_buffer (stream, p, n, delim, NULL);
211 }
212
213
214 void
215 print_utf8_buffer2 (estream_t stream, const void *p, size_t n, int delim)
216 {
217   char tmp[2];
218
219   tmp[0] = delim;
220   tmp[1] = 0;
221   do_print_utf8_buffer (stream, p, n, tmp, NULL);
222 }
223
224
225 void
226 print_utf8_buffer (estream_t stream, const void *p, size_t n)
227 {
228   do_print_utf8_buffer (stream, p, n, NULL, NULL);
229 }
230
231
232 void
233 print_utf8_string (estream_t stream, const char *p)
234 {
235   if (!p)
236     p = "";
237   do_print_utf8_buffer (stream, p, strlen (p), NULL, NULL);
238 }
239
240
241 /* Write LENGTH bytes of BUFFER to FP as a hex encoded string.
242    RESERVED must be 0. */
243 void
244 print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved)
245 {
246 #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A'))
247   const unsigned char *s;
248
249   (void)reserved;
250
251   for (s = buffer; length; s++, length--)
252     {
253       putc ( tohex ((*s>>4)&15), fp);
254       putc ( tohex (*s&15), fp);
255     }
256 #undef tohex
257 }
258
259
260 /* Create a string from the buffer P_ARG of length N which is suitable
261  * for printing.  Caller must release the created string using xfree.
262  * On error ERRNO is set and NULL returned.  Errors are only possible
263  * due to malloc failure.  */
264 char *
265 try_make_printable_string (const void *p_arg, size_t n, int delim)
266 {
267   const unsigned char *p = p_arg;
268   size_t save_n, buflen;
269   const unsigned char *save_p;
270   char *buffer, *d;
271
272   /* First count length. */
273   for (save_n = n, save_p = p, buflen=1 ; n; n--, p++ )
274     {
275       if ( *p < 0x20 || *p == 0x7f || *p == delim  || (delim && *p=='\\'))
276         {
277           if ( *p=='\n' || *p=='\r' || *p=='\f'
278                || *p=='\v' || *p=='\b' || !*p )
279             buflen += 2;
280           else
281             buflen += 5;
282         }
283       else
284         buflen++;
285     }
286   p = save_p;
287   n = save_n;
288   /* And now make the string */
289   d = buffer = xtrymalloc (buflen);
290   for ( ; n; n--, p++ )
291     {
292       if (*p < 0x20 || *p == 0x7f || *p == delim || (delim && *p=='\\')) {
293         *d++ = '\\';
294         if( *p == '\n' )
295           *d++ = 'n';
296         else if( *p == '\r' )
297           *d++ = 'r';
298         else if( *p == '\f' )
299           *d++ = 'f';
300         else if( *p == '\v' )
301           *d++ = 'v';
302         else if( *p == '\b' )
303           *d++ = 'b';
304         else if( !*p )
305           *d++ = '0';
306         else {
307           sprintf(d, "x%02x", *p );
308           d += 3;
309         }
310       }
311       else
312         *d++ = *p;
313     }
314   *d = 0;
315   return buffer;
316 }
317
318
319 /* Same as try_make_printable_string but terminates the process on
320  * memory shortage.  */
321 char *
322 make_printable_string (const void *p, size_t n, int delim )
323 {
324   char *string = try_make_printable_string (p, n, delim);
325   if (!string)
326     xoutofcore ();
327   return string;
328 }
329
330
331 /* Check whether (BUF,LEN) is valid header for an OpenPGP compressed
332  * packet.  LEN should be at least 6.  */
333 static int
334 is_openpgp_compressed_packet (unsigned char *buf, size_t len)
335 {
336   int c, ctb, pkttype;
337   int lenbytes;
338
339   ctb = *buf++; len--;
340   if (!(ctb & 0x80))
341     return 0; /* Invalid packet.  */
342
343   if ((ctb & 0x40)) /* New style (OpenPGP) CTB.  */
344     {
345       pkttype = (ctb & 0x3f);
346       if (!len)
347         return 0; /* Expected first length octet missing.  */
348       c = *buf++; len--;
349       if (c < 192)
350         ;
351       else if (c < 224)
352         {
353           if (!len)
354             return 0; /* Expected second length octet missing. */
355         }
356       else if (c == 255)
357         {
358           if (len < 4)
359             return 0; /* Expected length octets missing */
360         }
361     }
362   else /* Old style CTB.  */
363     {
364       pkttype = (ctb>>2)&0xf;
365       lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3));
366       if (len < lenbytes)
367         return 0; /* Not enough length bytes.  */
368     }
369
370   return (pkttype == 8);
371 }
372
373
374
375 /*
376  * Check if the file is compressed.
377  */
378 int
379 is_file_compressed (const char *s, int *ret_rc)
380 {
381     iobuf_t a;
382     byte buf[6];
383     int i;
384     int rc = 0;
385     int overflow;
386
387     struct magic_compress_s {
388         size_t len;
389         byte magic[4];
390     } magic[] = {
391         { 3, { 0x42, 0x5a, 0x68, 0x00 } }, /* bzip2 */
392         { 3, { 0x1f, 0x8b, 0x08, 0x00 } }, /* gzip */
393         { 4, { 0x50, 0x4b, 0x03, 0x04 } }, /* (pk)zip */
394     };
395
396     if ( iobuf_is_pipe_filename (s) || !ret_rc )
397         return 0; /* We can't check stdin or no file was given */
398
399     a = iobuf_open( s );
400     if ( a == NULL ) {
401         *ret_rc = gpg_error_from_syserror ();
402         return 0;
403     }
404
405     if ( iobuf_get_filelength( a, &overflow ) < 6 && !overflow) {
406         *ret_rc = 0;
407         goto leave;
408     }
409
410     if ( iobuf_read( a, buf, 6 ) == -1 ) {
411         *ret_rc = a->error;
412         goto leave;
413     }
414
415     for ( i = 0; i < DIM( magic ); i++ ) {
416         if ( !memcmp( buf, magic[i].magic, magic[i].len ) ) {
417             *ret_rc = 0;
418             rc = 1;
419             goto leave;
420         }
421     }
422
423     if (is_openpgp_compressed_packet (buf, 6))
424       {
425         *ret_rc = 0;
426         rc = 1;
427       }
428
429  leave:
430     iobuf_close( a );
431     return rc;
432 }
433
434
435 /* Try match against each substring of multistr, delimited by | */
436 int
437 match_multistr (const char *multistr,const char *match)
438 {
439   do
440     {
441       size_t seglen = strcspn (multistr,"|");
442       if (!seglen)
443         break;
444       /* Using the localized strncasecmp! */
445       if (strncasecmp(multistr,match,seglen)==0)
446         return 1;
447       multistr += seglen;
448       if (*multistr == '|')
449         multistr++;
450     }
451   while (*multistr);
452
453   return 0;
454 }
455
456
457 \f
458 /* Parse the first portion of the version number S and store it at
459    NUMBER.  On success, the function returns a pointer into S starting
460    with the first character, which is not part of the initial number
461    portion; on failure, NULL is returned.  */
462 static const char*
463 parse_version_number (const char *s, int *number)
464 {
465   int val = 0;
466
467   if (*s == '0' && digitp (s+1))
468     return NULL; /* Leading zeros are not allowed.  */
469   for (; digitp (s); s++ )
470     {
471       val *= 10;
472       val += *s - '0';
473     }
474   *number = val;
475   return val < 0? NULL : s;
476 }
477
478 /* Break up the complete string representation of the version number S,
479    which is expected to have this format:
480
481       <major number>.<minor number>.<micro number><patch level>.
482
483    The major, minor and micro number components will be stored at
484    MAJOR, MINOR and MICRO. On success, a pointer to the last
485    component, the patch level, will be returned; on failure, NULL will
486    be returned.  */
487 static const char *
488 parse_version_string (const char *s, int *major, int *minor, int *micro)
489 {
490   s = parse_version_number (s, major);
491   if (!s || *s != '.')
492     return NULL;
493   s++;
494   s = parse_version_number (s, minor);
495   if (!s || *s != '.')
496     return NULL;
497   s++;
498   s = parse_version_number (s, micro);
499   if (!s)
500     return NULL;
501   return s; /* Patchlevel.  */
502 }
503
504 /* Return true if version string is at least version B. */
505 int
506 gnupg_compare_version (const char *a, const char *b)
507 {
508   int a_major, a_minor, a_micro;
509   int b_major, b_minor, b_micro;
510   const char *a_plvl, *b_plvl;
511
512   if (!a || !b)
513     return 0;
514
515   /* Parse version A.  */
516   a_plvl = parse_version_string (a, &a_major, &a_minor, &a_micro);
517   if (!a_plvl )
518     return 0; /* Invalid version number.  */
519
520   /* Parse version B.  */
521   b_plvl = parse_version_string (b, &b_major, &b_minor, &b_micro);
522   if (!b_plvl )
523     return 0; /* Invalid version number.  */
524
525   /* Compare version numbers.  */
526   return (a_major > b_major
527           || (a_major == b_major && a_minor > b_minor)
528           || (a_major == b_major && a_minor == b_minor
529               && a_micro > b_micro)
530           || (a_major == b_major && a_minor == b_minor
531               && a_micro == b_micro
532               && strcmp (a_plvl, b_plvl) >= 0));
533 }
534
535
536 \f
537 /* Parse an --debug style argument.  We allow the use of number values
538  * in the usual C notation or a string with comma separated keywords.
539  *
540  * Returns: 0 on success or -1 and ERRNO set on error.  On success the
541  *          supplied variable is updated by the parsed flags.
542  *
543  * If STRING is NULL the enabled debug flags are printed.
544  *
545  * See doc/DETAILS for a summary of used debug options.
546  */
547 int
548 parse_debug_flag (const char *string, unsigned int *debugvar,
549                   const struct debug_flags_s *flags)
550
551 {
552   unsigned long result = 0;
553   int i, j;
554
555   if (!string)
556     {
557       if (debugvar)
558         {
559           log_info ("enabled debug flags:");
560           for (i=0; flags[i].name; i++)
561             if ((*debugvar & flags[i].flag))
562               log_printf (" %s", flags[i].name);
563           log_printf ("\n");
564         }
565       return 0;
566     }
567
568   while (spacep (string))
569     string++;
570   if (*string == '-')
571     {
572       errno = EINVAL;
573       return -1;
574     }
575
576   if (!strcmp (string, "?") || !strcmp (string, "help"))
577     {
578       log_info ("available debug flags:\n");
579       for (i=0; flags[i].name; i++)
580         log_info (" %5u %s\n", flags[i].flag, flags[i].name);
581       if (flags[i].flag != 77)
582         exit (0);
583     }
584   else if (digitp (string))
585     {
586       errno = 0;
587       result = strtoul (string, NULL, 0);
588       if (result == ULONG_MAX && errno == ERANGE)
589         return -1;
590     }
591   else
592     {
593       char **words;
594       words = strtokenize (string, ",");
595       if (!words)
596         return -1;
597       for (i=0; words[i]; i++)
598         {
599           if (*words[i])
600             {
601               for (j=0; flags[j].name; j++)
602                 if (!strcmp (words[i], flags[j].name))
603                   {
604                     result |= flags[j].flag;
605                     break;
606                   }
607               if (!flags[j].name)
608                 {
609                   if (!strcmp (words[i], "none"))
610                     {
611                       *debugvar = 0;
612                       result = 0;
613                     }
614                   else if (!strcmp (words[i], "all"))
615                     result = ~0;
616                   else
617                     log_info (_("unknown debug flag '%s' ignored\n"), words[i]);
618                 }
619             }
620         }
621       xfree (words);
622     }
623
624   *debugvar |= result;
625   return 0;
626 }