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