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