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