Bump to 2.4.3
[platform/upstream/gpg2.git] / dirmngr / dirmngr.c
1 /* dirmngr.c - Keyserver and X.509 LDAP access
2  * Copyright (C) 2002 Klarälvdalens Datakonsult AB
3  * Copyright (C) 2003-2004, 2006-2007, 2008, 2010-2011, 2020 g10 Code GmbH
4  * Copyright (C) 2014 Werner Koch
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  * SPDX-License-Identifier: GPL-3.0-or-later
21  */
22
23 #include <config.h>
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stddef.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <assert.h>
32 #include <time.h>
33 #include <fcntl.h>
34 #ifndef HAVE_W32_SYSTEM
35 #include <sys/socket.h>
36 #include <sys/un.h>
37 #endif
38 #include <sys/stat.h>
39 #include <unistd.h>
40 #ifdef HAVE_SIGNAL_H
41 # include <signal.h>
42 #endif
43 #ifdef HAVE_INOTIFY_INIT
44 # include <sys/inotify.h>
45 #endif /*HAVE_INOTIFY_INIT*/
46 #include <npth.h>
47
48 #include "dirmngr-err.h"
49
50 #if  HTTP_USE_NTBTLS
51 # include <ntbtls.h>
52 #elif HTTP_USE_GNUTLS
53 # include <gnutls/gnutls.h>
54 #endif /*HTTP_USE_GNUTLS*/
55
56
57 #define INCLUDED_BY_MAIN_MODULE 1
58 #define GNUPG_COMMON_NEED_AFLOCAL
59 #include "dirmngr.h"
60
61 #include <assuan.h>
62
63 #include "certcache.h"
64 #include "crlcache.h"
65 #include "crlfetch.h"
66 #include "misc.h"
67 #if USE_LDAP
68 # include "ldapserver.h"
69 #endif
70 #include "../common/asshelp.h"
71 #if USE_LDAP
72 # include "ldap-wrapper.h"
73 #endif
74 #include "../common/comopt.h"
75 #include "../common/init.h"
76 #include "../common/gc-opt-flags.h"
77 #include "dns-stuff.h"
78 #include "http-common.h"
79
80 #ifndef ENAMETOOLONG
81 # define ENAMETOOLONG EINVAL
82 #endif
83
84
85 enum cmd_and_opt_values {
86   aNull = 0,
87   oCsh            = 'c',
88   oQuiet          = 'q',
89   oSh             = 's',
90   oVerbose        = 'v',
91   oNoVerbose = 500,
92
93   aServer,
94   aDaemon,
95   aSupervised,
96   aListCRLs,
97   aLoadCRL,
98   aFetchCRL,
99   aShutdown,
100   aFlush,
101   aGPGConfList,
102   aGPGConfTest,
103   aGPGConfVersions,
104
105   oOptions,
106   oDebug,
107   oDebugAll,
108   oDebugWait,
109   oDebugLevel,
110   oGnutlsDebug,
111   oDebugCacheExpiredCerts,
112   oNoGreeting,
113   oNoOptions,
114   oHomedir,
115   oNoDetach,
116   oLogFile,
117   oBatch,
118   oDisableHTTP,
119   oDisableLDAP,
120   oDisableIPv4,
121   oDisableIPv6,
122   oIgnoreLDAPDP,
123   oIgnoreHTTPDP,
124   oIgnoreOCSPSvcUrl,
125   oHonorHTTPProxy,
126   oHTTPProxy,
127   oLDAPProxy,
128   oOnlyLDAPProxy,
129   oLDAPServer,
130   oLDAPFile,
131   oLDAPTimeout,
132   oLDAPAddServers,
133   oOCSPResponder,
134   oOCSPSigner,
135   oOCSPMaxClockSkew,
136   oOCSPMaxPeriod,
137   oOCSPCurrentPeriod,
138   oMaxReplies,
139   oHkpCaCert,
140   oFakedSystemTime,
141   oForce,
142   oAllowOCSP,
143   oAllowVersionCheck,
144   oStealSocket,
145   oSocketName,
146   oLDAPWrapperProgram,
147   oHTTPWrapperProgram,
148   oIgnoreCert,
149   oIgnoreCertExtension,
150   oIgnoreCRLExtension,
151   oUseTor,
152   oNoUseTor,
153   oKeyServer,
154   oNameServer,
155   oDisableCheckOwnSocket,
156   oStandardResolver,
157   oRecursiveResolver,
158   oResolverTimeout,
159   oConnectTimeout,
160   oConnectQuickTimeout,
161   oListenBacklog,
162   oFakeCRL,
163   oCompatibilityFlags,
164   aTest
165 };
166
167
168
169 static gpgrt_opt_t opts[] = {
170
171   ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
172   ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
173   ARGPARSE_c (aGPGConfVersions, "gpgconf-versions", "@"),
174
175   ARGPARSE_group (300, N_("@Commands:\n ")),
176
177   ARGPARSE_c (aServer,   "server",  N_("run in server mode (foreground)") ),
178   ARGPARSE_c (aDaemon,   "daemon",  N_("run in daemon mode (background)") ),
179 #ifndef HAVE_W32_SYSTEM
180   ARGPARSE_c (aSupervised,  "supervised", "@"),
181 #endif
182   ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")),
183   ARGPARSE_c (aLoadCRL,  "load-crl", N_("|FILE|load CRL from FILE into cache")),
184   ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")),
185   ARGPARSE_c (aShutdown, "shutdown",  N_("shutdown the dirmngr")),
186   ARGPARSE_c (aFlush,    "flush",     N_("flush the cache")),
187
188
189   ARGPARSE_header (NULL, N_("Options used for startup")),
190
191   ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
192   ARGPARSE_s_n (oSh,       "sh",        N_("sh-style command output")),
193   ARGPARSE_s_n (oCsh,      "csh",       N_("csh-style command output")),
194   ARGPARSE_s_n (oStealSocket, "steal-socket", "@"),
195   ARGPARSE_s_s (oHomedir, "homedir", "@"),
196   ARGPARSE_conffile (oOptions,  "options", N_("|FILE|read options from FILE")),
197   ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
198
199
200   ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
201
202   ARGPARSE_s_n (oVerbose,  "verbose",   N_("verbose")),
203   ARGPARSE_s_n (oQuiet,    "quiet",     N_("be somewhat more quiet")),
204   ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
205   ARGPARSE_s_s (oDebugLevel, "debug-level",
206                 N_("|LEVEL|set the debugging level to LEVEL")),
207   ARGPARSE_s_s (oDebug,    "debug", "@"),
208   ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
209   ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"),
210   ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"),
211   ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
212   ARGPARSE_s_s (oLogFile,  "log-file",
213                 N_("|FILE|write server mode logs to FILE")),
214
215
216   ARGPARSE_header ("Configuration",
217                    N_("Options controlling the configuration")),
218
219   ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check",
220                 N_("allow online software version check")),
221   ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
222   ARGPARSE_s_i (oMaxReplies, "max-replies",
223                 N_("|N|do not return more than N items in one query")),
224   ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/
225   ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
226   ARGPARSE_s_s (oIgnoreCert,"ignore-cert", "@"),
227   ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"),
228   ARGPARSE_s_s (oIgnoreCRLExtension,"ignore-crl-extension", "@"),
229
230
231   ARGPARSE_header ("Network", N_("Network related options")),
232
233   ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")),
234   ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"),
235   ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"),
236   ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"),
237   ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"),
238   ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"),
239   ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"),
240   ARGPARSE_s_s (oNameServer, "nameserver", "@"),
241   ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"),
242   ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"),
243
244
245   ARGPARSE_header ("HTTP", N_("Configuration for HTTP servers")),
246
247   ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")),
248   ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp",
249                 N_("ignore HTTP CRL distribution points")),
250   ARGPARSE_s_s (oHTTPProxy,  "http-proxy",
251                 N_("|URL|redirect all HTTP requests to URL")),
252   ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy",
253                 N_("use system's HTTP proxy setting")),
254   ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"),
255
256   ARGPARSE_header ("Keyserver", N_("Configuration for OpenPGP servers")),
257
258   ARGPARSE_s_s (oKeyServer, "keyserver",
259                 N_("|URL|use keyserver at URL")),
260   ARGPARSE_s_s (oHkpCaCert, "hkp-cacert",
261                 N_("|FILE|use the CA certificates in FILE for HKP over TLS")),
262
263   ARGPARSE_header ("LDAP", N_("Configuration for X.509 servers")),
264
265   ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")),
266   ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp",
267                 N_("ignore LDAP CRL distribution points")),
268   ARGPARSE_s_s (oLDAPProxy,  "ldap-proxy",
269                 N_("|HOST|use HOST for LDAP queries")),
270   ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy",
271                 N_("do not use fallback hosts with --ldap-proxy")),
272   ARGPARSE_s_s (oLDAPServer, "ldapserver",
273                 N_("|SPEC|use this keyserver to lookup keys")),
274   ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file",
275                 N_("|FILE|read LDAP server list from FILE")),
276   ARGPARSE_s_n (oLDAPAddServers, "add-servers",
277                 N_("add new servers discovered in CRL distribution"
278                    " points to serverlist")),
279   ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout",
280                 N_("|N|set LDAP timeout to N seconds")),
281   ARGPARSE_s_s (oFakeCRL, "fake-crl", "@"),
282
283   ARGPARSE_header ("OCSP", N_("Configuration for OCSP")),
284
285   ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")),
286   ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url",
287                 N_("ignore certificate contained OCSP service URLs")),
288   ARGPARSE_s_s (oOCSPResponder, "ocsp-responder",
289                 N_("|URL|use OCSP responder at URL")),
290   ARGPARSE_s_s (oOCSPSigner, "ocsp-signer",
291                 N_("|FPR|OCSP response signed by FPR")),
292   ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"),
293   ARGPARSE_s_i (oOCSPMaxPeriod,    "ocsp-max-period", "@"),
294   ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"),
295
296
297   ARGPARSE_header (NULL, N_("Other options")),
298
299   ARGPARSE_s_n (oForce,    "force",    N_("force loading of outdated CRLs")),
300
301   ARGPARSE_s_s (oSocketName, "socket-name", "@"),  /* Only for debugging.  */
302   ARGPARSE_s_n (oDebugCacheExpiredCerts, "debug-cache-expired-certs", "@"),
303   ARGPARSE_s_s (oCompatibilityFlags, "compatibility-flags", "@"),
304
305   ARGPARSE_header (NULL, ""),  /* Stop the header group.  */
306
307   /* Not yet used options.  */
308   ARGPARSE_s_n (oBatch,    "batch",       "@"),
309   ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"),
310
311
312   ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing "
313                          "of all commands and options)\n")),
314
315   ARGPARSE_end ()
316 };
317
318 /* The list of supported debug flags.  */
319 static struct debug_flags_s debug_flags [] =
320   {
321     { DBG_X509_VALUE   , "x509"    },
322     { DBG_CRYPTO_VALUE , "crypto"  },
323     { DBG_MEMORY_VALUE , "memory"  },
324     { DBG_CACHE_VALUE  , "cache"   },
325     { DBG_MEMSTAT_VALUE, "memstat" },
326     { DBG_HASHING_VALUE, "hashing" },
327     { DBG_IPC_VALUE    , "ipc"     },
328     { DBG_DNS_VALUE    , "dns"     },
329     { DBG_NETWORK_VALUE, "network" },
330     { DBG_LOOKUP_VALUE , "lookup"  },
331     { DBG_EXTPROG_VALUE, "extprog" },
332     { DBG_KEEPTMP_VALUE, "keeptmp" },
333     { 77, NULL } /* 77 := Do not exit on "help" or "?".  */
334   };
335
336 /* The list of compatibility flags.  */
337 static struct compatibility_flags_s compatibility_flags [] =
338   {
339     { COMPAT_RESTRICT_HTTP_REDIR, "restrict-http-redir" },
340     { 0, NULL }
341   };
342
343
344 #define DEFAULT_MAX_REPLIES 10
345 #define DEFAULT_LDAP_TIMEOUT 15  /* seconds */
346
347 #define DEFAULT_CONNECT_TIMEOUT       (15*1000)  /* 15 seconds */
348 #define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000)  /*  2 seconds */
349
350 /* For the cleanup handler we need to keep track of the socket's name.  */
351 static const char *socket_name;
352 /* If the socket has been redirected, this is the name of the
353    redirected socket..  */
354 static const char *redir_socket_name;
355
356 /* We need to keep track of the server's nonces (these are dummies for
357    POSIX systems). */
358 static assuan_sock_nonce_t socket_nonce;
359
360 /* Value for the listen() backlog argument.
361  * Change at runtime with --listen-backlog.  */
362 static int listen_backlog = 64;
363
364 /* Only if this flag has been set will we remove the socket file.  */
365 static int cleanup_socket;
366
367 /* Keep track of the current log file so that we can avoid updating
368    the log file after a SIGHUP if it didn't changed. Malloced. */
369 static char *current_logfile;
370
371 /* Helper to implement --debug-level. */
372 static const char *debug_level;
373
374 /* Helper to set the NTBTLS or GNUTLS log level.  */
375 static int opt_gnutls_debug = -1;
376
377 /* Flag indicating that a shutdown has been requested.  */
378 static volatile int shutdown_pending;
379
380 /* Flags to indicate that we shall not watch our own socket. */
381 static int disable_check_own_socket;
382
383 /* Flag indicating to start the daemon even if one already runs.  */
384 static int steal_socket;
385
386
387 /* Flag to control the Tor mode.  */
388 static enum
389   { TOR_MODE_AUTO = 0,  /* Switch to NO or YES         */
390     TOR_MODE_NEVER,     /* Never use Tor.              */
391     TOR_MODE_NO,        /* Do not use Tor              */
392     TOR_MODE_YES,       /* Use Tor                     */
393     TOR_MODE_FORCE      /* Force using Tor             */
394   } tor_mode;
395
396
397 /* Counter for the active connections.  */
398 static int active_connections;
399
400 /* This flag is set by any network access and used by the housekeeping
401  * thread to run background network tasks.  */
402 static int network_activity_seen;
403
404 /* A list of filenames registered with --hkp-cacert.  */
405 static strlist_t hkp_cacert_filenames;
406
407 /* A flag used to clear the list of ldapservers iff --ldapserver is
408  * given on the command line or one of the conf files. In this case we
409  * want to clear all old specifications through the legacy
410  * dirmngr_ldapservers.conf. */
411 static int ldapserver_list_needs_reset;
412
413 /* The timer tick used for housekeeping stuff.  The second constant is used when a shutdown is pending.  */
414 #define TIMERTICK_INTERVAL           (60)
415 #define TIMERTICK_INTERVAL_SHUTDOWN  (4)
416
417 /* How oft to run the housekeeping.  */
418 #define HOUSEKEEPING_INTERVAL      (600)
419
420
421 /* This union is used to avoid compiler warnings in case a pointer is
422    64 bit and an int 32 bit.  We store an integer in a pointer and get
423    it back later (npth_getspecific et al.).  */
424 union int_and_ptr_u
425 {
426   int  aint;
427   assuan_fd_t afd;
428   void *aptr;
429 };
430
431
432
433 /* The key used to store the current file descriptor in the thread
434    local storage.  We use this in conjunction with the
435    log_set_pid_suffix_cb feature.  */
436 #ifndef HAVE_W32_SYSTEM
437 static npth_key_t my_tlskey_current_fd;
438 #endif
439
440 /* Prototypes. */
441 static void cleanup (void);
442 #if USE_LDAP
443 static ldap_server_t parse_ldapserver_file (const char* filename, int ienoent);
444 #endif /*USE_LDAP*/
445 static fingerprint_list_t parse_fingerprint_item (const char *string,
446                                                   const  char *optionname,
447                                                   int want_binary);
448 static void netactivity_action (void);
449 static void handle_connections (assuan_fd_t listen_fd);
450 static void gpgconf_versions (void);
451
452
453 /* NPth wrapper function definitions. */
454 ASSUAN_SYSTEM_NPTH_IMPL;
455
456 static const char *
457 my_strusage( int level )
458 {
459   const char *p;
460   switch ( level )
461     {
462     case  9: p = "GPL-3.0-or-later"; break;
463     case 11: p = "@DIRMNGR@ (@GNUPG@)";
464       break;
465     case 13: p = VERSION; break;
466     case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
467     case 17: p = PRINTABLE_OS_NAME; break;
468       /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
469          reporting address.  This is so that we can change the
470          reporting address without breaking the translations.  */
471     case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
472     case 49: p = PACKAGE_BUGREPORT; break;
473     case 1:
474     case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)");
475       break;
476     case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n"
477                    "Keyserver, CRL, and OCSP access for @GNUPG@\n");
478       break;
479
480     default: p = NULL;
481     }
482   return p;
483 }
484
485
486 /* Callback from libksba to hash a provided buffer.  Our current
487    implementation does only allow SHA-1 for hashing. This may be
488    extended by mapping the name, testing for algorithm availability
489    and adjust the length checks accordingly. */
490 static gpg_error_t
491 my_ksba_hash_buffer (void *arg, const char *oid,
492                      const void *buffer, size_t length, size_t resultsize,
493                      unsigned char *result, size_t *resultlen)
494 {
495   (void)arg;
496
497   if (oid && strcmp (oid, "1.3.14.3.2.26"))
498     return gpg_error (GPG_ERR_NOT_SUPPORTED);
499   if (resultsize < 20)
500     return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
501   gcry_md_hash_buffer (2, result, buffer, length);
502   *resultlen = 20;
503   return 0;
504 }
505
506
507 /* GNUTLS log function callback.  */
508 #ifdef HTTP_USE_GNUTLS
509 static void
510 my_gnutls_log (int level, const char *text)
511 {
512   int n;
513
514   n = strlen (text);
515   while (n && text[n-1] == '\n')
516     n--;
517
518   log_debug ("gnutls:L%d: %.*s\n", level, n, text);
519 }
520 #endif /*HTTP_USE_GNUTLS*/
521
522 /* Setup the debugging.  With a LEVEL of NULL only the active debug
523    flags are propagated to the subsystems.  With LEVEL set, a specific
524    set of debug flags is set; thus overriding all flags already
525    set. */
526 static void
527 set_debug (void)
528 {
529   int numok = (debug_level && digitp (debug_level));
530   int numlvl = numok? atoi (debug_level) : 0;
531
532   if (!debug_level)
533     ;
534   else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
535     opt.debug = 0;
536   else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
537     opt.debug = DBG_IPC_VALUE;
538   else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
539     opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE);
540   else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
541     opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE
542                  |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
543   else if (!strcmp (debug_level, "guru") || numok)
544     {
545       opt.debug = ~0;
546       /* Unless the "guru" string has been used we don't want to allow
547          hashing debugging.  The rationale is that people tend to
548          select the highest debug value and would then clutter their
549          disk with debug files which may reveal confidential data.  */
550       if (numok)
551         opt.debug &= ~(DBG_HASHING_VALUE|DBG_KEEPTMP_VALUE);
552     }
553   else
554     {
555       log_error (_("invalid debug-level '%s' given\n"), debug_level);
556       log_info (_("valid debug levels are: %s\n"),
557                 "none, basic, advanced, expert, guru");
558       opt.debug = 0; /* Reset debugging, so that prior debug
559                         statements won't have an undesired effect. */
560     }
561
562
563   if (opt.debug && !opt.verbose)
564     {
565       opt.verbose = 1;
566       gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
567     }
568   if (opt.debug && opt.quiet)
569     opt.quiet = 0;
570
571   if (opt.debug & DBG_CRYPTO_VALUE )
572     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
573
574 #if HTTP_USE_NTBTLS
575   if (opt_gnutls_debug >= 0)
576     {
577       ntbtls_set_debug (opt_gnutls_debug, NULL, NULL);
578     }
579 #elif HTTP_USE_GNUTLS
580   if (opt_gnutls_debug >= 0)
581     {
582       gnutls_global_set_log_function (my_gnutls_log);
583       gnutls_global_set_log_level (opt_gnutls_debug);
584     }
585 #endif /*HTTP_USE_GNUTLS*/
586
587   if (opt.debug)
588     parse_debug_flag (NULL, &opt.debug, debug_flags);
589 }
590
591
592 static void
593 set_tor_mode (void)
594 {
595   if (dirmngr_use_tor ())
596     {
597       /* Enable Tor mode and when called again force a new circuit
598        * (e.g. on SIGHUP).  */
599       enable_dns_tormode (1);
600       if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
601         {
602           log_error ("error enabling Tor mode: %s\n", strerror (errno));
603           log_info ("(is your Libassuan recent enough?)\n");
604         }
605     }
606   else
607     disable_dns_tormode ();
608 }
609
610
611 /* Return true if Tor shall be used.  */
612 int
613 dirmngr_use_tor (void)
614 {
615   if (tor_mode == TOR_MODE_AUTO)
616     {
617       /* Figure out whether Tor is running.  */
618       assuan_fd_t sock;
619
620       sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR);
621       if (sock == ASSUAN_INVALID_FD)
622         tor_mode = TOR_MODE_NO;
623       else
624         {
625           tor_mode = TOR_MODE_YES;
626           assuan_sock_close (sock);
627         }
628     }
629
630   if (tor_mode == TOR_MODE_FORCE)
631     return 2; /* Use Tor (using 2 to indicate force mode) */
632   else if (tor_mode == TOR_MODE_YES)
633     return 1; /* Use Tor */
634   else
635     return 0; /* Do not use Tor.  */
636 }
637
638
639 /* This is somewhat similar to dirmngr_use_tor but avoids a trial
640  * connect and may thus be faster for this special case.  */
641 int
642 dirmngr_never_use_tor_p (void)
643 {
644   return tor_mode == TOR_MODE_NEVER;
645 }
646
647
648 static void
649 wrong_args (const char *text)
650 {
651   es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME);
652   es_fputs (text, es_stderr);
653   es_putc ('\n', es_stderr);
654   dirmngr_exit (2);
655 }
656
657
658 /* Helper to stop the reaper thread for the ldap wrapper.  */
659 static void
660 shutdown_reaper (void)
661 {
662 #if USE_LDAP
663   ldap_wrapper_wait_connections ();
664 #endif
665 }
666
667
668 /* Handle options which are allowed to be reset after program start.
669    Return true if the current option in PARGS could be handled and
670    false if not.  As a special feature, passing a value of NULL for
671    PARGS, resets the options to the default.  REREAD should be set
672    true if it is not the initial option parsing. */
673 static int
674 parse_rereadable_options (gpgrt_argparse_t *pargs, int reread)
675 {
676   if (!pargs)
677     { /* Reset mode. */
678       opt.quiet = 0;
679       opt.verbose = 0;
680       opt.debug = 0;
681       opt.ldap_wrapper_program = NULL;
682       opt.disable_http = 0;
683       opt.disable_ldap = 0;
684       opt.honor_http_proxy = 0;
685       opt.http_proxy = NULL;
686       opt.ldap_proxy = NULL;
687       opt.only_ldap_proxy = 0;
688       opt.ignore_http_dp = 0;
689       opt.ignore_ldap_dp = 0;
690       opt.ignore_ocsp_service_url = 0;
691       opt.allow_ocsp = 0;
692       opt.allow_version_check = 0;
693       opt.ocsp_responder = NULL;
694       opt.ocsp_max_clock_skew = 10 * 60;      /* 10 minutes.  */
695       opt.ocsp_max_period = 90 * 86400;       /* 90 days.  */
696       opt.ocsp_current_period = 3 * 60 * 60;  /* 3 hours. */
697       opt.max_replies = DEFAULT_MAX_REPLIES;
698       while (opt.ocsp_signer)
699         {
700           fingerprint_list_t tmp = opt.ocsp_signer->next;
701           xfree (opt.ocsp_signer);
702           opt.ocsp_signer = tmp;
703         }
704       while (opt.ignored_certs)
705         {
706           fingerprint_list_t tmp = opt.ignored_certs->next;
707           xfree (opt.ignored_certs);
708           opt.ignored_certs = tmp;
709         }
710       FREE_STRLIST (opt.ignored_cert_extensions);
711       FREE_STRLIST (opt.ignored_crl_extensions);
712       http_register_tls_ca (NULL);
713       FREE_STRLIST (hkp_cacert_filenames);
714       FREE_STRLIST (opt.keyserver);
715       /* Note: We do not allow resetting of TOR_MODE_FORCE at runtime.  */
716       if (tor_mode != TOR_MODE_FORCE)
717         tor_mode = TOR_MODE_AUTO;
718       disable_check_own_socket = 0;
719       enable_standard_resolver (0);
720       set_dns_timeout (0);
721       opt.connect_timeout = 0;
722       opt.connect_quick_timeout = 0;
723       opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
724       ldapserver_list_needs_reset = 1;
725       opt.debug_cache_expired_certs = 0;
726       xfree (opt.fake_crl);
727       opt.fake_crl = NULL;
728       opt.compat_flags = 0;
729       return 1;
730     }
731
732   switch (pargs->r_opt)
733     {
734     case oQuiet:   opt.quiet = 1; break;
735     case oVerbose: opt.verbose++; break;
736     case oDebug:
737       parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
738       break;
739     case oDebugAll: opt.debug = ~0; break;
740     case oDebugLevel: debug_level = pargs->r.ret_str; break;
741     case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break;
742
743     case oLogFile:
744       if (!reread)
745         return 0; /* Not handled. */
746       if (!current_logfile || !pargs->r.ret_str
747           || strcmp (current_logfile, pargs->r.ret_str))
748         {
749           log_set_file (pargs->r.ret_str);
750           xfree (current_logfile);
751           current_logfile = xtrystrdup (pargs->r.ret_str);
752         }
753       break;
754
755     case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
756
757     case oLDAPWrapperProgram:
758       opt.ldap_wrapper_program = pargs->r.ret_str;
759       break;
760     case oHTTPWrapperProgram:
761       opt.http_wrapper_program = pargs->r.ret_str;
762       break;
763
764     case oDisableHTTP: opt.disable_http = 1; break;
765     case oDisableLDAP: opt.disable_ldap = 1; break;
766     case oDisableIPv4: opt.disable_ipv4 = 1; break;
767     case oDisableIPv6: opt.disable_ipv6 = 1; break;
768     case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
769     case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
770     case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
771     case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
772     case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
773     case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
774     case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
775
776     case oAllowOCSP: opt.allow_ocsp = 1; break;
777     case oAllowVersionCheck: opt.allow_version_check = 1; break;
778     case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
779     case oOCSPSigner:
780       opt.ocsp_signer = parse_fingerprint_item (pargs->r.ret_str,
781                                                 "--ocsp-signer", 0);
782       break;
783     case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
784     case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
785     case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
786
787     case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
788
789     case oHkpCaCert:
790       {
791         /* We need to register the filenames with gnutls (http.c) and
792          * also for our own cert cache.  */
793         char *tmpname;
794
795         /* Do tilde expansion and make path absolute.  */
796         tmpname = make_absfilename (pargs->r.ret_str, NULL);
797         http_register_tls_ca (tmpname);
798         add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str);
799         xfree (tmpname);
800       }
801       break;
802
803     case oIgnoreCert:
804       {
805         fingerprint_list_t item, r;
806         item = parse_fingerprint_item (pargs->r.ret_str, "--ignore-cert", 20);
807         if (item)
808           {  /* Append  */
809             if (!opt.ignored_certs)
810               opt.ignored_certs = item;
811             else
812               {
813                 for (r = opt.ignored_certs; r->next; r = r->next)
814                   ;
815                 r->next = item;
816               }
817           }
818       }
819       break;
820
821     case oIgnoreCertExtension:
822       add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
823       break;
824
825     case oIgnoreCRLExtension:
826       add_to_strlist (&opt.ignored_crl_extensions, pargs->r.ret_str);
827       break;
828
829     case oUseTor:
830       tor_mode = TOR_MODE_FORCE;
831       break;
832     case oNoUseTor:
833       if (tor_mode != TOR_MODE_FORCE)
834         tor_mode = TOR_MODE_NEVER;
835       break;
836
837     case oStandardResolver: enable_standard_resolver (1); break;
838     case oRecursiveResolver: enable_recursive_resolver (1); break;
839
840     case oLDAPServer:
841 #if USE_LDAP
842       {
843         ldap_server_t server;
844         char *p;
845
846         p = pargs->r.ret_str;
847         if (!strncmp (p, "ldap:", 5) && !(p[5] == '/' && p[6] == '/'))
848           p += 5;
849
850         server = ldapserver_parse_one (p, NULL, 0);
851         if (server)
852           {
853             if (ldapserver_list_needs_reset)
854               {
855                 ldapserver_list_needs_reset = 0;
856                 ldapserver_list_free (opt.ldapservers);
857                 opt.ldapservers = NULL;
858               }
859             server->next = opt.ldapservers;
860             opt.ldapservers = server;
861           }
862       }
863 #endif
864       break;
865
866     case oKeyServer:
867       if (*pargs->r.ret_str)
868         add_to_strlist (&opt.keyserver, pargs->r.ret_str);
869       break;
870
871     case oNameServer:
872       set_dns_nameserver (pargs->r.ret_str);
873       break;
874
875     case oResolverTimeout:
876       set_dns_timeout (pargs->r.ret_int);
877       break;
878
879     case oConnectTimeout:
880       opt.connect_timeout = pargs->r.ret_ulong * 1000;
881       break;
882
883     case oConnectQuickTimeout:
884       opt.connect_quick_timeout = pargs->r.ret_ulong * 1000;
885       break;
886
887     case oLDAPTimeout:
888       opt.ldaptimeout = pargs->r.ret_int;
889       break;
890
891     case oDebugCacheExpiredCerts:
892       opt.debug_cache_expired_certs = 0;
893       break;
894
895     case oFakeCRL:
896       xfree (opt.fake_crl);
897       opt.fake_crl = *pargs->r.ret_str? xstrdup (pargs->r.ret_str) : NULL;
898       break;
899
900     case oCompatibilityFlags:
901       if (parse_compatibility_flags (pargs->r.ret_str, &opt.compat_flags,
902                                      compatibility_flags))
903         {
904           pargs->r_opt = ARGPARSE_INVALID_ARG;
905           pargs->err = ARGPARSE_PRINT_WARNING;
906         }
907       break;
908
909     default:
910       return 0; /* Not handled. */
911     }
912
913   set_dns_verbose (opt.verbose, !!DBG_DNS);
914   http_set_verbose (opt.verbose, !!DBG_NETWORK);
915   set_dns_disable_ipv4 (opt.disable_ipv4);
916   set_dns_disable_ipv6 (opt.disable_ipv6);
917
918   return 1; /* Handled. */
919 }
920
921
922 /* This function is called after option parsing to adjust some values
923  * and call option setup functions.  */
924 static void
925 post_option_parsing (enum cmd_and_opt_values cmd)
926 {
927   /* It would be too surpirsing if the quick timeout is larger than
928    * the standard value.  */
929   if (opt.connect_quick_timeout > opt.connect_timeout)
930     opt.connect_quick_timeout = opt.connect_timeout;
931
932   set_debug ();
933   /* For certain commands we do not want to set/test for Tor mode
934    * because that is somewhat expensive.  */
935   switch (cmd)
936     {
937     case aGPGConfList:
938     case aGPGConfTest:
939     case aGPGConfVersions:
940       break;
941     default:
942       set_tor_mode ();
943       break;
944     }
945 }
946
947
948 #ifndef HAVE_W32_SYSTEM
949 static int
950 pid_suffix_callback (unsigned long *r_suffix)
951 {
952   union int_and_ptr_u value;
953
954   memset (&value, 0, sizeof value);
955   value.aptr = npth_getspecific (my_tlskey_current_fd);
956   *r_suffix = value.aint;
957   return (*r_suffix != -1);  /* Use decimal representation.  */
958 }
959 #endif /*!HAVE_W32_SYSTEM*/
960
961 #if HTTP_USE_NTBTLS
962 static void
963 my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv)
964 {
965   (void)opaque;
966
967   if (level == -1)
968     log_logv_prefix (GPGRT_LOGLVL_INFO, "ntbtls: ", fmt, argv);
969   else
970     {
971       char prefix[10+20];
972       snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level);
973       log_logv_prefix (GPGRT_LOGLVL_DEBUG, prefix, fmt, argv);
974     }
975 }
976 #endif
977
978
979 static void
980 thread_init (void)
981 {
982   npth_init ();
983   assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
984   gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
985
986   /* Now with NPth running we can set the logging callback.  Our
987      windows implementation does not yet feature the NPth TLS
988      functions.  */
989 #ifndef HAVE_W32_SYSTEM
990   if (npth_key_create (&my_tlskey_current_fd, NULL) == 0)
991     if (npth_setspecific (my_tlskey_current_fd, NULL) == 0)
992       log_set_pid_suffix_cb (pid_suffix_callback);
993 #endif /*!HAVE_W32_SYSTEM*/
994 }
995
996
997 int
998 main (int argc, char **argv)
999 {
1000   enum cmd_and_opt_values cmd = 0;
1001   gpgrt_argparse_t pargs;
1002   int orig_argc;
1003   char **orig_argv;
1004   char *last_configname = NULL;
1005   const char *configname = NULL;
1006   const char *shell;
1007   int debug_argparser = 0;
1008   int greeting = 0;
1009   int nogreeting = 0;
1010   int nodetach = 0;
1011   int csh_style = 0;
1012   char *logfile = NULL;
1013 #if USE_LDAP
1014   char *ldapfile = NULL;
1015 #endif /*USE_LDAP*/
1016   int debug_wait = 0;
1017   int rc;
1018   struct assuan_malloc_hooks malloc_hooks;
1019
1020   early_system_init ();
1021   gpgrt_set_strusage (my_strusage);
1022   log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
1023
1024   /* Make sure that our subsystems are ready.  */
1025   i18n_init ();
1026   init_common_subsystems (&argc, &argv);
1027
1028   gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
1029
1030  /* Check that the libraries are suitable.  Do it here because
1031     the option parsing may need services of the libraries. */
1032   if (!ksba_check_version (NEED_KSBA_VERSION) )
1033     log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba",
1034                NEED_KSBA_VERSION, ksba_check_version (NULL) );
1035
1036   ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
1037   ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
1038
1039   /* Init TLS library.  */
1040 #if HTTP_USE_NTBTLS
1041   if (!ntbtls_check_version (NEED_NTBTLS_VERSION) )
1042     log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls",
1043                NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) );
1044 #elif HTTP_USE_GNUTLS
1045   rc = gnutls_global_init ();
1046   if (rc)
1047     log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));
1048 #endif /*HTTP_USE_GNUTLS*/
1049
1050   /* Init Assuan. */
1051   malloc_hooks.malloc = gcry_malloc;
1052   malloc_hooks.realloc = gcry_realloc;
1053   malloc_hooks.free = gcry_free;
1054   assuan_set_malloc_hooks (&malloc_hooks);
1055   assuan_set_assuan_log_prefix (log_get_prefix (NULL));
1056   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
1057   assuan_sock_init ();
1058   setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor);
1059
1060   setup_libgcrypt_logging ();
1061
1062 #if HTTP_USE_NTBTLS
1063   ntbtls_set_log_handler (my_ntbtls_log_handler, NULL);
1064 #endif
1065
1066   /* Setup defaults. */
1067   shell = getenv ("SHELL");
1068   if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
1069     csh_style = 1;
1070
1071   /* Reset rereadable options to default values. */
1072   parse_rereadable_options (NULL, 0);
1073
1074   /* Default TCP timeouts.  */
1075   opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT;
1076   opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT;
1077
1078   /* LDAP defaults.  */
1079   opt.add_new_ldapservers = 0;
1080   opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
1081
1082   /* Other defaults.  */
1083
1084   /* Check whether we have a config file given on the commandline */
1085   orig_argc = argc;
1086   orig_argv = argv;
1087   pargs.argc = &argc;
1088   pargs.argv = &argv;
1089   pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1090   while (gpgrt_argparse (NULL, &pargs, opts))
1091     {
1092       switch (pargs.r_opt)
1093         {
1094         case oDebug:
1095         case oDebugAll:
1096           debug_argparser++;
1097           break;
1098         case oHomedir:
1099           gnupg_set_homedir (pargs.r.ret_str);
1100           break;
1101         }
1102     }
1103   /* Reset the flags.  */
1104   pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1105
1106   socket_name = dirmngr_socket_name ();
1107
1108   /* The configuraton directories for use by gpgrt_argparser.  */
1109   gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
1110   gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
1111
1112   /* We are re-using the struct, thus the reset flag.  We OR the
1113    * flags so that the internal intialized flag won't be cleared. */
1114   argc = orig_argc;
1115   argv = orig_argv;
1116   pargs.argc = &argc;
1117   pargs.argv = &argv;
1118   pargs.flags |=  (ARGPARSE_FLAG_RESET
1119                    | ARGPARSE_FLAG_KEEP
1120                    | ARGPARSE_FLAG_SYS
1121                    | ARGPARSE_FLAG_USER);
1122   while (gpgrt_argparser (&pargs, opts, DIRMNGR_NAME EXTSEP_S "conf"))
1123     {
1124       if (pargs.r_opt == ARGPARSE_CONFFILE)
1125         {
1126           if (debug_argparser)
1127             log_info (_("reading options from '%s'\n"),
1128                       pargs.r_type? pargs.r.ret_str: "[cmdline]");
1129           if (pargs.r_type)
1130             {
1131               xfree (last_configname);
1132               last_configname = xstrdup (pargs.r.ret_str);
1133               configname = last_configname;
1134             }
1135           else
1136             configname = NULL;
1137           continue;
1138         }
1139       if (parse_rereadable_options (&pargs, 0))
1140         continue; /* Already handled */
1141       switch (pargs.r_opt)
1142         {
1143         case aServer:
1144         case aDaemon:
1145         case aSupervised:
1146         case aShutdown:
1147         case aFlush:
1148         case aListCRLs:
1149         case aLoadCRL:
1150         case aFetchCRL:
1151         case aGPGConfList:
1152         case aGPGConfTest:
1153         case aGPGConfVersions:
1154           cmd = pargs.r_opt;
1155           break;
1156
1157         case oQuiet: opt.quiet = 1; break;
1158         case oVerbose: opt.verbose++; break;
1159         case oBatch: opt.batch=1; break;
1160
1161         case oDebugWait: debug_wait = pargs.r.ret_int; break;
1162
1163         case oNoGreeting: nogreeting = 1; break;
1164         case oNoVerbose: opt.verbose = 0; break;
1165         case oHomedir: /* Ignore this option here. */; break;
1166         case oNoDetach: nodetach = 1; break;
1167         case oStealSocket: steal_socket = 1; break;
1168         case oLogFile: logfile = pargs.r.ret_str; break;
1169         case oCsh: csh_style = 1; break;
1170         case oSh: csh_style = 0; break;
1171         case oLDAPFile:
1172 #        if USE_LDAP
1173           ldapfile = pargs.r.ret_str;
1174 #        endif /*USE_LDAP*/
1175           break;
1176         case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
1177
1178         case oFakedSystemTime:
1179           gnupg_set_time ((time_t)pargs.r.ret_ulong, 0);
1180           break;
1181
1182         case oForce: opt.force = 1; break;
1183
1184         case oSocketName: socket_name = pargs.r.ret_str; break;
1185
1186         case oListenBacklog:
1187           listen_backlog = pargs.r.ret_int;
1188           break;
1189
1190         default:
1191           if (configname)
1192             pargs.err = ARGPARSE_PRINT_WARNING;
1193           else
1194             pargs.err = ARGPARSE_PRINT_ERROR;
1195           break;
1196         }
1197     }
1198   gpgrt_argparse (NULL, &pargs, NULL);  /* Release internal state.  */
1199
1200   if (!last_configname)
1201     opt.config_filename = gpgrt_fnameconcat (gnupg_homedir (),
1202                                              DIRMNGR_NAME EXTSEP_S "conf",
1203                                              NULL);
1204   else
1205     {
1206       opt.config_filename = last_configname;
1207       last_configname = NULL;
1208     }
1209
1210   if (log_get_errorcount(0))
1211     exit(2);
1212
1213   /* Get a default log file from common.conf.  */
1214   if (!logfile && !parse_comopt (GNUPG_MODULE_NAME_DIRMNGR, debug_argparser))
1215     {
1216       logfile = comopt.logfile;
1217       comopt.logfile = NULL;
1218     }
1219
1220   if (nogreeting )
1221     greeting = 0;
1222
1223   if (!opt.homedir_cache)
1224     opt.homedir_cache = xstrdup (gnupg_homedir ());
1225
1226   if (greeting)
1227     {
1228       es_fprintf (es_stderr, "%s %s; %s\n",
1229                   gpgrt_strusage(11), gpgrt_strusage(13), gpgrt_strusage(14));
1230       es_fprintf (es_stderr, "%s\n", gpgrt_strusage(15));
1231     }
1232
1233 #ifdef IS_DEVELOPMENT_VERSION
1234   log_info ("NOTE: this is a development version!\n");
1235 #endif
1236
1237   /* Print a warning if an argument looks like an option.  */
1238   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1239     {
1240       int i;
1241
1242       for (i=0; i < argc; i++)
1243         if (argv[i][0] == '-' && argv[i][1] == '-')
1244           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1245     }
1246
1247   if (!gnupg_access ("/etc/"DIRMNGR_NAME, F_OK)
1248       && !strncmp (gnupg_homedir (), "/etc/", 5))
1249     log_info
1250       ("NOTE: DirMngr is now a proper part of %s.  The configuration and"
1251        " other directory names changed.  Please check that no other version"
1252        " of dirmngr is still installed.  To disable this warning, remove the"
1253        " directory '/etc/dirmngr'.\n", GNUPG_NAME);
1254
1255   if (gnupg_faked_time_p ())
1256     {
1257       gnupg_isotime_t tbuf;
1258
1259       log_info (_("WARNING: running with faked system time: "));
1260       gnupg_get_isotime (tbuf);
1261       dump_isotime (tbuf);
1262       log_printf ("\n");
1263     }
1264
1265   post_option_parsing (cmd);
1266
1267   /* Get LDAP server list from file unless --ldapserver has been used.  */
1268 #if USE_LDAP
1269   if (opt.ldapservers)
1270     ;
1271   else if (!ldapfile)
1272     {
1273       ldapfile = make_filename (gnupg_homedir (),
1274                                 "dirmngr_ldapservers.conf",
1275                                 NULL);
1276       opt.ldapservers = parse_ldapserver_file (ldapfile, 1);
1277       xfree (ldapfile);
1278     }
1279   else
1280     opt.ldapservers = parse_ldapserver_file (ldapfile, 0);
1281 #endif /*USE_LDAP*/
1282
1283 #ifndef HAVE_W32_SYSTEM
1284   /* We need to ignore the PIPE signal because the we might log to a
1285      socket and that code handles EPIPE properly.  The ldap wrapper
1286      also requires us to ignore this silly signal. Assuan would set
1287      this signal to ignore anyway.*/
1288   signal (SIGPIPE, SIG_IGN);
1289 #endif
1290
1291   /* Ready.  Now to our duties. */
1292   if (!cmd)
1293     cmd = aServer;
1294   rc = 0;
1295
1296   if (cmd == aServer)
1297     {
1298       /* Note that this server mode is mainly useful for debugging.  */
1299       if (argc)
1300         wrong_args ("--server");
1301
1302       if (logfile)
1303         {
1304           log_set_file (logfile);
1305           log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1306         }
1307
1308       if (debug_wait)
1309         {
1310           log_debug ("waiting for debugger - my pid is %u .....\n",
1311                      (unsigned int)getpid());
1312           gnupg_sleep (debug_wait);
1313           log_debug ("... okay\n");
1314         }
1315
1316
1317       thread_init ();
1318       cert_cache_init (hkp_cacert_filenames);
1319       crl_cache_init ();
1320       ks_hkp_init ();
1321       http_register_netactivity_cb (netactivity_action);
1322       start_command_handler (ASSUAN_INVALID_FD, 0);
1323       shutdown_reaper ();
1324     }
1325 #ifndef HAVE_W32_SYSTEM
1326   else if (cmd == aSupervised)
1327     {
1328       struct stat statbuf;
1329
1330       if (!opt.quiet)
1331         log_info(_("WARNING: \"%s\" is a deprecated option\n"), "--supervised");
1332
1333       /* In supervised mode, we expect file descriptor 3 to be an
1334          already opened, listening socket.
1335
1336          We will also not detach from the controlling process or close
1337          stderr; the supervisor should handle all of that.  */
1338       if (fstat (3, &statbuf) == -1 && errno == EBADF)
1339         {
1340           log_error ("file descriptor 3 must be validin --supervised mode\n");
1341           dirmngr_exit (1);
1342         }
1343       socket_name = gnupg_get_socket_name (3);
1344
1345       /* Now start with logging to a file if this is desired. */
1346       if (logfile)
1347         {
1348           log_set_file (logfile);
1349           log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1350                                  |GPGRT_LOG_WITH_TIME
1351                                  |GPGRT_LOG_WITH_PID));
1352           current_logfile = xstrdup (logfile);
1353         }
1354       else
1355         log_set_prefix (NULL, 0);
1356
1357       thread_init ();
1358       cert_cache_init (hkp_cacert_filenames);
1359       crl_cache_init ();
1360       ks_hkp_init ();
1361       http_register_netactivity_cb (netactivity_action);
1362       handle_connections (3);
1363       shutdown_reaper ();
1364     }
1365 #endif /*HAVE_W32_SYSTEM*/
1366   else if (cmd == aDaemon)
1367     {
1368       assuan_fd_t fd;
1369       pid_t pid;
1370       int len;
1371       struct sockaddr_un serv_addr;
1372
1373       if (argc)
1374         wrong_args ("--daemon");
1375
1376       /* Now start with logging to a file if this is desired. */
1377       if (logfile)
1378         {
1379           log_set_file (logfile);
1380           log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1381                                  |GPGRT_LOG_WITH_TIME
1382                                  |GPGRT_LOG_WITH_PID));
1383           current_logfile = xstrdup (logfile);
1384         }
1385
1386       if (debug_wait)
1387         {
1388           log_debug ("waiting for debugger - my pid is %u .....\n",
1389                      (unsigned int)getpid());
1390           gnupg_sleep (debug_wait);
1391           log_debug ("... okay\n");
1392         }
1393
1394 #ifndef HAVE_W32_SYSTEM
1395       if (strchr (socket_name, ':'))
1396         {
1397           log_error (_("colons are not allowed in the socket name\n"));
1398           dirmngr_exit (1);
1399         }
1400 #endif
1401       fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1402       if (fd == ASSUAN_INVALID_FD)
1403         {
1404           log_error (_("can't create socket: %s\n"), strerror (errno));
1405           cleanup ();
1406           dirmngr_exit (1);
1407         }
1408
1409       {
1410         int redirected;
1411
1412         if (assuan_sock_set_sockaddr_un (socket_name,
1413                                          (struct sockaddr*)&serv_addr,
1414                                          &redirected))
1415           {
1416             if (errno == ENAMETOOLONG)
1417               log_error (_("socket name '%s' is too long\n"), socket_name);
1418             else
1419               log_error ("error preparing socket '%s': %s\n",
1420                          socket_name,
1421                          gpg_strerror (gpg_error_from_syserror ()));
1422             dirmngr_exit (1);
1423           }
1424         if (redirected)
1425           {
1426             redir_socket_name = xstrdup (serv_addr.sun_path);
1427             if (opt.verbose)
1428               log_info ("redirecting socket '%s' to '%s'\n",
1429                         socket_name, redir_socket_name);
1430           }
1431       }
1432
1433       len = SUN_LEN (&serv_addr);
1434
1435       rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1436       if (rc == -1
1437           && (errno == EADDRINUSE
1438 #ifdef HAVE_W32_SYSTEM
1439               || errno == EEXIST
1440 #endif
1441               ))
1442         {
1443           /* Fixme: We should actually test whether a dirmngr is
1444            * already running.  For now the steal option is a dummy. */
1445           /* if (steal_socket) */
1446           /*   log_info (N_("trying to steal socket from running %s\n"), */
1447           /*             "dirmngr"); */
1448           gnupg_remove (redir_socket_name? redir_socket_name : socket_name);
1449           rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1450         }
1451       if (rc != -1
1452           && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
1453         log_error (_("error getting nonce for the socket\n"));
1454       if (rc == -1)
1455         {
1456           log_error (_("error binding socket to '%s': %s\n"),
1457                      serv_addr.sun_path,
1458                      gpg_strerror (gpg_error_from_syserror ()));
1459           assuan_sock_close (fd);
1460           dirmngr_exit (1);
1461         }
1462       cleanup_socket = 1;
1463
1464       if (gnupg_chmod (serv_addr.sun_path, "-rwx"))
1465         log_error (_("can't set permissions of '%s': %s\n"),
1466                    serv_addr.sun_path, strerror (errno));
1467
1468       if (listen (FD2INT (fd), listen_backlog) == -1)
1469         {
1470           log_error ("listen(fd,%d) failed: %s\n",
1471                      listen_backlog, strerror (errno));
1472           assuan_sock_close (fd);
1473           dirmngr_exit (1);
1474         }
1475
1476       if (opt.verbose)
1477         log_info (_("listening on socket '%s'\n"), serv_addr.sun_path);
1478
1479       es_fflush (NULL);
1480
1481       /* Note: We keep the dirmngr_info output only for the sake of
1482          existing scripts which might use this to detect a successful
1483          start of the dirmngr.  */
1484 #ifdef HAVE_W32_SYSTEM
1485       (void)csh_style;
1486       (void)nodetach;
1487
1488       pid = getpid ();
1489       es_printf ("set %s=%s;%lu;1\n",
1490                  DIRMNGR_INFO_NAME, socket_name, (ulong) pid);
1491 #else
1492       pid = fork();
1493       if (pid == (pid_t)-1)
1494         {
1495           log_fatal (_("error forking process: %s\n"), strerror (errno));
1496           dirmngr_exit (1);
1497         }
1498
1499       if (pid)
1500         { /* We are the parent */
1501           char *infostr;
1502
1503           /* Don't let cleanup() remove the socket - the child is
1504              responsible for doing that.  */
1505           cleanup_socket = 0;
1506
1507           close (fd);
1508
1509           /* Create the info string: <name>:<pid>:<protocol_version> */
1510           if (asprintf (&infostr, "%s=%s:%lu:1",
1511                         DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0)
1512             {
1513               log_error (_("out of core\n"));
1514               kill (pid, SIGTERM);
1515               dirmngr_exit (1);
1516             }
1517           /* Print the environment string, so that the caller can use
1518              shell's eval to set it.  But see above.  */
1519           if (csh_style)
1520             {
1521               *strchr (infostr, '=') = ' ';
1522               es_printf ( "setenv %s;\n", infostr);
1523             }
1524           else
1525             {
1526               es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME);
1527             }
1528           free (infostr);
1529           exit (0);
1530           /*NEVER REACHED*/
1531         } /* end parent */
1532
1533
1534       /*
1535          This is the child
1536        */
1537
1538       /* Detach from tty and put process into a new session */
1539       if (!nodetach )
1540         {
1541           int i;
1542           unsigned int oldflags;
1543
1544           /* Close stdin, stdout and stderr unless it is the log stream */
1545           for (i=0; i <= 2; i++)
1546             {
1547               if (!log_test_fd (i) && i != fd )
1548                 {
1549                   if ( !close (i)
1550                        && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1551                     {
1552                       log_error ("failed to open '%s': %s\n",
1553                                  "/dev/null", strerror (errno));
1554                       cleanup ();
1555                       dirmngr_exit (1);
1556                     }
1557                 }
1558             }
1559
1560           if (setsid() == -1)
1561             {
1562               log_error ("setsid() failed: %s\n", strerror(errno) );
1563               dirmngr_exit (1);
1564             }
1565
1566           log_get_prefix (&oldflags);
1567           log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1568           opt.running_detached = 1;
1569
1570         }
1571 #endif
1572
1573       if (!nodetach )
1574         {
1575           if (gnupg_chdir (gnupg_daemon_rootdir ()))
1576             {
1577               log_error ("chdir to '%s' failed: %s\n",
1578                          gnupg_daemon_rootdir (), strerror (errno));
1579               dirmngr_exit (1);
1580             }
1581         }
1582
1583       thread_init ();
1584       cert_cache_init (hkp_cacert_filenames);
1585       crl_cache_init ();
1586       ks_hkp_init ();
1587       http_register_netactivity_cb (netactivity_action);
1588       handle_connections (fd);
1589       shutdown_reaper ();
1590     }
1591   else if (cmd == aListCRLs)
1592     {
1593       /* Just list the CRL cache and exit. */
1594       if (argc)
1595         wrong_args ("--list-crls");
1596       crl_cache_init ();
1597       crl_cache_list (es_stdout);
1598     }
1599   else if (cmd == aLoadCRL)
1600     {
1601       struct server_control_s ctrlbuf;
1602
1603       memset (&ctrlbuf, 0, sizeof ctrlbuf);
1604       dirmngr_init_default_ctrl (&ctrlbuf);
1605
1606       thread_init ();
1607       cert_cache_init (hkp_cacert_filenames);
1608       crl_cache_init ();
1609       ks_hkp_init ();
1610       if (!argc)
1611         rc = crl_cache_load (&ctrlbuf, NULL);
1612       else
1613         {
1614           for (; !rc && argc; argc--, argv++)
1615             rc = crl_cache_load (&ctrlbuf, *argv);
1616         }
1617       dirmngr_deinit_default_ctrl (&ctrlbuf);
1618     }
1619   else if (cmd == aFetchCRL)
1620     {
1621       ksba_reader_t reader;
1622       struct server_control_s ctrlbuf;
1623
1624       if (argc != 1)
1625         wrong_args ("--fetch-crl URL");
1626
1627       memset (&ctrlbuf, 0, sizeof ctrlbuf);
1628       dirmngr_init_default_ctrl (&ctrlbuf);
1629
1630       thread_init ();
1631       cert_cache_init (hkp_cacert_filenames);
1632       crl_cache_init ();
1633       ks_hkp_init ();
1634       rc = crl_fetch (&ctrlbuf, argv[0], &reader);
1635       if (rc)
1636         log_error (_("fetching CRL from '%s' failed: %s\n"),
1637                      argv[0], gpg_strerror (rc));
1638       else
1639         {
1640           rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
1641           if (rc)
1642             log_error (_("processing CRL from '%s' failed: %s\n"),
1643                        argv[0], gpg_strerror (rc));
1644           crl_close_reader (reader);
1645         }
1646       dirmngr_deinit_default_ctrl (&ctrlbuf);
1647     }
1648   else if (cmd == aFlush)
1649     {
1650       /* Delete cache and exit. */
1651       if (argc)
1652         wrong_args ("--flush");
1653       rc = crl_cache_flush();
1654     }
1655   else if (cmd == aGPGConfTest)
1656     dirmngr_exit (0);
1657   else if (cmd == aGPGConfList)
1658     {
1659       unsigned long flags = 0;
1660       char *filename_esc;
1661
1662       es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
1663       es_printf ("ldaptimeout:%lu:%u\n",
1664                  flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
1665       es_printf ("max-replies:%lu:%u\n",
1666                  flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
1667
1668       filename_esc = percent_escape (get_default_keyserver (0), NULL);
1669       es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT,
1670                  filename_esc);
1671       xfree (filename_esc);
1672
1673       es_printf ("resolver-timeout:%lu:%u\n",
1674                  flags | GC_OPT_FLAG_DEFAULT, 0);
1675     }
1676   else if (cmd == aGPGConfVersions)
1677     gpgconf_versions ();
1678
1679   cleanup ();
1680   return !!rc;
1681 }
1682
1683
1684 static void
1685 cleanup (void)
1686 {
1687   crl_cache_deinit ();
1688   cert_cache_deinit (1);
1689   reload_dns_stuff (1);
1690
1691 #if USE_LDAP
1692   ldapserver_list_free (opt.ldapservers);
1693 #endif /*USE_LDAP*/
1694   opt.ldapservers = NULL;
1695
1696   if (cleanup_socket)
1697     {
1698       cleanup_socket = 0;
1699       if (redir_socket_name)
1700         gnupg_remove (redir_socket_name);
1701       else if (socket_name && *socket_name)
1702         gnupg_remove (socket_name);
1703     }
1704 }
1705
1706
1707 void
1708 dirmngr_exit (int rc)
1709 {
1710   cleanup ();
1711   exit (rc);
1712 }
1713
1714
1715 void
1716 dirmngr_init_default_ctrl (ctrl_t ctrl)
1717 {
1718   ctrl->magic = SERVER_CONTROL_MAGIC;
1719   if (opt.http_proxy)
1720     ctrl->http_proxy = xstrdup (opt.http_proxy);
1721   ctrl->http_no_crl = 1;
1722   ctrl->timeout = opt.connect_timeout;
1723 }
1724
1725
1726 void
1727 dirmngr_deinit_default_ctrl (ctrl_t ctrl)
1728 {
1729   if (!ctrl)
1730     return;
1731   ctrl->magic = 0xdeadbeef;
1732
1733   xfree (ctrl->http_proxy);
1734   ctrl->http_proxy = NULL;
1735   nvc_release (ctrl->rootdse);
1736   ctrl->rootdse = NULL;
1737 }
1738
1739
1740 /* Create a list of LDAP servers from the file FILENAME. Returns the
1741    list or NULL in case of errors.
1742
1743    The format of such a file is line oriented where empty lines and
1744    lines starting with a hash mark are ignored.  All other lines are
1745    assumed to be colon seprated with these fields:
1746
1747    1. field: Hostname
1748    2. field: Portnumber
1749    3. field: Username
1750    4. field: Password
1751    5. field: Base DN
1752
1753 */
1754 #if USE_LDAP
1755 static ldap_server_t
1756 parse_ldapserver_file (const char* filename, int ignore_enoent)
1757 {
1758   char buffer[1024];
1759   char *p;
1760   ldap_server_t server, serverstart, *serverend;
1761   int c;
1762   unsigned int lineno = 0;
1763   estream_t fp;
1764
1765   fp = es_fopen (filename, "r");
1766   if (!fp)
1767     {
1768       if (ignore_enoent && gpg_err_code_from_syserror () == GPG_ERR_ENOENT)
1769         ;
1770       else
1771         log_info ("failed to open '%s': %s\n", filename, strerror (errno));
1772       return NULL;
1773     }
1774
1775   serverstart = NULL;
1776   serverend = &serverstart;
1777   while (es_fgets (buffer, sizeof buffer, fp))
1778     {
1779       lineno++;
1780       if (!*buffer || buffer[strlen(buffer)-1] != '\n')
1781         {
1782           if (*buffer && es_feof (fp))
1783             ; /* Last line not terminated - continue. */
1784           else
1785             {
1786               log_error (_("%s:%u: line too long - skipped\n"),
1787                          filename, lineno);
1788               while ( (c=es_fgetc (fp)) != EOF && c != '\n')
1789                 ; /* Skip until end of line. */
1790               continue;
1791             }
1792         }
1793       /* Skip empty and comment lines.*/
1794       for (p=buffer; spacep (p); p++)
1795         ;
1796       if (!*p || *p == '\n' || *p == '#')
1797         continue;
1798
1799       /* Parse the colon separated fields. */
1800       server = ldapserver_parse_one (buffer, filename, lineno);
1801       if (server)
1802         {
1803           *serverend = server;
1804           serverend = &server->next;
1805         }
1806     }
1807
1808   if (es_ferror (fp))
1809     log_error (_("error reading '%s': %s\n"), filename, strerror (errno));
1810   es_fclose (fp);
1811
1812   return serverstart;
1813 }
1814 #endif /*USE_LDAP*/
1815
1816
1817 /* Parse a fingerprint entry as used by --ocsc-signer.  OPTIONNAME as
1818  * a description on the options used.  WANT_BINARY requests to store a
1819  * binary fingerprint.  Returns NULL on error and logs that error. */
1820 static fingerprint_list_t
1821 parse_fingerprint_item (const char *string,
1822                         const char *optionname, int want_binary)
1823 {
1824   gpg_error_t err;
1825   char *fname;
1826   estream_t fp;
1827   char line[256];
1828   char *p;
1829   fingerprint_list_t list, *list_tail, item;
1830   unsigned int lnr = 0;
1831   int c, i, j;
1832   int errflag = 0;
1833
1834
1835   /* Check whether this is not a filename and treat it as a direct
1836      fingerprint specification.  */
1837   if (!strpbrk (string, "/.~\\"))
1838     {
1839       item = xcalloc (1, sizeof *item);
1840       for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
1841         if ( string[i] != ':' )
1842           item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
1843       item->hexfpr[j] = 0;
1844       if (j != 40 || !(spacep (string+i) || !string[i]))
1845         {
1846           log_error (_("%s:%u: invalid fingerprint detected\n"),
1847                      optionname, 0);
1848           xfree (item);
1849           return NULL;
1850         }
1851       if (want_binary)
1852         {
1853           item->binlen = 20;
1854           hex2bin (item->hexfpr, item->hexfpr, 20);
1855         }
1856       return item;
1857     }
1858
1859   /* Well, it is a filename.  */
1860   if (*string == '/' || (*string == '~' && string[1] == '/'))
1861     fname = make_filename (string, NULL);
1862   else
1863     {
1864       if (string[0] == '.' && string[1] == '/' )
1865         string += 2;
1866       fname = make_filename (gnupg_homedir (), string, NULL);
1867     }
1868
1869   fp = es_fopen (fname, "r");
1870   if (!fp)
1871     {
1872       err = gpg_error_from_syserror ();
1873       log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
1874       xfree (fname);
1875       return NULL;
1876     }
1877
1878   list = NULL;
1879   list_tail = &list;
1880   for (;;)
1881     {
1882       if (!es_fgets (line, DIM(line)-1, fp) )
1883         {
1884           if (!es_feof (fp))
1885             {
1886               err = gpg_error_from_syserror ();
1887               log_error (_("%s:%u: read error: %s\n"),
1888                          fname, lnr, gpg_strerror (err));
1889               errflag = 1;
1890             }
1891           es_fclose (fp);
1892           if (errflag)
1893             {
1894               while (list)
1895                 {
1896                   fingerprint_list_t tmp = list->next;
1897                   xfree (list);
1898                   list = tmp;
1899                 }
1900             }
1901           xfree (fname);
1902           return list; /* Ready.  */
1903         }
1904
1905       lnr++;
1906       if (!*line || line[strlen(line)-1] != '\n')
1907         {
1908           /* Eat until end of line. */
1909           while ( (c=es_getc (fp)) != EOF && c != '\n')
1910             ;
1911           err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
1912                            /* */: GPG_ERR_INCOMPLETE_LINE);
1913           log_error (_("%s:%u: read error: %s\n"),
1914                      fname, lnr, gpg_strerror (err));
1915           errflag = 1;
1916           continue;
1917         }
1918
1919       /* Allow for empty lines and spaces */
1920       for (p=line; spacep (p); p++)
1921         ;
1922       if (!*p || *p == '\n' || *p == '#')
1923         continue;
1924
1925       item = xcalloc (1, sizeof *item);
1926       *list_tail = item;
1927       list_tail = &item->next;
1928
1929       for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
1930         if ( p[i] != ':' )
1931           item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
1932       item->hexfpr[j] = 0;
1933       if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
1934         {
1935           log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
1936           errflag = 1;
1937         }
1938       else if (want_binary)
1939         {
1940           item->binlen = 20;
1941           hex2bin (item->hexfpr, item->hexfpr, 20);
1942         }
1943
1944       i++;
1945       while (spacep (p+i))
1946         i++;
1947       if (p[i] && p[i] != '\n')
1948         log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
1949     }
1950   /*NOTREACHED*/
1951 }
1952
1953
1954
1955 \f
1956 /*
1957    Stuff used in daemon mode.
1958  */
1959
1960
1961
1962 /* Reread parts of the configuration.  Note, that this function is
1963    obviously not thread-safe and should only be called from the NPTH
1964    signal handler.
1965
1966    Fixme: Due to the way the argument parsing works, we create a
1967    memory leak here for all string type arguments.  There is currently
1968    no clean way to tell whether the memory for the argument has been
1969    allocated or points into the process's original arguments.  Unless
1970    we have a mechanism to tell this, we need to live on with this. */
1971 static void
1972 reread_configuration (void)
1973 {
1974   gpgrt_argparse_t pargs;
1975   char *twopart;
1976   int dummy;
1977   int logfile_seen = 0;
1978
1979   if (!opt.config_filename)
1980     goto finish; /* No config file. */
1981
1982   twopart = strconcat (DIRMNGR_NAME EXTSEP_S "conf" PATHSEP_S,
1983                        opt.config_filename, NULL);
1984   if (!twopart)
1985     return;  /* Out of core.  */
1986
1987   parse_rereadable_options (NULL, 1); /* Start from the default values. */
1988
1989   memset (&pargs, 0, sizeof pargs);
1990   dummy = 0;
1991   pargs.argc = &dummy;
1992   pargs.flags = (ARGPARSE_FLAG_KEEP
1993                  |ARGPARSE_FLAG_SYS
1994                  |ARGPARSE_FLAG_USER);
1995   while (gpgrt_argparser (&pargs, opts, twopart))
1996     {
1997       if (pargs.r_opt == ARGPARSE_CONFFILE)
1998         {
1999           log_info (_("reading options from '%s'\n"),
2000                     pargs.r_type? pargs.r.ret_str: "[cmdline]");
2001         }
2002       else if (pargs.r_opt < -1)
2003         pargs.err = ARGPARSE_PRINT_WARNING;
2004       else /* Try to parse this option - ignore unchangeable ones. */
2005         {
2006           if (pargs.r_opt == oLogFile)
2007             logfile_seen = 1;
2008           parse_rereadable_options (&pargs, 1);
2009         }
2010     }
2011   gpgrt_argparse (NULL, &pargs, NULL);  /* Release internal state.  */
2012   xfree (twopart);
2013   post_option_parsing (0);
2014
2015  finish:
2016   /* Get a default log file from common.conf.  */
2017   if (!logfile_seen && !parse_comopt (GNUPG_MODULE_NAME_DIRMNGR, !!opt.debug))
2018     {
2019       if (!current_logfile || !comopt.logfile
2020           || strcmp (current_logfile, comopt.logfile))
2021         {
2022           log_set_file (comopt.logfile);
2023           xfree (current_logfile);
2024           current_logfile = comopt.logfile? xtrystrdup (comopt.logfile) : NULL;
2025         }
2026     }
2027 }
2028
2029
2030 /* A global function which allows us to trigger the reload stuff from
2031    other places.  */
2032 void
2033 dirmngr_sighup_action (void)
2034 {
2035   log_info (_("SIGHUP received - "
2036               "re-reading configuration and flushing caches\n"));
2037   reread_configuration ();
2038   set_tor_mode ();
2039   cert_cache_deinit (0);
2040   crl_cache_deinit ();
2041   cert_cache_init (hkp_cacert_filenames);
2042   crl_cache_init ();
2043   reload_dns_stuff (0);
2044   ks_hkp_reload ();
2045 }
2046
2047
2048 /* This function is called if some network activity was done.  At this
2049  * point we know the we have a network and we can decide whether to
2050  * run scheduled background tasks soon.  The function should return
2051  * quickly and only trigger actions for another thread. */
2052 static void
2053 netactivity_action (void)
2054 {
2055   network_activity_seen = 1;
2056 }
2057
2058
2059 /* The signal handler. */
2060 #ifndef HAVE_W32_SYSTEM
2061 static void
2062 handle_signal (int signo)
2063 {
2064   switch (signo)
2065     {
2066     case SIGHUP:
2067       dirmngr_sighup_action ();
2068       break;
2069
2070     case SIGUSR1:
2071       /* See also cmd_getinfo:"stats".  */
2072       cert_cache_print_stats (NULL);
2073       domaininfo_print_stats (NULL);
2074       break;
2075
2076     case SIGUSR2:
2077       log_info (_("SIGUSR2 received - no action defined\n"));
2078       break;
2079
2080     case SIGTERM:
2081       if (!shutdown_pending)
2082         log_info (_("SIGTERM received - shutting down ...\n"));
2083       else
2084         log_info (_("SIGTERM received - still %d active connections\n"),
2085                   active_connections);
2086       shutdown_pending++;
2087       if (shutdown_pending > 2)
2088         {
2089           log_info (_("shutdown forced\n"));
2090           log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2091           cleanup ();
2092           dirmngr_exit (0);
2093         }
2094       break;
2095
2096     case SIGINT:
2097       log_info (_("SIGINT received - immediate shutdown\n"));
2098       log_info( "%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2099       cleanup ();
2100       dirmngr_exit (0);
2101       break;
2102
2103     default:
2104       log_info (_("signal %d received - no action defined\n"), signo);
2105     }
2106 }
2107 #endif /*!HAVE_W32_SYSTEM*/
2108
2109
2110 /* Thread to do the housekeeping.  */
2111 static void *
2112 housekeeping_thread (void *arg)
2113 {
2114   static int sentinel;
2115   time_t curtime;
2116   struct server_control_s ctrlbuf;
2117
2118   (void)arg;
2119
2120   curtime = gnupg_get_time ();
2121   if (sentinel)
2122     {
2123       log_info ("housekeeping is already going on\n");
2124       return NULL;
2125     }
2126   sentinel++;
2127   if (opt.verbose > 1)
2128     log_info ("starting housekeeping\n");
2129
2130   memset (&ctrlbuf, 0, sizeof ctrlbuf);
2131   dirmngr_init_default_ctrl (&ctrlbuf);
2132
2133   dns_stuff_housekeeping ();
2134   ks_hkp_housekeeping (curtime);
2135   if (network_activity_seen)
2136     {
2137       network_activity_seen = 0;
2138       if (opt.allow_version_check)
2139         dirmngr_load_swdb (&ctrlbuf, 0);
2140       workqueue_run_global_tasks (&ctrlbuf, 1);
2141     }
2142   else
2143     workqueue_run_global_tasks (&ctrlbuf, 0);
2144
2145   dirmngr_deinit_default_ctrl (&ctrlbuf);
2146
2147   if (opt.verbose > 1)
2148     log_info ("ready with housekeeping\n");
2149   sentinel--;
2150   return NULL;
2151
2152 }
2153
2154
2155 /* We try to enable correct overflow handling for signed int (commonly
2156  * used for time_t). With gcc 4.2 -fno-strict-overflow was introduced
2157  * and used here as a pragma.  Later gcc versions (gcc 6?) removed
2158  * this as a pragma and -fwrapv was then suggested as a replacement
2159  * for -fno-strict-overflow.  */
2160 #if GPGRT_HAVE_PRAGMA_GCC_PUSH
2161 # pragma GCC push_options
2162 # pragma GCC optimize ("wrapv")
2163 #endif
2164 static int
2165 time_for_housekeeping_p (time_t curtime)
2166 {
2167   static time_t last_housekeeping;
2168
2169   if (!last_housekeeping)
2170     last_housekeeping = curtime;
2171
2172   if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime
2173       || last_housekeeping > curtime /*(be prepared for y2038)*/)
2174     {
2175       last_housekeeping = curtime;
2176       return 1;
2177     }
2178   return 0;
2179 }
2180 #if GPGRT_HAVE_PRAGMA_GCC_PUSH
2181 # pragma GCC pop_options
2182 #endif
2183
2184
2185 /* This is the worker for the ticker.  It is called every few seconds
2186    and may only do fast operations. */
2187 static void
2188 handle_tick (void)
2189 {
2190   struct stat statbuf;
2191
2192   if (time_for_housekeeping_p (gnupg_get_time ()))
2193     {
2194       npth_t thread;
2195       npth_attr_t tattr;
2196       int err;
2197
2198       err = npth_attr_init (&tattr);
2199       if (err)
2200         log_error ("error preparing housekeeping thread: %s\n", strerror (err));
2201       else
2202         {
2203           npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2204           err = npth_create (&thread, &tattr, housekeeping_thread, NULL);
2205           if (err)
2206             log_error ("error spawning housekeeping thread: %s\n",
2207                        strerror (err));
2208           npth_attr_destroy (&tattr);
2209         }
2210     }
2211
2212   /* Check whether the homedir is still available.  */
2213   if (!shutdown_pending
2214       && gnupg_stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
2215     {
2216       shutdown_pending = 1;
2217       log_info ("homedir has been removed - shutting down\n");
2218     }
2219 }
2220
2221
2222 /* Check the nonce on a new connection.  This is a NOP unless we are
2223    using our Unix domain socket emulation under Windows.  */
2224 static int
2225 check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
2226 {
2227   if (assuan_sock_check_nonce (fd, nonce))
2228     {
2229       log_info (_("error reading nonce on fd %d: %s\n"),
2230                 FD2INT (fd), strerror (errno));
2231       assuan_sock_close (fd);
2232       return -1;
2233     }
2234   else
2235     return 0;
2236 }
2237
2238
2239 /* Helper to call a connection's main function. */
2240 static void *
2241 start_connection_thread (void *arg)
2242 {
2243   static unsigned int last_session_id;
2244   unsigned int session_id;
2245   union int_and_ptr_u argval;
2246   gnupg_fd_t fd;
2247
2248   memset (&argval, 0, sizeof argval);
2249   argval.aptr = arg;
2250   fd = argval.afd;
2251
2252   if (check_nonce (fd, &socket_nonce))
2253     {
2254       log_error ("handler nonce check FAILED\n");
2255       return NULL;
2256     }
2257
2258 #ifndef HAVE_W32_SYSTEM
2259   npth_setspecific (my_tlskey_current_fd, argval.aptr);
2260 #endif
2261
2262   active_connections++;
2263   if (opt.verbose)
2264     log_info (_("handler for fd %d started\n"), FD2INT (fd));
2265
2266   session_id = ++last_session_id;
2267   if (!session_id)
2268     session_id = ++last_session_id;
2269   start_command_handler (fd, session_id);
2270
2271   if (opt.verbose)
2272     log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
2273   active_connections--;
2274
2275   workqueue_run_post_session_tasks (session_id);
2276
2277 #ifndef HAVE_W32_SYSTEM
2278   argval.afd = ASSUAN_INVALID_FD;
2279   npth_setspecific (my_tlskey_current_fd, argval.aptr);
2280 #endif
2281
2282   return NULL;
2283 }
2284
2285
2286 #ifdef HAVE_INOTIFY_INIT
2287 /* Read an inotify event and return true if it matches NAME.  */
2288 static int
2289 my_inotify_is_name (int fd, const char *name)
2290 {
2291   union {
2292     struct inotify_event ev;
2293     char _buf[sizeof (struct inotify_event) + 100 + 1];
2294   } buf;
2295   int n;
2296   const char *s;
2297
2298   s = strrchr (name, '/');
2299   if (s && s[1])
2300     name = s + 1;
2301
2302   n = npth_read (fd, &buf, sizeof buf);
2303   if (n < sizeof (struct inotify_event))
2304     return 0;
2305   if (buf.ev.len < strlen (name)+1)
2306     return 0;
2307   if (strcmp (buf.ev.name, name))
2308     return 0; /* Not the desired file.  */
2309
2310   return 1; /* Found.  */
2311 }
2312 #endif /*HAVE_INOTIFY_INIT*/
2313
2314
2315 /* Main loop in daemon mode.  Note that LISTEN_FD will be owned by
2316  * this function. */
2317 static void
2318 handle_connections (assuan_fd_t listen_fd)
2319 {
2320   npth_attr_t tattr;
2321 #ifndef HAVE_W32_SYSTEM
2322   int signo;
2323 #endif
2324   struct sockaddr_un paddr;
2325   socklen_t plen = sizeof( paddr );
2326   int nfd, ret;
2327   fd_set fdset, read_fdset;
2328   struct timespec abstime;
2329   struct timespec curtime;
2330   struct timespec timeout;
2331   int saved_errno;
2332   int my_inotify_fd = -1;
2333
2334   npth_attr_init (&tattr);
2335   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2336
2337 #ifndef HAVE_W32_SYSTEM /* FIXME */
2338   npth_sigev_init ();
2339   npth_sigev_add (SIGHUP);
2340   npth_sigev_add (SIGUSR1);
2341   npth_sigev_add (SIGUSR2);
2342   npth_sigev_add (SIGINT);
2343   npth_sigev_add (SIGTERM);
2344   npth_sigev_fini ();
2345 #endif
2346
2347 #ifdef HAVE_INOTIFY_INIT
2348   if (disable_check_own_socket)
2349     my_inotify_fd = -1;
2350   else if ((my_inotify_fd = inotify_init ()) == -1)
2351     log_info ("error enabling fast daemon termination: %s\n",
2352               strerror (errno));
2353   else
2354     {
2355       /* We need to watch the directory for the file because there
2356        * won't be an IN_DELETE_SELF for a socket file.  */
2357       char *slash = strrchr (socket_name, '/');
2358       log_assert (slash && slash[1]);
2359       *slash = 0;
2360       if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1)
2361         {
2362           close (my_inotify_fd);
2363           my_inotify_fd = -1;
2364         }
2365       *slash = '/';
2366     }
2367 #endif /*HAVE_INOTIFY_INIT*/
2368
2369
2370   /* Setup the fdset.  It has only one member.  This is because we use
2371      pth_select instead of pth_accept to properly sync timeouts with
2372      to full second.  */
2373   FD_ZERO (&fdset);
2374   FD_SET (FD2INT (listen_fd), &fdset);
2375   nfd = FD2INT (listen_fd);
2376   if (my_inotify_fd != -1)
2377     {
2378       FD_SET (my_inotify_fd, &fdset);
2379       if (my_inotify_fd > nfd)
2380         nfd = my_inotify_fd;
2381     }
2382
2383   npth_clock_gettime (&abstime);
2384   abstime.tv_sec += TIMERTICK_INTERVAL;
2385
2386   /* Main loop.  */
2387   for (;;)
2388     {
2389       /* Shutdown test.  */
2390       if (shutdown_pending)
2391         {
2392           if (!active_connections)
2393             break; /* ready */
2394
2395           /* Do not accept new connections but keep on running the
2396            * loop to cope with the timer events.
2397            *
2398            * Note that we do not close the listening socket because a
2399            * client trying to connect to that socket would instead
2400            * restart a new dirmngr instance - which is unlikely the
2401            * intention of a shutdown. */
2402           /* assuan_sock_close (listen_fd); */
2403           /* listen_fd = -1; */
2404           FD_ZERO (&fdset);
2405           nfd = -1;
2406           if (my_inotify_fd != -1)
2407             {
2408               FD_SET (my_inotify_fd, &fdset);
2409               nfd = my_inotify_fd;
2410             }
2411         }
2412
2413       /* Take a copy of the fdset.  */
2414       read_fdset = fdset;
2415
2416       npth_clock_gettime (&curtime);
2417       if (!(npth_timercmp (&curtime, &abstime, <)))
2418         {
2419           /* Timeout.  When a shutdown is pending we use a shorter
2420            * interval to handle the shutdown more quickly.  */
2421           handle_tick ();
2422           npth_clock_gettime (&abstime);
2423           abstime.tv_sec += (shutdown_pending
2424                              ? TIMERTICK_INTERVAL_SHUTDOWN
2425                              : TIMERTICK_INTERVAL);
2426         }
2427       npth_timersub (&abstime, &curtime, &timeout);
2428
2429 #ifndef HAVE_W32_SYSTEM
2430       ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2431                           npth_sigev_sigmask());
2432       saved_errno = errno;
2433
2434       while (npth_sigev_get_pending(&signo))
2435         handle_signal (signo);
2436 #else
2437       ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
2438       saved_errno = errno;
2439 #endif
2440
2441       if (ret == -1 && saved_errno != EINTR)
2442         {
2443           log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2444                      strerror (saved_errno));
2445           gnupg_sleep (1);
2446           continue;
2447         }
2448
2449       if (ret <= 0)
2450         {
2451           /* Interrupt or timeout.  Will be handled when calculating the
2452              next timeout.  */
2453           continue;
2454         }
2455
2456       if (shutdown_pending)
2457         {
2458           /* Do not anymore accept connections.  */
2459           continue;
2460         }
2461
2462 #ifdef HAVE_INOTIFY_INIT
2463       if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset)
2464           && my_inotify_is_name (my_inotify_fd, socket_name))
2465         {
2466           shutdown_pending = 1;
2467           log_info ("socket file has been removed - shutting down\n");
2468         }
2469 #endif /*HAVE_INOTIFY_INIT*/
2470
2471       if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
2472         {
2473           gnupg_fd_t fd;
2474
2475           plen = sizeof paddr;
2476           fd = INT2FD (npth_accept (FD2INT(listen_fd),
2477                                     (struct sockaddr *)&paddr, &plen));
2478           if (fd == GNUPG_INVALID_FD)
2479             {
2480               log_error ("accept failed: %s\n", strerror (errno));
2481             }
2482           else
2483             {
2484               char threadname[50];
2485               union int_and_ptr_u argval;
2486               npth_t thread;
2487
2488               memset (&argval, 0, sizeof argval);
2489               argval.afd = fd;
2490               snprintf (threadname, sizeof threadname,
2491                         "conn fd=%d", FD2INT(fd));
2492
2493               ret = npth_create (&thread, &tattr,
2494                                  start_connection_thread, argval.aptr);
2495               if (ret)
2496                 {
2497                   log_error ("error spawning connection handler: %s\n",
2498                              strerror (ret) );
2499                   assuan_sock_close (fd);
2500                 }
2501               npth_setname_np (thread, threadname);
2502             }
2503         }
2504     }
2505
2506 #ifdef HAVE_INOTIFY_INIT
2507   if (my_inotify_fd != -1)
2508     close (my_inotify_fd);
2509 #endif /*HAVE_INOTIFY_INIT*/
2510   npth_attr_destroy (&tattr);
2511   if (listen_fd != GNUPG_INVALID_FD)
2512     assuan_sock_close (listen_fd);
2513   cleanup ();
2514   log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2515 }
2516
2517 const char*
2518 dirmngr_get_current_socket_name (void)
2519 {
2520   if (socket_name)
2521     return socket_name;
2522   else
2523     return dirmngr_socket_name ();
2524 }
2525
2526
2527
2528 /* Parse the revision part from the extended version blurb.  */
2529 static const char *
2530 get_revision_from_blurb (const char *blurb, int *r_len)
2531 {
2532   const char *s = blurb? blurb : "";
2533   int n;
2534
2535   for (; *s; s++)
2536     if (*s == '\n' && s[1] == '(')
2537       break;
2538   if (*s)
2539     {
2540       s += 2;
2541       for (n=0; s[n] && s[n] != ' '; n++)
2542         ;
2543     }
2544   else
2545     {
2546       s = "?";
2547       n = 1;
2548     }
2549   *r_len = n;
2550   return s;
2551 }
2552
2553
2554 /* Print versions of dirmngr and used libraries.  This is used by
2555  * "gpgconf --show-versions" so that there is no need to link gpgconf
2556  * against all these libraries.  This is an internal API and should
2557  * not be relied upon.  */
2558 static void
2559 gpgconf_versions (void)
2560 {
2561   const char *s;
2562   int n;
2563
2564   /* Unfortunately Npth has no way to get the version.  */
2565
2566   s = get_revision_from_blurb (assuan_check_version ("\x01\x01"), &n);
2567   es_fprintf (es_stdout, "* Libassuan %s (%.*s)\n\n",
2568               assuan_check_version (NULL), n, s);
2569
2570   s = get_revision_from_blurb (ksba_check_version ("\x01\x01"), &n);
2571   es_fprintf (es_stdout, "* KSBA %s (%.*s)\n\n",
2572               ksba_check_version (NULL), n, s);
2573
2574 #ifdef HTTP_USE_NTBTLS
2575   s = get_revision_from_blurb (ntbtls_check_version ("\x01\x01"), &n);
2576   es_fprintf (es_stdout, "* NTBTLS %s (%.*s)\n\n",
2577               ntbtls_check_version (NULL), n, s);
2578 #elif HTTP_USE_GNUTLS
2579   es_fprintf (es_stdout, "* GNUTLS %s\n\n",
2580               gnutls_check_version (NULL));
2581 #endif
2582
2583 }