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);
231 /* Write LENGTH bytes of BUFFER to FP as a hex encoded string.
232 RESERVED must be 0. */
234 print_hexstring (FILE *fp, const void *buffer, size_t length, int reserved)
236 #define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A'))
237 const unsigned char *s;
241 for (s = buffer; length; s++, length--)
243 putc ( tohex ((*s>>4)&15), fp);
244 putc ( tohex (*s&15), fp);
250 /* Create a string from the buffer P_ARG of length N which is suitable
251 * for printing. Caller must release the created string using xfree.
252 * On error ERRNO is set and NULL returned. Errors are only possible
253 * due to malloc failure. */
255 try_make_printable_string (const void *p_arg, size_t n, int delim)
257 const unsigned char *p = p_arg;
258 size_t save_n, buflen;
259 const unsigned char *save_p;
262 /* First count length. */
263 for (save_n = n, save_p = p, buflen=1 ; n; n--, p++ )
265 if ( *p < 0x20 || *p == 0x7f || *p == delim || (delim && *p=='\\'))
267 if ( *p=='\n' || *p=='\r' || *p=='\f'
268 || *p=='\v' || *p=='\b' || !*p )
278 /* And now make the string */
279 d = buffer = xtrymalloc (buflen);
280 for ( ; n; n--, p++ )
282 if (*p < 0x20 || *p == 0x7f || *p == delim || (delim && *p=='\\')) {
286 else if( *p == '\r' )
288 else if( *p == '\f' )
290 else if( *p == '\v' )
292 else if( *p == '\b' )
297 sprintf(d, "x%02x", *p );
309 /* Same as try_make_printable_string but terminates the process on
310 * memory shortage. */
312 make_printable_string (const void *p, size_t n, int delim )
314 char *string = try_make_printable_string (p, n, delim);
322 * Check if the file is compressed.
325 is_file_compressed (const char *s, int *ret_rc)
332 struct magic_compress_s {
336 { 3, { 0x42, 0x5a, 0x68, 0x00 } }, /* bzip2 */
337 { 3, { 0x1f, 0x8b, 0x08, 0x00 } }, /* gzip */
338 { 4, { 0x50, 0x4b, 0x03, 0x04 } }, /* (pk)zip */
341 if ( iobuf_is_pipe_filename (s) || !ret_rc )
342 return 0; /* We can't check stdin or no file was given */
346 *ret_rc = gpg_error_from_syserror ();
350 if ( iobuf_get_filelength( a, &overflow ) < 4 && !overflow) {
355 if ( iobuf_read( a, buf, 4 ) == -1 ) {
360 for ( i = 0; i < DIM( magic ); i++ ) {
361 if ( !memcmp( buf, magic[i].magic, magic[i].len ) ) {
374 /* Try match against each substring of multistr, delimited by | */
376 match_multistr (const char *multistr,const char *match)
380 size_t seglen = strcspn (multistr,"|");
383 /* Using the localized strncasecmp! */
384 if (strncasecmp(multistr,match,seglen)==0)
387 if (*multistr == '|')
397 /* Parse the first portion of the version number S and store it at
398 NUMBER. On success, the function returns a pointer into S starting
399 with the first character, which is not part of the initial number
400 portion; on failure, NULL is returned. */
402 parse_version_number (const char *s, int *number)
406 if (*s == '0' && digitp (s+1))
407 return NULL; /* Leading zeros are not allowed. */
408 for (; digitp (s); s++ )
414 return val < 0? NULL : s;
417 /* Break up the complete string representation of the version number S,
418 which is expected to have this format:
420 <major number>.<minor number>.<micro number><patch level>.
422 The major, minor and micro number components will be stored at
423 MAJOR, MINOR and MICRO. On success, a pointer to the last
424 component, the patch level, will be returned; on failure, NULL will
427 parse_version_string (const char *s, int *major, int *minor, int *micro)
429 s = parse_version_number (s, major);
433 s = parse_version_number (s, minor);
437 s = parse_version_number (s, micro);
440 return s; /* Patchlevel. */
443 /* Return true if version string is at least version B. */
445 gnupg_compare_version (const char *a, const char *b)
447 int a_major, a_minor, a_micro;
448 int b_major, b_minor, b_micro;
449 const char *a_plvl, *b_plvl;
454 /* Parse version A. */
455 a_plvl = parse_version_string (a, &a_major, &a_minor, &a_micro);
457 return 0; /* Invalid version number. */
459 /* Parse version B. */
460 b_plvl = parse_version_string (b, &b_major, &b_minor, &b_micro);
462 return 0; /* Invalid version number. */
464 /* Compare version numbers. */
465 return (a_major > b_major
466 || (a_major == b_major && a_minor > b_minor)
467 || (a_major == b_major && a_minor == b_minor
468 && a_micro > b_micro)
469 || (a_major == b_major && a_minor == b_minor
470 && a_micro == b_micro
471 && strcmp (a_plvl, b_plvl) >= 0));
476 /* Parse an --debug style argument. We allow the use of number values
477 * in the usual C notation or a string with comma separated keywords.
479 * Returns: 0 on success or -1 and ERRNO set on error. On success the
480 * supplied variable is updated by the parsed flags.
482 * If STRING is NULL the enabled debug flags are printed.
484 * See doc/DETAILS for a summary of used debug options.
487 parse_debug_flag (const char *string, unsigned int *debugvar,
488 const struct debug_flags_s *flags)
491 unsigned long result = 0;
498 log_info ("enabled debug flags:");
499 for (i=0; flags[i].name; i++)
500 if ((*debugvar & flags[i].flag))
501 log_printf (" %s", flags[i].name);
507 while (spacep (string))
515 if (!strcmp (string, "?") || !strcmp (string, "help"))
517 log_info ("available debug flags:\n");
518 for (i=0; flags[i].name; i++)
519 log_info (" %5u %s\n", flags[i].flag, flags[i].name);
520 if (flags[i].flag != 77)
523 else if (digitp (string))
526 result = strtoul (string, NULL, 0);
527 if (result == ULONG_MAX && errno == ERANGE)
533 words = strtokenize (string, ",");
536 for (i=0; words[i]; i++)
540 for (j=0; flags[j].name; j++)
541 if (!strcmp (words[i], flags[j].name))
543 result |= flags[j].flag;
548 if (!strcmp (words[i], "none"))
553 else if (!strcmp (words[i], "all"))
556 log_info (_("unknown debug flag '%s' ignored\n"), words[i]);