chiark / gitweb /
Import gnupg2_2.1.18.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
1106 /* Initialization and finalization.  */
1107
1108 static void
1109 gc_option_free (gc_option_t *o)
1110 {
1111   if (o == NULL || o->name == NULL)
1112     return;
1113
1114   xfree (o->value);
1115   gc_option_free (o + 1);
1116 }
1117
1118 static void
1119 gc_components_free (void)
1120 {
1121   int i;
1122   for (i = 0; i < DIM (gc_component); i++)
1123     gc_option_free (gc_component[i].options);
1124 }
1125
1126 void
1127 gc_components_init (void)
1128 {
1129   atexit (gc_components_free);
1130 }
1131
1132 \f
1133
1134 /* Engine specific support.  */
1135 static void
1136 gpg_agent_runtime_change (int killflag)
1137 {
1138   gpg_error_t err = 0;
1139   const char *pgmname;
1140   const char *argv[5];
1141   pid_t pid = (pid_t)(-1);
1142   char *abs_homedir = NULL;
1143   int i = 0;
1144
1145   pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
1146   if (!gnupg_default_homedir_p ())
1147     {
1148       abs_homedir = make_absfilename_try (gnupg_homedir (), NULL);
1149       if (!abs_homedir)
1150         err = gpg_error_from_syserror ();
1151
1152       argv[i++] = "--homedir";
1153       argv[i++] = abs_homedir;
1154     }
1155   argv[i++] = "--no-autostart";
1156   argv[i++] = killflag? "KILLAGENT" : "RELOADAGENT";
1157   argv[i++] = NULL;
1158
1159   if (!err)
1160     err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
1161   if (!err)
1162     err = gnupg_wait_process (pgmname, pid, 1, NULL);
1163   if (err)
1164     gc_error (0, 0, "error running '%s %s': %s",
1165               pgmname, argv[1], gpg_strerror (err));
1166   gnupg_release_process (pid);
1167   xfree (abs_homedir);
1168 }
1169
1170
1171 static void
1172 scdaemon_runtime_change (int killflag)
1173 {
1174   gpg_error_t err = 0;
1175   const char *pgmname;
1176   const char *argv[9];
1177   pid_t pid = (pid_t)(-1);
1178   char *abs_homedir = NULL;
1179   int i = 0;
1180
1181   (void)killflag;  /* For scdaemon kill and reload are synonyms.  */
1182
1183   /* We use "GETINFO app_running" to see whether the agent is already
1184      running and kill it only in this case.  This avoids an explicit
1185      starting of the agent in case it is not yet running.  There is
1186      obviously a race condition but that should not harm too much.  */
1187
1188   pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
1189   if (!gnupg_default_homedir_p ())
1190     {
1191       abs_homedir = make_absfilename_try (gnupg_homedir (), NULL);
1192       if (!abs_homedir)
1193         err = gpg_error_from_syserror ();
1194
1195       argv[i++] = "--homedir";
1196       argv[i++] = abs_homedir;
1197     }
1198   argv[i++] = "-s";
1199   argv[i++] = "--no-autostart";
1200   argv[i++] = "GETINFO scd_running";
1201   argv[i++] = "/if ${! $?}";
1202   argv[i++] = "scd killscd";
1203   argv[i++] = "/end";
1204   argv[i++] = NULL;
1205
1206   if (!err)
1207     err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
1208   if (!err)
1209     err = gnupg_wait_process (pgmname, pid, 1, NULL);
1210   if (err)
1211     gc_error (0, 0, "error running '%s %s': %s",
1212               pgmname, argv[4], gpg_strerror (err));
1213   gnupg_release_process (pid);
1214   xfree (abs_homedir);
1215 }
1216
1217
1218 static void
1219 dirmngr_runtime_change (int killflag)
1220 {
1221   gpg_error_t err = 0;
1222   const char *pgmname;
1223   const char *argv[6];
1224   pid_t pid = (pid_t)(-1);
1225   char *abs_homedir = NULL;
1226
1227   pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
1228   argv[0] = "--no-autostart";
1229   argv[1] = "--dirmngr";
1230   argv[2] = killflag? "KILLDIRMNGR" : "RELOADDIRMNGR";
1231   if (gnupg_default_homedir_p ())
1232     argv[3] = NULL;
1233   else
1234     {
1235       abs_homedir = make_absfilename_try (gnupg_homedir (), NULL);
1236       if (!abs_homedir)
1237         err = gpg_error_from_syserror ();
1238
1239       argv[3] = "--homedir";
1240       argv[4] = abs_homedir;
1241       argv[5] = NULL;
1242     }
1243
1244   if (!err)
1245     err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
1246   if (!err)
1247     err = gnupg_wait_process (pgmname, pid, 1, NULL);
1248   if (err)
1249     gc_error (0, 0, "error running '%s %s': %s",
1250               pgmname, argv[2], gpg_strerror (err));
1251   gnupg_release_process (pid);
1252   xfree (abs_homedir);
1253 }
1254
1255
1256 /* Launch the gpg-agent or the dirmngr if not already running.  */
1257 gpg_error_t
1258 gc_component_launch (int component)
1259 {
1260   gpg_error_t err;
1261   const char *pgmname;
1262   const char *argv[3];
1263   int i;
1264   pid_t pid;
1265
1266   if (component < 0)
1267     {
1268       err = gc_component_launch (GC_COMPONENT_GPG_AGENT);
1269       if (!err)
1270         err = gc_component_launch (GC_COMPONENT_DIRMNGR);
1271       return err;
1272     }
1273
1274   if (!(component == GC_COMPONENT_GPG_AGENT
1275         || component == GC_COMPONENT_DIRMNGR))
1276     {
1277       es_fputs (_("Component not suitable for launching"), es_stderr);
1278       es_putc ('\n', es_stderr);
1279       exit (1);
1280     }
1281
1282   pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
1283   i = 0;
1284   if (component == GC_COMPONENT_DIRMNGR)
1285     argv[i++] = "--dirmngr";
1286   argv[i++] = "NOP";
1287   argv[i] = NULL;
1288
1289   err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
1290   if (!err)
1291     err = gnupg_wait_process (pgmname, pid, 1, NULL);
1292   if (err)
1293     gc_error (0, 0, "error running '%s%s%s': %s",
1294               pgmname,
1295               component == GC_COMPONENT_DIRMNGR? " --dirmngr":"",
1296               " NOP",
1297               gpg_strerror (err));
1298   gnupg_release_process (pid);
1299   return err;
1300 }
1301
1302
1303 /* Unconditionally restart COMPONENT.  */
1304 void
1305 gc_component_kill (int component)
1306 {
1307   int runtime[GC_BACKEND_NR];
1308   gc_option_t *option;
1309   gc_backend_t backend;
1310
1311   /* Set a flag for the backends to be reloaded.  */
1312   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1313     runtime[backend] = 0;
1314
1315   if (component < 0)
1316     {
1317       for (component = 0; component < GC_COMPONENT_NR; component++)
1318         {
1319           option = gc_component[component].options;
1320           for (; option && option->name; option++)
1321             runtime[option->backend] = 1;
1322         }
1323     }
1324   else
1325     {
1326       assert (component < GC_COMPONENT_NR);
1327       option = gc_component[component].options;
1328       for (; option && option->name; option++)
1329         runtime[option->backend] = 1;
1330     }
1331
1332   /* Do the restart for the selected backends.  */
1333   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1334     {
1335       if (runtime[backend] && gc_backend[backend].runtime_change)
1336         (*gc_backend[backend].runtime_change) (1);
1337     }
1338 }
1339
1340
1341 /* Unconditionally reload COMPONENT or all components if COMPONENT is -1.  */
1342 void
1343 gc_component_reload (int component)
1344 {
1345   int runtime[GC_BACKEND_NR];
1346   gc_option_t *option;
1347   gc_backend_t backend;
1348
1349   /* Set a flag for the backends to be reloaded.  */
1350   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1351     runtime[backend] = 0;
1352
1353   if (component < 0)
1354     {
1355       for (component = 0; component < GC_COMPONENT_NR; component++)
1356         {
1357           option = gc_component[component].options;
1358           for (; option && option->name; option++)
1359             runtime[option->backend] = 1;
1360         }
1361     }
1362   else
1363     {
1364       assert (component < GC_COMPONENT_NR);
1365       option = gc_component[component].options;
1366       for (; option && option->name; option++)
1367         runtime[option->backend] = 1;
1368     }
1369
1370   /* Do the reload for all selected backends.  */
1371   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1372     {
1373       if (runtime[backend] && gc_backend[backend].runtime_change)
1374         (*gc_backend[backend].runtime_change) (0);
1375     }
1376 }
1377
1378
1379 \f
1380 /* More or less Robust version of dgettext.  It has the side effect of
1381    switching the codeset to utf-8 because this is what we want to
1382    output.  In theory it is posible to keep the original code set and
1383    switch back for regular disgnostic output (redefine "_(" for that)
1384    but given the natur of this tool, being something invoked from
1385    other pograms, it does not make much sense.  */
1386 static const char *
1387 my_dgettext (const char *domain, const char *msgid)
1388 {
1389 #ifdef USE_SIMPLE_GETTEXT
1390   if (domain)
1391     {
1392       static int switched_codeset;
1393       char *text;
1394
1395       if (!switched_codeset)
1396         {
1397           switched_codeset = 1;
1398           gettext_use_utf8 (1);
1399         }
1400
1401       if (!strcmp (domain, "gnupg"))
1402         domain = PACKAGE_GT;
1403
1404       /* FIXME: we have no dgettext, thus we can't switch.  */
1405
1406       text = (char*)gettext (msgid);
1407       return text ? text : msgid;
1408     }
1409   else
1410     return msgid;
1411 #elif defined(ENABLE_NLS)
1412   if (domain)
1413     {
1414       static int switched_codeset;
1415       char *text;
1416
1417       if (!switched_codeset)
1418         {
1419           switched_codeset = 1;
1420           bind_textdomain_codeset (PACKAGE_GT, "utf-8");
1421
1422           bindtextdomain (DIRMNGR_NAME, LOCALEDIR);
1423           bind_textdomain_codeset (DIRMNGR_NAME, "utf-8");
1424
1425         }
1426
1427       /* Note: This is a hack to actually use the gnupg2 domain as
1428          long we are in a transition phase where gnupg 1.x and 1.9 may
1429          coexist. */
1430       if (!strcmp (domain, "gnupg"))
1431         domain = PACKAGE_GT;
1432
1433       text = dgettext (domain, msgid);
1434       return text ? text : msgid;
1435     }
1436   else
1437     return msgid;
1438 #else
1439   (void)domain;
1440   return msgid;
1441 #endif
1442 }
1443
1444
1445 /* Percent-Escape special characters.  The string is valid until the
1446    next invocation of the function.  */
1447 char *
1448 gc_percent_escape (const char *src)
1449 {
1450   static char *esc_str;
1451   static int esc_str_len;
1452   int new_len = 3 * strlen (src) + 1;
1453   char *dst;
1454
1455   if (esc_str_len < new_len)
1456     {
1457       char *new_esc_str = realloc (esc_str, new_len);
1458       if (!new_esc_str)
1459         gc_error (1, errno, "can not escape string");
1460       esc_str = new_esc_str;
1461       esc_str_len = new_len;
1462     }
1463
1464   dst = esc_str;
1465   while (*src)
1466     {
1467       if (*src == '%')
1468         {
1469           *(dst++) = '%';
1470           *(dst++) = '2';
1471           *(dst++) = '5';
1472         }
1473       else if (*src == ':')
1474         {
1475           /* The colon is used as field separator.  */
1476           *(dst++) = '%';
1477           *(dst++) = '3';
1478           *(dst++) = 'a';
1479         }
1480       else if (*src == ',')
1481         {
1482           /* The comma is used as list separator.  */
1483           *(dst++) = '%';
1484           *(dst++) = '2';
1485           *(dst++) = 'c';
1486         }
1487       else
1488         *(dst++) = *(src);
1489       src++;
1490     }
1491   *dst = '\0';
1492   return esc_str;
1493 }
1494
1495
1496
1497 /* Percent-Deescape special characters.  The string is valid until the
1498    next invocation of the function.  */
1499 static char *
1500 percent_deescape (const char *src)
1501 {
1502   static char *str;
1503   static int str_len;
1504   int new_len = 3 * strlen (src) + 1;
1505   char *dst;
1506
1507   if (str_len < new_len)
1508     {
1509       char *new_str = realloc (str, new_len);
1510       if (!new_str)
1511         gc_error (1, errno, "can not deescape string");
1512       str = new_str;
1513       str_len = new_len;
1514     }
1515
1516   dst = str;
1517   while (*src)
1518     {
1519       if (*src == '%')
1520         {
1521           int val = hextobyte (src + 1);
1522
1523           if (val < 0)
1524             gc_error (1, 0, "malformed end of string %s", src);
1525
1526           *(dst++) = (char) val;
1527           src += 3;
1528         }
1529       else
1530         *(dst++) = *(src++);
1531     }
1532   *dst = '\0';
1533   return str;
1534 }
1535
1536 \f
1537 /* List all components that are available.  */
1538 void
1539 gc_component_list_components (estream_t out)
1540 {
1541   gc_component_t component;
1542   gc_option_t *option;
1543   gc_backend_t backend;
1544   int backend_seen[GC_BACKEND_NR];
1545   const char *desc;
1546   const char *pgmname;
1547
1548   for (component = 0; component < GC_COMPONENT_NR; component++)
1549     {
1550       option = gc_component[component].options;
1551       if (option)
1552         {
1553           for (backend = 0; backend < GC_BACKEND_NR; backend++)
1554             backend_seen[backend] = 0;
1555
1556           pgmname = "";
1557           for (; option && option->name; option++)
1558             {
1559               if ((option->flags & GC_OPT_FLAG_GROUP))
1560                 continue;
1561               backend = option->backend;
1562               if (backend_seen[backend])
1563                 continue;
1564               backend_seen[backend] = 1;
1565               assert (backend != GC_BACKEND_ANY);
1566               if (gc_backend[backend].program
1567                   && !gc_backend[backend].module_name)
1568                 continue;
1569               pgmname = gnupg_module_name (gc_backend[backend].module_name);
1570               break;
1571             }
1572
1573           desc = gc_component[component].desc;
1574           desc = my_dgettext (gc_component[component].desc_domain, desc);
1575           es_fprintf (out, "%s:%s:",
1576                       gc_component[component].name,  gc_percent_escape (desc));
1577           es_fprintf (out, "%s\n",  gc_percent_escape (pgmname));
1578         }
1579     }
1580 }
1581
1582
1583 \f
1584 static int
1585 all_digits_p (const char *p, size_t len)
1586 {
1587   if (!len)
1588     return 0; /* No. */
1589   for (; len; len--, p++)
1590     if (!isascii (*p) || !isdigit (*p))
1591       return 0; /* No.  */
1592   return 1; /* Yes.  */
1593 }
1594
1595
1596 /* Collect all error lines from stream FP. Only lines prefixed with
1597    TAG are considered.  Returns a list of error line items (which may
1598    be empty).  There is no error return.  */
1599 static error_line_t
1600 collect_error_output (estream_t fp, const char *tag)
1601 {
1602   char buffer[1024];
1603   char *p, *p2, *p3;
1604   int c, cont_line;
1605   unsigned int pos;
1606   error_line_t eitem, errlines, *errlines_tail;
1607   size_t taglen = strlen (tag);
1608
1609   errlines = NULL;
1610   errlines_tail = &errlines;
1611   pos = 0;
1612   cont_line = 0;
1613   while ((c=es_getc (fp)) != EOF)
1614     {
1615       buffer[pos++] = c;
1616       if (pos >= sizeof buffer - 5 || c == '\n')
1617         {
1618           buffer[pos - (c == '\n')] = 0;
1619           if (cont_line)
1620             ; /*Ignore continuations of previous line. */
1621           else if (!strncmp (buffer, tag, taglen) && buffer[taglen] == ':')
1622             {
1623               /* "gpgsm: foo:4: bla" */
1624               /* Yep, we are interested in this line.  */
1625               p = buffer + taglen + 1;
1626               while (*p == ' ' || *p == '\t')
1627                 p++;
1628               trim_trailing_spaces (p); /* Get rid of extra CRs.  */
1629               if (!*p)
1630                 ; /* Empty lines are ignored.  */
1631               else if ( (p2 = strchr (p, ':')) && (p3 = strchr (p2+1, ':'))
1632                         && all_digits_p (p2+1, p3 - (p2+1)))
1633                 {
1634                   /* Line in standard compiler format.  */
1635                   p3++;
1636                   while (*p3 == ' ' || *p3 == '\t')
1637                     p3++;
1638                   eitem = xmalloc (sizeof *eitem + strlen (p));
1639                   eitem->next = NULL;
1640                   strcpy (eitem->buffer, p);
1641                   eitem->fname = eitem->buffer;
1642                   eitem->buffer[p2-p] = 0;
1643                   eitem->errtext = eitem->buffer + (p3 - p);
1644                   /* (we already checked that there are only ascii
1645                      digits followed by a colon) */
1646                   eitem->lineno = 0;
1647                   for (p2++; isdigit (*p2); p2++)
1648                     eitem->lineno = eitem->lineno*10 + (*p2 - '0');
1649                   *errlines_tail = eitem;
1650                   errlines_tail = &eitem->next;
1651                 }
1652               else
1653                 {
1654                   /* Other error output.  */
1655                   eitem = xmalloc (sizeof *eitem + strlen (p));
1656                   eitem->next = NULL;
1657                   strcpy (eitem->buffer, p);
1658                   eitem->fname = NULL;
1659                   eitem->errtext = eitem->buffer;
1660                   eitem->lineno = 0;
1661                   *errlines_tail = eitem;
1662                   errlines_tail = &eitem->next;
1663                 }
1664             }
1665           pos = 0;
1666           /* If this was not a complete line mark that we are in a
1667              continuation.  */
1668           cont_line = (c != '\n');
1669         }
1670     }
1671
1672   /* We ignore error lines not terminated by a LF.  */
1673   return errlines;
1674 }
1675
1676
1677 /* Check the options of a single component.  Returns 0 if everything
1678    is OK.  */
1679 int
1680 gc_component_check_options (int component, estream_t out, const char *conf_file)
1681 {
1682   gpg_error_t err;
1683   unsigned int result;
1684   int backend_seen[GC_BACKEND_NR];
1685   gc_backend_t backend;
1686   gc_option_t *option;
1687   const char *pgmname;
1688   const char *argv[4];
1689   int i;
1690   pid_t pid;
1691   int exitcode;
1692   estream_t errfp;
1693   error_line_t errlines;
1694
1695   for (backend = 0; backend < GC_BACKEND_NR; backend++)
1696     backend_seen[backend] = 0;
1697
1698   option = gc_component[component].options;
1699   for (; option && option->name; option++)
1700     {
1701       if ((option->flags & GC_OPT_FLAG_GROUP))
1702         continue;
1703       backend = option->backend;
1704       if (backend_seen[backend])
1705         continue;
1706       backend_seen[backend] = 1;
1707       assert (backend != GC_BACKEND_ANY);
1708       if (!gc_backend[backend].program)
1709         continue;
1710       if (!gc_backend[backend].module_name)
1711         continue;
1712
1713       break;
1714     }
1715   if (! option || ! option->name)
1716     return 0;
1717
1718   pgmname = gnupg_module_name (gc_backend[backend].module_name);
1719   i = 0;
1720   if (conf_file)
1721     {
1722       argv[i++] = "--options";
1723       argv[i++] = conf_file;
1724     }
1725   if (component == GC_COMPONENT_PINENTRY)
1726     argv[i++] = "--version";
1727   else
1728     argv[i++] = "--gpgconf-test";
1729   argv[i++] = NULL;
1730
1731   result = 0;
1732   errlines = NULL;
1733   err = gnupg_spawn_process (pgmname, argv, NULL, NULL, 0,
1734                              NULL, NULL, &errfp, &pid);
1735   if (err)
1736     result |= 1; /* Program could not be run.  */
1737   else
1738     {
1739       errlines = collect_error_output (errfp,
1740                                        gc_component[component].name);
1741       if (gnupg_wait_process (pgmname, pid, 1, &exitcode))
1742         {
1743           if (exitcode == -1)
1744             result |= 1; /* Program could not be run or it
1745                             terminated abnormally.  */
1746           result |= 2; /* Program returned an error.  */
1747         }
1748       gnupg_release_process (pid);
1749       es_fclose (errfp);
1750     }
1751
1752   /* If the program could not be run, we can't tell whether
1753      the config file is good.  */
1754   if (result & 1)
1755     result |= 2;
1756
1757   if (out)
1758     {
1759       const char *desc;
1760       error_line_t errptr;
1761
1762       desc = gc_component[component].desc;
1763       desc = my_dgettext (gc_component[component].desc_domain, desc);
1764       es_fprintf (out, "%s:%s:",
1765                   gc_component[component].name, gc_percent_escape (desc));
1766       es_fputs (gc_percent_escape (pgmname), out);
1767       es_fprintf (out, ":%d:%d:", !(result & 1), !(result & 2));
1768       for (errptr = errlines; errptr; errptr = errptr->next)
1769         {
1770           if (errptr != errlines)
1771             es_fputs ("\n:::::", out); /* Continuation line.  */
1772           if (errptr->fname)
1773             es_fputs (gc_percent_escape (errptr->fname), out);
1774           es_putc (':', out);
1775           if (errptr->fname)
1776             es_fprintf (out, "%u", errptr->lineno);
1777           es_putc (':', out);
1778           es_fputs (gc_percent_escape (errptr->errtext), out);
1779           es_putc (':', out);
1780         }
1781       es_putc ('\n', out);
1782     }
1783
1784   while (errlines)
1785     {
1786       error_line_t tmp = errlines->next;
1787       xfree (errlines);
1788       errlines = tmp;
1789     }
1790
1791   return result;
1792 }
1793
1794
1795
1796 /* Check all components that are available.  */
1797 void
1798 gc_check_programs (estream_t out)
1799 {
1800   gc_component_t component;
1801
1802   for (component = 0; component < GC_COMPONENT_NR; component++)
1803     gc_component_check_options (component, out, NULL);
1804 }
1805
1806
1807 \f
1808 /* Find the component with the name NAME.  Returns -1 if not
1809    found.  */
1810 int
1811 gc_component_find (const char *name)
1812 {
1813   gc_component_t idx;
1814
1815   for (idx = 0; idx < GC_COMPONENT_NR; idx++)
1816     {
1817       if (gc_component[idx].options
1818           && !strcmp (name, gc_component[idx].name))
1819         return idx;
1820     }
1821   return -1;
1822 }
1823
1824 \f
1825 /* List the option OPTION.  */
1826 static void
1827 list_one_option (const gc_option_t *option, estream_t out)
1828 {
1829   const char *desc = NULL;
1830   char *arg_name = NULL;
1831
1832   if (option->desc)
1833     {
1834       desc = my_dgettext (option->desc_domain, option->desc);
1835
1836       if (*desc == '|')
1837         {
1838           const char *arg_tail = strchr (&desc[1], '|');
1839
1840           if (arg_tail)
1841             {
1842               int arg_len = arg_tail - &desc[1];
1843               arg_name = xmalloc (arg_len + 1);
1844               memcpy (arg_name, &desc[1], arg_len);
1845               arg_name[arg_len] = '\0';
1846               desc = arg_tail + 1;
1847             }
1848         }
1849     }
1850
1851
1852   /* YOU MUST NOT REORDER THE FIELDS IN THIS OUTPUT, AS THEIR ORDER IS
1853      PART OF THE EXTERNAL INTERFACE.  YOU MUST NOT REMOVE ANY
1854      FIELDS.  */
1855
1856   /* The name field.  */
1857   es_fprintf (out, "%s", option->name);
1858
1859   /* The flags field.  */
1860   es_fprintf (out, ":%lu", option->flags);
1861   if (opt.verbose)
1862     {
1863       es_putc (' ', out);
1864
1865       if (!option->flags)
1866         es_fprintf (out, "none");
1867       else
1868         {
1869           unsigned long flags = option->flags;
1870           unsigned long flag = 0;
1871           unsigned long first = 1;
1872
1873           while (flags)
1874             {
1875               if (flags & 1)
1876                 {
1877                   if (first)
1878                     first = 0;
1879                   else
1880                     es_putc (',', out);
1881                   es_fprintf (out, "%s", gc_flag[flag].name);
1882                 }
1883               flags >>= 1;
1884               flag++;
1885             }
1886         }
1887     }
1888
1889   /* The level field.  */
1890   es_fprintf (out, ":%u", option->level);
1891   if (opt.verbose)
1892     es_fprintf (out, " %s", gc_level[option->level].name);
1893
1894   /* The description field.  */
1895   es_fprintf (out, ":%s", desc ? gc_percent_escape (desc) : "");
1896
1897   /* The type field.  */
1898   es_fprintf (out, ":%u", option->arg_type);
1899   if (opt.verbose)
1900     es_fprintf (out, " %s", gc_arg_type[option->arg_type].name);
1901
1902   /* The alternate type field.  */
1903   es_fprintf (out, ":%u", gc_arg_type[option->arg_type].fallback);
1904   if (opt.verbose)
1905     es_fprintf (out, " %s",
1906                 gc_arg_type[gc_arg_type[option->arg_type].fallback].name);
1907
1908   /* The argument name field.  */
1909   es_fprintf (out, ":%s", arg_name ? gc_percent_escape (arg_name) : "");
1910   xfree (arg_name);
1911
1912   /* The default value field.  */
1913   es_fprintf (out, ":%s", option->default_value ? option->default_value : "");
1914
1915   /* The default argument field.  */
1916   es_fprintf (out, ":%s", option->default_arg ? option->default_arg : "");
1917
1918   /* The value field.  */
1919   if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE
1920       && (option->flags & GC_OPT_FLAG_LIST)
1921       && option->value)
1922     /* The special format "1,1,1,1,...,1" is converted to a number
1923        here.  */
1924     es_fprintf (out, ":%u", (unsigned int)((strlen (option->value) + 1) / 2));
1925   else
1926     es_fprintf (out, ":%s", option->value ? option->value : "");
1927
1928   /* ADD NEW FIELDS HERE.  */
1929
1930   es_putc ('\n', out);
1931 }
1932
1933
1934 /* List all options of the component COMPONENT.  */
1935 void
1936 gc_component_list_options (int component, estream_t out)
1937 {
1938   const gc_option_t *option = gc_component[component].options;
1939
1940   while (option && option->name)
1941     {
1942       /* Do not output unknown or internal options.  */
1943       if (!(option->flags & GC_OPT_FLAG_GROUP)
1944           && (!option->active || option->level == GC_LEVEL_INTERNAL))
1945         {
1946           option++;
1947           continue;
1948         }
1949
1950       if (option->flags & GC_OPT_FLAG_GROUP)
1951         {
1952           const gc_option_t *group_option = option + 1;
1953           gc_expert_level_t level = GC_LEVEL_NR;
1954
1955           /* The manual states that the group level is always the
1956              minimum of the levels of all contained options.  Due to
1957              different active options, and because it is hard to
1958              maintain manually, we calculate it here.  The value in
1959              the global static table is ignored.  */
1960
1961           while (group_option->name)
1962             {
1963               if (group_option->flags & GC_OPT_FLAG_GROUP)
1964                 break;
1965               if (group_option->level < level)
1966                 level = group_option->level;
1967               group_option++;
1968             }
1969
1970           /* Check if group is empty.  */
1971           if (level != GC_LEVEL_NR)
1972             {
1973               gc_option_t opt_copy;
1974
1975               /* Fix up the group level.  */
1976               memcpy (&opt_copy, option, sizeof (opt_copy));
1977               opt_copy.level = level;
1978               list_one_option (&opt_copy, out);
1979             }
1980         }
1981       else
1982         list_one_option (option, out);
1983
1984       option++;
1985     }
1986 }
1987
1988
1989 /* Find the option NAME in component COMPONENT, for the backend
1990    BACKEND.  If BACKEND is GC_BACKEND_ANY, any backend will match.  */
1991 static gc_option_t *
1992 find_option (gc_component_t component, const char *name,
1993              gc_backend_t backend)
1994 {
1995   gc_option_t *option = gc_component[component].options;
1996   while (option->name)
1997     {
1998       if (!(option->flags & GC_OPT_FLAG_GROUP)
1999           && !strcmp (option->name, name)
2000           && (backend == GC_BACKEND_ANY || option->backend == backend))
2001         break;
2002       option++;
2003     }
2004   return option->name ? option : NULL;
2005 }
2006
2007 \f
2008 /* Determine the configuration filename for the component COMPONENT
2009    and backend BACKEND.  */
2010 static char *
2011 get_config_filename (gc_component_t component, gc_backend_t backend)
2012 {
2013   char *filename = NULL;
2014   gc_option_t *option = find_option
2015     (component, gc_backend[backend].option_config_filename, GC_BACKEND_ANY);
2016   assert (option);
2017   assert (option->arg_type == GC_ARG_TYPE_FILENAME);
2018   assert (!(option->flags & GC_OPT_FLAG_LIST));
2019
2020   if (!option->active || !option->default_value)
2021     gc_error (1, 0, "Option %s, needed by backend %s, was not initialized",
2022               gc_backend[backend].option_config_filename,
2023               gc_backend[backend].name);
2024
2025   if (option->value && *option->value)
2026     filename = percent_deescape (&option->value[1]);
2027   else if (option->default_value && *option->default_value)
2028     filename = percent_deescape (&option->default_value[1]);
2029   else
2030     filename = "";
2031
2032 #if HAVE_W32CE_SYSTEM
2033   if (!(filename[0] == '/' || filename[0] == '\\'))
2034 #elif defined(HAVE_DOSISH_SYSTEM)
2035   if (!(filename[0]
2036         && filename[1] == ':'
2037         && (filename[2] == '/' || filename[2] == '\\')))
2038 #else
2039   if (filename[0] != '/')
2040 #endif
2041     gc_error (1, 0, "Option %s, needed by backend %s, is not absolute",
2042               gc_backend[backend].option_config_filename,
2043               gc_backend[backend].name);
2044
2045   return filename;
2046 }
2047
2048 \f
2049 /* Retrieve the options for the component COMPONENT from backend
2050    BACKEND, which we already know is a program-type backend.  */
2051 static void
2052 retrieve_options_from_program (gc_component_t component, gc_backend_t backend)
2053 {
2054   gpg_error_t err;
2055   const char *pgmname;
2056   const char *argv[2];
2057   estream_t outfp;
2058   int exitcode;
2059   pid_t pid;
2060   char *line = NULL;
2061   size_t line_len = 0;
2062   ssize_t length;
2063   estream_t config;
2064   char *config_filename;
2065
2066   pgmname = (gc_backend[backend].module_name
2067              ? gnupg_module_name (gc_backend[backend].module_name)
2068              : gc_backend[backend].program );
2069   argv[0] = "--gpgconf-list";
2070   argv[1] = NULL;
2071
2072   err = gnupg_spawn_process (pgmname, argv, NULL, NULL, 0,
2073                              NULL, &outfp, NULL, &pid);
2074   if (err)
2075     {
2076       gc_error (1, 0, "could not gather active options from '%s': %s",
2077                 pgmname, gpg_strerror (err));
2078     }
2079
2080   while ((length = es_read_line (outfp, &line, &line_len, NULL)) > 0)
2081     {
2082       gc_option_t *option;
2083       char *linep;
2084       unsigned long flags = 0;
2085       char *default_value = NULL;
2086
2087       /* Strip newline and carriage return, if present.  */
2088       while (length > 0
2089              && (line[length - 1] == '\n' || line[length - 1] == '\r'))
2090         line[--length] = '\0';
2091
2092       linep = strchr (line, ':');
2093       if (linep)
2094         *(linep++) = '\0';
2095
2096       /* Extract additional flags.  Default to none.  */
2097       if (linep)
2098         {
2099           char *end;
2100           char *tail;
2101
2102           end = strchr (linep, ':');
2103           if (end)
2104             *(end++) = '\0';
2105
2106           gpg_err_set_errno (0);
2107           flags = strtoul (linep, &tail, 0);
2108           if (errno)
2109             gc_error (1, errno, "malformed flags in option %s from %s",
2110                       line, pgmname);
2111           if (!(*tail == '\0' || *tail == ':' || *tail == ' '))
2112             gc_error (1, 0, "garbage after flags in option %s from %s",
2113                       line, pgmname);
2114
2115           linep = end;
2116         }
2117
2118       /* Extract default value, if present.  Default to empty if
2119          not.  */
2120       if (linep)
2121         {
2122           char *end;
2123
2124           end = strchr (linep, ':');
2125           if (end)
2126             *(end++) = '\0';
2127
2128           if (flags & GC_OPT_FLAG_DEFAULT)
2129             default_value = linep;
2130
2131           linep = end;
2132         }
2133
2134       /* Look up the option in the component and install the
2135          configuration data.  */
2136       option = find_option (component, line, backend);
2137       if (option)
2138         {
2139           if (option->active)
2140             gc_error (1, errno, "option %s returned twice from %s",
2141                       line, pgmname);
2142           option->active = 1;
2143
2144           option->flags |= flags;
2145           if (default_value && *default_value)
2146             option->default_value = xstrdup (default_value);
2147         }
2148     }
2149   if (length < 0 || es_ferror (outfp))
2150     gc_error (1, errno, "error reading from %s", pgmname);
2151   if (es_fclose (outfp))
2152     gc_error (1, errno, "error closing %s", pgmname);
2153
2154   err = gnupg_wait_process (pgmname, pid, 1, &exitcode);
2155   if (err)
2156     gc_error (1, 0, "running %s failed (exitcode=%d): %s",
2157               pgmname, exitcode, gpg_strerror (err));
2158   gnupg_release_process (pid);
2159
2160
2161   /* At this point, we can parse the configuration file.  */
2162   config_filename = get_config_filename (component, backend);
2163
2164   config = es_fopen (config_filename, "r");
2165   if (!config)
2166     gc_error (0, errno, "warning: can not open config file %s",
2167               config_filename);
2168   else
2169     {
2170       while ((length = es_read_line (config, &line, &line_len, NULL)) > 0)
2171         {
2172           char *name;
2173           char *value;
2174           gc_option_t *option;
2175
2176           name = line;
2177           while (*name == ' ' || *name == '\t')
2178             name++;
2179           if (!*name || *name == '#' || *name == '\r' || *name == '\n')
2180             continue;
2181
2182           value = name;
2183           while (*value && *value != ' ' && *value != '\t'
2184                  && *value != '#' && *value != '\r' && *value != '\n')
2185             value++;
2186           if (*value == ' ' || *value == '\t')
2187             {
2188               char *end;
2189
2190               *(value++) = '\0';
2191               while (*value == ' ' || *value == '\t')
2192                 value++;
2193
2194               end = value;
2195               while (*end && *end != '#' && *end != '\r' && *end != '\n')
2196                 end++;
2197               while (end > value && (end[-1] == ' ' || end[-1] == '\t'))
2198                 end--;
2199               *end = '\0';
2200             }
2201           else
2202             *value = '\0';
2203
2204           /* Look up the option in the component and install the
2205              configuration data.  */
2206           option = find_option (component, line, backend);
2207           if (option)
2208             {
2209               char *opt_value;
2210
2211               if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE)
2212                 {
2213                   if (*value)
2214                     gc_error (0, 0,
2215                               "warning: ignoring argument %s for option %s",
2216                               value, name);
2217                   opt_value = xstrdup ("1");
2218                 }
2219               else if (gc_arg_type[option->arg_type].fallback
2220                        == GC_ARG_TYPE_STRING)
2221                 opt_value = xasprintf ("\"%s", gc_percent_escape (value));
2222               else
2223                 {
2224                   /* FIXME: Verify that the number is sane.  */
2225                   opt_value = xstrdup (value);
2226                 }
2227
2228               /* Now enter the option into the table.  */
2229               if (!(option->flags & GC_OPT_FLAG_LIST))
2230                 {
2231                   if (option->value)
2232                     xfree (option->value);
2233                   option->value = opt_value;
2234                 }
2235               else
2236                 {
2237                   if (!option->value)
2238                     option->value = opt_value;
2239                   else
2240                     {
2241                       char *old = option->value;
2242                       option->value = xasprintf ("%s,%s", old, opt_value);
2243                       xfree (old);
2244                       xfree (opt_value);
2245                     }
2246                 }
2247             }
2248         }
2249
2250       if (length < 0 || es_ferror (config))
2251         gc_error (1, errno, "error reading from %s", config_filename);
2252       if (es_fclose (config))
2253         gc_error (1, errno, "error closing %s", config_filename);
2254     }
2255
2256   xfree (line);
2257 }
2258
2259
2260 /* Retrieve the options for the component COMPONENT from backend
2261    BACKEND, which we already know is of type file list.  */
2262 static void
2263 retrieve_options_from_file (gc_component_t component, gc_backend_t backend)
2264 {
2265   gc_option_t *list_option;
2266   gc_option_t *config_option;
2267   char *list_filename;
2268   FILE *list_file;
2269   char *line = NULL;
2270   size_t line_len = 0;
2271   ssize_t length;
2272   char *list = NULL;
2273
2274   list_option = find_option (component,
2275                              gc_backend[backend].option_name, GC_BACKEND_ANY);
2276   assert (list_option);
2277   assert (!list_option->active);
2278
2279   list_filename = get_config_filename (component, backend);
2280   list_file = fopen (list_filename, "r");
2281   if (!list_file)
2282     gc_error (0, errno, "warning: can not open list file %s", list_filename);
2283   else
2284     {
2285
2286       while ((length = read_line (list_file, &line, &line_len, NULL)) > 0)
2287         {
2288           char *start;
2289           char *end;
2290           char *new_list;
2291
2292           start = line;
2293           while (*start == ' ' || *start == '\t')
2294             start++;
2295           if (!*start || *start == '#' || *start == '\r' || *start == '\n')
2296             continue;
2297
2298           end = start;
2299           while (*end && *end != '#' && *end != '\r' && *end != '\n')
2300             end++;
2301           /* Walk back to skip trailing white spaces.  Looks evil, but
2302              works because of the conditions on START and END imposed
2303              at this point (END is at least START + 1, and START is
2304              not a whitespace character).  */
2305           while (*(end - 1) == ' ' || *(end - 1) == '\t')
2306             end--;
2307           *end = '\0';
2308           /* FIXME: Oh, no!  This is so lame!  Should use realloc and
2309              really append.  */
2310           if (list)
2311             {
2312               new_list = xasprintf ("%s,\"%s", list, gc_percent_escape (start));
2313               xfree (list);
2314               list = new_list;
2315             }
2316           else
2317             list = xasprintf ("\"%s", gc_percent_escape (start));
2318         }
2319       if (length < 0 || ferror (list_file))
2320         gc_error (1, errno, "can not read list file %s", list_filename);
2321     }
2322
2323   list_option->active = 1;
2324   list_option->value = list;
2325
2326   /* Fix up the read-only flag.  */
2327   config_option = find_option
2328     (component, gc_backend[backend].option_config_filename, GC_BACKEND_ANY);
2329   if (config_option->flags & GC_OPT_FLAG_NO_CHANGE)
2330     list_option->flags |= GC_OPT_FLAG_NO_CHANGE;
2331
2332   if (list_file && fclose (list_file))
2333     gc_error (1, errno, "error closing %s", list_filename);
2334   xfree (line);
2335 }
2336
2337
2338 /* Retrieve the currently active options and their defaults from all
2339    involved backends for this component.  Using -1 for component will
2340    retrieve all options from all components. */
2341 void
2342 gc_component_retrieve_options (int component)
2343 {
2344   int process_all = 0;
2345   int backend_seen[GC_BACKEND_NR];
2346   gc_backend_t backend;
2347   gc_option_t *option;
2348
2349   for (backend = 0; backend < GC_BACKEND_NR; backend++)
2350     backend_seen[backend] = 0;
2351
2352   if (component == -1)
2353     {
2354       process_all = 1;
2355       component = 0;
2356       assert (component < GC_COMPONENT_NR);
2357     }
2358
2359   do
2360     {
2361       if (component == GC_COMPONENT_PINENTRY)
2362         continue; /* Skip this dummy component.  */
2363
2364       option = gc_component[component].options;
2365
2366       while (option && option->name)
2367         {
2368           if (!(option->flags & GC_OPT_FLAG_GROUP))
2369             {
2370               backend = option->backend;
2371
2372               if (backend_seen[backend])
2373                 {
2374                   option++;
2375                   continue;
2376                 }
2377               backend_seen[backend] = 1;
2378
2379               assert (backend != GC_BACKEND_ANY);
2380
2381               if (gc_backend[backend].program)
2382                 retrieve_options_from_program (component, backend);
2383               else
2384                 retrieve_options_from_file (component, backend);
2385             }
2386           option++;
2387         }
2388     }
2389   while (process_all && ++component < GC_COMPONENT_NR);
2390
2391 }
2392
2393
2394 \f
2395 /* Perform a simple validity check based on the type.  Return in
2396  * NEW_VALUE_NR the value of the number in NEW_VALUE if OPTION is of
2397  * type GC_ARG_TYPE_NONE.  If VERBATIM is set the profile parsing mode
2398  * is used. */
2399 static void
2400 option_check_validity (gc_option_t *option, unsigned long flags,
2401                        char *new_value, unsigned long *new_value_nr,
2402                        int verbatim)
2403 {
2404   char *arg;
2405
2406   if (!option->active)
2407     gc_error (1, 0, "option %s not supported by backend %s",
2408               option->name, gc_backend[option->backend].name);
2409
2410   if (option->new_flags || option->new_value)
2411     gc_error (1, 0, "option %s already changed", option->name);
2412
2413   if (flags & GC_OPT_FLAG_DEFAULT)
2414     {
2415       if (*new_value)
2416         gc_error (1, 0, "argument %s provided for deleted option %s",
2417                   new_value, option->name);
2418
2419       return;
2420     }
2421
2422   /* GC_ARG_TYPE_NONE options have special list treatment.  */
2423   if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE)
2424     {
2425       char *tail;
2426
2427       gpg_err_set_errno (0);
2428       *new_value_nr = strtoul (new_value, &tail, 0);
2429
2430       if (errno)
2431         gc_error (1, errno, "invalid argument for option %s",
2432                   option->name);
2433       if (*tail)
2434         gc_error (1, 0, "garbage after argument for option %s",
2435                       option->name);
2436
2437       if (!(option->flags & GC_OPT_FLAG_LIST))
2438         {
2439           if (*new_value_nr != 1)
2440             gc_error (1, 0, "argument for non-list option %s of type 0 "
2441                       "(none) must be 1", option->name);
2442         }
2443       else
2444         {
2445           if (*new_value_nr == 0)
2446             gc_error (1, 0, "argument for option %s of type 0 (none) "
2447                       "must be positive", option->name);
2448         }
2449
2450       return;
2451     }
2452
2453   arg = new_value;
2454   do
2455     {
2456       if (*arg == '\0' || (*arg == ',' && !verbatim))
2457         {
2458           if (!(option->flags & GC_OPT_FLAG_ARG_OPT))
2459             gc_error (1, 0, "argument required for option %s", option->name);
2460
2461           if (*arg == ',' && !verbatim && !(option->flags & GC_OPT_FLAG_LIST))
2462             gc_error (1, 0, "list found for non-list option %s", option->name);
2463         }
2464       else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_STRING)
2465         {
2466           if (*arg != '"' && !verbatim)
2467             gc_error (1, 0, "string argument for option %s must begin "
2468                       "with a quote (\") character", option->name);
2469
2470           /* FIXME: We do not allow empty string arguments for now, as
2471              we do not quote arguments in configuration files, and
2472              thus no argument is indistinguishable from the empty
2473              string.  */
2474           if (arg[1] == '\0' || (arg[1] == ',' && !verbatim))
2475             gc_error (1, 0, "empty string argument for option %s is "
2476                       "currently not allowed.  Please report this!",
2477                       option->name);
2478         }
2479       else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_INT32)
2480         {
2481           long res;
2482
2483           gpg_err_set_errno (0);
2484           res = strtol (arg, &arg, 0);
2485           (void) res;
2486
2487           if (errno)
2488             gc_error (1, errno, "invalid argument for option %s",
2489                       option->name);
2490
2491           if (*arg != '\0' && (*arg != ',' || verbatim))
2492             gc_error (1, 0, "garbage after argument for option %s",
2493                       option->name);
2494         }
2495       else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_UINT32)
2496         {
2497           unsigned long res;
2498
2499           gpg_err_set_errno (0);
2500           res = strtoul (arg, &arg, 0);
2501           (void) res;
2502
2503           if (errno)
2504             gc_error (1, errno, "invalid argument for option %s",
2505                       option->name);
2506
2507           if (*arg != '\0' && (*arg != ',' || verbatim))
2508             gc_error (1, 0, "garbage after argument for option %s",
2509                       option->name);
2510         }
2511       arg = verbatim? strchr (arg, ',') : NULL;
2512       if (arg)
2513         arg++;
2514     }
2515   while (arg && *arg);
2516 }
2517
2518
2519 #ifdef HAVE_W32_SYSTEM
2520 int
2521 copy_file (const char *src_name, const char *dst_name)
2522 {
2523 #define BUF_LEN 4096
2524   char buffer[BUF_LEN];
2525   int len;
2526   FILE *src;
2527   FILE *dst;
2528
2529   src = fopen (src_name, "r");
2530   if (src == NULL)
2531     return -1;
2532
2533   dst = fopen (dst_name, "w");
2534   if (dst == NULL)
2535     {
2536       int saved_err = errno;
2537       fclose (src);
2538       gpg_err_set_errno (saved_err);
2539       return -1;
2540     }
2541
2542   do
2543     {
2544       int written;
2545
2546       len = fread (buffer, 1, BUF_LEN, src);
2547       if (len == 0)
2548         break;
2549       written = fwrite (buffer, 1, len, dst);
2550       if (written != len)
2551         break;
2552     }
2553   while (!feof (src) && !ferror (src) && !ferror (dst));
2554
2555   if (ferror (src) || ferror (dst) || !feof (src))
2556     {
2557       int saved_errno = errno;
2558       fclose (src);
2559       fclose (dst);
2560       unlink (dst_name);
2561       gpg_err_set_errno (saved_errno);
2562       return -1;
2563     }
2564
2565   if (fclose (dst))
2566     gc_error (1, errno, "error closing %s", dst_name);
2567   if (fclose (src))
2568     gc_error (1, errno, "error closing %s", src_name);
2569
2570   return 0;
2571 }
2572 #endif /* HAVE_W32_SYSTEM */
2573
2574
2575 /* Create and verify the new configuration file for the specified
2576    backend and component.  Returns 0 on success and -1 on error.  */
2577 static int
2578 change_options_file (gc_component_t component, gc_backend_t backend,
2579                      char **src_filenamep, char **dest_filenamep,
2580                      char **orig_filenamep)
2581 {
2582   static const char marker[] = "###+++--- " GPGCONF_DISP_NAME " ---+++###";
2583   /* True if we are within the marker in the config file.  */
2584   int in_marker = 0;
2585   gc_option_t *option;
2586   char *line = NULL;
2587   size_t line_len;
2588   ssize_t length;
2589   int res;
2590   int fd;
2591   FILE *src_file = NULL;
2592   FILE *dest_file = NULL;
2593   char *src_filename;
2594   char *dest_filename;
2595   char *orig_filename;
2596   char *arg;
2597   char *cur_arg = NULL;
2598
2599   option = find_option (component,
2600                         gc_backend[backend].option_name, GC_BACKEND_ANY);
2601   assert (option);
2602   assert (option->active);
2603   assert (gc_arg_type[option->arg_type].fallback != GC_ARG_TYPE_NONE);
2604
2605   /* FIXME.  Throughout the function, do better error reporting.  */
2606   /* Note that get_config_filename() calls percent_deescape(), so we
2607      call this before processing the arguments.  */
2608   dest_filename = xstrdup (get_config_filename (component, backend));
2609   src_filename = xasprintf ("%s.%s.%i.new",
2610                             dest_filename, GPGCONF_NAME, (int)getpid ());
2611   orig_filename = xasprintf ("%s.%s.%i.bak",
2612                              dest_filename, GPGCONF_NAME, (int)getpid ());
2613
2614   arg = option->new_value;
2615   if (arg && arg[0] == '\0')
2616     arg = NULL;
2617   else if (arg)
2618     {
2619       char *end;
2620
2621       arg++;
2622       end = strchr (arg, ',');
2623       if (end)
2624         *end = '\0';
2625
2626       cur_arg = percent_deescape (arg);
2627       if (end)
2628         {
2629           *end = ',';
2630           arg = end + 1;
2631         }
2632       else
2633         arg = NULL;
2634     }
2635
2636 #ifdef HAVE_W32_SYSTEM
2637   res = copy_file (dest_filename, orig_filename);
2638 #else
2639   res = link (dest_filename, orig_filename);
2640 #endif
2641   if (res < 0 && errno != ENOENT)
2642     {
2643       xfree (dest_filename);
2644       return -1;
2645     }
2646   if (res < 0)
2647     {
2648       xfree (orig_filename);
2649       orig_filename = NULL;
2650     }
2651
2652   /* We now initialize the return strings, so the caller can do the
2653      cleanup for us.  */
2654   *src_filenamep = src_filename;
2655   *dest_filenamep = dest_filename;
2656   *orig_filenamep = orig_filename;
2657
2658   /* Use open() so that we can use O_EXCL.  */
2659   fd = open (src_filename, O_CREAT | O_EXCL | O_WRONLY, 0644);
2660   if (fd < 0)
2661     return -1;
2662   src_file = fdopen (fd, "w");
2663   res = errno;
2664   if (!src_file)
2665     {
2666       gpg_err_set_errno (res);
2667       return -1;
2668     }
2669
2670   /* Only if ORIG_FILENAME is not NULL did the configuration file
2671      exist already.  In this case, we will copy its content into the
2672      new configuration file, changing it to our liking in the
2673      process.  */
2674   if (orig_filename)
2675     {
2676       dest_file = fopen (dest_filename, "r");
2677       if (!dest_file)
2678         goto change_file_one_err;
2679
2680       while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
2681         {
2682           int disable = 0;
2683           char *start;
2684
2685           if (!strncmp (marker, line, sizeof (marker) - 1))
2686             {
2687               if (!in_marker)
2688                 in_marker = 1;
2689               else
2690                 break;
2691             }
2692
2693           start = line;
2694           while (*start == ' ' || *start == '\t')
2695             start++;
2696           if (*start && *start != '\r' && *start != '\n' && *start != '#')
2697             {
2698               char *end;
2699               char *endp;
2700               char saved_end;
2701
2702               endp = start;
2703               end = endp;
2704
2705               /* Search for the end of the line.  */
2706               while (*endp && *endp != '#' && *endp != '\r' && *endp != '\n')
2707                 {
2708                   endp++;
2709                   if (*endp && *endp != ' ' && *endp != '\t'
2710                       && *endp != '\r' && *endp != '\n' && *endp != '#')
2711                     end = endp + 1;
2712                 }
2713               saved_end = *end;
2714               *end = '\0';
2715
2716               if ((option->new_flags & GC_OPT_FLAG_DEFAULT)
2717                   || !cur_arg || strcmp (start, cur_arg))
2718                 disable = 1;
2719               else
2720                 {
2721                   /* Find next argument.  */
2722                   if (arg)
2723                     {
2724                       char *arg_end;
2725
2726                       arg++;
2727                       arg_end = strchr (arg, ',');
2728                       if (arg_end)
2729                         *arg_end = '\0';
2730
2731                       cur_arg = percent_deescape (arg);
2732                       if (arg_end)
2733                         {
2734                           *arg_end = ',';
2735                           arg = arg_end + 1;
2736                         }
2737                       else
2738                         arg = NULL;
2739                     }
2740                   else
2741                     cur_arg = NULL;
2742                 }
2743
2744               *end = saved_end;
2745             }
2746
2747           if (disable)
2748             {
2749               if (!in_marker)
2750                 {
2751                   fprintf (src_file,
2752                            "# %s disabled this option here at %s\n",
2753                            GPGCONF_DISP_NAME, asctimestamp (gnupg_get_time ()));
2754                   if (ferror (src_file))
2755                     goto change_file_one_err;
2756                   fprintf (src_file, "# %s", line);
2757                   if (ferror (src_file))
2758                     goto change_file_one_err;
2759                 }
2760             }
2761           else
2762             {
2763               fprintf (src_file, "%s", line);
2764               if (ferror (src_file))
2765                 goto change_file_one_err;
2766             }
2767         }
2768       if (length < 0 || ferror (dest_file))
2769         goto change_file_one_err;
2770     }
2771
2772   if (!in_marker)
2773     {
2774       /* There was no marker.  This is the first time we edit the
2775          file.  We add our own marker at the end of the file and
2776          proceed.  Note that we first write a newline, this guards us
2777          against files which lack the newline at the end of the last
2778          line, while it doesn't hurt us in all other cases.  */
2779       fprintf (src_file, "\n%s\n", marker);
2780       if (ferror (src_file))
2781         goto change_file_one_err;
2782     }
2783
2784   /* At this point, we have copied everything up to the end marker
2785      into the new file, except for the arguments we are going to add.
2786      Now, dump the new arguments and write the end marker, possibly
2787      followed by the rest of the original file.  */
2788   while (cur_arg)
2789     {
2790       fprintf (src_file, "%s\n", cur_arg);
2791
2792       /* Find next argument.  */
2793       if (arg)
2794         {
2795           char *end;
2796
2797           arg++;
2798           end = strchr (arg, ',');
2799           if (end)
2800             *end = '\0';
2801
2802           cur_arg = percent_deescape (arg);
2803           if (end)
2804             {
2805               *end = ',';
2806               arg = end + 1;
2807             }
2808           else
2809             arg = NULL;
2810         }
2811       else
2812         cur_arg = NULL;
2813     }
2814
2815   fprintf (src_file, "%s %s\n", marker, asctimestamp (gnupg_get_time ()));
2816   if (ferror (src_file))
2817     goto change_file_one_err;
2818
2819   if (!in_marker)
2820     {
2821       fprintf (src_file, "# %s edited this configuration file.\n",
2822                GPGCONF_DISP_NAME);
2823       if (ferror (src_file))
2824         goto change_file_one_err;
2825       fprintf (src_file, "# It will disable options before this marked "
2826                "block, but it will\n");
2827       if (ferror (src_file))
2828         goto change_file_one_err;
2829       fprintf (src_file, "# never change anything below these lines.\n");
2830       if (ferror (src_file))
2831         goto change_file_one_err;
2832     }
2833   if (dest_file)
2834     {
2835       while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
2836         {
2837           fprintf (src_file, "%s", line);
2838           if (ferror (src_file))
2839             goto change_file_one_err;
2840         }
2841       if (length < 0 || ferror (dest_file))
2842         goto change_file_one_err;
2843     }
2844   xfree (line);
2845   line = NULL;
2846
2847   res = fclose (src_file);
2848   if (res)
2849     {
2850       res = errno;
2851       close (fd);
2852       if (dest_file)
2853         fclose (dest_file);
2854       gpg_err_set_errno (res);
2855       return -1;
2856     }
2857   close (fd);
2858   if (dest_file)
2859     {
2860       res = fclose (dest_file);
2861       if (res)
2862         return -1;
2863     }
2864   return 0;
2865
2866  change_file_one_err:
2867   xfree (line);
2868   res = errno;
2869   if (src_file)
2870     {
2871       fclose (src_file);
2872       close (fd);
2873     }
2874   if (dest_file)
2875     fclose (dest_file);
2876   gpg_err_set_errno (res);
2877   return -1;
2878 }
2879
2880
2881 /* Create and verify the new configuration file for the specified
2882  * backend and component.  Returns 0 on success and -1 on error.  If
2883  * VERBATIM is set the profile mode is used. */
2884 static int
2885 change_options_program (gc_component_t component, gc_backend_t backend,
2886                         char **src_filenamep, char **dest_filenamep,
2887                         char **orig_filenamep,
2888                         int verbatim)
2889 {
2890   static const char marker[] = "###+++--- " GPGCONF_DISP_NAME " ---+++###";
2891   /* True if we are within the marker in the config file.  */
2892   int in_marker = 0;
2893   gc_option_t *option;
2894   char *line = NULL;
2895   size_t line_len;
2896   ssize_t length;
2897   int res;
2898   int fd;
2899   FILE *src_file = NULL;
2900   FILE *dest_file = NULL;
2901   char *src_filename;
2902   char *dest_filename;
2903   char *orig_filename;
2904   /* Special hack for gpg, see below.  */
2905   int utf8strings_seen = 0;
2906
2907   /* FIXME.  Throughout the function, do better error reporting.  */
2908   dest_filename = xstrdup (get_config_filename (component, backend));
2909   src_filename = xasprintf ("%s.%s.%i.new",
2910                             dest_filename, GPGCONF_NAME, (int)getpid ());
2911   orig_filename = xasprintf ("%s.%s.%i.bak",
2912                              dest_filename, GPGCONF_NAME, (int)getpid ());
2913
2914 #ifdef HAVE_W32_SYSTEM
2915   res = copy_file (dest_filename, orig_filename);
2916 #else
2917   res = link (dest_filename, orig_filename);
2918 #endif
2919   if (res < 0 && errno != ENOENT)
2920     {
2921       xfree (dest_filename);
2922       xfree (src_filename);
2923       xfree (orig_filename);
2924       return -1;
2925     }
2926   if (res < 0)
2927     {
2928       xfree (orig_filename);
2929       orig_filename = NULL;
2930     }
2931
2932   /* We now initialize the return strings, so the caller can do the
2933      cleanup for us.  */
2934   *src_filenamep = src_filename;
2935   *dest_filenamep = dest_filename;
2936   *orig_filenamep = orig_filename;
2937
2938   /* Use open() so that we can use O_EXCL.  */
2939   fd = open (src_filename, O_CREAT | O_EXCL | O_WRONLY, 0644);
2940   if (fd < 0)
2941     return -1;
2942   src_file = fdopen (fd, "w");
2943   res = errno;
2944   if (!src_file)
2945     {
2946       gpg_err_set_errno (res);
2947       return -1;
2948     }
2949
2950   /* Only if ORIG_FILENAME is not NULL did the configuration file
2951      exist already.  In this case, we will copy its content into the
2952      new configuration file, changing it to our liking in the
2953      process.  */
2954   if (orig_filename)
2955     {
2956       dest_file = fopen (dest_filename, "r");
2957       if (!dest_file)
2958         goto change_one_err;
2959
2960       while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
2961         {
2962           int disable = 0;
2963           char *start;
2964
2965           if (!strncmp (marker, line, sizeof (marker) - 1))
2966             {
2967               if (!in_marker)
2968                 in_marker = 1;
2969               else
2970                 break;
2971             }
2972           else if (backend == GC_BACKEND_GPG && in_marker
2973                    && ! strcmp ("utf8-strings\n", line))
2974             {
2975               /* Strip duplicated entries.  */
2976               if (utf8strings_seen)
2977                 disable = 1;
2978               else
2979                 utf8strings_seen = 1;
2980             }
2981
2982           start = line;
2983           while (*start == ' ' || *start == '\t')
2984             start++;
2985           if (*start && *start != '\r' && *start != '\n' && *start != '#')
2986             {
2987               char *end;
2988               char saved_end;
2989
2990               end = start;
2991               while (*end && *end != ' ' && *end != '\t'
2992                      && *end != '\r' && *end != '\n' && *end != '#')
2993                 end++;
2994               saved_end = *end;
2995               *end = '\0';
2996
2997               option = find_option (component, start, backend);
2998               *end = saved_end;
2999               if (option && ((option->new_flags & GC_OPT_FLAG_DEFAULT)
3000                              || option->new_value))
3001                 disable = 1;
3002             }
3003           if (disable)
3004             {
3005               if (!in_marker)
3006                 {
3007                   fprintf (src_file,
3008                            "# %s disabled this option here at %s\n",
3009                            GPGCONF_DISP_NAME, asctimestamp (gnupg_get_time ()));
3010                   if (ferror (src_file))
3011                     goto change_one_err;
3012                   fprintf (src_file, "# %s", line);
3013                   if (ferror (src_file))
3014                     goto change_one_err;
3015                 }
3016             }
3017           else
3018             {
3019               fprintf (src_file, "%s", line);
3020               if (ferror (src_file))
3021                 goto change_one_err;
3022             }
3023         }
3024       if (length < 0 || ferror (dest_file))
3025         goto change_one_err;
3026     }
3027
3028   if (!in_marker)
3029     {
3030       /* There was no marker.  This is the first time we edit the
3031          file.  We add our own marker at the end of the file and
3032          proceed.  Note that we first write a newline, this guards us
3033          against files which lack the newline at the end of the last
3034          line, while it doesn't hurt us in all other cases.  */
3035       fprintf (src_file, "\n%s\n", marker);
3036       if (ferror (src_file))
3037         goto change_one_err;
3038     }
3039   /* At this point, we have copied everything up to the end marker
3040      into the new file, except for the options we are going to change.
3041      Now, dump the changed options (except for those we are going to
3042      revert to their default), and write the end marker, possibly
3043      followed by the rest of the original file.  */
3044
3045   /* We have to turn on UTF8 strings for GnuPG.  */
3046   if (backend == GC_BACKEND_GPG && ! utf8strings_seen)
3047     fprintf (src_file, "utf8-strings\n");
3048
3049   option = gc_component[component].options;
3050   while (option->name)
3051     {
3052       if (!(option->flags & GC_OPT_FLAG_GROUP)
3053           && option->backend == backend
3054           && option->new_value)
3055         {
3056           char *arg = option->new_value;
3057
3058           do
3059             {
3060               if (*arg == '\0' || *arg == ',')
3061                 {
3062                   fprintf (src_file, "%s\n", option->name);
3063                   if (ferror (src_file))
3064                     goto change_one_err;
3065                 }
3066               else if (gc_arg_type[option->arg_type].fallback
3067                        == GC_ARG_TYPE_NONE)
3068                 {
3069                   assert (*arg == '1');
3070                   fprintf (src_file, "%s\n", option->name);
3071                   if (ferror (src_file))
3072                     goto change_one_err;
3073
3074                   arg++;
3075                 }
3076               else if (gc_arg_type[option->arg_type].fallback
3077                        == GC_ARG_TYPE_STRING)
3078                 {
3079                   char *end;
3080
3081                   if (!verbatim)
3082                     {
3083                       log_assert (*arg == '"');
3084                       arg++;
3085
3086                       end = strchr (arg, ',');
3087                       if (end)
3088                         *end = '\0';
3089                     }
3090                   else
3091                     end = NULL;
3092
3093                   fprintf (src_file, "%s %s\n", option->name,
3094                            verbatim? arg : percent_deescape (arg));
3095                   if (ferror (src_file))
3096                     goto change_one_err;
3097
3098                   if (end)
3099                     *end = ',';
3100                   arg = end;
3101                 }
3102               else
3103                 {
3104                   char *end;
3105
3106                   end = strchr (arg, ',');
3107                   if (end)
3108                     *end = '\0';
3109
3110                   fprintf (src_file, "%s %s\n", option->name, arg);
3111                   if (ferror (src_file))
3112                     goto change_one_err;
3113
3114                   if (end)
3115                     *end = ',';
3116                   arg = end;
3117                 }
3118
3119               assert (arg == NULL || *arg == '\0' || *arg == ',');
3120               if (arg && *arg == ',')
3121                 arg++;
3122             }
3123           while (arg && *arg);
3124         }
3125       option++;
3126     }
3127
3128   fprintf (src_file, "%s %s\n", marker, asctimestamp (gnupg_get_time ()));
3129   if (ferror (src_file))
3130     goto change_one_err;
3131
3132   if (!in_marker)
3133     {
3134       fprintf (src_file, "# %s edited this configuration file.\n",
3135                GPGCONF_DISP_NAME);
3136       if (ferror (src_file))
3137         goto change_one_err;
3138       fprintf (src_file, "# It will disable options before this marked "
3139                "block, but it will\n");
3140       if (ferror (src_file))
3141         goto change_one_err;
3142       fprintf (src_file, "# never change anything below these lines.\n");
3143       if (ferror (src_file))
3144         goto change_one_err;
3145     }
3146   if (dest_file)
3147     {
3148       while ((length = read_line (dest_file, &line, &line_len, NULL)) > 0)
3149         {
3150           fprintf (src_file, "%s", line);
3151           if (ferror (src_file))
3152             goto change_one_err;
3153         }
3154       if (length < 0 || ferror (dest_file))
3155         goto change_one_err;
3156     }
3157   xfree (line);
3158   line = NULL;
3159
3160   res = fclose (src_file);
3161   if (res)
3162     {
3163       res = errno;
3164       close (fd);
3165       if (dest_file)
3166         fclose (dest_file);
3167       gpg_err_set_errno (res);
3168       return -1;
3169     }
3170   close (fd);
3171   if (dest_file)
3172     {
3173       res = fclose (dest_file);
3174       if (res)
3175         return -1;
3176     }
3177   return 0;
3178
3179  change_one_err:
3180   xfree (line);
3181   res = errno;
3182   if (src_file)
3183     {
3184       fclose (src_file);
3185       close (fd);
3186     }
3187   if (dest_file)
3188     fclose (dest_file);
3189   gpg_err_set_errno (res);
3190   return -1;
3191 }
3192
3193
3194 /* Common code for gc_component_change_options and
3195  * gc_process_gpgconf_conf.  If VERBATIM is set the profile parsing
3196  * mode is used.  */
3197 static void
3198 change_one_value (gc_option_t *option, int *runtime,
3199                   unsigned long flags, char *new_value, int verbatim)
3200 {
3201   unsigned long new_value_nr = 0;
3202
3203   option_check_validity (option, flags, new_value, &new_value_nr, verbatim);
3204
3205   if (option->flags & GC_OPT_FLAG_RUNTIME)
3206     runtime[option->backend] = 1;
3207
3208   option->new_flags = flags;
3209   if (!(flags & GC_OPT_FLAG_DEFAULT))
3210     {
3211       if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE
3212           && (option->flags & GC_OPT_FLAG_LIST))
3213         {
3214           char *str;
3215
3216           /* We convert the number to a list of 1's for convenient
3217              list handling.  */
3218           assert (new_value_nr > 0);
3219           option->new_value = xmalloc ((2 * (new_value_nr - 1) + 1) + 1);
3220           str = option->new_value;
3221           *(str++) = '1';
3222           while (--new_value_nr > 0)
3223             {
3224               *(str++) = ',';
3225               *(str++) = '1';
3226             }
3227           *(str++) = '\0';
3228         }
3229       else
3230         option->new_value = xstrdup (new_value);
3231     }
3232 }
3233
3234
3235 /* Read the modifications from IN and apply them.  If IN is NULL the
3236    modifications are expected to already have been set to the global
3237    table.  If VERBATIM is set the profile mode is used.  */
3238 void
3239 gc_component_change_options (int component, estream_t in, estream_t out,
3240                              int verbatim)
3241 {
3242   int err = 0;
3243   int runtime[GC_BACKEND_NR];
3244   char *src_filename[GC_BACKEND_NR];
3245   char *dest_filename[GC_BACKEND_NR];
3246   char *orig_filename[GC_BACKEND_NR];
3247   gc_backend_t backend;
3248   gc_option_t *option;
3249   char *line = NULL;
3250   size_t line_len = 0;
3251   ssize_t length;
3252
3253   if (component == GC_COMPONENT_PINENTRY)
3254     return; /* Dummy component for now.  */
3255
3256   for (backend = 0; backend < GC_BACKEND_NR; backend++)
3257     {
3258       runtime[backend] = 0;
3259       src_filename[backend] = NULL;
3260       dest_filename[backend] = NULL;
3261       orig_filename[backend] = NULL;
3262     }
3263
3264   if (in)
3265     {
3266       /* Read options from the file IN.  */
3267       while ((length = es_read_line (in, &line, &line_len, NULL)) > 0)
3268         {
3269           char *linep;
3270           unsigned long flags = 0;
3271           char *new_value = "";
3272
3273           /* Strip newline and carriage return, if present.  */
3274           while (length > 0
3275                  && (line[length - 1] == '\n' || line[length - 1] == '\r'))
3276             line[--length] = '\0';
3277
3278           linep = strchr (line, ':');
3279           if (linep)
3280             *(linep++) = '\0';
3281
3282           /* Extract additional flags.  Default to none.  */
3283           if (linep)
3284             {
3285               char *end;
3286               char *tail;
3287
3288               end = strchr (linep, ':');
3289               if (end)
3290                 *(end++) = '\0';
3291
3292               gpg_err_set_errno (0);
3293               flags = strtoul (linep, &tail, 0);
3294               if (errno)
3295                 gc_error (1, errno, "malformed flags in option %s", line);
3296               if (!(*tail == '\0' || *tail == ':' || *tail == ' '))
3297                 gc_error (1, 0, "garbage after flags in option %s", line);
3298
3299               linep = end;
3300             }
3301
3302           /* Don't allow setting of the no change flag.  */
3303           flags &= ~GC_OPT_FLAG_NO_CHANGE;
3304
3305           /* Extract default value, if present.  Default to empty if not.  */
3306           if (linep)
3307             {
3308               char *end;
3309               end = strchr (linep, ':');
3310               if (end)
3311                 *(end++) = '\0';
3312               new_value = linep;
3313               linep = end;
3314             }
3315
3316           option = find_option (component, line, GC_BACKEND_ANY);
3317           if (!option)
3318             gc_error (1, 0, "unknown option %s", line);
3319
3320           if ((option->flags & GC_OPT_FLAG_NO_CHANGE))
3321             {
3322               gc_error (0, 0, "ignoring new value for option %s",
3323                         option->name);
3324               continue;
3325             }
3326
3327           change_one_value (option, runtime, flags, new_value, 0);
3328         }
3329     }
3330
3331   /* Now that we have collected and locally verified the changes,
3332      write them out to new configuration files, verify them
3333      externally, and then commit them.  */
3334   option = gc_component[component].options;
3335   while (option && option->name)
3336     {
3337       /* Go on if we have already seen this backend, or if there is
3338          nothing to do.  */
3339       if (src_filename[option->backend]
3340           || !(option->new_flags || option->new_value))
3341         {
3342           option++;
3343           continue;
3344         }
3345
3346       if (gc_backend[option->backend].program)
3347         {
3348           err = change_options_program (component, option->backend,
3349                                         &src_filename[option->backend],
3350                                         &dest_filename[option->backend],
3351                                         &orig_filename[option->backend],
3352                                         verbatim);
3353           if (! err)
3354             {
3355               /* External verification.  */
3356               err = gc_component_check_options (component, out,
3357                                                 src_filename[option->backend]);
3358               if (err)
3359                 {
3360                   gc_error (0, 0,
3361                             _("External verification of component %s failed"),
3362                             gc_component[component].name);
3363                   gpg_err_set_errno (EINVAL);
3364                 }
3365             }
3366
3367         }
3368       else
3369         err = change_options_file (component, option->backend,
3370                                    &src_filename[option->backend],
3371                                    &dest_filename[option->backend],
3372                                    &orig_filename[option->backend]);
3373
3374       if (err)
3375         break;
3376
3377       option++;
3378     }
3379
3380   if (! err && ! opt.dry_run)
3381     {
3382       int i;
3383
3384       for (i = 0; i < GC_BACKEND_NR; i++)
3385         {
3386           if (src_filename[i])
3387             {
3388               /* FIXME: Make a verification here.  */
3389
3390               assert (dest_filename[i]);
3391
3392               if (orig_filename[i])
3393                 {
3394 #ifdef HAVE_W32_SYSTEM
3395                   /* There is no atomic update on W32.  */
3396                   err = unlink (dest_filename[i]);
3397 #endif /* HAVE_W32_SYSTEM */
3398                   if (!err)
3399                     err = rename (src_filename[i], dest_filename[i]);
3400                 }
3401               else
3402                 {
3403 #ifdef HAVE_W32_SYSTEM
3404                   /* We skip the unlink if we expect the file not to
3405                      be there.  */
3406                   err = rename (src_filename[i], dest_filename[i]);
3407 #else /* HAVE_W32_SYSTEM */
3408                   /* This is a bit safer than rename() because we
3409                      expect DEST_FILENAME not to be there.  If it
3410                      happens to be there, this will fail.  */
3411                   err = link (src_filename[i], dest_filename[i]);
3412                   if (!err)
3413                     err = unlink (src_filename[i]);
3414 #endif /* !HAVE_W32_SYSTEM */
3415                 }
3416               if (err)
3417                 break;
3418               xfree (src_filename[i]);
3419               src_filename[i] = NULL;
3420             }
3421         }
3422     }
3423
3424   if (err || opt.dry_run)
3425     {
3426       int i;
3427       int saved_errno = errno;
3428
3429       /* An error occurred or a dry-run is requested.  */
3430       for (i = 0; i < GC_BACKEND_NR; i++)
3431         {
3432           if (src_filename[i])
3433             {
3434               /* The change was not yet committed.  */
3435               unlink (src_filename[i]);
3436               if (orig_filename[i])
3437                 unlink (orig_filename[i]);
3438             }
3439           else
3440             {
3441               /* The changes were already committed.  FIXME: This is a
3442                  tad dangerous, as we don't know if we don't overwrite
3443                  a version of the file that is even newer than the one
3444                  we just installed.  */
3445               if (orig_filename[i])
3446                 {
3447 #ifdef HAVE_W32_SYSTEM
3448                   /* There is no atomic update on W32.  */
3449                   unlink (dest_filename[i]);
3450 #endif /* HAVE_W32_SYSTEM */
3451                   rename (orig_filename[i], dest_filename[i]);
3452                 }
3453               else
3454                 unlink (dest_filename[i]);
3455             }
3456         }
3457       if (err)
3458         gc_error (1, saved_errno, "could not commit changes");
3459
3460       /* Fall-through for dry run.  */
3461       goto leave;
3462     }
3463
3464   /* If it all worked, notify the daemons of the changes.  */
3465   if (opt.runtime)
3466     for (backend = 0; backend < GC_BACKEND_NR; backend++)
3467       {
3468         if (runtime[backend] && gc_backend[backend].runtime_change)
3469           (*gc_backend[backend].runtime_change) (0);
3470       }
3471
3472   /* Move the per-process backup file into its place.  */
3473   for (backend = 0; backend < GC_BACKEND_NR; backend++)
3474     if (orig_filename[backend])
3475       {
3476         char *backup_filename;
3477
3478         assert (dest_filename[backend]);
3479
3480         backup_filename = xasprintf ("%s.%s.bak",
3481                                      dest_filename[backend], GPGCONF_NAME);
3482
3483 #ifdef HAVE_W32_SYSTEM
3484         /* There is no atomic update on W32.  */
3485         unlink (backup_filename);
3486 #endif /* HAVE_W32_SYSTEM */
3487         rename (orig_filename[backend], backup_filename);
3488         xfree (backup_filename);
3489       }
3490
3491  leave:
3492   xfree (line);
3493   for (backend = 0; backend < GC_BACKEND_NR; backend++)
3494     {
3495       xfree (src_filename[backend]);
3496       xfree (dest_filename[backend]);
3497       xfree (orig_filename[backend]);
3498     }
3499 }
3500
3501
3502 /* Check whether USER matches the current user of one of its group.
3503    This function may change USER.  Returns true is there is a
3504    match.  */
3505 static int
3506 key_matches_user_or_group (char *user)
3507 {
3508   char *group;
3509
3510   if (*user == '*' && user[1] == 0)
3511     return 1; /* A single asterisk matches all users.  */
3512
3513   group = strchr (user, ':');
3514   if (group)
3515     *group++ = 0;
3516
3517 #ifdef HAVE_W32_SYSTEM
3518   /* Under Windows we don't support groups. */
3519   if (group && *group)
3520     gc_error (0, 0, _("Note that group specifications are ignored\n"));
3521 #ifndef HAVE_W32CE_SYSTEM
3522   if (*user)
3523     {
3524       static char *my_name;
3525
3526       if (!my_name)
3527         {
3528           char tmp[1];
3529           DWORD size = 1;
3530
3531           GetUserNameA (tmp, &size);
3532           my_name = xmalloc (size);
3533           if (!GetUserNameA (my_name, &size))
3534             gc_error (1,0, "error getting current user name: %s",
3535                       w32_strerror (-1));
3536         }
3537
3538       if (!strcmp (user, my_name))
3539         return 1; /* Found.  */
3540     }
3541 #endif /*HAVE_W32CE_SYSTEM*/
3542 #else /*!HAVE_W32_SYSTEM*/
3543   /* First check whether the user matches.  */
3544   if (*user)
3545     {
3546       static char *my_name;
3547
3548       if (!my_name)
3549         {
3550           struct passwd *pw = getpwuid ( getuid () );
3551           if (!pw)
3552             gc_error (1, errno, "getpwuid failed for current user");
3553           my_name = xstrdup (pw->pw_name);
3554         }
3555       if (!strcmp (user, my_name))
3556         return 1; /* Found.  */
3557     }
3558
3559   /* If that failed, check whether a group matches.  */
3560   if (group && *group)
3561     {
3562       static char *my_group;
3563       static char **my_supgroups;
3564       int n;
3565
3566       if (!my_group)
3567         {
3568           struct group *gr = getgrgid ( getgid () );
3569           if (!gr)
3570             gc_error (1, errno, "getgrgid failed for current user");
3571           my_group = xstrdup (gr->gr_name);
3572         }
3573       if (!strcmp (group, my_group))
3574         return 1; /* Found.  */
3575
3576       if (!my_supgroups)
3577         {
3578           int ngids;
3579           gid_t *gids;
3580
3581           ngids = getgroups (0, NULL);
3582           gids  = xcalloc (ngids+1, sizeof *gids);
3583           ngids = getgroups (ngids, gids);
3584           if (ngids < 0)
3585             gc_error (1, errno, "getgroups failed for current user");
3586           my_supgroups = xcalloc (ngids+1, sizeof *my_supgroups);
3587           for (n=0; n < ngids; n++)
3588             {
3589               struct group *gr = getgrgid ( gids[n] );
3590               if (!gr)
3591                 gc_error (1, errno, "getgrgid failed for supplementary group");
3592               my_supgroups[n] = xstrdup (gr->gr_name);
3593             }
3594           xfree (gids);
3595         }
3596
3597       for (n=0; my_supgroups[n]; n++)
3598         if (!strcmp (group, my_supgroups[n]))
3599           return 1; /* Found.  */
3600     }
3601 #endif /*!HAVE_W32_SYSTEM*/
3602   return 0; /* No match.  */
3603 }
3604
3605
3606
3607 /* Read and process the global configuration file for gpgconf.  This
3608    optional file is used to update our internal tables at runtime and
3609    may also be used to set new default values.  If FNAME is NULL the
3610    default name will be used.  With UPDATE set to true the internal
3611    tables are actually updated; if not set, only a syntax check is
3612    done.  If DEFAULTS is true the global options are written to the
3613    configuration files.  If LISTFP is set, no changes are done but the
3614    configuration file is printed to LISTFP in a colon separated format.
3615
3616    Returns 0 on success or if the config file is not present; -1 is
3617    returned on error. */
3618 int
3619 gc_process_gpgconf_conf (const char *fname_arg, int update, int defaults,
3620                          estream_t listfp)
3621 {
3622   int result = 0;
3623   char *line = NULL;
3624   size_t line_len = 0;
3625   ssize_t length;
3626   FILE *config;
3627   int lineno = 0;
3628   int in_rule = 0;
3629   int got_match = 0;
3630   int runtime[GC_BACKEND_NR];
3631   int backend_id, component_id;
3632   char *fname;
3633
3634   if (fname_arg)
3635     fname = xstrdup (fname_arg);
3636   else
3637     fname = make_filename (gnupg_sysconfdir (), GPGCONF_NAME EXTSEP_S "conf",
3638                            NULL);
3639
3640   for (backend_id = 0; backend_id < GC_BACKEND_NR; backend_id++)
3641     runtime[backend_id] = 0;
3642
3643   config = fopen (fname, "r");
3644   if (!config)
3645     {
3646       /* Do not print an error if the file is not available, except
3647          when running in syntax check mode.  */
3648       if (errno != ENOENT || !update)
3649         {
3650           gc_error (0, errno, "can not open global config file '%s'", fname);
3651           result = -1;
3652         }
3653       xfree (fname);
3654       return result;
3655     }
3656
3657   while ((length = read_line (config, &line, &line_len, NULL)) > 0)
3658     {
3659       char *key, *component, *option, *flags, *value;
3660       char *empty;
3661       gc_option_t *option_info = NULL;
3662       char *p;
3663       int is_continuation;
3664
3665       lineno++;
3666       key = line;
3667       while (*key == ' ' || *key == '\t')
3668         key++;
3669       if (!*key || *key == '#' || *key == '\r' || *key == '\n')
3670         continue;
3671
3672       is_continuation = (key != line);
3673
3674       /* Parse the key field.  */
3675       if (!is_continuation && got_match)
3676         break;  /* Finish after the first match.  */
3677       else if (!is_continuation)
3678         {
3679           in_rule = 0;
3680           for (p=key+1; *p && !strchr (" \t\r\n", *p); p++)
3681             ;
3682           if (!*p)
3683             {
3684               gc_error (0, 0, "missing rule at '%s', line %d", fname, lineno);
3685               result = -1;
3686               continue;
3687             }
3688           *p++ = 0;
3689           component = p;
3690         }
3691       else if (!in_rule)
3692         {
3693           gc_error (0, 0, "continuation but no rule at '%s', line %d",
3694                     fname, lineno);
3695           result = -1;
3696           continue;
3697         }
3698       else
3699         {
3700           component = key;
3701           key = NULL;
3702         }
3703
3704       in_rule = 1;
3705
3706       /* Parse the component.  */
3707       while (*component == ' ' || *component == '\t')
3708         component++;
3709       for (p=component; *p && !strchr (" \t\r\n", *p); p++)
3710         ;
3711       if (p == component)
3712         {
3713           gc_error (0, 0, "missing component at '%s', line %d",
3714                     fname, lineno);
3715           result = -1;
3716           continue;
3717         }
3718       empty = p;
3719       *p++ = 0;
3720       option = p;
3721       component_id = gc_component_find (component);
3722       if (component_id < 0)
3723         {
3724           gc_error (0, 0, "unknown component at '%s', line %d",
3725                     fname, lineno);
3726           result = -1;
3727         }
3728
3729       /* Parse the option name.  */
3730       while (*option == ' ' || *option == '\t')
3731         option++;
3732       for (p=option; *p && !strchr (" \t\r\n", *p); p++)
3733         ;
3734       if (p == option)
3735         {
3736           gc_error (0, 0, "missing option at '%s', line %d",
3737                     fname, lineno);
3738           result = -1;
3739           continue;
3740         }
3741       *p++ = 0;
3742       flags = p;
3743       if ( component_id != -1)
3744         {
3745           option_info = find_option (component_id, option, GC_BACKEND_ANY);
3746           if (!option_info)
3747             {
3748               gc_error (0, 0, "unknown option at '%s', line %d",
3749                         fname, lineno);
3750               result = -1;
3751             }
3752         }
3753
3754
3755       /* Parse the optional flags.  */
3756       while (*flags == ' ' || *flags == '\t')
3757         flags++;
3758       if (*flags == '[')
3759         {
3760           flags++;
3761           p = strchr (flags, ']');
3762           if (!p)
3763             {
3764               gc_error (0, 0, "syntax error in rule at '%s', line %d",
3765                         fname, lineno);
3766               result = -1;
3767               continue;
3768             }
3769           *p++ = 0;
3770           value = p;
3771         }
3772       else  /* No flags given.  */
3773         {
3774           value = flags;
3775           flags = NULL;
3776         }
3777
3778       /* Parse the optional value.  */
3779       while (*value == ' ' || *value == '\t')
3780        value++;
3781       for (p=value; *p && !strchr ("\r\n", *p); p++)
3782         ;
3783       if (p == value)
3784         value = empty; /* No value given; let it point to an empty string.  */
3785       else
3786         {
3787           /* Strip trailing white space.  */
3788           *p = 0;
3789           for (p--; p > value && (*p == ' ' || *p == '\t'); p--)
3790             *p = 0;
3791         }
3792
3793       /* Check flag combinations.  */
3794       if (!flags)
3795         ;
3796       else if (!strcmp (flags, "default"))
3797         {
3798           if (*value)
3799             {
3800               gc_error (0, 0, "flag \"default\" may not be combined "
3801                         "with a value at '%s', line %d",
3802                         fname, lineno);
3803               result = -1;
3804             }
3805         }
3806       else if (!strcmp (flags, "change"))
3807         ;
3808       else if (!strcmp (flags, "no-change"))
3809         ;
3810       else
3811         {
3812           gc_error (0, 0, "unknown flag at '%s', line %d",
3813                     fname, lineno);
3814           result = -1;
3815         }
3816
3817       /* In list mode we print out all records.  */
3818       if (listfp && !result)
3819         {
3820           /* If this is a new ruleset, print a key record.  */
3821           if (!is_continuation)
3822             {
3823               char *group = strchr (key, ':');
3824               if (group)
3825                 {
3826                   *group++ = 0;
3827                   if ((p = strchr (group, ':')))
3828                     *p = 0; /* We better strip any extra stuff. */
3829                 }
3830
3831               es_fprintf (listfp, "k:%s:", gc_percent_escape (key));
3832               es_fprintf (listfp, "%s\n", group? gc_percent_escape (group):"");
3833             }
3834
3835           /* All other lines are rule records.  */
3836           es_fprintf (listfp, "r:::%s:%s:%s:",
3837                       gc_component[component_id].name,
3838                       option_info->name? option_info->name : "",
3839                       flags? flags : "");
3840           if (value != empty)
3841             es_fprintf (listfp, "\"%s", gc_percent_escape (value));
3842
3843           es_putc ('\n', listfp);
3844         }
3845
3846       /* Check whether the key matches but do this only if we are not
3847          running in syntax check mode. */
3848       if ( update
3849            && !result && !listfp
3850            && (got_match || (key && key_matches_user_or_group (key))) )
3851         {
3852           int newflags = 0;
3853
3854           got_match = 1;
3855
3856           /* Apply the flags from gpgconf.conf.  */
3857           if (!flags)
3858             ;
3859           else if (!strcmp (flags, "default"))
3860             newflags |= GC_OPT_FLAG_DEFAULT;
3861           else if (!strcmp (flags, "no-change"))
3862             option_info->flags |= GC_OPT_FLAG_NO_CHANGE;
3863           else if (!strcmp (flags, "change"))
3864             option_info->flags &= ~GC_OPT_FLAG_NO_CHANGE;
3865
3866           if (defaults)
3867             {
3868               /* Here we explicitly allow updating the value again.  */
3869               if (newflags)
3870                 {
3871                   option_info->new_flags = 0;
3872                 }
3873               if (*value)
3874                 {
3875                   xfree (option_info->new_value);
3876                   option_info->new_value = NULL;
3877                 }
3878               change_one_value (option_info, runtime, newflags, value, 0);
3879             }
3880         }
3881     }
3882
3883   if (length < 0 || ferror (config))
3884     {
3885       gc_error (0, errno, "error reading from '%s'", fname);
3886       result = -1;
3887     }
3888   if (fclose (config))
3889     gc_error (0, errno, "error closing '%s'", fname);
3890
3891   xfree (line);
3892
3893   /* If it all worked, process the options. */
3894   if (!result && update && defaults && !listfp)
3895     {
3896       /* We need to switch off the runtime update, so that we can do
3897          it later all at once. */
3898       int save_opt_runtime = opt.runtime;
3899       opt.runtime = 0;
3900
3901       for (component_id = 0; component_id < GC_COMPONENT_NR; component_id++)
3902         {
3903           gc_component_change_options (component_id, NULL, NULL, 0);
3904         }
3905       opt.runtime = save_opt_runtime;
3906
3907       if (opt.runtime)
3908         {
3909           for (backend_id = 0; backend_id < GC_BACKEND_NR; backend_id++)
3910             if (runtime[backend_id] && gc_backend[backend_id].runtime_change)
3911               (*gc_backend[backend_id].runtime_change) (0);
3912         }
3913     }
3914
3915   xfree (fname);
3916   return result;
3917 }
3918
3919
3920 /*
3921  * Apply the profile FNAME to all known configure files.
3922  */
3923 gpg_error_t
3924 gc_apply_profile (const char *fname)
3925 {
3926   gpg_error_t err;
3927   char *fname_buffer = NULL;
3928   char *line = NULL;
3929   size_t line_len = 0;
3930   ssize_t length;
3931   estream_t fp;
3932   int lineno = 0;
3933   int runtime[GC_BACKEND_NR];
3934   int backend_id;
3935   int component_id = -1;
3936   int skip_section = 0;
3937   int error_count = 0;
3938   int newflags;
3939
3940   if (!fname)
3941     fname = "-";
3942
3943   for (backend_id = 0; backend_id < GC_BACKEND_NR; backend_id++)
3944     runtime[backend_id] = 0;
3945
3946
3947   if (!(!strcmp (fname, "-")
3948         || strchr (fname, '/')
3949 #ifdef HAVE_W32_SYSTEM
3950         || strchr (fname, '\\')
3951 #endif
3952         || strchr (fname, '.')))
3953     {
3954       /* FNAME looks like a standard profile name.  Check whether one
3955        * is installed and use that instead of the given file name.  */
3956       fname_buffer = xstrconcat (gnupg_datadir (), DIRSEP_S,
3957                                  fname, ".prf", NULL);
3958       if (!access (fname_buffer, F_OK))
3959         fname = fname_buffer;
3960     }
3961
3962   fp = !strcmp (fname, "-")? es_stdin : es_fopen (fname, "r");
3963   if (!fp)
3964     {
3965       err = gpg_error_from_syserror ();
3966       log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
3967       return err;
3968     }
3969
3970   if (opt.verbose)
3971     log_info ("applying profile '%s'\n", fname);
3972
3973   err = 0;
3974   while ((length = es_read_line (fp, &line, &line_len, NULL)) > 0)
3975     {
3976       char *name, *flags, *value;
3977       gc_option_t *option_info = NULL;
3978       char *p;
3979
3980       lineno++;
3981       name = line;
3982       while (*name == ' ' || *name == '\t')
3983         name++;
3984       if (!*name || *name == '#' || *name == '\r' || *name == '\n')
3985         continue;
3986       trim_trailing_spaces (name);
3987
3988       /* Check whether this is a new section.  */
3989       if (*name == '[')
3990         {
3991           name++;
3992           skip_section = 0;
3993           /* New section: Get the name of the component.  */
3994           p = strchr (name, ']');
3995           if (!p)
3996             {
3997               error_count++;
3998               log_info ("%s:%d:%d: error: syntax error in section tag\n",
3999                         fname, lineno, (int)(name - line));
4000               skip_section = 1;
4001               continue;
4002             }
4003           *p++ = 0;
4004           if (*p)
4005             log_info ("%s:%d:%d: warning: garbage after section tag\n",
4006                       fname, lineno, (int)(p - line));
4007
4008           trim_spaces (name);
4009           component_id = gc_component_find (name);
4010           if (component_id < 0)
4011             {
4012               log_info ("%s:%d:%d: warning: skipping unknown section '%s'\n",
4013                         fname, lineno, (int)(name - line), name );
4014               skip_section = 1;
4015             }
4016           continue;
4017         }
4018
4019       if (skip_section)
4020         continue;
4021       if (component_id < 0)
4022         {
4023           error_count++;
4024           log_info ("%s:%d:%d: error: not in a valid section\n",
4025                     fname, lineno, (int)(name - line));
4026           skip_section = 1;
4027           continue;
4028         }
4029
4030       /* Parse the option name.  */
4031       for (p = name; *p && !spacep (p); p++)
4032         ;
4033       *p++ = 0;
4034       value = p;
4035
4036       option_info = find_option (component_id, name, GC_BACKEND_ANY);
4037       if (!option_info)
4038         {
4039           error_count++;
4040           log_info ("%s:%d:%d: error: unknown option '%s' in section '%s'\n",
4041                     fname, lineno, (int)(name - line),
4042                     name, gc_component[component_id].name);
4043           continue;
4044         }
4045
4046       /* Parse the optional flags. */
4047       trim_spaces (value);
4048       flags = value;
4049       if (*flags == '[')
4050         {
4051           flags++;
4052           p = strchr (flags, ']');
4053           if (!p)
4054             {
4055               log_info ("%s:%d:%d: warning: invalid flag specification\n",
4056                         fname, lineno, (int)(p - line));
4057               continue;
4058             }
4059           *p++ = 0;
4060           value = p;
4061           trim_spaces (value);
4062         }
4063       else /* No flags given.  */
4064         flags = NULL;
4065
4066       /* Set required defaults.  */
4067       if (gc_arg_type[option_info->arg_type].fallback == GC_ARG_TYPE_NONE
4068           && !*value)
4069         value = "1";
4070
4071       /* Check and save this option.  */
4072       newflags = 0;
4073       if (flags && !strcmp (flags, "default"))
4074         newflags |= GC_OPT_FLAG_DEFAULT;
4075
4076       if (newflags)
4077         option_info->new_flags = 0;
4078       if (*value)
4079         {
4080           xfree (option_info->new_value);
4081           option_info->new_value = NULL;
4082         }
4083       change_one_value (option_info, runtime, newflags, value, 1);
4084     }
4085
4086   if (length < 0 || es_ferror (fp))
4087     {
4088       err = gpg_error_from_syserror ();
4089       error_count++;
4090       log_error (_("%s:%u: read error: %s\n"),
4091                  fname, lineno, gpg_strerror (err));
4092     }
4093   if (es_fclose (fp))
4094     log_error (_("error closing '%s'\n"), fname);
4095   if (error_count)
4096     log_error (_("error parsing '%s'\n"), fname);
4097
4098   xfree (line);
4099
4100   /* If it all worked, process the options. */
4101   if (!err)
4102     {
4103       /* We need to switch off the runtime update, so that we can do
4104          it later all at once. */
4105       int save_opt_runtime = opt.runtime;
4106       opt.runtime = 0;
4107
4108       for (component_id = 0; component_id < GC_COMPONENT_NR; component_id++)
4109         {
4110           gc_component_change_options (component_id, NULL, NULL, 1);
4111         }
4112       opt.runtime = save_opt_runtime;
4113
4114       if (opt.runtime)
4115         {
4116           for (backend_id = 0; backend_id < GC_BACKEND_NR; backend_id++)
4117             if (runtime[backend_id] && gc_backend[backend_id].runtime_change)
4118               (*gc_backend[backend_id].runtime_change) (0);
4119         }
4120     }
4121
4122   xfree (fname_buffer);
4123   return err;
4124 }