diff --git a/src/argparse.c b/src/argparse.c index 2dab2ca..fecd3b5 100644 --- a/src/argparse.c +++ b/src/argparse.c @@ -1,1593 +1,1593 @@ /* argparse.c - Argument Parser for option handling * Copyright (C) 1997-2001, 2006-2008, 2013-2017 Werner Koch * Copyright (C) 1998-2001, 2006-2008, 2012 Free Software Foundation, Inc. * Copyright (C) 2015-2018 g10 Code GmbH * * This file is part of Libgpg-error. * * This file is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later * * This file was originally a part of GnuPG. */ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include "gpgrt-int.h" /* Special short options which are auto-inserterd. */ #define ARGPARSE_SHORTOPT_HELP 32768 #define ARGPARSE_SHORTOPT_VERSION 32769 #define ARGPARSE_SHORTOPT_WARRANTY 32770 #define ARGPARSE_SHORTOPT_DUMP_OPTIONS 32771 /* A mask for the types. */ #define ARGPARSE_TYPE_MASK 7 /* Mask for the type values. */ /* Internal object of the public gpgrt_argparse_t object. */ struct _gpgrt_argparse_internal_s { int idx; int inarg; int stopped; const char *last; void *aliases; const void *cur_alias; void *iio_list; gpgrt_opt_t **opts; /* Malloced array of pointer to user provided opts. */ }; typedef struct alias_def_s *ALIAS_DEF; struct alias_def_s { ALIAS_DEF next; char *name; /* malloced buffer with name, \0, value */ const char *value; /* ptr into name */ }; /* Object to store the names for the --ignore-invalid-option option. This is a simple linked list. */ typedef struct iio_item_def_s *IIO_ITEM_DEF; struct iio_item_def_s { IIO_ITEM_DEF next; char name[1]; /* String with the long option name. */ }; /* The almost always needed user handler for strusage. */ static const char *(*strusage_handler)( int ) = NULL; /* Optional handler to write strings. See _gpgrt_set_usage_outfnc. */ static int (*custom_outfnc) (int, const char *); /* Optional handler to map strings. See _gpgrt_set_fixed_string_mapper. */ static const char *(*fixed_string_mapper)(const char*); static int set_opt_arg (gpgrt_argparse_t *arg, unsigned int flags, char *s); static void show_help (gpgrt_opt_t **opts, unsigned int flags); static void show_version (void); static int writestrings (int is_error, const char *string, ...) GPGRT_ATTR_SENTINEL(0); static int arg_parse (gpgrt_argparse_t *arg, gpgrt_opt_t *opts); /* Return true if the native charset is utf-8. */ static int is_native_utf8 (void) { static char result; if (!result) { const char *p = _gpgrt_strusage (8); if (!p || !*p || !strcmp (p, "utf-8")) result = 1; result |= 128; } return (result & 1); } static char * trim_spaces (char *str) { char *string, *p, *mark; string = str; /* Find first non space character. */ for (p=string; *p && isspace (*(unsigned char*)p) ; p++) ; /* Move characters. */ for ((mark = NULL); (*string = *p); string++, p++) if (isspace (*(unsigned char*)p)) { if (!mark) mark = string; } else mark = NULL; if (mark) *mark = '\0' ; /* Remove trailing spaces. */ return str ; } static const char * map_fixed_string (const char *string) { return fixed_string_mapper? fixed_string_mapper (string) : string; } /* Write STRING and all following const char * arguments either to stdout or, if IS_ERROR is set, to stderr. The list of strings must be terminated by a NULL. */ static int writestrings (int is_error, const char *string, ...) { va_list arg_ptr; const char *s; int count = 0; if (string) { s = string; va_start (arg_ptr, string); do { if (custom_outfnc) custom_outfnc (is_error? 2:1, s); else fputs (s, is_error? stderr : stdout); count += strlen (s); } while ((s = va_arg (arg_ptr, const char *))); va_end (arg_ptr); } return count; } static void flushstrings (int is_error) { if (custom_outfnc) custom_outfnc (is_error? 2:1, NULL); else _gpgrt_fflush (is_error? es_stderr : es_stdout); } static void deinitialize (gpgrt_argparse_t *arg) { if (arg->internal) { xfree (arg->internal->opts); xfree (arg->internal); arg->internal = NULL; } arg->lineno = 0; arg->err = 0; } /* Our own exit handler to clean up used memory. */ static void my_exit (gpgrt_argparse_t *arg, int code) { deinitialize (arg); exit (code); } static gpg_err_code_t initialize (gpgrt_argparse_t *arg, gpgrt_opt_t *opts, estream_t fp) { if (!arg->internal || (arg->flags & ARGPARSE_FLAG_RESET)) { /* Allocate internal data. */ if (!arg->internal) { arg->internal = xtrymalloc (sizeof *arg->internal); if (!arg->internal) return _gpg_err_code_from_syserror (); } else if (arg->internal->opts) xfree (arg->internal->opts); arg->internal->opts = NULL; /* Initialize this instance. */ arg->internal->idx = 0; arg->internal->last = NULL; arg->internal->inarg = 0; arg->internal->stopped = 0; arg->internal->aliases = NULL; arg->internal->cur_alias = NULL; arg->internal->iio_list = NULL; /* Clear the copy of the option list. */ /* Clear the error indicator. */ arg->err = 0; /* Usually an option file will be parsed from the start. * However, we do not open the stream and thus we have no way to * know the current lineno. Using this flag we can allow the * user to provide a lineno which we don't reset. */ if (fp || !(arg->flags & ARGPARSE_FLAG_NOLINENO)) arg->lineno = 0; /* Need to clear the reset request. */ arg->flags &= ~ARGPARSE_FLAG_RESET; /* Check initial args. */ if ( *arg->argc < 0 ) _gpgrt_log_bug ("invalid argument passed to gpgrt_argparse\n"); } /* Create an array with pointers to the provided list of options. * Keeping a copy is useful to sort that array and thus do a binary * search and to allow for extra space at the end to insert the * hidden options. An ARGPARSE_FLAG_RESET can be used to reinit * this array. */ if (!arg->internal->opts) { static gpgrt_opt_t help_opt = ARGPARSE_s_n (ARGPARSE_SHORTOPT_HELP, "help", "@"); static gpgrt_opt_t version_opt = ARGPARSE_s_n (ARGPARSE_SHORTOPT_VERSION, "version", "@"); static gpgrt_opt_t warranty_opt = ARGPARSE_s_n (ARGPARSE_SHORTOPT_WARRANTY, "warranty", "@"); static gpgrt_opt_t dump_options_opt = ARGPARSE_s_n(ARGPARSE_SHORTOPT_DUMP_OPTIONS, "dump-options", "@"); static gpgrt_opt_t end_marker = ARGPARSE_end (); int seen_help = 0; int seen_version = 0; int seen_warranty = 0; int seen_dump_options = 0; int i; for (i=0; opts[i].short_opt; i++) { if (opts[i].long_opt) { if (!strcmp(opts[i].long_opt, help_opt.long_opt)) seen_help = 1; else if (!strcmp(opts[i].long_opt, version_opt.long_opt)) seen_version = 1; else if (!strcmp(opts[i].long_opt, warranty_opt.long_opt)) seen_warranty = 1; else if (!strcmp(opts[i].long_opt, dump_options_opt.long_opt)) seen_dump_options = 1; } } i += 4; /* The number of the above internal options. */ i++; /* End of list marker. */ arg->internal->opts = xtrycalloc (i, sizeof *arg->internal->opts); if (!arg->internal->opts) return _gpg_err_code_from_syserror (); for(i=0; opts[i].short_opt; i++) arg->internal->opts[i] = opts + i; if (!seen_help) arg->internal->opts[i++] = &help_opt; if (!seen_version) arg->internal->opts[i++] = &version_opt; if (!seen_warranty) arg->internal->opts[i++] = &warranty_opt; if (!seen_dump_options) arg->internal->opts[i++] = &dump_options_opt; arg->internal->opts[i] = &end_marker; } if (arg->err) { /* Last option was erroneous. */ const char *s; if (fp) { if ( arg->r_opt == ARGPARSE_UNEXPECTED_ARG ) s = _("argument not expected"); else if ( arg->r_opt == ARGPARSE_READ_ERROR ) s = _("read error"); else if ( arg->r_opt == ARGPARSE_KEYWORD_TOO_LONG ) s = _("keyword too long"); else if ( arg->r_opt == ARGPARSE_MISSING_ARG ) s = _("missing argument"); else if ( arg->r_opt == ARGPARSE_INVALID_ARG ) s = _("invalid argument"); else if ( arg->r_opt == ARGPARSE_INVALID_COMMAND ) s = _("invalid command"); else if ( arg->r_opt == ARGPARSE_INVALID_ALIAS ) s = _("invalid alias definition"); else if ( arg->r_opt == ARGPARSE_OUT_OF_CORE ) s = _("out of core"); else s = _("invalid option"); _gpgrt_log_error ("%s:%u: %s\n", _gpgrt_fname_get (fp), arg->lineno, s); } else { s = arg->internal->last? arg->internal->last:"[??]"; if ( arg->r_opt == ARGPARSE_MISSING_ARG ) _gpgrt_log_error (_("missing argument for option \"%.50s\"\n"), s); else if ( arg->r_opt == ARGPARSE_INVALID_ARG ) _gpgrt_log_error (_("invalid argument for option \"%.50s\"\n"), s); else if ( arg->r_opt == ARGPARSE_UNEXPECTED_ARG ) _gpgrt_log_error (_("option \"%.50s\" does not expect " "an argument\n"), s); else if ( arg->r_opt == ARGPARSE_INVALID_COMMAND ) _gpgrt_log_error (_("invalid command \"%.50s\"\n"), s); else if ( arg->r_opt == ARGPARSE_AMBIGUOUS_OPTION ) _gpgrt_log_error (_("option \"%.50s\" is ambiguous\n"), s); else if ( arg->r_opt == ARGPARSE_AMBIGUOUS_COMMAND ) _gpgrt_log_error (_("command \"%.50s\" is ambiguous\n"),s ); else if ( arg->r_opt == ARGPARSE_OUT_OF_CORE ) _gpgrt_log_error ("%s\n", _("out of core\n")); else _gpgrt_log_error (_("invalid option \"%.50s\"\n"), s); } if (arg->err != ARGPARSE_PRINT_WARNING) my_exit (arg, 2); arg->err = 0; } /* Zero out the return value union. */ arg->r.ret_str = NULL; arg->r.ret_long = 0; return 0; } static void store_alias( gpgrt_argparse_t *arg, char *name, char *value ) { /* TODO: replace this dummy function with a rea one * and fix the probelms IRIX has with (ALIAS_DEV)arg.. * used as lvalue */ (void)arg; (void)name; (void)value; #if 0 ALIAS_DEF a = xmalloc( sizeof *a ); a->name = name; a->value = value; a->next = (ALIAS_DEF)arg->internal->aliases; (ALIAS_DEF)arg->internal->aliases = a; #endif } /* Return true if KEYWORD is in the ignore-invalid-option list. */ static int ignore_invalid_option_p (gpgrt_argparse_t *arg, const char *keyword) { IIO_ITEM_DEF item = arg->internal->iio_list; for (; item; item = item->next) if (!strcmp (item->name, keyword)) return 1; return 0; } /* Add the keywords up to the next LF to the list of to be ignored options. After returning FP will either be at EOF or the next character read wll be the first of a new line. The function returns 0 on success or true on malloc failure. */ static int ignore_invalid_option_add (gpgrt_argparse_t *arg, estream_t fp) { IIO_ITEM_DEF item; int c; char name[100]; int namelen = 0; int ready = 0; enum { skipWS, collectNAME, skipNAME, addNAME} state = skipWS; while (!ready) { c = _gpgrt_fgetc (fp); if (c == '\n') ready = 1; else if (c == EOF) { c = '\n'; ready = 1; } again: switch (state) { case skipWS: if (!isascii (c) || !isspace(c)) { namelen = 0; state = collectNAME; goto again; } break; case collectNAME: if (isspace (c)) { state = addNAME; goto again; } else if (namelen < DIM(name)-1) name[namelen++] = c; else /* Too long. */ state = skipNAME; break; case skipNAME: if (isspace (c)) { state = skipWS; goto again; } break; case addNAME: name[namelen] = 0; if (!ignore_invalid_option_p (arg, name)) { item = xtrymalloc (sizeof *item + namelen); if (!item) return 1; strcpy (item->name, name); item->next = (IIO_ITEM_DEF)arg->internal->iio_list; arg->internal->iio_list = item; } state = skipWS; goto again; } } return 0; } /* Clear the entire ignore-invalid-option list. */ static void ignore_invalid_option_clear (gpgrt_argparse_t *arg) { IIO_ITEM_DEF item, tmpitem; for (item = arg->internal->iio_list; item; item = tmpitem) { tmpitem = item->next; xfree (item); } arg->internal->iio_list = NULL; } /**************** * Get options from a file. * Lines starting with '#' are comment lines. * Syntax is simply a keyword and the argument. * Valid keywords are all keywords from the long_opt list without * the leading dashes. The special keywords "help", "warranty" and "version" * are not valid here. * The special keyword "alias" may be used to store alias definitions, * which are later expanded like long options. * The option * ignore-invalid-option OPTIONNAMEs * is recognized and updates a list of option which should be ignored if they * are not defined. * Caller must free returned strings. * If called with FP set to NULL command line args are parse instead. * * Q: Should we allow the syntax * keyword = value * and accept for boolean options a value of 1/0, yes/no or true/false? * Note: Abbreviation of options is here not allowed. */ int _gpgrt_argparse (estream_t fp, gpgrt_argparse_t *arg, gpgrt_opt_t *opts_orig) { gpgrt_opt_t **opts; int state, i, c; int idx = 0; char keyword[100]; char *buffer = NULL; size_t buflen = 0; int in_alias=0; int unread_buf[3]; /* We use an int so that we can store EOF. */ int unread_buf_count = 0; if (arg && !opts_orig) { deinitialize (arg); return 0; } if (!fp) /* Divert to arg_parse() in this case. */ return arg_parse (arg, opts_orig); if (initialize (arg, opts_orig, fp)) return (arg->r_opt = ARGPARSE_OUT_OF_CORE); opts = arg->internal->opts; /* If the LINENO is zero we assume that we are at the start of a * file and we skip over a possible Byte Order Mark. */ if (!arg->lineno) { unread_buf[0] = _gpgrt_fgetc (fp); unread_buf[1] = _gpgrt_fgetc (fp); unread_buf[2] = _gpgrt_fgetc (fp); if (unread_buf[0] != 0xef || unread_buf[1] != 0xbb || unread_buf[2] != 0xbf) unread_buf_count = 3; } /* Find the next keyword. */ state = i = 0; for (;;) { if (unread_buf_count) c = unread_buf[3 - unread_buf_count--]; else c = _gpgrt_fgetc (fp); if (c == '\n' || c== EOF ) { if ( c != EOF ) arg->lineno++; if (state == -1) break; else if (state == 2) { keyword[i] = 0; for (i=0; opts[i]->short_opt; i++ ) { if (opts[i]->long_opt && !strcmp (opts[i]->long_opt, keyword)) break; } idx = i; arg->r_opt = opts[idx]->short_opt; if ((opts[idx]->flags & ARGPARSE_OPT_IGNORE)) { state = i = 0; continue; } else if (!opts[idx]->short_opt ) { if (!strcmp (keyword, "ignore-invalid-option")) { /* No argument - ignore this meta option. */ state = i = 0; continue; } else if (ignore_invalid_option_p (arg, keyword)) { /* This invalid option is in the iio list. */ state = i = 0; continue; } arg->r_opt = ((opts[idx]->flags & ARGPARSE_OPT_COMMAND) ? ARGPARSE_INVALID_COMMAND : ARGPARSE_INVALID_OPTION); } else if (!(opts[idx]->flags & ARGPARSE_TYPE_MASK)) arg->r_type = 0; /* Does not take an arg. */ else if ((opts[idx]->flags & ARGPARSE_OPT_OPTIONAL) ) arg->r_type = 0; /* Arg is optional. */ else arg->r_opt = ARGPARSE_MISSING_ARG; break; } else if (state == 3) { /* No argument found. */ if (in_alias) arg->r_opt = ARGPARSE_MISSING_ARG; else if (!(opts[idx]->flags & ARGPARSE_TYPE_MASK)) arg->r_type = 0; /* Does not take an arg. */ else if ((opts[idx]->flags & ARGPARSE_OPT_OPTIONAL)) arg->r_type = 0; /* No optional argument. */ else arg->r_opt = ARGPARSE_MISSING_ARG; break; } else if (state == 4) { /* Has an argument. */ if (in_alias) { if (!buffer) arg->r_opt = ARGPARSE_UNEXPECTED_ARG; else { char *p; buffer[i] = 0; p = strpbrk (buffer, " \t"); if (p) { *p++ = 0; trim_spaces (p); } if (!p || !*p) { xfree (buffer); arg->r_opt = ARGPARSE_INVALID_ALIAS; } else { store_alias (arg, buffer, p); } } } else if (!(opts[idx]->flags & ARGPARSE_TYPE_MASK)) arg->r_opt = ARGPARSE_UNEXPECTED_ARG; else { char *p; if (!buffer) { keyword[i] = 0; buffer = xtrystrdup (keyword); if (!buffer) arg->r_opt = ARGPARSE_OUT_OF_CORE; } else buffer[i] = 0; if (buffer) { trim_spaces (buffer); p = buffer; if (*p == '"') { /* Remove quotes. */ p++; if (*p && p[strlen(p)-1] == '\"' ) p[strlen(p)-1] = 0; } if (!set_opt_arg (arg, opts[idx]->flags, p)) xfree (buffer); else gpgrt_annotate_leaked_object (buffer); } } break; } else if (c == EOF) { ignore_invalid_option_clear (arg); if (_gpgrt_ferror (fp)) arg->r_opt = ARGPARSE_READ_ERROR; else arg->r_opt = 0; /* EOF. */ break; } state = 0; i = 0; } else if (state == -1) ; /* Skip. */ else if (state == 0 && isascii (c) && isspace(c)) ; /* Skip leading white space. */ else if (state == 0 && c == '#' ) state = 1; /* Start of a comment. */ else if (state == 1) ; /* Skip comments. */ else if (state == 2 && isascii (c) && isspace(c)) { /* Check keyword. */ keyword[i] = 0; for (i=0; opts[i]->short_opt; i++ ) if (opts[i]->long_opt && !strcmp (opts[i]->long_opt, keyword)) break; idx = i; arg->r_opt = opts[idx]->short_opt; if ((opts[idx]->flags & ARGPARSE_OPT_IGNORE)) { state = 1; /* Process like a comment. */ } else if (!opts[idx]->short_opt) { if (!strcmp (keyword, "alias")) { in_alias = 1; state = 3; } else if (!strcmp (keyword, "ignore-invalid-option")) { if (ignore_invalid_option_add (arg, fp)) { arg->r_opt = ARGPARSE_OUT_OF_CORE; break; } state = i = 0; arg->lineno++; } else if (ignore_invalid_option_p (arg, keyword)) state = 1; /* Process like a comment. */ else { arg->r_opt = ((opts[idx]->flags & ARGPARSE_OPT_COMMAND) ? ARGPARSE_INVALID_COMMAND : ARGPARSE_INVALID_OPTION); state = -1; /* Skip rest of line and leave. */ } } else state = 3; } else if (state == 3) { /* Skip leading spaces of the argument. */ if (!isascii (c) || !isspace(c)) { i = 0; keyword[i++] = c; state = 4; } } else if (state == 4) { /* Collect the argument. */ if (buffer) { if (i < buflen-1) buffer[i++] = c; else { char *tmp; size_t tmplen = buflen + 50; tmp = xtryrealloc (buffer, tmplen); if (tmp) { buflen = tmplen; buffer = tmp; buffer[i++] = c; } else { xfree (buffer); arg->r_opt = ARGPARSE_OUT_OF_CORE; break; } } } else if (i < DIM(keyword)-1) keyword[i++] = c; else { size_t tmplen = DIM(keyword) + 50; buffer = xtrymalloc (tmplen); if (buffer) { buflen = tmplen; memcpy(buffer, keyword, i); buffer[i++] = c; } else { arg->r_opt = ARGPARSE_OUT_OF_CORE; break; } } } else if (i >= DIM(keyword)-1) { arg->r_opt = ARGPARSE_KEYWORD_TOO_LONG; state = -1; /* Skip rest of line and leave. */ } else { keyword[i++] = c; state = 2; } } return arg->r_opt; } /* Given the list of options OPTS and a keyword, return the index of * the long option macthing KEYWORD. On error -1 is retruned for not * found or -2 for ambigious keyword. */ static int find_long_option (gpgrt_argparse_t *arg, gpgrt_opt_t **opts, const char *keyword) { int i; size_t n; (void)arg; /* Not yet required. */ /* Would be better if we can do a binary search, but it is not * possible to reorder our option table because we would mess up our * help strings. What we can do is: Build an option lookup table * when this function is first invoked. */ if (!*keyword) return -1; for (i=0; opts[i]->short_opt; i++ ) if (opts[i]->long_opt && !strcmp (opts[i]->long_opt, keyword)) return i; #if 0 { ALIAS_DEF a; /* see whether it is an alias */ for (a = args->internal->aliases; a; a = a->next) { if (!strcmp( a->name, keyword)) { /* todo: must parse the alias here */ args->internal->cur_alias = a; return -3; /* alias available */ } } } #endif /* Not found. See whether it is an abbreviation. Aliases may not * be abbreviated, though. */ n = strlen (keyword); for (i=0; opts[i]->short_opt; i++) { if (opts[i]->long_opt && !strncmp (opts[i]->long_opt, keyword, n)) { int j; for (j=i+1; opts[j]->short_opt; j++) { if (opts[j]->long_opt && !strncmp (opts[j]->long_opt, keyword, n) && !(opts[j]->short_opt == opts[i]->short_opt && opts[j]->flags == opts[i]->flags ) ) return -2; /* Abbreviation is ambiguous. */ } return i; } } return -1; /* Not found. */ } /* The option parser for command line options. */ static int arg_parse (gpgrt_argparse_t *arg, gpgrt_opt_t *opts_orig) { int idx; gpgrt_opt_t **opts; int argc; char **argv; char *s, *s2; int i; if (initialize (arg, opts_orig, NULL)) return (arg->r_opt = ARGPARSE_OUT_OF_CORE); opts = arg->internal->opts; argc = *arg->argc; argv = *arg->argv; idx = arg->internal->idx; if (!idx && argc && !(arg->flags & ARGPARSE_FLAG_ARG0)) { /* Skip the first argument. */ argc--; argv++; idx++; } next_one: if (!argc) { /* No more args. */ arg->r_opt = 0; goto leave; /* Ready. */ } s = *argv; arg->internal->last = s; if (arg->internal->stopped && (arg->flags & ARGPARSE_FLAG_ALL)) { arg->r_opt = ARGPARSE_IS_ARG; /* Not an option but an argument. */ arg->r_type = 2; arg->r.ret_str = s; argc--; argv++; idx++; /* set to next one */ } else if( arg->internal->stopped ) { arg->r_opt = 0; goto leave; /* Ready. */ } else if ( *s == '-' && s[1] == '-' ) { /* Long option. */ char *argpos; arg->internal->inarg = 0; if (!s[2] && !(arg->flags & ARGPARSE_FLAG_NOSTOP)) { /* Stop option processing. */ arg->internal->stopped = 1; arg->flags |= ARGPARSE_FLAG_STOP_SEEN; argc--; argv++; idx++; goto next_one; } argpos = strchr( s+2, '=' ); if ( argpos ) *argpos = 0; i = find_long_option ( arg, opts, s+2 ); if ( argpos ) *argpos = '='; if (i > 0 && opts[i]->short_opt == ARGPARSE_SHORTOPT_HELP) show_help (opts, arg->flags); else if (i > 0 && opts[i]->short_opt == ARGPARSE_SHORTOPT_VERSION) { if (!(arg->flags & ARGPARSE_FLAG_NOVERSION)) { show_version (); my_exit (arg, 0); } } else if (i > 0 && opts[i]->short_opt == ARGPARSE_SHORTOPT_WARRANTY) { writestrings (0, _gpgrt_strusage (16), "\n", NULL); my_exit (arg, 0); } else if (i > 0 && opts[i]->short_opt == ARGPARSE_SHORTOPT_DUMP_OPTIONS) { for (i=0; opts[i]->short_opt; i++ ) { if (opts[i]->long_opt && !(opts[i]->flags & ARGPARSE_OPT_IGNORE)) writestrings (0, "--", opts[i]->long_opt, "\n", NULL); } my_exit (arg, 0); } if ( i == -2 ) arg->r_opt = ARGPARSE_AMBIGUOUS_OPTION; else if ( i == -1 ) { arg->r_opt = ARGPARSE_INVALID_OPTION; arg->r.ret_str = s+2; } else arg->r_opt = opts[i]->short_opt; if ( i < 0 ) ; else if ( (opts[i]->flags & ARGPARSE_TYPE_MASK) ) { if ( argpos ) { s2 = argpos+1; if ( !*s2 ) s2 = NULL; } else s2 = argv[1]; if ( !s2 && (opts[i]->flags & ARGPARSE_OPT_OPTIONAL) ) { arg->r_type = ARGPARSE_TYPE_NONE; /* Argument is optional. */ } else if ( !s2 ) { arg->r_opt = ARGPARSE_MISSING_ARG; } else if ( !argpos && *s2 == '-' && (opts[i]->flags & ARGPARSE_OPT_OPTIONAL) ) { /* The argument is optional and the next seems to be an option. We do not check this possible option but assume no argument */ arg->r_type = ARGPARSE_TYPE_NONE; } else { set_opt_arg (arg, opts[i]->flags, s2); if ( !argpos ) { argc--; argv++; idx++; /* Skip one. */ } } } else { /* Does not take an argument. */ if ( argpos ) arg->r_type = ARGPARSE_UNEXPECTED_ARG; else arg->r_type = 0; } argc--; argv++; idx++; /* Set to next one. */ } else if ( (*s == '-' && s[1]) || arg->internal->inarg ) { /* Short option. */ int dash_kludge = 0; i = 0; if ( !arg->internal->inarg ) { arg->internal->inarg++; if ( (arg->flags & ARGPARSE_FLAG_ONEDASH) ) { for (i=0; opts[i]->short_opt; i++ ) if ( opts[i]->long_opt && !strcmp (opts[i]->long_opt, s+1)) { dash_kludge = 1; break; } } } s += arg->internal->inarg; if (!dash_kludge ) { for (i=0; opts[i]->short_opt; i++ ) if ( opts[i]->short_opt == *s ) break; } if ( !opts[i]->short_opt && ( *s == 'h' || *s == '?' ) ) show_help (opts, arg->flags); arg->r_opt = opts[i]->short_opt; if (!opts[i]->short_opt ) { arg->r_opt = (opts[i]->flags & ARGPARSE_OPT_COMMAND)? ARGPARSE_INVALID_COMMAND:ARGPARSE_INVALID_OPTION; arg->internal->inarg++; /* Point to the next arg. */ arg->r.ret_str = s; } else if ( (opts[i]->flags & ARGPARSE_TYPE_MASK) ) { if ( s[1] && !dash_kludge ) { s2 = s+1; set_opt_arg (arg, opts[i]->flags, s2); } else { s2 = argv[1]; if ( !s2 && (opts[i]->flags & ARGPARSE_OPT_OPTIONAL) ) { arg->r_type = ARGPARSE_TYPE_NONE; } else if ( !s2 ) { arg->r_opt = ARGPARSE_MISSING_ARG; } else if ( *s2 == '-' && s2[1] && (opts[i]->flags & ARGPARSE_OPT_OPTIONAL) ) { /* The argument is optional and the next seems to be an option. We do not check this possible option but assume no argument. */ arg->r_type = ARGPARSE_TYPE_NONE; } else { set_opt_arg (arg, opts[i]->flags, s2); argc--; argv++; idx++; /* Skip one. */ } } s = "x"; /* This is so that !s[1] yields false. */ } else { /* Does not take an argument. */ arg->r_type = ARGPARSE_TYPE_NONE; arg->internal->inarg++; /* Point to the next arg. */ } if ( !s[1] || dash_kludge ) { /* No more concatenated short options. */ arg->internal->inarg = 0; argc--; argv++; idx++; } } else if ( arg->flags & ARGPARSE_FLAG_MIXED ) { arg->r_opt = ARGPARSE_IS_ARG; arg->r_type = 2; arg->r.ret_str = s; argc--; argv++; idx++; /* Set to next one. */ } else { arg->internal->stopped = 1; /* Stop option processing. */ goto next_one; } leave: *arg->argc = argc; *arg->argv = argv; arg->internal->idx = idx; return arg->r_opt; } /* Returns: -1 on error, 0 for an integer type and 1 for a non integer type argument. */ static int set_opt_arg (gpgrt_argparse_t *arg, unsigned flags, char *s) { int base = (flags & ARGPARSE_OPT_PREFIX)? 0 : 10; long l; switch ( (arg->r_type = (flags & ARGPARSE_TYPE_MASK)) ) { case ARGPARSE_TYPE_LONG: case ARGPARSE_TYPE_INT: errno = 0; l = strtol (s, NULL, base); if ((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE) { arg->r_opt = ARGPARSE_INVALID_ARG; return -1; } if (arg->r_type == ARGPARSE_TYPE_LONG) arg->r.ret_long = l; else if ( (l < 0 && l < INT_MIN) || l > INT_MAX ) { arg->r_opt = ARGPARSE_INVALID_ARG; return -1; } else arg->r.ret_int = (int)l; return 0; case ARGPARSE_TYPE_ULONG: while (isascii (*s) && isspace(*s)) s++; if (*s == '-') { arg->r.ret_ulong = 0; arg->r_opt = ARGPARSE_INVALID_ARG; return -1; } errno = 0; arg->r.ret_ulong = strtoul (s, NULL, base); if (arg->r.ret_ulong == ULONG_MAX && errno == ERANGE) { arg->r_opt = ARGPARSE_INVALID_ARG; return -1; } return 0; case ARGPARSE_TYPE_STRING: default: arg->r.ret_str = s; return 1; } } /* Return the length of the option O. This needs to consider the * description as weel as the option name. */ static size_t long_opt_strlen (gpgrt_opt_t *o) { size_t n = strlen (o->long_opt); if ( o->description && *o->description == '|' ) { const char *s; int is_utf8 = is_native_utf8 (); s=o->description+1; if ( *s != '=' ) n++; /* For a (mostly) correct length calculation we exclude * continuation bytes (10xxxxxx) if we are on a native utf8 * terminal. */ for (; *s && *s != '|'; s++ ) if ( is_utf8 && (*s&0xc0) != 0x80 ) n++; } return n; } /**************** * Print formatted help. The description string has some special * meanings: * - A description string which is "@" suppresses help output for * this option * - a description,ine which starts with a '@' and is followed by * any other characters is printed as is; this may be used for examples * ans such. * - A description which starts with a '|' outputs the string between this * bar and the next one as arguments of the long option. */ static void show_help (gpgrt_opt_t **opts, unsigned int flags) { const char *s; char tmp[2]; show_version (); writestrings (0, "\n", NULL); s = _gpgrt_strusage (42); if (s && *s == '1') { s = _gpgrt_strusage (40); writestrings (1, s, NULL); if (*s && s[strlen(s)] != '\n') writestrings (1, "\n", NULL); } s = _gpgrt_strusage(41); writestrings (0, s, "\n", NULL); if ( opts[0]->description ) { /* Auto format the option description. */ int i,j, indent; /* Get max. length of long options. */ for (i=indent=0; opts[i]->short_opt; i++ ) { if ( opts[i]->long_opt ) if ( !opts[i]->description || *opts[i]->description != '@' ) if ( (j=long_opt_strlen(opts[i])) > indent && j < 35 ) indent = j; } /* Example: " -v, --verbose Viele Sachen ausgeben" */ indent += 10; if ( *opts[0]->description != '@' ) writestrings (0, "Options:", "\n", NULL); for (i=0; opts[i]->short_opt; i++ ) { s = map_fixed_string (_( opts[i]->description )); if ( s && *s== '@' && !s[1] ) /* Hide this line. */ continue; if ( s && *s == '@' ) /* Unindented comment only line. */ { for (s++; *s; s++ ) { if ( *s == '\n' ) { if( s[1] ) writestrings (0, "\n", NULL); } else { tmp[0] = *s; tmp[1] = 0; writestrings (0, tmp, NULL); } } writestrings (0, "\n", NULL); continue; } j = 3; if ( opts[i]->short_opt < 256 ) { tmp[0] = opts[i]->short_opt; tmp[1] = 0; writestrings (0, " -", tmp, NULL ); if ( !opts[i]->long_opt ) { if (s && *s == '|' ) { writestrings (0, " ", NULL); j++; for (s++ ; *s && *s != '|'; s++, j++ ) { tmp[0] = *s; tmp[1] = 0; writestrings (0, tmp, NULL); } if ( *s ) s++; } } } else writestrings (0, " ", NULL); if ( opts[i]->long_opt ) { tmp[0] = opts[i]->short_opt < 256?',':' '; tmp[1] = 0; j += writestrings (0, tmp, " --", opts[i]->long_opt, NULL); if (s && *s == '|' ) { if ( *++s != '=' ) { writestrings (0, " ", NULL); j++; } for ( ; *s && *s != '|'; s++, j++ ) { tmp[0] = *s; tmp[1] = 0; writestrings (0, tmp, NULL); } if ( *s ) s++; } writestrings (0, " ", NULL); j += 3; } for (;j < indent; j++ ) writestrings (0, " ", NULL); if ( s ) { if ( *s && j > indent ) { writestrings (0, "\n", NULL); for (j=0;j < indent; j++ ) writestrings (0, " ", NULL); } for (; *s; s++ ) { if ( *s == '\n' ) { if ( s[1] ) { writestrings (0, "\n", NULL); for (j=0; j < indent; j++ ) writestrings (0, " ", NULL); } } else { tmp[0] = *s; tmp[1] = 0; writestrings (0, tmp, NULL); } } } writestrings (0, "\n", NULL); } if ( (flags & ARGPARSE_FLAG_ONEDASH) ) writestrings (0, "\n(A single dash may be used " "instead of the double ones)\n", NULL); } if ( (s=_gpgrt_strusage(19)) ) { writestrings (0, "\n", NULL); writestrings (0, s, NULL); } flushstrings (0); exit (0); } static void show_version () { const char *s; int i; /* Version line. */ writestrings (0, _gpgrt_strusage (11), NULL); if ((s=_gpgrt_strusage (12))) writestrings (0, " (", s, ")", NULL); writestrings (0, " ", _gpgrt_strusage (13), "\n", NULL); /* Additional version lines. */ for (i=20; i < 30; i++) if ((s=_gpgrt_strusage (i))) writestrings (0, s, "\n", NULL); /* Copyright string. */ if ((s=_gpgrt_strusage (14))) writestrings (0, s, "\n", NULL); /* Licence string. */ if( (s=_gpgrt_strusage (10)) ) writestrings (0, s, "\n", NULL); /* Copying conditions. */ if ( (s=_gpgrt_strusage(15)) ) writestrings (0, s, NULL); /* Thanks. */ if ((s=_gpgrt_strusage(18))) writestrings (0, s, NULL); /* Additional program info. */ for (i=30; i < 40; i++ ) if ( (s=_gpgrt_strusage (i)) ) writestrings (0, s, NULL); flushstrings (0); } void _gpgrt_usage (int level) { const char *p; if (!level) { writestrings (1, _gpgrt_strusage(11), " ", _gpgrt_strusage(13), "; ", _gpgrt_strusage (14), "\n", NULL); flushstrings (1); } else if (level == 1) { p = _gpgrt_strusage (40); writestrings (1, p, NULL); if (*p && p[strlen(p)] != '\n') writestrings (1, "\n", NULL); exit (2); } else if (level == 2) { p = _gpgrt_strusage (42); if (p && *p == '1') { p = _gpgrt_strusage (40); writestrings (1, p, NULL); if (*p && p[strlen(p)] != '\n') writestrings (1, "\n", NULL); } writestrings (0, _gpgrt_strusage(41), "\n", NULL); exit (0); } } /* Level * 0: Print copyright string to stderr * 1: Print a short usage hint to stderr and terminate * 2: Print a long usage hint to stdout and terminate * 8: Return NULL for UTF-8 or string with the native charset. * 9: Return the SPDX License tag. * 10: Return license info string * 11: Return the name of the program * 12: Return optional name of package which includes this program. * 13: version string * 14: copyright string * 15: Short copying conditions (with LFs) * 16: Long copying conditions (with LFs) * 17: Optional printable OS name * 18: Optional thanks list (with LFs) * 19: Bug report info *20..29: Additional lib version strings. *30..39: Additional program info (with LFs) * 40: short usage note (with LF) * 41: long usage note (with LF) * 42: Flag string: * First char is '1': * The short usage notes needs to be printed * before the long usage note. */ const char * _gpgrt_strusage (int level) { const char *p = strusage_handler? strusage_handler(level) : NULL; const char *tmp; if ( p ) return map_fixed_string (p); switch ( level ) { case 8: break; /* Default to utf-8. */ case 9: p = "GPL-3.0-or-later"; /* Suggested license. */ break; case 10: tmp = _gpgrt_strusage (9); if (tmp && !strcmp (tmp, "GPL-2.0-or-later")) p = ("License GPL-2.0-or-later "); else if (tmp && !strcmp (tmp, "LGPL-2.1-or-later")) p = ("License LGPL-2.1-or-later "); else /* Default to GPLv3+. */ p = ("License GPL-3.0-or-later "); break; case 11: p = "foo"; break; case 13: p = "0.0"; break; case 14: p = "Copyright (C) YEAR NAME"; break; case 15: p = "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n"; break; case 16: tmp = _gpgrt_strusage (9); if (tmp && !strcmp (tmp, "GPL-2.0-or-later")) p = "This is free software; you can redistribute it and/or modify\n" "it under the terms of the GNU General Public License as published by\n" "the Free Software Foundation; either version 2 of the License, or\n" "(at your option) any later version.\n\n" "It is distributed in the hope that it will be useful,\n" "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" "GNU General Public License for more details.\n\n" "You should have received a copy of the GNU General Public License\n" "along with this software. If not, see .\n"; else if (tmp && !strcmp (tmp, "LGPL-2.1-or-later")) p = "This is free software; you can redistribute it and/or modify\n" "it under the terms of the GNU Lesser General Public License as\n" "published by the Free Software Foundation; either version 2.1 of\n" "the License, or (at your option) any later version.\n\n" "It is distributed in the hope that it will be useful,\n" "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" "GNU Lesser General Public License for more details.\n\n" "You should have received a copy of the GNU General Public License\n" "along with this software. If not, see .\n"; else /* Default */ p = "This is free software; you can redistribute it and/or modify\n" "it under the terms of the GNU General Public License as published by\n" "the Free Software Foundation; either version 3 of the License, or\n" "(at your option) any later version.\n\n" "It is distributed in the hope that it will be useful,\n" "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" "GNU General Public License for more details.\n\n" "You should have received a copy of the GNU General Public License\n" "along with this software. If not, see .\n"; break; case 40: /* short and long usage */ case 41: p = ""; break; } return p; } /* Set the usage handler. This function is basically a constructor. */ void _gpgrt_set_strusage (const char *(*f)(int) ) { strusage_handler = f; } -/* Set a function to write strings which is the used instead of +/* Set a function to write strings which is then used instead of * estream. The first arg of that function is MODE and the second the * STRING to write. A mode of 1 is used for writing to stdout and a * mode of 2 to write to stderr. Other modes are reserved and should * not output anything. A NULL for STRING requests a flush. */ void _gpgrt_set_usage_outfnc (int (*f)(int, const char *)) { custom_outfnc = f; } /* Register function F as a string mapper which takes a string as * argument, replaces known "@FOO@" style macros and returns a new * fixed string. Warning: The input STRING must have been allocated * statically. */ void _gpgrt_set_fixed_string_mapper (const char *(*f)(const char*)) { fixed_string_mapper = f; } diff --git a/src/gpg-error.c b/src/gpg-error.c index e0b0150..ade2bae 100644 --- a/src/gpg-error.c +++ b/src/gpg-error.c @@ -1,632 +1,631 @@ /* gpg-error.c - Determining gpg-error error codes. Copyright (C) 2004, 2016 g10 Code GmbH This file is part of libgpg-error. libgpg-error is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. libgpg-error is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with libgpg-error; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #if HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #ifdef HAVE_LOCALE_H # include #endif #ifdef ENABLE_NLS #ifdef HAVE_W32_SYSTEM # include "gettext.h" #else # include #endif # define _(a) gettext (a) # ifdef gettext_noop # define N_(a) gettext_noop (a) # else # define N_(a) (a) # endif #else # define _(a) (a) # define N_(a) (a) #endif #include #if HAVE_W32_SYSTEM /* The implementation follows below. */ static char *get_locale_dir (void); static void drop_locale_dir (char *locale_dir); #else #define get_locale_dir() LOCALEDIR #define drop_locale_dir(dir) #endif static void i18n_init (void) { #ifdef ENABLE_NLS char *locale_dir; #ifdef HAVE_LC_MESSAGES setlocale (LC_TIME, ""); setlocale (LC_MESSAGES, ""); #else # ifndef HAVE_W32_SYSTEM setlocale (LC_ALL, "" ); # endif #endif /* Note that for this program we would only need the textdomain call because libgpg-error already initializes itself to its locale dir (via gpg_err_init or a constructor). However this is only done for the static standard locale and thus if the above setlocale calls select a different locale the bindtext below will do something else. */ locale_dir = get_locale_dir (); if (locale_dir) { bindtextdomain (PACKAGE, locale_dir); drop_locale_dir (locale_dir); } textdomain (PACKAGE); #endif } #ifdef HAVE_W32_SYSTEM #include static char * get_locale_dir (void) { static wchar_t moddir[MAX_PATH+5]; char *result, *p; int nbytes; if (!GetModuleFileNameW (NULL, moddir, MAX_PATH)) *moddir = 0; #define SLDIR "\\share\\locale" if (*moddir) { nbytes = WideCharToMultiByte (CP_UTF8, 0, moddir, -1, NULL, 0, NULL, NULL); if (nbytes < 0) return NULL; result = malloc (nbytes + strlen (SLDIR) + 1); if (result) { nbytes = WideCharToMultiByte (CP_UTF8, 0, moddir, -1, result, nbytes, NULL, NULL); if (nbytes < 0) { free (result); result = NULL; } else { p = strrchr (result, '\\'); if (p) *p = 0; /* If we are installed below "bin" strip that part and use the top directory instead. */ p = strrchr (result, '\\'); if (p && !strcmp (p+1, "bin")) *p = 0; /* Append the static part. */ strcat (result, SLDIR); } } } else /* Use the old default value. */ { result = malloc (10 + strlen (SLDIR) + 1); if (result) { strcpy (result, "c:\\gnupg"); strcat (result, SLDIR); } } #undef SLDIR return result; } static void drop_locale_dir (char *locale_dir) { free (locale_dir); } #endif /* HAVE_W32_SYSTEM */ const char *gpg_strerror_sym (gpg_error_t err); const char *gpg_strsource_sym (gpg_error_t err); static int get_err_from_number (char *str, gpg_error_t *err) { unsigned long nr; char *tail; gpg_err_set_errno (0); nr = strtoul (str, &tail, 0); if (errno) return 0; if (nr > UINT_MAX) return 0; if (*tail) { unsigned long cnr = strtoul (tail + 1, &tail, 0); if (errno || *tail) return 0; if (nr >= GPG_ERR_SOURCE_DIM || cnr >= GPG_ERR_CODE_DIM) return 0; nr = gpg_err_make (nr, cnr); } *err = (unsigned int) nr; return 1; } static int get_err_from_symbol_one (char *str, gpg_error_t *err, int *have_source, int *have_code) { static const char src_prefix[] = "GPG_ERR_SOURCE_"; static const char code_prefix[] = "GPG_ERR_"; if (!strncasecmp (src_prefix, str, sizeof (src_prefix) - 1)) { gpg_err_source_t src; if (*have_source) return 0; *have_source = 1; str += sizeof (src_prefix) - 1; for (src = 0; src < GPG_ERR_SOURCE_DIM; src++) { const char *src_sym; src_sym = gpg_strsource_sym (src << GPG_ERR_SOURCE_SHIFT); if (src_sym && !strcasecmp (str, src_sym + sizeof (src_prefix) - 1)) { *err |= src << GPG_ERR_SOURCE_SHIFT; return 1; } } } else if (!strncasecmp (code_prefix, str, sizeof (code_prefix) - 1)) { gpg_err_code_t code; if (*have_code) return 0; *have_code = 1; str += sizeof (code_prefix) - 1; for (code = 0; code < GPG_ERR_CODE_DIM; code++) { const char *code_sym = gpg_strerror_sym (code); if (code_sym && !strcasecmp (str, code_sym + sizeof (code_prefix) - 1)) { *err |= code; return 1; } } } return 0; } static int get_err_from_symbol (char *str, gpg_error_t *err) { char *str2 = str; int have_source = 0; int have_code = 0; int ret; char *saved_pos = NULL; char saved_char; *err = 0; while (*str2 && ((*str2 >= 'A' && *str2 <= 'Z') || (*str2 >= '0' && *str2 <= '9') || *str2 == '_')) str2++; if (*str2) { saved_pos = str2; saved_char = *str2; *str2 = '\0'; str2++; } else str2 = NULL; ret = get_err_from_symbol_one (str, err, &have_source, &have_code); if (ret && str2) ret = get_err_from_symbol_one (str2, err, &have_source, &have_code); if (saved_pos) *saved_pos = saved_char; return ret; } static int get_err_from_str_one (char *str, gpg_error_t *err, int *have_source, int *have_code) { gpg_err_source_t src; gpg_err_code_t code; for (src = 0; src < GPG_ERR_SOURCE_DIM; src++) { const char *src_str = gpg_strsource (src << GPG_ERR_SOURCE_SHIFT); if (src_str && !strcasecmp (str, src_str)) { if (*have_source) return 0; *have_source = 1; *err |= src << GPG_ERR_SOURCE_SHIFT; return 1; } } for (code = 0; code < GPG_ERR_CODE_DIM; code++) { const char *code_str = gpg_strerror (code); if (code_str && !strcasecmp (str, code_str)) { if (*have_code) return 0; *have_code = 1; *err |= code; return 1; } } return 0; } static int get_err_from_str (char *str, gpg_error_t *err) { char *str2 = str; int have_source = 0; int have_code = 0; int ret; char *saved_pos = NULL; char saved_char = 0; /* (avoid warning) */ *err = 0; ret = get_err_from_str_one (str, err, &have_source, &have_code); if (ret) return ret; while (*str2 && ((*str2 >= 'A' && *str2 <= 'Z') || (*str2 >= 'a' && *str2 <= 'z') || (*str2 >= '0' && *str2 <= '9') || *str2 == '_')) str2++; if (*str2) { saved_pos = str2; saved_char = *str2; *((char *) str2) = '\0'; str2++; while (*str2 && !((*str2 >= 'A' && *str2 <= 'Z') || (*str2 >= 'a' && *str2 <= 'z') || (*str2 >= '0' && *str2 <= '9') || *str2 == '_')) str2++; } else str2 = NULL; ret = get_err_from_str_one (str, err, &have_source, &have_code); if (ret && str2) ret = get_err_from_str_one (str2, err, &have_source, &have_code); if (saved_pos) *saved_pos = saved_char; return ret; } static void print_desc (const char *symbol) { static int initialized; static FILE *fp; char line[512]; char *p; int indesc = 0; int blanklines = 0; int last_was_keyword = 0; if (!symbol) return; if (!initialized) { initialized = 1; fp = fopen (PKGDATADIR "/errorref.txt", "r"); } if (!fp) return; rewind (fp); while (fgets (line, sizeof line, fp)) { if (*line == '#') continue; if (*line && line[strlen(line)-1] == '\n') line[strlen(line)-1] = 0; if (!strncmp (line, "GPG_ERR_", 8)) { if (indesc == 1 && last_was_keyword) continue; /* Skip keywords immediately following a matched * keyword. */ last_was_keyword = 1; indesc = 0; p = strchr (line, ' '); if (!p) continue; *p = 0; if (!strcmp (line, symbol)) { indesc = 1; continue; /* Skip this line. */ } } else last_was_keyword = 0; if (!indesc) continue; if (indesc == 1 && !*line) continue; /* Skip leading empty lines in a description. */ if (indesc == 1) putchar ('\n'); /* One leading empty line. */ indesc = 2; if (!*line) { blanklines++; continue; } for (; blanklines; blanklines--) putchar ('\n'); printf ("%s\n", line); } putchar ('\n'); /* One trailing blank line. */ } static const char * my_strusage (int level) { const char *p; switch (level) { case 9: p = "LGPL-2.1-or-later"; break; case 11: p = "gpg-error"; break; case 12: p = PACKAGE_NAME; break; case 13: p = PACKAGE_VERSION; break; case 14: p = "Copyright (C) 2018 g10 Code GmbH"; break; case 19: p = _("Please report bugs to .\n"); break; case 1: case 40: p = ("Usage: gpg-error [options] error-numbers"); break; case 41: p = ("Map error numbers to strings and vice versa.\n"); break; case 42: p = "1"; /* Flag: print 40 as part of 41. */ break; default: p = NULL; break; } return p; } int main (int argc, char *argv[]) { enum { CMD_DEFAULT = 0, CMD_LIB_VERSION = 501, CMD_LIST, CMD_DEFINES, OPT_DESC }; static gpgrt_opt_t opts[] = { ARGPARSE_c (CMD_LIB_VERSION, "lib-version", "Print library version"), ARGPARSE_c (CMD_LIST, "list", "Print all error codes"), ARGPARSE_c (CMD_DEFINES, "defines", "Print all error codes as #define lines"), ARGPARSE_s_n (OPT_DESC, "desc", "Print with error description"), ARGPARSE_end() }; gpgrt_argparse_t pargs = { &argc, &argv }; int i; int listmode = 0; int desc = 0; const char *source_sym; const char *error_sym; gpg_error_t err; gpgrt_init (); i18n_init (); gpgrt_set_strusage (my_strusage); gpgrt_log_set_prefix (gpgrt_strusage (11), GPGRT_LOG_WITH_PREFIX); while (gpgrt_argparse (NULL, &pargs, opts)) { switch (pargs.r_opt) { case CMD_LIB_VERSION: break; case CMD_LIST: listmode = 1; break; case CMD_DEFINES: listmode = 2; break; case OPT_DESC: desc = 1; break; default: pargs.err = ARGPARSE_PRINT_WARNING; break; } } gpgrt_argparse (NULL, &pargs, NULL); /* Free internal memory. */ - log_debug ("argc=%d listmode=%d\n", argc, listmode); if ((argc && listmode) || (!argc && !listmode)) gpgrt_usage (1); if (listmode == 1) { for (i=0; i < GPG_ERR_SOURCE_DIM; i++) { /* We use error code 1 because gpg_err_make requires a non-zero error code. */ err = gpg_err_make (i, 1); err -= 1; source_sym = gpg_strsource_sym (err); if (source_sym) { printf ("%u = (%u, -) = (%s, -) = (%s, -)\n", err, gpg_err_source (err), source_sym, gpg_strsource (err)); if (desc) print_desc (source_sym); } } for (i=0; i < GPG_ERR_CODE_DIM; i++) { err = gpg_err_make (GPG_ERR_SOURCE_UNKNOWN, i); error_sym = gpg_strerror_sym (err); if (error_sym) { printf ("%u = (-, %u) = (-, %s) = (-, %s)\n", err, gpg_err_code (err), error_sym, gpg_strerror (err)); if (desc) print_desc (error_sym); } } } else if (listmode == 2) { int n, nmax; for (i=0, nmax=0; i < GPG_ERR_SOURCE_DIM; i++) { err = gpg_err_make (i, 1); source_sym = gpg_strsource_sym (err); if (source_sym) { n = strlen (source_sym); if (n > nmax) nmax = n; } } for (i=0; i < GPG_ERR_SOURCE_DIM; i++) { err = gpg_err_make (i, 1); source_sym = gpg_strsource_sym (err); if (source_sym) printf ("#define %-*s %3u\n", nmax,source_sym,gpg_err_source (err)); } for (i=0, nmax = 0; i < GPG_ERR_CODE_DIM; i++) { err = gpg_err_make (GPG_ERR_SOURCE_UNKNOWN, i); error_sym = gpg_strerror_sym (err); if (error_sym) { n = strlen (error_sym); if (n > nmax) nmax = n; } } for (i=0; i < GPG_ERR_CODE_DIM; i++) { err = gpg_err_make (GPG_ERR_SOURCE_UNKNOWN, i); error_sym = gpg_strerror_sym (err); if (error_sym) printf ("#define %-*s %5u\n", nmax, error_sym, gpg_err_code (err)); } } else /* Standard mode. */ { for (i=0; i < argc; i++) { if (get_err_from_number (argv[i], &err) || get_err_from_symbol (argv[i], &err) || get_err_from_str (argv[i], &err)) { source_sym = gpg_strsource_sym (err); error_sym = gpg_strerror_sym (err); printf ("%u = (%u, %u) = (%s, %s) = (%s, %s)\n", err, gpg_err_source (err), gpg_err_code (err), source_sym ? source_sym : "-", error_sym ? error_sym:"-", gpg_strsource (err), gpg_strerror (err)); if (desc) print_desc (error_sym); } else log_error (_("warning: could not recognize %s\n"), argv[i]); } } exit (0); } diff --git a/src/gpg-error.h.in b/src/gpg-error.h.in index 4c5ac38..8bcafcc 100644 --- a/src/gpg-error.h.in +++ b/src/gpg-error.h.in @@ -1,1280 +1,1280 @@ /* gpg-error.h or gpgrt.h - Common code for GnuPG and others. -*- c -*- * Copyright (C) 2001-2018 g10 Code GmbH * * This file is part of libgpg-error (aka libgpgrt). * * libgpg-error is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * libgpg-error is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1+ * * @configure_input@ */ /* The GnuPG project consists of many components. Error codes are * exchanged between all components. The common error codes and their * user-presentable descriptions are kept into a shared library to * allow adding new error codes and components without recompiling any * of the other components. In addition to error codes this library * also features several other groups of functions which are common to * all GnuPG components. They may be used by independet project as * well. The interfaces will not change in a backward incompatible way. * * An error code together with an error source build up an error * value. As the error value is been passed from one component to * another, it preserves the information about the source and nature * of the error. * * A component of the GnuPG project can define the following macros to * tune the behaviour of the library: * * GPG_ERR_SOURCE_DEFAULT: Define to an error source of type * gpg_err_source_t to make that source the default for gpg_error(). * Otherwise GPG_ERR_SOURCE_UNKNOWN is used as default. * * GPG_ERR_ENABLE_GETTEXT_MACROS: Define to provide macros to map the * internal gettext API to standard names. This has only an effect on * Windows platforms. * * GPGRT_ENABLE_ES_MACROS: Define to provide "es_" macros for the * estream functions. * * GPGRT_ENABLE_LOG_MACROS: Define to provide short versions of the * log functions. * * GPGRT_ENABLE_ARGPARSE_MACROS: Needs to be defined to provide the * mandatory macros of the argparse interface. */ #ifndef GPG_ERROR_H #define GPG_ERROR_H 1 #ifndef GPGRT_H #define GPGRT_H 1 #include #include #include /* The version string of this header. */ #define GPG_ERROR_VERSION @version@ #define GPGRT_VERSION @version@ /* The version number of this header. */ #define GPG_ERROR_VERSION_NUMBER @version-number@ #define GPGRT_VERSION_NUMBER @version-number@ #ifdef __GNUC__ # define GPG_ERR_INLINE __inline__ #elif defined(_MSC_VER) && _MSC_VER >= 1300 # define GPG_ERR_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L # define GPG_ERR_INLINE inline #else # ifndef GPG_ERR_INLINE # define GPG_ERR_INLINE # endif #endif #ifdef __cplusplus extern "C" { #if 0 /* just to make Emacs auto-indent happy */ } #endif #endif /* __cplusplus */ /* The error source type gpg_err_source_t. * * Where as the Poo out of a welle small * Taketh his firste springing and his sours. * --Chaucer. */ /* Only use free slots, never change or reorder the existing * entries. */ typedef enum { @include:err-sources@ /* This is one more than the largest allowed entry. */ GPG_ERR_SOURCE_DIM = 128 } gpg_err_source_t; /* The error code type gpg_err_code_t. */ /* Only use free slots, never change or reorder the existing * entries. */ typedef enum { @include:err-codes@ /* The following error codes are used to map system errors. */ #define GPG_ERR_SYSTEM_ERROR (1 << 15) @include:errnos@ /* This is one more than the largest allowed entry. */ GPG_ERR_CODE_DIM = 65536 } gpg_err_code_t; /* The error value type gpg_error_t. */ /* We would really like to use bit-fields in a struct, but using * structs as return values can cause binary compatibility issues, in * particular if you want to do it efficiently (also see * -freg-struct-return option to GCC). */ typedef unsigned int gpg_error_t; /* We use the lowest 16 bits of gpg_error_t for error codes. The 16th * bit indicates system errors. */ #define GPG_ERR_CODE_MASK (GPG_ERR_CODE_DIM - 1) /* Bits 17 to 24 are reserved. */ /* We use the upper 7 bits of gpg_error_t for error sources. */ #define GPG_ERR_SOURCE_MASK (GPG_ERR_SOURCE_DIM - 1) #define GPG_ERR_SOURCE_SHIFT 24 /* The highest bit is reserved. It shouldn't be used to prevent * potential negative numbers when transmitting error values as * text. */ /* * GCC feature test. */ #if __GNUC__ # define _GPG_ERR_GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) #else # define _GPG_ERR_GCC_VERSION 0 #endif #undef _GPG_ERR_HAVE_CONSTRUCTOR #if _GPG_ERR_GCC_VERSION > 30100 # define _GPG_ERR_CONSTRUCTOR __attribute__ ((__constructor__)) # define _GPG_ERR_HAVE_CONSTRUCTOR #else # define _GPG_ERR_CONSTRUCTOR #endif #define GPGRT_GCC_VERSION _GPG_ERR_GCC_VERSION #if _GPG_ERR_GCC_VERSION >= 29200 # define _GPGRT__RESTRICT __restrict__ #else # define _GPGRT__RESTRICT #endif /* The noreturn attribute. */ #if _GPG_ERR_GCC_VERSION >= 20500 # define GPGRT_ATTR_NORETURN __attribute__ ((__noreturn__)) #else # define GPGRT_ATTR_NORETURN #endif /* The printf attributes. */ #if _GPG_ERR_GCC_VERSION >= 40400 # define GPGRT_ATTR_PRINTF(f, a) \ __attribute__ ((format(__gnu_printf__,f,a))) # define GPGRT_ATTR_NR_PRINTF(f, a) \ __attribute__ ((__noreturn__, format(__gnu_printf__,f,a))) #elif _GPG_ERR_GCC_VERSION >= 20500 # define GPGRT_ATTR_PRINTF(f, a) \ __attribute__ ((format(printf,f,a))) # define GPGRT_ATTR_NR_PRINTF(f, a) \ __attribute__ ((__noreturn__, format(printf,f,a))) #else # define GPGRT_ATTR_PRINTF(f, a) # define GPGRT_ATTR_NR_PRINTF(f, a) #endif #if _GPG_ERR_GCC_VERSION >= 20800 # define GPGRT_ATTR_FORMAT_ARG(a) __attribute__ ((__format_arg__ (a))) #else # define GPGRT_ATTR_FORMAT_ARG(a) #endif /* The sentinel attribute. */ #if _GPG_ERR_GCC_VERSION >= 40000 # define GPGRT_ATTR_SENTINEL(a) __attribute__ ((sentinel(a))) #else # define GPGRT_ATTR_SENTINEL(a) #endif /* The used and unused attributes. * I am not sure since when the unused attribute is really supported. * In any case it it only needed for gcc versions which print a * warning. Thus let us require gcc >= 3.5. */ #if _GPG_ERR_GCC_VERSION >= 40000 # define GPGRT_ATTR_USED __attribute__ ((used)) #else # define GPGRT_ATTR_USED #endif #if _GPG_ERR_GCC_VERSION >= 30500 # define GPGRT_ATTR_UNUSED __attribute__ ((unused)) #else # define GPGRT_ATTR_UNUSED #endif /* The deprecated attribute. */ #if _GPG_ERR_GCC_VERSION >= 30100 # define GPGRT_ATTR_DEPRECATED __attribute__ ((__deprecated__)) #else # define GPGRT_ATTR_DEPRECATED #endif /* The pure attribute. */ #if _GPG_ERR_GCC_VERSION >= 29600 # define GPGRT_ATTR_PURE __attribute__ ((__pure__)) #else # define GPGRT_ATTR_PURE #endif /* The malloc attribute. */ #if _GPG_ERR_GCC_VERSION >= 30200 # define GPGRT_ATTR_MALLOC __attribute__ ((__malloc__)) #else # define GPGRT_ATTR_MALLOC #endif /* A macro defined if a GCC style __FUNCTION__ macro is available. */ #undef GPGRT_HAVE_MACRO_FUNCTION #if _GPG_ERR_GCC_VERSION >= 20500 # define GPGRT_HAVE_MACRO_FUNCTION 1 #endif /* A macro defined if the pragma GCC push_options is available. */ #undef GPGRT_HAVE_PRAGMA_GCC_PUSH #if _GPG_ERR_GCC_VERSION >= 40400 # define GPGRT_HAVE_PRAGMA_GCC_PUSH 1 #endif /* Detect LeakSanitizer (LSan) support for GCC and Clang based on * whether AddressSanitizer (ASAN) is enabled via -fsanitize=address). * Note that -fsanitize=leak just affect the linker options which * cannot be detected here. In that case you have to define the * GPGRT_HAVE_LEAK_SANITIZER macro manually. */ #ifdef __GNUC__ # ifdef __SANITIZE_ADDRESS__ # define GPGRT_HAVE_LEAK_SANITIZER # elif defined(__has_feature) # if __has_feature(address_sanitizer) # define GPGRT_HAVE_LEAK_SANITIZER # endif # endif #endif /* The new name for the inline macro. */ #define GPGRT_INLINE GPG_ERR_INLINE #ifdef GPGRT_HAVE_LEAK_SANITIZER # include #endif /* Mark heap objects as non-leaked memory. */ static GPGRT_INLINE void gpgrt_annotate_leaked_object (const void *p) { #ifdef GPGRT_HAVE_LEAK_SANITIZER __lsan_ignore_object(p); #else (void)p; #endif } /* * Initialization function. */ /* Initialize the library. This function should be run early. */ gpg_error_t gpg_err_init (void) _GPG_ERR_CONSTRUCTOR; /* If this is defined, the library is already initialized by the constructor and does not need to be initialized explicitely. */ #undef GPG_ERR_INITIALIZED #ifdef _GPG_ERR_HAVE_CONSTRUCTOR # define GPG_ERR_INITIALIZED 1 # define gpgrt_init() do { gpg_err_init (); } while (0) #else # define gpgrt_init() do { ; } while (0) #endif /* See the source on how to use the deinit function; it is usually not required. */ void gpg_err_deinit (int mode); /* Register blocking system I/O clamping functions. */ void gpgrt_set_syscall_clamp (void (*pre)(void), void (*post)(void)); /* Get current I/O clamping functions. */ void gpgrt_get_syscall_clamp (void (**r_pre)(void), void (**r_post)(void)); /* Register a custom malloc/realloc/free function. */ void gpgrt_set_alloc_func (void *(*f)(void *a, size_t n)); /* * Constructor and accessor functions. */ /* Construct an error value from an error code and source. Within a * subsystem, use gpg_error. */ static GPG_ERR_INLINE gpg_error_t gpg_err_make (gpg_err_source_t source, gpg_err_code_t code) { return code == GPG_ERR_NO_ERROR ? GPG_ERR_NO_ERROR : (((source & GPG_ERR_SOURCE_MASK) << GPG_ERR_SOURCE_SHIFT) | (code & GPG_ERR_CODE_MASK)); } /* The user should define GPG_ERR_SOURCE_DEFAULT before including this * file to specify a default source for gpg_error. */ #ifndef GPG_ERR_SOURCE_DEFAULT #define GPG_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_UNKNOWN #endif static GPG_ERR_INLINE gpg_error_t gpg_error (gpg_err_code_t code) { return gpg_err_make (GPG_ERR_SOURCE_DEFAULT, code); } /* Retrieve the error code from an error value. */ static GPG_ERR_INLINE gpg_err_code_t gpg_err_code (gpg_error_t err) { return (gpg_err_code_t) (err & GPG_ERR_CODE_MASK); } /* Retrieve the error source from an error value. */ static GPG_ERR_INLINE gpg_err_source_t gpg_err_source (gpg_error_t err) { return (gpg_err_source_t) ((err >> GPG_ERR_SOURCE_SHIFT) & GPG_ERR_SOURCE_MASK); } /* String functions. */ /* Return a pointer to a string containing a description of the error * code in the error value ERR. This function is not thread-safe. */ const char *gpg_strerror (gpg_error_t err); /* Return the error string for ERR in the user-supplied buffer BUF of * size BUFLEN. This function is, in contrast to gpg_strerror, * thread-safe if a thread-safe strerror_r() function is provided by * the system. If the function succeeds, 0 is returned and BUF * contains the string describing the error. If the buffer was not * large enough, ERANGE is returned and BUF contains as much of the * beginning of the error string as fits into the buffer. */ int gpg_strerror_r (gpg_error_t err, char *buf, size_t buflen); /* Return a pointer to a string containing a description of the error * source in the error value ERR. */ const char *gpg_strsource (gpg_error_t err); /* * Mapping of system errors (errno). */ /* Retrieve the error code for the system error ERR. This returns * GPG_ERR_UNKNOWN_ERRNO if the system error is not mapped (report * this). */ gpg_err_code_t gpg_err_code_from_errno (int err); /* Retrieve the system error for the error code CODE. This returns 0 * if CODE is not a system error code. */ int gpg_err_code_to_errno (gpg_err_code_t code); /* Retrieve the error code directly from the ERRNO variable. This * returns GPG_ERR_UNKNOWN_ERRNO if the system error is not mapped * (report this) and GPG_ERR_MISSING_ERRNO if ERRNO has the value 0. */ gpg_err_code_t gpg_err_code_from_syserror (void); /* Set the ERRNO variable. This function is the preferred way to set * ERRNO due to peculiarities on WindowsCE. */ void gpg_err_set_errno (int err); /* Return or check the version. Both functions are identical. */ const char *gpgrt_check_version (const char *req_version); const char *gpg_error_check_version (const char *req_version); /* System specific type definitions. */ @define:pid_t@ @define:gpgrt_ssize_t@ @define:gpgrt_off_t@ @include:os-add@ /* Self-documenting convenience functions. */ static GPG_ERR_INLINE gpg_error_t gpg_err_make_from_errno (gpg_err_source_t source, int err) { return gpg_err_make (source, gpg_err_code_from_errno (err)); } static GPG_ERR_INLINE gpg_error_t gpg_error_from_errno (int err) { return gpg_error (gpg_err_code_from_errno (err)); } static GPG_ERR_INLINE gpg_error_t gpg_error_from_syserror (void) { return gpg_error (gpg_err_code_from_syserror ()); } /* * Malloc and friends */ void *gpgrt_realloc (void *a, size_t n); void *gpgrt_malloc (size_t n); void *gpgrt_calloc (size_t n, size_t m); char *gpgrt_strdup (const char *string); char *gpgrt_strconcat (const char *s1, ...) GPGRT_ATTR_SENTINEL(0); void gpgrt_free (void *a); /* * System specific function wrappers. */ /* A getenv replacement which mallocs the returned string. */ char *gpgrt_getenv (const char *name); /* A setenv and a unsetenv replacement.*/ gpg_err_code_t gpgrt_setenv (const char *name, const char *value, int overwrite); #define gpgrt_unsetenv(n) gpgrt_setenv ((n), NULL, 1) /* A wrapper around mkdir using a string for the mode. */ gpg_err_code_t gpgrt_mkdir (const char *name, const char *modestr); /* A simple wrapper around chdir. */ gpg_err_code_t gpgrt_chdir (const char *name); /* Return the current WD as a malloced string. */ char *gpgrt_getcwd (void); /* * Lock functions. */ @include:lock-obj@ #define GPGRT_LOCK_DEFINE(name) \ static gpgrt_lock_t name = GPGRT_LOCK_INITIALIZER /* NB: If GPGRT_LOCK_DEFINE is not used, zero out the lock variable before passing it to gpgrt_lock_init. */ gpg_err_code_t gpgrt_lock_init (gpgrt_lock_t *lockhd); gpg_err_code_t gpgrt_lock_lock (gpgrt_lock_t *lockhd); gpg_err_code_t gpgrt_lock_trylock (gpgrt_lock_t *lockhd); gpg_err_code_t gpgrt_lock_unlock (gpgrt_lock_t *lockhd); gpg_err_code_t gpgrt_lock_destroy (gpgrt_lock_t *lockhd); /* * Thread functions. */ gpg_err_code_t gpgrt_yield (void); /* * Estream */ /* The definition of this struct is entirely private. You must not use it for anything. It is only here so some functions can be implemented as macros. */ struct _gpgrt_stream_internal; struct _gpgrt__stream { /* The layout of this struct must never change. It may be grown, but only if all functions which access the new members are versioned. */ /* Various flags. */ struct { unsigned int magic: 16; unsigned int writing: 1; unsigned int reserved: 15; } flags; /* A pointer to the stream buffer. */ unsigned char *buffer; /* The size of the buffer in bytes. */ size_t buffer_size; /* The length of the usable data in the buffer, only valid when in read mode (see flags). */ size_t data_len; /* The current position of the offset pointer, valid in read and write mode. */ size_t data_offset; size_t data_flushed; unsigned char *unread_buffer; size_t unread_buffer_size; /* The number of unread bytes. */ size_t unread_data_len; /* A pointer to our internal data for this stream. */ struct _gpgrt_stream_internal *intern; }; /* The opaque type for an estream. */ typedef struct _gpgrt__stream *gpgrt_stream_t; #ifdef GPGRT_ENABLE_ES_MACROS typedef struct _gpgrt__stream *estream_t; #endif typedef @api_ssize_t@ (*gpgrt_cookie_read_function_t) (void *cookie, void *buffer, size_t size); typedef @api_ssize_t@ (*gpgrt_cookie_write_function_t) (void *cookie, const void *buffer, size_t size); typedef int (*gpgrt_cookie_seek_function_t) (void *cookie, gpgrt_off_t *pos, int whence); typedef int (*gpgrt_cookie_close_function_t) (void *cookie); struct _gpgrt_cookie_io_functions { gpgrt_cookie_read_function_t func_read; gpgrt_cookie_write_function_t func_write; gpgrt_cookie_seek_function_t func_seek; gpgrt_cookie_close_function_t func_close; }; typedef struct _gpgrt_cookie_io_functions gpgrt_cookie_io_functions_t; #ifdef GPGRT_ENABLE_ES_MACROS typedef struct _gpgrt_cookie_io_functions es_cookie_io_functions_t; #define es_cookie_read_function_t gpgrt_cookie_read_function_t #define es_cookie_write_function_t gpgrt_cookie_read_function_t #define es_cookie_seek_function_t gpgrt_cookie_read_function_t #define es_cookie_close_function_t gpgrt_cookie_read_function_t #endif enum gpgrt_syshd_types { GPGRT_SYSHD_NONE = 0, /* No system handle available. */ GPGRT_SYSHD_FD = 1, /* A file descriptor as returned by open(). */ GPGRT_SYSHD_SOCK = 2, /* A socket as returned by socket(). */ GPGRT_SYSHD_RVID = 3, /* A rendezvous id (see libassuan's gpgcedev.c). */ GPGRT_SYSHD_HANDLE = 4 /* A HANDLE object (Windows). */ }; struct _gpgrt_syshd { enum gpgrt_syshd_types type; union { int fd; int sock; int rvid; void *handle; } u; }; typedef struct _gpgrt_syshd gpgrt_syshd_t; #ifdef GPGRT_ENABLE_ES_MACROS typedef struct _gpgrt_syshd es_syshd_t; #define ES_SYSHD_NONE GPGRT_SYSHD_NONE #define ES_SYSHD_FD GPGRT_SYSHD_FD #define ES_SYSHD_SOCK GPGRT_SYSHD_SOCK #define ES_SYSHD_RVID GPGRT_SYSHD_RVID #define ES_SYSHD_HANDLE GPGRT_SYSHD_HANDLE #endif /* The object used with gpgrt_poll. */ struct _gpgrt_poll_s { gpgrt_stream_t stream; unsigned int want_read:1; unsigned int want_write:1; unsigned int want_oob:1; unsigned int want_rdhup:1; unsigned int _reserv1:4; unsigned int got_read:1; unsigned int got_write:1; unsigned int got_oob:1; unsigned int got_rdhup:1; unsigned int _reserv2:4; unsigned int got_err:1; unsigned int got_hup:1; unsigned int got_nval:1; unsigned int _reserv3:4; unsigned int ignore:1; unsigned int user:8; /* For application use. */ }; typedef struct _gpgrt_poll_s gpgrt_poll_t; #ifdef GPGRT_ENABLE_ES_MACROS typedef struct _gpgrt_poll_s es_poll_t; #endif gpgrt_stream_t gpgrt_fopen (const char *_GPGRT__RESTRICT path, const char *_GPGRT__RESTRICT mode); gpgrt_stream_t gpgrt_mopen (void *_GPGRT__RESTRICT data, size_t data_n, size_t data_len, unsigned int grow, void *(*func_realloc) (void *mem, size_t size), void (*func_free) (void *mem), const char *_GPGRT__RESTRICT mode); gpgrt_stream_t gpgrt_fopenmem (size_t memlimit, const char *_GPGRT__RESTRICT mode); gpgrt_stream_t gpgrt_fopenmem_init (size_t memlimit, const char *_GPGRT__RESTRICT mode, const void *data, size_t datalen); gpgrt_stream_t gpgrt_fdopen (int filedes, const char *mode); gpgrt_stream_t gpgrt_fdopen_nc (int filedes, const char *mode); gpgrt_stream_t gpgrt_sysopen (gpgrt_syshd_t *syshd, const char *mode); gpgrt_stream_t gpgrt_sysopen_nc (gpgrt_syshd_t *syshd, const char *mode); gpgrt_stream_t gpgrt_fpopen (FILE *fp, const char *mode); gpgrt_stream_t gpgrt_fpopen_nc (FILE *fp, const char *mode); gpgrt_stream_t gpgrt_freopen (const char *_GPGRT__RESTRICT path, const char *_GPGRT__RESTRICT mode, gpgrt_stream_t _GPGRT__RESTRICT stream); gpgrt_stream_t gpgrt_fopencookie (void *_GPGRT__RESTRICT cookie, const char *_GPGRT__RESTRICT mode, gpgrt_cookie_io_functions_t functions); int gpgrt_fclose (gpgrt_stream_t stream); int gpgrt_fclose_snatch (gpgrt_stream_t stream, void **r_buffer, size_t *r_buflen); int gpgrt_onclose (gpgrt_stream_t stream, int mode, void (*fnc) (gpgrt_stream_t, void*), void *fnc_value); int gpgrt_fileno (gpgrt_stream_t stream); int gpgrt_fileno_unlocked (gpgrt_stream_t stream); int gpgrt_syshd (gpgrt_stream_t stream, gpgrt_syshd_t *syshd); int gpgrt_syshd_unlocked (gpgrt_stream_t stream, gpgrt_syshd_t *syshd); void _gpgrt_set_std_fd (int no, int fd); gpgrt_stream_t _gpgrt_get_std_stream (int fd); #define gpgrt_stdin _gpgrt_get_std_stream (0) #define gpgrt_stdout _gpgrt_get_std_stream (1) #define gpgrt_stderr _gpgrt_get_std_stream (2) void gpgrt_flockfile (gpgrt_stream_t stream); int gpgrt_ftrylockfile (gpgrt_stream_t stream); void gpgrt_funlockfile (gpgrt_stream_t stream); int gpgrt_feof (gpgrt_stream_t stream); int gpgrt_feof_unlocked (gpgrt_stream_t stream); int gpgrt_ferror (gpgrt_stream_t stream); int gpgrt_ferror_unlocked (gpgrt_stream_t stream); void gpgrt_clearerr (gpgrt_stream_t stream); void gpgrt_clearerr_unlocked (gpgrt_stream_t stream); int _gpgrt_pending (gpgrt_stream_t stream); /* (private) */ int _gpgrt_pending_unlocked (gpgrt_stream_t stream); /* (private) */ #define gpgrt_pending(stream) _gpgrt_pending (stream) #define gpgrt_pending_unlocked(stream) \ (((!(stream)->flags.writing) \ && (((stream)->data_offset < (stream)->data_len) \ || ((stream)->unread_data_len))) \ ? 1 : _gpgrt_pending_unlocked ((stream))) int gpgrt_fflush (gpgrt_stream_t stream); int gpgrt_fseek (gpgrt_stream_t stream, long int offset, int whence); int gpgrt_fseeko (gpgrt_stream_t stream, gpgrt_off_t offset, int whence); long int gpgrt_ftell (gpgrt_stream_t stream); gpgrt_off_t gpgrt_ftello (gpgrt_stream_t stream); void gpgrt_rewind (gpgrt_stream_t stream); int gpgrt_fgetc (gpgrt_stream_t stream); int gpgrt_fputc (int c, gpgrt_stream_t stream); int _gpgrt_getc_underflow (gpgrt_stream_t stream); /* (private) */ int _gpgrt_putc_overflow (int c, gpgrt_stream_t stream); /* (private) */ #define gpgrt_getc_unlocked(stream) \ (((!(stream)->flags.writing) \ && ((stream)->data_offset < (stream)->data_len) \ && (! (stream)->unread_data_len)) \ ? ((int) (stream)->buffer[((stream)->data_offset)++]) \ : _gpgrt_getc_underflow ((stream))) #define gpgrt_putc_unlocked(c, stream) \ (((stream)->flags.writing \ && ((stream)->data_offset < (stream)->buffer_size) \ && (c != '\n')) \ ? ((int) ((stream)->buffer[((stream)->data_offset)++] = (c))) \ : _gpgrt_putc_overflow ((c), (stream))) #define gpgrt_getc(stream) gpgrt_fgetc (stream) #define gpgrt_putc(c, stream) gpgrt_fputc (c, stream) int gpgrt_ungetc (int c, gpgrt_stream_t stream); int gpgrt_read (gpgrt_stream_t _GPGRT__RESTRICT stream, void *_GPGRT__RESTRICT buffer, size_t bytes_to_read, size_t *_GPGRT__RESTRICT bytes_read); int gpgrt_write (gpgrt_stream_t _GPGRT__RESTRICT stream, const void *_GPGRT__RESTRICT buffer, size_t bytes_to_write, size_t *_GPGRT__RESTRICT bytes_written); int gpgrt_write_sanitized (gpgrt_stream_t _GPGRT__RESTRICT stream, const void *_GPGRT__RESTRICT buffer, size_t length, const char *delimiters, size_t *_GPGRT__RESTRICT bytes_written); int gpgrt_write_hexstring (gpgrt_stream_t _GPGRT__RESTRICT stream, const void *_GPGRT__RESTRICT buffer, size_t length, int reserved, size_t *_GPGRT__RESTRICT bytes_written); size_t gpgrt_fread (void *_GPGRT__RESTRICT ptr, size_t size, size_t nitems, gpgrt_stream_t _GPGRT__RESTRICT stream); -size_t gpgrt_fwrite (const void *_GPGRT__RESTRICT ptr, size_t size, size_t memb, - gpgrt_stream_t _GPGRT__RESTRICT stream); +size_t gpgrt_fwrite (const void *_GPGRT__RESTRICT ptr, size_t size, + size_t nitems, gpgrt_stream_t _GPGRT__RESTRICT stream); char *gpgrt_fgets (char *_GPGRT__RESTRICT s, int n, gpgrt_stream_t _GPGRT__RESTRICT stream); int gpgrt_fputs (const char *_GPGRT__RESTRICT s, gpgrt_stream_t _GPGRT__RESTRICT stream); int gpgrt_fputs_unlocked (const char *_GPGRT__RESTRICT s, gpgrt_stream_t _GPGRT__RESTRICT stream); @api_ssize_t@ gpgrt_getline (char *_GPGRT__RESTRICT *_GPGRT__RESTRICT lineptr, size_t *_GPGRT__RESTRICT n, gpgrt_stream_t stream); @api_ssize_t@ gpgrt_read_line (gpgrt_stream_t stream, char **addr_of_buffer, size_t *length_of_buffer, size_t *max_length); int gpgrt_fprintf (gpgrt_stream_t _GPGRT__RESTRICT stream, const char *_GPGRT__RESTRICT format, ...) GPGRT_ATTR_PRINTF(2,3); int gpgrt_fprintf_unlocked (gpgrt_stream_t _GPGRT__RESTRICT stream, const char *_GPGRT__RESTRICT format, ...) GPGRT_ATTR_PRINTF(2,3); int gpgrt_printf (const char *_GPGRT__RESTRICT format, ...) GPGRT_ATTR_PRINTF(1,2); int gpgrt_printf_unlocked (const char *_GPGRT__RESTRICT format, ...) GPGRT_ATTR_PRINTF(1,2); int gpgrt_vfprintf (gpgrt_stream_t _GPGRT__RESTRICT stream, const char *_GPGRT__RESTRICT format, va_list ap) GPGRT_ATTR_PRINTF(2,0); int gpgrt_vfprintf_unlocked (gpgrt_stream_t _GPGRT__RESTRICT stream, const char *_GPGRT__RESTRICT format, va_list ap) GPGRT_ATTR_PRINTF(2,0); int gpgrt_setvbuf (gpgrt_stream_t _GPGRT__RESTRICT stream, char *_GPGRT__RESTRICT buf, int mode, size_t size); void gpgrt_setbuf (gpgrt_stream_t _GPGRT__RESTRICT stream, char *_GPGRT__RESTRICT buf); void gpgrt_set_binary (gpgrt_stream_t stream); int gpgrt_set_nonblock (gpgrt_stream_t stream, int onoff); int gpgrt_get_nonblock (gpgrt_stream_t stream); int gpgrt_poll (gpgrt_poll_t *fdlist, unsigned int nfds, int timeout); gpgrt_stream_t gpgrt_tmpfile (void); void gpgrt_opaque_set (gpgrt_stream_t _GPGRT__RESTRICT stream, void *_GPGRT__RESTRICT opaque); void *gpgrt_opaque_get (gpgrt_stream_t stream); void gpgrt_fname_set (gpgrt_stream_t stream, const char *fname); const char *gpgrt_fname_get (gpgrt_stream_t stream); int gpgrt_asprintf (char **r_buf, const char * _GPGRT__RESTRICT format, ...) GPGRT_ATTR_PRINTF(2,3); int gpgrt_vasprintf (char **r_buf, const char * _GPGRT__RESTRICT format, va_list ap) GPGRT_ATTR_PRINTF(2,0); char *gpgrt_bsprintf (const char * _GPGRT__RESTRICT format, ...) GPGRT_ATTR_PRINTF(1,2); char *gpgrt_vbsprintf (const char * _GPGRT__RESTRICT format, va_list ap) GPGRT_ATTR_PRINTF(1,0); int gpgrt_snprintf (char *buf, size_t bufsize, const char * _GPGRT__RESTRICT format, ...) GPGRT_ATTR_PRINTF(3,4); int gpgrt_vsnprintf (char *buf,size_t bufsize, const char * _GPGRT__RESTRICT format, va_list arg_ptr) GPGRT_ATTR_PRINTF(3,0); #ifdef GPGRT_ENABLE_ES_MACROS # define es_fopen gpgrt_fopen # define es_mopen gpgrt_mopen # define es_fopenmem gpgrt_fopenmem # define es_fopenmem_init gpgrt_fopenmem_init # define es_fdopen gpgrt_fdopen # define es_fdopen_nc gpgrt_fdopen_nc # define es_sysopen gpgrt_sysopen # define es_sysopen_nc gpgrt_sysopen_nc # define es_fpopen gpgrt_fpopen # define es_fpopen_nc gpgrt_fpopen_nc # define es_freopen gpgrt_freopen # define es_fopencookie gpgrt_fopencookie # define es_fclose gpgrt_fclose # define es_fclose_snatch gpgrt_fclose_snatch # define es_onclose gpgrt_onclose # define es_fileno gpgrt_fileno # define es_fileno_unlocked gpgrt_fileno_unlocked # define es_syshd gpgrt_syshd # define es_syshd_unlocked gpgrt_syshd_unlocked # define es_stdin _gpgrt_get_std_stream (0) # define es_stdout _gpgrt_get_std_stream (1) # define es_stderr _gpgrt_get_std_stream (2) # define es_flockfile gpgrt_flockfile # define es_ftrylockfile gpgrt_ftrylockfile # define es_funlockfile gpgrt_funlockfile # define es_feof gpgrt_feof # define es_feof_unlocked gpgrt_feof_unlocked # define es_ferror gpgrt_ferror # define es_ferror_unlocked gpgrt_ferror_unlocked # define es_clearerr gpgrt_clearerr # define es_clearerr_unlocked gpgrt_clearerr_unlocked # define es_pending gpgrt_pending # define es_pending_unlocked gpgrt_pending_unlocked # define es_fflush gpgrt_fflush # define es_fseek gpgrt_fseek # define es_fseeko gpgrt_fseeko # define es_ftell gpgrt_ftell # define es_ftello gpgrt_ftello # define es_rewind gpgrt_rewind # define es_fgetc gpgrt_fgetc # define es_fputc gpgrt_fputc # define es_getc_unlocked gpgrt_getc_unlocked # define es_putc_unlocked gpgrt_putc_unlocked # define es_getc gpgrt_getc # define es_putc gpgrt_putc # define es_ungetc gpgrt_ungetc # define es_read gpgrt_read # define es_write gpgrt_write # define es_write_sanitized gpgrt_write_sanitized # define es_write_hexstring gpgrt_write_hexstring # define es_fread gpgrt_fread # define es_fwrite gpgrt_fwrite # define es_fgets gpgrt_fgets # define es_fputs gpgrt_fputs # define es_fputs_unlocked gpgrt_fputs_unlocked # define es_getline gpgrt_getline # define es_read_line gpgrt_read_line # define es_free gpgrt_free # define es_fprintf gpgrt_fprintf # define es_fprintf_unlocked gpgrt_fprintf_unlocked # define es_printf gpgrt_printf # define es_printf_unlocked gpgrt_printf_unlocked # define es_vfprintf gpgrt_vfprintf # define es_vfprintf_unlocked gpgrt_vfprintf_unlocked # define es_setvbuf gpgrt_setvbuf # define es_setbuf gpgrt_setbuf # define es_set_binary gpgrt_set_binary # define es_set_nonblock gpgrt_set_nonblock # define es_get_nonblock gpgrt_get_nonblock # define es_poll gpgrt_poll # define es_tmpfile gpgrt_tmpfile # define es_opaque_set gpgrt_opaque_set # define es_opaque_get gpgrt_opaque_get # define es_fname_set gpgrt_fname_set # define es_fname_get gpgrt_fname_get # define es_asprintf gpgrt_asprintf # define es_vasprintf gpgrt_vasprintf # define es_bsprintf gpgrt_bsprintf # define es_vbsprintf gpgrt_vbsprintf #endif /*GPGRT_ENABLE_ES_MACROS*/ /* * Base64 encode and decode functions. */ struct _gpgrt_b64state; typedef struct _gpgrt_b64state *gpgrt_b64state_t; gpgrt_b64state_t gpgrt_b64enc_start (gpgrt_stream_t stream, const char *title); gpg_err_code_t gpgrt_b64enc_write (gpgrt_b64state_t state, const void *buffer, size_t nbytes); gpg_err_code_t gpgrt_b64enc_finish (gpgrt_b64state_t state); gpgrt_b64state_t gpgrt_b64dec_start (const char *title); gpg_error_t gpgrt_b64dec_proc (gpgrt_b64state_t state, void *buffer, size_t length, size_t *r_nbytes); gpg_error_t gpgrt_b64dec_finish (gpgrt_b64state_t state); /* * Logging functions */ /* Flag values for gpgrt_log_set_prefix. */ #define GPGRT_LOG_WITH_PREFIX 1 #define GPGRT_LOG_WITH_TIME 2 #define GPGRT_LOG_WITH_PID 4 #define GPGRT_LOG_RUN_DETACHED 256 #define GPGRT_LOG_NO_REGISTRY 512 /* Log levels as used by gpgrt_log. */ enum gpgrt_log_levels { GPGRT_LOGLVL_BEGIN, GPGRT_LOGLVL_CONT, GPGRT_LOGLVL_INFO, GPGRT_LOGLVL_WARN, GPGRT_LOGLVL_ERROR, GPGRT_LOGLVL_FATAL, GPGRT_LOGLVL_BUG, GPGRT_LOGLVL_DEBUG }; /* The next 4 functions are not thread-safe - call them early. */ void gpgrt_log_set_sink (const char *name, gpgrt_stream_t stream, int fd); void gpgrt_log_set_socket_dir_cb (const char *(*fnc)(void)); void gpgrt_log_set_pid_suffix_cb (int (*cb)(unsigned long *r_value)); void gpgrt_log_set_prefix (const char *text, unsigned int flags); int gpgrt_get_errorcount (int clear); void gpgrt_inc_errorcount (void); const char *gpgrt_log_get_prefix (unsigned int *flags); int gpgrt_log_test_fd (int fd); int gpgrt_log_get_fd (void); gpgrt_stream_t gpgrt_log_get_stream (void); void gpgrt_log (int level, const char *fmt, ...) GPGRT_ATTR_PRINTF(2,3); void gpgrt_logv (int level, const char *fmt, va_list arg_ptr); void gpgrt_logv_prefix (int level, const char *prefix, const char *fmt, va_list arg_ptr); void gpgrt_log_string (int level, const char *string); void gpgrt_log_bug (const char *fmt, ...) GPGRT_ATTR_NR_PRINTF(1,2); void gpgrt_log_fatal (const char *fmt, ...) GPGRT_ATTR_NR_PRINTF(1,2); void gpgrt_log_error (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); void gpgrt_log_info (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); void gpgrt_log_debug (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); void gpgrt_log_debug_string (const char *string, const char *fmt, ...) GPGRT_ATTR_PRINTF(2,3); void gpgrt_log_printf (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); void gpgrt_log_printhex (const void *buffer, size_t length, const char *fmt, ...) GPGRT_ATTR_PRINTF(3,4); void gpgrt_log_clock (const char *fmt, ...) GPGRT_ATTR_PRINTF(1,2); void gpgrt_log_flush (void); void _gpgrt_log_assert (const char *expr, const char *file, int line, const char *func) GPGRT_ATTR_NORETURN; #ifdef GPGRT_HAVE_MACRO_FUNCTION # define gpgrt_assert(expr) \ ((expr) \ ? (void) 0 \ : _gpgrt_log_assert (#expr, __FILE__, __LINE__, __FUNCTION__)) #else /*!GPGRT_HAVE_MACRO_FUNCTION*/ # define gpgrt_assert(expr) \ ((expr) \ ? (void) 0 \ : _gpgrt_log_assert (#expr, __FILE__, __LINE__, NULL)) #endif /*!GPGRT_HAVE_MACRO_FUNCTION*/ #ifdef GPGRT_ENABLE_LOG_MACROS # define log_get_errorcount gpgrt_get_errorcount # define log_inc_errorcount gpgrt_inc_errorcount # define log_set_file(a) gpgrt_log_set_sink ((a), NULL, -1) # define log_set_fd(a) gpgrt_log_set_sink (NULL, NULL, (a)) # define log_set_stream(a) gpgrt_log_set_sink (NULL, (a), -1) # define log_set_socket_dir_cb gpgrt_log_set_socket_dir_cb # define log_set_pid_suffix_cb gpgrt_log_set_pid_suffix_cb # define log_set_prefix gpgrt_log_set_prefix # define log_get_prefix gpgrt_log_get_prefix # define log_test_fd gpgrt_log_test_fd # define log_get_fd gpgrt_log_get_fd # define log_get_stream gpgrt_log_get_stream # define log_log gpgrt_log # define log_logv gpgrt_logv # define log_logv_prefix gpgrt_logv_prefix # define log_string gpgrt_log_string # define log_bug gpgrt_log_bug # define log_fatal gpgrt_log_fatal # define log_error gpgrt_log_error # define log_info gpgrt_log_info # define log_debug gpgrt_log_debug # define log_debug_string gpgrt_log_debug_string # define log_printf gpgrt_log_printf # define log_printhex gpgrt_log_printhex # define log_clock gpgrt_log_clock # define log_flush gpgrt_log_flush # ifdef GPGRT_HAVE_MACRO_FUNCTION # define log_assert(expr) \ ((expr) \ ? (void) 0 \ : _gpgrt_log_assert (#expr, __FILE__, __LINE__, __FUNCTION__)) # else /*!GPGRT_HAVE_MACRO_FUNCTION*/ # define log_assert(expr) \ ((expr) \ ? (void) 0 \ : _gpgrt_log_assert (#expr, __FILE__, __LINE__, NULL)) # endif /*!GPGRT_HAVE_MACRO_FUNCTION*/ #endif /*GPGRT_ENABLE_LOG_MACROS*/ /* * Spawn functions (Not yet available) */ #define GPGRT_SPAWN_NONBLOCK 16 /* Set the streams to non-blocking. */ #define GPGRT_SPAWN_RUN_ASFW 64 /* Use AllowSetForegroundWindow on W32. */ #define GPGRT_SPAWN_DETACHED 128 /* Start the process in the background. */ #if 0 /* Function and convenience macros to create pipes. */ gpg_err_code_t gpgrt_make_pipe (int filedes[2], gpgrt_stream_t *r_fp, int direction, int nonblock); #define gpgrt_create_pipe(a) gpgrt_make_pipe ((a),NULL, 0, 0); #define gpgrt_create_inbound_pipe(a,b,c) gpgrt_make_pipe ((a), (b), -1,(c)); #define gpgrt_create_outbound_pipe(a,b,c) gpgrt_make_pipe ((a), (b), 1,(c)); /* Fork and exec PGMNAME. */ gpg_err_code_t gpgrt_spawn_process (const char *pgmname, const char *argv[], int *execpt, void (*preexec)(void), unsigned int flags, gpgrt_stream_t *r_infp, gpgrt_stream_t *r_outfp, gpgrt_stream_t *r_errfp, pid_t *pid); /* Fork and exec PGNNAME and connect the process to the given FDs. */ gpg_err_code_t gpgrt_spawn_process_fd (const char *pgmname, const char *argv[], int infd, int outfd, int errfd, pid_t *pid); /* Fork and exec PGMNAME as a detached process. */ gpg_err_code_t gpgrt_spawn_process_detached (const char *pgmname, const char *argv[], const char *envp[] ); /* Wait for a single process. */ gpg_err_code_t gpgrt_wait_process (const char *pgmname, pid_t pid, int hang, int *r_exitcode); /* Wait for a multiple processes. */ gpg_err_code_t gpgrt_wait_processes (const char **pgmnames, pid_t *pids, size_t count, int hang, int *r_exitcodes); /* Kill the process identified by PID. */ void gpgrt_kill_process (pid_t pid); /* Release process resources identified by PID. */ void gpgrt_release_process (pid_t pid); #endif /*0*/ /* * Option parsing. */ struct _gpgrt_argparse_internal_s; typedef struct { int *argc; /* Pointer to ARGC (value subject to change). */ char ***argv; /* Pointer to ARGV (value subject to change). */ unsigned int flags; /* Global flags. May be set prior to calling the parser. The parser may change the value. */ int err; /* Print error description for last option. Either 0, ARGPARSE_PRINT_WARNING or ARGPARSE_PRINT_ERROR. */ unsigned int lineno;/* The current line number. */ int r_opt; /* Returns option code. */ int r_type; /* Returns type of option value. */ union { int ret_int; long ret_long; unsigned long ret_ulong; char *ret_str; } r; /* Return values */ struct _gpgrt_argparse_internal_s *internal; } gpgrt_argparse_t; typedef struct { int short_opt; const char *long_opt; unsigned int flags; const char *description; /* Optional description. */ } gpgrt_opt_t; #ifdef GPGRT_ENABLE_ARGPARSE_MACROS /* Global flags for (gpgrt_argparse_t).flags. */ #define ARGPARSE_FLAG_KEEP 1 /* Do not remove options form argv. */ #define ARGPARSE_FLAG_ALL 2 /* Do not stop at last option but return remaining args with R_OPT set to -1. */ #define ARGPARSE_FLAG_MIXED 4 /* Assume options and args are mixed. */ #define ARGPARSE_FLAG_NOSTOP 8 /* Do not stop processing at "--". */ #define ARGPARSE_FLAG_ARG0 16 /* Do not skip the first arg. */ #define ARGPARSE_FLAG_ONEDASH 32 /* Allow long options with one dash. */ #define ARGPARSE_FLAG_NOVERSION 64 /* No output for "--version". */ #define ARGPARSE_FLAG_RESET 128 /* Request to reset the internal state. */ #define ARGPARSE_FLAG_STOP_SEEN 256 /* Set to true if a "--" has been seen. */ #define ARGPARSE_FLAG_NOLINENO 512 /* Do not zero the lineno field. */ /* Constants for (gpgrt_argparse_t).err. */ #define ARGPARSE_PRINT_WARNING 1 /* Print a diagnostic. */ #define ARGPARSE_PRINT_ERROR 2 /* Print a diagnostic and call exit. */ /* Special return values of gpgrt_argparse. */ #define ARGPARSE_IS_ARG (-1) #define ARGPARSE_INVALID_OPTION (-2) #define ARGPARSE_MISSING_ARG (-3) #define ARGPARSE_KEYWORD_TOO_LONG (-4) #define ARGPARSE_READ_ERROR (-5) #define ARGPARSE_UNEXPECTED_ARG (-6) #define ARGPARSE_INVALID_COMMAND (-7) #define ARGPARSE_AMBIGUOUS_OPTION (-8) #define ARGPARSE_AMBIGUOUS_COMMAND (-9) #define ARGPARSE_INVALID_ALIAS (-10) #define ARGPARSE_OUT_OF_CORE (-11) #define ARGPARSE_INVALID_ARG (-12) /* Flags for the option descriptor (gpgrt_opt_t)->flags. Note that * a TYPE constant may be or-ed with the OPT constants. */ #define ARGPARSE_TYPE_NONE 0 /* Does not take an argument. */ #define ARGPARSE_TYPE_INT 1 /* Takes an int argument. */ #define ARGPARSE_TYPE_STRING 2 /* Takes a string argument. */ #define ARGPARSE_TYPE_LONG 3 /* Takes a long argument. */ #define ARGPARSE_TYPE_ULONG 4 /* Takes an unsigned long argument. */ #define ARGPARSE_OPT_OPTIONAL (1<<3) /* Argument is optional. */ #define ARGPARSE_OPT_PREFIX (1<<4) /* Allow 0x etc. prefixed values. */ #define ARGPARSE_OPT_IGNORE (1<<6) /* Ignore command or option. */ #define ARGPARSE_OPT_COMMAND (1<<7) /* The argument is a command. */ /* A set of macros to make option definitions easier to read. */ #define ARGPARSE_x(s,l,t,f,d) \ { (s), (l), ARGPARSE_TYPE_ ## t | (f), (d) } #define ARGPARSE_s(s,l,t,d) \ { (s), (l), ARGPARSE_TYPE_ ## t, (d) } #define ARGPARSE_s_n(s,l,d) \ { (s), (l), ARGPARSE_TYPE_NONE, (d) } #define ARGPARSE_s_i(s,l,d) \ { (s), (l), ARGPARSE_TYPE_INT, (d) } #define ARGPARSE_s_s(s,l,d) \ { (s), (l), ARGPARSE_TYPE_STRING, (d) } #define ARGPARSE_s_l(s,l,d) \ { (s), (l), ARGPARSE_TYPE_LONG, (d) } #define ARGPARSE_s_u(s,l,d) \ { (s), (l), ARGPARSE_TYPE_ULONG, (d) } #define ARGPARSE_o(s,l,t,d) \ { (s), (l), (ARGPARSE_TYPE_ ## t | ARGPARSE_OPT_OPTIONAL), (d) } #define ARGPARSE_o_n(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_NONE | ARGPARSE_OPT_OPTIONAL), (d) } #define ARGPARSE_o_i(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_INT | ARGPARSE_OPT_OPTIONAL), (d) } #define ARGPARSE_o_s(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_STRING | ARGPARSE_OPT_OPTIONAL), (d) } #define ARGPARSE_o_l(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_LONG | ARGPARSE_OPT_OPTIONAL), (d) } #define ARGPARSE_o_u(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_ULONG | ARGPARSE_OPT_OPTIONAL), (d) } #define ARGPARSE_p(s,l,t,d) \ { (s), (l), (ARGPARSE_TYPE_ ## t | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_p_n(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_NONE | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_p_i(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_INT | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_p_s(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_STRING | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_p_l(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_LONG | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_p_u(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_ULONG | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_op(s,l,t,d) \ { (s), (l), (ARGPARSE_TYPE_ ## t \ | ARGPARSE_OPT_OPTIONAL | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_op_n(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_NONE \ | ARGPARSE_OPT_OPTIONAL | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_op_i(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_INT \ | ARGPARSE_OPT_OPTIONAL | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_op_s(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_STRING \ | ARGPARSE_OPT_OPTIONAL | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_op_l(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_LONG \ | ARGPARSE_OPT_OPTIONAL | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_op_u(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_ULONG \ | ARGPARSE_OPT_OPTIONAL | ARGPARSE_OPT_PREFIX), (d) } #define ARGPARSE_c(s,l,d) \ { (s), (l), (ARGPARSE_TYPE_NONE | ARGPARSE_OPT_COMMAND), (d) } #define ARGPARSE_ignore(s,l) \ { (s), (l), (ARGPARSE_OPT_IGNORE), "@" } #define ARGPARSE_group(s,d) \ { (s), NULL, 0, (d) } /* Mark the end of the list (mandatory). */ #define ARGPARSE_end() \ { 0, NULL, 0, NULL } #endif /* GPGRT_ENABLE_ARGPARSE_MACROS */ /* Take care: gpgrt_argparse keeps state in ARG and requires that * either ARGPARSE_FLAG_RESET is used after OPTS has been changed or * gpgrt_argparse (NULL, ARG, NULL) is called first. */ int gpgrt_argparse (gpgrt_stream_t fp, gpgrt_argparse_t *arg, gpgrt_opt_t *opts); void gpgrt_usage (int level); const char *gpgrt_strusage (int level); void gpgrt_set_strusage (const char *(*f)(int)); void gpgrt_set_usage_outfnc (int (*f)(int, const char *)); void gpgrt_set_fixed_string_mapper (const char *(*f)(const char*)); #ifdef __cplusplus } #endif #endif /* GPGRT_H */ #endif /* GPG_ERROR_H */