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/init.h"
75 #include "../common/gc-opt-flags.h"
76 #include "dns-stuff.h"
77 #include "http-common.h"
80 # define ENAMETOOLONG EINVAL
84 enum cmd_and_opt_values {
147 oIgnoreCertExtension,
152 oDisableCheckOwnSocket,
157 oConnectQuickTimeout,
164 static ARGPARSE_OPTS opts[] = {
166 ARGPARSE_group (300, N_("@Commands:\n ")),
168 ARGPARSE_c (aServer, "server", N_("run in server mode (foreground)") ),
169 ARGPARSE_c (aDaemon, "daemon", N_("run in daemon mode (background)") ),
170 #ifndef HAVE_W32_SYSTEM
171 ARGPARSE_c (aSupervised, "supervised", N_("run in supervised mode")),
173 ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")),
174 ARGPARSE_c (aLoadCRL, "load-crl", N_("|FILE|load CRL from FILE into cache")),
175 ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")),
176 ARGPARSE_c (aShutdown, "shutdown", N_("shutdown the dirmngr")),
177 ARGPARSE_c (aFlush, "flush", N_("flush the cache")),
178 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
179 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
180 ARGPARSE_c (aGPGConfVersions, "gpgconf-versions", "@"),
182 ARGPARSE_group (301, N_("@\nOptions:\n ")),
184 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
185 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
186 ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
187 ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
188 ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")),
189 ARGPARSE_s_s (oDebugLevel, "debug-level",
190 N_("|LEVEL|set the debugging level to LEVEL")),
191 ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
192 ARGPARSE_s_n (oStealSocket, "steal-socket", "@"),
193 ARGPARSE_s_s (oLogFile, "log-file",
194 N_("|FILE|write server mode logs to FILE")),
195 ARGPARSE_s_n (oBatch, "batch", N_("run without asking a user")),
196 ARGPARSE_s_n (oForce, "force", N_("force loading of outdated CRLs")),
197 ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")),
198 ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check",
199 N_("allow online software version check")),
200 ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")),
201 ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")),
202 ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp",
203 N_("ignore HTTP CRL distribution points")),
204 ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp",
205 N_("ignore LDAP CRL distribution points")),
206 ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url",
207 N_("ignore certificate contained OCSP service URLs")),
209 ARGPARSE_s_s (oHTTPProxy, "http-proxy",
210 N_("|URL|redirect all HTTP requests to URL")),
211 ARGPARSE_s_s (oLDAPProxy, "ldap-proxy",
212 N_("|HOST|use HOST for LDAP queries")),
213 ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy",
214 N_("do not use fallback hosts with --ldap-proxy")),
216 ARGPARSE_s_s (oLDAPServer, "ldapserver",
217 N_("|SPEC|use this keyserver to lookup keys")),
218 ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file",
219 N_("|FILE|read LDAP server list from FILE")),
220 ARGPARSE_s_n (oLDAPAddServers, "add-servers",
221 N_("add new servers discovered in CRL distribution"
222 " points to serverlist")),
223 ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout",
224 N_("|N|set LDAP timeout to N seconds")),
226 ARGPARSE_s_s (oOCSPResponder, "ocsp-responder",
227 N_("|URL|use OCSP responder at URL")),
228 ARGPARSE_s_s (oOCSPSigner, "ocsp-signer",
229 N_("|FPR|OCSP response signed by FPR")),
230 ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"),
231 ARGPARSE_s_i (oOCSPMaxPeriod, "ocsp-max-period", "@"),
232 ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"),
234 ARGPARSE_s_i (oMaxReplies, "max-replies",
235 N_("|N|do not return more than N items in one query")),
237 ARGPARSE_s_s (oNameServer, "nameserver", "@"),
238 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
239 ARGPARSE_s_s (oHkpCaCert, "hkp-cacert",
240 N_("|FILE|use the CA certificates in FILE for HKP over TLS")),
242 ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")),
243 ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"),
245 ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"),
246 ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"),
248 ARGPARSE_s_s (oSocketName, "socket-name", "@"), /* Only for debugging. */
250 ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/
251 ARGPARSE_s_s (oDebug, "debug", "@"),
252 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
253 ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"),
254 ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"),
255 ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
256 ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
257 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
258 ARGPARSE_s_s (oHomedir, "homedir", "@"),
259 ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"),
260 ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"),
261 ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy", "@"),
262 ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"),
263 ARGPARSE_s_s (oIgnoreCert,"ignore-cert", "@"),
264 ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"),
265 ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"),
266 ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"),
267 ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"),
268 ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"),
269 ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
270 ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
272 ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing "
273 "of all commands and options)\n")),
278 /* The list of supported debug flags. */
279 static struct debug_flags_s debug_flags [] =
281 { DBG_X509_VALUE , "x509" },
282 { DBG_CRYPTO_VALUE , "crypto" },
283 { DBG_MEMORY_VALUE , "memory" },
284 { DBG_CACHE_VALUE , "cache" },
285 { DBG_MEMSTAT_VALUE, "memstat" },
286 { DBG_HASHING_VALUE, "hashing" },
287 { DBG_IPC_VALUE , "ipc" },
288 { DBG_DNS_VALUE , "dns" },
289 { DBG_NETWORK_VALUE, "network" },
290 { DBG_LOOKUP_VALUE , "lookup" },
291 { DBG_EXTPROG_VALUE, "extprog" },
292 { 77, NULL } /* 77 := Do not exit on "help" or "?". */
295 #define DEFAULT_MAX_REPLIES 10
296 #define DEFAULT_LDAP_TIMEOUT 15 /* seconds */
298 #define DEFAULT_CONNECT_TIMEOUT (15*1000) /* 15 seconds */
299 #define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000) /* 2 seconds */
301 /* For the cleanup handler we need to keep track of the socket's name. */
302 static const char *socket_name;
303 /* If the socket has been redirected, this is the name of the
304 redirected socket.. */
305 static const char *redir_socket_name;
307 /* We need to keep track of the server's nonces (these are dummies for
309 static assuan_sock_nonce_t socket_nonce;
311 /* Value for the listen() backlog argument.
312 * Change at runtime with --listen-backlog. */
313 static int listen_backlog = 64;
315 /* Only if this flag has been set will we remove the socket file. */
316 static int cleanup_socket;
318 /* Keep track of the current log file so that we can avoid updating
319 the log file after a SIGHUP if it didn't changed. Malloced. */
320 static char *current_logfile;
322 /* Helper to implement --debug-level. */
323 static const char *debug_level;
325 /* Helper to set the NTBTLS or GNUTLS log level. */
326 static int opt_gnutls_debug = -1;
328 /* Flag indicating that a shutdown has been requested. */
329 static volatile int shutdown_pending;
331 /* Flags to indicate that we shall not watch our own socket. */
332 static int disable_check_own_socket;
334 /* Flag indicating to start the daemon even if one already runs. */
335 static int steal_socket;
338 /* Flag to control the Tor mode. */
340 { TOR_MODE_AUTO = 0, /* Switch to NO or YES */
341 TOR_MODE_NEVER, /* Never use Tor. */
342 TOR_MODE_NO, /* Do not use Tor */
343 TOR_MODE_YES, /* Use Tor */
344 TOR_MODE_FORCE /* Force using Tor */
348 /* Counter for the active connections. */
349 static int active_connections;
351 /* This flag is set by any network access and used by the housekeeping
352 * thread to run background network tasks. */
353 static int network_activity_seen;
355 /* A list of filenames registred with --hkp-cacert. */
356 static strlist_t hkp_cacert_filenames;
358 /* A flag used to clear the list of ldapservers iff --ldapserver is
359 * given on the command line or one of the conf files. In this case we
360 * want to clear all old specifications through the legacy
361 * dirmngr_ldapservers.conf. */
362 static int ldapserver_list_needs_reset;
364 /* The timer tick used for housekeeping stuff. The second constant is used when a shutdown is pending. */
365 #define TIMERTICK_INTERVAL (60)
366 #define TIMERTICK_INTERVAL_SHUTDOWN (4)
368 /* How oft to run the housekeeping. */
369 #define HOUSEKEEPING_INTERVAL (600)
372 /* This union is used to avoid compiler warnings in case a pointer is
373 64 bit and an int 32 bit. We store an integer in a pointer and get
374 it back later (npth_getspecific et al.). */
384 /* The key used to store the current file descriptor in the thread
385 local storage. We use this in conjunction with the
386 log_set_pid_suffix_cb feature. */
387 #ifndef HAVE_W32_SYSTEM
388 static npth_key_t my_tlskey_current_fd;
392 static void cleanup (void);
394 static ldap_server_t parse_ldapserver_file (const char* filename, int ienoent);
396 static fingerprint_list_t parse_fingerprint_item (const char *string,
397 const char *optionname,
399 static void netactivity_action (void);
400 static void handle_connections (assuan_fd_t listen_fd);
401 static void gpgconf_versions (void);
404 /* NPth wrapper function definitions. */
405 ASSUAN_SYSTEM_NPTH_IMPL;
408 my_strusage( int level )
413 case 9: p = "GPL-3.0-or-later"; break;
414 case 11: p = "@DIRMNGR@ (@GNUPG@)";
416 case 13: p = VERSION; break;
417 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
418 case 17: p = PRINTABLE_OS_NAME; break;
419 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
420 reporting address. This is so that we can change the
421 reporting address without breaking the translations. */
422 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
423 case 49: p = PACKAGE_BUGREPORT; break;
425 case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)");
427 case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n"
428 "Keyserver, CRL, and OCSP access for @GNUPG@\n");
437 /* Callback from libksba to hash a provided buffer. Our current
438 implementation does only allow SHA-1 for hashing. This may be
439 extended by mapping the name, testing for algorithm availibility
440 and adjust the length checks accordingly. */
442 my_ksba_hash_buffer (void *arg, const char *oid,
443 const void *buffer, size_t length, size_t resultsize,
444 unsigned char *result, size_t *resultlen)
448 if (oid && strcmp (oid, "1.3.14.3.2.26"))
449 return gpg_error (GPG_ERR_NOT_SUPPORTED);
451 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
452 gcry_md_hash_buffer (2, result, buffer, length);
458 /* GNUTLS log function callback. */
459 #ifdef HTTP_USE_GNUTLS
461 my_gnutls_log (int level, const char *text)
466 while (n && text[n-1] == '\n')
469 log_debug ("gnutls:L%d: %.*s\n", level, n, text);
471 #endif /*HTTP_USE_GNUTLS*/
473 /* Setup the debugging. With a LEVEL of NULL only the active debug
474 flags are propagated to the subsystems. With LEVEL set, a specific
475 set of debug flags is set; thus overriding all flags already
480 int numok = (debug_level && digitp (debug_level));
481 int numlvl = numok? atoi (debug_level) : 0;
485 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
487 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
488 opt.debug = DBG_IPC_VALUE;
489 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
490 opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE);
491 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
492 opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE
493 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
494 else if (!strcmp (debug_level, "guru") || numok)
497 /* Unless the "guru" string has been used we don't want to allow
498 hashing debugging. The rationale is that people tend to
499 select the highest debug value and would then clutter their
500 disk with debug files which may reveal confidential data. */
502 opt.debug &= ~(DBG_HASHING_VALUE);
506 log_error (_("invalid debug-level '%s' given\n"), debug_level);
507 log_info (_("valid debug levels are: %s\n"),
508 "none, basic, advanced, expert, guru");
509 opt.debug = 0; /* Reset debugging, so that prior debug
510 statements won't have an undesired effect. */
514 if (opt.debug && !opt.verbose)
517 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
519 if (opt.debug && opt.quiet)
522 if (opt.debug & DBG_CRYPTO_VALUE )
523 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
526 if (opt_gnutls_debug >= 0)
528 ntbtls_set_debug (opt_gnutls_debug, NULL, NULL);
530 #elif HTTP_USE_GNUTLS
531 if (opt_gnutls_debug >= 0)
533 gnutls_global_set_log_function (my_gnutls_log);
534 gnutls_global_set_log_level (opt_gnutls_debug);
536 #endif /*HTTP_USE_GNUTLS*/
539 parse_debug_flag (NULL, &opt.debug, debug_flags);
546 if (dirmngr_use_tor ())
548 /* Enable Tor mode and when called again force a new curcuit
549 * (e.g. on SIGHUP). */
550 enable_dns_tormode (1);
551 if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
553 log_error ("error enabling Tor mode: %s\n", strerror (errno));
554 log_info ("(is your Libassuan recent enough?)\n");
558 disable_dns_tormode ();
562 /* Return true if Tor shall be used. */
564 dirmngr_use_tor (void)
566 if (tor_mode == TOR_MODE_AUTO)
568 /* Figure out whether Tor is running. */
571 sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR);
572 if (sock == ASSUAN_INVALID_FD)
573 tor_mode = TOR_MODE_NO;
576 tor_mode = TOR_MODE_YES;
577 assuan_sock_close (sock);
581 if (tor_mode == TOR_MODE_FORCE)
582 return 2; /* Use Tor (using 2 to indicate force mode) */
583 else if (tor_mode == TOR_MODE_YES)
584 return 1; /* Use Tor */
586 return 0; /* Do not use Tor. */
591 wrong_args (const char *text)
593 es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME);
594 es_fputs (text, es_stderr);
595 es_putc ('\n', es_stderr);
600 /* Helper to stop the reaper thread for the ldap wrapper. */
602 shutdown_reaper (void)
605 ldap_wrapper_wait_connections ();
610 /* Handle options which are allowed to be reset after program start.
611 Return true if the current option in PARGS could be handled and
612 false if not. As a special feature, passing a value of NULL for
613 PARGS, resets the options to the default. REREAD should be set
614 true if it is not the initial option parsing. */
616 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
623 opt.ldap_wrapper_program = NULL;
624 opt.disable_http = 0;
625 opt.disable_ldap = 0;
626 opt.honor_http_proxy = 0;
627 opt.http_proxy = NULL;
628 opt.ldap_proxy = NULL;
629 opt.only_ldap_proxy = 0;
630 opt.ignore_http_dp = 0;
631 opt.ignore_ldap_dp = 0;
632 opt.ignore_ocsp_service_url = 0;
634 opt.allow_version_check = 0;
635 opt.ocsp_responder = NULL;
636 opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */
637 opt.ocsp_max_period = 90 * 86400; /* 90 days. */
638 opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */
639 opt.max_replies = DEFAULT_MAX_REPLIES;
640 while (opt.ocsp_signer)
642 fingerprint_list_t tmp = opt.ocsp_signer->next;
643 xfree (opt.ocsp_signer);
644 opt.ocsp_signer = tmp;
646 while (opt.ignored_certs)
648 fingerprint_list_t tmp = opt.ignored_certs->next;
649 xfree (opt.ignored_certs);
650 opt.ignored_certs = tmp;
652 FREE_STRLIST (opt.ignored_cert_extensions);
653 http_register_tls_ca (NULL);
654 FREE_STRLIST (hkp_cacert_filenames);
655 FREE_STRLIST (opt.keyserver);
656 /* Note: We do not allow resetting of TOR_MODE_FORCE at runtime. */
657 if (tor_mode != TOR_MODE_FORCE)
658 tor_mode = TOR_MODE_AUTO;
659 disable_check_own_socket = 0;
660 enable_standard_resolver (0);
662 opt.connect_timeout = 0;
663 opt.connect_quick_timeout = 0;
664 opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
665 ldapserver_list_needs_reset = 1;
669 switch (pargs->r_opt)
671 case oQuiet: opt.quiet = 1; break;
672 case oVerbose: opt.verbose++; break;
674 parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
676 case oDebugAll: opt.debug = ~0; break;
677 case oDebugLevel: debug_level = pargs->r.ret_str; break;
678 case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break;
682 return 0; /* Not handled. */
683 if (!current_logfile || !pargs->r.ret_str
684 || strcmp (current_logfile, pargs->r.ret_str))
686 log_set_file (pargs->r.ret_str);
687 xfree (current_logfile);
688 current_logfile = xtrystrdup (pargs->r.ret_str);
692 case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
694 case oLDAPWrapperProgram:
695 opt.ldap_wrapper_program = pargs->r.ret_str;
697 case oHTTPWrapperProgram:
698 opt.http_wrapper_program = pargs->r.ret_str;
701 case oDisableHTTP: opt.disable_http = 1; break;
702 case oDisableLDAP: opt.disable_ldap = 1; break;
703 case oDisableIPv4: opt.disable_ipv4 = 1; break;
704 case oDisableIPv6: opt.disable_ipv6 = 1; break;
705 case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
706 case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
707 case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
708 case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
709 case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
710 case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
711 case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
713 case oAllowOCSP: opt.allow_ocsp = 1; break;
714 case oAllowVersionCheck: opt.allow_version_check = 1; break;
715 case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
717 opt.ocsp_signer = parse_fingerprint_item (pargs->r.ret_str,
720 case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
721 case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
722 case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
724 case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
728 /* We need to register the filenames with gnutls (http.c) and
729 * also for our own cert cache. */
732 /* Do tilde expansion and make path absolute. */
733 tmpname = make_absfilename (pargs->r.ret_str, NULL);
734 http_register_tls_ca (tmpname);
735 add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str);
742 fingerprint_list_t item, r;
743 item = parse_fingerprint_item (pargs->r.ret_str, "--ignore-cert", 20);
746 if (!opt.ignored_certs)
747 opt.ignored_certs = item;
750 for (r = opt.ignored_certs; r->next; r = r->next)
758 case oIgnoreCertExtension:
759 add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
763 tor_mode = TOR_MODE_FORCE;
766 if (tor_mode != TOR_MODE_FORCE)
767 tor_mode = TOR_MODE_NEVER;
770 case oStandardResolver: enable_standard_resolver (1); break;
771 case oRecursiveResolver: enable_recursive_resolver (1); break;
776 ldap_server_t server;
779 p = pargs->r.ret_str;
780 if (!strncmp (p, "ldap:", 5) && !(p[5] == '/' && p[6] == '/'))
783 server = ldapserver_parse_one (p, NULL, 0);
786 if (ldapserver_list_needs_reset)
788 ldapserver_list_needs_reset = 0;
789 ldapserver_list_free (opt.ldapservers);
790 opt.ldapservers = NULL;
792 server->next = opt.ldapservers;
793 opt.ldapservers = server;
800 if (*pargs->r.ret_str)
801 add_to_strlist (&opt.keyserver, pargs->r.ret_str);
805 set_dns_nameserver (pargs->r.ret_str);
808 case oResolverTimeout:
809 set_dns_timeout (pargs->r.ret_int);
812 case oConnectTimeout:
813 opt.connect_timeout = pargs->r.ret_ulong * 1000;
816 case oConnectQuickTimeout:
817 opt.connect_quick_timeout = pargs->r.ret_ulong * 1000;
821 opt.ldaptimeout = pargs->r.ret_int;
825 return 0; /* Not handled. */
828 set_dns_verbose (opt.verbose, !!DBG_DNS);
829 http_set_verbose (opt.verbose, !!DBG_NETWORK);
830 set_dns_disable_ipv4 (opt.disable_ipv4);
831 set_dns_disable_ipv6 (opt.disable_ipv6);
833 return 1; /* Handled. */
837 /* This fucntion is called after option parsing to adjust some values
838 * and call option setup functions. */
840 post_option_parsing (void)
842 /* It would be too surpirsing if the quick timeout is larger than
843 * the standard value. */
844 if (opt.connect_quick_timeout > opt.connect_timeout)
845 opt.connect_quick_timeout = opt.connect_timeout;
852 #ifndef HAVE_W32_SYSTEM
854 pid_suffix_callback (unsigned long *r_suffix)
856 union int_and_ptr_u value;
858 memset (&value, 0, sizeof value);
859 value.aptr = npth_getspecific (my_tlskey_current_fd);
860 *r_suffix = value.aint;
861 return (*r_suffix != -1); /* Use decimal representation. */
863 #endif /*!HAVE_W32_SYSTEM*/
867 my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv)
872 log_logv_with_prefix (GPGRT_LOG_INFO, "ntbtls: ", fmt, argv);
876 snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level);
877 log_logv_with_prefix (GPGRT_LOG_DEBUG, prefix, fmt, argv);
887 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
888 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
890 /* Now with NPth running we can set the logging callback. Our
891 windows implementation does not yet feature the NPth TLS
893 #ifndef HAVE_W32_SYSTEM
894 if (npth_key_create (&my_tlskey_current_fd, NULL) == 0)
895 if (npth_setspecific (my_tlskey_current_fd, NULL) == 0)
896 log_set_pid_suffix_cb (pid_suffix_callback);
897 #endif /*!HAVE_W32_SYSTEM*/
902 main (int argc, char **argv)
904 enum cmd_and_opt_values cmd = 0;
908 char *last_configname = NULL;
909 const char *configname = NULL;
911 int debug_argparser = 0;
916 char *logfile = NULL;
918 char *ldapfile = NULL;
922 struct assuan_malloc_hooks malloc_hooks;
924 early_system_init ();
925 set_strusage (my_strusage);
926 log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
928 /* Make sure that our subsystems are ready. */
930 init_common_subsystems (&argc, &argv);
932 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
934 /* Check that the libraries are suitable. Do it here because
935 the option parsing may need services of the libraries. */
936 if (!ksba_check_version (NEED_KSBA_VERSION) )
937 log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba",
938 NEED_KSBA_VERSION, ksba_check_version (NULL) );
940 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
941 ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
943 /* Init TLS library. */
945 if (!ntbtls_check_version (NEED_NTBTLS_VERSION) )
946 log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls",
947 NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) );
948 #elif HTTP_USE_GNUTLS
949 rc = gnutls_global_init ();
951 log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));
952 #endif /*HTTP_USE_GNUTLS*/
955 malloc_hooks.malloc = gcry_malloc;
956 malloc_hooks.realloc = gcry_realloc;
957 malloc_hooks.free = gcry_free;
958 assuan_set_malloc_hooks (&malloc_hooks);
959 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
960 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
962 setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor);
964 setup_libgcrypt_logging ();
967 ntbtls_set_log_handler (my_ntbtls_log_handler, NULL);
970 /* Setup defaults. */
971 shell = getenv ("SHELL");
972 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
975 /* Reset rereadable options to default values. */
976 parse_rereadable_options (NULL, 0);
978 /* Default TCP timeouts. */
979 opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT;
980 opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT;
983 opt.add_new_ldapservers = 0;
984 opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
986 /* Other defaults. */
988 /* Check whether we have a config file given on the commandline */
993 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
994 while (gnupg_argparse (NULL, &pargs, opts))
1003 gnupg_set_homedir (pargs.r.ret_str);
1007 /* Reset the flags. */
1008 pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1010 socket_name = dirmngr_socket_name ();
1012 /* The configuraton directories for use by gpgrt_argparser. */
1013 gnupg_set_confdir (GNUPG_CONFDIR_SYS, gnupg_sysconfdir ());
1014 gnupg_set_confdir (GNUPG_CONFDIR_USER, gnupg_homedir ());
1016 /* We are re-using the struct, thus the reset flag. We OR the
1017 * flags so that the internal intialized flag won't be cleared. */
1022 pargs.flags |= (ARGPARSE_FLAG_RESET
1023 | ARGPARSE_FLAG_KEEP
1025 | ARGPARSE_FLAG_USER);
1026 while (gnupg_argparser (&pargs, opts, DIRMNGR_NAME EXTSEP_S "conf"))
1028 if (pargs.r_opt == ARGPARSE_CONFFILE)
1030 if (debug_argparser)
1031 log_info (_("reading options from '%s'\n"),
1032 pargs.r_type? pargs.r.ret_str: "[cmdline]");
1035 xfree (last_configname);
1036 last_configname = xstrdup (pargs.r.ret_str);
1037 configname = last_configname;
1043 if (parse_rereadable_options (&pargs, 0))
1044 continue; /* Already handled */
1045 switch (pargs.r_opt)
1057 case aGPGConfVersions:
1061 case oQuiet: opt.quiet = 1; break;
1062 case oVerbose: opt.verbose++; break;
1063 case oBatch: opt.batch=1; break;
1065 case oDebugWait: debug_wait = pargs.r.ret_int; break;
1067 case oNoGreeting: nogreeting = 1; break;
1068 case oNoVerbose: opt.verbose = 0; break;
1069 case oHomedir: /* Ignore this option here. */; break;
1070 case oNoDetach: nodetach = 1; break;
1071 case oStealSocket: steal_socket = 1; break;
1072 case oLogFile: logfile = pargs.r.ret_str; break;
1073 case oCsh: csh_style = 1; break;
1074 case oSh: csh_style = 0; break;
1077 ldapfile = pargs.r.ret_str;
1078 # endif /*USE_LDAP*/
1080 case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
1082 case oFakedSystemTime:
1083 gnupg_set_time ((time_t)pargs.r.ret_ulong, 0);
1086 case oForce: opt.force = 1; break;
1088 case oSocketName: socket_name = pargs.r.ret_str; break;
1090 case oListenBacklog:
1091 listen_backlog = pargs.r.ret_int;
1096 pargs.err = ARGPARSE_PRINT_WARNING;
1098 pargs.err = ARGPARSE_PRINT_ERROR;
1102 gnupg_argparse (NULL, &pargs, NULL); /* Release internal state. */
1104 if (!last_configname)
1105 opt.config_filename = make_filename (gnupg_homedir (),
1106 DIRMNGR_NAME EXTSEP_S "conf",
1110 opt.config_filename = last_configname;
1111 last_configname = NULL;
1114 if (log_get_errorcount(0))
1119 if (!opt.homedir_cache)
1120 opt.homedir_cache = xstrdup (gnupg_homedir ());
1124 es_fprintf (es_stderr, "%s %s; %s\n",
1125 strusage(11), strusage(13), strusage(14) );
1126 es_fprintf (es_stderr, "%s\n", strusage(15) );
1129 #ifdef IS_DEVELOPMENT_VERSION
1130 log_info ("NOTE: this is a development version!\n");
1133 /* Print a warning if an argument looks like an option. */
1134 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1138 for (i=0; i < argc; i++)
1139 if (argv[i][0] == '-' && argv[i][1] == '-')
1140 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1143 if (!gnupg_access ("/etc/"DIRMNGR_NAME, F_OK)
1144 && !strncmp (gnupg_homedir (), "/etc/", 5))
1146 ("NOTE: DirMngr is now a proper part of %s. The configuration and"
1147 " other directory names changed. Please check that no other version"
1148 " of dirmngr is still installed. To disable this warning, remove the"
1149 " directory '/etc/dirmngr'.\n", GNUPG_NAME);
1151 if (gnupg_faked_time_p ())
1153 gnupg_isotime_t tbuf;
1155 log_info (_("WARNING: running with faked system time: "));
1156 gnupg_get_isotime (tbuf);
1157 dump_isotime (tbuf);
1161 post_option_parsing ();
1163 /* Get LDAP server list from file unless --ldapserver has been used. */
1165 if (opt.ldapservers)
1169 ldapfile = make_filename (gnupg_homedir (),
1170 "dirmngr_ldapservers.conf",
1172 opt.ldapservers = parse_ldapserver_file (ldapfile, 1);
1176 opt.ldapservers = parse_ldapserver_file (ldapfile, 0);
1179 #ifndef HAVE_W32_SYSTEM
1180 /* We need to ignore the PIPE signal because the we might log to a
1181 socket and that code handles EPIPE properly. The ldap wrapper
1182 also requires us to ignore this silly signal. Assuan would set
1183 this signal to ignore anyway.*/
1184 signal (SIGPIPE, SIG_IGN);
1187 /* Ready. Now to our duties. */
1194 /* Note that this server mode is mainly useful for debugging. */
1196 wrong_args ("--server");
1200 log_set_file (logfile);
1201 log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1206 log_debug ("waiting for debugger - my pid is %u .....\n",
1207 (unsigned int)getpid());
1208 gnupg_sleep (debug_wait);
1209 log_debug ("... okay\n");
1214 cert_cache_init (hkp_cacert_filenames);
1216 http_register_netactivity_cb (netactivity_action);
1217 start_command_handler (ASSUAN_INVALID_FD, 0);
1220 #ifndef HAVE_W32_SYSTEM
1221 else if (cmd == aSupervised)
1223 /* In supervised mode, we expect file descriptor 3 to be an
1224 already opened, listening socket.
1226 We will also not detach from the controlling process or close
1227 stderr; the supervisor should handle all of that. */
1228 struct stat statbuf;
1229 if (fstat (3, &statbuf) == -1 && errno == EBADF)
1231 log_error ("file descriptor 3 must be validin --supervised mode\n");
1234 socket_name = gnupg_get_socket_name (3);
1236 /* Now start with logging to a file if this is desired. */
1239 log_set_file (logfile);
1240 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1241 |GPGRT_LOG_WITH_TIME
1242 |GPGRT_LOG_WITH_PID));
1243 current_logfile = xstrdup (logfile);
1246 log_set_prefix (NULL, 0);
1249 cert_cache_init (hkp_cacert_filenames);
1251 http_register_netactivity_cb (netactivity_action);
1252 handle_connections (3);
1255 #endif /*HAVE_W32_SYSTEM*/
1256 else if (cmd == aDaemon)
1261 struct sockaddr_un serv_addr;
1264 wrong_args ("--daemon");
1266 /* Now start with logging to a file if this is desired. */
1269 log_set_file (logfile);
1270 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1271 |GPGRT_LOG_WITH_TIME
1272 |GPGRT_LOG_WITH_PID));
1273 current_logfile = xstrdup (logfile);
1278 log_debug ("waiting for debugger - my pid is %u .....\n",
1279 (unsigned int)getpid());
1280 gnupg_sleep (debug_wait);
1281 log_debug ("... okay\n");
1284 #ifndef HAVE_W32_SYSTEM
1285 if (strchr (socket_name, ':'))
1287 log_error (_("colons are not allowed in the socket name\n"));
1291 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1292 if (fd == ASSUAN_INVALID_FD)
1294 log_error (_("can't create socket: %s\n"), strerror (errno));
1302 if (assuan_sock_set_sockaddr_un (socket_name,
1303 (struct sockaddr*)&serv_addr,
1306 if (errno == ENAMETOOLONG)
1307 log_error (_("socket name '%s' is too long\n"), socket_name);
1309 log_error ("error preparing socket '%s': %s\n",
1311 gpg_strerror (gpg_error_from_syserror ()));
1316 redir_socket_name = xstrdup (serv_addr.sun_path);
1318 log_info ("redirecting socket '%s' to '%s'\n",
1319 socket_name, redir_socket_name);
1323 len = SUN_LEN (&serv_addr);
1325 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1327 && (errno == EADDRINUSE
1328 #ifdef HAVE_W32_SYSTEM
1333 /* Fixme: We should actually test whether a dirmngr is
1334 * already running. For now the steal option is a dummy. */
1335 /* if (steal_socket) */
1336 /* log_info (N_("trying to steal socket from running %s\n"), */
1338 gnupg_remove (redir_socket_name? redir_socket_name : socket_name);
1339 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1342 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
1343 log_error (_("error getting nonce for the socket\n"));
1346 log_error (_("error binding socket to '%s': %s\n"),
1348 gpg_strerror (gpg_error_from_syserror ()));
1349 assuan_sock_close (fd);
1354 if (gnupg_chmod (serv_addr.sun_path, "-rwx"))
1355 log_error (_("can't set permissions of '%s': %s\n"),
1356 serv_addr.sun_path, strerror (errno));
1358 if (listen (FD2INT (fd), listen_backlog) == -1)
1360 log_error ("listen(fd,%d) failed: %s\n",
1361 listen_backlog, strerror (errno));
1362 assuan_sock_close (fd);
1367 log_info (_("listening on socket '%s'\n"), serv_addr.sun_path);
1371 /* Note: We keep the dirmngr_info output only for the sake of
1372 existing scripts which might use this to detect a successful
1373 start of the dirmngr. */
1374 #ifdef HAVE_W32_SYSTEM
1379 es_printf ("set %s=%s;%lu;1\n",
1380 DIRMNGR_INFO_NAME, socket_name, (ulong) pid);
1383 if (pid == (pid_t)-1)
1385 log_fatal (_("error forking process: %s\n"), strerror (errno));
1390 { /* We are the parent */
1393 /* Don't let cleanup() remove the socket - the child is
1394 responsible for doing that. */
1399 /* Create the info string: <name>:<pid>:<protocol_version> */
1400 if (asprintf (&infostr, "%s=%s:%lu:1",
1401 DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0)
1403 log_error (_("out of core\n"));
1404 kill (pid, SIGTERM);
1407 /* Print the environment string, so that the caller can use
1408 shell's eval to set it. But see above. */
1411 *strchr (infostr, '=') = ' ';
1412 es_printf ( "setenv %s;\n", infostr);
1416 es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME);
1428 /* Detach from tty and put process into a new session */
1432 unsigned int oldflags;
1434 /* Close stdin, stdout and stderr unless it is the log stream */
1435 for (i=0; i <= 2; i++)
1437 if (!log_test_fd (i) && i != fd )
1440 && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1442 log_error ("failed to open '%s': %s\n",
1443 "/dev/null", strerror (errno));
1452 log_error ("setsid() failed: %s\n", strerror(errno) );
1456 log_get_prefix (&oldflags);
1457 log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1458 opt.running_detached = 1;
1465 if (gnupg_chdir (gnupg_daemon_rootdir ()))
1467 log_error ("chdir to '%s' failed: %s\n",
1468 gnupg_daemon_rootdir (), strerror (errno));
1474 cert_cache_init (hkp_cacert_filenames);
1476 http_register_netactivity_cb (netactivity_action);
1477 handle_connections (fd);
1480 else if (cmd == aListCRLs)
1482 /* Just list the CRL cache and exit. */
1484 wrong_args ("--list-crls");
1486 crl_cache_list (es_stdout);
1488 else if (cmd == aLoadCRL)
1490 struct server_control_s ctrlbuf;
1492 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1493 dirmngr_init_default_ctrl (&ctrlbuf);
1496 cert_cache_init (hkp_cacert_filenames);
1499 rc = crl_cache_load (&ctrlbuf, NULL);
1502 for (; !rc && argc; argc--, argv++)
1503 rc = crl_cache_load (&ctrlbuf, *argv);
1505 dirmngr_deinit_default_ctrl (&ctrlbuf);
1507 else if (cmd == aFetchCRL)
1509 ksba_reader_t reader;
1510 struct server_control_s ctrlbuf;
1513 wrong_args ("--fetch-crl URL");
1515 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1516 dirmngr_init_default_ctrl (&ctrlbuf);
1519 cert_cache_init (hkp_cacert_filenames);
1521 rc = crl_fetch (&ctrlbuf, argv[0], &reader);
1523 log_error (_("fetching CRL from '%s' failed: %s\n"),
1524 argv[0], gpg_strerror (rc));
1527 rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
1529 log_error (_("processing CRL from '%s' failed: %s\n"),
1530 argv[0], gpg_strerror (rc));
1531 crl_close_reader (reader);
1533 dirmngr_deinit_default_ctrl (&ctrlbuf);
1535 else if (cmd == aFlush)
1537 /* Delete cache and exit. */
1539 wrong_args ("--flush");
1540 rc = crl_cache_flush();
1542 else if (cmd == aGPGConfTest)
1544 else if (cmd == aGPGConfList)
1546 unsigned long flags = 0;
1550 filename = percent_escape (opt.config_filename, NULL);
1551 es_printf ("gpgconf-dirmngr.conf:%lu:\"%s\n",
1552 GC_OPT_FLAG_DEFAULT, filename);
1555 es_printf ("verbose:%lu:\n", flags | GC_OPT_FLAG_NONE);
1556 es_printf ("quiet:%lu:\n", flags | GC_OPT_FLAG_NONE);
1557 es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
1558 es_printf ("log-file:%lu:\n", flags | GC_OPT_FLAG_NONE);
1559 es_printf ("force:%lu:\n", flags | GC_OPT_FLAG_NONE);
1561 /* --csh and --sh are mutually exclusive, something we can not
1562 express in GPG Conf. --options is only usable from the
1563 command line, really. --debug-all interacts with --debug,
1564 and having both of them is thus problematic. --no-detach is
1565 also only usable on the command line. --batch is unused. */
1567 filename = make_filename (gnupg_homedir (),
1568 "dirmngr_ldapservers.conf",
1570 filename_esc = percent_escape (filename, NULL);
1571 es_printf ("ldapserverlist-file:%lu:\"%s\n", flags | GC_OPT_FLAG_DEFAULT,
1573 xfree (filename_esc);
1576 es_printf ("ldaptimeout:%lu:%u\n",
1577 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
1578 es_printf ("max-replies:%lu:%u\n",
1579 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
1580 es_printf ("allow-ocsp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1581 es_printf ("allow-version-check:%lu:\n", flags | GC_OPT_FLAG_NONE);
1582 es_printf ("ocsp-responder:%lu:\n", flags | GC_OPT_FLAG_NONE);
1583 es_printf ("ocsp-signer:%lu:\n", flags | GC_OPT_FLAG_NONE);
1585 es_printf ("faked-system-time:%lu:\n", flags | GC_OPT_FLAG_NONE);
1586 es_printf ("no-greeting:%lu:\n", flags | GC_OPT_FLAG_NONE);
1588 es_printf ("disable-http:%lu:\n", flags | GC_OPT_FLAG_NONE);
1589 es_printf ("disable-ldap:%lu:\n", flags | GC_OPT_FLAG_NONE);
1590 es_printf ("honor-http-proxy:%lu\n", flags | GC_OPT_FLAG_NONE);
1591 es_printf ("http-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1592 es_printf ("ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1593 es_printf ("only-ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1594 es_printf ("ignore-ldap-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1595 es_printf ("ignore-http-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1596 es_printf ("ignore-ocsp-service-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1597 /* Note: The next one is to fix a typo in gpgconf - should be
1598 removed eventually. */
1599 es_printf ("ignore-ocsp-servic-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1601 es_printf ("use-tor:%lu:\n", flags | GC_OPT_FLAG_NONE);
1603 filename_esc = percent_escape (get_default_keyserver (0), NULL);
1604 es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT,
1606 xfree (filename_esc);
1608 es_printf ("nameserver:%lu:\n", flags | GC_OPT_FLAG_NONE);
1609 es_printf ("resolver-timeout:%lu:%u\n",
1610 flags | GC_OPT_FLAG_DEFAULT, 0);
1612 else if (cmd == aGPGConfVersions)
1613 gpgconf_versions ();
1623 crl_cache_deinit ();
1624 cert_cache_deinit (1);
1625 reload_dns_stuff (1);
1628 ldapserver_list_free (opt.ldapservers);
1630 opt.ldapservers = NULL;
1635 if (redir_socket_name)
1636 gnupg_remove (redir_socket_name);
1637 else if (socket_name && *socket_name)
1638 gnupg_remove (socket_name);
1644 dirmngr_exit (int rc)
1652 dirmngr_init_default_ctrl (ctrl_t ctrl)
1654 ctrl->magic = SERVER_CONTROL_MAGIC;
1656 ctrl->http_proxy = xstrdup (opt.http_proxy);
1657 ctrl->http_no_crl = 1;
1658 ctrl->timeout = opt.connect_timeout;
1663 dirmngr_deinit_default_ctrl (ctrl_t ctrl)
1667 ctrl->magic = 0xdeadbeef;
1669 xfree (ctrl->http_proxy);
1670 ctrl->http_proxy = NULL;
1674 /* Create a list of LDAP servers from the file FILENAME. Returns the
1675 list or NULL in case of errors.
1677 The format fo such a file is line oriented where empty lines and
1678 lines starting with a hash mark are ignored. All other lines are
1679 assumed to be colon seprated with these fields:
1682 2. field: Portnumber
1689 static ldap_server_t
1690 parse_ldapserver_file (const char* filename, int ignore_enoent)
1694 ldap_server_t server, serverstart, *serverend;
1696 unsigned int lineno = 0;
1699 fp = es_fopen (filename, "r");
1702 if (errno == ENOENT)
1705 log_info ("No ldapserver file at: '%s'\n", filename);
1708 log_error (_("error opening '%s': %s\n"), filename,
1714 serverend = &serverstart;
1715 while (es_fgets (buffer, sizeof buffer, fp))
1718 if (!*buffer || buffer[strlen(buffer)-1] != '\n')
1720 if (*buffer && es_feof (fp))
1721 ; /* Last line not terminated - continue. */
1724 log_error (_("%s:%u: line too long - skipped\n"),
1726 while ( (c=es_fgetc (fp)) != EOF && c != '\n')
1727 ; /* Skip until end of line. */
1731 /* Skip empty and comment lines.*/
1732 for (p=buffer; spacep (p); p++)
1734 if (!*p || *p == '\n' || *p == '#')
1737 /* Parse the colon separated fields. */
1738 server = ldapserver_parse_one (buffer, filename, lineno);
1741 *serverend = server;
1742 serverend = &server->next;
1747 log_error (_("error reading '%s': %s\n"), filename, strerror (errno));
1755 /* Parse a fingerprint entry as used by --ocsc-signer. OPTIONNAME as
1756 * a description on the options used. WANT_BINARY requests to store a
1757 * binary fingerprint. Returns NULL on error and logs that error. */
1758 static fingerprint_list_t
1759 parse_fingerprint_item (const char *string,
1760 const char *optionname, int want_binary)
1767 fingerprint_list_t list, *list_tail, item;
1768 unsigned int lnr = 0;
1773 /* Check whether this is not a filename and treat it as a direct
1774 fingerprint specification. */
1775 if (!strpbrk (string, "/.~\\"))
1777 item = xcalloc (1, sizeof *item);
1778 for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
1779 if ( string[i] != ':' )
1780 item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
1781 item->hexfpr[j] = 0;
1782 if (j != 40 || !(spacep (string+i) || !string[i]))
1784 log_error (_("%s:%u: invalid fingerprint detected\n"),
1792 hex2bin (item->hexfpr, item->hexfpr, 20);
1797 /* Well, it is a filename. */
1798 if (*string == '/' || (*string == '~' && string[1] == '/'))
1799 fname = make_filename (string, NULL);
1802 if (string[0] == '.' && string[1] == '/' )
1804 fname = make_filename (gnupg_homedir (), string, NULL);
1807 fp = es_fopen (fname, "r");
1810 err = gpg_error_from_syserror ();
1811 log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
1820 if (!es_fgets (line, DIM(line)-1, fp) )
1824 err = gpg_error_from_syserror ();
1825 log_error (_("%s:%u: read error: %s\n"),
1826 fname, lnr, gpg_strerror (err));
1834 fingerprint_list_t tmp = list->next;
1840 return list; /* Ready. */
1844 if (!*line || line[strlen(line)-1] != '\n')
1846 /* Eat until end of line. */
1847 while ( (c=es_getc (fp)) != EOF && c != '\n')
1849 err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
1850 /* */: GPG_ERR_INCOMPLETE_LINE);
1851 log_error (_("%s:%u: read error: %s\n"),
1852 fname, lnr, gpg_strerror (err));
1857 /* Allow for empty lines and spaces */
1858 for (p=line; spacep (p); p++)
1860 if (!*p || *p == '\n' || *p == '#')
1863 item = xcalloc (1, sizeof *item);
1865 list_tail = &item->next;
1867 for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
1869 item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
1870 item->hexfpr[j] = 0;
1871 if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
1873 log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
1876 else if (want_binary)
1879 hex2bin (item->hexfpr, item->hexfpr, 20);
1883 while (spacep (p+i))
1885 if (p[i] && p[i] != '\n')
1886 log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
1895 Stuff used in daemon mode.
1900 /* Reread parts of the configuration. Note, that this function is
1901 obviously not thread-safe and should only be called from the NPTH
1904 Fixme: Due to the way the argument parsing works, we create a
1905 memory leak here for all string type arguments. There is currently
1906 no clean way to tell whether the memory for the argument has been
1907 allocated or points into the process' original arguments. Unless
1908 we have a mechanism to tell this, we need to live on with this. */
1910 reread_configuration (void)
1912 ARGPARSE_ARGS pargs;
1916 if (!opt.config_filename)
1917 return; /* No config file. */
1919 twopart = strconcat (DIRMNGR_NAME EXTSEP_S "conf" PATHSEP_S,
1920 opt.config_filename, NULL);
1922 return; /* Out of core. */
1924 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1926 memset (&pargs, 0, sizeof pargs);
1928 pargs.argc = &dummy;
1929 pargs.flags = (ARGPARSE_FLAG_KEEP
1931 |ARGPARSE_FLAG_USER);
1932 while (gnupg_argparser (&pargs, opts, twopart))
1934 if (pargs.r_opt == ARGPARSE_CONFFILE)
1936 log_info (_("reading options from '%s'\n"),
1937 pargs.r_type? pargs.r.ret_str: "[cmdline]");
1939 else if (pargs.r_opt < -1)
1940 pargs.err = ARGPARSE_PRINT_WARNING;
1941 else /* Try to parse this option - ignore unchangeable ones. */
1942 parse_rereadable_options (&pargs, 1);
1944 gnupg_argparse (NULL, &pargs, NULL); /* Release internal state. */
1946 post_option_parsing ();
1950 /* A global function which allows us to trigger the reload stuff from
1953 dirmngr_sighup_action (void)
1955 log_info (_("SIGHUP received - "
1956 "re-reading configuration and flushing caches\n"));
1957 reread_configuration ();
1958 cert_cache_deinit (0);
1959 crl_cache_deinit ();
1960 cert_cache_init (hkp_cacert_filenames);
1962 reload_dns_stuff (0);
1967 /* This function is called if some network activity was done. At this
1968 * point we know the we have a network and we can decide whether to
1969 * run scheduled background tasks soon. The function should return
1970 * quickly and only trigger actions for another thread. */
1972 netactivity_action (void)
1974 network_activity_seen = 1;
1978 /* The signal handler. */
1979 #ifndef HAVE_W32_SYSTEM
1981 handle_signal (int signo)
1986 dirmngr_sighup_action ();
1990 cert_cache_print_stats ();
1991 domaininfo_print_stats ();
1995 log_info (_("SIGUSR2 received - no action defined\n"));
1999 if (!shutdown_pending)
2000 log_info (_("SIGTERM received - shutting down ...\n"));
2002 log_info (_("SIGTERM received - still %d active connections\n"),
2003 active_connections);
2005 if (shutdown_pending > 2)
2007 log_info (_("shutdown forced\n"));
2008 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
2015 log_info (_("SIGINT received - immediate shutdown\n"));
2016 log_info( "%s %s stopped\n", strusage(11), strusage(13));
2022 log_info (_("signal %d received - no action defined\n"), signo);
2025 #endif /*!HAVE_W32_SYSTEM*/
2028 /* Thread to do the housekeeping. */
2030 housekeeping_thread (void *arg)
2032 static int sentinel;
2034 struct server_control_s ctrlbuf;
2038 curtime = gnupg_get_time ();
2041 log_info ("housekeeping is already going on\n");
2045 if (opt.verbose > 1)
2046 log_info ("starting housekeeping\n");
2048 memset (&ctrlbuf, 0, sizeof ctrlbuf);
2049 dirmngr_init_default_ctrl (&ctrlbuf);
2051 dns_stuff_housekeeping ();
2052 ks_hkp_housekeeping (curtime);
2053 if (network_activity_seen)
2055 network_activity_seen = 0;
2056 if (opt.allow_version_check)
2057 dirmngr_load_swdb (&ctrlbuf, 0);
2058 workqueue_run_global_tasks (&ctrlbuf, 1);
2061 workqueue_run_global_tasks (&ctrlbuf, 0);
2063 dirmngr_deinit_default_ctrl (&ctrlbuf);
2065 if (opt.verbose > 1)
2066 log_info ("ready with housekeeping\n");
2073 #if GPGRT_GCC_HAVE_PUSH_PRAGMA
2074 # pragma GCC push_options
2075 # pragma GCC optimize ("no-strict-overflow")
2078 time_for_housekeeping_p (time_t curtime)
2080 static time_t last_housekeeping;
2082 if (!last_housekeeping)
2083 last_housekeeping = curtime;
2085 if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime
2086 || last_housekeeping > curtime /*(be prepared for y2038)*/)
2088 last_housekeeping = curtime;
2093 #if GPGRT_GCC_HAVE_PUSH_PRAGMA
2094 # pragma GCC pop_options
2098 /* This is the worker for the ticker. It is called every few seconds
2099 and may only do fast operations. */
2103 struct stat statbuf;
2105 if (time_for_housekeeping_p (gnupg_get_time ()))
2111 err = npth_attr_init (&tattr);
2113 log_error ("error preparing housekeeping thread: %s\n", strerror (err));
2116 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2117 err = npth_create (&thread, &tattr, housekeeping_thread, NULL);
2119 log_error ("error spawning housekeeping thread: %s\n",
2121 npth_attr_destroy (&tattr);
2125 /* Check whether the homedir is still available. */
2126 if (!shutdown_pending
2127 && gnupg_stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
2129 shutdown_pending = 1;
2130 log_info ("homedir has been removed - shutting down\n");
2135 /* Check the nonce on a new connection. This is a NOP unless we are
2136 using our Unix domain socket emulation under Windows. */
2138 check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
2140 if (assuan_sock_check_nonce (fd, nonce))
2142 log_info (_("error reading nonce on fd %d: %s\n"),
2143 FD2INT (fd), strerror (errno));
2144 assuan_sock_close (fd);
2152 /* Helper to call a connection's main function. */
2154 start_connection_thread (void *arg)
2156 static unsigned int last_session_id;
2157 unsigned int session_id;
2158 union int_and_ptr_u argval;
2161 memset (&argval, 0, sizeof argval);
2165 if (check_nonce (fd, &socket_nonce))
2167 log_error ("handler nonce check FAILED\n");
2171 #ifndef HAVE_W32_SYSTEM
2172 npth_setspecific (my_tlskey_current_fd, argval.aptr);
2175 active_connections++;
2177 log_info (_("handler for fd %d started\n"), FD2INT (fd));
2179 session_id = ++last_session_id;
2181 session_id = ++last_session_id;
2182 start_command_handler (fd, session_id);
2185 log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
2186 active_connections--;
2188 workqueue_run_post_session_tasks (session_id);
2190 #ifndef HAVE_W32_SYSTEM
2191 argval.afd = ASSUAN_INVALID_FD;
2192 npth_setspecific (my_tlskey_current_fd, argval.aptr);
2199 #ifdef HAVE_INOTIFY_INIT
2200 /* Read an inotify event and return true if it matches NAME. */
2202 my_inotify_is_name (int fd, const char *name)
2205 struct inotify_event ev;
2206 char _buf[sizeof (struct inotify_event) + 100 + 1];
2211 s = strrchr (name, '/');
2215 n = npth_read (fd, &buf, sizeof buf);
2216 if (n < sizeof (struct inotify_event))
2218 if (buf.ev.len < strlen (name)+1)
2220 if (strcmp (buf.ev.name, name))
2221 return 0; /* Not the desired file. */
2223 return 1; /* Found. */
2225 #endif /*HAVE_INOTIFY_INIT*/
2228 /* Main loop in daemon mode. Note that LISTEN_FD will be owned by
2231 handle_connections (assuan_fd_t listen_fd)
2234 #ifndef HAVE_W32_SYSTEM
2237 struct sockaddr_un paddr;
2238 socklen_t plen = sizeof( paddr );
2240 fd_set fdset, read_fdset;
2241 struct timespec abstime;
2242 struct timespec curtime;
2243 struct timespec timeout;
2245 int my_inotify_fd = -1;
2247 npth_attr_init (&tattr);
2248 npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2250 #ifndef HAVE_W32_SYSTEM /* FIXME */
2252 npth_sigev_add (SIGHUP);
2253 npth_sigev_add (SIGUSR1);
2254 npth_sigev_add (SIGUSR2);
2255 npth_sigev_add (SIGINT);
2256 npth_sigev_add (SIGTERM);
2260 #ifdef HAVE_INOTIFY_INIT
2261 if (disable_check_own_socket)
2263 else if ((my_inotify_fd = inotify_init ()) == -1)
2264 log_info ("error enabling fast daemon termination: %s\n",
2268 /* We need to watch the directory for the file because there
2269 * won't be an IN_DELETE_SELF for a socket file. */
2270 char *slash = strrchr (socket_name, '/');
2271 log_assert (slash && slash[1]);
2273 if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1)
2275 close (my_inotify_fd);
2280 #endif /*HAVE_INOTIFY_INIT*/
2283 /* Setup the fdset. It has only one member. This is because we use
2284 pth_select instead of pth_accept to properly sync timeouts with
2287 FD_SET (FD2INT (listen_fd), &fdset);
2288 nfd = FD2INT (listen_fd);
2289 if (my_inotify_fd != -1)
2291 FD_SET (my_inotify_fd, &fdset);
2292 if (my_inotify_fd > nfd)
2293 nfd = my_inotify_fd;
2296 npth_clock_gettime (&abstime);
2297 abstime.tv_sec += TIMERTICK_INTERVAL;
2302 /* Shutdown test. */
2303 if (shutdown_pending)
2305 if (!active_connections)
2308 /* Do not accept new connections but keep on running the
2309 * loop to cope with the timer events.
2311 * Note that we do not close the listening socket because a
2312 * client trying to connect to that socket would instead
2313 * restart a new dirmngr instance - which is unlikely the
2314 * intention of a shutdown. */
2315 /* assuan_sock_close (listen_fd); */
2316 /* listen_fd = -1; */
2319 if (my_inotify_fd != -1)
2321 FD_SET (my_inotify_fd, &fdset);
2322 nfd = my_inotify_fd;
2326 /* Take a copy of the fdset. */
2329 npth_clock_gettime (&curtime);
2330 if (!(npth_timercmp (&curtime, &abstime, <)))
2332 /* Timeout. When a shutdown is pending we use a shorter
2333 * interval to handle the shutdown more quickly. */
2335 npth_clock_gettime (&abstime);
2336 abstime.tv_sec += (shutdown_pending
2337 ? TIMERTICK_INTERVAL_SHUTDOWN
2338 : TIMERTICK_INTERVAL);
2340 npth_timersub (&abstime, &curtime, &timeout);
2342 #ifndef HAVE_W32_SYSTEM
2343 ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2344 npth_sigev_sigmask());
2345 saved_errno = errno;
2347 while (npth_sigev_get_pending(&signo))
2348 handle_signal (signo);
2350 ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
2351 saved_errno = errno;
2354 if (ret == -1 && saved_errno != EINTR)
2356 log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2357 strerror (saved_errno));
2364 /* Interrupt or timeout. Will be handled when calculating the
2369 if (shutdown_pending)
2371 /* Do not anymore accept connections. */
2375 #ifdef HAVE_INOTIFY_INIT
2376 if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset)
2377 && my_inotify_is_name (my_inotify_fd, socket_name))
2379 shutdown_pending = 1;
2380 log_info ("socket file has been removed - shutting down\n");
2382 #endif /*HAVE_INOTIFY_INIT*/
2384 if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
2388 plen = sizeof paddr;
2389 fd = INT2FD (npth_accept (FD2INT(listen_fd),
2390 (struct sockaddr *)&paddr, &plen));
2391 if (fd == GNUPG_INVALID_FD)
2393 log_error ("accept failed: %s\n", strerror (errno));
2397 char threadname[50];
2398 union int_and_ptr_u argval;
2401 memset (&argval, 0, sizeof argval);
2403 snprintf (threadname, sizeof threadname,
2404 "conn fd=%d", FD2INT(fd));
2406 ret = npth_create (&thread, &tattr,
2407 start_connection_thread, argval.aptr);
2410 log_error ("error spawning connection handler: %s\n",
2412 assuan_sock_close (fd);
2414 npth_setname_np (thread, threadname);
2419 #ifdef HAVE_INOTIFY_INIT
2420 if (my_inotify_fd != -1)
2421 close (my_inotify_fd);
2422 #endif /*HAVE_INOTIFY_INIT*/
2423 npth_attr_destroy (&tattr);
2424 if (listen_fd != GNUPG_INVALID_FD)
2425 assuan_sock_close (listen_fd);
2427 log_info ("%s %s stopped\n", strusage(11), strusage(13));
2431 dirmngr_get_current_socket_name (void)
2436 return dirmngr_socket_name ();
2441 /* Parse the revision part from the extended version blurb. */
2443 get_revision_from_blurb (const char *blurb, int *r_len)
2445 const char *s = blurb? blurb : "";
2449 if (*s == '\n' && s[1] == '(')
2454 for (n=0; s[n] && s[n] != ' '; n++)
2467 /* Print versions of dirmngr and used libraries. This is used by
2468 * "gpgconf --show-versions" so that there is no need to link gpgconf
2469 * against all these libraries. This is an internal API and should
2470 * not be relied upon. */
2472 gpgconf_versions (void)
2477 /* Unfortunately Npth has no way to get the version. */
2479 s = get_revision_from_blurb (assuan_check_version ("\x01\x01"), &n);
2480 es_fprintf (es_stdout, "* Libassuan %s (%.*s)\n\n",
2481 assuan_check_version (NULL), n, s);
2483 s = get_revision_from_blurb (ksba_check_version ("\x01\x01"), &n);
2484 es_fprintf (es_stdout, "* KSBA %s (%.*s)\n\n",
2485 ksba_check_version (NULL), n, s);
2487 #ifdef HTTP_USE_NTBTLS
2488 s = get_revision_from_blurb (ntbtls_check_version ("\x01\x01"), &n);
2489 es_fprintf (es_stdout, "* NTBTLS %s (%.*s)\n\n",
2490 ntbtls_check_version (NULL), n, s);
2491 #elif HTTP_USE_GNUTLS
2492 es_fprintf (es_stdout, "* GNUTLS %s\n\n",
2493 gnutls_check_version (NULL));