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