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