Imported Upstream version 2.1.1
[platform/upstream/gpg2.git] / tools / gpgconf-comp.c
1 /* gpgconf-comp.c - Configuration utility for GnuPG.
2  * Copyright (C) 2004, 2007, 2008, 2009, 2010,
3  *               2011 Free Software Foundation, Inc.
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with GnuPG; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #if HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <sys/types.h>
30 #include <assert.h>
31 #include <errno.h>
32 #include <time.h>
33 #include <stdarg.h>
34 #ifdef HAVE_SIGNAL_H
35 # include <signal.h>
36 #endif
37 #include <ctype.h>
38 #ifdef HAVE_W32_SYSTEM
39 # define WIN32_LEAN_AND_MEAN 1
40 # include <windows.h>
41 #else
42 # include <pwd.h>
43 # include <grp.h>
44 #endif
45
46 /* For log_logv(), asctimestamp(), gnupg_get_time ().  */
47 #define JNLIB_NEED_LOG_LOGV
48 #include "util.h"
49 #include "i18n.h"
50 #include "exechelp.h"
51
52 #include "gc-opt-flags.h"
53 #include "gpgconf.h"
54
55 /* There is a problem with gpg 1.4 under Windows: --gpgconf-list
56    returns a plain filename without escaping.  As long as we have not
57    fixed that we need to use gpg2.  */
58 #if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
59 #define GPGNAME "gpg2"
60 #else
61 #define GPGNAME GPG_NAME
62 #endif
63
64 \f
65 /* TODO:
66    Components: Add more components and their options.
67    Robustness: Do more validation.  Call programs to do validation for us.
68    Add options to change backend binary path.
69    Extract binary path for some backends from gpgsm/gpg config.
70 */
71
72 \f
73 #if (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ))
74 void gc_error (int status, int errnum, const char *fmt, ...) \
75   __attribute__ ((format (printf, 3, 4)));
76 #endif
77
78 /* Output a diagnostic message.  If ERRNUM is not 0, then the output
79    is followed by a colon, a white space, and the error string for the
80    error number ERRNUM.  In any case the output is finished by a
81    newline.  The message is prepended by the program name, a colon,
82    and a whitespace.  The output may be further formatted or
83    redirected by the jnlib logging facility.  */
84 void
85 gc_error (int status, int errnum, const char *fmt, ...)
86 {
87   va_list arg_ptr;
88
89   va_start (arg_ptr, fmt);
90   log_logv (JNLIB_LOG_ERROR, fmt, arg_ptr);
91   va_end (arg_ptr);
92
93   if (errnum)
94     log_printf (": %s\n", strerror (errnum));
95   else
96     log_printf ("\n");
97
98   if (status)
99     {
100       log_printf (NULL);
101       log_printf ("fatal error (exit status %i)\n", status);
102       exit (status);
103     }
104 }
105
106 \f
107 /* Forward declaration.  */
108 static void gpg_agent_runtime_change (int killflag);
109 static void scdaemon_runtime_change (int killflag);
110 static void dirmngr_runtime_change (int killflag);
111
112 /* Backend configuration.  Backends are used to decide how the default
113    and current value of an option can be determined, and how the
114    option can be changed.  To every option in every component belongs
115    exactly one backend that controls and determines the option.  Some
116    backends are programs from the GPG system.  Others might be
117    implemented by GPGConf itself.  If you change this enum, don't
118    forget to update GC_BACKEND below.  */
119 typedef enum
120   {
121     /* Any backend, used for find_option ().  */
122     GC_BACKEND_ANY,
123
124     /* The Gnu Privacy Guard.  */
125     GC_BACKEND_GPG,
126
127     /* The Gnu Privacy Guard for S/MIME.  */
128     GC_BACKEND_GPGSM,
129
130     /* The GPG Agent.  */
131     GC_BACKEND_GPG_AGENT,
132
133     /* The GnuPG SCDaemon.  */
134     GC_BACKEND_SCDAEMON,
135
136     /* The GnuPG directory manager.  */
137     GC_BACKEND_DIRMNGR,
138
139     /* The LDAP server list file for the director manager.  */
140     GC_BACKEND_DIRMNGR_LDAP_SERVER_LIST,
141
142     /* The Pinentry (not a part of GnuPG, proper).  */
143     GC_BACKEND_PINENTRY,
144
145     /* The number of the above entries.  */
146     GC_BACKEND_NR
147   } gc_backend_t;
148
149
150 /* To be able to implement generic algorithms for the various
151    backends, we collect all information about them in this struct.  */
152 static struct
153 {
154   /* The name of the backend.  */
155   const char *name;
156
157   /* The name of the program that acts as the backend.  Some backends
158      don't have an associated program, but are implemented directly by
159      GPGConf.  In this case, PROGRAM is NULL.  */
160   char *program;
161
162   /* The module name (GNUPG_MODULE_NAME_foo) as defined by
163      ../common/util.h.  This value is used to get the actual installed
164      path of the program.  0 is used if no backend program is
165      available. */
166   char module_name;
167
168   /* The runtime change callback.  If KILLFLAG is true the component
169      is killed and not just reloaded.  */
170   void (*runtime_change) (int killflag);
171
172   /* The option name for the configuration filename of this backend.
173      This must be an absolute filename.  It can be an option from a
174      different backend (but then ordering of the options might
175      matter).  Note: This must be unique among all components.  */
176   const char *option_config_filename;
177
178   /* If this is a file backend rather than a program backend, then
179      this is the name of the option associated with the file.  */
180   const char *option_name;
181 } gc_backend[GC_BACKEND_NR] =
182   {
183     { NULL },           /* GC_BACKEND_ANY dummy entry.  */
184     { GPG_DISP_NAME, GPGNAME, GNUPG_MODULE_NAME_GPG,
185       NULL, GPGCONF_NAME "-" GPG_NAME ".conf" },
186     { GPGSM_DISP_NAME, GPGSM_NAME, GNUPG_MODULE_NAME_GPGSM,
187       NULL, GPGCONF_NAME "-" GPGSM_NAME ".conf" },
188     { GPG_AGENT_DISP_NAME, GPG_AGENT_NAME, GNUPG_MODULE_NAME_AGENT,
189       gpg_agent_runtime_change, GPGCONF_NAME"-" GPG_AGENT_NAME ".conf" },
190     { SCDAEMON_DISP_NAME, SCDAEMON_NAME, GNUPG_MODULE_NAME_SCDAEMON,
191       scdaemon_runtime_change, GPGCONF_NAME"-" SCDAEMON_NAME ".conf" },
192     { DIRMNGR_DISP_NAME, DIRMNGR_NAME, GNUPG_MODULE_NAME_DIRMNGR,
193       dirmngr_runtime_change, GPGCONF_NAME "-" DIRMNGR_NAME ".conf" },
194     { DIRMNGR_DISP_NAME " LDAP Server List", NULL, 0,
195       NULL, "ldapserverlist-file", "LDAP Server" },
196     { "Pinentry", "pinentry", GNUPG_MODULE_NAME_PINENTRY,
197       NULL, GPGCONF_NAME "-pinentry.conf" },
198   };
199
200 \f
201 /* Option configuration.  */
202
203 /* An option might take an argument, or not.  Argument types can be
204    basic or complex.  Basic types are generic and easy to validate.
205    Complex types provide more specific information about the intended
206    use, but can be difficult to validate.  If you add to this enum,
207    don't forget to update GC_ARG_TYPE below.  YOU MUST NOT CHANGE THE
208    NUMBERS OF THE EXISTING ENTRIES, AS THEY ARE PART OF THE EXTERNAL
209    INTERFACE.  */
210 typedef enum
211   {
212     /* Basic argument types.  */
213
214     /* No argument.  */
215     GC_ARG_TYPE_NONE = 0,
216
217     /* A String argument.  */
218     GC_ARG_TYPE_STRING = 1,
219
220     /* A signed integer argument.  */
221     GC_ARG_TYPE_INT32 = 2,
222
223     /* An unsigned integer argument.  */
224     GC_ARG_TYPE_UINT32 = 3,
225
226     /* ADD NEW BASIC TYPE ENTRIES HERE.  */
227
228     /* Complex argument types.  */
229
230     /* A complete filename.  */
231     GC_ARG_TYPE_FILENAME = 32,
232
233     /* An LDAP server in the format
234        HOSTNAME:PORT:USERNAME:PASSWORD:BASE_DN.  */
235     GC_ARG_TYPE_LDAP_SERVER = 33,
236
237     /* A 40 character fingerprint.  */
238     GC_ARG_TYPE_KEY_FPR = 34,
239
240     /* A user ID or key ID or fingerprint for a certificate.  */
241     GC_ARG_TYPE_PUB_KEY = 35,
242
243     /* A user ID or key ID or fingerprint for a certificate with a key.  */
244     GC_ARG_TYPE_SEC_KEY = 36,
245
246     /* A alias list made up of a key, an equal sign and a space
247        separated list of values.  */
248     GC_ARG_TYPE_ALIAS_LIST = 37,
249
250     /* ADD NEW COMPLEX TYPE ENTRIES HERE.  */
251
252     /* The number of the above entries.  */
253     GC_ARG_TYPE_NR
254   } gc_arg_type_t;
255
256
257 /* For every argument, we record some information about it in the
258    following struct.  */
259 static struct
260 {
261   /* For every argument type exists a basic argument type that can be
262      used as a fallback for input and validation purposes.  */
263   gc_arg_type_t fallback;
264
265   /* Human-readable name of the type.  */
266   const char *name;
267 } gc_arg_type[GC_ARG_TYPE_NR] =
268   {
269     /* The basic argument types have their own types as fallback.  */
270     { GC_ARG_TYPE_NONE, "none" },
271     { GC_ARG_TYPE_STRING, "string" },
272     { GC_ARG_TYPE_INT32, "int32" },
273     { GC_ARG_TYPE_UINT32, "uint32" },
274
275     /* Reserved basic type entries for future extension.  */
276     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
277     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
278     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
279     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
280     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
281     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
282     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
283     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
284     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
285     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
286     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
287     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
288     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
289     { GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
290
291     /* The complex argument types have a basic type as fallback.  */
292     { GC_ARG_TYPE_STRING, "filename" },
293     { GC_ARG_TYPE_STRING, "ldap server" },
294     { GC_ARG_TYPE_STRING, "key fpr" },
295     { GC_ARG_TYPE_STRING, "pub key" },
296     { GC_ARG_TYPE_STRING, "sec key" },
297     { GC_ARG_TYPE_STRING, "alias list" },
298   };
299
300
301 /* Every option has an associated expert level, than can be used to
302    hide advanced and expert options from beginners.  If you add to
303    this list, don't forget to update GC_LEVEL below.  YOU MUST NOT
304    CHANGE THE NUMBERS OF THE EXISTING ENTRIES, AS THEY ARE PART OF THE
305    EXTERNAL INTERFACE.  */
306 typedef enum
307   {
308     /* The basic options should always be displayed.  */
309     GC_LEVEL_BASIC,
310
311     /* The advanced options may be hidden from beginners.  */
312     GC_LEVEL_ADVANCED,
313
314     /* The expert options should only be displayed to experts.  */
315     GC_LEVEL_EXPERT,
316
317     /* The invisible options should normally never be displayed.  */
318     GC_LEVEL_INVISIBLE,
319
320     /* The internal options are never exported, they mark options that
321        are recorded for internal use only.  */
322     GC_LEVEL_INTERNAL,
323
324     /* ADD NEW ENTRIES HERE.  */
325
326     /* The number of the above entries.  */
327     GC_LEVEL_NR
328   } gc_expert_level_t;
329
330 /* A description for each expert level.  */
331 static struct
332 {
333   const char *name;
334 } gc_level[] =
335   {
336     { "basic" },
337     { "advanced" },
338     { "expert" },
339     { "invisible" },
340     { "internal" }
341   };
342
343
344 /* Option flags.  The flags which are used by the backends are defined
345    by gc-opt-flags.h, included above.
346
347    YOU MUST NOT CHANGE THE NUMBERS OF THE EXISTING FLAGS, AS THEY ARE
348    PART OF THE EXTERNAL INTERFACE.  */
349
350 /* Some entries in the option list are not options, but mark the
351    beginning of a new group of options.  These entries have the GROUP
352    flag set.  */
353 #define GC_OPT_FLAG_GROUP       (1UL << 0)
354 /* The ARG_OPT flag for an option indicates that the argument is
355    optional.  This is never set for GC_ARG_TYPE_NONE options.  */
356 #define GC_OPT_FLAG_ARG_OPT     (1UL << 1)
357 /* The LIST flag for an option indicates that the option can occur
358    several times.  A comma separated list of arguments is used as the
359    argument value.  */
360 #define GC_OPT_FLAG_LIST        (1UL << 2)
361
362
363 /* A human-readable description for each flag.  */
364 static struct
365 {
366   const char *name;
367 } gc_flag[] =
368   {
369     { "group" },
370     { "optional arg" },
371     { "list" },
372     { "runtime" },
373     { "default" },
374     { "default desc" },
375     { "no arg desc" },
376     { "no change" }
377   };
378
379
380 /* To each option, or group marker, the information in the GC_OPTION
381    struct is provided.  If you change this, don't forget to update the
382    option list of each component.  */
383 struct gc_option
384 {
385   /* If this is NULL, then this is a terminator in an array of unknown
386      length.  Otherwise, if this entry is a group marker (see FLAGS),
387      then this is the name of the group described by this entry.
388      Otherwise it is the name of the option described by this
389      entry.  The name must not contain a colon.  */
390   const char *name;
391
392   /* The option flags.  If the GROUP flag is set, then this entry is a
393      group marker, not an option, and only the fields LEVEL,
394      DESC_DOMAIN and DESC are valid.  In all other cases, this entry
395      describes a new option and all fields are valid.  */
396   unsigned long flags;
397
398   /* The expert level.  This field is valid for options and groups.  A
399      group has the expert level of the lowest-level option in the
400      group.  */
401   gc_expert_level_t level;
402
403   /* A gettext domain in which the following description can be found.
404      If this is NULL, then DESC is not translated.  Valid for groups
405      and options.
406
407      Note that we try to keep the description of groups within the
408      gnupg domain.
409
410      IMPORTANT: If you add a new domain please make sure to add a code
411      set switching call to the function my_dgettext further below.  */
412   const char *desc_domain;
413
414   /* A gettext description for this group or option.  If it starts
415      with a '|', then the string up to the next '|' describes the
416      argument, and the description follows the second '|'.
417
418      In general enclosing these description in N_() is not required
419      because the description should be identical to the one in the
420      help menu of the respective program. */
421   const char *desc;
422
423   /* The following fields are only valid for options.  */
424
425   /* The type of the option argument.  */
426   gc_arg_type_t arg_type;
427
428   /* The backend that implements this option.  */
429   gc_backend_t backend;
430
431   /* The following fields are set to NULL at startup (because all
432      option's are declared as static variables).  They are at the end
433      of the list so that they can be omitted from the option
434      declarations.  */
435
436   /* This is true if the option is supported by this version of the
437      backend.  */
438   int active;
439
440   /* The default value for this option.  This is NULL if the option is
441      not present in the backend, the empty string if no default is
442      available, and otherwise a quoted string.  */
443   char *default_value;
444
445   /* The default argument is only valid if the "optional arg" flag is
446      set, and specifies the default argument (value) that is used if
447      the argument is omitted.  */
448   char *default_arg;
449
450   /* The current value of this option.  */
451   char *value;
452
453   /* The new flags for this option.  The only defined flag is actually
454      GC_OPT_FLAG_DEFAULT, and it means that the option should be
455      deleted.  In this case, NEW_VALUE is NULL.  */
456   unsigned long new_flags;
457
458   /* The new value of this option.  */
459   char *new_value;
460 };
461 typedef struct gc_option gc_option_t;
462
463 /* Use this macro to terminate an option list.  */
464 #define GC_OPTION_NULL { NULL }
465
466 \f
467 #ifndef BUILD_WITH_AGENT
468 #define gc_options_gpg_agent NULL
469 #else
470 /* The options of the GC_COMPONENT_GPG_AGENT component.  */
471 static gc_option_t gc_options_gpg_agent[] =
472  {
473    /* The configuration file to which we write the changes.  */
474    { GPGCONF_NAME"-" GPG_AGENT_NAME ".conf",
475      GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
476      NULL, NULL, GC_ARG_TYPE_FILENAME, GC_BACKEND_GPG_AGENT },
477
478    { "Monitor",
479      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
480      "gnupg", N_("Options controlling the diagnostic output") },
481    { "verbose", GC_OPT_FLAG_LIST|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
482      "gnupg", "verbose",
483      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
484    { "quiet", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
485      "gnupg", "be somewhat more quiet",
486      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
487    { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
488      NULL, NULL,
489      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
490
491    { "Configuration",
492      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
493      "gnupg", N_("Options controlling the configuration") },
494    { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
495      "gnupg", "|FILE|read options from FILE",
496      GC_ARG_TYPE_FILENAME, GC_BACKEND_GPG_AGENT },
497    { "disable-scdaemon", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
498      "gnupg", "do not use the SCdaemon",
499      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
500    { "enable-ssh-support", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
501      "gnupg", "enable ssh support",
502      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
503    { "enable-putty-support", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
504      "gnupg", "enable putty support",
505      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
506
507    { "Debug",
508      GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
509      "gnupg", N_("Options useful for debugging") },
510    { "debug-level", GC_OPT_FLAG_ARG_OPT|GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
511      "gnupg", "|LEVEL|set the debugging level to LEVEL",
512      GC_ARG_TYPE_STRING, GC_BACKEND_GPG_AGENT },
513    { "log-file", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
514      "gnupg", N_("|FILE|write server mode logs to FILE"),
515      GC_ARG_TYPE_FILENAME, GC_BACKEND_GPG_AGENT },
516    { "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
517      NULL, NULL,
518      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
519
520    { "Security",
521      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
522      "gnupg", N_("Options controlling the security") },
523    { "default-cache-ttl", GC_OPT_FLAG_RUNTIME,
524      GC_LEVEL_BASIC, "gnupg",
525      "|N|expire cached PINs after N seconds",
526      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
527    { "default-cache-ttl-ssh", GC_OPT_FLAG_RUNTIME,
528      GC_LEVEL_ADVANCED, "gnupg",
529      N_("|N|expire SSH keys after N seconds"),
530      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
531    { "max-cache-ttl", GC_OPT_FLAG_RUNTIME,
532      GC_LEVEL_EXPERT, "gnupg",
533      N_("|N|set maximum PIN cache lifetime to N seconds"),
534      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
535    { "max-cache-ttl-ssh", GC_OPT_FLAG_RUNTIME,
536      GC_LEVEL_EXPERT, "gnupg",
537      N_("|N|set maximum SSH key lifetime to N seconds"),
538      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
539    { "ignore-cache-for-signing", GC_OPT_FLAG_RUNTIME,
540      GC_LEVEL_BASIC, "gnupg", "do not use the PIN cache when signing",
541      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
542    { "no-allow-mark-trusted", GC_OPT_FLAG_RUNTIME,
543      GC_LEVEL_ADVANCED, "gnupg", "disallow clients to mark keys as \"trusted\"",
544      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
545    { "no-grab", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT,
546      "gnupg", "do not grab keyboard and mouse",
547      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
548
549    { "Passphrase policy",
550      GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
551      "gnupg", N_("Options enforcing a passphrase policy") },
552    { "enforce-passphrase-constraints", GC_OPT_FLAG_RUNTIME,
553      GC_LEVEL_EXPERT, "gnupg",
554      N_("do not allow to bypass the passphrase policy"),
555      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
556    { "min-passphrase-len", GC_OPT_FLAG_RUNTIME,
557      GC_LEVEL_ADVANCED, "gnupg",
558      N_("|N|set minimal required length for new passphrases to N"),
559      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
560    { "min-passphrase-nonalpha", GC_OPT_FLAG_RUNTIME,
561      GC_LEVEL_EXPERT, "gnupg",
562      N_("|N|require at least N non-alpha characters for a new passphrase"),
563      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
564    { "check-passphrase-pattern", GC_OPT_FLAG_RUNTIME,
565      GC_LEVEL_EXPERT,
566      "gnupg", N_("|FILE|check new passphrases against pattern in FILE"),
567      GC_ARG_TYPE_FILENAME, GC_BACKEND_GPG_AGENT },
568    { "max-passphrase-days", GC_OPT_FLAG_RUNTIME,
569      GC_LEVEL_EXPERT, "gnupg",
570      N_("|N|expire the passphrase after N days"),
571      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG_AGENT },
572    { "enable-passphrase-history", GC_OPT_FLAG_RUNTIME,
573      GC_LEVEL_EXPERT, "gnupg",
574      N_("do not allow the reuse of old passphrases"),
575      GC_ARG_TYPE_NONE, GC_BACKEND_GPG_AGENT },
576
577    GC_OPTION_NULL
578  };
579 #endif /*BUILD_WITH_AGENT*/
580
581
582 #ifndef BUILD_WITH_SCDAEMON
583 #define gc_options_scdaemon NULL
584 #else
585 /* The options of the GC_COMPONENT_SCDAEMON component.  */
586 static gc_option_t gc_options_scdaemon[] =
587  {
588    /* The configuration file to which we write the changes.  */
589    { GPGCONF_NAME"-"SCDAEMON_NAME".conf",
590      GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
591      NULL, NULL, GC_ARG_TYPE_FILENAME, GC_BACKEND_SCDAEMON },
592
593    { "Monitor",
594      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
595      "gnupg", N_("Options controlling the diagnostic output") },
596    { "verbose", GC_OPT_FLAG_LIST|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
597      "gnupg", "verbose",
598      GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
599    { "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
600      "gnupg", "be somewhat more quiet",
601      GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
602    { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
603      NULL, NULL,
604      GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
605
606    { "Configuration",
607      GC_OPT_FLAG_GROUP, GC_LEVEL_EXPERT,
608      "gnupg", N_("Options controlling the configuration") },
609    { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
610      "gnupg", "|FILE|read options from FILE",
611      GC_ARG_TYPE_FILENAME, GC_BACKEND_SCDAEMON },
612    { "reader-port", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
613      "gnupg", "|N|connect to reader at port N",
614      GC_ARG_TYPE_STRING, GC_BACKEND_SCDAEMON },
615    { "ctapi-driver", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
616      "gnupg", "|NAME|use NAME as ct-API driver",
617      GC_ARG_TYPE_STRING, GC_BACKEND_SCDAEMON },
618    { "pcsc-driver", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
619      "gnupg", "|NAME|use NAME as PC/SC driver",
620      GC_ARG_TYPE_STRING, GC_BACKEND_SCDAEMON },
621    { "disable-ccid", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT,
622      "gnupg", "do not use the internal CCID driver",
623      GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
624    { "disable-pinpad", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
625      "gnupg", "do not use a reader's pinpad",
626      GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
627    { "enable-pinpad-varlen",
628      GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
629      "gnupg", "use variable length input for pinpad",
630      GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
631    { "card-timeout", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
632      "gnupg", "|N|disconnect the card after N seconds of inactivity",
633      GC_ARG_TYPE_UINT32, GC_BACKEND_SCDAEMON },
634
635    { "Debug",
636      GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
637      "gnupg", N_("Options useful for debugging") },
638    { "debug-level", GC_OPT_FLAG_ARG_OPT|GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
639      "gnupg", "|LEVEL|set the debugging level to LEVEL",
640      GC_ARG_TYPE_STRING, GC_BACKEND_SCDAEMON },
641    { "log-file", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
642      "gnupg", N_("|FILE|write a log to FILE"),
643      GC_ARG_TYPE_FILENAME, GC_BACKEND_SCDAEMON },
644
645    { "Security",
646      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
647      "gnupg", N_("Options controlling the security") },
648    { "deny-admin", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC,
649      "gnupg", "deny the use of admin card commands",
650      GC_ARG_TYPE_NONE, GC_BACKEND_SCDAEMON },
651
652
653    GC_OPTION_NULL
654  };
655 #endif /*BUILD_WITH_SCDAEMON*/
656
657 #ifndef BUILD_WITH_GPG
658 #define gc_options_gpg NULL
659 #else
660 /* The options of the GC_COMPONENT_GPG component.  */
661 static gc_option_t gc_options_gpg[] =
662  {
663    /* The configuration file to which we write the changes.  */
664    { GPGCONF_NAME"-"GPG_NAME".conf",
665      GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
666      NULL, NULL, GC_ARG_TYPE_FILENAME, GC_BACKEND_GPG },
667
668    { "Monitor",
669      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
670      "gnupg", N_("Options controlling the diagnostic output") },
671    { "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
672      "gnupg", "verbose",
673      GC_ARG_TYPE_NONE, GC_BACKEND_GPG },
674    { "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
675      "gnupg", "be somewhat more quiet",
676      GC_ARG_TYPE_NONE, GC_BACKEND_GPG },
677    { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
678      NULL, NULL,
679      GC_ARG_TYPE_NONE, GC_BACKEND_GPG },
680
681    { "Configuration",
682      GC_OPT_FLAG_GROUP, GC_LEVEL_EXPERT,
683      "gnupg", N_("Options controlling the configuration") },
684    { "default-key", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
685      "gnupg", N_("|NAME|use NAME as default secret key"),
686      GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
687    { "encrypt-to", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
688      "gnupg", N_("|NAME|encrypt to user ID NAME as well"),
689      GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
690    { "group", GC_OPT_FLAG_LIST, GC_LEVEL_ADVANCED,
691      "gnupg", N_("|SPEC|set up email aliases"),
692      GC_ARG_TYPE_ALIAS_LIST, GC_BACKEND_GPG },
693    { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
694      "gnupg", "|FILE|read options from FILE",
695      GC_ARG_TYPE_FILENAME, GC_BACKEND_GPG },
696    { "default_pubkey_algo",
697      (GC_OPT_FLAG_ARG_OPT|GC_OPT_FLAG_NO_CHANGE), GC_LEVEL_INVISIBLE,
698      NULL, NULL,
699      GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
700
701
702    { "Debug",
703      GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
704      "gnupg", N_("Options useful for debugging") },
705    { "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED,
706      "gnupg", "|LEVEL|set the debugging level to LEVEL",
707      GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
708    { "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
709      "gnupg", N_("|FILE|write server mode logs to FILE"),
710      GC_ARG_TYPE_FILENAME, GC_BACKEND_GPG },
711 /*    { "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE, */
712 /*      NULL, NULL, */
713 /*      GC_ARG_TYPE_UINT32, GC_BACKEND_GPG }, */
714
715    { "Keyserver",
716      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
717      "gnupg", N_("Configuration for Keyservers") },
718    { "keyserver", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
719      "gnupg", N_("|URL|use keyserver at URL"),
720      GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
721    { "allow-pka-lookup", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
722      "gnupg", N_("allow PKA lookups (DNS requests)"),
723      GC_ARG_TYPE_NONE, GC_BACKEND_GPG },
724    { "auto-key-locate", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
725      "gnupg", N_("|MECHANISMS|use MECHANISMS to locate keys by mail address"),
726      GC_ARG_TYPE_STRING, GC_BACKEND_GPG },
727
728
729
730
731    GC_OPTION_NULL
732  };
733 #endif /*BUILD_WITH_GPG*/
734
735
736 #ifndef BUILD_WITH_GPGSM
737 #define gc_options_gpgsm NULL
738 #else
739 /* The options of the GC_COMPONENT_GPGSM component.  */
740 static gc_option_t gc_options_gpgsm[] =
741  {
742    /* The configuration file to which we write the changes.  */
743    { GPGCONF_NAME"-"GPGSM_NAME".conf",
744      GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
745      NULL, NULL, GC_ARG_TYPE_FILENAME, GC_BACKEND_GPGSM },
746
747    { "Monitor",
748      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
749      "gnupg", N_("Options controlling the diagnostic output") },
750    { "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
751      "gnupg", "verbose",
752      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
753    { "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
754      "gnupg", "be somewhat more quiet",
755      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
756    { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
757      NULL, NULL,
758      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
759
760    { "Configuration",
761      GC_OPT_FLAG_GROUP, GC_LEVEL_EXPERT,
762      "gnupg", N_("Options controlling the configuration") },
763    { "default-key", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
764      "gnupg", N_("|NAME|use NAME as default secret key"),
765      GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },
766    { "encrypt-to", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
767      "gnupg", N_("|NAME|encrypt to user ID NAME as well"),
768      GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },
769    { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
770      "gnupg", "|FILE|read options from FILE",
771      GC_ARG_TYPE_FILENAME, GC_BACKEND_GPGSM },
772    { "prefer-system-dirmngr", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
773      "gnupg", "use system's dirmngr if available",
774      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
775    { "disable-dirmngr", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
776      "gnupg", N_("disable all access to the dirmngr"),
777      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
778    { "p12-charset", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
779      "gnupg", N_("|NAME|use encoding NAME for PKCS#12 passphrases"),
780      GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },
781    { "keyserver", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
782      "gnupg", N_("|SPEC|use this keyserver to lookup keys"),
783      GC_ARG_TYPE_LDAP_SERVER, GC_BACKEND_GPGSM },
784    { "default_pubkey_algo",
785      (GC_OPT_FLAG_ARG_OPT|GC_OPT_FLAG_NO_CHANGE), GC_LEVEL_INVISIBLE,
786      NULL, NULL,
787      GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },
788
789    { "Debug",
790      GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
791      "gnupg", N_("Options useful for debugging") },
792    { "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED,
793      "gnupg", "|LEVEL|set the debugging level to LEVEL",
794      GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },
795    { "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
796      "gnupg", N_("|FILE|write server mode logs to FILE"),
797      GC_ARG_TYPE_FILENAME, GC_BACKEND_GPGSM },
798    { "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
799      NULL, NULL,
800      GC_ARG_TYPE_UINT32, GC_BACKEND_GPGSM },
801
802    { "Security",
803      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
804      "gnupg", N_("Options controlling the security") },
805    { "disable-crl-checks", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
806      "gnupg", "never consult a CRL",
807      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
808    { "disable-trusted-cert-crl-check", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
809      "gnupg", N_("do not check CRLs for root certificates"),
810      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
811    { "enable-ocsp", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
812      "gnupg", "check validity using OCSP",
813      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
814    { "include-certs", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
815      "gnupg", "|N|number of certificates to include",
816      GC_ARG_TYPE_INT32, GC_BACKEND_GPGSM },
817    { "disable-policy-checks", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
818      "gnupg", "do not check certificate policies",
819      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
820    { "auto-issuer-key-retrieve", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
821      "gnupg", "fetch missing issuer certificates",
822      GC_ARG_TYPE_NONE, GC_BACKEND_GPGSM },
823    { "cipher-algo", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
824      "gnupg", "|NAME|use cipher algorithm NAME",
825      GC_ARG_TYPE_STRING, GC_BACKEND_GPGSM },
826
827    GC_OPTION_NULL
828  };
829 #endif /*BUILD_WITH_GPGSM*/
830
831
832 #ifndef BUILD_WITH_DIRMNGR
833 #define gc_options_dirmngr NULL
834 #else
835 /* The options of the GC_COMPONENT_DIRMNGR component.  */
836 static gc_option_t gc_options_dirmngr[] =
837  {
838    /* The configuration file to which we write the changes.  */
839    { GPGCONF_NAME"-"DIRMNGR_NAME".conf",
840      GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
841      NULL, NULL, GC_ARG_TYPE_FILENAME, GC_BACKEND_DIRMNGR },
842
843    { "Monitor",
844      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
845      "gnupg", N_("Options controlling the diagnostic output") },
846    { "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
847      "dirmngr", "verbose",
848      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
849    { "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
850      "dirmngr", "be somewhat more quiet",
851      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
852    { "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
853      NULL, NULL,
854      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
855
856    { "Format",
857      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
858      "gnupg", N_("Options controlling the format of the output") },
859    { "sh", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
860      "dirmngr", "sh-style command output",
861      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
862    { "csh", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
863      "dirmngr", "csh-style command output",
864      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
865
866    { "Configuration",
867      GC_OPT_FLAG_GROUP, GC_LEVEL_EXPERT,
868      "gnupg", N_("Options controlling the configuration") },
869    { "options", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT,
870      "dirmngr", "|FILE|read options from FILE",
871      GC_ARG_TYPE_FILENAME, GC_BACKEND_DIRMNGR },
872
873    { "Debug",
874      GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
875      "gnupg", N_("Options useful for debugging") },
876    { "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED,
877      "dirmngr", "|LEVEL|set the debugging level to LEVEL",
878      GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },
879    { "no-detach", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
880      "dirmngr", "do not detach from the console",
881      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
882    { "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
883      "dirmngr", N_("|FILE|write server mode logs to FILE"),
884      GC_ARG_TYPE_FILENAME, GC_BACKEND_DIRMNGR },
885    { "debug-wait", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
886      NULL, NULL,
887      GC_ARG_TYPE_UINT32, GC_BACKEND_DIRMNGR },
888    { "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE,
889      NULL, NULL,
890      GC_ARG_TYPE_UINT32, GC_BACKEND_DIRMNGR },
891
892    { "Enforcement",
893      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
894      "gnupg", N_("Options controlling the interactivity and enforcement") },
895    { "batch", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
896      "dirmngr", "run without asking a user",
897      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
898    { "force", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
899      "dirmngr", "force loading of outdated CRLs",
900      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
901
902    { "HTTP",
903      GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
904      "gnupg", N_("Configuration for HTTP servers") },
905    { "disable-http", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
906      "dirmngr", "inhibit the use of HTTP",
907       GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
908    { "ignore-http-dp", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
909      "dirmngr", "ignore HTTP CRL distribution points",
910       GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
911    { "http-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
912      "dirmngr", "|URL|redirect all HTTP requests to URL",
913      GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },
914    { "honor-http-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
915      "gnupg", N_("use system's HTTP proxy setting"),
916      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
917
918    { "LDAP",
919      GC_OPT_FLAG_GROUP, GC_LEVEL_BASIC,
920      "gnupg", N_("Configuration of LDAP servers to use") },
921    { "disable-ldap", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
922      "dirmngr", "inhibit the use of LDAP",
923       GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
924    { "ignore-ldap-dp", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
925      "dirmngr", "ignore LDAP CRL distribution points",
926       GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
927    { "ldap-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
928      "dirmngr", "|HOST|use HOST for LDAP queries",
929      GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },
930    { "only-ldap-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
931      "dirmngr", "do not use fallback hosts with --ldap-proxy",
932       GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
933    { "add-servers", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
934      "dirmngr", "add new servers discovered in CRL distribution points"
935      " to serverlist", GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
936    { "ldaptimeout", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
937      "dirmngr", "|N|set LDAP timeout to N seconds",
938      GC_ARG_TYPE_UINT32, GC_BACKEND_DIRMNGR },
939    /* The following entry must not be removed, as it is required for
940       the GC_BACKEND_DIRMNGR_LDAP_SERVER_LIST.  */
941    { "ldapserverlist-file",
942      GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
943      "dirmngr", "|FILE|read LDAP server list from FILE",
944      GC_ARG_TYPE_FILENAME, GC_BACKEND_DIRMNGR },
945    /* This entry must come after at least one entry for
946       GC_BACKEND_DIRMNGR in this component, so that the entry for
947       "ldapserverlist-file will be initialized before this one.  */
948    { "LDAP Server", GC_OPT_FLAG_ARG_OPT|GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
949      "gnupg", N_("LDAP server list"),
950      GC_ARG_TYPE_LDAP_SERVER, GC_BACKEND_DIRMNGR_LDAP_SERVER_LIST },
951    { "max-replies", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
952      "dirmngr", "|N|do not return more than N items in one query",
953      GC_ARG_TYPE_UINT32, GC_BACKEND_DIRMNGR },
954
955    { "OCSP",
956      GC_OPT_FLAG_GROUP, GC_LEVEL_ADVANCED,
957      "gnupg", N_("Configuration for OCSP") },
958    { "allow-ocsp", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC,
959      "dirmngr", "allow sending OCSP requests",
960      GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
961    { "ignore-ocsp-service-url", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
962      "dirmngr", "ignore certificate contained OCSP service URLs",
963       GC_ARG_TYPE_NONE, GC_BACKEND_DIRMNGR },
964    { "ocsp-responder", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
965      "dirmngr", "|URL|use OCSP responder at URL",
966      GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },
967    { "ocsp-signer", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
968      "dirmngr", "|FPR|OCSP response signed by FPR",
969      GC_ARG_TYPE_STRING, GC_BACKEND_DIRMNGR },
970
971
972    GC_OPTION_NULL
973  };
974 #endif /*BUILD_WITH_DIRMNGR*/
975
976
977 /* The options of the GC_COMPONENT_PINENTRY component.  */
978 static gc_option_t gc_options_pinentry[] =
979  {
980    /* A dummy option to allow gc_component_list_components to find the
981       pinentry backend.  Needs to be a conf file. */
982    { GPGCONF_NAME"-pinentry.conf",
983      GC_OPT_FLAG_NONE, GC_LEVEL_INTERNAL,
984      NULL, NULL, GC_ARG_TYPE_FILENAME, GC_BACKEND_PINENTRY },
985
986    GC_OPTION_NULL
987  };
988
989
990 \f
991 /* Component system.  Each component is a set of options that can be
992    configured at the same time.  If you change this, don't forget to
993    update GC_COMPONENT below.  */
994 typedef enum
995   {
996     /* The classic GPG for OpenPGP.  */
997     GC_COMPONENT_GPG,
998
999     /* The GPG Agent.  */
1000     GC_COMPONENT_GPG_AGENT,
1001
1002     /* The Smardcard Daemon.  */
1003     GC_COMPONENT_SCDAEMON,
1004
1005     /* GPG for S/MIME.  */
1006     GC_COMPONENT_GPGSM,
1007
1008     /* The LDAP Directory Manager for CRLs.  */
1009     GC_COMPONENT_DIRMNGR,
1010
1011     /* The external Pinentry.  */
1012     GC_COMPONENT_PINENTRY,
1013
1014     /* The number of components.  */
1015     GC_COMPONENT_NR
1016   } gc_component_t;
1017
1018
1019 /* The information associated with each component.  */
1020 static struct
1021 {
1022   /* The name of this component.  Must not contain a colon (':')
1023      character.  */
1024   const char *name;
1025
1026   /* The gettext domain for the description DESC.  If this is NULL,
1027      then the description is not translated.  */
1028   const char *desc_domain;
1029
1030   /* The description for this domain.  */
1031   const char *desc;
1032
1033   /* The list of options for this component, terminated by
1034      GC_OPTION_NULL.  */
1035   gc_option_t *options;
1036 } gc_component[] =
1037   {
1038     { "gpg",      "gnupg", N_("GPG for OpenPGP"), gc_options_gpg },
1039     { "gpg-agent","gnupg", N_("GPG Agent"), gc_options_gpg_agent },
1040     { "scdaemon", "gnupg", N_("Smartcard Daemon"), gc_options_scdaemon },
1041     { "gpgsm",    "gnupg", N_("GPG for S/MIME"), gc_options_gpgsm },
1042     { "dirmngr",  "gnupg", N_("Directory Manager"), gc_options_dirmngr },
1043     { "pinentry", "gnupg", N_("PIN and Passphrase Entry"), gc_options_pinentry }
1044   };
1045
1046
1047
1048 /* Structure used to collect error output of the backend programs.  */
1049 struct error_line_s;
1050 typedef struct error_line_s *error_line_t;
1051 struct error_line_s
1052 {
1053   error_line_t next;   /* Link to next item.  */
1054   const char *fname;   /* Name of the config file (points into BUFFER).  */
1055   unsigned int lineno; /* Line number of the config file.  */
1056   const char *errtext; /* Text of the error message (points into BUFFER).  */
1057   char buffer[1];  /* Helper buffer.  */
1058 };
1059
1060
1061 \f
1062 /* Engine specific support.  */
1063 static void
1064 gpg_agent_runtime_change (int killflag)
1065 {
1066   gpg_error_t err;
1067   const char *pgmname;
1068   const char *argv[3];
1069   pid_t pid;
1070
1071   pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
1072   argv[0] = "--no-autostart";
1073   argv[1] = killflag? "KILLAGENT" : "RELOADAGENT";
1074   argv[2] = NULL;
1075
1076   err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
1077   if (!err)
1078     err = gnupg_wait_process (pgmname, pid, 1, NULL);
1079   if (err)
1080     gc_error (0, 0, "error running '%s %s': %s",
1081               pgmname, argv[1], gpg_strerror (err));
1082   gnupg_release_process (pid);
1083 }
1084
1085
1086 static void
1087 scdaemon_runtime_change (int killflag)
1088 {
1089   gpg_error_t err;
1090   const char *pgmname;
1091   const char *argv[7];
1092   pid_t pid;
1093
1094   (void)killflag;  /* For scdaemon kill and reload are synonyms.  */
1095
1096   /* We use "GETINFO app_running" to see whether the agent is already
1097      running and kill it only in this case.  This avoids an explicit
1098      starting of the agent in case it is not yet running.  There is
1099      obviously a race condition but that should not harm too much.  */
1100
1101   pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
1102   argv[0] = "-s";
1103   argv[1] = "--no-autostart";
1104   argv[2] = "GETINFO scd_running";
1105   argv[3] = "/if ${! $?}";
1106   argv[4] = "scd killscd";
1107   argv[5] = "/end";
1108   argv[6] = NULL;
1109
1110   err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
1111   if (!err)
1112     err = gnupg_wait_process (pgmname, pid, 1, NULL);
1113   if (err)
1114     gc_error (0, 0, "error running '%s %s': %s",
1115               pgmname, argv[4], gpg_strerror (err));
1116   gnupg_release_process (pid);
1117 }
1118
1119
1120 static void
1121 dirmngr_runtime_change (int killflag)
1122 {
1123   gpg_error_t err;
1124   const char *pgmname;
1125   const char *argv[4];
1126   pid_t pid;
1127
1128   pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
1129   argv[0] = "--no-autostart";
1130   argv[1] = "--dirmngr";
1131   argv[2] = killflag? "KILLDIRMNGR" : "RELOADDIRMNGR";
1132   argv[3] = NULL;
1133
1134   err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
1135   if (!err)
1136     err = gnupg_wait_process (pgmname, pid, 1, NULL);
1137   if (err)
1138     gc_error (0, 0, "error running '%s %s': %s",
1139               pgmname, argv[2], gpg_strerror (err));
1140   gnupg_release_process (pid);
1141 }
1142
1143
1144 /* Launch the gpg-agent or the dirmngr if not already running.  */
1145 void
1146 gc_component_launch (int component)
1147 {
1148   gpg_error_t err;
1149   const char *pgmname;
1150   const char *argv[3];
1151   int i;
1152   pid_t pid;
1153
1154   if (!(component == GC_COMPONENT_GPG_AGENT
1155         || component == GC_COMPONENT_DIRMNGR))
1156     {
1157       es_fputs (_("Component not suitable for launching"), es_stderr);
1158       es_putc ('\n', es_stderr);
1159       exit (1);
1160     }
1161
1162   pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
1163   i = 0;
1164   if (component == GC_COMPONENT_DIRMNGR)
1165     argv[i++] = "--dirmngr";
1166   argv[i++] = "NOP";
1167   argv[i] = NULL;
1168
1169   err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
1170   if (!err)
1171     err = gnupg_wait_process (pgmname, pid, 1, NULL);
1172   if (err)
1173     gc_error (0, 0, "error running '%s%s%s': %s",
1174               pgmname,
1175               component == GC_COMPONENT_DIRMNGR? " --dirmngr":"",
1176               " NOP",
1177               gpg_strerror (err));
1178   gnupg_release_process (pid);
1179 }
1180
1181
1182 /* Unconditionally restart COMPONENT.  */
1183 void
1184 gc_component_kill (int component)
1185 {
1186   int runtime[GC_BACKEND_NR];
1187   gc_option_t *option;
1188   gc_backend_t backend;
1189
1190   /* Set a flag for the backends to be reloaded.  */
1191   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1192     runtime[backend] = 0;
1193
1194   if (component >= 0)
1195     {
1196       assert (component < GC_COMPONENT_NR);
1197       option = gc_component[component].options;
1198       for (; option && option->name; option++)
1199         runtime[option->backend] = 1;
1200     }
1201
1202   /* Do the restart for the selected backends.  */
1203   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1204     {
1205       if (runtime[backend] && gc_backend[backend].runtime_change)
1206         (*gc_backend[backend].runtime_change) (1);
1207     }
1208 }
1209
1210
1211 /* Unconditionally reload COMPONENT or all components if COMPONENT is -1.  */
1212 void
1213 gc_component_reload (int component)
1214 {
1215   int runtime[GC_BACKEND_NR];
1216   gc_option_t *option;
1217   gc_backend_t backend;
1218
1219   /* Set a flag for the backends to be reloaded.  */
1220   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1221     runtime[backend] = 0;
1222
1223   if (component == -1)
1224     {
1225       for (component = 0; component < GC_COMPONENT_NR; component++)
1226         {
1227           option = gc_component[component].options;
1228           for (; option && option->name; option++)
1229             runtime[option->backend] = 1;
1230         }
1231     }
1232   else
1233     {
1234       assert (component < GC_COMPONENT_NR);
1235       option = gc_component[component].options;
1236       for (; option && option->name; option++)
1237         runtime[option->backend] = 1;
1238     }
1239
1240   /* Do the reload for all selected backends.  */
1241   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1242     {
1243       if (runtime[backend] && gc_backend[backend].runtime_change)
1244         (*gc_backend[backend].runtime_change) (0);
1245     }
1246 }
1247
1248
1249 \f
1250 /* More or less Robust version of dgettext.  It has the side effect of
1251    switching the codeset to utf-8 because this is what we want to
1252    output.  In theory it is posible to keep the orginal code set and
1253    switch back for regular disgnostic output (redefine "_(" for that)
1254    but given the natur of this tool, being something invoked from
1255    other pograms, it does not make much sense.  */
1256 static const char *
1257 my_dgettext (const char *domain, const char *msgid)
1258 {
1259 #ifdef USE_SIMPLE_GETTEXT
1260   if (domain)
1261     {
1262       static int switched_codeset;
1263       char *text;
1264
1265       if (!switched_codeset)
1266         {
1267           switched_codeset = 1;
1268           gettext_use_utf8 (1);
1269         }
1270
1271       if (!strcmp (domain, "gnupg"))
1272         domain = PACKAGE_GT;
1273
1274       /* FIXME: we have no dgettext, thus we can't switch.  */
1275
1276       text = (char*)gettext (msgid);
1277       return text ? text : msgid;
1278     }
1279   else
1280     return msgid;
1281 #elif defined(ENABLE_NLS)
1282   if (domain)
1283     {
1284       static int switched_codeset;
1285       char *text;
1286
1287       if (!switched_codeset)
1288         {
1289           switched_codeset = 1;
1290           bind_textdomain_codeset (PACKAGE_GT, "utf-8");
1291
1292           bindtextdomain (DIRMNGR_NAME, LOCALEDIR);
1293           bind_textdomain_codeset (DIRMNGR_NAME, "utf-8");
1294
1295         }
1296
1297       /* Note: This is a hack to actually use the gnupg2 domain as
1298          long we are in a transition phase where gnupg 1.x and 1.9 may
1299          coexist. */
1300       if (!strcmp (domain, "gnupg"))
1301         domain = PACKAGE_GT;
1302
1303       text = dgettext (domain, msgid);
1304       return text ? text : msgid;
1305     }
1306   else
1307     return msgid;
1308 #else
1309   (void)domain;
1310   return msgid;
1311 #endif
1312 }
1313
1314
1315 /* Percent-Escape special characters.  The string is valid until the
1316    next invocation of the function.  */
1317 char *
1318 gc_percent_escape (const char *src)
1319 {
1320   static char *esc_str;
1321   static int esc_str_len;
1322   int new_len = 3 * strlen (src) + 1;
1323   char *dst;
1324
1325   if (esc_str_len < new_len)
1326     {
1327       char *new_esc_str = realloc (esc_str, new_len);
1328       if (!new_esc_str)
1329         gc_error (1, errno, "can not escape string");
1330       esc_str = new_esc_str;
1331       esc_str_len = new_len;
1332     }
1333
1334   dst = esc_str;
1335   while (*src)
1336     {
1337       if (*src == '%')
1338         {
1339           *(dst++) = '%';
1340           *(dst++) = '2';
1341           *(dst++) = '5';
1342         }
1343       else if (*src == ':')
1344         {
1345           /* The colon is used as field separator.  */
1346           *(dst++) = '%';
1347           *(dst++) = '3';
1348           *(dst++) = 'a';
1349         }
1350       else if (*src == ',')
1351         {
1352           /* The comma is used as list separator.  */
1353           *(dst++) = '%';
1354           *(dst++) = '2';
1355           *(dst++) = 'c';
1356         }
1357       else
1358         *(dst++) = *(src);
1359       src++;
1360     }
1361   *dst = '\0';
1362   return esc_str;
1363 }
1364
1365
1366
1367 /* Percent-Deescape special characters.  The string is valid until the
1368    next invocation of the function.  */
1369 static char *
1370 percent_deescape (const char *src)
1371 {
1372   static char *str;
1373   static int str_len;
1374   int new_len = 3 * strlen (src) + 1;
1375   char *dst;
1376
1377   if (str_len < new_len)
1378     {
1379       char *new_str = realloc (str, new_len);
1380       if (!new_str)
1381         gc_error (1, errno, "can not deescape string");
1382       str = new_str;
1383       str_len = new_len;
1384     }
1385
1386   dst = str;
1387   while (*src)
1388     {
1389       if (*src == '%')
1390         {
1391           int val = hextobyte (src + 1);
1392
1393           if (val < 0)
1394             gc_error (1, 0, "malformed end of string %s", src);
1395
1396           *(dst++) = (char) val;
1397           src += 3;
1398         }
1399       else
1400         *(dst++) = *(src++);
1401     }
1402   *dst = '\0';
1403   return str;
1404 }
1405
1406 \f
1407 /* List all components that are available.  */
1408 void
1409 gc_component_list_components (estream_t out)
1410 {
1411   gc_component_t component;
1412   gc_option_t *option;
1413   gc_backend_t backend;
1414   int backend_seen[GC_BACKEND_NR];
1415   const char *desc;
1416   const char *pgmname;
1417
1418   for (component = 0; component < GC_COMPONENT_NR; component++)
1419     {
1420       option = gc_component[component].options;
1421       if (option)
1422         {
1423           for (backend = 0; backend < GC_BACKEND_NR; backend++)
1424             backend_seen[backend] = 0;
1425
1426           pgmname = "";
1427           for (; option && option->name; option++)
1428             {
1429               if ((option->flags & GC_OPT_FLAG_GROUP))
1430                 continue;
1431               backend = option->backend;
1432               if (backend_seen[backend])
1433                 continue;
1434               backend_seen[backend] = 1;
1435               assert (backend != GC_BACKEND_ANY);
1436               if (gc_backend[backend].program
1437                   && !gc_backend[backend].module_name)
1438                 continue;
1439               pgmname = gnupg_module_name (gc_backend[backend].module_name);
1440               break;
1441             }
1442
1443           desc = gc_component[component].desc;
1444           desc = my_dgettext (gc_component[component].desc_domain, desc);
1445           es_fprintf (out, "%s:%s:",
1446                       gc_component[component].name,  gc_percent_escape (desc));
1447           es_fprintf (out, "%s\n",  gc_percent_escape (pgmname));
1448         }
1449     }
1450 }
1451
1452
1453 \f
1454 static int
1455 all_digits_p (const char *p, size_t len)
1456 {
1457   if (!len)
1458     return 0; /* No. */
1459   for (; len; len--, p++)
1460     if (!isascii (*p) || !isdigit (*p))
1461       return 0; /* No.  */
1462   return 1; /* Yes.  */
1463 }
1464
1465
1466 /* Collect all error lines from stream FP. Only lines prefixed with
1467    TAG are considered.  Returns a list of error line items (which may
1468    be empty).  There is no error return.  */
1469 static error_line_t
1470 collect_error_output (estream_t fp, const char *tag)
1471 {
1472   char buffer[1024];
1473   char *p, *p2, *p3;
1474   int c, cont_line;
1475   unsigned int pos;
1476   error_line_t eitem, errlines, *errlines_tail;
1477   size_t taglen = strlen (tag);
1478
1479   errlines = NULL;
1480   errlines_tail = &errlines;
1481   pos = 0;
1482   cont_line = 0;
1483   while ((c=es_getc (fp)) != EOF)
1484     {
1485       buffer[pos++] = c;
1486       if (pos >= sizeof buffer - 5 || c == '\n')
1487         {
1488           buffer[pos - (c == '\n')] = 0;
1489           if (cont_line)
1490             ; /*Ignore continuations of previous line. */
1491           else if (!strncmp (buffer, tag, taglen) && buffer[taglen] == ':')
1492             {
1493               /* "gpgsm: foo:4: bla" */
1494               /* Yep, we are interested in this line.  */
1495               p = buffer + taglen + 1;
1496               while (*p == ' ' || *p == '\t')
1497                 p++;
1498               trim_trailing_spaces (p); /* Get rid of extra CRs.  */
1499               if (!*p)
1500                 ; /* Empty lines are ignored.  */
1501               else if ( (p2 = strchr (p, ':')) && (p3 = strchr (p2+1, ':'))
1502                         && all_digits_p (p2+1, p3 - (p2+1)))
1503                 {
1504                   /* Line in standard compiler format.  */
1505                   p3++;
1506                   while (*p3 == ' ' || *p3 == '\t')
1507                     p3++;
1508                   eitem = xmalloc (sizeof *eitem + strlen (p));
1509                   eitem->next = NULL;
1510                   strcpy (eitem->buffer, p);
1511                   eitem->fname = eitem->buffer;
1512                   eitem->buffer[p2-p] = 0;
1513                   eitem->errtext = eitem->buffer + (p3 - p);
1514                   /* (we already checked that there are only ascii
1515                      digits followed by a colon) */
1516                   eitem->lineno = 0;
1517                   for (p2++; isdigit (*p2); p2++)
1518                     eitem->lineno = eitem->lineno*10 + (*p2 - '0');
1519                   *errlines_tail = eitem;
1520                   errlines_tail = &eitem->next;
1521                 }
1522               else
1523                 {
1524                   /* Other error output.  */
1525                   eitem = xmalloc (sizeof *eitem + strlen (p));
1526                   eitem->next = NULL;
1527                   strcpy (eitem->buffer, p);
1528                   eitem->fname = NULL;
1529                   eitem->errtext = eitem->buffer;
1530                   eitem->lineno = 0;
1531                   *errlines_tail = eitem;
1532                   errlines_tail = &eitem->next;
1533                 }
1534             }
1535           pos = 0;
1536           /* If this was not a complete line mark that we are in a
1537              continuation.  */
1538           cont_line = (c != '\n');
1539         }
1540     }
1541
1542   /* We ignore error lines not terminated by a LF.  */
1543   return errlines;
1544 }
1545
1546
1547 /* Check the options of a single component.  Returns 0 if everything
1548    is OK.  */
1549 int
1550 gc_component_check_options (int component, estream_t out, const char *conf_file)
1551 {
1552   gpg_error_t err;
1553   unsigned int result;
1554   int backend_seen[GC_BACKEND_NR];
1555   gc_backend_t backend;
1556   gc_option_t *option;
1557   const char *pgmname;
1558   const char *argv[4];
1559   int i;
1560   pid_t pid;
1561   int exitcode;
1562   estream_t errfp;
1563   error_line_t errlines;
1564
1565   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1566     backend_seen[backend] = 0;
1567
1568   option = gc_component[component].options;
1569   for (; option && option->name; option++)
1570     {
1571       if ((option->flags & GC_OPT_FLAG_GROUP))
1572         continue;
1573       backend = option->backend;
1574       if (backend_seen[backend])
1575         continue;
1576       backend_seen[backend] = 1;
1577       assert (backend != GC_BACKEND_ANY);
1578       if (!gc_backend[backend].program)
1579         continue;
1580       if (!gc_backend[backend].module_name)
1581         continue;
1582
1583       break;
1584     }
1585   if (! option || ! option->name)
1586     return 0;
1587
1588   pgmname = gnupg_module_name (gc_backend[backend].module_name);
1589   i = 0;
1590   if (conf_file)
1591     {
1592       argv[i++] = "--options";
1593       argv[i++] = conf_file;
1594     }
1595   if (component == GC_COMPONENT_PINENTRY)
1596     argv[i++] = "--version";
1597   else
1598     argv[i++] = "--gpgconf-test";
1599   argv[i++] = NULL;
1600
1601   result = 0;
1602   errlines = NULL;
1603   err = gnupg_spawn_process (pgmname, argv, GPG_ERR_SOURCE_DEFAULT, NULL, 0,
1604                              NULL, NULL, &errfp, &pid);
1605   if (err)
1606     result |= 1; /* Program could not be run.  */
1607   else
1608     {
1609       errlines = collect_error_output (errfp,
1610                                        gc_component[component].name);
1611       if (gnupg_wait_process (pgmname, pid, 1, &exitcode))
1612         {
1613           if (exitcode == -1)
1614             result |= 1; /* Program could not be run or it
1615                             terminated abnormally.  */
1616           result |= 2; /* Program returned an error.  */
1617         }
1618       gnupg_release_process (pid);
1619       es_fclose (errfp);
1620     }
1621
1622   /* If the program could not be run, we can't tell whether
1623      the config file is good.  */
1624   if (result & 1)
1625     result |= 2;
1626
1627   if (out)
1628     {
1629       const char *desc;
1630       error_line_t errptr;
1631
1632       desc = gc_component[component].desc;
1633       desc = my_dgettext (gc_component[component].desc_domain, desc);
1634       es_fprintf (out, "%s:%s:",
1635                   gc_component[component].name, gc_percent_escape (desc));
1636       es_fputs (gc_percent_escape (pgmname), out);
1637       es_fprintf (out, ":%d:%d:", !(result & 1), !(result & 2));
1638       for (errptr = errlines; errptr; errptr = errptr->next)
1639         {
1640           if (errptr != errlines)
1641             es_fputs ("\n:::::", out); /* Continuation line.  */
1642           if (errptr->fname)
1643             es_fputs (gc_percent_escape (errptr->fname), out);
1644           es_putc (':', out);
1645           if (errptr->fname)
1646             es_fprintf (out, "%u", errptr->lineno);
1647           es_putc (':', out);
1648           es_fputs (gc_percent_escape (errptr->errtext), out);
1649           es_putc (':', out);
1650         }
1651       es_putc ('\n', out);
1652     }
1653
1654   while (errlines)
1655     {
1656       error_line_t tmp = errlines->next;
1657       xfree (errlines);
1658       errlines = tmp;
1659     }
1660
1661   return result;
1662 }
1663
1664
1665
1666 /* Check all components that are available.  */
1667 void
1668 gc_check_programs (estream_t out)
1669 {
1670   gc_component_t component;
1671
1672   for (component = 0; component < GC_COMPONENT_NR; component++)
1673     gc_component_check_options (component, out, NULL);
1674 }
1675
1676
1677 \f
1678 /* Find the component with the name NAME.  Returns -1 if not
1679    found.  */
1680 int
1681 gc_component_find (const char *name)
1682 {
1683   gc_component_t idx;
1684
1685   for (idx = 0; idx < GC_COMPONENT_NR; idx++)
1686     {
1687       if (gc_component[idx].options
1688           && !strcmp (name, gc_component[idx].name))
1689         return idx;
1690     }
1691   return -1;
1692 }
1693
1694 \f
1695 /* List the option OPTION.  */
1696 static void
1697 list_one_option (const gc_option_t *option, estream_t out)
1698 {
1699   const char *desc = NULL;
1700   char *arg_name = NULL;
1701
1702   if (option->desc)
1703     {
1704       desc = my_dgettext (option->desc_domain, option->desc);
1705
1706       if (*desc == '|')
1707         {
1708           const char *arg_tail = strchr (&desc[1], '|');
1709
1710           if (arg_tail)
1711             {
1712               int arg_len = arg_tail - &desc[1];
1713               arg_name = xmalloc (arg_len + 1);
1714               memcpy (arg_name, &desc[1], arg_len);
1715               arg_name[arg_len] = '\0';
1716               desc = arg_tail + 1;
1717             }
1718         }
1719     }
1720
1721
1722   /* YOU MUST NOT REORDER THE FIELDS IN THIS OUTPUT, AS THEIR ORDER IS
1723      PART OF THE EXTERNAL INTERFACE.  YOU MUST NOT REMOVE ANY
1724      FIELDS.  */
1725
1726   /* The name field.  */
1727   es_fprintf (out, "%s", option->name);
1728
1729   /* The flags field.  */
1730   es_fprintf (out, ":%lu", option->flags);
1731   if (opt.verbose)
1732     {
1733       es_putc (' ', out);
1734
1735       if (!option->flags)
1736         es_fprintf (out, "none");
1737       else
1738         {
1739           unsigned long flags = option->flags;
1740           unsigned long flag = 0;
1741           unsigned long first = 1;
1742
1743           while (flags)
1744             {
1745               if (flags & 1)
1746                 {
1747                   if (first)
1748                     first = 0;
1749                   else
1750                     es_putc (',', out);
1751                   es_fprintf (out, "%s", gc_flag[flag].name);
1752                 }
1753               flags >>= 1;
1754               flag++;
1755             }
1756         }
1757     }
1758
1759   /* The level field.  */
1760   es_fprintf (out, ":%u", option->level);
1761   if (opt.verbose)
1762     es_fprintf (out, " %s", gc_level[option->level].name);
1763
1764   /* The description field.  */
1765   es_fprintf (out, ":%s", desc ? gc_percent_escape (desc) : "");
1766
1767   /* The type field.  */
1768   es_fprintf (out, ":%u", option->arg_type);
1769   if (opt.verbose)
1770     es_fprintf (out, " %s", gc_arg_type[option->arg_type].name);
1771
1772   /* The alternate type field.  */
1773   es_fprintf (out, ":%u", gc_arg_type[option->arg_type].fallback);
1774   if (opt.verbose)
1775     es_fprintf (out, " %s",
1776                 gc_arg_type[gc_arg_type[option->arg_type].fallback].name);
1777
1778   /* The argument name field.  */
1779   es_fprintf (out, ":%s", arg_name ? gc_percent_escape (arg_name) : "");
1780   xfree (arg_name);
1781
1782   /* The default value field.  */
1783   es_fprintf (out, ":%s", option->default_value ? option->default_value : "");
1784
1785   /* The default argument field.  */
1786   es_fprintf (out, ":%s", option->default_arg ? option->default_arg : "");
1787
1788   /* The value field.  */
1789   if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE
1790       && (option->flags & GC_OPT_FLAG_LIST)
1791       && option->value)
1792     /* The special format "1,1,1,1,...,1" is converted to a number
1793        here.  */
1794     es_fprintf (out, ":%u", (unsigned int)((strlen (option->value) + 1) / 2));
1795   else
1796     es_fprintf (out, ":%s", option->value ? option->value : "");
1797
1798   /* ADD NEW FIELDS HERE.  */
1799
1800   es_putc ('\n', out);
1801 }
1802
1803
1804 /* List all options of the component COMPONENT.  */
1805 void
1806 gc_component_list_options (int component, estream_t out)
1807 {
1808   const gc_option_t *option = gc_component[component].options;
1809
1810   while (option && option->name)
1811     {
1812       /* Do not output unknown or internal options.  */
1813       if (!(option->flags & GC_OPT_FLAG_GROUP)
1814           && (!option->active || option->level == GC_LEVEL_INTERNAL))
1815         {
1816           option++;
1817           continue;
1818         }
1819
1820       if (option->flags & GC_OPT_FLAG_GROUP)
1821         {
1822           const gc_option_t *group_option = option + 1;
1823           gc_expert_level_t level = GC_LEVEL_NR;
1824
1825           /* The manual states that the group level is always the
1826              minimum of the levels of all contained options.  Due to
1827              different active options, and because it is hard to
1828              maintain manually, we calculate it here.  The value in
1829              the global static table is ignored.  */
1830
1831           while (group_option->name)
1832             {
1833               if (group_option->flags & GC_OPT_FLAG_GROUP)
1834                 break;
1835               if (group_option->level < level)
1836                 level = group_option->level;
1837               group_option++;
1838             }
1839
1840           /* Check if group is empty.  */
1841           if (level != GC_LEVEL_NR)
1842             {
1843               gc_option_t opt_copy;
1844
1845               /* Fix up the group level.  */
1846               memcpy (&opt_copy, option, sizeof (opt_copy));
1847               opt_copy.level = level;
1848               list_one_option (&opt_copy, out);
1849             }
1850         }
1851       else
1852         list_one_option (option, out);
1853
1854       option++;
1855     }
1856 }
1857
1858
1859 /* Find the option NAME in component COMPONENT, for the backend
1860    BACKEND.  If BACKEND is GC_BACKEND_ANY, any backend will match.  */
1861 static gc_option_t *
1862 find_option (gc_component_t component, const char *name,
1863              gc_backend_t backend)
1864 {
1865   gc_option_t *option = gc_component[component].options;
1866   while (option->name)
1867     {
1868       if (!(option->flags & GC_OPT_FLAG_GROUP)
1869           && !strcmp (option->name, name)
1870           && (backend == GC_BACKEND_ANY || option->backend == backend))
1871         break;
1872       option++;
1873     }
1874   return option->name ? option : NULL;
1875 }
1876
1877 \f
1878 /* Determine the configuration filename for the component COMPONENT
1879    and backend BACKEND.  */
1880 static char *
1881 get_config_filename (gc_component_t component, gc_backend_t backend)
1882 {
1883   char *filename = NULL;
1884   gc_option_t *option = find_option
1885     (component, gc_backend[backend].option_config_filename, GC_BACKEND_ANY);
1886   assert (option);
1887   assert (option->arg_type == GC_ARG_TYPE_FILENAME);
1888   assert (!(option->flags & GC_OPT_FLAG_LIST));
1889
1890   if (!option->active || !option->default_value)
1891     gc_error (1, 0, "Option %s, needed by backend %s, was not initialized",
1892               gc_backend[backend].option_config_filename,
1893               gc_backend[backend].name);
1894
1895   if (option->value && *option->value)
1896     filename = percent_deescape (&option->value[1]);
1897   else if (option->default_value && *option->default_value)
1898     filename = percent_deescape (&option->default_value[1]);
1899   else
1900     filename = "";
1901
1902 #if HAVE_W32CE_SYSTEM
1903   if (!(filename[0] == '/' || filename[0] == '\\'))
1904 #elif defined(HAVE_DOSISH_SYSTEM)
1905   if (!(filename[0]
1906         && filename[1] == ':'
1907         && (filename[2] == '/' || filename[2] == '\\')))
1908 #else
1909   if (filename[0] != '/')
1910 #endif
1911     gc_error (1, 0, "Option %s, needed by backend %s, is not absolute",
1912               gc_backend[backend].option_config_filename,
1913               gc_backend[backend].name);
1914
1915   return filename;
1916 }
1917
1918 \f
1919 /* Retrieve the options for the component COMPONENT from backend
1920    BACKEND, which we already know is a program-type backend.  */
1921 static void
1922 retrieve_options_from_program (gc_component_t component, gc_backend_t backend)
1923 {
1924   gpg_error_t err;
1925   const char *pgmname;
1926   const char *argv[2];
1927   estream_t outfp;
1928   int exitcode;
1929   pid_t pid;
1930   char *line = NULL;
1931   size_t line_len = 0;
1932   ssize_t length;
1933   estream_t config;
1934   char *config_filename;
1935
1936   pgmname = (gc_backend[backend].module_name
1937              ? gnupg_module_name (gc_backend[backend].module_name)
1938              : gc_backend[backend].program );
1939   argv[0] = "--gpgconf-list";
1940   argv[1] = NULL;
1941
1942   err = gnupg_spawn_process (pgmname, argv, GPG_ERR_SOURCE_DEFAULT, NULL, 0,
1943                              NULL, &outfp, NULL, &pid);
1944   if (err)
1945     {
1946       gc_error (1, 0, "could not gather active options from '%s': %s",
1947                 pgmname, gpg_strerror (err));
1948     }
1949
1950   while ((length = es_read_line (outfp, &line, &line_len, NULL)) > 0)
1951     {
1952       gc_option_t *option;
1953       char *linep;
1954       unsigned long flags = 0;
1955       char *default_value = NULL;
1956
1957       /* Strip newline and carriage return, if present.  */
1958       while (length > 0
1959              && (line[length - 1] == '\n' || line[length - 1] == '\r'))
1960         line[--length] = '\0';
1961
1962       linep = strchr (line, ':');
1963       if (linep)
1964         *(linep++) = '\0';
1965
1966       /* Extract additional flags.  Default to none.  */
1967       if (linep)
1968         {
1969           char *end;
1970           char *tail;
1971
1972           end = strchr (linep, ':');
1973           if (end)
1974             *(end++) = '\0';
1975
1976           gpg_err_set_errno (0);
1977           flags = strtoul (linep, &tail, 0);
1978           if (errno)
1979             gc_error (1, errno, "malformed flags in option %s from %s",
1980                       line, pgmname);
1981           if (!(*tail == '\0' || *tail == ':' || *tail == ' '))
1982             gc_error (1, 0, "garbage after flags in option %s from %s",
1983                       line, pgmname);
1984
1985           linep = end;
1986         }
1987
1988       /* Extract default value, if present.  Default to empty if
1989          not.  */
1990       if (linep)
1991         {
1992           char *end;
1993
1994           end = strchr (linep, ':');
1995           if (end)
1996             *(end++) = '\0';
1997
1998           if (flags & GC_OPT_FLAG_DEFAULT)
1999             default_value = linep;
2000
2001           linep = end;
2002         }
2003
2004       /* Look up the option in the component and install the
2005          configuration data.  */
2006       option = find_option (component, line, backend);
2007       if (option)
2008         {
2009           if (option->active)
2010             gc_error (1, errno, "option %s returned twice from %s",
2011                       line, pgmname);
2012           option->active = 1;
2013
2014           option->flags |= flags;
2015           if (default_value && *default_value)
2016             option->default_value = xstrdup (default_value);
2017         }
2018     }
2019   if (length < 0 || es_ferror (outfp))
2020     gc_error (1, errno, "error reading from %s", pgmname);
2021   if (es_fclose (outfp))
2022     gc_error (1, errno, "error closing %s", pgmname);
2023
2024   err = gnupg_wait_process (pgmname, pid, 1, &exitcode);
2025   if (err)
2026     gc_error (1, 0, "running %s failed (exitcode=%d): %s",
2027               pgmname, exitcode, gpg_strerror (err));
2028   gnupg_release_process (pid);
2029
2030
2031   /* At this point, we can parse the configuration file.  */
2032   config_filename = get_config_filename (component, backend);
2033
2034   config = es_fopen (config_filename, "r");
2035   if (!config)
2036     gc_error (0, errno, "warning: can not open config file %s",
2037               config_filename);
2038   else
2039     {
2040       while ((length = es_read_line (config, &line, &line_len, NULL)) > 0)
2041         {
2042           char *name;
2043           char *value;
2044           gc_option_t *option;
2045
2046           name = line;
2047           while (*name == ' ' || *name == '\t')
2048             name++;
2049           if (!*name || *name == '#' || *name == '\r' || *name == '\n')
2050             continue;
2051
2052           value = name;
2053           while (*value && *value != ' ' && *value != '\t'
2054                  && *value != '#' && *value != '\r' && *value != '\n')
2055             value++;
2056           if (*value == ' ' || *value == '\t')
2057             {
2058               char *end;
2059
2060               *(value++) = '\0';
2061               while (*value == ' ' || *value == '\t')
2062                 value++;
2063
2064               end = value;
2065               while (*end && *end != '#' && *end != '\r' && *end != '\n')
2066                 end++;
2067               while (end > value && (end[-1] == ' ' || end[-1] == '\t'))
2068                 end--;
2069               *end = '\0';
2070             }
2071           else
2072             *value = '\0';
2073
2074           /* Look up the option in the component and install the
2075              configuration data.  */
2076           option = find_option (component, line, backend);
2077           if (option)
2078             {
2079               char *opt_value;
2080
2081               if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE)
2082                 {
2083                   if (*value)
2084                     gc_error (0, 0,
2085                               "warning: ignoring argument %s for option %s",
2086                               value, name);
2087                   opt_value = xstrdup ("1");
2088                 }
2089               else if (gc_arg_type[option->arg_type].fallback
2090                        == GC_ARG_TYPE_STRING)
2091                 opt_value = xasprintf ("\"%s", gc_percent_escape (value));
2092               else
2093                 {
2094                   /* FIXME: Verify that the number is sane.  */
2095                   opt_value = xstrdup (value);
2096                 }
2097
2098               /* Now enter the option into the table.  */
2099               if (!(option->flags & GC_OPT_FLAG_LIST))
2100                 {
2101                   if (option->value)
2102                     free (option->value);
2103                   option->value = opt_value;
2104                 }
2105               else
2106                 {
2107                   if (!option->value)
2108                     option->value = opt_value;
2109                   else
2110                     {
2111                       char *opt_val = opt_value;
2112
2113                       option->value = xasprintf ("%s,%s", option->value,
2114                                                  opt_val);
2115                       xfree (opt_value);
2116                     }
2117                 }
2118             }
2119         }
2120
2121       if (length < 0 || es_ferror (config))
2122         gc_error (1, errno, "error reading from %s", config_filename);
2123       if (es_fclose (config))
2124         gc_error (1, errno, "error closing %s", config_filename);
2125     }
2126
2127   xfree (line);
2128 }
2129
2130
2131 /* Retrieve the options for the component COMPONENT from backend
2132    BACKEND, which we already know is of type file list.  */
2133 static void
2134 retrieve_options_from_file (gc_component_t component, gc_backend_t backend)
2135 {
2136   gc_option_t *list_option;
2137   gc_option_t *config_option;
2138   char *list_filename;
2139   FILE *list_file;
2140   char *line = NULL;
2141   size_t line_len = 0;
2142   ssize_t length;
2143   char *list = NULL;
2144
2145   list_option = find_option (component,
2146                              gc_backend[backend].option_name, GC_BACKEND_ANY);
2147   assert (list_option);
2148   assert (!list_option->active);
2149
2150   list_filename = get_config_filename (component, backend);
2151   list_file = fopen (list_filename, "r");
2152   if (!list_file)
2153     gc_error (0, errno, "warning: can not open list file %s", list_filename);
2154   else
2155     {
2156
2157       while ((length = read_line (list_file, &line, &line_len, NULL)) > 0)
2158         {
2159           char *start;
2160           char *end;
2161           char *new_list;
2162
2163           start = line;
2164           while (*start == ' ' || *start == '\t')
2165             start++;
2166           if (!*start || *start == '#' || *start == '\r' || *start == '\n')
2167             continue;
2168
2169           end = start;
2170           while (*end && *end != '#' && *end != '\r' && *end != '\n')
2171             end++;
2172           /* Walk back to skip trailing white spaces.  Looks evil, but
2173              works because of the conditions on START and END imposed
2174              at this point (END is at least START + 1, and START is
2175              not a whitespace character).  */
2176           while (*(end - 1) == ' ' || *(end - 1) == '\t')
2177             end--;
2178           *end = '\0';
2179           /* FIXME: Oh, no!  This is so lame!  Should use realloc and
2180              really append.  */
2181           if (list)
2182             {
2183               new_list = xasprintf ("%s,\"%s", list, gc_percent_escape (start));
2184               xfree (list);
2185               list = new_list;
2186             }
2187           else
2188             list = xasprintf ("\"%s", gc_percent_escape (start));
2189         }
2190       if (length < 0 || ferror (list_file))
2191         gc_error (1, errno, "can not read list file %s", list_filename);
2192     }
2193
2194   list_option->active = 1;
2195   list_option->value = list;
2196
2197   /* Fix up the read-only flag.  */
2198   config_option = find_option
2199     (component, gc_backend[backend].option_config_filename, GC_BACKEND_ANY);
2200   if (config_option->flags & GC_OPT_FLAG_NO_CHANGE)
2201     list_option->flags |= GC_OPT_FLAG_NO_CHANGE;
2202
2203   if (list_file && fclose (list_file))
2204     gc_error (1, errno, "error closing %s", list_filename);
2205   xfree (line);
2206 }
2207
2208
2209 /* Retrieve the currently active options and their defaults from all
2210    involved backends for this component.  Using -1 for component will
2211    retrieve all options from all components. */
2212 void
2213 gc_component_retrieve_options (int component)
2214 {
2215   int process_all = 0;
2216   int backend_seen[GC_BACKEND_NR];
2217   gc_backend_t backend;
2218   gc_option_t *option;
2219
2220   if (component == GC_COMPONENT_PINENTRY)
2221     return; /* Dummy module for now.  */
2222
2223   for (backend = 0; backend < GC_BACKEND_NR; backend++)
2224     backend_seen[backend] = 0;
2225
2226   if (component == -1)
2227     {
2228       process_all = 1;
2229       component = 0;
2230       assert (component < GC_COMPONENT_NR);
2231     }
2232
2233   do
2234     {
2235       option = gc_component[component].options;
2236
2237       while (option && option->name)
2238         {
2239           if (!(option->flags & GC_OPT_FLAG_GROUP))
2240             {
2241               backend = option->backend;
2242
2243               if (backend_seen[backend])
2244                 {
2245                   option++;
2246                   continue;
2247                 }
2248               backend_seen[backend] = 1;
2249
2250               assert (backend != GC_BACKEND_ANY);
2251
2252               if (gc_backend[backend].program)
2253                 retrieve_options_from_program (component, backend);
2254               else
2255                 retrieve_options_from_file (component, backend);
2256             }
2257           option++;
2258         }
2259     }
2260   while (process_all && ++component < GC_COMPONENT_NR);
2261
2262 }
2263
2264
2265 \f
2266 /* Perform a simple validity check based on the type.  Return in
2267    NEW_VALUE_NR the value of the number in NEW_VALUE if OPTION is of
2268    type GC_ARG_TYPE_NONE.  */
2269 static void
2270 option_check_validity (gc_option_t *option, unsigned long flags,
2271                        char *new_value, unsigned long *new_value_nr)
2272 {
2273   char *arg;
2274
2275   if (!option->active)
2276     gc_error (1, 0, "option %s not supported by backend %s",
2277               option->name, gc_backend[option->backend].name);
2278
2279   if (option->new_flags || option->new_value)
2280     gc_error (1, 0, "option %s already changed", option->name);
2281
2282   if (flags & GC_OPT_FLAG_DEFAULT)
2283     {
2284       if (*new_value)
2285         gc_error (1, 0, "argument %s provided for deleted option %s",
2286                   new_value, option->name);
2287
2288       return;
2289     }
2290
2291   /* GC_ARG_TYPE_NONE options have special list treatment.  */
2292   if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE)
2293     {
2294       char *tail;
2295
2296       gpg_err_set_errno (0);
2297       *new_value_nr = strtoul (new_value, &tail, 0);
2298
2299       if (errno)
2300         gc_error (1, errno, "invalid argument for option %s",
2301                   option->name);
2302       if (*tail)
2303         gc_error (1, 0, "garbage after argument for option %s",
2304                       option->name);
2305
2306       if (!(option->flags & GC_OPT_FLAG_LIST))
2307         {
2308           if (*new_value_nr != 1)
2309             gc_error (1, 0, "argument for non-list option %s of type 0 "
2310                       "(none) must be 1", option->name);
2311         }
2312       else
2313         {
2314           if (*new_value_nr == 0)
2315             gc_error (1, 0, "argument for option %s of type 0 (none) "
2316                       "must be positive", option->name);
2317         }
2318
2319       return;
2320     }
2321
2322   arg = new_value;
2323   do
2324     {
2325       if (*arg == '\0' || *arg == ',')
2326         {
2327           if (!(option->flags & GC_OPT_FLAG_ARG_OPT))
2328             gc_error (1, 0, "argument required for option %s", option->name);
2329
2330           if (*arg == ',' && !(option->flags & GC_OPT_FLAG_LIST))
2331             gc_error (1, 0, "list found for non-list option %s", option->name);
2332         }
2333       else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_STRING)
2334         {
2335           if (*arg != '"')
2336             gc_error (1, 0, "string argument for option %s must begin "
2337                       "with a quote (\") character", option->name);
2338
2339           /* FIXME: We do not allow empty string arguments for now, as
2340              we do not quote arguments in configuration files, and
2341              thus no argument is indistinguishable from the empty
2342              string.  */
2343           if (arg[1] == '\0' || arg[1] == ',')
2344             gc_error (1, 0, "empty string argument for option %s is "
2345                       "currently not allowed.  Please report this!",
2346                       option->name);
2347         }
2348       else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_INT32)
2349         {
2350           long res;
2351
2352           gpg_err_set_errno (0);
2353           res = strtol (arg, &arg, 0);
2354           (void) res;
2355
2356           if (errno)
2357             gc_error (1, errno, "invalid argument for option %s",
2358                       option->name);
2359
2360           if (*arg != '\0' && *arg != ',')
2361             gc_error (1, 0, "garbage after argument for option %s",
2362                       option->name);
2363         }
2364       else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_INT32)
2365         {
2366           unsigned long res;
2367
2368           gpg_err_set_errno (0);
2369           res = strtoul (arg, &arg, 0);
2370           (void) res;
2371
2372           if (errno)
2373             gc_error (1, errno, "invalid argument for option %s",
2374                       option->name);
2375
2376           if (*arg != '\0' && *arg != ',')
2377             gc_error (1, 0, "garbage after argument for option %s",
2378                       option->name);
2379         }
2380       arg = strchr (arg, ',');
2381       if (arg)
2382         arg++;
2383     }
2384   while (arg && *arg);
2385 }
2386
2387 #ifdef HAVE_W32_SYSTEM
2388 int
2389 copy_file (const char *src_name, const char *dst_name)
2390 {
2391 #define BUF_LEN 4096
2392   char buffer[BUF_LEN];
2393   int len;
2394   FILE *src;
2395   FILE *dst;
2396
2397   src = fopen (src_name, "r");
2398   if (src == NULL)
2399     return -1;
2400
2401   dst = fopen (dst_name, "w");
2402   if (dst == NULL)
2403     {
2404       int saved_err = errno;
2405       fclose (src);
2406       gpg_err_set_errno (saved_err);
2407       return -1;
2408     }
2409
2410   do
2411     {
2412       int written;
2413
2414       len = fread (buffer, 1, BUF_LEN, src);
2415       if (len == 0)
2416         break;
2417       written = fwrite (buffer, 1, len, dst);
2418       if (written != len)
2419         break;
2420     }
2421   while (!feof (src) && !ferror (src) && !ferror (dst));
2422
2423   if (ferror (src) || ferror (dst) || !feof (src))
2424     {
2425       int saved_errno = errno;
2426       fclose (src);
2427       fclose (dst);
2428       unlink (dst_name);
2429       gpg_err_set_errno (saved_errno);
2430       return -1;
2431     }
2432
2433   if (fclose (dst))
2434     gc_error (1, errno, "error closing %s", dst_name);
2435   if (fclose (src))
2436     gc_error (1, errno, "error closing %s", src_name);
2437
2438   return 0;
2439 }
2440 #endif /* HAVE_W32_SYSTEM */
2441
2442
2443 /* Create and verify the new configuration file for the specified
2444    backend and component.  Returns 0 on success and -1 on error.  */
2445 static int
2446 change_options_file (gc_component_t component, gc_backend_t backend,
2447                      char **src_filenamep, char **dest_filenamep,
2448                      char **orig_filenamep)
2449 {
2450   static const char marker[] = "###+++--- " GPGCONF_DISP_NAME " ---+++###";
2451   /* True if we are within the marker in the config file.  */
2452   int in_marker = 0;
2453   gc_option_t *option;
2454   char *line = NULL;
2455   size_t line_len;
2456   ssize_t length;
2457   int res;
2458   int fd;
2459   FILE *src_file = NULL;
2460   FILE *dest_file = NULL;
2461   char *src_filename;
2462   char *dest_filename;
2463   char *orig_filename;
2464   char *arg;
2465   char *cur_arg = NULL;
2466
2467   option = find_option (component,
2468                         gc_backend[backend].option_name, GC_BACKEND_ANY);
2469   assert (option);
2470   assert (option->active);
2471   assert (gc_arg_type[option->arg_type].fallback != GC_ARG_TYPE_NONE);
2472
2473   /* FIXME.  Throughout the function, do better error reporting.  */
2474   /* Note that get_config_filename() calls percent_deescape(), so we
2475      call this before processing the arguments.  */
2476   dest_filename = xstrdup (get_config_filename (component, backend));
2477   src_filename = xasprintf ("%s.%s.%i.new",
2478                             dest_filename, GPGCONF_NAME, (int)getpid ());
2479   orig_filename = xasprintf ("%s.%s.%i.bak",
2480                              dest_filename, GPGCONF_NAME, (int)getpid ());
2481
2482   arg = option->new_value;
2483   if (arg && arg[0] == '\0')
2484     arg = NULL;
2485   else if (arg)
2486     {
2487       char *end;
2488
2489       arg++;
2490       end = strchr (arg, ',');
2491       if (end)
2492         *end = '\0';
2493
2494       cur_arg = percent_deescape (arg);
2495       if (end)
2496         {
2497           *end = ',';
2498           arg = end + 1;
2499         }
2500       else
2501         arg = NULL;
2502     }
2503
2504 #ifdef HAVE_W32_SYSTEM
2505   res = copy_file (dest_filename, orig_filename);
2506 #else
2507   res = link (dest_filename, orig_filename);
2508 #endif
2509   if (res < 0 && errno != ENOENT)
2510     return -1;
2511   if (res < 0)
2512     {
2513       xfree (orig_filename);
2514       orig_filename = NULL;
2515     }
2516
2517   /* We now initialize the return strings, so the caller can do the
2518      cleanup for us.  */
2519   *src_filenamep = src_filename;
2520   *dest_filenamep = dest_filename;
2521   *orig_filenamep = orig_filename;
2522
2523   /* Use open() so that we can use O_EXCL.  */
2524   fd = open (src_filename, O_CREAT | O_EXCL | O_WRONLY, 0644);
2525   if (fd < 0)
2526     return -1;
2527   src_file = fdopen (fd, "w");
2528   res = errno;
2529   if (!src_file)
2530     {
2531       gpg_err_set_errno (res);
2532       return -1;
2533     }
2534
2535   /* Only if ORIG_FILENAME is not NULL did the configuration file
2536      exist already.  In this case, we will copy its content into the
2537      new configuration file, changing it to our liking in the
2538      process.  */
2539   if (orig_filename)
2540     {
2541       dest_file = fopen (dest_filename, "r");
2542       if (!dest_file)
2543         goto change_file_one_err;
2544
2545       while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
2546         {
2547           int disable = 0;
2548           char *start;
2549
2550           if (!strncmp (marker, line, sizeof (marker) - 1))
2551             {
2552               if (!in_marker)
2553                 in_marker = 1;
2554               else
2555                 break;
2556             }
2557
2558           start = line;
2559           while (*start == ' ' || *start == '\t')
2560             start++;
2561           if (*start && *start != '\r' && *start != '\n' && *start != '#')
2562             {
2563               char *end;
2564               char *endp;
2565               char saved_end;
2566
2567               endp = start;
2568               end = endp;
2569
2570               /* Search for the end of the line.  */
2571               while (*endp && *endp != '#' && *endp != '\r' && *endp != '\n')
2572                 {
2573                   endp++;
2574                   if (*endp && *endp != ' ' && *endp != '\t'
2575                       && *endp != '\r' && *endp != '\n' && *endp != '#')
2576                     end = endp + 1;
2577                 }
2578               saved_end = *end;
2579               *end = '\0';
2580
2581               if ((option->new_flags & GC_OPT_FLAG_DEFAULT)
2582                   || !cur_arg || strcmp (start, cur_arg))
2583                 disable = 1;
2584               else
2585                 {
2586                   /* Find next argument.  */
2587                   if (arg)
2588                     {
2589                       char *arg_end;
2590
2591                       arg++;
2592                       arg_end = strchr (arg, ',');
2593                       if (arg_end)
2594                         *arg_end = '\0';
2595
2596                       cur_arg = percent_deescape (arg);
2597                       if (arg_end)
2598                         {
2599                           *arg_end = ',';
2600                           arg = arg_end + 1;
2601                         }
2602                       else
2603                         arg = NULL;
2604                     }
2605                   else
2606                     cur_arg = NULL;
2607                 }
2608
2609               *end = saved_end;
2610             }
2611
2612           if (disable)
2613             {
2614               if (!in_marker)
2615                 {
2616                   fprintf (src_file,
2617                            "# %s disabled this option here at %s\n",
2618                            GPGCONF_DISP_NAME, asctimestamp (gnupg_get_time ()));
2619                   if (ferror (src_file))
2620                     goto change_file_one_err;
2621                   fprintf (src_file, "# %s", line);
2622                   if (ferror (src_file))
2623                     goto change_file_one_err;
2624                 }
2625             }
2626           else
2627             {
2628               fprintf (src_file, "%s", line);
2629               if (ferror (src_file))
2630                 goto change_file_one_err;
2631             }
2632         }
2633       if (length < 0 || ferror (dest_file))
2634         goto change_file_one_err;
2635     }
2636
2637   if (!in_marker)
2638     {
2639       /* There was no marker.  This is the first time we edit the
2640          file.  We add our own marker at the end of the file and
2641          proceed.  Note that we first write a newline, this guards us
2642          against files which lack the newline at the end of the last
2643          line, while it doesn't hurt us in all other cases.  */
2644       fprintf (src_file, "\n%s\n", marker);
2645       if (ferror (src_file))
2646         goto change_file_one_err;
2647     }
2648
2649   /* At this point, we have copied everything up to the end marker
2650      into the new file, except for the arguments we are going to add.
2651      Now, dump the new arguments and write the end marker, possibly
2652      followed by the rest of the original file.  */
2653   while (cur_arg)
2654     {
2655       fprintf (src_file, "%s\n", cur_arg);
2656
2657       /* Find next argument.  */
2658       if (arg)
2659         {
2660           char *end;
2661
2662           arg++;
2663           end = strchr (arg, ',');
2664           if (end)
2665             *end = '\0';
2666
2667           cur_arg = percent_deescape (arg);
2668           if (end)
2669             {
2670               *end = ',';
2671               arg = end + 1;
2672             }
2673           else
2674             arg = NULL;
2675         }
2676       else
2677         cur_arg = NULL;
2678     }
2679
2680   fprintf (src_file, "%s %s\n", marker, asctimestamp (gnupg_get_time ()));
2681   if (ferror (src_file))
2682     goto change_file_one_err;
2683
2684   if (!in_marker)
2685     {
2686       fprintf (src_file, "# %s edited this configuration file.\n",
2687                GPGCONF_DISP_NAME);
2688       if (ferror (src_file))
2689         goto change_file_one_err;
2690       fprintf (src_file, "# It will disable options before this marked "
2691                "block, but it will\n");
2692       if (ferror (src_file))
2693         goto change_file_one_err;
2694       fprintf (src_file, "# never change anything below these lines.\n");
2695       if (ferror (src_file))
2696         goto change_file_one_err;
2697     }
2698   if (dest_file)
2699     {
2700       while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
2701         {
2702           fprintf (src_file, "%s", line);
2703           if (ferror (src_file))
2704             goto change_file_one_err;
2705         }
2706       if (length < 0 || ferror (dest_file))
2707         goto change_file_one_err;
2708     }
2709   xfree (line);
2710   line = NULL;
2711
2712   res = fclose (src_file);
2713   if (res)
2714     {
2715       res = errno;
2716       close (fd);
2717       if (dest_file)
2718         fclose (dest_file);
2719       gpg_err_set_errno (res);
2720       return -1;
2721     }
2722   close (fd);
2723   if (dest_file)
2724     {
2725       res = fclose (dest_file);
2726       if (res)
2727         return -1;
2728     }
2729   return 0;
2730
2731  change_file_one_err:
2732   xfree (line);
2733   res = errno;
2734   if (src_file)
2735     {
2736       fclose (src_file);
2737       close (fd);
2738     }
2739   if (dest_file)
2740     fclose (dest_file);
2741   gpg_err_set_errno (res);
2742   return -1;
2743 }
2744
2745
2746 /* Create and verify the new configuration file for the specified
2747    backend and component.  Returns 0 on success and -1 on error.  */
2748 static int
2749 change_options_program (gc_component_t component, gc_backend_t backend,
2750                         char **src_filenamep, char **dest_filenamep,
2751                         char **orig_filenamep)
2752 {
2753   static const char marker[] = "###+++--- " GPGCONF_DISP_NAME " ---+++###";
2754   /* True if we are within the marker in the config file.  */
2755   int in_marker = 0;
2756   gc_option_t *option;
2757   char *line = NULL;
2758   size_t line_len;
2759   ssize_t length;
2760   int res;
2761   int fd;
2762   FILE *src_file = NULL;
2763   FILE *dest_file = NULL;
2764   char *src_filename;
2765   char *dest_filename;
2766   char *orig_filename;
2767   /* Special hack for gpg, see below.  */
2768   int utf8strings_seen = 0;
2769
2770   /* FIXME.  Throughout the function, do better error reporting.  */
2771   dest_filename = xstrdup (get_config_filename (component, backend));
2772   src_filename = xasprintf ("%s.%s.%i.new",
2773                             dest_filename, GPGCONF_NAME, (int)getpid ());
2774   orig_filename = xasprintf ("%s.%s.%i.bak",
2775                              dest_filename, GPGCONF_NAME, (int)getpid ());
2776
2777 #ifdef HAVE_W32_SYSTEM
2778   res = copy_file (dest_filename, orig_filename);
2779 #else
2780   res = link (dest_filename, orig_filename);
2781 #endif
2782   if (res < 0 && errno != ENOENT)
2783     return -1;
2784   if (res < 0)
2785     {
2786       xfree (orig_filename);
2787       orig_filename = NULL;
2788     }
2789
2790   /* We now initialize the return strings, so the caller can do the
2791      cleanup for us.  */
2792   *src_filenamep = src_filename;
2793   *dest_filenamep = dest_filename;
2794   *orig_filenamep = orig_filename;
2795
2796   /* Use open() so that we can use O_EXCL.  */
2797   fd = open (src_filename, O_CREAT | O_EXCL | O_WRONLY, 0644);
2798   if (fd < 0)
2799     return -1;
2800   src_file = fdopen (fd, "w");
2801   res = errno;
2802   if (!src_file)
2803     {
2804       gpg_err_set_errno (res);
2805       return -1;
2806     }
2807
2808   /* Only if ORIG_FILENAME is not NULL did the configuration file
2809      exist already.  In this case, we will copy its content into the
2810      new configuration file, changing it to our liking in the
2811      process.  */
2812   if (orig_filename)
2813     {
2814       dest_file = fopen (dest_filename, "r");
2815       if (!dest_file)
2816         goto change_one_err;
2817
2818       while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
2819         {
2820           int disable = 0;
2821           char *start;
2822
2823           if (!strncmp (marker, line, sizeof (marker) - 1))
2824             {
2825               if (!in_marker)
2826                 in_marker = 1;
2827               else
2828                 break;
2829             }
2830           else if (backend == GC_BACKEND_GPG && in_marker
2831                    && ! strcmp ("utf8-strings\n", line))
2832             {
2833               /* Strip duplicated entries.  */
2834               if (utf8strings_seen)
2835                 disable = 1;
2836               else
2837                 utf8strings_seen = 1;
2838             }
2839
2840           start = line;
2841           while (*start == ' ' || *start == '\t')
2842             start++;
2843           if (*start && *start != '\r' && *start != '\n' && *start != '#')
2844             {
2845               char *end;
2846               char saved_end;
2847
2848               end = start;
2849               while (*end && *end != ' ' && *end != '\t'
2850                      && *end != '\r' && *end != '\n' && *end != '#')
2851                 end++;
2852               saved_end = *end;
2853               *end = '\0';
2854
2855               option = find_option (component, start, backend);
2856               *end = saved_end;
2857               if (option && ((option->new_flags & GC_OPT_FLAG_DEFAULT)
2858                              || option->new_value))
2859                 disable = 1;
2860             }
2861           if (disable)
2862             {
2863               if (!in_marker)
2864                 {
2865                   fprintf (src_file,
2866                            "# %s disabled this option here at %s\n",
2867                            GPGCONF_DISP_NAME, asctimestamp (gnupg_get_time ()));
2868                   if (ferror (src_file))
2869                     goto change_one_err;
2870                   fprintf (src_file, "# %s", line);
2871                   if (ferror (src_file))
2872                     goto change_one_err;
2873                 }
2874             }
2875           else
2876             {
2877               fprintf (src_file, "%s", line);
2878               if (ferror (src_file))
2879                 goto change_one_err;
2880             }
2881         }
2882       if (length < 0 || ferror (dest_file))
2883         goto change_one_err;
2884     }
2885
2886   if (!in_marker)
2887     {
2888       /* There was no marker.  This is the first time we edit the
2889          file.  We add our own marker at the end of the file and
2890          proceed.  Note that we first write a newline, this guards us
2891          against files which lack the newline at the end of the last
2892          line, while it doesn't hurt us in all other cases.  */
2893       fprintf (src_file, "\n%s\n", marker);
2894       if (ferror (src_file))
2895         goto change_one_err;
2896     }
2897   /* At this point, we have copied everything up to the end marker
2898      into the new file, except for the options we are going to change.
2899      Now, dump the changed options (except for those we are going to
2900      revert to their default), and write the end marker, possibly
2901      followed by the rest of the original file.  */
2902
2903   /* We have to turn on UTF8 strings for GnuPG.  */
2904   if (backend == GC_BACKEND_GPG && ! utf8strings_seen)
2905     fprintf (src_file, "utf8-strings\n");
2906
2907   option = gc_component[component].options;
2908   while (option->name)
2909     {
2910       if (!(option->flags & GC_OPT_FLAG_GROUP)
2911           && option->backend == backend
2912           && option->new_value)
2913         {
2914           char *arg = option->new_value;
2915
2916           do
2917             {
2918               if (*arg == '\0' || *arg == ',')
2919                 {
2920                   fprintf (src_file, "%s\n", option->name);
2921                   if (ferror (src_file))
2922                     goto change_one_err;
2923                 }
2924               else if (gc_arg_type[option->arg_type].fallback
2925                        == GC_ARG_TYPE_NONE)
2926                 {
2927                   assert (*arg == '1');
2928                   fprintf (src_file, "%s\n", option->name);
2929                   if (ferror (src_file))
2930                     goto change_one_err;
2931
2932                   arg++;
2933                 }
2934               else if (gc_arg_type[option->arg_type].fallback
2935                        == GC_ARG_TYPE_STRING)
2936                 {
2937                   char *end;
2938
2939                   assert (*arg == '"');
2940                   arg++;
2941
2942                   end = strchr (arg, ',');
2943                   if (end)
2944                     *end = '\0';
2945
2946                   fprintf (src_file, "%s %s\n", option->name,
2947                            percent_deescape (arg));
2948                   if (ferror (src_file))
2949                     goto change_one_err;
2950
2951                   if (end)
2952                     *end = ',';
2953                   arg = end;
2954                 }
2955               else
2956                 {
2957                   char *end;
2958
2959                   end = strchr (arg, ',');
2960                   if (end)
2961                     *end = '\0';
2962
2963                   fprintf (src_file, "%s %s\n", option->name, arg);
2964                   if (ferror (src_file))
2965                     goto change_one_err;
2966
2967                   if (end)
2968                     *end = ',';
2969                   arg = end;
2970                 }
2971
2972               assert (arg == NULL || *arg == '\0' || *arg == ',');
2973               if (arg && *arg == ',')
2974                 arg++;
2975             }
2976           while (arg && *arg);
2977         }
2978       option++;
2979     }
2980
2981   fprintf (src_file, "%s %s\n", marker, asctimestamp (gnupg_get_time ()));
2982   if (ferror (src_file))
2983     goto change_one_err;
2984
2985   if (!in_marker)
2986     {
2987       fprintf (src_file, "# %s edited this configuration file.\n",
2988                GPGCONF_DISP_NAME);
2989       if (ferror (src_file))
2990         goto change_one_err;
2991       fprintf (src_file, "# It will disable options before this marked "
2992                "block, but it will\n");
2993       if (ferror (src_file))
2994         goto change_one_err;
2995       fprintf (src_file, "# never change anything below these lines.\n");
2996       if (ferror (src_file))
2997         goto change_one_err;
2998     }
2999   if (dest_file)
3000     {
3001       while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
3002         {
3003           fprintf (src_file, "%s", line);
3004           if (ferror (src_file))
3005             goto change_one_err;
3006         }
3007       if (length < 0 || ferror (dest_file))
3008         goto change_one_err;
3009     }
3010   xfree (line);
3011   line = NULL;
3012
3013   res = fclose (src_file);
3014   if (res)
3015     {
3016       res = errno;
3017       close (fd);
3018       if (dest_file)
3019         fclose (dest_file);
3020       gpg_err_set_errno (res);
3021       return -1;
3022     }
3023   close (fd);
3024   if (dest_file)
3025     {
3026       res = fclose (dest_file);
3027       if (res)
3028         return -1;
3029     }
3030   return 0;
3031
3032  change_one_err:
3033   xfree (line);
3034   res = errno;
3035   if (src_file)
3036     {
3037       fclose (src_file);
3038       close (fd);
3039     }
3040   if (dest_file)
3041     fclose (dest_file);
3042   gpg_err_set_errno (res);
3043   return -1;
3044 }
3045
3046
3047 /* Common code for gc_component_change_options and
3048    gc_process_gpgconf_conf.  */
3049 static void
3050 change_one_value (gc_option_t *option, int *runtime,
3051                   unsigned long flags, char *new_value)
3052 {
3053   unsigned long new_value_nr = 0;
3054
3055   option_check_validity (option, flags, new_value, &new_value_nr);
3056
3057   if (option->flags & GC_OPT_FLAG_RUNTIME)
3058     runtime[option->backend] = 1;
3059
3060   option->new_flags = flags;
3061   if (!(flags & GC_OPT_FLAG_DEFAULT))
3062     {
3063       if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE
3064           && (option->flags & GC_OPT_FLAG_LIST))
3065         {
3066           char *str;
3067
3068           /* We convert the number to a list of 1's for convenient
3069              list handling.  */
3070           assert (new_value_nr > 0);
3071           option->new_value = xmalloc ((2 * (new_value_nr - 1) + 1) + 1);
3072           str = option->new_value;
3073           *(str++) = '1';
3074           while (--new_value_nr > 0)
3075             {
3076               *(str++) = ',';
3077               *(str++) = '1';
3078             }
3079           *(str++) = '\0';
3080         }
3081       else
3082         option->new_value = xstrdup (new_value);
3083     }
3084 }
3085
3086
3087 /* Read the modifications from IN and apply them.  If IN is NULL the
3088    modifications are expected to already have been set to the global
3089    table. */
3090 void
3091 gc_component_change_options (int component, estream_t in, estream_t out)
3092 {
3093   int err = 0;
3094   int runtime[GC_BACKEND_NR];
3095   char *src_filename[GC_BACKEND_NR];
3096   char *dest_filename[GC_BACKEND_NR];
3097   char *orig_filename[GC_BACKEND_NR];
3098   gc_backend_t backend;
3099   gc_option_t *option;
3100   char *line = NULL;
3101   size_t line_len = 0;
3102   ssize_t length;
3103
3104   if (component == GC_COMPONENT_PINENTRY)
3105     return; /* Dummy component for now.  */
3106
3107   for (backend = 0; backend < GC_BACKEND_NR; backend++)
3108     {
3109       runtime[backend] = 0;
3110       src_filename[backend] = NULL;
3111       dest_filename[backend] = NULL;
3112       orig_filename[backend] = NULL;
3113     }
3114
3115   if (in)
3116     {
3117       /* Read options from the file IN.  */
3118       while ((length = es_read_line (in, &line, &line_len, NULL)) > 0)
3119         {
3120           char *linep;
3121           unsigned long flags = 0;
3122           char *new_value = "";
3123
3124           /* Strip newline and carriage return, if present.  */
3125           while (length > 0
3126                  && (line[length - 1] == '\n' || line[length - 1] == '\r'))
3127             line[--length] = '\0';
3128
3129           linep = strchr (line, ':');
3130           if (linep)
3131             *(linep++) = '\0';
3132
3133           /* Extract additional flags.  Default to none.  */
3134           if (linep)
3135             {
3136               char *end;
3137               char *tail;
3138
3139               end = strchr (linep, ':');
3140               if (end)
3141                 *(end++) = '\0';
3142
3143               gpg_err_set_errno (0);
3144               flags = strtoul (linep, &tail, 0);
3145               if (errno)
3146                 gc_error (1, errno, "malformed flags in option %s", line);
3147               if (!(*tail == '\0' || *tail == ':' || *tail == ' '))
3148                 gc_error (1, 0, "garbage after flags in option %s", line);
3149
3150               linep = end;
3151             }
3152
3153           /* Don't allow setting of the no change flag.  */
3154           flags &= ~GC_OPT_FLAG_NO_CHANGE;
3155
3156           /* Extract default value, if present.  Default to empty if not.  */
3157           if (linep)
3158             {
3159               char *end;
3160               end = strchr (linep, ':');
3161               if (end)
3162                 *(end++) = '\0';
3163               new_value = linep;
3164               linep = end;
3165             }
3166
3167           option = find_option (component, line, GC_BACKEND_ANY);
3168           if (!option)
3169             gc_error (1, 0, "unknown option %s", line);
3170
3171           if ((option->flags & GC_OPT_FLAG_NO_CHANGE))
3172             {
3173               gc_error (0, 0, "ignoring new value for option %s",
3174                         option->name);
3175               continue;
3176             }
3177
3178           change_one_value (option, runtime, flags, new_value);
3179         }
3180     }
3181
3182   /* Now that we have collected and locally verified the changes,
3183      write them out to new configuration files, verify them
3184      externally, and then commit them.  */
3185   option = gc_component[component].options;
3186   while (option && option->name)
3187     {
3188       /* Go on if we have already seen this backend, or if there is
3189          nothing to do.  */
3190       if (src_filename[option->backend]
3191           || !(option->new_flags || option->new_value))
3192         {
3193           option++;
3194           continue;
3195         }
3196
3197       if (gc_backend[option->backend].program)
3198         {
3199           err = change_options_program (component, option->backend,
3200                                         &src_filename[option->backend],
3201                                         &dest_filename[option->backend],
3202                                         &orig_filename[option->backend]);
3203           if (! err)
3204             {
3205               /* External verification.  */
3206               err = gc_component_check_options (component, out,
3207                                                 src_filename[option->backend]);
3208               if (err)
3209                 {
3210                   gc_error (0, 0,
3211                             _("External verification of component %s failed"),
3212                             gc_component[component].name);
3213                   gpg_err_set_errno (EINVAL);
3214                 }
3215             }
3216
3217         }
3218       else
3219         err = change_options_file (component, option->backend,
3220                                    &src_filename[option->backend],
3221                                    &dest_filename[option->backend],
3222                                    &orig_filename[option->backend]);
3223
3224       if (err)
3225         break;
3226
3227       option++;
3228     }
3229
3230   if (! err && ! opt.dry_run)
3231     {
3232       int i;
3233
3234       for (i = 0; i < GC_BACKEND_NR; i++)
3235         {
3236           if (src_filename[i])
3237             {
3238               /* FIXME: Make a verification here.  */
3239
3240               assert (dest_filename[i]);
3241
3242               if (orig_filename[i])
3243                 {
3244 #ifdef HAVE_W32_SYSTEM
3245                   /* There is no atomic update on W32.  */
3246                   err = unlink (dest_filename[i]);
3247 #endif /* HAVE_W32_SYSTEM */
3248                   if (!err)
3249                     err = rename (src_filename[i], dest_filename[i]);
3250                 }
3251               else
3252                 {
3253 #ifdef HAVE_W32_SYSTEM
3254                   /* We skip the unlink if we expect the file not to
3255                      be there.  */
3256                   err = rename (src_filename[i], dest_filename[i]);
3257 #else /* HAVE_W32_SYSTEM */
3258                   /* This is a bit safer than rename() because we
3259                      expect DEST_FILENAME not to be there.  If it
3260                      happens to be there, this will fail.  */
3261                   err = link (src_filename[i], dest_filename[i]);
3262                   if (!err)
3263                     err = unlink (src_filename[i]);
3264 #endif /* !HAVE_W32_SYSTEM */
3265                 }
3266               if (err)
3267                 break;
3268               src_filename[i] = NULL;
3269             }
3270         }
3271     }
3272
3273   if (err || opt.dry_run)
3274     {
3275       int i;
3276       int saved_errno = errno;
3277
3278       /* An error occured or a dry-run is requested.  */
3279       for (i = 0; i < GC_BACKEND_NR; i++)
3280         {
3281           if (src_filename[i])
3282             {
3283               /* The change was not yet committed.  */
3284               unlink (src_filename[i]);
3285               if (orig_filename[i])
3286                 unlink (orig_filename[i]);
3287             }
3288           else
3289             {
3290               /* The changes were already committed.  FIXME: This is a
3291                  tad dangerous, as we don't know if we don't overwrite
3292                  a version of the file that is even newer than the one
3293                  we just installed.  */
3294               if (orig_filename[i])
3295                 {
3296 #ifdef HAVE_W32_SYSTEM
3297                   /* There is no atomic update on W32.  */
3298                   unlink (dest_filename[i]);
3299 #endif /* HAVE_W32_SYSTEM */
3300                   rename (orig_filename[i], dest_filename[i]);
3301                 }
3302               else
3303                 unlink (dest_filename[i]);
3304             }
3305         }
3306       if (err)
3307         gc_error (1, saved_errno, "could not commit changes");
3308
3309       /* Fall-through for dry run.  */
3310       goto leave;
3311     }
3312
3313   /* If it all worked, notify the daemons of the changes.  */
3314   if (opt.runtime)
3315     for (backend = 0; backend < GC_BACKEND_NR; backend++)
3316       {
3317         if (runtime[backend] && gc_backend[backend].runtime_change)
3318           (*gc_backend[backend].runtime_change) (0);
3319       }
3320
3321   /* Move the per-process backup file into its place.  */
3322   for (backend = 0; backend < GC_BACKEND_NR; backend++)
3323     if (orig_filename[backend])
3324       {
3325         char *backup_filename;
3326
3327         assert (dest_filename[backend]);
3328
3329         backup_filename = xasprintf ("%s.%s.bak",
3330                                      dest_filename[backend], GPGCONF_NAME);
3331
3332 #ifdef HAVE_W32_SYSTEM
3333         /* There is no atomic update on W32.  */
3334         unlink (backup_filename);
3335 #endif /* HAVE_W32_SYSTEM */
3336         rename (orig_filename[backend], backup_filename);
3337       }
3338
3339  leave:
3340   xfree (line);
3341 }
3342
3343
3344 /* Check whether USER matches the current user of one of its group.
3345    This function may change USER.  Returns true is there is a
3346    match.  */
3347 static int
3348 key_matches_user_or_group (char *user)
3349 {
3350   char *group;
3351
3352   if (*user == '*' && user[1] == 0)
3353     return 1; /* A single asterisk matches all users.  */
3354
3355   group = strchr (user, ':');
3356   if (group)
3357     *group++ = 0;
3358
3359 #ifdef HAVE_W32_SYSTEM
3360   /* Under Windows we don't support groups. */
3361   if (group && *group)
3362     gc_error (0, 0, _("Note that group specifications are ignored\n"));
3363 #ifndef HAVE_W32CE_SYSTEM
3364   if (*user)
3365     {
3366       static char *my_name;
3367
3368       if (!my_name)
3369         {
3370           char tmp[1];
3371           DWORD size = 1;
3372
3373           GetUserNameA (tmp, &size);
3374           my_name = xmalloc (size);
3375           if (!GetUserNameA (my_name, &size))
3376             gc_error (1,0, "error getting current user name: %s",
3377                       w32_strerror (-1));
3378         }
3379
3380       if (!strcmp (user, my_name))
3381         return 1; /* Found.  */
3382     }
3383 #endif /*HAVE_W32CE_SYSTEM*/
3384 #else /*!HAVE_W32_SYSTEM*/
3385   /* First check whether the user matches.  */
3386   if (*user)
3387     {
3388       static char *my_name;
3389
3390       if (!my_name)
3391         {
3392           struct passwd *pw = getpwuid ( getuid () );
3393           if (!pw)
3394             gc_error (1, errno, "getpwuid failed for current user");
3395           my_name = xstrdup (pw->pw_name);
3396         }
3397       if (!strcmp (user, my_name))
3398         return 1; /* Found.  */
3399     }
3400
3401   /* If that failed, check whether a group matches.  */
3402   if (group && *group)
3403     {
3404       static char *my_group;
3405       static char **my_supgroups;
3406       int n;
3407
3408       if (!my_group)
3409         {
3410           struct group *gr = getgrgid ( getgid () );
3411           if (!gr)
3412             gc_error (1, errno, "getgrgid failed for current user");
3413           my_group = xstrdup (gr->gr_name);
3414         }
3415       if (!strcmp (group, my_group))
3416         return 1; /* Found.  */
3417
3418       if (!my_supgroups)
3419         {
3420           int ngids;
3421           gid_t *gids;
3422
3423           ngids = getgroups (0, NULL);
3424           gids  = xcalloc (ngids+1, sizeof *gids);
3425           ngids = getgroups (ngids, gids);
3426           if (ngids < 0)
3427             gc_error (1, errno, "getgroups failed for current user");
3428           my_supgroups = xcalloc (ngids+1, sizeof *my_supgroups);
3429           for (n=0; n < ngids; n++)
3430             {
3431               struct group *gr = getgrgid ( gids[n] );
3432               if (!gr)
3433                 gc_error (1, errno, "getgrgid failed for supplementary group");
3434               my_supgroups[n] = xstrdup (gr->gr_name);
3435             }
3436           xfree (gids);
3437         }
3438
3439       for (n=0; my_supgroups[n]; n++)
3440         if (!strcmp (group, my_supgroups[n]))
3441           return 1; /* Found.  */
3442     }
3443 #endif /*!HAVE_W32_SYSTEM*/
3444   return 0; /* No match.  */
3445 }
3446
3447
3448
3449 /* Read and process the global configuration file for gpgconf.  This
3450    optional file is used to update our internal tables at runtime and
3451    may also be used to set new default values.  If FNAME is NULL the
3452    default name will be used.  With UPDATE set to true the internal
3453    tables are actually updated; if not set, only a syntax check is
3454    done.  If DEFAULTS is true the global options are written to the
3455    configuration files.  If LISTFP is set, no changes are done but the
3456    configuration file is printed to LISTFP in a colon separated format.
3457
3458    Returns 0 on success or if the config file is not present; -1 is
3459    returned on error. */
3460 int
3461 gc_process_gpgconf_conf (const char *fname_arg, int update, int defaults,
3462                          estream_t listfp)
3463 {
3464   int result = 0;
3465   char *line = NULL;
3466   size_t line_len = 0;
3467   ssize_t length;
3468   FILE *config;
3469   int lineno = 0;
3470   int in_rule = 0;
3471   int got_match = 0;
3472   int runtime[GC_BACKEND_NR];
3473   int backend_id, component_id;
3474   char *fname;
3475
3476   if (fname_arg)
3477     fname = xstrdup (fname_arg);
3478   else
3479     fname = make_filename (gnupg_sysconfdir (), GPGCONF_NAME EXTSEP_S "conf",
3480                            NULL);
3481
3482   for (backend_id = 0; backend_id < GC_BACKEND_NR; backend_id++)
3483     runtime[backend_id] = 0;
3484
3485   config = fopen (fname, "r");
3486   if (!config)
3487     {
3488       /* Do not print an error if the file is not available, except
3489          when running in syntax check mode.  */
3490       if (errno != ENOENT || !update)
3491         {
3492           gc_error (0, errno, "can not open global config file '%s'", fname);
3493           result = -1;
3494         }
3495       xfree (fname);
3496       return result;
3497     }
3498
3499   while ((length = read_line (config, &line, &line_len, NULL)) > 0)
3500     {
3501       char *key, *component, *option, *flags, *value;
3502       char *empty;
3503       gc_option_t *option_info = NULL;
3504       char *p;
3505       int is_continuation;
3506
3507       lineno++;
3508       key = line;
3509       while (*key == ' ' || *key == '\t')
3510         key++;
3511       if (!*key || *key == '#' || *key == '\r' || *key == '\n')
3512         continue;
3513
3514       is_continuation = (key != line);
3515
3516       /* Parse the key field.  */
3517       if (!is_continuation && got_match)
3518         break;  /* Finish after the first match.  */
3519       else if (!is_continuation)
3520         {
3521           in_rule = 0;
3522           for (p=key+1; *p && !strchr (" \t\r\n", *p); p++)
3523             ;
3524           if (!*p)
3525             {
3526               gc_error (0, 0, "missing rule at '%s', line %d", fname, lineno);
3527               result = -1;
3528               continue;
3529             }
3530           *p++ = 0;
3531           component = p;
3532         }
3533       else if (!in_rule)
3534         {
3535           gc_error (0, 0, "continuation but no rule at '%s', line %d",
3536                     fname, lineno);
3537           result = -1;
3538           continue;
3539         }
3540       else
3541         {
3542           component = key;
3543           key = NULL;
3544         }
3545
3546       in_rule = 1;
3547
3548       /* Parse the component.  */
3549       while (*component == ' ' || *component == '\t')
3550         component++;
3551       for (p=component; *p && !strchr (" \t\r\n", *p); p++)
3552         ;
3553       if (p == component)
3554         {
3555           gc_error (0, 0, "missing component at '%s', line %d",
3556                     fname, lineno);
3557           result = -1;
3558           continue;
3559         }
3560       empty = p;
3561       *p++ = 0;
3562       option = p;
3563       component_id = gc_component_find (component);
3564       if (component_id < 0)
3565         {
3566           gc_error (0, 0, "unknown component at '%s', line %d",
3567                     fname, lineno);
3568           result = -1;
3569         }
3570
3571       /* Parse the option name.  */
3572       while (*option == ' ' || *option == '\t')
3573         option++;
3574       for (p=option; *p && !strchr (" \t\r\n", *p); p++)
3575         ;
3576       if (p == option)
3577         {
3578           gc_error (0, 0, "missing option at '%s', line %d",
3579                     fname, lineno);
3580           result = -1;
3581           continue;
3582         }
3583       *p++ = 0;
3584       flags = p;
3585       if ( component_id != -1)
3586         {
3587           option_info = find_option (component_id, option, GC_BACKEND_ANY);
3588           if (!option_info)
3589             {
3590               gc_error (0, 0, "unknown option at '%s', line %d",
3591                         fname, lineno);
3592               result = -1;
3593             }
3594         }
3595
3596
3597       /* Parse the optional flags.  */
3598       while (*flags == ' ' || *flags == '\t')
3599         flags++;
3600       if (*flags == '[')
3601         {
3602           flags++;
3603           p = strchr (flags, ']');
3604           if (!p)
3605             {
3606               gc_error (0, 0, "syntax error in rule at '%s', line %d",
3607                         fname, lineno);
3608               result = -1;
3609               continue;
3610             }
3611           *p++ = 0;
3612           value = p;
3613         }
3614       else  /* No flags given.  */
3615         {
3616           value = flags;
3617           flags = NULL;
3618         }
3619
3620       /* Parse the optional value.  */
3621       while (*value == ' ' || *value == '\t')
3622        value++;
3623       for (p=value; *p && !strchr ("\r\n", *p); p++)
3624         ;
3625       if (p == value)
3626         value = empty; /* No value given; let it point to an empty string.  */
3627       else
3628         {
3629           /* Strip trailing white space.  */
3630           *p = 0;
3631           for (p--; p > value && (*p == ' ' || *p == '\t'); p--)
3632             *p = 0;
3633         }
3634
3635       /* Check flag combinations.  */
3636       if (!flags)
3637         ;
3638       else if (!strcmp (flags, "default"))
3639         {
3640           if (*value)
3641             {
3642               gc_error (0, 0, "flag \"default\" may not be combined "
3643                         "with a value at '%s', line %d",
3644                         fname, lineno);
3645               result = -1;
3646             }
3647         }
3648       else if (!strcmp (flags, "change"))
3649         ;
3650       else if (!strcmp (flags, "no-change"))
3651         ;
3652       else
3653         {
3654           gc_error (0, 0, "unknown flag at '%s', line %d",
3655                     fname, lineno);
3656           result = -1;
3657         }
3658
3659       /* In list mode we print out all records.  */
3660       if (listfp && !result)
3661         {
3662           /* If this is a new ruleset, print a key record.  */
3663           if (!is_continuation)
3664             {
3665               char *group = strchr (key, ':');
3666               if (group)
3667                 {
3668                   *group++ = 0;
3669                   if ((p = strchr (group, ':')))
3670                     *p = 0; /* We better strip any extra stuff. */
3671                 }
3672
3673               es_fprintf (listfp, "k:%s:", gc_percent_escape (key));
3674               es_fprintf (listfp, "%s\n", group? gc_percent_escape (group):"");
3675             }
3676
3677           /* All other lines are rule records.  */
3678           es_fprintf (listfp, "r:::%s:%s:%s:",
3679                       gc_component[component_id].name,
3680                       option_info->name? option_info->name : "",
3681                       flags? flags : "");
3682           if (value != empty)
3683             es_fprintf (listfp, "\"%s", gc_percent_escape (value));
3684
3685           es_putc ('\n', listfp);
3686         }
3687
3688       /* Check whether the key matches but do this only if we are not
3689          running in syntax check mode. */
3690       if ( update
3691            && !result && !listfp
3692            && (got_match || (key && key_matches_user_or_group (key))) )
3693         {
3694           int newflags = 0;
3695
3696           got_match = 1;
3697
3698           /* Apply the flags from gpgconf.conf.  */
3699           if (!flags)
3700             ;
3701           else if (!strcmp (flags, "default"))
3702             newflags |= GC_OPT_FLAG_DEFAULT;
3703           else if (!strcmp (flags, "no-change"))
3704             option_info->flags |= GC_OPT_FLAG_NO_CHANGE;
3705           else if (!strcmp (flags, "change"))
3706             option_info->flags &= ~GC_OPT_FLAG_NO_CHANGE;
3707
3708           if (defaults)
3709             {
3710               /* Here we explicitly allow to update the value again.  */
3711               if (newflags)
3712                 {
3713                   option_info->new_flags = 0;
3714                 }
3715               if (*value)
3716                 {
3717                   xfree (option_info->new_value);
3718                   option_info->new_value = NULL;
3719                 }
3720               change_one_value (option_info, runtime, newflags, value);
3721             }
3722         }
3723     }
3724
3725   if (length < 0 || ferror (config))
3726     {
3727       gc_error (0, errno, "error reading from '%s'", fname);
3728       result = -1;
3729     }
3730   if (fclose (config))
3731     gc_error (0, errno, "error closing '%s'", fname);
3732
3733   xfree (line);
3734
3735   /* If it all worked, process the options. */
3736   if (!result && update && defaults && !listfp)
3737     {
3738       /* We need to switch off the runtime update, so that we can do
3739          it later all at once. */
3740       int save_opt_runtime = opt.runtime;
3741       opt.runtime = 0;
3742
3743       for (component_id = 0; component_id < GC_COMPONENT_NR; component_id++)
3744         {
3745           gc_component_change_options (component_id, NULL, NULL);
3746         }
3747       opt.runtime = save_opt_runtime;
3748
3749       if (opt.runtime)
3750         {
3751           for (backend_id = 0; backend_id < GC_BACKEND_NR; backend_id++)
3752             if (runtime[backend_id] && gc_backend[backend_id].runtime_change)
3753               (*gc_backend[backend_id].runtime_change) (0);
3754         }
3755     }
3756
3757   xfree (fname);
3758   return result;
3759 }