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