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