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