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