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"
68 #include "../common/asshelp.h"
70 # include "ldap-wrapper.h"
72 #include "../common/init.h"
73 #include "../common/gc-opt-flags.h"
74 #include "dns-stuff.h"
75 #include "http-common.h"
78 # define ENAMETOOLONG EINVAL
82 enum cmd_and_opt_values {
141 oIgnoreCertExtension,
146 oDisableCheckOwnSocket,
151 oConnectQuickTimeout,
157 static ARGPARSE_OPTS opts[] = {
159 ARGPARSE_group (300, N_("@Commands:\n ")),
161 ARGPARSE_c (aServer, "server", N_("run in server mode (foreground)") ),
162 ARGPARSE_c (aDaemon, "daemon", N_("run in daemon mode (background)") ),
163 #ifndef HAVE_W32_SYSTEM
164 ARGPARSE_c (aSupervised, "supervised", N_("run in supervised mode")),
166 ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")),
167 ARGPARSE_c (aLoadCRL, "load-crl", N_("|FILE|load CRL from FILE into cache")),
168 ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")),
169 ARGPARSE_c (aShutdown, "shutdown", N_("shutdown the dirmngr")),
170 ARGPARSE_c (aFlush, "flush", N_("flush the cache")),
171 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
172 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
174 ARGPARSE_group (301, N_("@\nOptions:\n ")),
176 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
177 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
178 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
179 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
180 ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
181 ARGPARSE_s_s (oDebugLevel, "debug-level",
182 N_("|LEVEL|set the debugging level to LEVEL")),
183 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
184 ARGPARSE_s_s (oLogFile, "log-file",
185 N_("|FILE|write server mode logs to FILE")),
186 ARGPARSE_s_n (oBatch, "batch", N_("run without asking a user")),
187 ARGPARSE_s_n (oForce, "force", N_("force loading of outdated CRLs")),
188 ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")),
189 ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check",
190 N_("allow online software version check")),
191 ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")),
192 ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")),
193 ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp",
194 N_("ignore HTTP CRL distribution points")),
195 ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp",
196 N_("ignore LDAP CRL distribution points")),
197 ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url",
198 N_("ignore certificate contained OCSP service URLs")),
200 ARGPARSE_s_s (oHTTPProxy, "http-proxy",
201 N_("|URL|redirect all HTTP requests to URL")),
202 ARGPARSE_s_s (oLDAPProxy, "ldap-proxy",
203 N_("|HOST|use HOST for LDAP queries")),
204 ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy",
205 N_("do not use fallback hosts with --ldap-proxy")),
207 ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file",
208 N_("|FILE|read LDAP server list from FILE")),
209 ARGPARSE_s_n (oLDAPAddServers, "add-servers",
210 N_("add new servers discovered in CRL distribution"
211 " points to serverlist")),
212 ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout",
213 N_("|N|set LDAP timeout to N seconds")),
215 ARGPARSE_s_s (oOCSPResponder, "ocsp-responder",
216 N_("|URL|use OCSP responder at URL")),
217 ARGPARSE_s_s (oOCSPSigner, "ocsp-signer",
218 N_("|FPR|OCSP response signed by FPR")),
219 ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"),
220 ARGPARSE_s_i (oOCSPMaxPeriod, "ocsp-max-period", "@"),
221 ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"),
223 ARGPARSE_s_i (oMaxReplies, "max-replies",
224 N_("|N|do not return more than N items in one query")),
226 ARGPARSE_s_s (oNameServer, "nameserver", "@"),
227 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
228 ARGPARSE_s_s (oHkpCaCert, "hkp-cacert",
229 N_("|FILE|use the CA certificates in FILE for HKP over TLS")),
231 ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")),
232 ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"),
234 ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"),
235 ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"),
237 ARGPARSE_s_s (oSocketName, "socket-name", "@"), /* Only for debugging. */
239 ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/
240 ARGPARSE_s_s (oDebug, "debug", "@"),
241 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
242 ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"),
243 ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"),
244 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
245 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
246 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
247 ARGPARSE_s_s (oHomedir, "homedir", "@"),
248 ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"),
249 ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"),
250 ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy", "@"),
251 ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"),
252 ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"),
253 ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"),
254 ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"),
255 ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"),
256 ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"),
258 ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing "
259 "of all commands and options)\n")),
264 /* The list of supported debug flags. */
265 static struct debug_flags_s debug_flags [] =
267 { DBG_X509_VALUE , "x509" },
268 { DBG_CRYPTO_VALUE , "crypto" },
269 { DBG_MEMORY_VALUE , "memory" },
270 { DBG_CACHE_VALUE , "cache" },
271 { DBG_MEMSTAT_VALUE, "memstat" },
272 { DBG_HASHING_VALUE, "hashing" },
273 { DBG_IPC_VALUE , "ipc" },
274 { DBG_DNS_VALUE , "dns" },
275 { DBG_NETWORK_VALUE, "network" },
276 { DBG_LOOKUP_VALUE , "lookup" },
277 { DBG_EXTPROG_VALUE, "extprog" },
278 { 77, NULL } /* 77 := Do not exit on "help" or "?". */
281 #define DEFAULT_MAX_REPLIES 10
282 #define DEFAULT_LDAP_TIMEOUT 100 /* arbitrary large timeout */
284 #define DEFAULT_CONNECT_TIMEOUT (15*1000) /* 15 seconds */
285 #define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000) /* 2 seconds */
287 /* For the cleanup handler we need to keep track of the socket's name. */
288 static const char *socket_name;
289 /* If the socket has been redirected, this is the name of the
290 redirected socket.. */
291 static const char *redir_socket_name;
293 /* We need to keep track of the server's nonces (these are dummies for
295 static assuan_sock_nonce_t socket_nonce;
297 /* Only if this flag has been set will we remove the socket file. */
298 static int cleanup_socket;
300 /* Keep track of the current log file so that we can avoid updating
301 the log file after a SIGHUP if it didn't changed. Malloced. */
302 static char *current_logfile;
304 /* Helper to implement --debug-level. */
305 static const char *debug_level;
307 /* Helper to set the NTBTLS or GNUTLS log level. */
308 static int opt_gnutls_debug = -1;
310 /* Flag indicating that a shutdown has been requested. */
311 static volatile int shutdown_pending;
313 /* Flags to indicate that we shall not watch our own socket. */
314 static int disable_check_own_socket;
316 /* Flag to control the Tor mode. */
318 { TOR_MODE_AUTO = 0, /* Switch to NO or YES */
319 TOR_MODE_NEVER, /* Never use Tor. */
320 TOR_MODE_NO, /* Do not use Tor */
321 TOR_MODE_YES, /* Use Tor */
322 TOR_MODE_FORCE /* Force using Tor */
326 /* Counter for the active connections. */
327 static int active_connections;
329 /* This flag is set by any network access and used by the housekeeping
330 * thread to run background network tasks. */
331 static int network_activity_seen;
333 /* A list of filenames registred with --hkp-cacert. */
334 static strlist_t hkp_cacert_filenames;
337 /* The timer tick used for housekeeping stuff. The second constant is used when a shutdown is pending. */
338 #define TIMERTICK_INTERVAL (60)
339 #define TIMERTICK_INTERVAL_SHUTDOWN (4)
341 /* How oft to run the housekeeping. */
342 #define HOUSEKEEPING_INTERVAL (600)
345 /* This union is used to avoid compiler warnings in case a pointer is
346 64 bit and an int 32 bit. We store an integer in a pointer and get
347 it back later (npth_getspecific et al.). */
357 /* The key used to store the current file descriptor in the thread
358 local storage. We use this in conjunction with the
359 log_set_pid_suffix_cb feature. */
360 #ifndef HAVE_W32_SYSTEM
361 static npth_key_t my_tlskey_current_fd;
365 static void cleanup (void);
367 static ldap_server_t parse_ldapserver_file (const char* filename);
369 static fingerprint_list_t parse_ocsp_signer (const char *string);
370 static void netactivity_action (void);
371 static void handle_connections (assuan_fd_t listen_fd);
373 /* NPth wrapper function definitions. */
374 ASSUAN_SYSTEM_NPTH_IMPL;
377 my_strusage( int level )
382 case 11: p = "@DIRMNGR@ (@GNUPG@)";
384 case 13: p = VERSION; break;
385 case 17: p = PRINTABLE_OS_NAME; break;
386 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
387 reporting address. This is so that we can change the
388 reporting address without breaking the translations. */
389 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
390 case 49: p = PACKAGE_BUGREPORT; break;
392 case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)");
394 case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n"
395 "Keyserver, CRL, and OCSP access for @GNUPG@\n");
404 /* Callback from libksba to hash a provided buffer. Our current
405 implementation does only allow SHA-1 for hashing. This may be
406 extended by mapping the name, testing for algorithm availibility
407 and adjust the length checks accordingly. */
409 my_ksba_hash_buffer (void *arg, const char *oid,
410 const void *buffer, size_t length, size_t resultsize,
411 unsigned char *result, size_t *resultlen)
415 if (oid && strcmp (oid, "1.3.14.3.2.26"))
416 return gpg_error (GPG_ERR_NOT_SUPPORTED);
418 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
419 gcry_md_hash_buffer (2, result, buffer, length);
425 /* GNUTLS log function callback. */
426 #ifdef HTTP_USE_GNUTLS
428 my_gnutls_log (int level, const char *text)
433 while (n && text[n-1] == '\n')
436 log_debug ("gnutls:L%d: %.*s\n", level, n, text);
438 #endif /*HTTP_USE_GNUTLS*/
440 /* Setup the debugging. With a LEVEL of NULL only the active debug
441 flags are propagated to the subsystems. With LEVEL set, a specific
442 set of debug flags is set; thus overriding all flags already
447 int numok = (debug_level && digitp (debug_level));
448 int numlvl = numok? atoi (debug_level) : 0;
452 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
454 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
455 opt.debug = DBG_IPC_VALUE;
456 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
457 opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE);
458 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
459 opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE
460 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
461 else if (!strcmp (debug_level, "guru") || numok)
464 /* Unless the "guru" string has been used we don't want to allow
465 hashing debugging. The rationale is that people tend to
466 select the highest debug value and would then clutter their
467 disk with debug files which may reveal confidential data. */
469 opt.debug &= ~(DBG_HASHING_VALUE);
473 log_error (_("invalid debug-level '%s' given\n"), debug_level);
474 log_info (_("valid debug levels are: %s\n"),
475 "none, basic, advanced, expert, guru");
476 opt.debug = 0; /* Reset debugging, so that prior debug
477 statements won't have an undesired effect. */
481 if (opt.debug && !opt.verbose)
484 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
486 if (opt.debug && opt.quiet)
489 if (opt.debug & DBG_CRYPTO_VALUE )
490 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
493 if (opt_gnutls_debug >= 0)
495 ntbtls_set_debug (opt_gnutls_debug, NULL, NULL);
497 #elif HTTP_USE_GNUTLS
498 if (opt_gnutls_debug >= 0)
500 gnutls_global_set_log_function (my_gnutls_log);
501 gnutls_global_set_log_level (opt_gnutls_debug);
503 #endif /*HTTP_USE_GNUTLS*/
506 parse_debug_flag (NULL, &opt.debug, debug_flags);
513 if (dirmngr_use_tor ())
515 /* Enable Tor mode and when called again force a new curcuit
516 * (e.g. on SIGHUP). */
517 enable_dns_tormode (1);
518 if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
520 log_error ("error enabling Tor mode: %s\n", strerror (errno));
521 log_info ("(is your Libassuan recent enough?)\n");
525 disable_dns_tormode ();
529 /* Return true if Tor shall be used. */
531 dirmngr_use_tor (void)
533 if (tor_mode == TOR_MODE_AUTO)
535 /* Figure out whether Tor is running. */
538 sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR);
539 if (sock == ASSUAN_INVALID_FD)
540 tor_mode = TOR_MODE_NO;
543 tor_mode = TOR_MODE_YES;
544 assuan_sock_close (sock);
548 if (tor_mode == TOR_MODE_FORCE)
549 return 2; /* Use Tor (using 2 to indicate force mode) */
550 else if (tor_mode == TOR_MODE_YES)
551 return 1; /* Use Tor */
553 return 0; /* Do not use Tor. */
558 wrong_args (const char *text)
560 es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME);
561 es_fputs (text, es_stderr);
562 es_putc ('\n', es_stderr);
567 /* Helper to stop the reaper thread for the ldap wrapper. */
569 shutdown_reaper (void)
572 ldap_wrapper_wait_connections ();
577 /* Handle options which are allowed to be reset after program start.
578 Return true if the current option in PARGS could be handled and
579 false if not. As a special feature, passing a value of NULL for
580 PARGS, resets the options to the default. REREAD should be set
581 true if it is not the initial option parsing. */
583 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
590 opt.ldap_wrapper_program = NULL;
591 opt.disable_http = 0;
592 opt.disable_ldap = 0;
593 opt.honor_http_proxy = 0;
594 opt.http_proxy = NULL;
595 opt.ldap_proxy = NULL;
596 opt.only_ldap_proxy = 0;
597 opt.ignore_http_dp = 0;
598 opt.ignore_ldap_dp = 0;
599 opt.ignore_ocsp_service_url = 0;
601 opt.allow_version_check = 0;
602 opt.ocsp_responder = NULL;
603 opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */
604 opt.ocsp_max_period = 90 * 86400; /* 90 days. */
605 opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */
606 opt.max_replies = DEFAULT_MAX_REPLIES;
607 while (opt.ocsp_signer)
609 fingerprint_list_t tmp = opt.ocsp_signer->next;
610 xfree (opt.ocsp_signer);
611 opt.ocsp_signer = tmp;
613 FREE_STRLIST (opt.ignored_cert_extensions);
614 http_register_tls_ca (NULL);
615 FREE_STRLIST (hkp_cacert_filenames);
616 FREE_STRLIST (opt.keyserver);
617 /* Note: We do not allow resetting of TOR_MODE_FORCE at runtime. */
618 if (tor_mode != TOR_MODE_FORCE)
619 tor_mode = TOR_MODE_AUTO;
620 disable_check_own_socket = 0;
621 enable_standard_resolver (0);
623 opt.connect_timeout = 0;
624 opt.connect_quick_timeout = 0;
628 switch (pargs->r_opt)
630 case oQuiet: opt.quiet = 1; break;
631 case oVerbose: opt.verbose++; break;
633 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
635 case oDebugAll: opt.debug = ~0; break;
636 case oDebugLevel: debug_level = pargs->r.ret_str; break;
637 case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break;
641 return 0; /* Not handled. */
642 if (!current_logfile || !pargs->r.ret_str
643 || strcmp (current_logfile, pargs->r.ret_str))
645 log_set_file (pargs->r.ret_str);
646 xfree (current_logfile);
647 current_logfile = xtrystrdup (pargs->r.ret_str);
651 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
653 case oLDAPWrapperProgram:
654 opt.ldap_wrapper_program = pargs->r.ret_str;
656 case oHTTPWrapperProgram:
657 opt.http_wrapper_program = pargs->r.ret_str;
660 case oDisableHTTP: opt.disable_http = 1; break;
661 case oDisableLDAP: opt.disable_ldap = 1; break;
662 case oDisableIPv4: opt.disable_ipv4 = 1; break;
663 case oDisableIPv6: opt.disable_ipv6 = 1; break;
664 case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
665 case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
666 case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
667 case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
668 case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
669 case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
670 case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
672 case oAllowOCSP: opt.allow_ocsp = 1; break;
673 case oAllowVersionCheck: opt.allow_version_check = 1; break;
674 case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
676 opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str);
678 case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
679 case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
680 case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
682 case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
686 /* We need to register the filenames with gnutls (http.c) and
687 * also for our own cert cache. */
690 /* Do tilde expansion and make path absolute. */
691 tmpname = make_absfilename (pargs->r.ret_str, NULL);
692 http_register_tls_ca (tmpname);
693 add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str);
698 case oIgnoreCertExtension:
699 add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
703 tor_mode = TOR_MODE_FORCE;
706 if (tor_mode != TOR_MODE_FORCE)
707 tor_mode = TOR_MODE_NEVER;
710 case oStandardResolver: enable_standard_resolver (1); break;
711 case oRecursiveResolver: enable_recursive_resolver (1); break;
714 if (*pargs->r.ret_str)
715 add_to_strlist (&opt.keyserver, pargs->r.ret_str);
719 set_dns_nameserver (pargs->r.ret_str);
722 case oResolverTimeout:
723 set_dns_timeout (pargs->r.ret_int);
726 case oConnectTimeout:
727 opt.connect_timeout = pargs->r.ret_ulong * 1000;
730 case oConnectQuickTimeout:
731 opt.connect_quick_timeout = pargs->r.ret_ulong * 1000;
735 return 0; /* Not handled. */
738 set_dns_verbose (opt.verbose, !!DBG_DNS);
739 http_set_verbose (opt.verbose, !!DBG_NETWORK);
740 set_dns_disable_ipv4 (opt.disable_ipv4);
741 set_dns_disable_ipv6 (opt.disable_ipv6);
743 return 1; /* Handled. */
747 /* This fucntion is called after option parsing to adjust some values
748 * and call option setup functions. */
750 post_option_parsing (void)
752 /* It would be too surpirsing if the quick timeout is larger than
753 * the standard value. */
754 if (opt.connect_quick_timeout > opt.connect_timeout)
755 opt.connect_quick_timeout = opt.connect_timeout;
762 #ifndef HAVE_W32_SYSTEM
764 pid_suffix_callback (unsigned long *r_suffix)
766 union int_and_ptr_u value;
768 memset (&value, 0, sizeof value);
769 value.aptr = npth_getspecific (my_tlskey_current_fd);
770 *r_suffix = value.aint;
771 return (*r_suffix != -1); /* Use decimal representation. */
773 #endif /*!HAVE_W32_SYSTEM*/
777 my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv)
782 log_logv_with_prefix (GPGRT_LOG_INFO, "ntbtls: ", fmt, argv);
786 snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level);
787 log_logv_with_prefix (GPGRT_LOG_DEBUG, prefix, fmt, argv);
797 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
799 /* Now with NPth running we can set the logging callback. Our
800 windows implementation does not yet feature the NPth TLS
802 #ifndef HAVE_W32_SYSTEM
803 if (npth_key_create (&my_tlskey_current_fd, NULL) == 0)
804 if (npth_setspecific (my_tlskey_current_fd, NULL) == 0)
805 log_set_pid_suffix_cb (pid_suffix_callback);
806 #endif /*!HAVE_W32_SYSTEM*/
811 main (int argc, char **argv)
813 enum cmd_and_opt_values cmd = 0;
817 FILE *configfp = NULL;
818 char *configname = NULL;
820 unsigned configlineno;
822 int default_config =1;
827 char *logfile = NULL;
829 char *ldapfile = NULL;
833 struct assuan_malloc_hooks malloc_hooks;
835 early_system_init ();
836 set_strusage (my_strusage);
837 log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
839 /* Make sure that our subsystems are ready. */
841 init_common_subsystems (&argc, &argv);
843 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
845 /* Check that the libraries are suitable. Do it here because
846 the option parsing may need services of the libraries. */
847 if (!ksba_check_version (NEED_KSBA_VERSION) )
848 log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba",
849 NEED_KSBA_VERSION, ksba_check_version (NULL) );
851 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
852 ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
854 /* Init TLS library. */
856 if (!ntbtls_check_version (NEED_NTBTLS_VERSION) )
857 log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls",
858 NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) );
859 #elif HTTP_USE_GNUTLS
860 rc = gnutls_global_init ();
862 log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));
863 #endif /*HTTP_USE_GNUTLS*/
866 malloc_hooks.malloc = gcry_malloc;
867 malloc_hooks.realloc = gcry_realloc;
868 malloc_hooks.free = gcry_free;
869 assuan_set_malloc_hooks (&malloc_hooks);
870 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
871 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
872 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
874 setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor);
876 setup_libgcrypt_logging ();
879 ntbtls_set_log_handler (my_ntbtls_log_handler, NULL);
882 /* Setup defaults. */
883 shell = getenv ("SHELL");
884 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
887 /* Reset rereadable options to default values. */
888 parse_rereadable_options (NULL, 0);
890 /* Default TCP timeouts. */
891 opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT;
892 opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT;
895 opt.add_new_ldapservers = 0;
896 opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
898 /* Other defaults. */
900 /* Check whether we have a config file given on the commandline */
905 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
906 while (arg_parse( &pargs, opts))
908 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
910 else if (pargs.r_opt == oOptions)
911 { /* Yes there is one, so we do not try the default one, but
912 read the option file when it is encountered at the
916 else if (pargs.r_opt == oNoOptions)
917 default_config = 0; /* --no-options */
918 else if (pargs.r_opt == oHomedir)
920 gnupg_set_homedir (pargs.r.ret_str);
924 socket_name = dirmngr_socket_name ();
926 configname = make_filename (gnupg_homedir (), DIRMNGR_NAME".conf", NULL );
932 pargs.flags= 1; /* do not remove the args */
937 configfp = fopen (configname, "r");
943 log_info (_("Note: no default option file '%s'\n"),
948 log_error (_("option file '%s': %s\n"),
949 configname, strerror(errno) );
955 if (parse_debug && configname )
956 log_info (_("reading options from '%s'\n"), configname );
960 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
962 if (parse_rereadable_options (&pargs, 0))
963 continue; /* Already handled */
979 case oQuiet: opt.quiet = 1; break;
980 case oVerbose: opt.verbose++; break;
981 case oBatch: opt.batch=1; break;
983 case oDebugWait: debug_wait = pargs.r.ret_int; break;
986 /* Config files may not be nested (silently ignore them) */
990 configname = xstrdup(pargs.r.ret_str);
994 case oNoGreeting: nogreeting = 1; break;
995 case oNoVerbose: opt.verbose = 0; break;
996 case oNoOptions: break; /* no-options */
997 case oHomedir: /* Ignore this option here. */; break;
998 case oNoDetach: nodetach = 1; break;
999 case oLogFile: logfile = pargs.r.ret_str; break;
1000 case oCsh: csh_style = 1; break;
1001 case oSh: csh_style = 0; break;
1004 ldapfile = pargs.r.ret_str;
1005 # endif /*USE_LDAP*/
1007 case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
1009 opt.ldaptimeout = pargs.r.ret_int;
1012 case oFakedSystemTime:
1013 gnupg_set_time ((time_t)pargs.r.ret_ulong, 0);
1016 case oForce: opt.force = 1; break;
1018 case oSocketName: socket_name = pargs.r.ret_str; break;
1020 default : pargs.err = configfp? 1:2; break;
1027 /* Keep a copy of the name so that it can be read on SIGHUP. */
1028 opt.config_filename = configname;
1034 if (log_get_errorcount(0))
1039 if (!opt.homedir_cache)
1040 opt.homedir_cache = xstrdup (gnupg_homedir ());
1044 es_fprintf (es_stderr, "%s %s; %s\n",
1045 strusage(11), strusage(13), strusage(14) );
1046 es_fprintf (es_stderr, "%s\n", strusage(15) );
1049 #ifdef IS_DEVELOPMENT_VERSION
1050 log_info ("NOTE: this is a development version!\n");
1053 /* Print a warning if an argument looks like an option. */
1054 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1058 for (i=0; i < argc; i++)
1059 if (argv[i][0] == '-' && argv[i][1] == '-')
1060 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1063 if (!access ("/etc/"DIRMNGR_NAME, F_OK)
1064 && !strncmp (gnupg_homedir (), "/etc/", 5))
1066 ("NOTE: DirMngr is now a proper part of %s. The configuration and"
1067 " other directory names changed. Please check that no other version"
1068 " of dirmngr is still installed. To disable this warning, remove the"
1069 " directory '/etc/dirmngr'.\n", GNUPG_NAME);
1071 if (gnupg_faked_time_p ())
1073 gnupg_isotime_t tbuf;
1075 log_info (_("WARNING: running with faked system time: "));
1076 gnupg_get_isotime (tbuf);
1077 dump_isotime (tbuf);
1081 post_option_parsing ();
1083 /* Get LDAP server list from file. */
1087 ldapfile = make_filename (gnupg_homedir (),
1088 "dirmngr_ldapservers.conf",
1090 opt.ldapservers = parse_ldapserver_file (ldapfile);
1094 opt.ldapservers = parse_ldapserver_file (ldapfile);
1097 #ifndef HAVE_W32_SYSTEM
1098 /* We need to ignore the PIPE signal because the we might log to a
1099 socket and that code handles EPIPE properly. The ldap wrapper
1100 also requires us to ignore this silly signal. Assuan would set
1101 this signal to ignore anyway.*/
1102 signal (SIGPIPE, SIG_IGN);
1105 /* Ready. Now to our duties. */
1112 /* Note that this server mode is mainly useful for debugging. */
1114 wrong_args ("--server");
1118 log_set_file (logfile);
1119 log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1124 log_debug ("waiting for debugger - my pid is %u .....\n",
1125 (unsigned int)getpid());
1126 gnupg_sleep (debug_wait);
1127 log_debug ("... okay\n");
1132 cert_cache_init (hkp_cacert_filenames);
1134 http_register_netactivity_cb (netactivity_action);
1135 start_command_handler (ASSUAN_INVALID_FD);
1138 #ifndef HAVE_W32_SYSTEM
1139 else if (cmd == aSupervised)
1141 /* In supervised mode, we expect file descriptor 3 to be an
1142 already opened, listening socket.
1144 We will also not detach from the controlling process or close
1145 stderr; the supervisor should handle all of that. */
1146 struct stat statbuf;
1147 if (fstat (3, &statbuf) == -1 && errno == EBADF)
1149 log_error ("file descriptor 3 must be validin --supervised mode\n");
1152 socket_name = gnupg_get_socket_name (3);
1154 /* Now start with logging to a file if this is desired. */
1157 log_set_file (logfile);
1158 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1159 |GPGRT_LOG_WITH_TIME
1160 |GPGRT_LOG_WITH_PID));
1161 current_logfile = xstrdup (logfile);
1164 log_set_prefix (NULL, 0);
1167 cert_cache_init (hkp_cacert_filenames);
1169 http_register_netactivity_cb (netactivity_action);
1170 handle_connections (3);
1173 #endif /*HAVE_W32_SYSTEM*/
1174 else if (cmd == aDaemon)
1179 struct sockaddr_un serv_addr;
1182 wrong_args ("--daemon");
1184 /* Now start with logging to a file if this is desired. */
1187 log_set_file (logfile);
1188 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1189 |GPGRT_LOG_WITH_TIME
1190 |GPGRT_LOG_WITH_PID));
1191 current_logfile = xstrdup (logfile);
1194 #ifndef HAVE_W32_SYSTEM
1195 if (strchr (socket_name, ':'))
1197 log_error (_("colons are not allowed in the socket name\n"));
1201 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1202 if (fd == ASSUAN_INVALID_FD)
1204 log_error (_("can't create socket: %s\n"), strerror (errno));
1212 if (assuan_sock_set_sockaddr_un (socket_name,
1213 (struct sockaddr*)&serv_addr,
1216 if (errno == ENAMETOOLONG)
1217 log_error (_("socket name '%s' is too long\n"), socket_name);
1219 log_error ("error preparing socket '%s': %s\n",
1221 gpg_strerror (gpg_error_from_syserror ()));
1226 redir_socket_name = xstrdup (serv_addr.sun_path);
1228 log_info ("redirecting socket '%s' to '%s'\n",
1229 socket_name, redir_socket_name);
1233 len = SUN_LEN (&serv_addr);
1235 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1237 && (errno == EADDRINUSE
1238 #ifdef HAVE_W32_SYSTEM
1243 /* Fixme: We should test whether a dirmngr is already running. */
1244 gnupg_remove (redir_socket_name? redir_socket_name : socket_name);
1245 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1248 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
1249 log_error (_("error getting nonce for the socket\n"));
1252 log_error (_("error binding socket to '%s': %s\n"),
1254 gpg_strerror (gpg_error_from_errno (errno)));
1255 assuan_sock_close (fd);
1260 if (gnupg_chmod (serv_addr.sun_path, "-rwx"))
1261 log_error (_("can't set permissions of '%s': %s\n"),
1262 serv_addr.sun_path, strerror (errno));
1264 if (listen (FD2INT (fd), 5) == -1)
1266 log_error (_("listen() failed: %s\n"), strerror (errno));
1267 assuan_sock_close (fd);
1272 log_info (_("listening on socket '%s'\n"), serv_addr.sun_path);
1276 /* Note: We keep the dirmngr_info output only for the sake of
1277 existing scripts which might use this to detect a successful
1278 start of the dirmngr. */
1279 #ifdef HAVE_W32_SYSTEM
1284 es_printf ("set %s=%s;%lu;1\n",
1285 DIRMNGR_INFO_NAME, socket_name, (ulong) pid);
1288 if (pid == (pid_t)-1)
1290 log_fatal (_("error forking process: %s\n"), strerror (errno));
1295 { /* We are the parent */
1298 /* Don't let cleanup() remove the socket - the child is
1299 responsible for doing that. */
1304 /* Create the info string: <name>:<pid>:<protocol_version> */
1305 if (asprintf (&infostr, "%s=%s:%lu:1",
1306 DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0)
1308 log_error (_("out of core\n"));
1309 kill (pid, SIGTERM);
1312 /* Print the environment string, so that the caller can use
1313 shell's eval to set it. But see above. */
1316 *strchr (infostr, '=') = ' ';
1317 es_printf ( "setenv %s;\n", infostr);
1321 es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME);
1333 /* Detach from tty and put process into a new session */
1337 unsigned int oldflags;
1339 /* Close stdin, stdout and stderr unless it is the log stream */
1340 for (i=0; i <= 2; i++)
1342 if (!log_test_fd (i) && i != fd )
1345 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1347 log_error ("failed to open '%s': %s\n",
1348 "/dev/null", strerror (errno));
1357 log_error ("setsid() failed: %s\n", strerror(errno) );
1361 log_get_prefix (&oldflags);
1362 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1363 opt.running_detached = 1;
1370 if (gnupg_chdir (gnupg_daemon_rootdir ()))
1372 log_error ("chdir to '%s' failed: %s\n",
1373 gnupg_daemon_rootdir (), strerror (errno));
1379 cert_cache_init (hkp_cacert_filenames);
1381 http_register_netactivity_cb (netactivity_action);
1382 handle_connections (fd);
1385 else if (cmd == aListCRLs)
1387 /* Just list the CRL cache and exit. */
1389 wrong_args ("--list-crls");
1391 crl_cache_list (es_stdout);
1393 else if (cmd == aLoadCRL)
1395 struct server_control_s ctrlbuf;
1397 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1398 dirmngr_init_default_ctrl (&ctrlbuf);
1401 cert_cache_init (hkp_cacert_filenames);
1404 rc = crl_cache_load (&ctrlbuf, NULL);
1407 for (; !rc && argc; argc--, argv++)
1408 rc = crl_cache_load (&ctrlbuf, *argv);
1410 dirmngr_deinit_default_ctrl (&ctrlbuf);
1412 else if (cmd == aFetchCRL)
1414 ksba_reader_t reader;
1415 struct server_control_s ctrlbuf;
1418 wrong_args ("--fetch-crl URL");
1420 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1421 dirmngr_init_default_ctrl (&ctrlbuf);
1424 cert_cache_init (hkp_cacert_filenames);
1426 rc = crl_fetch (&ctrlbuf, argv[0], &reader);
1428 log_error (_("fetching CRL from '%s' failed: %s\n"),
1429 argv[0], gpg_strerror (rc));
1432 rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
1434 log_error (_("processing CRL from '%s' failed: %s\n"),
1435 argv[0], gpg_strerror (rc));
1436 crl_close_reader (reader);
1438 dirmngr_deinit_default_ctrl (&ctrlbuf);
1440 else if (cmd == aFlush)
1442 /* Delete cache and exit. */
1444 wrong_args ("--flush");
1445 rc = crl_cache_flush();
1447 else if (cmd == aGPGConfTest)
1449 else if (cmd == aGPGConfList)
1451 unsigned long flags = 0;
1455 /* First the configuration file. This is not an option, but it
1456 is vital information for GPG Conf. */
1457 if (!opt.config_filename)
1458 opt.config_filename = make_filename (gnupg_homedir (),
1459 "dirmngr.conf", NULL );
1461 filename = percent_escape (opt.config_filename, NULL);
1462 es_printf ("gpgconf-dirmngr.conf:%lu:\"%s\n",
1463 GC_OPT_FLAG_DEFAULT, filename);
1466 es_printf ("verbose:%lu:\n", flags | GC_OPT_FLAG_NONE);
1467 es_printf ("quiet:%lu:\n", flags | GC_OPT_FLAG_NONE);
1468 es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
1469 es_printf ("log-file:%lu:\n", flags | GC_OPT_FLAG_NONE);
1470 es_printf ("force:%lu:\n", flags | GC_OPT_FLAG_NONE);
1472 /* --csh and --sh are mutually exclusive, something we can not
1473 express in GPG Conf. --options is only usable from the
1474 command line, really. --debug-all interacts with --debug,
1475 and having both of them is thus problematic. --no-detach is
1476 also only usable on the command line. --batch is unused. */
1478 filename = make_filename (gnupg_homedir (),
1479 "dirmngr_ldapservers.conf",
1481 filename_esc = percent_escape (filename, NULL);
1482 es_printf ("ldapserverlist-file:%lu:\"%s\n", flags | GC_OPT_FLAG_DEFAULT,
1484 xfree (filename_esc);
1487 es_printf ("ldaptimeout:%lu:%u\n",
1488 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
1489 es_printf ("max-replies:%lu:%u\n",
1490 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
1491 es_printf ("allow-ocsp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1492 es_printf ("allow-version-check:%lu:\n", flags | GC_OPT_FLAG_NONE);
1493 es_printf ("ocsp-responder:%lu:\n", flags | GC_OPT_FLAG_NONE);
1494 es_printf ("ocsp-signer:%lu:\n", flags | GC_OPT_FLAG_NONE);
1496 es_printf ("faked-system-time:%lu:\n", flags | GC_OPT_FLAG_NONE);
1497 es_printf ("no-greeting:%lu:\n", flags | GC_OPT_FLAG_NONE);
1499 es_printf ("disable-http:%lu:\n", flags | GC_OPT_FLAG_NONE);
1500 es_printf ("disable-ldap:%lu:\n", flags | GC_OPT_FLAG_NONE);
1501 es_printf ("honor-http-proxy:%lu\n", flags | GC_OPT_FLAG_NONE);
1502 es_printf ("http-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1503 es_printf ("ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1504 es_printf ("only-ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1505 es_printf ("ignore-ldap-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1506 es_printf ("ignore-http-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1507 es_printf ("ignore-ocsp-service-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1508 /* Note: The next one is to fix a typo in gpgconf - should be
1509 removed eventually. */
1510 es_printf ("ignore-ocsp-servic-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1512 es_printf ("use-tor:%lu:\n", flags | GC_OPT_FLAG_NONE);
1514 filename_esc = percent_escape (get_default_keyserver (0), NULL);
1515 es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT,
1517 xfree (filename_esc);
1520 es_printf ("nameserver:%lu:\n", flags | GC_OPT_FLAG_NONE);
1521 es_printf ("resolver-timeout:%lu:%u\n",
1522 flags | GC_OPT_FLAG_DEFAULT, 0);
1532 crl_cache_deinit ();
1533 cert_cache_deinit (1);
1534 reload_dns_stuff (1);
1537 ldapserver_list_free (opt.ldapservers);
1539 opt.ldapservers = NULL;
1544 if (redir_socket_name)
1545 gnupg_remove (redir_socket_name);
1546 else if (socket_name && *socket_name)
1547 gnupg_remove (socket_name);
1553 dirmngr_exit (int rc)
1561 dirmngr_init_default_ctrl (ctrl_t ctrl)
1563 ctrl->magic = SERVER_CONTROL_MAGIC;
1565 ctrl->http_proxy = xstrdup (opt.http_proxy);
1566 ctrl->http_no_crl = 1;
1567 ctrl->timeout = opt.connect_timeout;
1572 dirmngr_deinit_default_ctrl (ctrl_t ctrl)
1576 ctrl->magic = 0xdeadbeef;
1578 xfree (ctrl->http_proxy);
1579 ctrl->http_proxy = NULL;
1583 /* Create a list of LDAP servers from the file FILENAME. Returns the
1584 list or NULL in case of errors.
1586 The format fo such a file is line oriented where empty lines and
1587 lines starting with a hash mark are ignored. All other lines are
1588 assumed to be colon seprated with these fields:
1591 2. field: Portnumber
1598 static ldap_server_t
1599 parse_ldapserver_file (const char* filename)
1603 ldap_server_t server, serverstart, *serverend;
1605 unsigned int lineno = 0;
1608 fp = es_fopen (filename, "r");
1611 log_error (_("error opening '%s': %s\n"), filename, strerror (errno));
1616 serverend = &serverstart;
1617 while (es_fgets (buffer, sizeof buffer, fp))
1620 if (!*buffer || buffer[strlen(buffer)-1] != '\n')
1622 if (*buffer && es_feof (fp))
1623 ; /* Last line not terminated - continue. */
1626 log_error (_("%s:%u: line too long - skipped\n"),
1628 while ( (c=es_fgetc (fp)) != EOF && c != '\n')
1629 ; /* Skip until end of line. */
1633 /* Skip empty and comment lines.*/
1634 for (p=buffer; spacep (p); p++)
1636 if (!*p || *p == '\n' || *p == '#')
1639 /* Parse the colon separated fields. */
1640 server = ldapserver_parse_one (buffer, filename, lineno);
1643 *serverend = server;
1644 serverend = &server->next;
1649 log_error (_("error reading '%s': %s\n"), filename, strerror (errno));
1656 static fingerprint_list_t
1657 parse_ocsp_signer (const char *string)
1664 fingerprint_list_t list, *list_tail, item;
1665 unsigned int lnr = 0;
1670 /* Check whether this is not a filename and treat it as a direct
1671 fingerprint specification. */
1672 if (!strpbrk (string, "/.~\\"))
1674 item = xcalloc (1, sizeof *item);
1675 for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
1676 if ( string[i] != ':' )
1677 item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
1678 item->hexfpr[j] = 0;
1679 if (j != 40 || !(spacep (string+i) || !string[i]))
1681 log_error (_("%s:%u: invalid fingerprint detected\n"),
1682 "--ocsp-signer", 0);
1689 /* Well, it is a filename. */
1690 if (*string == '/' || (*string == '~' && string[1] == '/'))
1691 fname = make_filename (string, NULL);
1694 if (string[0] == '.' && string[1] == '/' )
1696 fname = make_filename (gnupg_homedir (), string, NULL);
1699 fp = es_fopen (fname, "r");
1702 err = gpg_error_from_syserror ();
1703 log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
1712 if (!es_fgets (line, DIM(line)-1, fp) )
1716 err = gpg_error_from_syserror ();
1717 log_error (_("%s:%u: read error: %s\n"),
1718 fname, lnr, gpg_strerror (err));
1726 fingerprint_list_t tmp = list->next;
1732 return list; /* Ready. */
1736 if (!*line || line[strlen(line)-1] != '\n')
1738 /* Eat until end of line. */
1739 while ( (c=es_getc (fp)) != EOF && c != '\n')
1741 err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
1742 /* */: GPG_ERR_INCOMPLETE_LINE);
1743 log_error (_("%s:%u: read error: %s\n"),
1744 fname, lnr, gpg_strerror (err));
1749 /* Allow for empty lines and spaces */
1750 for (p=line; spacep (p); p++)
1752 if (!*p || *p == '\n' || *p == '#')
1755 item = xcalloc (1, sizeof *item);
1757 list_tail = &item->next;
1759 for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
1761 item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
1762 item->hexfpr[j] = 0;
1763 if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
1765 log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
1769 while (spacep (p+i))
1771 if (p[i] && p[i] != '\n')
1772 log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
1781 Stuff used in daemon mode.
1786 /* Reread parts of the configuration. Note, that this function is
1787 obviously not thread-safe and should only be called from the NPTH
1790 Fixme: Due to the way the argument parsing works, we create a
1791 memory leak here for all string type arguments. There is currently
1792 no clean way to tell whether the memory for the argument has been
1793 allocated or points into the process' original arguments. Unless
1794 we have a mechanism to tell this, we need to live on with this. */
1796 reread_configuration (void)
1798 ARGPARSE_ARGS pargs;
1800 unsigned int configlineno = 0;
1803 if (!opt.config_filename)
1804 return; /* No config file. */
1806 fp = fopen (opt.config_filename, "r");
1809 log_error (_("option file '%s': %s\n"),
1810 opt.config_filename, strerror(errno) );
1814 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1816 memset (&pargs, 0, sizeof pargs);
1818 pargs.argc = &dummy;
1819 pargs.flags = 1; /* do not remove the args */
1820 while (optfile_parse (fp, opt.config_filename, &configlineno, &pargs, opts) )
1822 if (pargs.r_opt < -1)
1823 pargs.err = 1; /* Print a warning. */
1824 else /* Try to parse this option - ignore unchangeable ones. */
1825 parse_rereadable_options (&pargs, 1);
1829 post_option_parsing ();
1833 /* A global function which allows us to trigger the reload stuff from
1836 dirmngr_sighup_action (void)
1838 log_info (_("SIGHUP received - "
1839 "re-reading configuration and flushing caches\n"));
1840 reread_configuration ();
1841 cert_cache_deinit (0);
1842 crl_cache_deinit ();
1843 cert_cache_init (hkp_cacert_filenames);
1845 reload_dns_stuff (0);
1850 /* This function is called if some network activity was done. At this
1851 * point we know the we have a network and we can decide whether to
1852 * run scheduled background tasks soon. The function should return
1853 * quickly and only trigger actions for another thread. */
1855 netactivity_action (void)
1857 network_activity_seen = 1;
1861 /* The signal handler. */
1862 #ifndef HAVE_W32_SYSTEM
1864 handle_signal (int signo)
1869 dirmngr_sighup_action ();
1873 cert_cache_print_stats ();
1877 log_info (_("SIGUSR2 received - no action defined\n"));
1881 if (!shutdown_pending)
1882 log_info (_("SIGTERM received - shutting down ...\n"));
1884 log_info (_("SIGTERM received - still %d active connections\n"),
1885 active_connections);
1887 if (shutdown_pending > 2)
1889 log_info (_("shutdown forced\n"));
1890 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1897 log_info (_("SIGINT received - immediate shutdown\n"));
1898 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1904 log_info (_("signal %d received - no action defined\n"), signo);
1907 #endif /*!HAVE_W32_SYSTEM*/
1910 /* Thread to do the housekeeping. */
1912 housekeeping_thread (void *arg)
1914 static int sentinel;
1916 struct server_control_s ctrlbuf;
1920 curtime = gnupg_get_time ();
1923 log_info ("housekeeping is already going on\n");
1927 if (opt.verbose > 1)
1928 log_info ("starting housekeeping\n");
1930 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1931 dirmngr_init_default_ctrl (&ctrlbuf);
1933 ks_hkp_housekeeping (curtime);
1934 if (network_activity_seen)
1936 network_activity_seen = 0;
1937 if (opt.allow_version_check)
1938 dirmngr_load_swdb (&ctrlbuf, 0);
1941 dirmngr_deinit_default_ctrl (&ctrlbuf);
1943 if (opt.verbose > 1)
1944 log_info ("ready with housekeeping\n");
1951 #if GPGRT_GCC_HAVE_PUSH_PRAGMA
1952 # pragma GCC push_options
1953 # pragma GCC optimize ("no-strict-overflow")
1956 time_for_housekeeping_p (time_t curtime)
1958 static time_t last_housekeeping;
1960 if (!last_housekeeping)
1961 last_housekeeping = curtime;
1963 if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime
1964 || last_housekeeping > curtime /*(be prepared for y2038)*/)
1966 last_housekeeping = curtime;
1971 #if GPGRT_GCC_HAVE_PUSH_PRAGMA
1972 # pragma GCC pop_options
1976 /* This is the worker for the ticker. It is called every few seconds
1977 and may only do fast operations. */
1981 struct stat statbuf;
1983 if (time_for_housekeeping_p (gnupg_get_time ()))
1989 err = npth_attr_init (&tattr);
1991 log_error ("error preparing housekeeping thread: %s\n", strerror (err));
1994 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
1995 err = npth_create (&thread, &tattr, housekeeping_thread, NULL);
1997 log_error ("error spawning housekeeping thread: %s\n",
1999 npth_attr_destroy (&tattr);
2003 /* Check whether the homedir is still available. */
2004 if (!shutdown_pending
2005 && stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
2007 shutdown_pending = 1;
2008 log_info ("homedir has been removed - shutting down\n");
2013 /* Check the nonce on a new connection. This is a NOP unless we are
2014 using our Unix domain socket emulation under Windows. */
2016 check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
2018 if (assuan_sock_check_nonce (fd, nonce))
2020 log_info (_("error reading nonce on fd %d: %s\n"),
2021 FD2INT (fd), strerror (errno));
2022 assuan_sock_close (fd);
2030 /* Helper to call a connection's main function. */
2032 start_connection_thread (void *arg)
2034 union int_and_ptr_u argval;
2037 memset (&argval, 0, sizeof argval);
2041 if (check_nonce (fd, &socket_nonce))
2043 log_error ("handler nonce check FAILED\n");
2047 #ifndef HAVE_W32_SYSTEM
2048 npth_setspecific (my_tlskey_current_fd, argval.aptr);
2051 active_connections++;
2053 log_info (_("handler for fd %d started\n"), FD2INT (fd));
2055 start_command_handler (fd);
2058 log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
2059 active_connections--;
2061 #ifndef HAVE_W32_SYSTEM
2062 argval.afd = ASSUAN_INVALID_FD;
2063 npth_setspecific (my_tlskey_current_fd, argval.aptr);
2070 #ifdef HAVE_INOTIFY_INIT
2071 /* Read an inotify event and return true if it matches NAME. */
2073 my_inotify_is_name (int fd, const char *name)
2076 struct inotify_event ev;
2077 char _buf[sizeof (struct inotify_event) + 100 + 1];
2082 s = strrchr (name, '/');
2086 n = npth_read (fd, &buf, sizeof buf);
2087 if (n < sizeof (struct inotify_event))
2089 if (buf.ev.len < strlen (name)+1)
2091 if (strcmp (buf.ev.name, name))
2092 return 0; /* Not the desired file. */
2094 return 1; /* Found. */
2096 #endif /*HAVE_INOTIFY_INIT*/
2099 /* Main loop in daemon mode. Note that LISTEN_FD will be owned by
2102 handle_connections (assuan_fd_t listen_fd)
2105 #ifndef HAVE_W32_SYSTEM
2108 struct sockaddr_un paddr;
2109 socklen_t plen = sizeof( paddr );
2111 fd_set fdset, read_fdset;
2112 struct timespec abstime;
2113 struct timespec curtime;
2114 struct timespec timeout;
2116 int my_inotify_fd = -1;
2118 npth_attr_init (&tattr);
2119 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2121 #ifndef HAVE_W32_SYSTEM /* FIXME */
2123 npth_sigev_add (SIGHUP);
2124 npth_sigev_add (SIGUSR1);
2125 npth_sigev_add (SIGUSR2);
2126 npth_sigev_add (SIGINT);
2127 npth_sigev_add (SIGTERM);
2131 #ifdef HAVE_INOTIFY_INIT
2132 if (disable_check_own_socket)
2134 else if ((my_inotify_fd = inotify_init ()) == -1)
2135 log_info ("error enabling fast daemon termination: %s\n",
2139 /* We need to watch the directory for the file because there
2140 * won't be an IN_DELETE_SELF for a socket file. */
2141 char *slash = strrchr (socket_name, '/');
2142 log_assert (slash && slash[1]);
2144 if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1)
2146 close (my_inotify_fd);
2151 #endif /*HAVE_INOTIFY_INIT*/
2154 /* Setup the fdset. It has only one member. This is because we use
2155 pth_select instead of pth_accept to properly sync timeouts with
2158 FD_SET (FD2INT (listen_fd), &fdset);
2159 nfd = FD2INT (listen_fd);
2160 if (my_inotify_fd != -1)
2162 FD_SET (my_inotify_fd, &fdset);
2163 if (my_inotify_fd > nfd)
2164 nfd = my_inotify_fd;
2167 npth_clock_gettime (&abstime);
2168 abstime.tv_sec += TIMERTICK_INTERVAL;
2173 /* Shutdown test. */
2174 if (shutdown_pending)
2176 if (!active_connections)
2179 /* Do not accept new connections but keep on running the
2180 * loop to cope with the timer events.
2182 * Note that we do not close the listening socket because a
2183 * client trying to connect to that socket would instead
2184 * restart a new dirmngr instance - which is unlikely the
2185 * intention of a shutdown. */
2186 /* assuan_sock_close (listen_fd); */
2187 /* listen_fd = -1; */
2190 if (my_inotify_fd != -1)
2192 FD_SET (my_inotify_fd, &fdset);
2193 nfd = my_inotify_fd;
2197 /* Take a copy of the fdset. */
2200 npth_clock_gettime (&curtime);
2201 if (!(npth_timercmp (&curtime, &abstime, <)))
2203 /* Timeout. When a shutdown is pending we use a shorter
2204 * interval to handle the shutdown more quickly. */
2206 npth_clock_gettime (&abstime);
2207 abstime.tv_sec += (shutdown_pending
2208 ? TIMERTICK_INTERVAL_SHUTDOWN
2209 : TIMERTICK_INTERVAL);
2211 npth_timersub (&abstime, &curtime, &timeout);
2213 #ifndef HAVE_W32_SYSTEM
2214 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask());
2215 saved_errno = errno;
2217 while (npth_sigev_get_pending(&signo))
2218 handle_signal (signo);
2220 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
2221 saved_errno = errno;
2224 if (ret == -1 && saved_errno != EINTR)
2226 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2227 strerror (saved_errno));
2234 /* Interrupt or timeout. Will be handled when calculating the
2239 if (shutdown_pending)
2241 /* Do not anymore accept connections. */
2245 #ifdef HAVE_INOTIFY_INIT
2246 if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset)
2247 && my_inotify_is_name (my_inotify_fd, socket_name))
2249 shutdown_pending = 1;
2250 log_info ("socket file has been removed - shutting down\n");
2252 #endif /*HAVE_INOTIFY_INIT*/
2254 if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
2258 plen = sizeof paddr;
2259 fd = INT2FD (npth_accept (FD2INT(listen_fd),
2260 (struct sockaddr *)&paddr, &plen));
2261 if (fd == GNUPG_INVALID_FD)
2263 log_error ("accept failed: %s\n", strerror (errno));
2267 char threadname[50];
2268 union int_and_ptr_u argval;
2271 memset (&argval, 0, sizeof argval);
2273 snprintf (threadname, sizeof threadname,
2274 "conn fd=%d", FD2INT(fd));
2276 ret = npth_create (&thread, &tattr,
2277 start_connection_thread, argval.aptr);
2280 log_error ("error spawning connection handler: %s\n",
2282 assuan_sock_close (fd);
2284 npth_setname_np (thread, threadname);
2289 #ifdef HAVE_INOTIFY_INIT
2290 if (my_inotify_fd != -1)
2291 close (my_inotify_fd);
2292 #endif /*HAVE_INOTIFY_INIT*/
2293 npth_attr_destroy (&tattr);
2294 if (listen_fd != GNUPG_INVALID_FD)
2295 assuan_sock_close (listen_fd);
2297 log_info ("%s %s stopped\n", strusage(11), strusage(13));
2301 dirmngr_get_current_socket_name (void)
2306 return dirmngr_socket_name ();