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