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