1 /* miscellaneous.c - Stuff not fitting elsewhere
2 * Copyright (C) 2003, 2006 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * This file is free software; you can redistribute it and/or modify
7 * it under the terms of either
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.
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.
19 * or both in parallel, as here.
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.
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/>.
39 /* Used by libgcrypt for logging. */
41 my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr)
45 /* Map the log levels. */
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;
57 log_logv (level, fmt, arg_ptr);
61 /* This function is called by libgcrypt on a fatal error. */
63 my_gcry_fatalerror_handler (void *opaque, int rc, const char *text)
67 log_fatal ("libgcrypt problem: %s\n", text ? text : gpg_strerror (rc));
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. */
76 my_gcry_outofcore_handler (void *opaque, size_t req_n, unsigned int flags)
78 static int been_here; /* Used to protect against recursive calls. */
86 log_fatal (_("out of core in secure memory "
87 "while allocating %lu bytes"), (unsigned long)req_n);
89 log_fatal (_("out of core while allocating %lu bytes"),
90 (unsigned long)req_n);
92 return 0; /* Let libgcrypt call its own fatal error handler.
93 Actually this will turn out to be
94 my_gcry_fatalerror_handler. */
98 /* Setup libgcrypt to use our own logging functions. Should be used
101 setup_libgcrypt_logging (void)
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);
109 /* Print an out of core message and let the process die. The printed
110 * error is taken from ERRNO. */
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. */
120 /* Wrapper around gpgrt_reallocarray. */
122 xreallocarray (void *a, size_t oldnmemb, size_t nmemb, size_t size)
124 void *p = gpgrt_reallocarray (a, oldnmemb, nmemb, size);
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. */
138 gnupg_cipher_algo_name (int algo)
142 s = gcry_cipher_algo_name (algo);
143 if (!strcmp (s, "AES"))
150 obsolete_option (const char *configname, unsigned int configlineno,
154 log_info (_("%s:%u: obsolete option \"%s\" - it has no effect\n"),
155 configname, configlineno, name);
157 log_info (_("WARNING: \"%s%s\" is an obsolete option - it has no effect\n"),
162 /* Decide whether the filename is stdout or a real filename and return
163 * an appropriate string. */
165 print_fname_stdout (const char *s)
167 if( !s || (*s == '-' && !s[1]) )
173 /* Decide whether the filename is stdin or a real filename and return
174 * an appropriate string. */
176 print_fname_stdin (const char *s)
178 if( !s || (*s == '-' && !s[1]) )
185 do_print_utf8_buffer (estream_t stream,
186 const void *buffer, size_t length,
187 const char *delimiters, size_t *bytes_written)
189 const char *p = buffer;
192 /* We can handle plain ascii simpler, so check for it first. */
193 for (i=0; i < length; i++ )
200 int delim = delimiters? *delimiters : 0;
204 /*(utf8 conversion already does the control character quoting). */
205 buf = utf8_to_native (p, length, delim);
207 *bytes_written = strlen (buf);
208 ret = es_fputs (buf, stream);
210 return ret == EOF? ret : (int)i;
213 return es_write_sanitized (stream, p, length, delimiters, bytes_written);
218 print_utf8_buffer3 (estream_t stream, const void *p, size_t n,
221 do_print_utf8_buffer (stream, p, n, delim, NULL);
226 print_utf8_buffer2 (estream_t stream, const void *p, size_t n, int delim)
232 do_print_utf8_buffer (stream, p, n, tmp, NULL);
237 print_utf8_buffer (estream_t stream, const void *p, size_t n)
239 do_print_utf8_buffer (stream, p, n, NULL, NULL);
244 print_utf8_string (estream_t stream, const char *p)
248 do_print_utf8_buffer (stream, p, strlen (p), NULL, NULL);
252 /* Write LENGTH bytes of BUFFER to FP as a hex encoded string.
253 RESERVED must be 0. */
255 print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved)
257 #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A'))
258 const unsigned char *s;
262 for (s = buffer; length; s++, length--)
264 putc ( tohex ((*s>>4)&15), fp);
265 putc ( tohex (*s&15), fp);
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. */
276 try_make_printable_string (const void *p_arg, size_t n, int delim)
278 const unsigned char *p = p_arg;
279 size_t save_n, buflen;
280 const unsigned char *save_p;
283 /* First count length. */
284 for (save_n = n, save_p = p, buflen=1 ; n; n--, p++ )
286 if ( *p < 0x20 || *p == 0x7f || *p == delim || (delim && *p=='\\'))
288 if ( *p=='\n' || *p=='\r' || *p=='\f'
289 || *p=='\v' || *p=='\b' || !*p )
299 /* And now make the string */
300 d = buffer = xtrymalloc (buflen);
301 for ( ; n; n--, p++ )
303 if (*p < 0x20 || *p == 0x7f || *p == delim || (delim && *p=='\\')) {
307 else if( *p == '\r' )
309 else if( *p == '\f' )
311 else if( *p == '\v' )
313 else if( *p == '\b' )
318 sprintf(d, "x%02x", *p );
330 /* Same as try_make_printable_string but terminates the process on
331 * memory shortage. */
333 make_printable_string (const void *p, size_t n, int delim )
335 char *string = try_make_printable_string (p, n, delim);
342 /* Decode the C formatted string SRC and return the result in a newly
343 * allocated buffer. In error returns NULL and sets ERRNO. */
345 decode_c_string (const char *src)
350 /* The converted string will never be larger than the original
352 buffer = dst = xtrymalloc (strlen (src) + 1);
364 #define DECODE_ONE(_m,_r) case _m: src += 2; *dst++ = _r; break;
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 ('\"', '\"');
379 val = hextobyte (src+2);
380 if (val == -1) /* Bad coding, keep as is. */
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. */
400 *(unsigned char *)dst++ = val;
405 default: /* Bad coding; keep as is.. */
418 /* Check whether (BUF,LEN) is valid header for an OpenPGP compressed
419 * packet. LEN should be at least 6. */
421 is_openpgp_compressed_packet (unsigned char *buf, size_t len)
428 return 0; /* Invalid packet. */
430 if ((ctb & 0x40)) /* New style (OpenPGP) CTB. */
432 pkttype = (ctb & 0x3f);
434 return 0; /* Expected first length octet missing. */
441 return 0; /* Expected second length octet missing. */
446 return 0; /* Expected length octets missing */
449 else /* Old style CTB. */
451 pkttype = (ctb>>2)&0xf;
452 lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3));
454 return 0; /* Not enough length bytes. */
457 return (pkttype == 8);
463 * Check if the file is compressed.
466 is_file_compressed (const char *s, int *ret_rc)
474 struct magic_compress_s {
478 { 3, { 0x42, 0x5a, 0x68, 0x00 } }, /* bzip2 */
479 { 3, { 0x1f, 0x8b, 0x08, 0x00 } }, /* gzip */
480 { 4, { 0x50, 0x4b, 0x03, 0x04 } }, /* (pk)zip */
483 if ( iobuf_is_pipe_filename (s) || !ret_rc )
484 return 0; /* We can't check stdin or no file was given */
488 *ret_rc = gpg_error_from_syserror ();
491 iobuf_ioctl (a, IOBUF_IOCTL_NO_CACHE, 1, NULL);
493 if ( iobuf_get_filelength( a, &overflow ) < 6 && !overflow) {
498 if ( iobuf_read( a, buf, 6 ) == -1 ) {
503 for ( i = 0; i < DIM( magic ); i++ ) {
504 if ( !memcmp( buf, magic[i].magic, magic[i].len ) ) {
511 if (is_openpgp_compressed_packet (buf, 6))
523 /* Try match against each substring of multistr, delimited by | */
525 match_multistr (const char *multistr,const char *match)
529 size_t seglen = strcspn (multistr,"|");
532 /* Using the localized strncasecmp! */
533 if (strncasecmp(multistr,match,seglen)==0)
536 if (*multistr == '|')
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. */
551 parse_version_number (const char *s, int *number)
555 if (*s == '0' && digitp (s+1))
556 return NULL; /* Leading zeros are not allowed. */
557 for (; digitp (s); s++ )
563 return val < 0? NULL : s;
566 /* Break up the complete string representation of the version number S,
567 which is expected to have this format:
569 <major number>.<minor number>.<micro number><patch level>.
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
576 parse_version_string (const char *s, int *major, int *minor, int *micro)
578 s = parse_version_number (s, major);
582 s = parse_version_number (s, minor);
586 s = parse_version_number (s, micro);
589 return s; /* Patchlevel. */
592 /* Return true if version string is at least version B. */
594 gnupg_compare_version (const char *a, const char *b)
596 int a_major, a_minor, a_micro;
597 int b_major, b_minor, b_micro;
598 const char *a_plvl, *b_plvl;
603 /* Parse version A. */
604 a_plvl = parse_version_string (a, &a_major, &a_minor, &a_micro);
606 return 0; /* Invalid version number. */
608 /* Parse version B. */
609 b_plvl = parse_version_string (b, &b_major, &b_minor, &b_micro);
611 return 0; /* Invalid version number. */
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));
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.
628 * Returns: 0 on success or -1 and ERRNO set on error. On success the
629 * supplied variable is updated by the parsed flags.
631 * If STRING is NULL the enabled debug flags are printed.
633 * See doc/DETAILS for a summary of used debug options.
636 parse_debug_flag (const char *string, unsigned int *debugvar,
637 const struct debug_flags_s *flags)
640 unsigned long result = 0;
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);
656 while (spacep (string))
664 if (!strcmp (string, "?") || !strcmp (string, "help"))
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)
672 else if (digitp (string))
675 result = strtoul (string, NULL, 0);
676 if (result == ULONG_MAX && errno == ERANGE)
682 words = strtokenize (string, ",");
685 for (i=0; words[i]; i++)
689 for (j=0; flags[j].name; j++)
690 if (!strcmp (words[i], flags[j].name))
692 result |= flags[j].flag;
697 if (!strcmp (words[i], "none"))
702 else if (!strcmp (words[i], "all"))
705 log_info (_("unknown debug flag '%s' ignored\n"), words[i]);
718 /* Parse an --comaptibility_flags style argument consisting of comma
721 * Returns: 0 on success or -1 and ERRNO set on error. On success the
722 * supplied variable is updated by the parsed flags.
724 * If STRING is NULL the enabled flags are printed.
727 parse_compatibility_flags (const char *string, unsigned int *flagvar,
728 const struct compatibility_flags_s *flags)
731 unsigned long result = 0;
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);
747 while (spacep (string))
750 if (!strcmp (string, "?") || !strcmp (string, "help"))
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)
761 words = strtokenize (string, ",");
764 for (i=0; words[i]; i++)
768 for (j=0; flags[j].name; j++)
769 if (!strcmp (words[i], flags[j].name))
771 result |= flags[j].flag;
776 if (!strcmp (words[i], "none"))
781 else if (!strcmp (words[i], "all"))
784 log_info ("unknown compatibility flag '%s' ignored\n",