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