chiark / gitweb /
0b8bb02e6aedc77fdb6626a28701e2faab0cdcbb
[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       if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
478         {
479           log_error ("error enabling Tor mode: %s\n", strerror (errno));
480           log_info ("(is your Libassuan recent enough?)\n");
481         }
482     }
483 }
484
485
486 static void
487 wrong_args (const char *text)
488 {
489   es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME);
490   es_fputs (text, es_stderr);
491   es_putc ('\n', es_stderr);
492   dirmngr_exit (2);
493 }
494
495
496 /* Helper to stop the reaper thread for the ldap wrapper.  */
497 static void
498 shutdown_reaper (void)
499 {
500 #if USE_LDAP
501   ldap_wrapper_wait_connections ();
502 #endif
503 }
504
505
506 /* Handle options which are allowed to be reset after program start.
507    Return true if the current option in PARGS could be handled and
508    false if not.  As a special feature, passing a value of NULL for
509    PARGS, resets the options to the default.  REREAD should be set
510    true if it is not the initial option parsing. */
511 static int
512 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
513 {
514   if (!pargs)
515     { /* Reset mode. */
516       opt.quiet = 0;
517       opt.verbose = 0;
518       opt.debug = 0;
519       opt.ldap_wrapper_program = NULL;
520       opt.disable_http = 0;
521       opt.disable_ldap = 0;
522       opt.honor_http_proxy = 0;
523       opt.http_proxy = NULL;
524       opt.ldap_proxy = NULL;
525       opt.only_ldap_proxy = 0;
526       opt.ignore_http_dp = 0;
527       opt.ignore_ldap_dp = 0;
528       opt.ignore_ocsp_service_url = 0;
529       opt.allow_ocsp = 0;
530       opt.allow_version_check = 0;
531       opt.ocsp_responder = NULL;
532       opt.ocsp_max_clock_skew = 10 * 60;      /* 10 minutes.  */
533       opt.ocsp_max_period = 90 * 86400;       /* 90 days.  */
534       opt.ocsp_current_period = 3 * 60 * 60;  /* 3 hours. */
535       opt.max_replies = DEFAULT_MAX_REPLIES;
536       while (opt.ocsp_signer)
537         {
538           fingerprint_list_t tmp = opt.ocsp_signer->next;
539           xfree (opt.ocsp_signer);
540           opt.ocsp_signer = tmp;
541         }
542       FREE_STRLIST (opt.ignored_cert_extensions);
543       http_register_tls_ca (NULL);
544       FREE_STRLIST (opt.keyserver);
545       /* Note: We do not allow resetting of opt.use_tor at runtime.  */
546       disable_check_own_socket = 0;
547       enable_standard_resolver (0);
548       set_dns_timeout (0);
549       return 1;
550     }
551
552   switch (pargs->r_opt)
553     {
554     case oQuiet:   opt.quiet = 1; break;
555     case oVerbose: opt.verbose++; break;
556     case oDebug:
557       parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
558       break;
559     case oDebugAll: opt.debug = ~0; break;
560     case oDebugLevel: debug_level = pargs->r.ret_str; break;
561     case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break;
562
563     case oLogFile:
564       if (!reread)
565         return 0; /* Not handled. */
566       if (!current_logfile || !pargs->r.ret_str
567           || strcmp (current_logfile, pargs->r.ret_str))
568         {
569           log_set_file (pargs->r.ret_str);
570           xfree (current_logfile);
571           current_logfile = xtrystrdup (pargs->r.ret_str);
572         }
573       break;
574
575     case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
576
577     case oLDAPWrapperProgram:
578       opt.ldap_wrapper_program = pargs->r.ret_str;
579       break;
580     case oHTTPWrapperProgram:
581       opt.http_wrapper_program = pargs->r.ret_str;
582       break;
583
584     case oDisableHTTP: opt.disable_http = 1; break;
585     case oDisableLDAP: opt.disable_ldap = 1; break;
586     case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
587     case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
588     case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
589     case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
590     case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
591     case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
592     case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
593
594     case oAllowOCSP: opt.allow_ocsp = 1; break;
595     case oAllowVersionCheck: opt.allow_version_check = 1; break;
596     case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
597     case oOCSPSigner:
598       opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str);
599       break;
600     case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
601     case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
602     case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
603
604     case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
605
606     case oHkpCaCert:
607       {
608         char *tmpname;
609
610         /* Do tilde expansion and make path absolute.  */
611         tmpname = make_absfilename (pargs->r.ret_str, NULL);
612         http_register_tls_ca (tmpname);
613         xfree (tmpname);
614       }
615       break;
616
617     case oIgnoreCertExtension:
618       add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
619       break;
620
621     case oUseTor: opt.use_tor = 1; break;
622
623     case oStandardResolver: enable_standard_resolver (1); break;
624     case oRecursiveResolver: enable_recursive_resolver (1); break;
625
626     case oKeyServer:
627       if (*pargs->r.ret_str)
628         add_to_strlist (&opt.keyserver, pargs->r.ret_str);
629       break;
630
631     case oNameServer:
632       set_dns_nameserver (pargs->r.ret_str);
633       break;
634
635     case oResolverTimeout:
636       set_dns_timeout (pargs->r.ret_int);
637       break;
638
639     default:
640       return 0; /* Not handled. */
641     }
642
643   set_dns_verbose (opt.verbose, !!DBG_DNS);
644
645   return 1; /* Handled. */
646 }
647
648
649 #ifndef HAVE_W32_SYSTEM
650 static int
651 pid_suffix_callback (unsigned long *r_suffix)
652 {
653   union int_and_ptr_u value;
654
655   memset (&value, 0, sizeof value);
656   value.aptr = npth_getspecific (my_tlskey_current_fd);
657   *r_suffix = value.aint;
658   return (*r_suffix != -1);  /* Use decimal representation.  */
659 }
660 #endif /*!HAVE_W32_SYSTEM*/
661
662
663 static void
664 thread_init (void)
665 {
666   npth_init ();
667   gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
668
669   /* Now with NPth running we can set the logging callback.  Our
670      windows implementation does not yet feature the NPth TLS
671      functions.  */
672 #ifndef HAVE_W32_SYSTEM
673   if (npth_key_create (&my_tlskey_current_fd, NULL) == 0)
674     if (npth_setspecific (my_tlskey_current_fd, NULL) == 0)
675       log_set_pid_suffix_cb (pid_suffix_callback);
676 #endif /*!HAVE_W32_SYSTEM*/
677 }
678
679
680 int
681 main (int argc, char **argv)
682 {
683   enum cmd_and_opt_values cmd = 0;
684   ARGPARSE_ARGS pargs;
685   int orig_argc;
686   char **orig_argv;
687   FILE *configfp = NULL;
688   char *configname = NULL;
689   const char *shell;
690   unsigned configlineno;
691   int parse_debug = 0;
692   int default_config =1;
693   int greeting = 0;
694   int nogreeting = 0;
695   int nodetach = 0;
696   int csh_style = 0;
697   char *logfile = NULL;
698 #if USE_LDAP
699   char *ldapfile = NULL;
700 #endif /*USE_LDAP*/
701   int debug_wait = 0;
702   int rc;
703   struct assuan_malloc_hooks malloc_hooks;
704
705   early_system_init ();
706   set_strusage (my_strusage);
707   log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
708
709   /* Make sure that our subsystems are ready.  */
710   i18n_init ();
711   init_common_subsystems (&argc, &argv);
712
713   gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
714
715  /* Check that the libraries are suitable.  Do it here because
716     the option parsing may need services of the libraries. */
717   if (!ksba_check_version (NEED_KSBA_VERSION) )
718     log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba",
719                NEED_KSBA_VERSION, ksba_check_version (NULL) );
720
721   ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
722   ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
723
724   /* Init TLS library.  */
725 #if HTTP_USE_NTBTLS
726   if (!ntbtls_check_version (NEED_NTBTLS_VERSION) )
727     log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls",
728                NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) );
729 #elif HTTP_USE_GNUTLS
730   rc = gnutls_global_init ();
731   if (rc)
732     log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));
733 #endif /*HTTP_USE_GNUTLS*/
734
735   /* Init Assuan. */
736   malloc_hooks.malloc = gcry_malloc;
737   malloc_hooks.realloc = gcry_realloc;
738   malloc_hooks.free = gcry_free;
739   assuan_set_malloc_hooks (&malloc_hooks);
740   assuan_set_assuan_log_prefix (log_get_prefix (NULL));
741   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
742   assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
743   assuan_sock_init ();
744   setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor);
745
746   setup_libgcrypt_logging ();
747
748   /* Setup defaults. */
749   shell = getenv ("SHELL");
750   if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
751     csh_style = 1;
752
753   /* Reset rereadable options to default values. */
754   parse_rereadable_options (NULL, 0);
755
756   /* LDAP defaults.  */
757   opt.add_new_ldapservers = 0;
758   opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
759
760   /* Other defaults.  */
761
762   /* Check whether we have a config file given on the commandline */
763   orig_argc = argc;
764   orig_argv = argv;
765   pargs.argc = &argc;
766   pargs.argv = &argv;
767   pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
768   while (arg_parse( &pargs, opts))
769     {
770       if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
771         parse_debug++;
772       else if (pargs.r_opt == oOptions)
773         { /* Yes there is one, so we do not try the default one, but
774              read the option file when it is encountered at the
775              commandline */
776           default_config = 0;
777         }
778       else if (pargs.r_opt == oNoOptions)
779         default_config = 0; /* --no-options */
780       else if (pargs.r_opt == oHomedir)
781         {
782           gnupg_set_homedir (pargs.r.ret_str);
783         }
784     }
785
786   socket_name = dirmngr_socket_name ();
787   if (default_config)
788     configname = make_filename (gnupg_homedir (), DIRMNGR_NAME".conf", NULL );
789
790   argc = orig_argc;
791   argv = orig_argv;
792   pargs.argc = &argc;
793   pargs.argv = &argv;
794   pargs.flags= 1;  /* do not remove the args */
795  next_pass:
796   if (configname)
797     {
798       configlineno = 0;
799       configfp = fopen (configname, "r");
800       if (!configfp)
801         {
802           if (default_config)
803             {
804               if( parse_debug )
805                 log_info (_("Note: no default option file '%s'\n"),
806                           configname );
807             }
808           else
809             {
810               log_error (_("option file '%s': %s\n"),
811                          configname, strerror(errno) );
812               exit(2);
813             }
814           xfree (configname);
815           configname = NULL;
816         }
817       if (parse_debug && configname )
818         log_info (_("reading options from '%s'\n"), configname );
819       default_config = 0;
820     }
821
822   while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
823     {
824       if (parse_rereadable_options (&pargs, 0))
825         continue; /* Already handled */
826       switch (pargs.r_opt)
827         {
828         case aServer:
829         case aDaemon:
830         case aSupervised:
831         case aShutdown:
832         case aFlush:
833         case aListCRLs:
834         case aLoadCRL:
835         case aFetchCRL:
836         case aGPGConfList:
837         case aGPGConfTest:
838           cmd = pargs.r_opt;
839           break;
840
841         case oQuiet: opt.quiet = 1; break;
842         case oVerbose: opt.verbose++; break;
843         case oBatch: opt.batch=1; break;
844
845         case oDebugWait: debug_wait = pargs.r.ret_int; break;
846
847         case oOptions:
848           /* Config files may not be nested (silently ignore them) */
849           if (!configfp)
850             {
851                 xfree(configname);
852                 configname = xstrdup(pargs.r.ret_str);
853                 goto next_pass;
854             }
855           break;
856         case oNoGreeting: nogreeting = 1; break;
857         case oNoVerbose: opt.verbose = 0; break;
858         case oNoOptions: break; /* no-options */
859         case oHomedir: /* Ignore this option here. */; break;
860         case oNoDetach: nodetach = 1; break;
861         case oLogFile: logfile = pargs.r.ret_str; break;
862         case oCsh: csh_style = 1; break;
863         case oSh: csh_style = 0; break;
864         case oLDAPFile:
865 #        if USE_LDAP
866           ldapfile = pargs.r.ret_str;
867 #        endif /*USE_LDAP*/
868           break;
869         case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
870         case oLDAPTimeout:
871           opt.ldaptimeout = pargs.r.ret_int;
872           break;
873
874         case oFakedSystemTime:
875           gnupg_set_time ((time_t)pargs.r.ret_ulong, 0);
876           break;
877
878         case oForce: opt.force = 1; break;
879
880         case oSocketName: socket_name = pargs.r.ret_str; break;
881
882         default : pargs.err = configfp? 1:2; break;
883         }
884     }
885   if (configfp)
886     {
887       fclose (configfp);
888       configfp = NULL;
889       /* Keep a copy of the name so that it can be read on SIGHUP. */
890       opt.config_filename = configname;
891       configname = NULL;
892       goto next_pass;
893     }
894   xfree (configname);
895   configname = NULL;
896   if (log_get_errorcount(0))
897     exit(2);
898   if (nogreeting )
899     greeting = 0;
900
901   if (!opt.homedir_cache)
902     opt.homedir_cache = xstrdup (gnupg_homedir ());
903
904   if (greeting)
905     {
906       es_fprintf (es_stderr, "%s %s; %s\n",
907                   strusage(11), strusage(13), strusage(14) );
908       es_fprintf (es_stderr, "%s\n", strusage(15) );
909     }
910
911 #ifdef IS_DEVELOPMENT_VERSION
912   log_info ("NOTE: this is a development version!\n");
913 #endif
914
915   if (opt.use_tor)
916     {
917       log_info ("WARNING: ***************************************\n");
918       log_info ("WARNING: Tor mode (--use-tor) MAY NOT FULLY WORK!\n");
919       log_info ("WARNING: ***************************************\n");
920     }
921
922   /* Print a warning if an argument looks like an option.  */
923   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
924     {
925       int i;
926
927       for (i=0; i < argc; i++)
928         if (argv[i][0] == '-' && argv[i][1] == '-')
929           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
930     }
931
932   if (!access ("/etc/"DIRMNGR_NAME, F_OK)
933       && !strncmp (gnupg_homedir (), "/etc/", 5))
934     log_info
935       ("NOTE: DirMngr is now a proper part of %s.  The configuration and"
936        " other directory names changed.  Please check that no other version"
937        " of dirmngr is still installed.  To disable this warning, remove the"
938        " directory '/etc/dirmngr'.\n", GNUPG_NAME);
939
940   if (gnupg_faked_time_p ())
941     {
942       gnupg_isotime_t tbuf;
943
944       log_info (_("WARNING: running with faked system time: "));
945       gnupg_get_isotime (tbuf);
946       dump_isotime (tbuf);
947       log_printf ("\n");
948     }
949
950   set_debug ();
951   set_tor_mode ();
952
953   /* Get LDAP server list from file. */
954 #if USE_LDAP
955   if (!ldapfile)
956     {
957       ldapfile = make_filename (gnupg_homedir (),
958                                 "dirmngr_ldapservers.conf",
959                                 NULL);
960       opt.ldapservers = parse_ldapserver_file (ldapfile);
961       xfree (ldapfile);
962     }
963   else
964       opt.ldapservers = parse_ldapserver_file (ldapfile);
965 #endif /*USE_LDAP*/
966
967 #ifndef HAVE_W32_SYSTEM
968   /* We need to ignore the PIPE signal because the we might log to a
969      socket and that code handles EPIPE properly.  The ldap wrapper
970      also requires us to ignore this silly signal. Assuan would set
971      this signal to ignore anyway.*/
972   signal (SIGPIPE, SIG_IGN);
973 #endif
974
975   /* Ready.  Now to our duties. */
976   if (!cmd)
977     cmd = aServer;
978   rc = 0;
979
980   if (cmd == aServer)
981     {
982       /* Note that this server mode is mainly useful for debugging.  */
983       if (argc)
984         wrong_args ("--server");
985
986       if (logfile)
987         {
988           log_set_file (logfile);
989           log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
990         }
991
992       if (debug_wait)
993         {
994           log_debug ("waiting for debugger - my pid is %u .....\n",
995                      (unsigned int)getpid());
996           gnupg_sleep (debug_wait);
997           log_debug ("... okay\n");
998         }
999
1000
1001       thread_init ();
1002       cert_cache_init ();
1003       crl_cache_init ();
1004       http_register_netactivity_cb (netactivity_action);
1005       start_command_handler (ASSUAN_INVALID_FD);
1006       shutdown_reaper ();
1007     }
1008 #ifndef HAVE_W32_SYSTEM
1009   else if (cmd == aSupervised)
1010     {
1011       /* In supervised mode, we expect file descriptor 3 to be an
1012          already opened, listening socket.
1013
1014          We will also not detach from the controlling process or close
1015          stderr; the supervisor should handle all of that.  */
1016       struct stat statbuf;
1017       if (fstat (3, &statbuf) == -1 && errno == EBADF)
1018         {
1019           log_error ("file descriptor 3 must be validin --supervised mode\n");
1020           dirmngr_exit (1);
1021         }
1022       socket_name = gnupg_get_socket_name (3);
1023
1024       /* Now start with logging to a file if this is desired. */
1025       if (logfile)
1026         {
1027           log_set_file (logfile);
1028           log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1029                                  |GPGRT_LOG_WITH_TIME
1030                                  |GPGRT_LOG_WITH_PID));
1031           current_logfile = xstrdup (logfile);
1032         }
1033       else
1034         log_set_prefix (NULL, 0);
1035
1036       thread_init ();
1037       cert_cache_init ();
1038       crl_cache_init ();
1039       http_register_netactivity_cb (netactivity_action);
1040       handle_connections (3);
1041       shutdown_reaper ();
1042     }
1043 #endif /*HAVE_W32_SYSTEM*/
1044   else if (cmd == aDaemon)
1045     {
1046       assuan_fd_t fd;
1047       pid_t pid;
1048       int len;
1049       struct sockaddr_un serv_addr;
1050
1051       if (argc)
1052         wrong_args ("--daemon");
1053
1054       /* Now start with logging to a file if this is desired. */
1055       if (logfile)
1056         {
1057           log_set_file (logfile);
1058           log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1059                                  |GPGRT_LOG_WITH_TIME
1060                                  |GPGRT_LOG_WITH_PID));
1061           current_logfile = xstrdup (logfile);
1062         }
1063
1064 #ifndef HAVE_W32_SYSTEM
1065       if (strchr (socket_name, ':'))
1066         {
1067           log_error (_("colons are not allowed in the socket name\n"));
1068           dirmngr_exit (1);
1069         }
1070 #endif
1071       fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1072       if (fd == ASSUAN_INVALID_FD)
1073         {
1074           log_error (_("can't create socket: %s\n"), strerror (errno));
1075           cleanup ();
1076           dirmngr_exit (1);
1077         }
1078
1079       {
1080         int redirected;
1081
1082         if (assuan_sock_set_sockaddr_un (socket_name,
1083                                          (struct sockaddr*)&serv_addr,
1084                                          &redirected))
1085           {
1086             if (errno == ENAMETOOLONG)
1087               log_error (_("socket name '%s' is too long\n"), socket_name);
1088             else
1089               log_error ("error preparing socket '%s': %s\n",
1090                          socket_name,
1091                          gpg_strerror (gpg_error_from_syserror ()));
1092             dirmngr_exit (1);
1093           }
1094         if (redirected)
1095           {
1096             redir_socket_name = xstrdup (serv_addr.sun_path);
1097             if (opt.verbose)
1098               log_info ("redirecting socket '%s' to '%s'\n",
1099                         socket_name, redir_socket_name);
1100           }
1101       }
1102
1103       len = SUN_LEN (&serv_addr);
1104
1105       rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1106       if (rc == -1
1107           && (errno == EADDRINUSE
1108 #ifdef HAVE_W32_SYSTEM
1109               || errno == EEXIST
1110 #endif
1111               ))
1112         {
1113           /* Fixme: We should test whether a dirmngr is already running. */
1114           gnupg_remove (redir_socket_name? redir_socket_name : socket_name);
1115           rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1116         }
1117       if (rc != -1
1118           && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
1119         log_error (_("error getting nonce for the socket\n"));
1120       if (rc == -1)
1121         {
1122           log_error (_("error binding socket to '%s': %s\n"),
1123                      serv_addr.sun_path,
1124                      gpg_strerror (gpg_error_from_errno (errno)));
1125           assuan_sock_close (fd);
1126           dirmngr_exit (1);
1127         }
1128       cleanup_socket = 1;
1129
1130       if (gnupg_chmod (serv_addr.sun_path, "-rwx"))
1131         log_error (_("can't set permissions of '%s': %s\n"),
1132                    serv_addr.sun_path, strerror (errno));
1133
1134       if (listen (FD2INT (fd), 5) == -1)
1135         {
1136           log_error (_("listen() failed: %s\n"), strerror (errno));
1137           assuan_sock_close (fd);
1138           dirmngr_exit (1);
1139         }
1140
1141       if (opt.verbose)
1142         log_info (_("listening on socket '%s'\n"), serv_addr.sun_path);
1143
1144       es_fflush (NULL);
1145
1146       /* Note: We keep the dirmngr_info output only for the sake of
1147          existing scripts which might use this to detect a successful
1148          start of the dirmngr.  */
1149 #ifdef HAVE_W32_SYSTEM
1150       (void)csh_style;
1151       (void)nodetach;
1152
1153       pid = getpid ();
1154       es_printf ("set %s=%s;%lu;1\n",
1155                  DIRMNGR_INFO_NAME, socket_name, (ulong) pid);
1156 #else
1157       pid = fork();
1158       if (pid == (pid_t)-1)
1159         {
1160           log_fatal (_("error forking process: %s\n"), strerror (errno));
1161           dirmngr_exit (1);
1162         }
1163
1164       if (pid)
1165         { /* We are the parent */
1166           char *infostr;
1167
1168           /* Don't let cleanup() remove the socket - the child is
1169              responsible for doing that.  */
1170           cleanup_socket = 0;
1171
1172           close (fd);
1173
1174           /* Create the info string: <name>:<pid>:<protocol_version> */
1175           if (asprintf (&infostr, "%s=%s:%lu:1",
1176                         DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0)
1177             {
1178               log_error (_("out of core\n"));
1179               kill (pid, SIGTERM);
1180               dirmngr_exit (1);
1181             }
1182           /* Print the environment string, so that the caller can use
1183              shell's eval to set it.  But see above.  */
1184           if (csh_style)
1185             {
1186               *strchr (infostr, '=') = ' ';
1187               es_printf ( "setenv %s;\n", infostr);
1188             }
1189           else
1190             {
1191               es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME);
1192             }
1193           free (infostr);
1194           exit (0);
1195           /*NEVER REACHED*/
1196         } /* end parent */
1197
1198
1199       /*
1200          This is the child
1201        */
1202
1203       /* Detach from tty and put process into a new session */
1204       if (!nodetach )
1205         {
1206           int i;
1207           unsigned int oldflags;
1208
1209           /* Close stdin, stdout and stderr unless it is the log stream */
1210           for (i=0; i <= 2; i++)
1211             {
1212               if (!log_test_fd (i) && i != fd )
1213                 {
1214                   if ( !close (i)
1215                        && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1216                     {
1217                       log_error ("failed to open '%s': %s\n",
1218                                  "/dev/null", strerror (errno));
1219                       cleanup ();
1220                       dirmngr_exit (1);
1221                     }
1222                 }
1223             }
1224
1225           if (setsid() == -1)
1226             {
1227               log_error ("setsid() failed: %s\n", strerror(errno) );
1228               dirmngr_exit (1);
1229             }
1230
1231           log_get_prefix (&oldflags);
1232           log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1233           opt.running_detached = 1;
1234
1235           if (chdir("/"))
1236             {
1237               log_error ("chdir to / failed: %s\n", strerror (errno));
1238               dirmngr_exit (1);
1239             }
1240         }
1241 #endif
1242
1243       thread_init ();
1244       cert_cache_init ();
1245       crl_cache_init ();
1246       http_register_netactivity_cb (netactivity_action);
1247       handle_connections (fd);
1248       shutdown_reaper ();
1249     }
1250   else if (cmd == aListCRLs)
1251     {
1252       /* Just list the CRL cache and exit. */
1253       if (argc)
1254         wrong_args ("--list-crls");
1255       crl_cache_init ();
1256       crl_cache_list (es_stdout);
1257     }
1258   else if (cmd == aLoadCRL)
1259     {
1260       struct server_control_s ctrlbuf;
1261
1262       memset (&ctrlbuf, 0, sizeof ctrlbuf);
1263       dirmngr_init_default_ctrl (&ctrlbuf);
1264
1265       thread_init ();
1266       cert_cache_init ();
1267       crl_cache_init ();
1268       if (!argc)
1269         rc = crl_cache_load (&ctrlbuf, NULL);
1270       else
1271         {
1272           for (; !rc && argc; argc--, argv++)
1273             rc = crl_cache_load (&ctrlbuf, *argv);
1274         }
1275       dirmngr_deinit_default_ctrl (&ctrlbuf);
1276     }
1277   else if (cmd == aFetchCRL)
1278     {
1279       ksba_reader_t reader;
1280       struct server_control_s ctrlbuf;
1281
1282       if (argc != 1)
1283         wrong_args ("--fetch-crl URL");
1284
1285       memset (&ctrlbuf, 0, sizeof ctrlbuf);
1286       dirmngr_init_default_ctrl (&ctrlbuf);
1287
1288       thread_init ();
1289       cert_cache_init ();
1290       crl_cache_init ();
1291       rc = crl_fetch (&ctrlbuf, argv[0], &reader);
1292       if (rc)
1293         log_error (_("fetching CRL from '%s' failed: %s\n"),
1294                      argv[0], gpg_strerror (rc));
1295       else
1296         {
1297           rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
1298           if (rc)
1299             log_error (_("processing CRL from '%s' failed: %s\n"),
1300                        argv[0], gpg_strerror (rc));
1301           crl_close_reader (reader);
1302         }
1303       dirmngr_deinit_default_ctrl (&ctrlbuf);
1304     }
1305   else if (cmd == aFlush)
1306     {
1307       /* Delete cache and exit. */
1308       if (argc)
1309         wrong_args ("--flush");
1310       rc = crl_cache_flush();
1311     }
1312   else if (cmd == aGPGConfTest)
1313     dirmngr_exit (0);
1314   else if (cmd == aGPGConfList)
1315     {
1316       unsigned long flags = 0;
1317       char *filename;
1318       char *filename_esc;
1319
1320       /* First the configuration file.  This is not an option, but it
1321          is vital information for GPG Conf.  */
1322       if (!opt.config_filename)
1323         opt.config_filename = make_filename (gnupg_homedir (),
1324                                              "dirmngr.conf", NULL );
1325
1326       filename = percent_escape (opt.config_filename, NULL);
1327       es_printf ("gpgconf-dirmngr.conf:%lu:\"%s\n",
1328               GC_OPT_FLAG_DEFAULT, filename);
1329       xfree (filename);
1330
1331       es_printf ("verbose:%lu:\n", flags | GC_OPT_FLAG_NONE);
1332       es_printf ("quiet:%lu:\n", flags | GC_OPT_FLAG_NONE);
1333       es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
1334       es_printf ("log-file:%lu:\n", flags | GC_OPT_FLAG_NONE);
1335       es_printf ("force:%lu:\n", flags | GC_OPT_FLAG_NONE);
1336
1337       /* --csh and --sh are mutually exclusive, something we can not
1338          express in GPG Conf.  --options is only usable from the
1339          command line, really.  --debug-all interacts with --debug,
1340          and having both of them is thus problematic.  --no-detach is
1341          also only usable on the command line.  --batch is unused.  */
1342
1343       filename = make_filename (gnupg_homedir (),
1344                                 "dirmngr_ldapservers.conf",
1345                                 NULL);
1346       filename_esc = percent_escape (filename, NULL);
1347       es_printf ("ldapserverlist-file:%lu:\"%s\n", flags | GC_OPT_FLAG_DEFAULT,
1348               filename_esc);
1349       xfree (filename_esc);
1350       xfree (filename);
1351
1352       es_printf ("ldaptimeout:%lu:%u\n",
1353               flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
1354       es_printf ("max-replies:%lu:%u\n",
1355               flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
1356       es_printf ("allow-ocsp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1357       es_printf ("allow-version-check:%lu:\n", flags | GC_OPT_FLAG_NONE);
1358       es_printf ("ocsp-responder:%lu:\n", flags | GC_OPT_FLAG_NONE);
1359       es_printf ("ocsp-signer:%lu:\n", flags | GC_OPT_FLAG_NONE);
1360
1361       es_printf ("faked-system-time:%lu:\n", flags | GC_OPT_FLAG_NONE);
1362       es_printf ("no-greeting:%lu:\n", flags | GC_OPT_FLAG_NONE);
1363
1364       es_printf ("disable-http:%lu:\n", flags | GC_OPT_FLAG_NONE);
1365       es_printf ("disable-ldap:%lu:\n", flags | GC_OPT_FLAG_NONE);
1366       es_printf ("honor-http-proxy:%lu\n", flags | GC_OPT_FLAG_NONE);
1367       es_printf ("http-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1368       es_printf ("ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1369       es_printf ("only-ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1370       es_printf ("ignore-ldap-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1371       es_printf ("ignore-http-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1372       es_printf ("ignore-ocsp-service-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1373       /* Note: The next one is to fix a typo in gpgconf - should be
1374          removed eventually. */
1375       es_printf ("ignore-ocsp-servic-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1376
1377       es_printf ("use-tor:%lu:\n", flags | GC_OPT_FLAG_NONE);
1378       es_printf ("keyserver:%lu:\n", flags | GC_OPT_FLAG_NONE);
1379       es_printf ("nameserver:%lu:\n", flags | GC_OPT_FLAG_NONE);
1380       es_printf ("resolver-timeout:%lu:%u\n",
1381                  flags | GC_OPT_FLAG_DEFAULT, 0);
1382     }
1383   cleanup ();
1384   return !!rc;
1385 }
1386
1387
1388 static void
1389 cleanup (void)
1390 {
1391   crl_cache_deinit ();
1392   cert_cache_deinit (1);
1393   reload_dns_stuff (1);
1394
1395 #if USE_LDAP
1396   ldapserver_list_free (opt.ldapservers);
1397 #endif /*USE_LDAP*/
1398   opt.ldapservers = NULL;
1399
1400   if (cleanup_socket)
1401     {
1402       cleanup_socket = 0;
1403       if (redir_socket_name)
1404         gnupg_remove (redir_socket_name);
1405       else if (socket_name && *socket_name)
1406         gnupg_remove (socket_name);
1407     }
1408 }
1409
1410
1411 void
1412 dirmngr_exit (int rc)
1413 {
1414   cleanup ();
1415   exit (rc);
1416 }
1417
1418
1419 void
1420 dirmngr_init_default_ctrl (ctrl_t ctrl)
1421 {
1422   if (opt.http_proxy)
1423     ctrl->http_proxy = xstrdup (opt.http_proxy);
1424 }
1425
1426
1427 void
1428 dirmngr_deinit_default_ctrl (ctrl_t ctrl)
1429 {
1430   if (!ctrl)
1431     return;
1432   xfree (ctrl->http_proxy);
1433   ctrl->http_proxy = NULL;
1434 }
1435
1436
1437 /* Create a list of LDAP servers from the file FILENAME. Returns the
1438    list or NULL in case of errors.
1439
1440    The format fo such a file is line oriented where empty lines and
1441    lines starting with a hash mark are ignored.  All other lines are
1442    assumed to be colon seprated with these fields:
1443
1444    1. field: Hostname
1445    2. field: Portnumber
1446    3. field: Username
1447    4. field: Password
1448    5. field: Base DN
1449
1450 */
1451 #if USE_LDAP
1452 static ldap_server_t
1453 parse_ldapserver_file (const char* filename)
1454 {
1455   char buffer[1024];
1456   char *p;
1457   ldap_server_t server, serverstart, *serverend;
1458   int c;
1459   unsigned int lineno = 0;
1460   estream_t fp;
1461
1462   fp = es_fopen (filename, "r");
1463   if (!fp)
1464     {
1465       log_error (_("error opening '%s': %s\n"), filename, strerror (errno));
1466       return NULL;
1467     }
1468
1469   serverstart = NULL;
1470   serverend = &serverstart;
1471   while (es_fgets (buffer, sizeof buffer, fp))
1472     {
1473       lineno++;
1474       if (!*buffer || buffer[strlen(buffer)-1] != '\n')
1475         {
1476           if (*buffer && es_feof (fp))
1477             ; /* Last line not terminated - continue. */
1478           else
1479             {
1480               log_error (_("%s:%u: line too long - skipped\n"),
1481                          filename, lineno);
1482               while ( (c=es_fgetc (fp)) != EOF && c != '\n')
1483                 ; /* Skip until end of line. */
1484               continue;
1485             }
1486         }
1487       /* Skip empty and comment lines.*/
1488       for (p=buffer; spacep (p); p++)
1489         ;
1490       if (!*p || *p == '\n' || *p == '#')
1491         continue;
1492
1493       /* Parse the colon separated fields. */
1494       server = ldapserver_parse_one (buffer, filename, lineno);
1495       if (server)
1496         {
1497           *serverend = server;
1498           serverend = &server->next;
1499         }
1500     }
1501
1502   if (es_ferror (fp))
1503     log_error (_("error reading '%s': %s\n"), filename, strerror (errno));
1504   es_fclose (fp);
1505
1506   return serverstart;
1507 }
1508 #endif /*USE_LDAP*/
1509
1510 static fingerprint_list_t
1511 parse_ocsp_signer (const char *string)
1512 {
1513   gpg_error_t err;
1514   char *fname;
1515   estream_t fp;
1516   char line[256];
1517   char *p;
1518   fingerprint_list_t list, *list_tail, item;
1519   unsigned int lnr = 0;
1520   int c, i, j;
1521   int errflag = 0;
1522
1523
1524   /* Check whether this is not a filename and treat it as a direct
1525      fingerprint specification.  */
1526   if (!strpbrk (string, "/.~\\"))
1527     {
1528       item = xcalloc (1, sizeof *item);
1529       for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
1530         if ( string[i] != ':' )
1531           item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
1532       item->hexfpr[j] = 0;
1533       if (j != 40 || !(spacep (string+i) || !string[i]))
1534         {
1535           log_error (_("%s:%u: invalid fingerprint detected\n"),
1536                      "--ocsp-signer", 0);
1537           xfree (item);
1538           return NULL;
1539         }
1540       return item;
1541     }
1542
1543   /* Well, it is a filename.  */
1544   if (*string == '/' || (*string == '~' && string[1] == '/'))
1545     fname = make_filename (string, NULL);
1546   else
1547     {
1548       if (string[0] == '.' && string[1] == '/' )
1549         string += 2;
1550       fname = make_filename (gnupg_homedir (), string, NULL);
1551     }
1552
1553   fp = es_fopen (fname, "r");
1554   if (!fp)
1555     {
1556       err = gpg_error_from_syserror ();
1557       log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
1558       xfree (fname);
1559       return NULL;
1560     }
1561
1562   list = NULL;
1563   list_tail = &list;
1564   for (;;)
1565     {
1566       if (!es_fgets (line, DIM(line)-1, fp) )
1567         {
1568           if (!es_feof (fp))
1569             {
1570               err = gpg_error_from_syserror ();
1571               log_error (_("%s:%u: read error: %s\n"),
1572                          fname, lnr, gpg_strerror (err));
1573               errflag = 1;
1574             }
1575           es_fclose (fp);
1576           if (errflag)
1577             {
1578               while (list)
1579                 {
1580                   fingerprint_list_t tmp = list->next;
1581                   xfree (list);
1582                   list = tmp;
1583                 }
1584             }
1585           xfree (fname);
1586           return list; /* Ready.  */
1587         }
1588
1589       lnr++;
1590       if (!*line || line[strlen(line)-1] != '\n')
1591         {
1592           /* Eat until end of line. */
1593           while ( (c=es_getc (fp)) != EOF && c != '\n')
1594             ;
1595           err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
1596                            /* */: GPG_ERR_INCOMPLETE_LINE);
1597           log_error (_("%s:%u: read error: %s\n"),
1598                      fname, lnr, gpg_strerror (err));
1599           errflag = 1;
1600           continue;
1601         }
1602
1603       /* Allow for empty lines and spaces */
1604       for (p=line; spacep (p); p++)
1605         ;
1606       if (!*p || *p == '\n' || *p == '#')
1607         continue;
1608
1609       item = xcalloc (1, sizeof *item);
1610       *list_tail = item;
1611       list_tail = &item->next;
1612
1613       for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
1614         if ( p[i] != ':' )
1615           item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
1616       item->hexfpr[j] = 0;
1617       if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
1618         {
1619           log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
1620           errflag = 1;
1621         }
1622       i++;
1623       while (spacep (p+i))
1624         i++;
1625       if (p[i] && p[i] != '\n')
1626         log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
1627     }
1628   /*NOTREACHED*/
1629 }
1630
1631
1632
1633 \f
1634 /*
1635    Stuff used in daemon mode.
1636  */
1637
1638
1639
1640 /* Reread parts of the configuration.  Note, that this function is
1641    obviously not thread-safe and should only be called from the NPTH
1642    signal handler.
1643
1644    Fixme: Due to the way the argument parsing works, we create a
1645    memory leak here for all string type arguments.  There is currently
1646    no clean way to tell whether the memory for the argument has been
1647    allocated or points into the process' original arguments.  Unless
1648    we have a mechanism to tell this, we need to live on with this. */
1649 static void
1650 reread_configuration (void)
1651 {
1652   ARGPARSE_ARGS pargs;
1653   FILE *fp;
1654   unsigned int configlineno = 0;
1655   int dummy;
1656
1657   if (!opt.config_filename)
1658     return; /* No config file. */
1659
1660   fp = fopen (opt.config_filename, "r");
1661   if (!fp)
1662     {
1663       log_error (_("option file '%s': %s\n"),
1664                  opt.config_filename, strerror(errno) );
1665       return;
1666     }
1667
1668   parse_rereadable_options (NULL, 1); /* Start from the default values. */
1669
1670   memset (&pargs, 0, sizeof pargs);
1671   dummy = 0;
1672   pargs.argc = &dummy;
1673   pargs.flags = 1;  /* do not remove the args */
1674   while (optfile_parse (fp, opt.config_filename, &configlineno, &pargs, opts) )
1675     {
1676       if (pargs.r_opt < -1)
1677         pargs.err = 1; /* Print a warning. */
1678       else /* Try to parse this option - ignore unchangeable ones. */
1679         parse_rereadable_options (&pargs, 1);
1680     }
1681   fclose (fp);
1682
1683   set_debug ();
1684   set_tor_mode ();
1685 }
1686
1687
1688 /* A global function which allows us to trigger the reload stuff from
1689    other places.  */
1690 void
1691 dirmngr_sighup_action (void)
1692 {
1693   log_info (_("SIGHUP received - "
1694               "re-reading configuration and flushing caches\n"));
1695   reread_configuration ();
1696   cert_cache_deinit (0);
1697   crl_cache_deinit ();
1698   cert_cache_init ();
1699   crl_cache_init ();
1700   reload_dns_stuff (0);
1701 }
1702
1703
1704 /* This function is called if some network activity was done.  At this
1705  * point we know the we have a network and we can decide whether to
1706  * run scheduled background tasks soon.  The function should return
1707  * quickly and only trigger actions for another thread. */
1708 static void
1709 netactivity_action (void)
1710 {
1711   network_activity_seen = 1;
1712 }
1713
1714
1715 /* The signal handler. */
1716 #ifndef HAVE_W32_SYSTEM
1717 static void
1718 handle_signal (int signo)
1719 {
1720   switch (signo)
1721     {
1722     case SIGHUP:
1723       dirmngr_sighup_action ();
1724       break;
1725
1726     case SIGUSR1:
1727       cert_cache_print_stats ();
1728       break;
1729
1730     case SIGUSR2:
1731       log_info (_("SIGUSR2 received - no action defined\n"));
1732       break;
1733
1734     case SIGTERM:
1735       if (!shutdown_pending)
1736         log_info (_("SIGTERM received - shutting down ...\n"));
1737       else
1738         log_info (_("SIGTERM received - still %d active connections\n"),
1739                   active_connections);
1740       shutdown_pending++;
1741       if (shutdown_pending > 2)
1742         {
1743           log_info (_("shutdown forced\n"));
1744           log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1745           cleanup ();
1746           dirmngr_exit (0);
1747         }
1748       break;
1749
1750     case SIGINT:
1751       log_info (_("SIGINT received - immediate shutdown\n"));
1752       log_info( "%s %s stopped\n", strusage(11), strusage(13));
1753       cleanup ();
1754       dirmngr_exit (0);
1755       break;
1756
1757     default:
1758       log_info (_("signal %d received - no action defined\n"), signo);
1759     }
1760 }
1761 #endif /*!HAVE_W32_SYSTEM*/
1762
1763
1764 /* Check the nonce on a new connection.  This is a NOP unless we are
1765    using our Unix domain socket emulation under Windows.  */
1766 static int
1767 check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
1768 {
1769   if (assuan_sock_check_nonce (fd, nonce))
1770     {
1771       log_info (_("error reading nonce on fd %d: %s\n"),
1772                 FD2INT (fd), strerror (errno));
1773       assuan_sock_close (fd);
1774       return -1;
1775     }
1776   else
1777     return 0;
1778 }
1779
1780
1781 /* Helper to call a connection's main function. */
1782 static void *
1783 start_connection_thread (void *arg)
1784 {
1785   union int_and_ptr_u argval;
1786   gnupg_fd_t fd;
1787
1788   memset (&argval, 0, sizeof argval);
1789   argval.aptr = arg;
1790   fd = argval.afd;
1791
1792   if (check_nonce (fd, &socket_nonce))
1793     {
1794       log_error ("handler nonce check FAILED\n");
1795       return NULL;
1796     }
1797
1798 #ifndef HAVE_W32_SYSTEM
1799   npth_setspecific (my_tlskey_current_fd, argval.aptr);
1800 #endif
1801
1802   active_connections++;
1803   if (opt.verbose)
1804     log_info (_("handler for fd %d started\n"), FD2INT (fd));
1805
1806   start_command_handler (fd);
1807
1808   if (opt.verbose)
1809     log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
1810   active_connections--;
1811
1812 #ifndef HAVE_W32_SYSTEM
1813   argval.afd = ASSUAN_INVALID_FD;
1814   npth_setspecific (my_tlskey_current_fd, argval.aptr);
1815 #endif
1816
1817   return NULL;
1818 }
1819
1820
1821 #ifdef HAVE_INOTIFY_INIT
1822 /* Read an inotify event and return true if it matches NAME.  */
1823 static int
1824 my_inotify_is_name (int fd, const char *name)
1825 {
1826   union {
1827     struct inotify_event ev;
1828     char _buf[sizeof (struct inotify_event) + 100 + 1];
1829   } buf;
1830   int n;
1831   const char *s;
1832
1833   s = strrchr (name, '/');
1834   if (s && s[1])
1835     name = s + 1;
1836
1837   n = npth_read (fd, &buf, sizeof buf);
1838   if (n < sizeof (struct inotify_event))
1839     return 0;
1840   if (buf.ev.len < strlen (name)+1)
1841     return 0;
1842   if (strcmp (buf.ev.name, name))
1843     return 0; /* Not the desired file.  */
1844
1845   return 1; /* Found.  */
1846 }
1847 #endif /*HAVE_INOTIFY_INIT*/
1848
1849
1850 /* Main loop in daemon mode.  Note that LISTEN_FD will be owned by
1851  * this function. */
1852 static void
1853 handle_connections (assuan_fd_t listen_fd)
1854 {
1855   npth_attr_t tattr;
1856 #ifndef HAVE_W32_SYSTEM
1857   int signo;
1858 #endif
1859   struct sockaddr_un paddr;
1860   socklen_t plen = sizeof( paddr );
1861   gnupg_fd_t fd;
1862   int nfd, ret;
1863   fd_set fdset, read_fdset;
1864   int saved_errno;
1865   int my_inotify_fd = -1;
1866
1867   npth_attr_init (&tattr);
1868   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1869
1870 #ifndef HAVE_W32_SYSTEM /* FIXME */
1871   npth_sigev_init ();
1872   npth_sigev_add (SIGHUP);
1873   npth_sigev_add (SIGUSR1);
1874   npth_sigev_add (SIGUSR2);
1875   npth_sigev_add (SIGINT);
1876   npth_sigev_add (SIGTERM);
1877   npth_sigev_fini ();
1878 #endif
1879
1880 #ifdef HAVE_INOTIFY_INIT
1881   if (disable_check_own_socket)
1882     my_inotify_fd = -1;
1883   else if ((my_inotify_fd = inotify_init ()) == -1)
1884     log_info ("error enabling fast daemon termination: %s\n",
1885               strerror (errno));
1886   else
1887     {
1888       /* We need to watch the directory for the file because there
1889        * won't be an IN_DELETE_SELF for a socket file.  */
1890       char *slash = strrchr (socket_name, '/');
1891       log_assert (slash && slash[1]);
1892       *slash = 0;
1893       if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1)
1894         {
1895           close (my_inotify_fd);
1896           my_inotify_fd = -1;
1897         }
1898       *slash = '/';
1899     }
1900 #endif /*HAVE_INOTIFY_INIT*/
1901
1902
1903   /* Setup the fdset.  */
1904   FD_ZERO (&fdset);
1905   FD_SET (FD2INT (listen_fd), &fdset);
1906   nfd = FD2INT (listen_fd);
1907   if (my_inotify_fd != -1)
1908     {
1909       FD_SET (my_inotify_fd, &fdset);
1910       if (my_inotify_fd > nfd)
1911         nfd = my_inotify_fd;
1912     }
1913
1914   /* Main loop.  */
1915   for (;;)
1916     {
1917       /* Shutdown test.  */
1918       if (shutdown_pending)
1919         {
1920           if (!active_connections)
1921             break; /* ready */
1922
1923           /* Do not accept new connections but keep on running the
1924            * select loop to wait for signals (e.g. SIGCHLD).
1925            *
1926            * Note that we do not close the listening socket because a
1927            * client trying to connect to that socket would instead
1928            * restart a new dirmngr instance - which is unlikely the
1929            * intention of a shutdown. */
1930           /* assuan_sock_close (listen_fd); */
1931           /* listen_fd = -1; */
1932           FD_ZERO (&fdset);
1933           nfd = -1;
1934           if (my_inotify_fd != -1)
1935             {
1936               FD_SET (my_inotify_fd, &fdset);
1937               nfd = my_inotify_fd;
1938             }
1939         }
1940
1941       /* Take a copy of the fdset.  */
1942       read_fdset = fdset;
1943
1944 #ifndef HAVE_W32_SYSTEM
1945       ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, NULL, npth_sigev_sigmask());
1946       saved_errno = errno;
1947
1948       while (npth_sigev_get_pending(&signo))
1949         handle_signal (signo);
1950 #else
1951       ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, NULL, NULL, NULL);
1952       saved_errno = errno;
1953 #endif
1954
1955       if (ret == -1 && saved_errno != EINTR)
1956         {
1957           log_error (_("npth_pselect failed: %s - waiting 1s\n"),
1958                      strerror (saved_errno));
1959           npth_sleep (1);
1960           continue;
1961         }
1962
1963       if (ret <= 0)
1964         {
1965           /* Interrupt.  Will be handled at the top of the next loop.  */
1966           continue;
1967         }
1968
1969       if (shutdown_pending)
1970         {
1971           /* Do not anymore accept connections.  */
1972           continue;
1973         }
1974
1975 #ifdef HAVE_INOTIFY_INIT
1976       if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset)
1977           && my_inotify_is_name (my_inotify_fd, socket_name))
1978         {
1979           shutdown_pending = 1;
1980           log_info ("socket file has been removed - shutting down\n");
1981         }
1982 #endif /*HAVE_INOTIFY_INIT*/
1983
1984       if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
1985         {
1986           plen = sizeof paddr;
1987           fd = INT2FD (npth_accept (FD2INT(listen_fd),
1988                                     (struct sockaddr *)&paddr, &plen));
1989           if (fd == GNUPG_INVALID_FD)
1990             {
1991               log_error ("accept failed: %s\n", strerror (errno));
1992             }
1993           else
1994             {
1995               char threadname[50];
1996               union int_and_ptr_u argval;
1997               npth_t thread;
1998
1999               memset (&argval, 0, sizeof argval);
2000               argval.afd = fd;
2001               snprintf (threadname, sizeof threadname,
2002                         "conn fd=%d", FD2INT(fd));
2003
2004               ret = npth_create (&thread, &tattr,
2005                                  start_connection_thread, argval.aptr);
2006               if (ret)
2007                 {
2008                   log_error ("error spawning connection handler: %s\n",
2009                              strerror (ret) );
2010                   assuan_sock_close (fd);
2011                 }
2012               npth_setname_np (thread, threadname);
2013             }
2014           fd = GNUPG_INVALID_FD;
2015         }
2016     }
2017
2018 #ifdef HAVE_INOTIFY_INIT
2019   if (my_inotify_fd != -1)
2020     close (my_inotify_fd);
2021 #endif /*HAVE_INOTIFY_INIT*/
2022   npth_attr_destroy (&tattr);
2023   if (listen_fd != -1)
2024     assuan_sock_close (fd);
2025   cleanup ();
2026   log_info ("%s %s stopped\n", strusage(11), strusage(13));
2027 }
2028
2029 const char*
2030 dirmngr_get_current_socket_name (void)
2031 {
2032   if (socket_name)
2033     return socket_name;
2034   else
2035     return dirmngr_socket_name ();
2036 }