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