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