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