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 if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
486 log_error ("error enabling Tor mode: %s\n", strerror (errno));
487 log_info ("(is your Libassuan recent enough?)\n");
494 wrong_args (const char *text)
496 es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME);
497 es_fputs (text, es_stderr);
498 es_putc ('\n', es_stderr);
503 /* Helper to stop the reaper thread for the ldap wrapper. */
505 shutdown_reaper (void)
508 ldap_wrapper_wait_connections ();
513 /* Handle options which are allowed to be reset after program start.
514 Return true if the current option in PARGS could be handled and
515 false if not. As a special feature, passing a value of NULL for
516 PARGS, resets the options to the default. REREAD should be set
517 true if it is not the initial option parsing. */
519 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
526 opt.ldap_wrapper_program = NULL;
527 opt.disable_http = 0;
528 opt.disable_ldap = 0;
529 opt.honor_http_proxy = 0;
530 opt.http_proxy = NULL;
531 opt.ldap_proxy = NULL;
532 opt.only_ldap_proxy = 0;
533 opt.ignore_http_dp = 0;
534 opt.ignore_ldap_dp = 0;
535 opt.ignore_ocsp_service_url = 0;
537 opt.allow_version_check = 0;
538 opt.ocsp_responder = NULL;
539 opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */
540 opt.ocsp_max_period = 90 * 86400; /* 90 days. */
541 opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */
542 opt.max_replies = DEFAULT_MAX_REPLIES;
543 while (opt.ocsp_signer)
545 fingerprint_list_t tmp = opt.ocsp_signer->next;
546 xfree (opt.ocsp_signer);
547 opt.ocsp_signer = tmp;
549 FREE_STRLIST (opt.ignored_cert_extensions);
550 http_register_tls_ca (NULL);
551 FREE_STRLIST (opt.keyserver);
552 /* Note: We do not allow resetting of opt.use_tor at runtime. */
553 disable_check_own_socket = 0;
554 enable_standard_resolver (0);
559 switch (pargs->r_opt)
561 case oQuiet: opt.quiet = 1; break;
562 case oVerbose: opt.verbose++; break;
564 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
566 case oDebugAll: opt.debug = ~0; break;
567 case oDebugLevel: debug_level = pargs->r.ret_str; break;
568 case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break;
572 return 0; /* Not handled. */
573 if (!current_logfile || !pargs->r.ret_str
574 || strcmp (current_logfile, pargs->r.ret_str))
576 log_set_file (pargs->r.ret_str);
577 xfree (current_logfile);
578 current_logfile = xtrystrdup (pargs->r.ret_str);
582 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
584 case oLDAPWrapperProgram:
585 opt.ldap_wrapper_program = pargs->r.ret_str;
587 case oHTTPWrapperProgram:
588 opt.http_wrapper_program = pargs->r.ret_str;
591 case oDisableHTTP: opt.disable_http = 1; break;
592 case oDisableLDAP: opt.disable_ldap = 1; break;
593 case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
594 case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
595 case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
596 case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
597 case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
598 case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
599 case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
601 case oAllowOCSP: opt.allow_ocsp = 1; break;
602 case oAllowVersionCheck: opt.allow_version_check = 1; break;
603 case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
605 opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str);
607 case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
608 case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
609 case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
611 case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
617 /* Do tilde expansion and make path absolute. */
618 tmpname = make_absfilename (pargs->r.ret_str, NULL);
619 http_register_tls_ca (tmpname);
624 case oIgnoreCertExtension:
625 add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
628 case oUseTor: opt.use_tor = 1; break;
630 case oStandardResolver: enable_standard_resolver (1); break;
631 case oRecursiveResolver: enable_recursive_resolver (1); break;
634 if (*pargs->r.ret_str)
635 add_to_strlist (&opt.keyserver, pargs->r.ret_str);
639 set_dns_nameserver (pargs->r.ret_str);
642 case oResolverTimeout:
643 set_dns_timeout (pargs->r.ret_int);
647 return 0; /* Not handled. */
650 set_dns_verbose (opt.verbose, !!DBG_DNS);
652 return 1; /* Handled. */
656 #ifndef HAVE_W32_SYSTEM
658 pid_suffix_callback (unsigned long *r_suffix)
660 union int_and_ptr_u value;
662 memset (&value, 0, sizeof value);
663 value.aptr = npth_getspecific (my_tlskey_current_fd);
664 *r_suffix = value.aint;
665 return (*r_suffix != -1); /* Use decimal representation. */
667 #endif /*!HAVE_W32_SYSTEM*/
674 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
676 /* Now with NPth running we can set the logging callback. Our
677 windows implementation does not yet feature the NPth TLS
679 #ifndef HAVE_W32_SYSTEM
680 if (npth_key_create (&my_tlskey_current_fd, NULL) == 0)
681 if (npth_setspecific (my_tlskey_current_fd, NULL) == 0)
682 log_set_pid_suffix_cb (pid_suffix_callback);
683 #endif /*!HAVE_W32_SYSTEM*/
688 main (int argc, char **argv)
690 enum cmd_and_opt_values cmd = 0;
694 FILE *configfp = NULL;
695 char *configname = NULL;
697 unsigned configlineno;
699 int default_config =1;
704 char *logfile = NULL;
706 char *ldapfile = NULL;
710 struct assuan_malloc_hooks malloc_hooks;
712 early_system_init ();
713 set_strusage (my_strusage);
714 log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
716 /* Make sure that our subsystems are ready. */
718 init_common_subsystems (&argc, &argv);
720 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
722 /* Check that the libraries are suitable. Do it here because
723 the option parsing may need services of the libraries. */
724 if (!ksba_check_version (NEED_KSBA_VERSION) )
725 log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba",
726 NEED_KSBA_VERSION, ksba_check_version (NULL) );
728 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
729 ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
731 /* Init TLS library. */
733 if (!ntbtls_check_version (NEED_NTBTLS_VERSION) )
734 log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls",
735 NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) );
736 #elif HTTP_USE_GNUTLS
737 rc = gnutls_global_init ();
739 log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));
740 #endif /*HTTP_USE_GNUTLS*/
743 malloc_hooks.malloc = gcry_malloc;
744 malloc_hooks.realloc = gcry_realloc;
745 malloc_hooks.free = gcry_free;
746 assuan_set_malloc_hooks (&malloc_hooks);
747 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
748 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
749 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
751 setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor);
753 setup_libgcrypt_logging ();
755 /* Setup defaults. */
756 shell = getenv ("SHELL");
757 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
760 /* Reset rereadable options to default values. */
761 parse_rereadable_options (NULL, 0);
764 opt.add_new_ldapservers = 0;
765 opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
767 /* Other defaults. */
769 /* Check whether we have a config file given on the commandline */
774 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
775 while (arg_parse( &pargs, opts))
777 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
779 else if (pargs.r_opt == oOptions)
780 { /* Yes there is one, so we do not try the default one, but
781 read the option file when it is encountered at the
785 else if (pargs.r_opt == oNoOptions)
786 default_config = 0; /* --no-options */
787 else if (pargs.r_opt == oHomedir)
789 gnupg_set_homedir (pargs.r.ret_str);
793 socket_name = dirmngr_socket_name ();
795 configname = make_filename (gnupg_homedir (), DIRMNGR_NAME".conf", NULL );
801 pargs.flags= 1; /* do not remove the args */
806 configfp = fopen (configname, "r");
812 log_info (_("Note: no default option file '%s'\n"),
817 log_error (_("option file '%s': %s\n"),
818 configname, strerror(errno) );
824 if (parse_debug && configname )
825 log_info (_("reading options from '%s'\n"), configname );
829 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
831 if (parse_rereadable_options (&pargs, 0))
832 continue; /* Already handled */
848 case oQuiet: opt.quiet = 1; break;
849 case oVerbose: opt.verbose++; break;
850 case oBatch: opt.batch=1; break;
852 case oDebugWait: debug_wait = pargs.r.ret_int; break;
855 /* Config files may not be nested (silently ignore them) */
859 configname = xstrdup(pargs.r.ret_str);
863 case oNoGreeting: nogreeting = 1; break;
864 case oNoVerbose: opt.verbose = 0; break;
865 case oNoOptions: break; /* no-options */
866 case oHomedir: /* Ignore this option here. */; break;
867 case oNoDetach: nodetach = 1; break;
868 case oLogFile: logfile = pargs.r.ret_str; break;
869 case oCsh: csh_style = 1; break;
870 case oSh: csh_style = 0; break;
873 ldapfile = pargs.r.ret_str;
876 case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
878 opt.ldaptimeout = pargs.r.ret_int;
881 case oFakedSystemTime:
882 gnupg_set_time ((time_t)pargs.r.ret_ulong, 0);
885 case oForce: opt.force = 1; break;
887 case oSocketName: socket_name = pargs.r.ret_str; break;
889 default : pargs.err = configfp? 1:2; break;
896 /* Keep a copy of the name so that it can be read on SIGHUP. */
897 opt.config_filename = configname;
903 if (log_get_errorcount(0))
908 if (!opt.homedir_cache)
909 opt.homedir_cache = xstrdup (gnupg_homedir ());
913 es_fprintf (es_stderr, "%s %s; %s\n",
914 strusage(11), strusage(13), strusage(14) );
915 es_fprintf (es_stderr, "%s\n", strusage(15) );
918 #ifdef IS_DEVELOPMENT_VERSION
919 log_info ("NOTE: this is a development version!\n");
924 log_info ("WARNING: ***************************************\n");
925 log_info ("WARNING: Tor mode (--use-tor) MAY NOT FULLY WORK!\n");
926 log_info ("WARNING: ***************************************\n");
929 /* Print a warning if an argument looks like an option. */
930 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
934 for (i=0; i < argc; i++)
935 if (argv[i][0] == '-' && argv[i][1] == '-')
936 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
939 if (!access ("/etc/"DIRMNGR_NAME, F_OK)
940 && !strncmp (gnupg_homedir (), "/etc/", 5))
942 ("NOTE: DirMngr is now a proper part of %s. The configuration and"
943 " other directory names changed. Please check that no other version"
944 " of dirmngr is still installed. To disable this warning, remove the"
945 " directory '/etc/dirmngr'.\n", GNUPG_NAME);
947 if (gnupg_faked_time_p ())
949 gnupg_isotime_t tbuf;
951 log_info (_("WARNING: running with faked system time: "));
952 gnupg_get_isotime (tbuf);
960 /* Get LDAP server list from file. */
964 ldapfile = make_filename (gnupg_homedir (),
965 "dirmngr_ldapservers.conf",
967 opt.ldapservers = parse_ldapserver_file (ldapfile);
971 opt.ldapservers = parse_ldapserver_file (ldapfile);
974 #ifndef HAVE_W32_SYSTEM
975 /* We need to ignore the PIPE signal because the we might log to a
976 socket and that code handles EPIPE properly. The ldap wrapper
977 also requires us to ignore this silly signal. Assuan would set
978 this signal to ignore anyway.*/
979 signal (SIGPIPE, SIG_IGN);
982 /* Ready. Now to our duties. */
989 /* Note that this server mode is mainly useful for debugging. */
991 wrong_args ("--server");
995 log_set_file (logfile);
996 log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1001 log_debug ("waiting for debugger - my pid is %u .....\n",
1002 (unsigned int)getpid());
1003 gnupg_sleep (debug_wait);
1004 log_debug ("... okay\n");
1011 http_register_netactivity_cb (netactivity_action);
1012 start_command_handler (ASSUAN_INVALID_FD);
1015 #ifndef HAVE_W32_SYSTEM
1016 else if (cmd == aSupervised)
1018 /* In supervised mode, we expect file descriptor 3 to be an
1019 already opened, listening socket.
1021 We will also not detach from the controlling process or close
1022 stderr; the supervisor should handle all of that. */
1023 struct stat statbuf;
1024 if (fstat (3, &statbuf) == -1 && errno == EBADF)
1026 log_error ("file descriptor 3 must be validin --supervised mode\n");
1029 socket_name = gnupg_get_socket_name (3);
1031 /* Now start with logging to a file if this is desired. */
1034 log_set_file (logfile);
1035 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1036 |GPGRT_LOG_WITH_TIME
1037 |GPGRT_LOG_WITH_PID));
1038 current_logfile = xstrdup (logfile);
1041 log_set_prefix (NULL, 0);
1046 http_register_netactivity_cb (netactivity_action);
1047 handle_connections (3);
1050 #endif /*HAVE_W32_SYSTEM*/
1051 else if (cmd == aDaemon)
1056 struct sockaddr_un serv_addr;
1059 wrong_args ("--daemon");
1061 /* Now start with logging to a file if this is desired. */
1064 log_set_file (logfile);
1065 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1066 |GPGRT_LOG_WITH_TIME
1067 |GPGRT_LOG_WITH_PID));
1068 current_logfile = xstrdup (logfile);
1071 #ifndef HAVE_W32_SYSTEM
1072 if (strchr (socket_name, ':'))
1074 log_error (_("colons are not allowed in the socket name\n"));
1078 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1079 if (fd == ASSUAN_INVALID_FD)
1081 log_error (_("can't create socket: %s\n"), strerror (errno));
1089 if (assuan_sock_set_sockaddr_un (socket_name,
1090 (struct sockaddr*)&serv_addr,
1093 if (errno == ENAMETOOLONG)
1094 log_error (_("socket name '%s' is too long\n"), socket_name);
1096 log_error ("error preparing socket '%s': %s\n",
1098 gpg_strerror (gpg_error_from_syserror ()));
1103 redir_socket_name = xstrdup (serv_addr.sun_path);
1105 log_info ("redirecting socket '%s' to '%s'\n",
1106 socket_name, redir_socket_name);
1110 len = SUN_LEN (&serv_addr);
1112 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1114 && (errno == EADDRINUSE
1115 #ifdef HAVE_W32_SYSTEM
1120 /* Fixme: We should test whether a dirmngr is already running. */
1121 gnupg_remove (redir_socket_name? redir_socket_name : socket_name);
1122 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1125 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
1126 log_error (_("error getting nonce for the socket\n"));
1129 log_error (_("error binding socket to '%s': %s\n"),
1131 gpg_strerror (gpg_error_from_errno (errno)));
1132 assuan_sock_close (fd);
1137 if (gnupg_chmod (serv_addr.sun_path, "-rwx"))
1138 log_error (_("can't set permissions of '%s': %s\n"),
1139 serv_addr.sun_path, strerror (errno));
1141 if (listen (FD2INT (fd), 5) == -1)
1143 log_error (_("listen() failed: %s\n"), strerror (errno));
1144 assuan_sock_close (fd);
1149 log_info (_("listening on socket '%s'\n"), serv_addr.sun_path);
1153 /* Note: We keep the dirmngr_info output only for the sake of
1154 existing scripts which might use this to detect a successful
1155 start of the dirmngr. */
1156 #ifdef HAVE_W32_SYSTEM
1161 es_printf ("set %s=%s;%lu;1\n",
1162 DIRMNGR_INFO_NAME, socket_name, (ulong) pid);
1165 if (pid == (pid_t)-1)
1167 log_fatal (_("error forking process: %s\n"), strerror (errno));
1172 { /* We are the parent */
1175 /* Don't let cleanup() remove the socket - the child is
1176 responsible for doing that. */
1181 /* Create the info string: <name>:<pid>:<protocol_version> */
1182 if (asprintf (&infostr, "%s=%s:%lu:1",
1183 DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0)
1185 log_error (_("out of core\n"));
1186 kill (pid, SIGTERM);
1189 /* Print the environment string, so that the caller can use
1190 shell's eval to set it. But see above. */
1193 *strchr (infostr, '=') = ' ';
1194 es_printf ( "setenv %s;\n", infostr);
1198 es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME);
1210 /* Detach from tty and put process into a new session */
1214 unsigned int oldflags;
1216 /* Close stdin, stdout and stderr unless it is the log stream */
1217 for (i=0; i <= 2; i++)
1219 if (!log_test_fd (i) && i != fd )
1222 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1224 log_error ("failed to open '%s': %s\n",
1225 "/dev/null", strerror (errno));
1234 log_error ("setsid() failed: %s\n", strerror(errno) );
1238 log_get_prefix (&oldflags);
1239 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1240 opt.running_detached = 1;
1244 log_error ("chdir to / failed: %s\n", strerror (errno));
1253 http_register_netactivity_cb (netactivity_action);
1254 handle_connections (fd);
1257 else if (cmd == aListCRLs)
1259 /* Just list the CRL cache and exit. */
1261 wrong_args ("--list-crls");
1263 crl_cache_list (es_stdout);
1265 else if (cmd == aLoadCRL)
1267 struct server_control_s ctrlbuf;
1269 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1270 dirmngr_init_default_ctrl (&ctrlbuf);
1276 rc = crl_cache_load (&ctrlbuf, NULL);
1279 for (; !rc && argc; argc--, argv++)
1280 rc = crl_cache_load (&ctrlbuf, *argv);
1282 dirmngr_deinit_default_ctrl (&ctrlbuf);
1284 else if (cmd == aFetchCRL)
1286 ksba_reader_t reader;
1287 struct server_control_s ctrlbuf;
1290 wrong_args ("--fetch-crl URL");
1292 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1293 dirmngr_init_default_ctrl (&ctrlbuf);
1298 rc = crl_fetch (&ctrlbuf, argv[0], &reader);
1300 log_error (_("fetching CRL from '%s' failed: %s\n"),
1301 argv[0], gpg_strerror (rc));
1304 rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
1306 log_error (_("processing CRL from '%s' failed: %s\n"),
1307 argv[0], gpg_strerror (rc));
1308 crl_close_reader (reader);
1310 dirmngr_deinit_default_ctrl (&ctrlbuf);
1312 else if (cmd == aFlush)
1314 /* Delete cache and exit. */
1316 wrong_args ("--flush");
1317 rc = crl_cache_flush();
1319 else if (cmd == aGPGConfTest)
1321 else if (cmd == aGPGConfList)
1323 unsigned long flags = 0;
1327 /* First the configuration file. This is not an option, but it
1328 is vital information for GPG Conf. */
1329 if (!opt.config_filename)
1330 opt.config_filename = make_filename (gnupg_homedir (),
1331 "dirmngr.conf", NULL );
1333 filename = percent_escape (opt.config_filename, NULL);
1334 es_printf ("gpgconf-dirmngr.conf:%lu:\"%s\n",
1335 GC_OPT_FLAG_DEFAULT, filename);
1338 es_printf ("verbose:%lu:\n", flags | GC_OPT_FLAG_NONE);
1339 es_printf ("quiet:%lu:\n", flags | GC_OPT_FLAG_NONE);
1340 es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
1341 es_printf ("log-file:%lu:\n", flags | GC_OPT_FLAG_NONE);
1342 es_printf ("force:%lu:\n", flags | GC_OPT_FLAG_NONE);
1344 /* --csh and --sh are mutually exclusive, something we can not
1345 express in GPG Conf. --options is only usable from the
1346 command line, really. --debug-all interacts with --debug,
1347 and having both of them is thus problematic. --no-detach is
1348 also only usable on the command line. --batch is unused. */
1350 filename = make_filename (gnupg_homedir (),
1351 "dirmngr_ldapservers.conf",
1353 filename_esc = percent_escape (filename, NULL);
1354 es_printf ("ldapserverlist-file:%lu:\"%s\n", flags | GC_OPT_FLAG_DEFAULT,
1356 xfree (filename_esc);
1359 es_printf ("ldaptimeout:%lu:%u\n",
1360 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
1361 es_printf ("max-replies:%lu:%u\n",
1362 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
1363 es_printf ("allow-ocsp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1364 es_printf ("allow-version-check:%lu:\n", flags | GC_OPT_FLAG_NONE);
1365 es_printf ("ocsp-responder:%lu:\n", flags | GC_OPT_FLAG_NONE);
1366 es_printf ("ocsp-signer:%lu:\n", flags | GC_OPT_FLAG_NONE);
1368 es_printf ("faked-system-time:%lu:\n", flags | GC_OPT_FLAG_NONE);
1369 es_printf ("no-greeting:%lu:\n", flags | GC_OPT_FLAG_NONE);
1371 es_printf ("disable-http:%lu:\n", flags | GC_OPT_FLAG_NONE);
1372 es_printf ("disable-ldap:%lu:\n", flags | GC_OPT_FLAG_NONE);
1373 es_printf ("honor-http-proxy:%lu\n", flags | GC_OPT_FLAG_NONE);
1374 es_printf ("http-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1375 es_printf ("ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1376 es_printf ("only-ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1377 es_printf ("ignore-ldap-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1378 es_printf ("ignore-http-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1379 es_printf ("ignore-ocsp-service-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1380 /* Note: The next one is to fix a typo in gpgconf - should be
1381 removed eventually. */
1382 es_printf ("ignore-ocsp-servic-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1384 es_printf ("use-tor:%lu:\n", flags | GC_OPT_FLAG_NONE);
1385 es_printf ("keyserver:%lu:\n", flags | GC_OPT_FLAG_NONE);
1386 es_printf ("nameserver:%lu:\n", flags | GC_OPT_FLAG_NONE);
1387 es_printf ("resolver-timeout:%lu:%u\n",
1388 flags | GC_OPT_FLAG_DEFAULT, 0);
1398 crl_cache_deinit ();
1399 cert_cache_deinit (1);
1400 reload_dns_stuff (1);
1403 ldapserver_list_free (opt.ldapservers);
1405 opt.ldapservers = NULL;
1410 if (redir_socket_name)
1411 gnupg_remove (redir_socket_name);
1412 else if (socket_name && *socket_name)
1413 gnupg_remove (socket_name);
1419 dirmngr_exit (int rc)
1427 dirmngr_init_default_ctrl (ctrl_t ctrl)
1430 ctrl->http_proxy = xstrdup (opt.http_proxy);
1435 dirmngr_deinit_default_ctrl (ctrl_t ctrl)
1439 xfree (ctrl->http_proxy);
1440 ctrl->http_proxy = NULL;
1444 /* Create a list of LDAP servers from the file FILENAME. Returns the
1445 list or NULL in case of errors.
1447 The format fo such a file is line oriented where empty lines and
1448 lines starting with a hash mark are ignored. All other lines are
1449 assumed to be colon seprated with these fields:
1452 2. field: Portnumber
1459 static ldap_server_t
1460 parse_ldapserver_file (const char* filename)
1464 ldap_server_t server, serverstart, *serverend;
1466 unsigned int lineno = 0;
1469 fp = es_fopen (filename, "r");
1472 log_error (_("error opening '%s': %s\n"), filename, strerror (errno));
1477 serverend = &serverstart;
1478 while (es_fgets (buffer, sizeof buffer, fp))
1481 if (!*buffer || buffer[strlen(buffer)-1] != '\n')
1483 if (*buffer && es_feof (fp))
1484 ; /* Last line not terminated - continue. */
1487 log_error (_("%s:%u: line too long - skipped\n"),
1489 while ( (c=es_fgetc (fp)) != EOF && c != '\n')
1490 ; /* Skip until end of line. */
1494 /* Skip empty and comment lines.*/
1495 for (p=buffer; spacep (p); p++)
1497 if (!*p || *p == '\n' || *p == '#')
1500 /* Parse the colon separated fields. */
1501 server = ldapserver_parse_one (buffer, filename, lineno);
1504 *serverend = server;
1505 serverend = &server->next;
1510 log_error (_("error reading '%s': %s\n"), filename, strerror (errno));
1517 static fingerprint_list_t
1518 parse_ocsp_signer (const char *string)
1525 fingerprint_list_t list, *list_tail, item;
1526 unsigned int lnr = 0;
1531 /* Check whether this is not a filename and treat it as a direct
1532 fingerprint specification. */
1533 if (!strpbrk (string, "/.~\\"))
1535 item = xcalloc (1, sizeof *item);
1536 for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
1537 if ( string[i] != ':' )
1538 item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
1539 item->hexfpr[j] = 0;
1540 if (j != 40 || !(spacep (string+i) || !string[i]))
1542 log_error (_("%s:%u: invalid fingerprint detected\n"),
1543 "--ocsp-signer", 0);
1550 /* Well, it is a filename. */
1551 if (*string == '/' || (*string == '~' && string[1] == '/'))
1552 fname = make_filename (string, NULL);
1555 if (string[0] == '.' && string[1] == '/' )
1557 fname = make_filename (gnupg_homedir (), string, NULL);
1560 fp = es_fopen (fname, "r");
1563 err = gpg_error_from_syserror ();
1564 log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
1573 if (!es_fgets (line, DIM(line)-1, fp) )
1577 err = gpg_error_from_syserror ();
1578 log_error (_("%s:%u: read error: %s\n"),
1579 fname, lnr, gpg_strerror (err));
1587 fingerprint_list_t tmp = list->next;
1593 return list; /* Ready. */
1597 if (!*line || line[strlen(line)-1] != '\n')
1599 /* Eat until end of line. */
1600 while ( (c=es_getc (fp)) != EOF && c != '\n')
1602 err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
1603 /* */: GPG_ERR_INCOMPLETE_LINE);
1604 log_error (_("%s:%u: read error: %s\n"),
1605 fname, lnr, gpg_strerror (err));
1610 /* Allow for empty lines and spaces */
1611 for (p=line; spacep (p); p++)
1613 if (!*p || *p == '\n' || *p == '#')
1616 item = xcalloc (1, sizeof *item);
1618 list_tail = &item->next;
1620 for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
1622 item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
1623 item->hexfpr[j] = 0;
1624 if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
1626 log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
1630 while (spacep (p+i))
1632 if (p[i] && p[i] != '\n')
1633 log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
1642 Stuff used in daemon mode.
1647 /* Reread parts of the configuration. Note, that this function is
1648 obviously not thread-safe and should only be called from the NPTH
1651 Fixme: Due to the way the argument parsing works, we create a
1652 memory leak here for all string type arguments. There is currently
1653 no clean way to tell whether the memory for the argument has been
1654 allocated or points into the process' original arguments. Unless
1655 we have a mechanism to tell this, we need to live on with this. */
1657 reread_configuration (void)
1659 ARGPARSE_ARGS pargs;
1661 unsigned int configlineno = 0;
1664 if (!opt.config_filename)
1665 return; /* No config file. */
1667 fp = fopen (opt.config_filename, "r");
1670 log_error (_("option file '%s': %s\n"),
1671 opt.config_filename, strerror(errno) );
1675 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1677 memset (&pargs, 0, sizeof pargs);
1679 pargs.argc = &dummy;
1680 pargs.flags = 1; /* do not remove the args */
1681 while (optfile_parse (fp, opt.config_filename, &configlineno, &pargs, opts) )
1683 if (pargs.r_opt < -1)
1684 pargs.err = 1; /* Print a warning. */
1685 else /* Try to parse this option - ignore unchangeable ones. */
1686 parse_rereadable_options (&pargs, 1);
1695 /* A global function which allows us to trigger the reload stuff from
1698 dirmngr_sighup_action (void)
1700 log_info (_("SIGHUP received - "
1701 "re-reading configuration and flushing caches\n"));
1702 reread_configuration ();
1703 cert_cache_deinit (0);
1704 crl_cache_deinit ();
1707 reload_dns_stuff (0);
1711 /* This function is called if some network activity was done. At this
1712 * point we know the we have a network and we can decide whether to
1713 * run scheduled background tasks soon. The function should return
1714 * quickly and only trigger actions for another thread. */
1716 netactivity_action (void)
1718 network_activity_seen = 1;
1722 /* The signal handler. */
1723 #ifndef HAVE_W32_SYSTEM
1725 handle_signal (int signo)
1730 dirmngr_sighup_action ();
1734 cert_cache_print_stats ();
1738 log_info (_("SIGUSR2 received - no action defined\n"));
1742 if (!shutdown_pending)
1743 log_info (_("SIGTERM received - shutting down ...\n"));
1745 log_info (_("SIGTERM received - still %d active connections\n"),
1746 active_connections);
1748 if (shutdown_pending > 2)
1750 log_info (_("shutdown forced\n"));
1751 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1758 log_info (_("SIGINT received - immediate shutdown\n"));
1759 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1765 log_info (_("signal %d received - no action defined\n"), signo);
1768 #endif /*!HAVE_W32_SYSTEM*/
1771 /* Thread to do the housekeeping. */
1773 housekeeping_thread (void *arg)
1775 static int sentinel;
1781 log_info ("housekeeping is already going on\n");
1785 if (opt.verbose > 1)
1786 log_info ("starting housekeeping\n");
1788 if (opt.verbose > 1)
1789 log_info ("ready with housekeeping\n");
1796 #if GPGRT_GCC_HAVE_PUSH_PRAGMA
1797 # pragma GCC push_options
1798 # pragma GCC optimize ("no-strict-overflow")
1801 time_for_housekeeping_p (time_t curtime)
1803 static time_t last_housekeeping;
1805 if (!last_housekeeping)
1806 last_housekeeping = curtime;
1808 if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime
1809 || last_housekeeping > curtime /*(be prepared for y2038)*/)
1811 last_housekeeping = curtime;
1816 #if GPGRT_GCC_HAVE_PUSH_PRAGMA
1817 # pragma GCC pop_options
1821 /* This is the worker for the ticker. It is called every few seconds
1822 and may only do fast operations. */
1826 if (time_for_housekeeping_p (gnupg_get_time ()))
1832 err = npth_attr_init (&tattr);
1834 log_error ("error preparing housekeeping thread: %s\n", strerror (err));
1837 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1838 err = npth_create (&thread, &tattr, housekeeping_thread, NULL);
1840 log_error ("error spawning housekeeping thread: %s\n",
1842 npth_attr_destroy (&tattr);
1848 /* Check the nonce on a new connection. This is a NOP unless we are
1849 using our Unix domain socket emulation under Windows. */
1851 check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
1853 if (assuan_sock_check_nonce (fd, nonce))
1855 log_info (_("error reading nonce on fd %d: %s\n"),
1856 FD2INT (fd), strerror (errno));
1857 assuan_sock_close (fd);
1865 /* Helper to call a connection's main function. */
1867 start_connection_thread (void *arg)
1869 union int_and_ptr_u argval;
1872 memset (&argval, 0, sizeof argval);
1876 if (check_nonce (fd, &socket_nonce))
1878 log_error ("handler nonce check FAILED\n");
1882 #ifndef HAVE_W32_SYSTEM
1883 npth_setspecific (my_tlskey_current_fd, argval.aptr);
1886 active_connections++;
1888 log_info (_("handler for fd %d started\n"), FD2INT (fd));
1890 start_command_handler (fd);
1893 log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
1894 active_connections--;
1896 #ifndef HAVE_W32_SYSTEM
1897 argval.afd = ASSUAN_INVALID_FD;
1898 npth_setspecific (my_tlskey_current_fd, argval.aptr);
1905 #ifdef HAVE_INOTIFY_INIT
1906 /* Read an inotify event and return true if it matches NAME. */
1908 my_inotify_is_name (int fd, const char *name)
1911 struct inotify_event ev;
1912 char _buf[sizeof (struct inotify_event) + 100 + 1];
1917 s = strrchr (name, '/');
1921 n = npth_read (fd, &buf, sizeof buf);
1922 if (n < sizeof (struct inotify_event))
1924 if (buf.ev.len < strlen (name)+1)
1926 if (strcmp (buf.ev.name, name))
1927 return 0; /* Not the desired file. */
1929 return 1; /* Found. */
1931 #endif /*HAVE_INOTIFY_INIT*/
1934 /* Main loop in daemon mode. Note that LISTEN_FD will be owned by
1937 handle_connections (assuan_fd_t listen_fd)
1940 #ifndef HAVE_W32_SYSTEM
1943 struct sockaddr_un paddr;
1944 socklen_t plen = sizeof( paddr );
1947 fd_set fdset, read_fdset;
1948 struct timespec abstime;
1949 struct timespec curtime;
1950 struct timespec timeout;
1952 int my_inotify_fd = -1;
1954 npth_attr_init (&tattr);
1955 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1957 #ifndef HAVE_W32_SYSTEM /* FIXME */
1959 npth_sigev_add (SIGHUP);
1960 npth_sigev_add (SIGUSR1);
1961 npth_sigev_add (SIGUSR2);
1962 npth_sigev_add (SIGINT);
1963 npth_sigev_add (SIGTERM);
1967 #ifdef HAVE_INOTIFY_INIT
1968 if (disable_check_own_socket)
1970 else if ((my_inotify_fd = inotify_init ()) == -1)
1971 log_info ("error enabling fast daemon termination: %s\n",
1975 /* We need to watch the directory for the file because there
1976 * won't be an IN_DELETE_SELF for a socket file. */
1977 char *slash = strrchr (socket_name, '/');
1978 log_assert (slash && slash[1]);
1980 if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1)
1982 close (my_inotify_fd);
1987 #endif /*HAVE_INOTIFY_INIT*/
1990 /* Setup the fdset. It has only one member. This is because we use
1991 pth_select instead of pth_accept to properly sync timeouts with
1994 FD_SET (FD2INT (listen_fd), &fdset);
1995 nfd = FD2INT (listen_fd);
1996 if (my_inotify_fd != -1)
1998 FD_SET (my_inotify_fd, &fdset);
1999 if (my_inotify_fd > nfd)
2000 nfd = my_inotify_fd;
2003 npth_clock_gettime (&abstime);
2004 abstime.tv_sec += TIMERTICK_INTERVAL;
2009 /* Shutdown test. */
2010 if (shutdown_pending)
2012 if (!active_connections)
2015 /* Do not accept new connections but keep on running the
2016 * loop to cope with the timer events.
2018 * Note that we do not close the listening socket because a
2019 * client trying to connect to that socket would instead
2020 * restart a new dirmngr instance - which is unlikely the
2021 * intention of a shutdown. */
2022 /* assuan_sock_close (listen_fd); */
2023 /* listen_fd = -1; */
2026 if (my_inotify_fd != -1)
2028 FD_SET (my_inotify_fd, &fdset);
2029 nfd = my_inotify_fd;
2033 /* Take a copy of the fdset. */
2036 npth_clock_gettime (&curtime);
2037 if (!(npth_timercmp (&curtime, &abstime, <)))
2041 npth_clock_gettime (&abstime);
2042 abstime.tv_sec += TIMERTICK_INTERVAL;
2044 npth_timersub (&abstime, &curtime, &timeout);
2046 #ifndef HAVE_W32_SYSTEM
2047 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask());
2048 saved_errno = errno;
2050 while (npth_sigev_get_pending(&signo))
2051 handle_signal (signo);
2053 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
2054 saved_errno = errno;
2057 if (ret == -1 && saved_errno != EINTR)
2059 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2060 strerror (saved_errno));
2067 /* Interrupt or timeout. Will be handled when calculating the
2072 if (shutdown_pending)
2074 /* Do not anymore accept connections. */
2078 #ifdef HAVE_INOTIFY_INIT
2079 if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset)
2080 && my_inotify_is_name (my_inotify_fd, socket_name))
2082 shutdown_pending = 1;
2083 log_info ("socket file has been removed - shutting down\n");
2085 #endif /*HAVE_INOTIFY_INIT*/
2087 if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
2089 plen = sizeof paddr;
2090 fd = INT2FD (npth_accept (FD2INT(listen_fd),
2091 (struct sockaddr *)&paddr, &plen));
2092 if (fd == GNUPG_INVALID_FD)
2094 log_error ("accept failed: %s\n", strerror (errno));
2098 char threadname[50];
2099 union int_and_ptr_u argval;
2102 memset (&argval, 0, sizeof argval);
2104 snprintf (threadname, sizeof threadname,
2105 "conn fd=%d", FD2INT(fd));
2107 ret = npth_create (&thread, &tattr,
2108 start_connection_thread, argval.aptr);
2111 log_error ("error spawning connection handler: %s\n",
2113 assuan_sock_close (fd);
2115 npth_setname_np (thread, threadname);
2117 fd = GNUPG_INVALID_FD;
2121 #ifdef HAVE_INOTIFY_INIT
2122 if (my_inotify_fd != -1)
2123 close (my_inotify_fd);
2124 #endif /*HAVE_INOTIFY_INIT*/
2125 npth_attr_destroy (&tattr);
2126 if (listen_fd != -1)
2127 assuan_sock_close (fd);
2129 log_info ("%s %s stopped\n", strusage(11), strusage(13));
2133 dirmngr_get_current_socket_name (void)
2138 return dirmngr_socket_name ();