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