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