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_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;
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 /* 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. */
127 gnupg_cipher_algo_name (int algo)
131 s = gcry_cipher_algo_name (algo);
132 if (!strcmp (s, "AES"))
139 obsolete_option (const char *configname, unsigned int configlineno,
143 log_info (_("%s:%u: obsolete option \"%s\" - it has no effect\n"),
144 configname, configlineno, name);
146 log_info (_("WARNING: \"%s%s\" is an obsolete option - it has no effect\n"),
151 /* Decide whether the filename is stdout or a real filename and return
152 * an appropriate string. */
154 print_fname_stdout (const char *s)
156 if( !s || (*s == '-' && !s[1]) )
162 /* Decide whether the filename is stdin or a real filename and return
163 * an appropriate string. */
165 print_fname_stdin (const char *s)
167 if( !s || (*s == '-' && !s[1]) )
174 do_print_utf8_buffer (estream_t stream,
175 const void *buffer, size_t length,
176 const char *delimiters, size_t *bytes_written)
178 const char *p = buffer;
181 /* We can handle plain ascii simpler, so check for it first. */
182 for (i=0; i < length; i++ )
189 int delim = delimiters? *delimiters : 0;
193 /*(utf8 conversion already does the control character quoting). */
194 buf = utf8_to_native (p, length, delim);
196 *bytes_written = strlen (buf);
197 ret = es_fputs (buf, stream);
199 return ret == EOF? ret : (int)i;
202 return es_write_sanitized (stream, p, length, delimiters, bytes_written);
207 print_utf8_buffer3 (estream_t stream, const void *p, size_t n,
210 do_print_utf8_buffer (stream, p, n, delim, NULL);
215 print_utf8_buffer2 (estream_t stream, const void *p, size_t n, int delim)
221 do_print_utf8_buffer (stream, p, n, tmp, NULL);
226 print_utf8_buffer (estream_t stream, const void *p, size_t n)
228 do_print_utf8_buffer (stream, p, n, NULL, NULL);
233 print_utf8_string (estream_t stream, const char *p)
237 do_print_utf8_buffer (stream, p, strlen (p), NULL, NULL);
241 /* Write LENGTH bytes of BUFFER to FP as a hex encoded string.
242 RESERVED must be 0. */
244 print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved)
246 #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A'))
247 const unsigned char *s;
251 for (s = buffer; length; s++, length--)
253 putc ( tohex ((*s>>4)&15), fp);
254 putc ( tohex (*s&15), fp);
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. */
265 try_make_printable_string (const void *p_arg, size_t n, int delim)
267 const unsigned char *p = p_arg;
268 size_t save_n, buflen;
269 const unsigned char *save_p;
272 /* First count length. */
273 for (save_n = n, save_p = p, buflen=1 ; n; n--, p++ )
275 if ( *p < 0x20 || *p == 0x7f || *p == delim || (delim && *p=='\\'))
277 if ( *p=='\n' || *p=='\r' || *p=='\f'
278 || *p=='\v' || *p=='\b' || !*p )
288 /* And now make the string */
289 d = buffer = xtrymalloc (buflen);
290 for ( ; n; n--, p++ )
292 if (*p < 0x20 || *p == 0x7f || *p == delim || (delim && *p=='\\')) {
296 else if( *p == '\r' )
298 else if( *p == '\f' )
300 else if( *p == '\v' )
302 else if( *p == '\b' )
307 sprintf(d, "x%02x", *p );
319 /* Same as try_make_printable_string but terminates the process on
320 * memory shortage. */
322 make_printable_string (const void *p, size_t n, int delim )
324 char *string = try_make_printable_string (p, n, delim);
331 /* Check whether (BUF,LEN) is valid header for an OpenPGP compressed
332 * packet. LEN should be at least 6. */
334 is_openpgp_compressed_packet (unsigned char *buf, size_t len)
341 return 0; /* Invalid packet. */
343 if ((ctb & 0x40)) /* New style (OpenPGP) CTB. */
345 pkttype = (ctb & 0x3f);
347 return 0; /* Expected first length octet missing. */
354 return 0; /* Expected second length octet missing. */
359 return 0; /* Expected length octets missing */
362 else /* Old style CTB. */
364 pkttype = (ctb>>2)&0xf;
365 lenbytes = ((ctb&3)==3)? 0 : (1<<(ctb & 3));
367 return 0; /* Not enough length bytes. */
370 return (pkttype == 8);
376 * Check if the file is compressed.
379 is_file_compressed (const char *s, int *ret_rc)
387 struct magic_compress_s {
391 { 3, { 0x42, 0x5a, 0x68, 0x00 } }, /* bzip2 */
392 { 3, { 0x1f, 0x8b, 0x08, 0x00 } }, /* gzip */
393 { 4, { 0x50, 0x4b, 0x03, 0x04 } }, /* (pk)zip */
396 if ( iobuf_is_pipe_filename (s) || !ret_rc )
397 return 0; /* We can't check stdin or no file was given */
401 *ret_rc = gpg_error_from_syserror ();
405 if ( iobuf_get_filelength( a, &overflow ) < 6 && !overflow) {
410 if ( iobuf_read( a, buf, 6 ) == -1 ) {
415 for ( i = 0; i < DIM( magic ); i++ ) {
416 if ( !memcmp( buf, magic[i].magic, magic[i].len ) ) {
423 if (is_openpgp_compressed_packet (buf, 6))
435 /* Try match against each substring of multistr, delimited by | */
437 match_multistr (const char *multistr,const char *match)
441 size_t seglen = strcspn (multistr,"|");
444 /* Using the localized strncasecmp! */
445 if (strncasecmp(multistr,match,seglen)==0)
448 if (*multistr == '|')
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. */
463 parse_version_number (const char *s, int *number)
467 if (*s == '0' && digitp (s+1))
468 return NULL; /* Leading zeros are not allowed. */
469 for (; digitp (s); s++ )
475 return val < 0? NULL : s;
478 /* Break up the complete string representation of the version number S,
479 which is expected to have this format:
481 <major number>.<minor number>.<micro number><patch level>.
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
488 parse_version_string (const char *s, int *major, int *minor, int *micro)
490 s = parse_version_number (s, major);
494 s = parse_version_number (s, minor);
498 s = parse_version_number (s, micro);
501 return s; /* Patchlevel. */
504 /* Return true if version string is at least version B. */
506 gnupg_compare_version (const char *a, const char *b)
508 int a_major, a_minor, a_micro;
509 int b_major, b_minor, b_micro;
510 const char *a_plvl, *b_plvl;
515 /* Parse version A. */
516 a_plvl = parse_version_string (a, &a_major, &a_minor, &a_micro);
518 return 0; /* Invalid version number. */
520 /* Parse version B. */
521 b_plvl = parse_version_string (b, &b_major, &b_minor, &b_micro);
523 return 0; /* Invalid version number. */
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));
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.
540 * Returns: 0 on success or -1 and ERRNO set on error. On success the
541 * supplied variable is updated by the parsed flags.
543 * If STRING is NULL the enabled debug flags are printed.
545 * See doc/DETAILS for a summary of used debug options.
548 parse_debug_flag (const char *string, unsigned int *debugvar,
549 const struct debug_flags_s *flags)
552 unsigned long result = 0;
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);
568 while (spacep (string))
576 if (!strcmp (string, "?") || !strcmp (string, "help"))
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)
584 else if (digitp (string))
587 result = strtoul (string, NULL, 0);
588 if (result == ULONG_MAX && errno == ERANGE)
594 words = strtokenize (string, ",");
597 for (i=0; words[i]; i++)
601 for (j=0; flags[j].name; j++)
602 if (!strcmp (words[i], flags[j].name))
604 result |= flags[j].flag;
609 if (!strcmp (words[i], "none"))
614 else if (!strcmp (words[i], "all"))
617 log_info (_("unknown debug flag '%s' ignored\n"), words[i]);