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