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