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
6 * This file is part of GnuPG.
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.
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.
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/>.
33 #ifndef HAVE_W32_SYSTEM
34 #include <sys/socket.h>
42 #ifdef HAVE_INOTIFY_INIT
43 # include <sys/inotify.h>
44 #endif /*HAVE_INOTIFY_INIT*/
47 #include "dirmngr-err.h"
52 # include <gnutls/gnutls.h>
53 #endif /*HTTP_USE_GNUTLS*/
56 #define GNUPG_COMMON_NEED_AFLOCAL
61 #include "certcache.h"
66 # include "ldapserver.h"
70 # include "ldap-wrapper.h"
72 #include "../common/init.h"
73 #include "gc-opt-flags.h"
74 #include "dns-stuff.h"
77 # define ENAMETOOLONG EINVAL
81 enum cmd_and_opt_values {
138 oIgnoreCertExtension,
142 oDisableCheckOwnSocket,
151 static ARGPARSE_OPTS opts[] = {
153 ARGPARSE_group (300, N_("@Commands:\n ")),
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")),
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", "@"),
168 ARGPARSE_group (301, N_("@\nOptions:\n ")),
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")),
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")),
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")),
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", "@"),
217 ARGPARSE_s_i (oMaxReplies, "max-replies",
218 N_("|N|do not return more than N items in one query")),
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")),
225 ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")),
227 ARGPARSE_s_s (oSocketName, "socket-name", "@"), /* Only for debugging. */
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", "@"),
246 ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing "
247 "of all commands and options)\n")),
252 /* The list of supported debug flags. */
253 static struct debug_flags_s debug_flags [] =
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 "?". */
268 #define DEFAULT_MAX_REPLIES 10
269 #define DEFAULT_LDAP_TIMEOUT 100 /* arbitrary large timeout */
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;
277 /* We need to keep track of the server's nonces (these are dummies for
279 static assuan_sock_nonce_t socket_nonce;
281 /* Only if this flag has been set will we remove the socket file. */
282 static int cleanup_socket;
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;
288 /* Helper to implement --debug-level. */
289 static const char *debug_level;
291 /* Helper to set the NTBTLS or GNUTLS log level. */
292 static int opt_gnutls_debug = -1;
294 /* Flag indicating that a shutdown has been requested. */
295 static volatile int shutdown_pending;
297 /* Flags to indicate that we shall not watch our own socket. */
298 static int disable_check_own_socket;
300 /* Counter for the active connections. */
301 static int active_connections;
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;
307 /* The timer tick used for housekeeping stuff. */
308 #define TIMERTICK_INTERVAL (60)
310 /* How oft to run the housekeeping. */
311 #define HOUSEKEEPING_INTERVAL (600)
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.). */
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;
334 static void cleanup (void);
336 static ldap_server_t parse_ldapserver_file (const char* filename);
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);
342 /* NPth wrapper function definitions. */
343 ASSUAN_SYSTEM_NPTH_IMPL;
346 my_strusage( int level )
351 case 11: p = "@DIRMNGR@ (@GNUPG@)";
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;
361 case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)");
363 case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n"
364 "Keyserver, CRL, and OCSP access for @GNUPG@\n");
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. */
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)
384 if (oid && strcmp (oid, "1.3.14.3.2.26"))
385 return gpg_error (GPG_ERR_NOT_SUPPORTED);
387 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
388 gcry_md_hash_buffer (2, result, buffer, length);
394 /* GNUTLS log function callback. */
395 #ifdef HTTP_USE_GNUTLS
397 my_gnutls_log (int level, const char *text)
402 while (n && text[n-1] == '\n')
405 log_debug ("gnutls:L%d: %.*s\n", level, n, text);
407 #endif /*HTTP_USE_GNUTLS*/
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
416 int numok = (debug_level && digitp (debug_level));
417 int numlvl = numok? atoi (debug_level) : 0;
421 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
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)
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. */
438 opt.debug &= ~(DBG_HASHING_VALUE);
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. */
450 if (opt.debug && !opt.verbose)
453 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
455 if (opt.debug && opt.quiet)
458 if (opt.debug & DBG_CRYPTO_VALUE )
459 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
462 if (opt_gnutls_debug >= 0)
464 ntbtls_set_debug (opt_gnutls_debug, NULL, NULL);
466 #elif HTTP_USE_GNUTLS
467 if (opt_gnutls_debug >= 0)
469 gnutls_global_set_log_function (my_gnutls_log);
470 gnutls_global_set_log_level (opt_gnutls_debug);
472 #endif /*HTTP_USE_GNUTLS*/
475 parse_debug_flag (NULL, &opt.debug, debug_flags);
484 /* Enable Tor mode and when called again force a new curcuit
485 * (e.g. on SIGHUP). */
486 enable_dns_tormode (1);
487 if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
489 log_error ("error enabling Tor mode: %s\n", strerror (errno));
490 log_info ("(is your Libassuan recent enough?)\n");
497 wrong_args (const char *text)
499 es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME);
500 es_fputs (text, es_stderr);
501 es_putc ('\n', es_stderr);
506 /* Helper to stop the reaper thread for the ldap wrapper. */
508 shutdown_reaper (void)
511 ldap_wrapper_wait_connections ();
516 /* Handle options which are allowed to be reset after program start.
517 Return true if the current option in PARGS could be handled and
518 false if not. As a special feature, passing a value of NULL for
519 PARGS, resets the options to the default. REREAD should be set
520 true if it is not the initial option parsing. */
522 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
529 opt.ldap_wrapper_program = NULL;
530 opt.disable_http = 0;
531 opt.disable_ldap = 0;
532 opt.honor_http_proxy = 0;
533 opt.http_proxy = NULL;
534 opt.ldap_proxy = NULL;
535 opt.only_ldap_proxy = 0;
536 opt.ignore_http_dp = 0;
537 opt.ignore_ldap_dp = 0;
538 opt.ignore_ocsp_service_url = 0;
540 opt.allow_version_check = 0;
541 opt.ocsp_responder = NULL;
542 opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */
543 opt.ocsp_max_period = 90 * 86400; /* 90 days. */
544 opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */
545 opt.max_replies = DEFAULT_MAX_REPLIES;
546 while (opt.ocsp_signer)
548 fingerprint_list_t tmp = opt.ocsp_signer->next;
549 xfree (opt.ocsp_signer);
550 opt.ocsp_signer = tmp;
552 FREE_STRLIST (opt.ignored_cert_extensions);
553 http_register_tls_ca (NULL);
554 FREE_STRLIST (opt.keyserver);
555 /* Note: We do not allow resetting of opt.use_tor at runtime. */
556 disable_check_own_socket = 0;
557 enable_standard_resolver (0);
562 switch (pargs->r_opt)
564 case oQuiet: opt.quiet = 1; break;
565 case oVerbose: opt.verbose++; break;
567 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
569 case oDebugAll: opt.debug = ~0; break;
570 case oDebugLevel: debug_level = pargs->r.ret_str; break;
571 case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break;
575 return 0; /* Not handled. */
576 if (!current_logfile || !pargs->r.ret_str
577 || strcmp (current_logfile, pargs->r.ret_str))
579 log_set_file (pargs->r.ret_str);
580 xfree (current_logfile);
581 current_logfile = xtrystrdup (pargs->r.ret_str);
585 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
587 case oLDAPWrapperProgram:
588 opt.ldap_wrapper_program = pargs->r.ret_str;
590 case oHTTPWrapperProgram:
591 opt.http_wrapper_program = pargs->r.ret_str;
594 case oDisableHTTP: opt.disable_http = 1; break;
595 case oDisableLDAP: opt.disable_ldap = 1; break;
596 case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
597 case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
598 case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
599 case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
600 case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
601 case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
602 case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
604 case oAllowOCSP: opt.allow_ocsp = 1; break;
605 case oAllowVersionCheck: opt.allow_version_check = 1; break;
606 case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
608 opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str);
610 case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
611 case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
612 case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
614 case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
620 /* Do tilde expansion and make path absolute. */
621 tmpname = make_absfilename (pargs->r.ret_str, NULL);
622 http_register_tls_ca (tmpname);
627 case oIgnoreCertExtension:
628 add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
631 case oUseTor: opt.use_tor = 1; break;
633 case oStandardResolver: enable_standard_resolver (1); break;
634 case oRecursiveResolver: enable_recursive_resolver (1); break;
637 if (*pargs->r.ret_str)
638 add_to_strlist (&opt.keyserver, pargs->r.ret_str);
642 set_dns_nameserver (pargs->r.ret_str);
645 case oResolverTimeout:
646 set_dns_timeout (pargs->r.ret_int);
650 return 0; /* Not handled. */
653 set_dns_verbose (opt.verbose, !!DBG_DNS);
654 http_set_verbose (opt.verbose, !!DBG_NETWORK);
656 return 1; /* Handled. */
660 #ifndef HAVE_W32_SYSTEM
662 pid_suffix_callback (unsigned long *r_suffix)
664 union int_and_ptr_u value;
666 memset (&value, 0, sizeof value);
667 value.aptr = npth_getspecific (my_tlskey_current_fd);
668 *r_suffix = value.aint;
669 return (*r_suffix != -1); /* Use decimal representation. */
671 #endif /*!HAVE_W32_SYSTEM*/
678 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
680 /* Now with NPth running we can set the logging callback. Our
681 windows implementation does not yet feature the NPth TLS
683 #ifndef HAVE_W32_SYSTEM
684 if (npth_key_create (&my_tlskey_current_fd, NULL) == 0)
685 if (npth_setspecific (my_tlskey_current_fd, NULL) == 0)
686 log_set_pid_suffix_cb (pid_suffix_callback);
687 #endif /*!HAVE_W32_SYSTEM*/
692 main (int argc, char **argv)
694 enum cmd_and_opt_values cmd = 0;
698 FILE *configfp = NULL;
699 char *configname = NULL;
701 unsigned configlineno;
703 int default_config =1;
708 char *logfile = NULL;
710 char *ldapfile = NULL;
714 struct assuan_malloc_hooks malloc_hooks;
716 early_system_init ();
717 set_strusage (my_strusage);
718 log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
720 /* Make sure that our subsystems are ready. */
722 init_common_subsystems (&argc, &argv);
724 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
726 /* Check that the libraries are suitable. Do it here because
727 the option parsing may need services of the libraries. */
728 if (!ksba_check_version (NEED_KSBA_VERSION) )
729 log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba",
730 NEED_KSBA_VERSION, ksba_check_version (NULL) );
732 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
733 ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
735 /* Init TLS library. */
737 if (!ntbtls_check_version (NEED_NTBTLS_VERSION) )
738 log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls",
739 NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) );
740 #elif HTTP_USE_GNUTLS
741 rc = gnutls_global_init ();
743 log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));
744 #endif /*HTTP_USE_GNUTLS*/
747 malloc_hooks.malloc = gcry_malloc;
748 malloc_hooks.realloc = gcry_realloc;
749 malloc_hooks.free = gcry_free;
750 assuan_set_malloc_hooks (&malloc_hooks);
751 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
752 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
753 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
755 setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor);
757 setup_libgcrypt_logging ();
759 /* Setup defaults. */
760 shell = getenv ("SHELL");
761 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
764 /* Reset rereadable options to default values. */
765 parse_rereadable_options (NULL, 0);
768 opt.add_new_ldapservers = 0;
769 opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
771 /* Other defaults. */
773 /* Check whether we have a config file given on the commandline */
778 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
779 while (arg_parse( &pargs, opts))
781 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
783 else if (pargs.r_opt == oOptions)
784 { /* Yes there is one, so we do not try the default one, but
785 read the option file when it is encountered at the
789 else if (pargs.r_opt == oNoOptions)
790 default_config = 0; /* --no-options */
791 else if (pargs.r_opt == oHomedir)
793 gnupg_set_homedir (pargs.r.ret_str);
797 socket_name = dirmngr_socket_name ();
799 configname = make_filename (gnupg_homedir (), DIRMNGR_NAME".conf", NULL );
805 pargs.flags= 1; /* do not remove the args */
810 configfp = fopen (configname, "r");
816 log_info (_("Note: no default option file '%s'\n"),
821 log_error (_("option file '%s': %s\n"),
822 configname, strerror(errno) );
828 if (parse_debug && configname )
829 log_info (_("reading options from '%s'\n"), configname );
833 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
835 if (parse_rereadable_options (&pargs, 0))
836 continue; /* Already handled */
852 case oQuiet: opt.quiet = 1; break;
853 case oVerbose: opt.verbose++; break;
854 case oBatch: opt.batch=1; break;
856 case oDebugWait: debug_wait = pargs.r.ret_int; break;
859 /* Config files may not be nested (silently ignore them) */
863 configname = xstrdup(pargs.r.ret_str);
867 case oNoGreeting: nogreeting = 1; break;
868 case oNoVerbose: opt.verbose = 0; break;
869 case oNoOptions: break; /* no-options */
870 case oHomedir: /* Ignore this option here. */; break;
871 case oNoDetach: nodetach = 1; break;
872 case oLogFile: logfile = pargs.r.ret_str; break;
873 case oCsh: csh_style = 1; break;
874 case oSh: csh_style = 0; break;
877 ldapfile = pargs.r.ret_str;
880 case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
882 opt.ldaptimeout = pargs.r.ret_int;
885 case oFakedSystemTime:
886 gnupg_set_time ((time_t)pargs.r.ret_ulong, 0);
889 case oForce: opt.force = 1; break;
891 case oSocketName: socket_name = pargs.r.ret_str; break;
893 default : pargs.err = configfp? 1:2; break;
900 /* Keep a copy of the name so that it can be read on SIGHUP. */
901 opt.config_filename = configname;
907 if (log_get_errorcount(0))
912 if (!opt.homedir_cache)
913 opt.homedir_cache = xstrdup (gnupg_homedir ());
917 es_fprintf (es_stderr, "%s %s; %s\n",
918 strusage(11), strusage(13), strusage(14) );
919 es_fprintf (es_stderr, "%s\n", strusage(15) );
922 #ifdef IS_DEVELOPMENT_VERSION
923 log_info ("NOTE: this is a development version!\n");
926 /* Print a warning if an argument looks like an option. */
927 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
931 for (i=0; i < argc; i++)
932 if (argv[i][0] == '-' && argv[i][1] == '-')
933 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
936 if (!access ("/etc/"DIRMNGR_NAME, F_OK)
937 && !strncmp (gnupg_homedir (), "/etc/", 5))
939 ("NOTE: DirMngr is now a proper part of %s. The configuration and"
940 " other directory names changed. Please check that no other version"
941 " of dirmngr is still installed. To disable this warning, remove the"
942 " directory '/etc/dirmngr'.\n", GNUPG_NAME);
944 if (gnupg_faked_time_p ())
946 gnupg_isotime_t tbuf;
948 log_info (_("WARNING: running with faked system time: "));
949 gnupg_get_isotime (tbuf);
957 /* Get LDAP server list from file. */
961 ldapfile = make_filename (gnupg_homedir (),
962 "dirmngr_ldapservers.conf",
964 opt.ldapservers = parse_ldapserver_file (ldapfile);
968 opt.ldapservers = parse_ldapserver_file (ldapfile);
971 #ifndef HAVE_W32_SYSTEM
972 /* We need to ignore the PIPE signal because the we might log to a
973 socket and that code handles EPIPE properly. The ldap wrapper
974 also requires us to ignore this silly signal. Assuan would set
975 this signal to ignore anyway.*/
976 signal (SIGPIPE, SIG_IGN);
979 /* Ready. Now to our duties. */
986 /* Note that this server mode is mainly useful for debugging. */
988 wrong_args ("--server");
992 log_set_file (logfile);
993 log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
998 log_debug ("waiting for debugger - my pid is %u .....\n",
999 (unsigned int)getpid());
1000 gnupg_sleep (debug_wait);
1001 log_debug ("... okay\n");
1008 http_register_netactivity_cb (netactivity_action);
1009 start_command_handler (ASSUAN_INVALID_FD);
1012 #ifndef HAVE_W32_SYSTEM
1013 else if (cmd == aSupervised)
1015 /* In supervised mode, we expect file descriptor 3 to be an
1016 already opened, listening socket.
1018 We will also not detach from the controlling process or close
1019 stderr; the supervisor should handle all of that. */
1020 struct stat statbuf;
1021 if (fstat (3, &statbuf) == -1 && errno == EBADF)
1023 log_error ("file descriptor 3 must be validin --supervised mode\n");
1026 socket_name = gnupg_get_socket_name (3);
1028 /* Now start with logging to a file if this is desired. */
1031 log_set_file (logfile);
1032 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1033 |GPGRT_LOG_WITH_TIME
1034 |GPGRT_LOG_WITH_PID));
1035 current_logfile = xstrdup (logfile);
1038 log_set_prefix (NULL, 0);
1043 http_register_netactivity_cb (netactivity_action);
1044 handle_connections (3);
1047 #endif /*HAVE_W32_SYSTEM*/
1048 else if (cmd == aDaemon)
1053 struct sockaddr_un serv_addr;
1056 wrong_args ("--daemon");
1058 /* Now start with logging to a file if this is desired. */
1061 log_set_file (logfile);
1062 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1063 |GPGRT_LOG_WITH_TIME
1064 |GPGRT_LOG_WITH_PID));
1065 current_logfile = xstrdup (logfile);
1068 #ifndef HAVE_W32_SYSTEM
1069 if (strchr (socket_name, ':'))
1071 log_error (_("colons are not allowed in the socket name\n"));
1075 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1076 if (fd == ASSUAN_INVALID_FD)
1078 log_error (_("can't create socket: %s\n"), strerror (errno));
1086 if (assuan_sock_set_sockaddr_un (socket_name,
1087 (struct sockaddr*)&serv_addr,
1090 if (errno == ENAMETOOLONG)
1091 log_error (_("socket name '%s' is too long\n"), socket_name);
1093 log_error ("error preparing socket '%s': %s\n",
1095 gpg_strerror (gpg_error_from_syserror ()));
1100 redir_socket_name = xstrdup (serv_addr.sun_path);
1102 log_info ("redirecting socket '%s' to '%s'\n",
1103 socket_name, redir_socket_name);
1107 len = SUN_LEN (&serv_addr);
1109 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1111 && (errno == EADDRINUSE
1112 #ifdef HAVE_W32_SYSTEM
1117 /* Fixme: We should test whether a dirmngr is already running. */
1118 gnupg_remove (redir_socket_name? redir_socket_name : socket_name);
1119 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1122 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
1123 log_error (_("error getting nonce for the socket\n"));
1126 log_error (_("error binding socket to '%s': %s\n"),
1128 gpg_strerror (gpg_error_from_errno (errno)));
1129 assuan_sock_close (fd);
1134 if (gnupg_chmod (serv_addr.sun_path, "-rwx"))
1135 log_error (_("can't set permissions of '%s': %s\n"),
1136 serv_addr.sun_path, strerror (errno));
1138 if (listen (FD2INT (fd), 5) == -1)
1140 log_error (_("listen() failed: %s\n"), strerror (errno));
1141 assuan_sock_close (fd);
1146 log_info (_("listening on socket '%s'\n"), serv_addr.sun_path);
1150 /* Note: We keep the dirmngr_info output only for the sake of
1151 existing scripts which might use this to detect a successful
1152 start of the dirmngr. */
1153 #ifdef HAVE_W32_SYSTEM
1158 es_printf ("set %s=%s;%lu;1\n",
1159 DIRMNGR_INFO_NAME, socket_name, (ulong) pid);
1162 if (pid == (pid_t)-1)
1164 log_fatal (_("error forking process: %s\n"), strerror (errno));
1169 { /* We are the parent */
1172 /* Don't let cleanup() remove the socket - the child is
1173 responsible for doing that. */
1178 /* Create the info string: <name>:<pid>:<protocol_version> */
1179 if (asprintf (&infostr, "%s=%s:%lu:1",
1180 DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0)
1182 log_error (_("out of core\n"));
1183 kill (pid, SIGTERM);
1186 /* Print the environment string, so that the caller can use
1187 shell's eval to set it. But see above. */
1190 *strchr (infostr, '=') = ' ';
1191 es_printf ( "setenv %s;\n", infostr);
1195 es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME);
1207 /* Detach from tty and put process into a new session */
1211 unsigned int oldflags;
1213 /* Close stdin, stdout and stderr unless it is the log stream */
1214 for (i=0; i <= 2; i++)
1216 if (!log_test_fd (i) && i != fd )
1219 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1221 log_error ("failed to open '%s': %s\n",
1222 "/dev/null", strerror (errno));
1231 log_error ("setsid() failed: %s\n", strerror(errno) );
1235 log_get_prefix (&oldflags);
1236 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1237 opt.running_detached = 1;
1241 log_error ("chdir to / failed: %s\n", strerror (errno));
1250 http_register_netactivity_cb (netactivity_action);
1251 handle_connections (fd);
1254 else if (cmd == aListCRLs)
1256 /* Just list the CRL cache and exit. */
1258 wrong_args ("--list-crls");
1260 crl_cache_list (es_stdout);
1262 else if (cmd == aLoadCRL)
1264 struct server_control_s ctrlbuf;
1266 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1267 dirmngr_init_default_ctrl (&ctrlbuf);
1273 rc = crl_cache_load (&ctrlbuf, NULL);
1276 for (; !rc && argc; argc--, argv++)
1277 rc = crl_cache_load (&ctrlbuf, *argv);
1279 dirmngr_deinit_default_ctrl (&ctrlbuf);
1281 else if (cmd == aFetchCRL)
1283 ksba_reader_t reader;
1284 struct server_control_s ctrlbuf;
1287 wrong_args ("--fetch-crl URL");
1289 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1290 dirmngr_init_default_ctrl (&ctrlbuf);
1295 rc = crl_fetch (&ctrlbuf, argv[0], &reader);
1297 log_error (_("fetching CRL from '%s' failed: %s\n"),
1298 argv[0], gpg_strerror (rc));
1301 rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
1303 log_error (_("processing CRL from '%s' failed: %s\n"),
1304 argv[0], gpg_strerror (rc));
1305 crl_close_reader (reader);
1307 dirmngr_deinit_default_ctrl (&ctrlbuf);
1309 else if (cmd == aFlush)
1311 /* Delete cache and exit. */
1313 wrong_args ("--flush");
1314 rc = crl_cache_flush();
1316 else if (cmd == aGPGConfTest)
1318 else if (cmd == aGPGConfList)
1320 unsigned long flags = 0;
1324 /* First the configuration file. This is not an option, but it
1325 is vital information for GPG Conf. */
1326 if (!opt.config_filename)
1327 opt.config_filename = make_filename (gnupg_homedir (),
1328 "dirmngr.conf", NULL );
1330 filename = percent_escape (opt.config_filename, NULL);
1331 es_printf ("gpgconf-dirmngr.conf:%lu:\"%s\n",
1332 GC_OPT_FLAG_DEFAULT, filename);
1335 es_printf ("verbose:%lu:\n", flags | GC_OPT_FLAG_NONE);
1336 es_printf ("quiet:%lu:\n", flags | GC_OPT_FLAG_NONE);
1337 es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
1338 es_printf ("log-file:%lu:\n", flags | GC_OPT_FLAG_NONE);
1339 es_printf ("force:%lu:\n", flags | GC_OPT_FLAG_NONE);
1341 /* --csh and --sh are mutually exclusive, something we can not
1342 express in GPG Conf. --options is only usable from the
1343 command line, really. --debug-all interacts with --debug,
1344 and having both of them is thus problematic. --no-detach is
1345 also only usable on the command line. --batch is unused. */
1347 filename = make_filename (gnupg_homedir (),
1348 "dirmngr_ldapservers.conf",
1350 filename_esc = percent_escape (filename, NULL);
1351 es_printf ("ldapserverlist-file:%lu:\"%s\n", flags | GC_OPT_FLAG_DEFAULT,
1353 xfree (filename_esc);
1356 es_printf ("ldaptimeout:%lu:%u\n",
1357 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
1358 es_printf ("max-replies:%lu:%u\n",
1359 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
1360 es_printf ("allow-ocsp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1361 es_printf ("allow-version-check:%lu:\n", flags | GC_OPT_FLAG_NONE);
1362 es_printf ("ocsp-responder:%lu:\n", flags | GC_OPT_FLAG_NONE);
1363 es_printf ("ocsp-signer:%lu:\n", flags | GC_OPT_FLAG_NONE);
1365 es_printf ("faked-system-time:%lu:\n", flags | GC_OPT_FLAG_NONE);
1366 es_printf ("no-greeting:%lu:\n", flags | GC_OPT_FLAG_NONE);
1368 es_printf ("disable-http:%lu:\n", flags | GC_OPT_FLAG_NONE);
1369 es_printf ("disable-ldap:%lu:\n", flags | GC_OPT_FLAG_NONE);
1370 es_printf ("honor-http-proxy:%lu\n", flags | GC_OPT_FLAG_NONE);
1371 es_printf ("http-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1372 es_printf ("ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1373 es_printf ("only-ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1374 es_printf ("ignore-ldap-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1375 es_printf ("ignore-http-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1376 es_printf ("ignore-ocsp-service-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1377 /* Note: The next one is to fix a typo in gpgconf - should be
1378 removed eventually. */
1379 es_printf ("ignore-ocsp-servic-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1381 es_printf ("use-tor:%lu:\n", flags | GC_OPT_FLAG_NONE);
1382 es_printf ("keyserver:%lu:\n", flags | GC_OPT_FLAG_NONE);
1383 es_printf ("nameserver:%lu:\n", flags | GC_OPT_FLAG_NONE);
1384 es_printf ("resolver-timeout:%lu:%u\n",
1385 flags | GC_OPT_FLAG_DEFAULT, 0);
1395 crl_cache_deinit ();
1396 cert_cache_deinit (1);
1397 reload_dns_stuff (1);
1400 ldapserver_list_free (opt.ldapservers);
1402 opt.ldapservers = NULL;
1407 if (redir_socket_name)
1408 gnupg_remove (redir_socket_name);
1409 else if (socket_name && *socket_name)
1410 gnupg_remove (socket_name);
1416 dirmngr_exit (int rc)
1424 dirmngr_init_default_ctrl (ctrl_t ctrl)
1427 ctrl->http_proxy = xstrdup (opt.http_proxy);
1432 dirmngr_deinit_default_ctrl (ctrl_t ctrl)
1436 xfree (ctrl->http_proxy);
1437 ctrl->http_proxy = NULL;
1441 /* Create a list of LDAP servers from the file FILENAME. Returns the
1442 list or NULL in case of errors.
1444 The format fo such a file is line oriented where empty lines and
1445 lines starting with a hash mark are ignored. All other lines are
1446 assumed to be colon seprated with these fields:
1449 2. field: Portnumber
1456 static ldap_server_t
1457 parse_ldapserver_file (const char* filename)
1461 ldap_server_t server, serverstart, *serverend;
1463 unsigned int lineno = 0;
1466 fp = es_fopen (filename, "r");
1469 log_error (_("error opening '%s': %s\n"), filename, strerror (errno));
1474 serverend = &serverstart;
1475 while (es_fgets (buffer, sizeof buffer, fp))
1478 if (!*buffer || buffer[strlen(buffer)-1] != '\n')
1480 if (*buffer && es_feof (fp))
1481 ; /* Last line not terminated - continue. */
1484 log_error (_("%s:%u: line too long - skipped\n"),
1486 while ( (c=es_fgetc (fp)) != EOF && c != '\n')
1487 ; /* Skip until end of line. */
1491 /* Skip empty and comment lines.*/
1492 for (p=buffer; spacep (p); p++)
1494 if (!*p || *p == '\n' || *p == '#')
1497 /* Parse the colon separated fields. */
1498 server = ldapserver_parse_one (buffer, filename, lineno);
1501 *serverend = server;
1502 serverend = &server->next;
1507 log_error (_("error reading '%s': %s\n"), filename, strerror (errno));
1514 static fingerprint_list_t
1515 parse_ocsp_signer (const char *string)
1522 fingerprint_list_t list, *list_tail, item;
1523 unsigned int lnr = 0;
1528 /* Check whether this is not a filename and treat it as a direct
1529 fingerprint specification. */
1530 if (!strpbrk (string, "/.~\\"))
1532 item = xcalloc (1, sizeof *item);
1533 for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
1534 if ( string[i] != ':' )
1535 item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
1536 item->hexfpr[j] = 0;
1537 if (j != 40 || !(spacep (string+i) || !string[i]))
1539 log_error (_("%s:%u: invalid fingerprint detected\n"),
1540 "--ocsp-signer", 0);
1547 /* Well, it is a filename. */
1548 if (*string == '/' || (*string == '~' && string[1] == '/'))
1549 fname = make_filename (string, NULL);
1552 if (string[0] == '.' && string[1] == '/' )
1554 fname = make_filename (gnupg_homedir (), string, NULL);
1557 fp = es_fopen (fname, "r");
1560 err = gpg_error_from_syserror ();
1561 log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
1570 if (!es_fgets (line, DIM(line)-1, fp) )
1574 err = gpg_error_from_syserror ();
1575 log_error (_("%s:%u: read error: %s\n"),
1576 fname, lnr, gpg_strerror (err));
1584 fingerprint_list_t tmp = list->next;
1590 return list; /* Ready. */
1594 if (!*line || line[strlen(line)-1] != '\n')
1596 /* Eat until end of line. */
1597 while ( (c=es_getc (fp)) != EOF && c != '\n')
1599 err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
1600 /* */: GPG_ERR_INCOMPLETE_LINE);
1601 log_error (_("%s:%u: read error: %s\n"),
1602 fname, lnr, gpg_strerror (err));
1607 /* Allow for empty lines and spaces */
1608 for (p=line; spacep (p); p++)
1610 if (!*p || *p == '\n' || *p == '#')
1613 item = xcalloc (1, sizeof *item);
1615 list_tail = &item->next;
1617 for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
1619 item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
1620 item->hexfpr[j] = 0;
1621 if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
1623 log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
1627 while (spacep (p+i))
1629 if (p[i] && p[i] != '\n')
1630 log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
1639 Stuff used in daemon mode.
1644 /* Reread parts of the configuration. Note, that this function is
1645 obviously not thread-safe and should only be called from the NPTH
1648 Fixme: Due to the way the argument parsing works, we create a
1649 memory leak here for all string type arguments. There is currently
1650 no clean way to tell whether the memory for the argument has been
1651 allocated or points into the process' original arguments. Unless
1652 we have a mechanism to tell this, we need to live on with this. */
1654 reread_configuration (void)
1656 ARGPARSE_ARGS pargs;
1658 unsigned int configlineno = 0;
1661 if (!opt.config_filename)
1662 return; /* No config file. */
1664 fp = fopen (opt.config_filename, "r");
1667 log_error (_("option file '%s': %s\n"),
1668 opt.config_filename, strerror(errno) );
1672 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1674 memset (&pargs, 0, sizeof pargs);
1676 pargs.argc = &dummy;
1677 pargs.flags = 1; /* do not remove the args */
1678 while (optfile_parse (fp, opt.config_filename, &configlineno, &pargs, opts) )
1680 if (pargs.r_opt < -1)
1681 pargs.err = 1; /* Print a warning. */
1682 else /* Try to parse this option - ignore unchangeable ones. */
1683 parse_rereadable_options (&pargs, 1);
1692 /* A global function which allows us to trigger the reload stuff from
1695 dirmngr_sighup_action (void)
1697 log_info (_("SIGHUP received - "
1698 "re-reading configuration and flushing caches\n"));
1699 reread_configuration ();
1700 cert_cache_deinit (0);
1701 crl_cache_deinit ();
1704 reload_dns_stuff (0);
1709 /* This function is called if some network activity was done. At this
1710 * point we know the we have a network and we can decide whether to
1711 * run scheduled background tasks soon. The function should return
1712 * quickly and only trigger actions for another thread. */
1714 netactivity_action (void)
1716 network_activity_seen = 1;
1720 /* The signal handler. */
1721 #ifndef HAVE_W32_SYSTEM
1723 handle_signal (int signo)
1728 dirmngr_sighup_action ();
1732 cert_cache_print_stats ();
1736 log_info (_("SIGUSR2 received - no action defined\n"));
1740 if (!shutdown_pending)
1741 log_info (_("SIGTERM received - shutting down ...\n"));
1743 log_info (_("SIGTERM received - still %d active connections\n"),
1744 active_connections);
1746 if (shutdown_pending > 2)
1748 log_info (_("shutdown forced\n"));
1749 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1756 log_info (_("SIGINT received - immediate shutdown\n"));
1757 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1763 log_info (_("signal %d received - no action defined\n"), signo);
1766 #endif /*!HAVE_W32_SYSTEM*/
1769 /* Thread to do the housekeeping. */
1771 housekeeping_thread (void *arg)
1773 static int sentinel;
1779 log_info ("housekeeping is already going on\n");
1783 if (opt.verbose > 1)
1784 log_info ("starting housekeeping\n");
1786 if (opt.verbose > 1)
1787 log_info ("ready with housekeeping\n");
1794 #if GPGRT_GCC_HAVE_PUSH_PRAGMA
1795 # pragma GCC push_options
1796 # pragma GCC optimize ("no-strict-overflow")
1799 time_for_housekeeping_p (time_t curtime)
1801 static time_t last_housekeeping;
1803 if (!last_housekeeping)
1804 last_housekeeping = curtime;
1806 if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime
1807 || last_housekeeping > curtime /*(be prepared for y2038)*/)
1809 last_housekeeping = curtime;
1814 #if GPGRT_GCC_HAVE_PUSH_PRAGMA
1815 # pragma GCC pop_options
1819 /* This is the worker for the ticker. It is called every few seconds
1820 and may only do fast operations. */
1824 if (time_for_housekeeping_p (gnupg_get_time ()))
1830 err = npth_attr_init (&tattr);
1832 log_error ("error preparing housekeeping thread: %s\n", strerror (err));
1835 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1836 err = npth_create (&thread, &tattr, housekeeping_thread, NULL);
1838 log_error ("error spawning housekeeping thread: %s\n",
1840 npth_attr_destroy (&tattr);
1846 /* Check the nonce on a new connection. This is a NOP unless we are
1847 using our Unix domain socket emulation under Windows. */
1849 check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
1851 if (assuan_sock_check_nonce (fd, nonce))
1853 log_info (_("error reading nonce on fd %d: %s\n"),
1854 FD2INT (fd), strerror (errno));
1855 assuan_sock_close (fd);
1863 /* Helper to call a connection's main function. */
1865 start_connection_thread (void *arg)
1867 union int_and_ptr_u argval;
1870 memset (&argval, 0, sizeof argval);
1874 if (check_nonce (fd, &socket_nonce))
1876 log_error ("handler nonce check FAILED\n");
1880 #ifndef HAVE_W32_SYSTEM
1881 npth_setspecific (my_tlskey_current_fd, argval.aptr);
1884 active_connections++;
1886 log_info (_("handler for fd %d started\n"), FD2INT (fd));
1888 start_command_handler (fd);
1891 log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
1892 active_connections--;
1894 #ifndef HAVE_W32_SYSTEM
1895 argval.afd = ASSUAN_INVALID_FD;
1896 npth_setspecific (my_tlskey_current_fd, argval.aptr);
1903 #ifdef HAVE_INOTIFY_INIT
1904 /* Read an inotify event and return true if it matches NAME. */
1906 my_inotify_is_name (int fd, const char *name)
1909 struct inotify_event ev;
1910 char _buf[sizeof (struct inotify_event) + 100 + 1];
1915 s = strrchr (name, '/');
1919 n = npth_read (fd, &buf, sizeof buf);
1920 if (n < sizeof (struct inotify_event))
1922 if (buf.ev.len < strlen (name)+1)
1924 if (strcmp (buf.ev.name, name))
1925 return 0; /* Not the desired file. */
1927 return 1; /* Found. */
1929 #endif /*HAVE_INOTIFY_INIT*/
1932 /* Main loop in daemon mode. Note that LISTEN_FD will be owned by
1935 handle_connections (assuan_fd_t listen_fd)
1938 #ifndef HAVE_W32_SYSTEM
1941 struct sockaddr_un paddr;
1942 socklen_t plen = sizeof( paddr );
1945 fd_set fdset, read_fdset;
1946 struct timespec abstime;
1947 struct timespec curtime;
1948 struct timespec timeout;
1950 int my_inotify_fd = -1;
1952 npth_attr_init (&tattr);
1953 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1955 #ifndef HAVE_W32_SYSTEM /* FIXME */
1957 npth_sigev_add (SIGHUP);
1958 npth_sigev_add (SIGUSR1);
1959 npth_sigev_add (SIGUSR2);
1960 npth_sigev_add (SIGINT);
1961 npth_sigev_add (SIGTERM);
1965 #ifdef HAVE_INOTIFY_INIT
1966 if (disable_check_own_socket)
1968 else if ((my_inotify_fd = inotify_init ()) == -1)
1969 log_info ("error enabling fast daemon termination: %s\n",
1973 /* We need to watch the directory for the file because there
1974 * won't be an IN_DELETE_SELF for a socket file. */
1975 char *slash = strrchr (socket_name, '/');
1976 log_assert (slash && slash[1]);
1978 if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1)
1980 close (my_inotify_fd);
1985 #endif /*HAVE_INOTIFY_INIT*/
1988 /* Setup the fdset. It has only one member. This is because we use
1989 pth_select instead of pth_accept to properly sync timeouts with
1992 FD_SET (FD2INT (listen_fd), &fdset);
1993 nfd = FD2INT (listen_fd);
1994 if (my_inotify_fd != -1)
1996 FD_SET (my_inotify_fd, &fdset);
1997 if (my_inotify_fd > nfd)
1998 nfd = my_inotify_fd;
2001 npth_clock_gettime (&abstime);
2002 abstime.tv_sec += TIMERTICK_INTERVAL;
2007 /* Shutdown test. */
2008 if (shutdown_pending)
2010 if (!active_connections)
2013 /* Do not accept new connections but keep on running the
2014 * loop to cope with the timer events.
2016 * Note that we do not close the listening socket because a
2017 * client trying to connect to that socket would instead
2018 * restart a new dirmngr instance - which is unlikely the
2019 * intention of a shutdown. */
2020 /* assuan_sock_close (listen_fd); */
2021 /* listen_fd = -1; */
2024 if (my_inotify_fd != -1)
2026 FD_SET (my_inotify_fd, &fdset);
2027 nfd = my_inotify_fd;
2031 /* Take a copy of the fdset. */
2034 npth_clock_gettime (&curtime);
2035 if (!(npth_timercmp (&curtime, &abstime, <)))
2039 npth_clock_gettime (&abstime);
2040 abstime.tv_sec += TIMERTICK_INTERVAL;
2042 npth_timersub (&abstime, &curtime, &timeout);
2044 #ifndef HAVE_W32_SYSTEM
2045 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask());
2046 saved_errno = errno;
2048 while (npth_sigev_get_pending(&signo))
2049 handle_signal (signo);
2051 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
2052 saved_errno = errno;
2055 if (ret == -1 && saved_errno != EINTR)
2057 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2058 strerror (saved_errno));
2065 /* Interrupt or timeout. Will be handled when calculating the
2070 if (shutdown_pending)
2072 /* Do not anymore accept connections. */
2076 #ifdef HAVE_INOTIFY_INIT
2077 if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset)
2078 && my_inotify_is_name (my_inotify_fd, socket_name))
2080 shutdown_pending = 1;
2081 log_info ("socket file has been removed - shutting down\n");
2083 #endif /*HAVE_INOTIFY_INIT*/
2085 if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
2087 plen = sizeof paddr;
2088 fd = INT2FD (npth_accept (FD2INT(listen_fd),
2089 (struct sockaddr *)&paddr, &plen));
2090 if (fd == GNUPG_INVALID_FD)
2092 log_error ("accept failed: %s\n", strerror (errno));
2096 char threadname[50];
2097 union int_and_ptr_u argval;
2100 memset (&argval, 0, sizeof argval);
2102 snprintf (threadname, sizeof threadname,
2103 "conn fd=%d", FD2INT(fd));
2105 ret = npth_create (&thread, &tattr,
2106 start_connection_thread, argval.aptr);
2109 log_error ("error spawning connection handler: %s\n",
2111 assuan_sock_close (fd);
2113 npth_setname_np (thread, threadname);
2115 fd = GNUPG_INVALID_FD;
2119 #ifdef HAVE_INOTIFY_INIT
2120 if (my_inotify_fd != -1)
2121 close (my_inotify_fd);
2122 #endif /*HAVE_INOTIFY_INIT*/
2123 npth_attr_destroy (&tattr);
2124 if (listen_fd != -1)
2125 assuan_sock_close (fd);
2127 log_info ("%s %s stopped\n", strusage(11), strusage(13));
2131 dirmngr_get_current_socket_name (void)
2136 return dirmngr_socket_name ();