1 /* dirmngr.c - Keyserver and X.509 LDAP access
2 * Copyright (C) 2002 Klarälvdalens Datakonsult AB
3 * Copyright (C) 2003-2004, 2006-2007, 2008, 2010-2011, 2020 g10 Code GmbH
4 * Copyright (C) 2014 Werner Koch
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/>.
20 * SPDX-License-Identifier: GPL-3.0-or-later
34 #ifndef HAVE_W32_SYSTEM
35 #include <sys/socket.h>
43 #ifdef HAVE_INOTIFY_INIT
44 # include <sys/inotify.h>
45 #endif /*HAVE_INOTIFY_INIT*/
48 #include "dirmngr-err.h"
53 # include <gnutls/gnutls.h>
54 #endif /*HTTP_USE_GNUTLS*/
57 #define INCLUDED_BY_MAIN_MODULE 1
58 #define GNUPG_COMMON_NEED_AFLOCAL
63 #include "certcache.h"
68 # include "ldapserver.h"
70 #include "../common/asshelp.h"
72 # include "ldap-wrapper.h"
74 #include "../common/comopt.h"
75 #include "../common/init.h"
76 #include "../common/gc-opt-flags.h"
77 #include "dns-stuff.h"
78 #include "http-common.h"
81 # define ENAMETOOLONG EINVAL
85 enum cmd_and_opt_values {
148 oIgnoreCertExtension,
153 oDisableCheckOwnSocket,
158 oConnectQuickTimeout,
165 static gpgrt_opt_t opts[] = {
167 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
168 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
169 ARGPARSE_c (aGPGConfVersions, "gpgconf-versions", "@"),
171 ARGPARSE_group (300, N_("@Commands:\n ")),
173 ARGPARSE_c (aServer, "server", N_("run in server mode (foreground)") ),
174 ARGPARSE_c (aDaemon, "daemon", N_("run in daemon mode (background)") ),
175 #ifndef HAVE_W32_SYSTEM
176 ARGPARSE_c (aSupervised, "supervised", N_("run in supervised mode")),
178 ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")),
179 ARGPARSE_c (aLoadCRL, "load-crl", N_("|FILE|load CRL from FILE into cache")),
180 ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")),
181 ARGPARSE_c (aShutdown, "shutdown", N_("shutdown the dirmngr")),
182 ARGPARSE_c (aFlush, "flush", N_("flush the cache")),
185 ARGPARSE_header (NULL, N_("Options used for startup")),
187 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
188 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
189 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
190 ARGPARSE_s_n (oStealSocket, "steal-socket", "@"),
191 ARGPARSE_s_s (oHomedir, "homedir", "@"),
192 ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")),
193 ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
196 ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
198 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
199 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
200 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
201 ARGPARSE_s_s (oDebugLevel, "debug-level",
202 N_("|LEVEL|set the debugging level to LEVEL")),
203 ARGPARSE_s_s (oDebug, "debug", "@"),
204 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
205 ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"),
206 ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"),
207 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
208 ARGPARSE_s_s (oLogFile, "log-file",
209 N_("|FILE|write server mode logs to FILE")),
212 ARGPARSE_header ("Configuration",
213 N_("Options controlling the configuration")),
215 ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check",
216 N_("allow online software version check")),
217 ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
218 ARGPARSE_s_i (oMaxReplies, "max-replies",
219 N_("|N|do not return more than N items in one query")),
220 ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/
221 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
222 ARGPARSE_s_s (oIgnoreCert,"ignore-cert", "@"),
223 ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"),
226 ARGPARSE_header ("Network", N_("Network related options")),
228 ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")),
229 ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"),
230 ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"),
231 ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"),
232 ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"),
233 ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"),
234 ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"),
235 ARGPARSE_s_s (oNameServer, "nameserver", "@"),
236 ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"),
237 ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"),
240 ARGPARSE_header ("Keyserver", N_("Configuration for Keyservers")),
242 ARGPARSE_s_s (oKeyServer, "keyserver",
243 N_("|URL|use keyserver at URL")),
244 ARGPARSE_s_s (oHkpCaCert, "hkp-cacert",
245 N_("|FILE|use the CA certificates in FILE for HKP over TLS")),
247 ARGPARSE_header ("HTTP", N_("Configuration for HTTP servers")),
249 ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")),
250 ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp",
251 N_("ignore HTTP CRL distribution points")),
252 ARGPARSE_s_s (oHTTPProxy, "http-proxy",
253 N_("|URL|redirect all HTTP requests to URL")),
254 ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy",
255 N_("use system's HTTP proxy setting")),
256 ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"),
259 ARGPARSE_header ("LDAP", N_("Configuration of LDAP servers to use")),
261 ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")),
262 ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp",
263 N_("ignore LDAP CRL distribution points")),
264 ARGPARSE_s_s (oLDAPProxy, "ldap-proxy",
265 N_("|HOST|use HOST for LDAP queries")),
266 ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy",
267 N_("do not use fallback hosts with --ldap-proxy")),
268 ARGPARSE_s_s (oLDAPServer, "ldapserver",
269 N_("|SPEC|use this keyserver to lookup keys")),
270 ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file",
271 N_("|FILE|read LDAP server list from FILE")),
272 ARGPARSE_s_n (oLDAPAddServers, "add-servers",
273 N_("add new servers discovered in CRL distribution"
274 " points to serverlist")),
275 ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout",
276 N_("|N|set LDAP timeout to N seconds")),
279 ARGPARSE_header ("OCSP", N_("Configuration for OCSP")),
281 ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")),
282 ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url",
283 N_("ignore certificate contained OCSP service URLs")),
284 ARGPARSE_s_s (oOCSPResponder, "ocsp-responder",
285 N_("|URL|use OCSP responder at URL")),
286 ARGPARSE_s_s (oOCSPSigner, "ocsp-signer",
287 N_("|FPR|OCSP response signed by FPR")),
288 ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"),
289 ARGPARSE_s_i (oOCSPMaxPeriod, "ocsp-max-period", "@"),
290 ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"),
293 ARGPARSE_header (NULL, N_("Other options")),
295 ARGPARSE_s_n (oForce, "force", N_("force loading of outdated CRLs")),
296 ARGPARSE_s_s (oSocketName, "socket-name", "@"), /* Only for debugging. */
299 ARGPARSE_header (NULL, ""), /* Stop the header group. */
301 /* Not yet used options. */
302 ARGPARSE_s_n (oBatch, "batch", "@"),
303 ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"),
306 ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing "
307 "of all commands and options)\n")),
312 /* The list of supported debug flags. */
313 static struct debug_flags_s debug_flags [] =
315 { DBG_X509_VALUE , "x509" },
316 { DBG_CRYPTO_VALUE , "crypto" },
317 { DBG_MEMORY_VALUE , "memory" },
318 { DBG_CACHE_VALUE , "cache" },
319 { DBG_MEMSTAT_VALUE, "memstat" },
320 { DBG_HASHING_VALUE, "hashing" },
321 { DBG_IPC_VALUE , "ipc" },
322 { DBG_DNS_VALUE , "dns" },
323 { DBG_NETWORK_VALUE, "network" },
324 { DBG_LOOKUP_VALUE , "lookup" },
325 { DBG_EXTPROG_VALUE, "extprog" },
326 { 77, NULL } /* 77 := Do not exit on "help" or "?". */
329 #define DEFAULT_MAX_REPLIES 10
330 #define DEFAULT_LDAP_TIMEOUT 15 /* seconds */
332 #define DEFAULT_CONNECT_TIMEOUT (15*1000) /* 15 seconds */
333 #define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000) /* 2 seconds */
335 /* For the cleanup handler we need to keep track of the socket's name. */
336 static const char *socket_name;
337 /* If the socket has been redirected, this is the name of the
338 redirected socket.. */
339 static const char *redir_socket_name;
341 /* We need to keep track of the server's nonces (these are dummies for
343 static assuan_sock_nonce_t socket_nonce;
345 /* Value for the listen() backlog argument.
346 * Change at runtime with --listen-backlog. */
347 static int listen_backlog = 64;
349 /* Only if this flag has been set will we remove the socket file. */
350 static int cleanup_socket;
352 /* Keep track of the current log file so that we can avoid updating
353 the log file after a SIGHUP if it didn't changed. Malloced. */
354 static char *current_logfile;
356 /* Helper to implement --debug-level. */
357 static const char *debug_level;
359 /* Helper to set the NTBTLS or GNUTLS log level. */
360 static int opt_gnutls_debug = -1;
362 /* Flag indicating that a shutdown has been requested. */
363 static volatile int shutdown_pending;
365 /* Flags to indicate that we shall not watch our own socket. */
366 static int disable_check_own_socket;
368 /* Flag indicating to start the daemon even if one already runs. */
369 static int steal_socket;
372 /* Flag to control the Tor mode. */
374 { TOR_MODE_AUTO = 0, /* Switch to NO or YES */
375 TOR_MODE_NEVER, /* Never use Tor. */
376 TOR_MODE_NO, /* Do not use Tor */
377 TOR_MODE_YES, /* Use Tor */
378 TOR_MODE_FORCE /* Force using Tor */
382 /* Counter for the active connections. */
383 static int active_connections;
385 /* This flag is set by any network access and used by the housekeeping
386 * thread to run background network tasks. */
387 static int network_activity_seen;
389 /* A list of filenames registered with --hkp-cacert. */
390 static strlist_t hkp_cacert_filenames;
392 /* A flag used to clear the list of ldapservers iff --ldapserver is
393 * given on the command line or one of the conf files. In this case we
394 * want to clear all old specifications through the legacy
395 * dirmngr_ldapservers.conf. */
396 static int ldapserver_list_needs_reset;
398 /* The timer tick used for housekeeping stuff. The second constant is used when a shutdown is pending. */
399 #define TIMERTICK_INTERVAL (60)
400 #define TIMERTICK_INTERVAL_SHUTDOWN (4)
402 /* How oft to run the housekeeping. */
403 #define HOUSEKEEPING_INTERVAL (600)
406 /* This union is used to avoid compiler warnings in case a pointer is
407 64 bit and an int 32 bit. We store an integer in a pointer and get
408 it back later (npth_getspecific et al.). */
418 /* The key used to store the current file descriptor in the thread
419 local storage. We use this in conjunction with the
420 log_set_pid_suffix_cb feature. */
421 #ifndef HAVE_W32_SYSTEM
422 static npth_key_t my_tlskey_current_fd;
426 static void cleanup (void);
428 static ldap_server_t parse_ldapserver_file (const char* filename, int ienoent);
430 static fingerprint_list_t parse_fingerprint_item (const char *string,
431 const char *optionname,
433 static void netactivity_action (void);
434 static void handle_connections (assuan_fd_t listen_fd);
435 static void gpgconf_versions (void);
438 /* NPth wrapper function definitions. */
439 ASSUAN_SYSTEM_NPTH_IMPL;
442 my_strusage( int level )
447 case 9: p = "GPL-3.0-or-later"; break;
448 case 11: p = "@DIRMNGR@ (@GNUPG@)";
450 case 13: p = VERSION; break;
451 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
452 case 17: p = PRINTABLE_OS_NAME; break;
453 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
454 reporting address. This is so that we can change the
455 reporting address without breaking the translations. */
456 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
457 case 49: p = PACKAGE_BUGREPORT; break;
459 case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)");
461 case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n"
462 "Keyserver, CRL, and OCSP access for @GNUPG@\n");
471 /* Callback from libksba to hash a provided buffer. Our current
472 implementation does only allow SHA-1 for hashing. This may be
473 extended by mapping the name, testing for algorithm availability
474 and adjust the length checks accordingly. */
476 my_ksba_hash_buffer (void *arg, const char *oid,
477 const void *buffer, size_t length, size_t resultsize,
478 unsigned char *result, size_t *resultlen)
482 if (oid && strcmp (oid, "1.3.14.3.2.26"))
483 return gpg_error (GPG_ERR_NOT_SUPPORTED);
485 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
486 gcry_md_hash_buffer (2, result, buffer, length);
492 /* GNUTLS log function callback. */
493 #ifdef HTTP_USE_GNUTLS
495 my_gnutls_log (int level, const char *text)
500 while (n && text[n-1] == '\n')
503 log_debug ("gnutls:L%d: %.*s\n", level, n, text);
505 #endif /*HTTP_USE_GNUTLS*/
507 /* Setup the debugging. With a LEVEL of NULL only the active debug
508 flags are propagated to the subsystems. With LEVEL set, a specific
509 set of debug flags is set; thus overriding all flags already
514 int numok = (debug_level && digitp (debug_level));
515 int numlvl = numok? atoi (debug_level) : 0;
519 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
521 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
522 opt.debug = DBG_IPC_VALUE;
523 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
524 opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE);
525 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
526 opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE
527 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
528 else if (!strcmp (debug_level, "guru") || numok)
531 /* Unless the "guru" string has been used we don't want to allow
532 hashing debugging. The rationale is that people tend to
533 select the highest debug value and would then clutter their
534 disk with debug files which may reveal confidential data. */
536 opt.debug &= ~(DBG_HASHING_VALUE);
540 log_error (_("invalid debug-level '%s' given\n"), debug_level);
541 log_info (_("valid debug levels are: %s\n"),
542 "none, basic, advanced, expert, guru");
543 opt.debug = 0; /* Reset debugging, so that prior debug
544 statements won't have an undesired effect. */
548 if (opt.debug && !opt.verbose)
551 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
553 if (opt.debug && opt.quiet)
556 if (opt.debug & DBG_CRYPTO_VALUE )
557 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
560 if (opt_gnutls_debug >= 0)
562 ntbtls_set_debug (opt_gnutls_debug, NULL, NULL);
564 #elif HTTP_USE_GNUTLS
565 if (opt_gnutls_debug >= 0)
567 gnutls_global_set_log_function (my_gnutls_log);
568 gnutls_global_set_log_level (opt_gnutls_debug);
570 #endif /*HTTP_USE_GNUTLS*/
573 parse_debug_flag (NULL, &opt.debug, debug_flags);
580 if (dirmngr_use_tor ())
582 /* Enable Tor mode and when called again force a new circuit
583 * (e.g. on SIGHUP). */
584 enable_dns_tormode (1);
585 if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
587 log_error ("error enabling Tor mode: %s\n", strerror (errno));
588 log_info ("(is your Libassuan recent enough?)\n");
592 disable_dns_tormode ();
596 /* Return true if Tor shall be used. */
598 dirmngr_use_tor (void)
600 if (tor_mode == TOR_MODE_AUTO)
602 /* Figure out whether Tor is running. */
605 sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR);
606 if (sock == ASSUAN_INVALID_FD)
607 tor_mode = TOR_MODE_NO;
610 tor_mode = TOR_MODE_YES;
611 assuan_sock_close (sock);
615 if (tor_mode == TOR_MODE_FORCE)
616 return 2; /* Use Tor (using 2 to indicate force mode) */
617 else if (tor_mode == TOR_MODE_YES)
618 return 1; /* Use Tor */
620 return 0; /* Do not use Tor. */
625 wrong_args (const char *text)
627 es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME);
628 es_fputs (text, es_stderr);
629 es_putc ('\n', es_stderr);
634 /* Helper to stop the reaper thread for the ldap wrapper. */
636 shutdown_reaper (void)
639 ldap_wrapper_wait_connections ();
644 /* Handle options which are allowed to be reset after program start.
645 Return true if the current option in PARGS could be handled and
646 false if not. As a special feature, passing a value of NULL for
647 PARGS, resets the options to the default. REREAD should be set
648 true if it is not the initial option parsing. */
650 parse_rereadable_options (gpgrt_argparse_t *pargs, int reread)
657 opt.ldap_wrapper_program = NULL;
658 opt.disable_http = 0;
659 opt.disable_ldap = 0;
660 opt.honor_http_proxy = 0;
661 opt.http_proxy = NULL;
662 opt.ldap_proxy = NULL;
663 opt.only_ldap_proxy = 0;
664 opt.ignore_http_dp = 0;
665 opt.ignore_ldap_dp = 0;
666 opt.ignore_ocsp_service_url = 0;
668 opt.allow_version_check = 0;
669 opt.ocsp_responder = NULL;
670 opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */
671 opt.ocsp_max_period = 90 * 86400; /* 90 days. */
672 opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */
673 opt.max_replies = DEFAULT_MAX_REPLIES;
674 while (opt.ocsp_signer)
676 fingerprint_list_t tmp = opt.ocsp_signer->next;
677 xfree (opt.ocsp_signer);
678 opt.ocsp_signer = tmp;
680 while (opt.ignored_certs)
682 fingerprint_list_t tmp = opt.ignored_certs->next;
683 xfree (opt.ignored_certs);
684 opt.ignored_certs = tmp;
686 FREE_STRLIST (opt.ignored_cert_extensions);
687 http_register_tls_ca (NULL);
688 FREE_STRLIST (hkp_cacert_filenames);
689 FREE_STRLIST (opt.keyserver);
690 /* Note: We do not allow resetting of TOR_MODE_FORCE at runtime. */
691 if (tor_mode != TOR_MODE_FORCE)
692 tor_mode = TOR_MODE_AUTO;
693 disable_check_own_socket = 0;
694 enable_standard_resolver (0);
696 opt.connect_timeout = 0;
697 opt.connect_quick_timeout = 0;
698 opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
699 ldapserver_list_needs_reset = 1;
703 switch (pargs->r_opt)
705 case oQuiet: opt.quiet = 1; break;
706 case oVerbose: opt.verbose++; break;
708 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
710 case oDebugAll: opt.debug = ~0; break;
711 case oDebugLevel: debug_level = pargs->r.ret_str; break;
712 case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break;
716 return 0; /* Not handled. */
717 if (!current_logfile || !pargs->r.ret_str
718 || strcmp (current_logfile, pargs->r.ret_str))
720 log_set_file (pargs->r.ret_str);
721 xfree (current_logfile);
722 current_logfile = xtrystrdup (pargs->r.ret_str);
726 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
728 case oLDAPWrapperProgram:
729 opt.ldap_wrapper_program = pargs->r.ret_str;
731 case oHTTPWrapperProgram:
732 opt.http_wrapper_program = pargs->r.ret_str;
735 case oDisableHTTP: opt.disable_http = 1; break;
736 case oDisableLDAP: opt.disable_ldap = 1; break;
737 case oDisableIPv4: opt.disable_ipv4 = 1; break;
738 case oDisableIPv6: opt.disable_ipv6 = 1; break;
739 case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
740 case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
741 case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
742 case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
743 case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
744 case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
745 case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
747 case oAllowOCSP: opt.allow_ocsp = 1; break;
748 case oAllowVersionCheck: opt.allow_version_check = 1; break;
749 case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
751 opt.ocsp_signer = parse_fingerprint_item (pargs->r.ret_str,
754 case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
755 case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
756 case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
758 case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
762 /* We need to register the filenames with gnutls (http.c) and
763 * also for our own cert cache. */
766 /* Do tilde expansion and make path absolute. */
767 tmpname = make_absfilename (pargs->r.ret_str, NULL);
768 http_register_tls_ca (tmpname);
769 add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str);
776 fingerprint_list_t item, r;
777 item = parse_fingerprint_item (pargs->r.ret_str, "--ignore-cert", 20);
780 if (!opt.ignored_certs)
781 opt.ignored_certs = item;
784 for (r = opt.ignored_certs; r->next; r = r->next)
792 case oIgnoreCertExtension:
793 add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
797 tor_mode = TOR_MODE_FORCE;
800 if (tor_mode != TOR_MODE_FORCE)
801 tor_mode = TOR_MODE_NEVER;
804 case oStandardResolver: enable_standard_resolver (1); break;
805 case oRecursiveResolver: enable_recursive_resolver (1); break;
810 ldap_server_t server;
813 p = pargs->r.ret_str;
814 if (!strncmp (p, "ldap:", 5) && !(p[5] == '/' && p[6] == '/'))
817 server = ldapserver_parse_one (p, NULL, 0);
820 if (ldapserver_list_needs_reset)
822 ldapserver_list_needs_reset = 0;
823 ldapserver_list_free (opt.ldapservers);
824 opt.ldapservers = NULL;
826 server->next = opt.ldapservers;
827 opt.ldapservers = server;
834 if (*pargs->r.ret_str)
835 add_to_strlist (&opt.keyserver, pargs->r.ret_str);
839 set_dns_nameserver (pargs->r.ret_str);
842 case oResolverTimeout:
843 set_dns_timeout (pargs->r.ret_int);
846 case oConnectTimeout:
847 opt.connect_timeout = pargs->r.ret_ulong * 1000;
850 case oConnectQuickTimeout:
851 opt.connect_quick_timeout = pargs->r.ret_ulong * 1000;
855 opt.ldaptimeout = pargs->r.ret_int;
859 return 0; /* Not handled. */
862 set_dns_verbose (opt.verbose, !!DBG_DNS);
863 http_set_verbose (opt.verbose, !!DBG_NETWORK);
864 set_dns_disable_ipv4 (opt.disable_ipv4);
865 set_dns_disable_ipv6 (opt.disable_ipv6);
867 return 1; /* Handled. */
871 /* This function is called after option parsing to adjust some values
872 * and call option setup functions. */
874 post_option_parsing (void)
876 /* It would be too surpirsing if the quick timeout is larger than
877 * the standard value. */
878 if (opt.connect_quick_timeout > opt.connect_timeout)
879 opt.connect_quick_timeout = opt.connect_timeout;
885 #ifndef HAVE_W32_SYSTEM
887 pid_suffix_callback (unsigned long *r_suffix)
889 union int_and_ptr_u value;
891 memset (&value, 0, sizeof value);
892 value.aptr = npth_getspecific (my_tlskey_current_fd);
893 *r_suffix = value.aint;
894 return (*r_suffix != -1); /* Use decimal representation. */
896 #endif /*!HAVE_W32_SYSTEM*/
900 my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv)
905 log_logv_prefix (GPGRT_LOGLVL_INFO, "ntbtls: ", fmt, argv);
909 snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level);
910 log_logv_prefix (GPGRT_LOGLVL_DEBUG, prefix, fmt, argv);
920 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
921 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
923 /* Now with NPth running we can set the logging callback. Our
924 windows implementation does not yet feature the NPth TLS
926 #ifndef HAVE_W32_SYSTEM
927 if (npth_key_create (&my_tlskey_current_fd, NULL) == 0)
928 if (npth_setspecific (my_tlskey_current_fd, NULL) == 0)
929 log_set_pid_suffix_cb (pid_suffix_callback);
930 #endif /*!HAVE_W32_SYSTEM*/
935 main (int argc, char **argv)
937 enum cmd_and_opt_values cmd = 0;
938 gpgrt_argparse_t pargs;
941 char *last_configname = NULL;
942 const char *configname = NULL;
944 int debug_argparser = 0;
949 char *logfile = NULL;
951 char *ldapfile = NULL;
955 struct assuan_malloc_hooks malloc_hooks;
957 early_system_init ();
958 gpgrt_set_strusage (my_strusage);
959 log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
961 /* Make sure that our subsystems are ready. */
963 init_common_subsystems (&argc, &argv);
965 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
967 /* Check that the libraries are suitable. Do it here because
968 the option parsing may need services of the libraries. */
969 if (!ksba_check_version (NEED_KSBA_VERSION) )
970 log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba",
971 NEED_KSBA_VERSION, ksba_check_version (NULL) );
973 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
974 ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
976 /* Init TLS library. */
978 if (!ntbtls_check_version (NEED_NTBTLS_VERSION) )
979 log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls",
980 NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) );
981 #elif HTTP_USE_GNUTLS
982 rc = gnutls_global_init ();
984 log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));
985 #endif /*HTTP_USE_GNUTLS*/
988 malloc_hooks.malloc = gcry_malloc;
989 malloc_hooks.realloc = gcry_realloc;
990 malloc_hooks.free = gcry_free;
991 assuan_set_malloc_hooks (&malloc_hooks);
992 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
993 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
995 setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor);
997 setup_libgcrypt_logging ();
1000 ntbtls_set_log_handler (my_ntbtls_log_handler, NULL);
1003 /* Setup defaults. */
1004 shell = getenv ("SHELL");
1005 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
1008 /* Reset rereadable options to default values. */
1009 parse_rereadable_options (NULL, 0);
1011 /* Default TCP timeouts. */
1012 opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT;
1013 opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT;
1015 /* LDAP defaults. */
1016 opt.add_new_ldapservers = 0;
1017 opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
1019 /* Other defaults. */
1021 /* Check whether we have a config file given on the commandline */
1026 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1027 while (gpgrt_argparse (NULL, &pargs, opts))
1029 switch (pargs.r_opt)
1036 gnupg_set_homedir (pargs.r.ret_str);
1040 /* Reset the flags. */
1041 pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1043 socket_name = dirmngr_socket_name ();
1045 /* The configuraton directories for use by gpgrt_argparser. */
1046 gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
1047 gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
1049 /* We are re-using the struct, thus the reset flag. We OR the
1050 * flags so that the internal intialized flag won't be cleared. */
1055 pargs.flags |= (ARGPARSE_FLAG_RESET
1056 | ARGPARSE_FLAG_KEEP
1058 | ARGPARSE_FLAG_USER);
1059 while (gpgrt_argparser (&pargs, opts, DIRMNGR_NAME EXTSEP_S "conf"))
1061 if (pargs.r_opt == ARGPARSE_CONFFILE)
1063 if (debug_argparser)
1064 log_info (_("reading options from '%s'\n"),
1065 pargs.r_type? pargs.r.ret_str: "[cmdline]");
1068 xfree (last_configname);
1069 last_configname = xstrdup (pargs.r.ret_str);
1070 configname = last_configname;
1076 if (parse_rereadable_options (&pargs, 0))
1077 continue; /* Already handled */
1078 switch (pargs.r_opt)
1090 case aGPGConfVersions:
1094 case oQuiet: opt.quiet = 1; break;
1095 case oVerbose: opt.verbose++; break;
1096 case oBatch: opt.batch=1; break;
1098 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1100 case oNoGreeting: nogreeting = 1; break;
1101 case oNoVerbose: opt.verbose = 0; break;
1102 case oHomedir: /* Ignore this option here. */; break;
1103 case oNoDetach: nodetach = 1; break;
1104 case oStealSocket: steal_socket = 1; break;
1105 case oLogFile: logfile = pargs.r.ret_str; break;
1106 case oCsh: csh_style = 1; break;
1107 case oSh: csh_style = 0; break;
1110 ldapfile = pargs.r.ret_str;
1111 # endif /*USE_LDAP*/
1113 case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
1115 case oFakedSystemTime:
1116 gnupg_set_time ((time_t)pargs.r.ret_ulong, 0);
1119 case oForce: opt.force = 1; break;
1121 case oSocketName: socket_name = pargs.r.ret_str; break;
1123 case oListenBacklog:
1124 listen_backlog = pargs.r.ret_int;
1129 pargs.err = ARGPARSE_PRINT_WARNING;
1131 pargs.err = ARGPARSE_PRINT_ERROR;
1135 gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */
1137 if (!last_configname)
1138 opt.config_filename = gpgrt_fnameconcat (gnupg_homedir (),
1139 DIRMNGR_NAME EXTSEP_S "conf",
1143 opt.config_filename = last_configname;
1144 last_configname = NULL;
1147 if (log_get_errorcount(0))
1150 /* Get a default log file from common.conf. */
1151 if (!logfile && !parse_comopt (GNUPG_MODULE_NAME_DIRMNGR, debug_argparser))
1153 logfile = comopt.logfile;
1154 comopt.logfile = NULL;
1160 if (!opt.homedir_cache)
1161 opt.homedir_cache = xstrdup (gnupg_homedir ());
1165 es_fprintf (es_stderr, "%s %s; %s\n",
1166 gpgrt_strusage(11), gpgrt_strusage(13), gpgrt_strusage(14));
1167 es_fprintf (es_stderr, "%s\n", gpgrt_strusage(15));
1170 #ifdef IS_DEVELOPMENT_VERSION
1171 log_info ("NOTE: this is a development version!\n");
1174 /* Print a warning if an argument looks like an option. */
1175 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1179 for (i=0; i < argc; i++)
1180 if (argv[i][0] == '-' && argv[i][1] == '-')
1181 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1184 if (!gnupg_access ("/etc/"DIRMNGR_NAME, F_OK)
1185 && !strncmp (gnupg_homedir (), "/etc/", 5))
1187 ("NOTE: DirMngr is now a proper part of %s. The configuration and"
1188 " other directory names changed. Please check that no other version"
1189 " of dirmngr is still installed. To disable this warning, remove the"
1190 " directory '/etc/dirmngr'.\n", GNUPG_NAME);
1192 if (gnupg_faked_time_p ())
1194 gnupg_isotime_t tbuf;
1196 log_info (_("WARNING: running with faked system time: "));
1197 gnupg_get_isotime (tbuf);
1198 dump_isotime (tbuf);
1202 /* Note that we do not run set_tor_mode in --gpgconf-list mode
1203 * because it will attempt to connect to the tor client and that can
1204 * be time consuming. */
1205 post_option_parsing ();
1206 if (cmd != aGPGConfTest && cmd != aGPGConfList && cmd != aGPGConfVersions)
1209 /* Get LDAP server list from file unless --ldapserver has been used. */
1211 if (opt.ldapservers)
1215 ldapfile = make_filename (gnupg_homedir (),
1216 "dirmngr_ldapservers.conf",
1218 opt.ldapservers = parse_ldapserver_file (ldapfile, 1);
1222 opt.ldapservers = parse_ldapserver_file (ldapfile, 0);
1225 #ifndef HAVE_W32_SYSTEM
1226 /* We need to ignore the PIPE signal because the we might log to a
1227 socket and that code handles EPIPE properly. The ldap wrapper
1228 also requires us to ignore this silly signal. Assuan would set
1229 this signal to ignore anyway.*/
1230 signal (SIGPIPE, SIG_IGN);
1233 /* Ready. Now to our duties. */
1240 /* Note that this server mode is mainly useful for debugging. */
1242 wrong_args ("--server");
1246 log_set_file (logfile);
1247 log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1252 log_debug ("waiting for debugger - my pid is %u .....\n",
1253 (unsigned int)getpid());
1254 gnupg_sleep (debug_wait);
1255 log_debug ("... okay\n");
1260 cert_cache_init (hkp_cacert_filenames);
1263 http_register_netactivity_cb (netactivity_action);
1264 start_command_handler (ASSUAN_INVALID_FD, 0);
1267 #ifndef HAVE_W32_SYSTEM
1268 else if (cmd == aSupervised)
1270 /* In supervised mode, we expect file descriptor 3 to be an
1271 already opened, listening socket.
1273 We will also not detach from the controlling process or close
1274 stderr; the supervisor should handle all of that. */
1275 struct stat statbuf;
1276 if (fstat (3, &statbuf) == -1 && errno == EBADF)
1278 log_error ("file descriptor 3 must be validin --supervised mode\n");
1281 socket_name = gnupg_get_socket_name (3);
1283 /* Now start with logging to a file if this is desired. */
1286 log_set_file (logfile);
1287 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1288 |GPGRT_LOG_WITH_TIME
1289 |GPGRT_LOG_WITH_PID));
1290 current_logfile = xstrdup (logfile);
1293 log_set_prefix (NULL, 0);
1296 cert_cache_init (hkp_cacert_filenames);
1299 http_register_netactivity_cb (netactivity_action);
1300 handle_connections (3);
1303 #endif /*HAVE_W32_SYSTEM*/
1304 else if (cmd == aDaemon)
1309 struct sockaddr_un serv_addr;
1312 wrong_args ("--daemon");
1314 /* Now start with logging to a file if this is desired. */
1317 log_set_file (logfile);
1318 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1319 |GPGRT_LOG_WITH_TIME
1320 |GPGRT_LOG_WITH_PID));
1321 current_logfile = xstrdup (logfile);
1326 log_debug ("waiting for debugger - my pid is %u .....\n",
1327 (unsigned int)getpid());
1328 gnupg_sleep (debug_wait);
1329 log_debug ("... okay\n");
1332 #ifndef HAVE_W32_SYSTEM
1333 if (strchr (socket_name, ':'))
1335 log_error (_("colons are not allowed in the socket name\n"));
1339 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1340 if (fd == ASSUAN_INVALID_FD)
1342 log_error (_("can't create socket: %s\n"), strerror (errno));
1350 if (assuan_sock_set_sockaddr_un (socket_name,
1351 (struct sockaddr*)&serv_addr,
1354 if (errno == ENAMETOOLONG)
1355 log_error (_("socket name '%s' is too long\n"), socket_name);
1357 log_error ("error preparing socket '%s': %s\n",
1359 gpg_strerror (gpg_error_from_syserror ()));
1364 redir_socket_name = xstrdup (serv_addr.sun_path);
1366 log_info ("redirecting socket '%s' to '%s'\n",
1367 socket_name, redir_socket_name);
1371 len = SUN_LEN (&serv_addr);
1373 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1375 && (errno == EADDRINUSE
1376 #ifdef HAVE_W32_SYSTEM
1381 /* Fixme: We should actually test whether a dirmngr is
1382 * already running. For now the steal option is a dummy. */
1383 /* if (steal_socket) */
1384 /* log_info (N_("trying to steal socket from running %s\n"), */
1386 gnupg_remove (redir_socket_name? redir_socket_name : socket_name);
1387 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1390 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
1391 log_error (_("error getting nonce for the socket\n"));
1394 log_error (_("error binding socket to '%s': %s\n"),
1396 gpg_strerror (gpg_error_from_syserror ()));
1397 assuan_sock_close (fd);
1402 if (gnupg_chmod (serv_addr.sun_path, "-rwx"))
1403 log_error (_("can't set permissions of '%s': %s\n"),
1404 serv_addr.sun_path, strerror (errno));
1406 if (listen (FD2INT (fd), listen_backlog) == -1)
1408 log_error ("listen(fd,%d) failed: %s\n",
1409 listen_backlog, strerror (errno));
1410 assuan_sock_close (fd);
1415 log_info (_("listening on socket '%s'\n"), serv_addr.sun_path);
1419 /* Note: We keep the dirmngr_info output only for the sake of
1420 existing scripts which might use this to detect a successful
1421 start of the dirmngr. */
1422 #ifdef HAVE_W32_SYSTEM
1427 es_printf ("set %s=%s;%lu;1\n",
1428 DIRMNGR_INFO_NAME, socket_name, (ulong) pid);
1431 if (pid == (pid_t)-1)
1433 log_fatal (_("error forking process: %s\n"), strerror (errno));
1438 { /* We are the parent */
1441 /* Don't let cleanup() remove the socket - the child is
1442 responsible for doing that. */
1447 /* Create the info string: <name>:<pid>:<protocol_version> */
1448 if (asprintf (&infostr, "%s=%s:%lu:1",
1449 DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0)
1451 log_error (_("out of core\n"));
1452 kill (pid, SIGTERM);
1455 /* Print the environment string, so that the caller can use
1456 shell's eval to set it. But see above. */
1459 *strchr (infostr, '=') = ' ';
1460 es_printf ( "setenv %s;\n", infostr);
1464 es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME);
1476 /* Detach from tty and put process into a new session */
1480 unsigned int oldflags;
1482 /* Close stdin, stdout and stderr unless it is the log stream */
1483 for (i=0; i <= 2; i++)
1485 if (!log_test_fd (i) && i != fd )
1488 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1490 log_error ("failed to open '%s': %s\n",
1491 "/dev/null", strerror (errno));
1500 log_error ("setsid() failed: %s\n", strerror(errno) );
1504 log_get_prefix (&oldflags);
1505 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1506 opt.running_detached = 1;
1513 if (gnupg_chdir (gnupg_daemon_rootdir ()))
1515 log_error ("chdir to '%s' failed: %s\n",
1516 gnupg_daemon_rootdir (), strerror (errno));
1522 cert_cache_init (hkp_cacert_filenames);
1525 http_register_netactivity_cb (netactivity_action);
1526 handle_connections (fd);
1529 else if (cmd == aListCRLs)
1531 /* Just list the CRL cache and exit. */
1533 wrong_args ("--list-crls");
1535 crl_cache_list (es_stdout);
1537 else if (cmd == aLoadCRL)
1539 struct server_control_s ctrlbuf;
1541 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1542 dirmngr_init_default_ctrl (&ctrlbuf);
1545 cert_cache_init (hkp_cacert_filenames);
1549 rc = crl_cache_load (&ctrlbuf, NULL);
1552 for (; !rc && argc; argc--, argv++)
1553 rc = crl_cache_load (&ctrlbuf, *argv);
1555 dirmngr_deinit_default_ctrl (&ctrlbuf);
1557 else if (cmd == aFetchCRL)
1559 ksba_reader_t reader;
1560 struct server_control_s ctrlbuf;
1563 wrong_args ("--fetch-crl URL");
1565 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1566 dirmngr_init_default_ctrl (&ctrlbuf);
1569 cert_cache_init (hkp_cacert_filenames);
1572 rc = crl_fetch (&ctrlbuf, argv[0], &reader);
1574 log_error (_("fetching CRL from '%s' failed: %s\n"),
1575 argv[0], gpg_strerror (rc));
1578 rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
1580 log_error (_("processing CRL from '%s' failed: %s\n"),
1581 argv[0], gpg_strerror (rc));
1582 crl_close_reader (reader);
1584 dirmngr_deinit_default_ctrl (&ctrlbuf);
1586 else if (cmd == aFlush)
1588 /* Delete cache and exit. */
1590 wrong_args ("--flush");
1591 rc = crl_cache_flush();
1593 else if (cmd == aGPGConfTest)
1595 else if (cmd == aGPGConfList)
1597 unsigned long flags = 0;
1600 es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
1601 es_printf ("ldaptimeout:%lu:%u\n",
1602 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
1603 es_printf ("max-replies:%lu:%u\n",
1604 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
1606 filename_esc = percent_escape (get_default_keyserver (0), NULL);
1607 es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT,
1609 xfree (filename_esc);
1611 es_printf ("resolver-timeout:%lu:%u\n",
1612 flags | GC_OPT_FLAG_DEFAULT, 0);
1614 else if (cmd == aGPGConfVersions)
1615 gpgconf_versions ();
1625 crl_cache_deinit ();
1626 cert_cache_deinit (1);
1627 reload_dns_stuff (1);
1630 ldapserver_list_free (opt.ldapservers);
1632 opt.ldapservers = NULL;
1637 if (redir_socket_name)
1638 gnupg_remove (redir_socket_name);
1639 else if (socket_name && *socket_name)
1640 gnupg_remove (socket_name);
1646 dirmngr_exit (int rc)
1654 dirmngr_init_default_ctrl (ctrl_t ctrl)
1656 ctrl->magic = SERVER_CONTROL_MAGIC;
1658 ctrl->http_proxy = xstrdup (opt.http_proxy);
1659 ctrl->http_no_crl = 1;
1660 ctrl->timeout = opt.connect_timeout;
1665 dirmngr_deinit_default_ctrl (ctrl_t ctrl)
1669 ctrl->magic = 0xdeadbeef;
1671 xfree (ctrl->http_proxy);
1672 ctrl->http_proxy = NULL;
1676 /* Create a list of LDAP servers from the file FILENAME. Returns the
1677 list or NULL in case of errors.
1679 The format of such a file is line oriented where empty lines and
1680 lines starting with a hash mark are ignored. All other lines are
1681 assumed to be colon seprated with these fields:
1684 2. field: Portnumber
1691 static ldap_server_t
1692 parse_ldapserver_file (const char* filename, int ignore_enoent)
1696 ldap_server_t server, serverstart, *serverend;
1698 unsigned int lineno = 0;
1701 fp = es_fopen (filename, "r");
1704 if (ignore_enoent && gpg_err_code_from_syserror () == GPG_ERR_ENOENT)
1707 log_info ("failed to open '%s': %s\n", filename, strerror (errno));
1712 serverend = &serverstart;
1713 while (es_fgets (buffer, sizeof buffer, fp))
1716 if (!*buffer || buffer[strlen(buffer)-1] != '\n')
1718 if (*buffer && es_feof (fp))
1719 ; /* Last line not terminated - continue. */
1722 log_error (_("%s:%u: line too long - skipped\n"),
1724 while ( (c=es_fgetc (fp)) != EOF && c != '\n')
1725 ; /* Skip until end of line. */
1729 /* Skip empty and comment lines.*/
1730 for (p=buffer; spacep (p); p++)
1732 if (!*p || *p == '\n' || *p == '#')
1735 /* Parse the colon separated fields. */
1736 server = ldapserver_parse_one (buffer, filename, lineno);
1739 *serverend = server;
1740 serverend = &server->next;
1745 log_error (_("error reading '%s': %s\n"), filename, strerror (errno));
1753 /* Parse a fingerprint entry as used by --ocsc-signer. OPTIONNAME as
1754 * a description on the options used. WANT_BINARY requests to store a
1755 * binary fingerprint. Returns NULL on error and logs that error. */
1756 static fingerprint_list_t
1757 parse_fingerprint_item (const char *string,
1758 const char *optionname, int want_binary)
1765 fingerprint_list_t list, *list_tail, item;
1766 unsigned int lnr = 0;
1771 /* Check whether this is not a filename and treat it as a direct
1772 fingerprint specification. */
1773 if (!strpbrk (string, "/.~\\"))
1775 item = xcalloc (1, sizeof *item);
1776 for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
1777 if ( string[i] != ':' )
1778 item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
1779 item->hexfpr[j] = 0;
1780 if (j != 40 || !(spacep (string+i) || !string[i]))
1782 log_error (_("%s:%u: invalid fingerprint detected\n"),
1790 hex2bin (item->hexfpr, item->hexfpr, 20);
1795 /* Well, it is a filename. */
1796 if (*string == '/' || (*string == '~' && string[1] == '/'))
1797 fname = make_filename (string, NULL);
1800 if (string[0] == '.' && string[1] == '/' )
1802 fname = make_filename (gnupg_homedir (), string, NULL);
1805 fp = es_fopen (fname, "r");
1808 err = gpg_error_from_syserror ();
1809 log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
1818 if (!es_fgets (line, DIM(line)-1, fp) )
1822 err = gpg_error_from_syserror ();
1823 log_error (_("%s:%u: read error: %s\n"),
1824 fname, lnr, gpg_strerror (err));
1832 fingerprint_list_t tmp = list->next;
1838 return list; /* Ready. */
1842 if (!*line || line[strlen(line)-1] != '\n')
1844 /* Eat until end of line. */
1845 while ( (c=es_getc (fp)) != EOF && c != '\n')
1847 err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
1848 /* */: GPG_ERR_INCOMPLETE_LINE);
1849 log_error (_("%s:%u: read error: %s\n"),
1850 fname, lnr, gpg_strerror (err));
1855 /* Allow for empty lines and spaces */
1856 for (p=line; spacep (p); p++)
1858 if (!*p || *p == '\n' || *p == '#')
1861 item = xcalloc (1, sizeof *item);
1863 list_tail = &item->next;
1865 for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
1867 item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
1868 item->hexfpr[j] = 0;
1869 if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
1871 log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
1874 else if (want_binary)
1877 hex2bin (item->hexfpr, item->hexfpr, 20);
1881 while (spacep (p+i))
1883 if (p[i] && p[i] != '\n')
1884 log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
1893 Stuff used in daemon mode.
1898 /* Reread parts of the configuration. Note, that this function is
1899 obviously not thread-safe and should only be called from the NPTH
1902 Fixme: Due to the way the argument parsing works, we create a
1903 memory leak here for all string type arguments. There is currently
1904 no clean way to tell whether the memory for the argument has been
1905 allocated or points into the process's original arguments. Unless
1906 we have a mechanism to tell this, we need to live on with this. */
1908 reread_configuration (void)
1910 gpgrt_argparse_t pargs;
1913 int logfile_seen = 0;
1915 if (!opt.config_filename)
1916 goto finish; /* No config file. */
1918 twopart = strconcat (DIRMNGR_NAME EXTSEP_S "conf" PATHSEP_S,
1919 opt.config_filename, NULL);
1921 return; /* Out of core. */
1923 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1925 memset (&pargs, 0, sizeof pargs);
1927 pargs.argc = &dummy;
1928 pargs.flags = (ARGPARSE_FLAG_KEEP
1930 |ARGPARSE_FLAG_USER);
1931 while (gpgrt_argparser (&pargs, opts, twopart))
1933 if (pargs.r_opt == ARGPARSE_CONFFILE)
1935 log_info (_("reading options from '%s'\n"),
1936 pargs.r_type? pargs.r.ret_str: "[cmdline]");
1938 else if (pargs.r_opt < -1)
1939 pargs.err = ARGPARSE_PRINT_WARNING;
1940 else /* Try to parse this option - ignore unchangeable ones. */
1942 if (pargs.r_opt == oLogFile)
1944 parse_rereadable_options (&pargs, 1);
1947 gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */
1949 post_option_parsing ();
1952 /* Get a default log file from common.conf. */
1953 if (!logfile_seen && !parse_comopt (GNUPG_MODULE_NAME_DIRMNGR, !!opt.debug))
1955 if (!current_logfile || !comopt.logfile
1956 || strcmp (current_logfile, comopt.logfile))
1958 log_set_file (comopt.logfile);
1959 xfree (current_logfile);
1960 current_logfile = comopt.logfile? xtrystrdup (comopt.logfile) : NULL;
1966 /* A global function which allows us to trigger the reload stuff from
1969 dirmngr_sighup_action (void)
1971 log_info (_("SIGHUP received - "
1972 "re-reading configuration and flushing caches\n"));
1973 reread_configuration ();
1975 cert_cache_deinit (0);
1976 crl_cache_deinit ();
1977 cert_cache_init (hkp_cacert_filenames);
1979 reload_dns_stuff (0);
1984 /* This function is called if some network activity was done. At this
1985 * point we know the we have a network and we can decide whether to
1986 * run scheduled background tasks soon. The function should return
1987 * quickly and only trigger actions for another thread. */
1989 netactivity_action (void)
1991 network_activity_seen = 1;
1995 /* The signal handler. */
1996 #ifndef HAVE_W32_SYSTEM
1998 handle_signal (int signo)
2003 dirmngr_sighup_action ();
2007 cert_cache_print_stats ();
2008 domaininfo_print_stats ();
2012 log_info (_("SIGUSR2 received - no action defined\n"));
2016 if (!shutdown_pending)
2017 log_info (_("SIGTERM received - shutting down ...\n"));
2019 log_info (_("SIGTERM received - still %d active connections\n"),
2020 active_connections);
2022 if (shutdown_pending > 2)
2024 log_info (_("shutdown forced\n"));
2025 log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2032 log_info (_("SIGINT received - immediate shutdown\n"));
2033 log_info( "%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2039 log_info (_("signal %d received - no action defined\n"), signo);
2042 #endif /*!HAVE_W32_SYSTEM*/
2045 /* Thread to do the housekeeping. */
2047 housekeeping_thread (void *arg)
2049 static int sentinel;
2051 struct server_control_s ctrlbuf;
2055 curtime = gnupg_get_time ();
2058 log_info ("housekeeping is already going on\n");
2062 if (opt.verbose > 1)
2063 log_info ("starting housekeeping\n");
2065 memset (&ctrlbuf, 0, sizeof ctrlbuf);
2066 dirmngr_init_default_ctrl (&ctrlbuf);
2068 dns_stuff_housekeeping ();
2069 ks_hkp_housekeeping (curtime);
2070 if (network_activity_seen)
2072 network_activity_seen = 0;
2073 if (opt.allow_version_check)
2074 dirmngr_load_swdb (&ctrlbuf, 0);
2075 workqueue_run_global_tasks (&ctrlbuf, 1);
2078 workqueue_run_global_tasks (&ctrlbuf, 0);
2080 dirmngr_deinit_default_ctrl (&ctrlbuf);
2082 if (opt.verbose > 1)
2083 log_info ("ready with housekeeping\n");
2090 /* We try to enable correct overflow handling for signed int (commonly
2091 * used for time_t). With gcc 4.2 -fno-strict-overflow was introduced
2092 * and used here as a pragma. Later gcc versions (gcc 6?) removed
2093 * this as a pragma and -fwrapv was then suggested as a replacement
2094 * for -fno-strict-overflow. */
2095 #if GPGRT_HAVE_PRAGMA_GCC_PUSH
2096 # pragma GCC push_options
2097 # pragma GCC optimize ("wrapv")
2100 time_for_housekeeping_p (time_t curtime)
2102 static time_t last_housekeeping;
2104 if (!last_housekeeping)
2105 last_housekeeping = curtime;
2107 if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime
2108 || last_housekeeping > curtime /*(be prepared for y2038)*/)
2110 last_housekeeping = curtime;
2115 #if GPGRT_HAVE_PRAGMA_GCC_PUSH
2116 # pragma GCC pop_options
2120 /* This is the worker for the ticker. It is called every few seconds
2121 and may only do fast operations. */
2125 struct stat statbuf;
2127 if (time_for_housekeeping_p (gnupg_get_time ()))
2133 err = npth_attr_init (&tattr);
2135 log_error ("error preparing housekeeping thread: %s\n", strerror (err));
2138 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2139 err = npth_create (&thread, &tattr, housekeeping_thread, NULL);
2141 log_error ("error spawning housekeeping thread: %s\n",
2143 npth_attr_destroy (&tattr);
2147 /* Check whether the homedir is still available. */
2148 if (!shutdown_pending
2149 && gnupg_stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
2151 shutdown_pending = 1;
2152 log_info ("homedir has been removed - shutting down\n");
2157 /* Check the nonce on a new connection. This is a NOP unless we are
2158 using our Unix domain socket emulation under Windows. */
2160 check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
2162 if (assuan_sock_check_nonce (fd, nonce))
2164 log_info (_("error reading nonce on fd %d: %s\n"),
2165 FD2INT (fd), strerror (errno));
2166 assuan_sock_close (fd);
2174 /* Helper to call a connection's main function. */
2176 start_connection_thread (void *arg)
2178 static unsigned int last_session_id;
2179 unsigned int session_id;
2180 union int_and_ptr_u argval;
2183 memset (&argval, 0, sizeof argval);
2187 if (check_nonce (fd, &socket_nonce))
2189 log_error ("handler nonce check FAILED\n");
2193 #ifndef HAVE_W32_SYSTEM
2194 npth_setspecific (my_tlskey_current_fd, argval.aptr);
2197 active_connections++;
2199 log_info (_("handler for fd %d started\n"), FD2INT (fd));
2201 session_id = ++last_session_id;
2203 session_id = ++last_session_id;
2204 start_command_handler (fd, session_id);
2207 log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
2208 active_connections--;
2210 workqueue_run_post_session_tasks (session_id);
2212 #ifndef HAVE_W32_SYSTEM
2213 argval.afd = ASSUAN_INVALID_FD;
2214 npth_setspecific (my_tlskey_current_fd, argval.aptr);
2221 #ifdef HAVE_INOTIFY_INIT
2222 /* Read an inotify event and return true if it matches NAME. */
2224 my_inotify_is_name (int fd, const char *name)
2227 struct inotify_event ev;
2228 char _buf[sizeof (struct inotify_event) + 100 + 1];
2233 s = strrchr (name, '/');
2237 n = npth_read (fd, &buf, sizeof buf);
2238 if (n < sizeof (struct inotify_event))
2240 if (buf.ev.len < strlen (name)+1)
2242 if (strcmp (buf.ev.name, name))
2243 return 0; /* Not the desired file. */
2245 return 1; /* Found. */
2247 #endif /*HAVE_INOTIFY_INIT*/
2250 /* Main loop in daemon mode. Note that LISTEN_FD will be owned by
2253 handle_connections (assuan_fd_t listen_fd)
2256 #ifndef HAVE_W32_SYSTEM
2259 struct sockaddr_un paddr;
2260 socklen_t plen = sizeof( paddr );
2262 fd_set fdset, read_fdset;
2263 struct timespec abstime;
2264 struct timespec curtime;
2265 struct timespec timeout;
2267 int my_inotify_fd = -1;
2269 npth_attr_init (&tattr);
2270 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2272 #ifndef HAVE_W32_SYSTEM /* FIXME */
2274 npth_sigev_add (SIGHUP);
2275 npth_sigev_add (SIGUSR1);
2276 npth_sigev_add (SIGUSR2);
2277 npth_sigev_add (SIGINT);
2278 npth_sigev_add (SIGTERM);
2282 #ifdef HAVE_INOTIFY_INIT
2283 if (disable_check_own_socket)
2285 else if ((my_inotify_fd = inotify_init ()) == -1)
2286 log_info ("error enabling fast daemon termination: %s\n",
2290 /* We need to watch the directory for the file because there
2291 * won't be an IN_DELETE_SELF for a socket file. */
2292 char *slash = strrchr (socket_name, '/');
2293 log_assert (slash && slash[1]);
2295 if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1)
2297 close (my_inotify_fd);
2302 #endif /*HAVE_INOTIFY_INIT*/
2305 /* Setup the fdset. It has only one member. This is because we use
2306 pth_select instead of pth_accept to properly sync timeouts with
2309 FD_SET (FD2INT (listen_fd), &fdset);
2310 nfd = FD2INT (listen_fd);
2311 if (my_inotify_fd != -1)
2313 FD_SET (my_inotify_fd, &fdset);
2314 if (my_inotify_fd > nfd)
2315 nfd = my_inotify_fd;
2318 npth_clock_gettime (&abstime);
2319 abstime.tv_sec += TIMERTICK_INTERVAL;
2324 /* Shutdown test. */
2325 if (shutdown_pending)
2327 if (!active_connections)
2330 /* Do not accept new connections but keep on running the
2331 * loop to cope with the timer events.
2333 * Note that we do not close the listening socket because a
2334 * client trying to connect to that socket would instead
2335 * restart a new dirmngr instance - which is unlikely the
2336 * intention of a shutdown. */
2337 /* assuan_sock_close (listen_fd); */
2338 /* listen_fd = -1; */
2341 if (my_inotify_fd != -1)
2343 FD_SET (my_inotify_fd, &fdset);
2344 nfd = my_inotify_fd;
2348 /* Take a copy of the fdset. */
2351 npth_clock_gettime (&curtime);
2352 if (!(npth_timercmp (&curtime, &abstime, <)))
2354 /* Timeout. When a shutdown is pending we use a shorter
2355 * interval to handle the shutdown more quickly. */
2357 npth_clock_gettime (&abstime);
2358 abstime.tv_sec += (shutdown_pending
2359 ? TIMERTICK_INTERVAL_SHUTDOWN
2360 : TIMERTICK_INTERVAL);
2362 npth_timersub (&abstime, &curtime, &timeout);
2364 #ifndef HAVE_W32_SYSTEM
2365 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2366 npth_sigev_sigmask());
2367 saved_errno = errno;
2369 while (npth_sigev_get_pending(&signo))
2370 handle_signal (signo);
2372 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
2373 saved_errno = errno;
2376 if (ret == -1 && saved_errno != EINTR)
2378 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2379 strerror (saved_errno));
2386 /* Interrupt or timeout. Will be handled when calculating the
2391 if (shutdown_pending)
2393 /* Do not anymore accept connections. */
2397 #ifdef HAVE_INOTIFY_INIT
2398 if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset)
2399 && my_inotify_is_name (my_inotify_fd, socket_name))
2401 shutdown_pending = 1;
2402 log_info ("socket file has been removed - shutting down\n");
2404 #endif /*HAVE_INOTIFY_INIT*/
2406 if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
2410 plen = sizeof paddr;
2411 fd = INT2FD (npth_accept (FD2INT(listen_fd),
2412 (struct sockaddr *)&paddr, &plen));
2413 if (fd == GNUPG_INVALID_FD)
2415 log_error ("accept failed: %s\n", strerror (errno));
2419 char threadname[50];
2420 union int_and_ptr_u argval;
2423 memset (&argval, 0, sizeof argval);
2425 snprintf (threadname, sizeof threadname,
2426 "conn fd=%d", FD2INT(fd));
2428 ret = npth_create (&thread, &tattr,
2429 start_connection_thread, argval.aptr);
2432 log_error ("error spawning connection handler: %s\n",
2434 assuan_sock_close (fd);
2436 npth_setname_np (thread, threadname);
2441 #ifdef HAVE_INOTIFY_INIT
2442 if (my_inotify_fd != -1)
2443 close (my_inotify_fd);
2444 #endif /*HAVE_INOTIFY_INIT*/
2445 npth_attr_destroy (&tattr);
2446 if (listen_fd != GNUPG_INVALID_FD)
2447 assuan_sock_close (listen_fd);
2449 log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2453 dirmngr_get_current_socket_name (void)
2458 return dirmngr_socket_name ();
2463 /* Parse the revision part from the extended version blurb. */
2465 get_revision_from_blurb (const char *blurb, int *r_len)
2467 const char *s = blurb? blurb : "";
2471 if (*s == '\n' && s[1] == '(')
2476 for (n=0; s[n] && s[n] != ' '; n++)
2489 /* Print versions of dirmngr and used libraries. This is used by
2490 * "gpgconf --show-versions" so that there is no need to link gpgconf
2491 * against all these libraries. This is an internal API and should
2492 * not be relied upon. */
2494 gpgconf_versions (void)
2499 /* Unfortunately Npth has no way to get the version. */
2501 s = get_revision_from_blurb (assuan_check_version ("\x01\x01"), &n);
2502 es_fprintf (es_stdout, "* Libassuan %s (%.*s)\n\n",
2503 assuan_check_version (NULL), n, s);
2505 s = get_revision_from_blurb (ksba_check_version ("\x01\x01"), &n);
2506 es_fprintf (es_stdout, "* KSBA %s (%.*s)\n\n",
2507 ksba_check_version (NULL), n, s);
2509 #ifdef HTTP_USE_NTBTLS
2510 s = get_revision_from_blurb (ntbtls_check_version ("\x01\x01"), &n);
2511 es_fprintf (es_stdout, "* NTBTLS %s (%.*s)\n\n",
2512 ntbtls_check_version (NULL), n, s);
2513 #elif HTTP_USE_GNUTLS
2514 es_fprintf (es_stdout, "* GNUTLS %s\n\n",
2515 gnutls_check_version (NULL));