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