diff --git a/dirmngr/dirmngr.c b/dirmngr/dirmngr.c index 667308cc7..4f7f4be32 100644 --- a/dirmngr/dirmngr.c +++ b/dirmngr/dirmngr.c @@ -1,2344 +1,2341 @@ /* dirmngr.c - Keyserver and X.509 LDAP access * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2010, 2011 g10 Code GmbH * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * * SPDX-License-Identifier: GPL-3.0+ */ #include #include #include #include #include #include #include #include #include #include #ifndef HAVE_W32_SYSTEM #include #include #endif #include #include #ifdef HAVE_SIGNAL_H # include #endif #ifdef HAVE_INOTIFY_INIT # include #endif /*HAVE_INOTIFY_INIT*/ #include #include "dirmngr-err.h" #if HTTP_USE_NTBTLS # include #elif HTTP_USE_GNUTLS # include #endif /*HTTP_USE_GNUTLS*/ #define GNUPG_COMMON_NEED_AFLOCAL #include "dirmngr.h" #include #include "certcache.h" #include "crlcache.h" #include "crlfetch.h" #include "misc.h" #if USE_LDAP # include "ldapserver.h" #endif #include "../common/asshelp.h" #if USE_LDAP # include "ldap-wrapper.h" #endif #include "../common/init.h" #include "../common/gc-opt-flags.h" #include "dns-stuff.h" #include "http-common.h" #ifndef ENAMETOOLONG # define ENAMETOOLONG EINVAL #endif enum cmd_and_opt_values { aNull = 0, oCsh = 'c', oQuiet = 'q', oSh = 's', oVerbose = 'v', oNoVerbose = 500, aServer, aDaemon, aSupervised, aListCRLs, aLoadCRL, aFetchCRL, aShutdown, aFlush, aGPGConfList, aGPGConfTest, oOptions, oDebug, oDebugAll, oDebugWait, oDebugLevel, oGnutlsDebug, oNoGreeting, oNoOptions, oHomedir, oNoDetach, oLogFile, oBatch, oDisableHTTP, oDisableLDAP, oDisableIPv4, oDisableIPv6, oIgnoreLDAPDP, oIgnoreHTTPDP, oIgnoreOCSPSvcUrl, oHonorHTTPProxy, oHTTPProxy, oLDAPProxy, oOnlyLDAPProxy, oLDAPFile, oLDAPTimeout, oLDAPAddServers, oOCSPResponder, oOCSPSigner, oOCSPMaxClockSkew, oOCSPMaxPeriod, oOCSPCurrentPeriod, oMaxReplies, oHkpCaCert, oFakedSystemTime, oForce, oAllowOCSP, oAllowVersionCheck, oSocketName, oLDAPWrapperProgram, oHTTPWrapperProgram, oIgnoreCertExtension, oUseTor, oNoUseTor, oKeyServer, oNameServer, oDisableCheckOwnSocket, oStandardResolver, oRecursiveResolver, oResolverTimeout, oConnectTimeout, oConnectQuickTimeout, oListenBacklog, aTest }; static ARGPARSE_OPTS opts[] = { ARGPARSE_group (300, N_("@Commands:\n ")), ARGPARSE_c (aServer, "server", N_("run in server mode (foreground)") ), ARGPARSE_c (aDaemon, "daemon", N_("run in daemon mode (background)") ), #ifndef HAVE_W32_SYSTEM ARGPARSE_c (aSupervised, "supervised", N_("run in supervised mode")), #endif ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")), ARGPARSE_c (aLoadCRL, "load-crl", N_("|FILE|load CRL from FILE into cache")), ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")), ARGPARSE_c (aShutdown, "shutdown", N_("shutdown the dirmngr")), ARGPARSE_c (aFlush, "flush", N_("flush the cache")), ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"), ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"), ARGPARSE_group (301, N_("@\nOptions:\n ")), ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")), ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")), ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")), ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")), ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")), ARGPARSE_s_s (oDebugLevel, "debug-level", N_("|LEVEL|set the debugging level to LEVEL")), ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")), ARGPARSE_s_s (oLogFile, "log-file", N_("|FILE|write server mode logs to FILE")), ARGPARSE_s_n (oBatch, "batch", N_("run without asking a user")), ARGPARSE_s_n (oForce, "force", N_("force loading of outdated CRLs")), ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")), ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check", N_("allow online software version check")), ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")), ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")), ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp", N_("ignore HTTP CRL distribution points")), ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp", N_("ignore LDAP CRL distribution points")), ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url", N_("ignore certificate contained OCSP service URLs")), ARGPARSE_s_s (oHTTPProxy, "http-proxy", N_("|URL|redirect all HTTP requests to URL")), ARGPARSE_s_s (oLDAPProxy, "ldap-proxy", N_("|HOST|use HOST for LDAP queries")), ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy", N_("do not use fallback hosts with --ldap-proxy")), ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file", N_("|FILE|read LDAP server list from FILE")), ARGPARSE_s_n (oLDAPAddServers, "add-servers", N_("add new servers discovered in CRL distribution" " points to serverlist")), ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout", N_("|N|set LDAP timeout to N seconds")), ARGPARSE_s_s (oOCSPResponder, "ocsp-responder", N_("|URL|use OCSP responder at URL")), ARGPARSE_s_s (oOCSPSigner, "ocsp-signer", N_("|FPR|OCSP response signed by FPR")), ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"), ARGPARSE_s_i (oOCSPMaxPeriod, "ocsp-max-period", "@"), ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"), ARGPARSE_s_i (oMaxReplies, "max-replies", N_("|N|do not return more than N items in one query")), ARGPARSE_s_s (oNameServer, "nameserver", "@"), ARGPARSE_s_s (oKeyServer, "keyserver", "@"), ARGPARSE_s_s (oHkpCaCert, "hkp-cacert", N_("|FILE|use the CA certificates in FILE for HKP over TLS")), ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")), ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"), ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"), ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"), ARGPARSE_s_s (oSocketName, "socket-name", "@"), /* Only for debugging. */ ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/ ARGPARSE_s_s (oDebug, "debug", "@"), ARGPARSE_s_n (oDebugAll, "debug-all", "@"), ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"), ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"), ARGPARSE_s_i (oDebugWait, "debug-wait", "@"), ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"), ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"), ARGPARSE_s_s (oHomedir, "homedir", "@"), ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"), ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"), ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy", "@"), ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"), ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"), ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"), ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"), ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"), ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"), ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"), ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing " "of all commands and options)\n")), ARGPARSE_end () }; /* The list of supported debug flags. */ static struct debug_flags_s debug_flags [] = { { DBG_X509_VALUE , "x509" }, { DBG_CRYPTO_VALUE , "crypto" }, { DBG_MEMORY_VALUE , "memory" }, { DBG_CACHE_VALUE , "cache" }, { DBG_MEMSTAT_VALUE, "memstat" }, { DBG_HASHING_VALUE, "hashing" }, { DBG_IPC_VALUE , "ipc" }, { DBG_DNS_VALUE , "dns" }, { DBG_NETWORK_VALUE, "network" }, { DBG_LOOKUP_VALUE , "lookup" }, { DBG_EXTPROG_VALUE, "extprog" }, { 77, NULL } /* 77 := Do not exit on "help" or "?". */ }; #define DEFAULT_MAX_REPLIES 10 #define DEFAULT_LDAP_TIMEOUT 15 /* seconds */ #define DEFAULT_CONNECT_TIMEOUT (15*1000) /* 15 seconds */ #define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000) /* 2 seconds */ /* For the cleanup handler we need to keep track of the socket's name. */ static const char *socket_name; /* If the socket has been redirected, this is the name of the redirected socket.. */ static const char *redir_socket_name; /* We need to keep track of the server's nonces (these are dummies for POSIX systems). */ static assuan_sock_nonce_t socket_nonce; /* Value for the listen() backlog argument. * Change at runtime with --listen-backlog. */ static int listen_backlog = 64; /* Only if this flag has been set will we remove the socket file. */ static int cleanup_socket; /* Keep track of the current log file so that we can avoid updating the log file after a SIGHUP if it didn't changed. Malloced. */ static char *current_logfile; /* Helper to implement --debug-level. */ static const char *debug_level; /* Helper to set the NTBTLS or GNUTLS log level. */ static int opt_gnutls_debug = -1; /* Flag indicating that a shutdown has been requested. */ static volatile int shutdown_pending; /* Flags to indicate that we shall not watch our own socket. */ static int disable_check_own_socket; /* Flag to control the Tor mode. */ static enum { TOR_MODE_AUTO = 0, /* Switch to NO or YES */ TOR_MODE_NEVER, /* Never use Tor. */ TOR_MODE_NO, /* Do not use Tor */ TOR_MODE_YES, /* Use Tor */ TOR_MODE_FORCE /* Force using Tor */ } tor_mode; /* Counter for the active connections. */ static int active_connections; /* This flag is set by any network access and used by the housekeeping * thread to run background network tasks. */ static int network_activity_seen; /* A list of filenames registred with --hkp-cacert. */ static strlist_t hkp_cacert_filenames; /* The timer tick used for housekeeping stuff. The second constant is used when a shutdown is pending. */ #define TIMERTICK_INTERVAL (60) #define TIMERTICK_INTERVAL_SHUTDOWN (4) /* How oft to run the housekeeping. */ #define HOUSEKEEPING_INTERVAL (600) /* This union is used to avoid compiler warnings in case a pointer is 64 bit and an int 32 bit. We store an integer in a pointer and get it back later (npth_getspecific et al.). */ union int_and_ptr_u { int aint; assuan_fd_t afd; void *aptr; }; /* The key used to store the current file descriptor in the thread local storage. We use this in conjunction with the log_set_pid_suffix_cb feature. */ #ifndef HAVE_W32_SYSTEM static npth_key_t my_tlskey_current_fd; #endif /* Prototypes. */ static void cleanup (void); #if USE_LDAP static ldap_server_t parse_ldapserver_file (const char* filename); #endif /*USE_LDAP*/ static fingerprint_list_t parse_ocsp_signer (const char *string); static void netactivity_action (void); static void handle_connections (assuan_fd_t listen_fd); /* NPth wrapper function definitions. */ ASSUAN_SYSTEM_NPTH_IMPL; static const char * my_strusage( int level ) { const char *p; switch ( level ) { case 11: p = "@DIRMNGR@ (@GNUPG@)"; break; case 13: p = VERSION; break; case 17: p = PRINTABLE_OS_NAME; break; /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug reporting address. This is so that we can change the reporting address without breaking the translations. */ case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break; case 49: p = PACKAGE_BUGREPORT; break; case 1: case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)"); break; case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n" "Keyserver, CRL, and OCSP access for @GNUPG@\n"); break; default: p = NULL; } return p; } /* Callback from libksba to hash a provided buffer. Our current implementation does only allow SHA-1 for hashing. This may be extended by mapping the name, testing for algorithm availibility and adjust the length checks accordingly. */ static gpg_error_t my_ksba_hash_buffer (void *arg, const char *oid, const void *buffer, size_t length, size_t resultsize, unsigned char *result, size_t *resultlen) { (void)arg; if (oid && strcmp (oid, "1.3.14.3.2.26")) return gpg_error (GPG_ERR_NOT_SUPPORTED); if (resultsize < 20) return gpg_error (GPG_ERR_BUFFER_TOO_SHORT); gcry_md_hash_buffer (2, result, buffer, length); *resultlen = 20; return 0; } /* GNUTLS log function callback. */ #ifdef HTTP_USE_GNUTLS static void my_gnutls_log (int level, const char *text) { int n; n = strlen (text); while (n && text[n-1] == '\n') n--; log_debug ("gnutls:L%d: %.*s\n", level, n, text); } #endif /*HTTP_USE_GNUTLS*/ /* Setup the debugging. With a LEVEL of NULL only the active debug flags are propagated to the subsystems. With LEVEL set, a specific set of debug flags is set; thus overriding all flags already set. */ static void set_debug (void) { int numok = (debug_level && digitp (debug_level)); int numlvl = numok? atoi (debug_level) : 0; if (!debug_level) ; else if (!strcmp (debug_level, "none") || (numok && numlvl < 1)) opt.debug = 0; else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2)) opt.debug = DBG_IPC_VALUE; else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5)) opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE); else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8)) opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE); else if (!strcmp (debug_level, "guru") || numok) { opt.debug = ~0; /* Unless the "guru" string has been used we don't want to allow hashing debugging. The rationale is that people tend to select the highest debug value and would then clutter their disk with debug files which may reveal confidential data. */ if (numok) opt.debug &= ~(DBG_HASHING_VALUE); } else { log_error (_("invalid debug-level '%s' given\n"), debug_level); log_info (_("valid debug levels are: %s\n"), "none, basic, advanced, expert, guru"); opt.debug = 0; /* Reset debugging, so that prior debug statements won't have an undesired effect. */ } if (opt.debug && !opt.verbose) { opt.verbose = 1; gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose); } if (opt.debug && opt.quiet) opt.quiet = 0; if (opt.debug & DBG_CRYPTO_VALUE ) gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1); #if HTTP_USE_NTBTLS if (opt_gnutls_debug >= 0) { ntbtls_set_debug (opt_gnutls_debug, NULL, NULL); } #elif HTTP_USE_GNUTLS if (opt_gnutls_debug >= 0) { gnutls_global_set_log_function (my_gnutls_log); gnutls_global_set_log_level (opt_gnutls_debug); } #endif /*HTTP_USE_GNUTLS*/ if (opt.debug) parse_debug_flag (NULL, &opt.debug, debug_flags); } static void set_tor_mode (void) { if (dirmngr_use_tor ()) { /* Enable Tor mode and when called again force a new curcuit * (e.g. on SIGHUP). */ enable_dns_tormode (1); if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1)) { log_error ("error enabling Tor mode: %s\n", strerror (errno)); log_info ("(is your Libassuan recent enough?)\n"); } } else disable_dns_tormode (); } /* Return true if Tor shall be used. */ int dirmngr_use_tor (void) { if (tor_mode == TOR_MODE_AUTO) { /* Figure out whether Tor is running. */ assuan_fd_t sock; sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR); if (sock == ASSUAN_INVALID_FD) tor_mode = TOR_MODE_NO; else { tor_mode = TOR_MODE_YES; assuan_sock_close (sock); } } if (tor_mode == TOR_MODE_FORCE) return 2; /* Use Tor (using 2 to indicate force mode) */ else if (tor_mode == TOR_MODE_YES) return 1; /* Use Tor */ else return 0; /* Do not use Tor. */ } static void wrong_args (const char *text) { es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME); es_fputs (text, es_stderr); es_putc ('\n', es_stderr); dirmngr_exit (2); } /* Helper to stop the reaper thread for the ldap wrapper. */ static void shutdown_reaper (void) { #if USE_LDAP ldap_wrapper_wait_connections (); #endif } /* Handle options which are allowed to be reset after program start. Return true if the current option in PARGS could be handled and false if not. As a special feature, passing a value of NULL for PARGS, resets the options to the default. REREAD should be set true if it is not the initial option parsing. */ static int parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread) { if (!pargs) { /* Reset mode. */ opt.quiet = 0; opt.verbose = 0; opt.debug = 0; opt.ldap_wrapper_program = NULL; opt.disable_http = 0; opt.disable_ldap = 0; opt.honor_http_proxy = 0; opt.http_proxy = NULL; opt.ldap_proxy = NULL; opt.only_ldap_proxy = 0; opt.ignore_http_dp = 0; opt.ignore_ldap_dp = 0; opt.ignore_ocsp_service_url = 0; opt.allow_ocsp = 0; opt.allow_version_check = 0; opt.ocsp_responder = NULL; opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */ opt.ocsp_max_period = 90 * 86400; /* 90 days. */ opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */ opt.max_replies = DEFAULT_MAX_REPLIES; while (opt.ocsp_signer) { fingerprint_list_t tmp = opt.ocsp_signer->next; xfree (opt.ocsp_signer); opt.ocsp_signer = tmp; } FREE_STRLIST (opt.ignored_cert_extensions); http_register_tls_ca (NULL); FREE_STRLIST (hkp_cacert_filenames); FREE_STRLIST (opt.keyserver); /* Note: We do not allow resetting of TOR_MODE_FORCE at runtime. */ if (tor_mode != TOR_MODE_FORCE) tor_mode = TOR_MODE_AUTO; disable_check_own_socket = 0; enable_standard_resolver (0); set_dns_timeout (0); opt.connect_timeout = 0; opt.connect_quick_timeout = 0; return 1; } switch (pargs->r_opt) { case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oDebug: parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags); break; case oDebugAll: opt.debug = ~0; break; case oDebugLevel: debug_level = pargs->r.ret_str; break; case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break; case oLogFile: if (!reread) return 0; /* Not handled. */ if (!current_logfile || !pargs->r.ret_str || strcmp (current_logfile, pargs->r.ret_str)) { log_set_file (pargs->r.ret_str); xfree (current_logfile); current_logfile = xtrystrdup (pargs->r.ret_str); } break; case oDisableCheckOwnSocket: disable_check_own_socket = 1; break; case oLDAPWrapperProgram: opt.ldap_wrapper_program = pargs->r.ret_str; break; case oHTTPWrapperProgram: opt.http_wrapper_program = pargs->r.ret_str; break; case oDisableHTTP: opt.disable_http = 1; break; case oDisableLDAP: opt.disable_ldap = 1; break; case oDisableIPv4: opt.disable_ipv4 = 1; break; case oDisableIPv6: opt.disable_ipv6 = 1; break; case oHonorHTTPProxy: opt.honor_http_proxy = 1; break; case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break; case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break; case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break; case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break; case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break; case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break; case oAllowOCSP: opt.allow_ocsp = 1; break; case oAllowVersionCheck: opt.allow_version_check = 1; break; case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break; case oOCSPSigner: opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str); break; case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break; case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break; case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break; case oMaxReplies: opt.max_replies = pargs->r.ret_int; break; case oHkpCaCert: { /* We need to register the filenames with gnutls (http.c) and * also for our own cert cache. */ char *tmpname; /* Do tilde expansion and make path absolute. */ tmpname = make_absfilename (pargs->r.ret_str, NULL); http_register_tls_ca (tmpname); add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str); xfree (tmpname); } break; case oIgnoreCertExtension: add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str); break; case oUseTor: tor_mode = TOR_MODE_FORCE; break; case oNoUseTor: if (tor_mode != TOR_MODE_FORCE) tor_mode = TOR_MODE_NEVER; break; case oStandardResolver: enable_standard_resolver (1); break; case oRecursiveResolver: enable_recursive_resolver (1); break; case oKeyServer: if (*pargs->r.ret_str) add_to_strlist (&opt.keyserver, pargs->r.ret_str); break; case oNameServer: set_dns_nameserver (pargs->r.ret_str); break; case oResolverTimeout: set_dns_timeout (pargs->r.ret_int); break; case oConnectTimeout: opt.connect_timeout = pargs->r.ret_ulong * 1000; break; case oConnectQuickTimeout: opt.connect_quick_timeout = pargs->r.ret_ulong * 1000; break; default: return 0; /* Not handled. */ } set_dns_verbose (opt.verbose, !!DBG_DNS); http_set_verbose (opt.verbose, !!DBG_NETWORK); set_dns_disable_ipv4 (opt.disable_ipv4); set_dns_disable_ipv6 (opt.disable_ipv6); return 1; /* Handled. */ } /* This fucntion is called after option parsing to adjust some values * and call option setup functions. */ static void post_option_parsing (void) { /* It would be too surpirsing if the quick timeout is larger than * the standard value. */ if (opt.connect_quick_timeout > opt.connect_timeout) opt.connect_quick_timeout = opt.connect_timeout; set_debug (); set_tor_mode (); } #ifndef HAVE_W32_SYSTEM static int pid_suffix_callback (unsigned long *r_suffix) { union int_and_ptr_u value; memset (&value, 0, sizeof value); value.aptr = npth_getspecific (my_tlskey_current_fd); *r_suffix = value.aint; return (*r_suffix != -1); /* Use decimal representation. */ } #endif /*!HAVE_W32_SYSTEM*/ #if HTTP_USE_NTBTLS static void my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv) { (void)opaque; if (level == -1) log_logv_with_prefix (GPGRT_LOG_INFO, "ntbtls: ", fmt, argv); else { char prefix[10+20]; snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level); log_logv_with_prefix (GPGRT_LOG_DEBUG, prefix, fmt, argv); } } #endif static void thread_init (void) { npth_init (); assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH); gpgrt_set_syscall_clamp (npth_unprotect, npth_protect); /* Now with NPth running we can set the logging callback. Our windows implementation does not yet feature the NPth TLS functions. */ #ifndef HAVE_W32_SYSTEM if (npth_key_create (&my_tlskey_current_fd, NULL) == 0) if (npth_setspecific (my_tlskey_current_fd, NULL) == 0) log_set_pid_suffix_cb (pid_suffix_callback); #endif /*!HAVE_W32_SYSTEM*/ } int main (int argc, char **argv) { enum cmd_and_opt_values cmd = 0; ARGPARSE_ARGS pargs; int orig_argc; char **orig_argv; FILE *configfp = NULL; char *configname = NULL; const char *shell; unsigned configlineno; int parse_debug = 0; int default_config =1; int greeting = 0; int nogreeting = 0; int nodetach = 0; int csh_style = 0; char *logfile = NULL; #if USE_LDAP char *ldapfile = NULL; #endif /*USE_LDAP*/ int debug_wait = 0; int rc; struct assuan_malloc_hooks malloc_hooks; early_system_init (); set_strusage (my_strusage); log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID); /* Make sure that our subsystems are ready. */ i18n_init (); init_common_subsystems (&argc, &argv); gcry_control (GCRYCTL_DISABLE_SECMEM, 0); /* Check that the libraries are suitable. Do it here because the option parsing may need services of the libraries. */ if (!ksba_check_version (NEED_KSBA_VERSION) ) log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba", NEED_KSBA_VERSION, ksba_check_version (NULL) ); ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free ); ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL); /* Init TLS library. */ #if HTTP_USE_NTBTLS if (!ntbtls_check_version (NEED_NTBTLS_VERSION) ) log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls", NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) ); #elif HTTP_USE_GNUTLS rc = gnutls_global_init (); if (rc) log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc)); #endif /*HTTP_USE_GNUTLS*/ /* Init Assuan. */ malloc_hooks.malloc = gcry_malloc; malloc_hooks.realloc = gcry_realloc; malloc_hooks.free = gcry_free; assuan_set_malloc_hooks (&malloc_hooks); assuan_set_assuan_log_prefix (log_get_prefix (NULL)); assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT); assuan_sock_init (); setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor); setup_libgcrypt_logging (); #if HTTP_USE_NTBTLS ntbtls_set_log_handler (my_ntbtls_log_handler, NULL); #endif /* Setup defaults. */ shell = getenv ("SHELL"); if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") ) csh_style = 1; /* Reset rereadable options to default values. */ parse_rereadable_options (NULL, 0); /* Default TCP timeouts. */ opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT; opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT; /* LDAP defaults. */ opt.add_new_ldapservers = 0; opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT; /* Other defaults. */ /* Check whether we have a config file given on the commandline */ orig_argc = argc; orig_argv = argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */ while (arg_parse( &pargs, opts)) { if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll) parse_debug++; else if (pargs.r_opt == oOptions) { /* Yes there is one, so we do not try the default one, but read the option file when it is encountered at the commandline */ default_config = 0; } else if (pargs.r_opt == oNoOptions) default_config = 0; /* --no-options */ else if (pargs.r_opt == oHomedir) { gnupg_set_homedir (pargs.r.ret_str); } } socket_name = dirmngr_socket_name (); if (default_config) configname = make_filename (gnupg_homedir (), DIRMNGR_NAME".conf", NULL ); argc = orig_argc; argv = orig_argv; pargs.argc = &argc; pargs.argv = &argv; pargs.flags= 1; /* do not remove the args */ next_pass: if (configname) { configlineno = 0; configfp = fopen (configname, "r"); if (!configfp) { if (default_config) { if( parse_debug ) log_info (_("Note: no default option file '%s'\n"), configname ); } else { log_error (_("option file '%s': %s\n"), configname, strerror(errno) ); exit(2); } xfree (configname); configname = NULL; } if (parse_debug && configname ) log_info (_("reading options from '%s'\n"), configname ); default_config = 0; } while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) ) { if (parse_rereadable_options (&pargs, 0)) continue; /* Already handled */ switch (pargs.r_opt) { case aServer: case aDaemon: case aSupervised: case aShutdown: case aFlush: case aListCRLs: case aLoadCRL: case aFetchCRL: case aGPGConfList: case aGPGConfTest: cmd = pargs.r_opt; break; case oQuiet: opt.quiet = 1; break; case oVerbose: opt.verbose++; break; case oBatch: opt.batch=1; break; case oDebugWait: debug_wait = pargs.r.ret_int; break; case oOptions: /* Config files may not be nested (silently ignore them) */ if (!configfp) { xfree(configname); configname = xstrdup(pargs.r.ret_str); goto next_pass; } break; case oNoGreeting: nogreeting = 1; break; case oNoVerbose: opt.verbose = 0; break; case oNoOptions: break; /* no-options */ case oHomedir: /* Ignore this option here. */; break; case oNoDetach: nodetach = 1; break; case oLogFile: logfile = pargs.r.ret_str; break; case oCsh: csh_style = 1; break; case oSh: csh_style = 0; break; case oLDAPFile: # if USE_LDAP ldapfile = pargs.r.ret_str; # endif /*USE_LDAP*/ break; case oLDAPAddServers: opt.add_new_ldapservers = 1; break; case oLDAPTimeout: opt.ldaptimeout = pargs.r.ret_int; break; case oFakedSystemTime: gnupg_set_time ((time_t)pargs.r.ret_ulong, 0); break; case oForce: opt.force = 1; break; case oSocketName: socket_name = pargs.r.ret_str; break; case oListenBacklog: listen_backlog = pargs.r.ret_int; break; default : pargs.err = configfp? 1:2; break; } } if (configfp) { fclose (configfp); configfp = NULL; /* Keep a copy of the name so that it can be read on SIGHUP. */ opt.config_filename = configname; configname = NULL; goto next_pass; } xfree (configname); configname = NULL; if (log_get_errorcount(0)) exit(2); if (nogreeting ) greeting = 0; if (!opt.homedir_cache) opt.homedir_cache = xstrdup (gnupg_homedir ()); if (greeting) { es_fprintf (es_stderr, "%s %s; %s\n", strusage(11), strusage(13), strusage(14) ); es_fprintf (es_stderr, "%s\n", strusage(15) ); } #ifdef IS_DEVELOPMENT_VERSION log_info ("NOTE: this is a development version!\n"); #endif /* Print a warning if an argument looks like an option. */ if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN)) { int i; for (i=0; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == '-') log_info (_("Note: '%s' is not considered an option\n"), argv[i]); } if (!access ("/etc/"DIRMNGR_NAME, F_OK) && !strncmp (gnupg_homedir (), "/etc/", 5)) log_info ("NOTE: DirMngr is now a proper part of %s. The configuration and" " other directory names changed. Please check that no other version" " of dirmngr is still installed. To disable this warning, remove the" " directory '/etc/dirmngr'.\n", GNUPG_NAME); if (gnupg_faked_time_p ()) { gnupg_isotime_t tbuf; log_info (_("WARNING: running with faked system time: ")); gnupg_get_isotime (tbuf); dump_isotime (tbuf); log_printf ("\n"); } post_option_parsing (); /* Get LDAP server list from file. */ #if USE_LDAP if (!ldapfile) { ldapfile = make_filename (gnupg_homedir (), "dirmngr_ldapservers.conf", NULL); opt.ldapservers = parse_ldapserver_file (ldapfile); xfree (ldapfile); } else opt.ldapservers = parse_ldapserver_file (ldapfile); #endif /*USE_LDAP*/ #ifndef HAVE_W32_SYSTEM /* We need to ignore the PIPE signal because the we might log to a socket and that code handles EPIPE properly. The ldap wrapper also requires us to ignore this silly signal. Assuan would set this signal to ignore anyway.*/ signal (SIGPIPE, SIG_IGN); #endif /* Ready. Now to our duties. */ if (!cmd) cmd = aServer; rc = 0; if (cmd == aServer) { /* Note that this server mode is mainly useful for debugging. */ if (argc) wrong_args ("--server"); if (logfile) { log_set_file (logfile); log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID); } if (debug_wait) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); http_register_netactivity_cb (netactivity_action); start_command_handler (ASSUAN_INVALID_FD, 0); shutdown_reaper (); } #ifndef HAVE_W32_SYSTEM else if (cmd == aSupervised) { /* In supervised mode, we expect file descriptor 3 to be an already opened, listening socket. We will also not detach from the controlling process or close stderr; the supervisor should handle all of that. */ struct stat statbuf; if (fstat (3, &statbuf) == -1 && errno == EBADF) { log_error ("file descriptor 3 must be validin --supervised mode\n"); dirmngr_exit (1); } socket_name = gnupg_get_socket_name (3); /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX |GPGRT_LOG_WITH_TIME |GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } else log_set_prefix (NULL, 0); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); http_register_netactivity_cb (netactivity_action); handle_connections (3); shutdown_reaper (); } #endif /*HAVE_W32_SYSTEM*/ else if (cmd == aDaemon) { assuan_fd_t fd; pid_t pid; int len; struct sockaddr_un serv_addr; if (argc) wrong_args ("--daemon"); /* Now start with logging to a file if this is desired. */ if (logfile) { log_set_file (logfile); log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX |GPGRT_LOG_WITH_TIME |GPGRT_LOG_WITH_PID)); current_logfile = xstrdup (logfile); } if (debug_wait) { log_debug ("waiting for debugger - my pid is %u .....\n", (unsigned int)getpid()); gnupg_sleep (debug_wait); log_debug ("... okay\n"); } #ifndef HAVE_W32_SYSTEM if (strchr (socket_name, ':')) { log_error (_("colons are not allowed in the socket name\n")); dirmngr_exit (1); } #endif fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0); if (fd == ASSUAN_INVALID_FD) { log_error (_("can't create socket: %s\n"), strerror (errno)); cleanup (); dirmngr_exit (1); } { int redirected; if (assuan_sock_set_sockaddr_un (socket_name, (struct sockaddr*)&serv_addr, &redirected)) { if (errno == ENAMETOOLONG) log_error (_("socket name '%s' is too long\n"), socket_name); else log_error ("error preparing socket '%s': %s\n", socket_name, gpg_strerror (gpg_error_from_syserror ())); dirmngr_exit (1); } if (redirected) { redir_socket_name = xstrdup (serv_addr.sun_path); if (opt.verbose) log_info ("redirecting socket '%s' to '%s'\n", socket_name, redir_socket_name); } } len = SUN_LEN (&serv_addr); rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len); if (rc == -1 && (errno == EADDRINUSE #ifdef HAVE_W32_SYSTEM || errno == EEXIST #endif )) { /* Fixme: We should test whether a dirmngr is already running. */ gnupg_remove (redir_socket_name? redir_socket_name : socket_name); rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len); } if (rc != -1 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce))) log_error (_("error getting nonce for the socket\n")); if (rc == -1) { log_error (_("error binding socket to '%s': %s\n"), serv_addr.sun_path, gpg_strerror (gpg_error_from_errno (errno))); assuan_sock_close (fd); dirmngr_exit (1); } cleanup_socket = 1; if (gnupg_chmod (serv_addr.sun_path, "-rwx")) log_error (_("can't set permissions of '%s': %s\n"), serv_addr.sun_path, strerror (errno)); if (listen (FD2INT (fd), listen_backlog) == -1) { log_error ("listen(fd,%d) failed: %s\n", listen_backlog, strerror (errno)); assuan_sock_close (fd); dirmngr_exit (1); } if (opt.verbose) log_info (_("listening on socket '%s'\n"), serv_addr.sun_path); es_fflush (NULL); /* Note: We keep the dirmngr_info output only for the sake of existing scripts which might use this to detect a successful start of the dirmngr. */ #ifdef HAVE_W32_SYSTEM (void)csh_style; (void)nodetach; pid = getpid (); es_printf ("set %s=%s;%lu;1\n", DIRMNGR_INFO_NAME, socket_name, (ulong) pid); #else pid = fork(); if (pid == (pid_t)-1) { log_fatal (_("error forking process: %s\n"), strerror (errno)); dirmngr_exit (1); } if (pid) { /* We are the parent */ char *infostr; /* Don't let cleanup() remove the socket - the child is responsible for doing that. */ cleanup_socket = 0; close (fd); /* Create the info string: :: */ if (asprintf (&infostr, "%s=%s:%lu:1", DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0) { log_error (_("out of core\n")); kill (pid, SIGTERM); dirmngr_exit (1); } /* Print the environment string, so that the caller can use shell's eval to set it. But see above. */ if (csh_style) { *strchr (infostr, '=') = ' '; es_printf ( "setenv %s;\n", infostr); } else { es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME); } free (infostr); exit (0); /*NEVER REACHED*/ } /* end parent */ /* This is the child */ /* Detach from tty and put process into a new session */ if (!nodetach ) { int i; unsigned int oldflags; /* Close stdin, stdout and stderr unless it is the log stream */ for (i=0; i <= 2; i++) { if (!log_test_fd (i) && i != fd ) { if ( !close (i) && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1) { log_error ("failed to open '%s': %s\n", "/dev/null", strerror (errno)); cleanup (); dirmngr_exit (1); } } } if (setsid() == -1) { log_error ("setsid() failed: %s\n", strerror(errno) ); dirmngr_exit (1); } log_get_prefix (&oldflags); log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED); opt.running_detached = 1; } #endif if (!nodetach ) { if (gnupg_chdir (gnupg_daemon_rootdir ())) { log_error ("chdir to '%s' failed: %s\n", gnupg_daemon_rootdir (), strerror (errno)); dirmngr_exit (1); } } thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); http_register_netactivity_cb (netactivity_action); handle_connections (fd); shutdown_reaper (); } else if (cmd == aListCRLs) { /* Just list the CRL cache and exit. */ if (argc) wrong_args ("--list-crls"); crl_cache_init (); crl_cache_list (es_stdout); } else if (cmd == aLoadCRL) { struct server_control_s ctrlbuf; memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); if (!argc) rc = crl_cache_load (&ctrlbuf, NULL); else { for (; !rc && argc; argc--, argv++) rc = crl_cache_load (&ctrlbuf, *argv); } dirmngr_deinit_default_ctrl (&ctrlbuf); } else if (cmd == aFetchCRL) { ksba_reader_t reader; struct server_control_s ctrlbuf; if (argc != 1) wrong_args ("--fetch-crl URL"); memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); thread_init (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); rc = crl_fetch (&ctrlbuf, argv[0], &reader); if (rc) log_error (_("fetching CRL from '%s' failed: %s\n"), argv[0], gpg_strerror (rc)); else { rc = crl_cache_insert (&ctrlbuf, argv[0], reader); if (rc) log_error (_("processing CRL from '%s' failed: %s\n"), argv[0], gpg_strerror (rc)); crl_close_reader (reader); } dirmngr_deinit_default_ctrl (&ctrlbuf); } else if (cmd == aFlush) { /* Delete cache and exit. */ if (argc) wrong_args ("--flush"); rc = crl_cache_flush(); } else if (cmd == aGPGConfTest) dirmngr_exit (0); else if (cmd == aGPGConfList) { unsigned long flags = 0; char *filename; char *filename_esc; /* First the configuration file. This is not an option, but it is vital information for GPG Conf. */ if (!opt.config_filename) opt.config_filename = make_filename (gnupg_homedir (), "dirmngr.conf", NULL ); filename = percent_escape (opt.config_filename, NULL); es_printf ("gpgconf-dirmngr.conf:%lu:\"%s\n", GC_OPT_FLAG_DEFAULT, filename); xfree (filename); es_printf ("verbose:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("quiet:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT); es_printf ("log-file:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("force:%lu:\n", flags | GC_OPT_FLAG_NONE); /* --csh and --sh are mutually exclusive, something we can not express in GPG Conf. --options is only usable from the command line, really. --debug-all interacts with --debug, and having both of them is thus problematic. --no-detach is also only usable on the command line. --batch is unused. */ filename = make_filename (gnupg_homedir (), "dirmngr_ldapservers.conf", NULL); filename_esc = percent_escape (filename, NULL); es_printf ("ldapserverlist-file:%lu:\"%s\n", flags | GC_OPT_FLAG_DEFAULT, filename_esc); xfree (filename_esc); xfree (filename); es_printf ("ldaptimeout:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT); es_printf ("max-replies:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES); es_printf ("allow-ocsp:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("allow-version-check:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ocsp-responder:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ocsp-signer:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("faked-system-time:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("no-greeting:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("disable-http:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("disable-ldap:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("honor-http-proxy:%lu\n", flags | GC_OPT_FLAG_NONE); es_printf ("http-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("only-ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ignore-ldap-dp:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ignore-http-dp:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("ignore-ocsp-service-url:%lu:\n", flags | GC_OPT_FLAG_NONE); /* Note: The next one is to fix a typo in gpgconf - should be removed eventually. */ es_printf ("ignore-ocsp-servic-url:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("use-tor:%lu:\n", flags | GC_OPT_FLAG_NONE); filename_esc = percent_escape (get_default_keyserver (0), NULL); es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT, filename_esc); xfree (filename_esc); es_printf ("nameserver:%lu:\n", flags | GC_OPT_FLAG_NONE); es_printf ("resolver-timeout:%lu:%u\n", flags | GC_OPT_FLAG_DEFAULT, 0); } cleanup (); return !!rc; } static void cleanup (void) { crl_cache_deinit (); cert_cache_deinit (1); reload_dns_stuff (1); #if USE_LDAP ldapserver_list_free (opt.ldapservers); #endif /*USE_LDAP*/ opt.ldapservers = NULL; if (cleanup_socket) { cleanup_socket = 0; if (redir_socket_name) gnupg_remove (redir_socket_name); else if (socket_name && *socket_name) gnupg_remove (socket_name); } } void dirmngr_exit (int rc) { cleanup (); exit (rc); } void dirmngr_init_default_ctrl (ctrl_t ctrl) { ctrl->magic = SERVER_CONTROL_MAGIC; if (opt.http_proxy) ctrl->http_proxy = xstrdup (opt.http_proxy); ctrl->http_no_crl = 1; ctrl->timeout = opt.connect_timeout; } void dirmngr_deinit_default_ctrl (ctrl_t ctrl) { if (!ctrl) return; ctrl->magic = 0xdeadbeef; xfree (ctrl->http_proxy); ctrl->http_proxy = NULL; } /* Create a list of LDAP servers from the file FILENAME. Returns the list or NULL in case of errors. The format fo such a file is line oriented where empty lines and lines starting with a hash mark are ignored. All other lines are assumed to be colon seprated with these fields: 1. field: Hostname 2. field: Portnumber 3. field: Username 4. field: Password 5. field: Base DN */ #if USE_LDAP static ldap_server_t parse_ldapserver_file (const char* filename) { char buffer[1024]; char *p; ldap_server_t server, serverstart, *serverend; int c; unsigned int lineno = 0; estream_t fp; fp = es_fopen (filename, "r"); if (!fp) { if (errno == ENOENT) log_info ("No ldapserver file at: '%s'\n", filename); else log_error (_("error opening '%s': %s\n"), filename, strerror (errno)); return NULL; } serverstart = NULL; serverend = &serverstart; while (es_fgets (buffer, sizeof buffer, fp)) { lineno++; if (!*buffer || buffer[strlen(buffer)-1] != '\n') { if (*buffer && es_feof (fp)) ; /* Last line not terminated - continue. */ else { log_error (_("%s:%u: line too long - skipped\n"), filename, lineno); while ( (c=es_fgetc (fp)) != EOF && c != '\n') ; /* Skip until end of line. */ continue; } } /* Skip empty and comment lines.*/ for (p=buffer; spacep (p); p++) ; if (!*p || *p == '\n' || *p == '#') continue; /* Parse the colon separated fields. */ server = ldapserver_parse_one (buffer, filename, lineno); if (server) { *serverend = server; serverend = &server->next; } } if (es_ferror (fp)) log_error (_("error reading '%s': %s\n"), filename, strerror (errno)); es_fclose (fp); return serverstart; } #endif /*USE_LDAP*/ static fingerprint_list_t parse_ocsp_signer (const char *string) { gpg_error_t err; char *fname; estream_t fp; char line[256]; char *p; fingerprint_list_t list, *list_tail, item; unsigned int lnr = 0; int c, i, j; int errflag = 0; /* Check whether this is not a filename and treat it as a direct fingerprint specification. */ if (!strpbrk (string, "/.~\\")) { item = xcalloc (1, sizeof *item); for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++) if ( string[i] != ':' ) item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i]; item->hexfpr[j] = 0; if (j != 40 || !(spacep (string+i) || !string[i])) { log_error (_("%s:%u: invalid fingerprint detected\n"), "--ocsp-signer", 0); xfree (item); return NULL; } return item; } /* Well, it is a filename. */ if (*string == '/' || (*string == '~' && string[1] == '/')) fname = make_filename (string, NULL); else { if (string[0] == '.' && string[1] == '/' ) string += 2; fname = make_filename (gnupg_homedir (), string, NULL); } fp = es_fopen (fname, "r"); if (!fp) { err = gpg_error_from_syserror (); log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err)); xfree (fname); return NULL; } list = NULL; list_tail = &list; for (;;) { if (!es_fgets (line, DIM(line)-1, fp) ) { if (!es_feof (fp)) { err = gpg_error_from_syserror (); log_error (_("%s:%u: read error: %s\n"), fname, lnr, gpg_strerror (err)); errflag = 1; } es_fclose (fp); if (errflag) { while (list) { fingerprint_list_t tmp = list->next; xfree (list); list = tmp; } } xfree (fname); return list; /* Ready. */ } lnr++; if (!*line || line[strlen(line)-1] != '\n') { /* Eat until end of line. */ while ( (c=es_getc (fp)) != EOF && c != '\n') ; err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG /* */: GPG_ERR_INCOMPLETE_LINE); log_error (_("%s:%u: read error: %s\n"), fname, lnr, gpg_strerror (err)); errflag = 1; continue; } /* Allow for empty lines and spaces */ for (p=line; spacep (p); p++) ; if (!*p || *p == '\n' || *p == '#') continue; item = xcalloc (1, sizeof *item); *list_tail = item; list_tail = &item->next; for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++) if ( p[i] != ':' ) item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i]; item->hexfpr[j] = 0; if (j != 40 || !(spacep (p+i) || p[i] == '\n')) { log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr); errflag = 1; } i++; while (spacep (p+i)) i++; if (p[i] && p[i] != '\n') log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr); } /*NOTREACHED*/ } /* Stuff used in daemon mode. */ /* Reread parts of the configuration. Note, that this function is obviously not thread-safe and should only be called from the NPTH signal handler. Fixme: Due to the way the argument parsing works, we create a memory leak here for all string type arguments. There is currently no clean way to tell whether the memory for the argument has been allocated or points into the process' original arguments. Unless we have a mechanism to tell this, we need to live on with this. */ static void reread_configuration (void) { ARGPARSE_ARGS pargs; FILE *fp; unsigned int configlineno = 0; int dummy; if (!opt.config_filename) return; /* No config file. */ fp = fopen (opt.config_filename, "r"); if (!fp) { log_error (_("option file '%s': %s\n"), opt.config_filename, strerror(errno) ); return; } parse_rereadable_options (NULL, 1); /* Start from the default values. */ memset (&pargs, 0, sizeof pargs); dummy = 0; pargs.argc = &dummy; pargs.flags = 1; /* do not remove the args */ while (optfile_parse (fp, opt.config_filename, &configlineno, &pargs, opts) ) { if (pargs.r_opt < -1) pargs.err = 1; /* Print a warning. */ else /* Try to parse this option - ignore unchangeable ones. */ parse_rereadable_options (&pargs, 1); } fclose (fp); post_option_parsing (); } /* A global function which allows us to trigger the reload stuff from other places. */ void dirmngr_sighup_action (void) { log_info (_("SIGHUP received - " "re-reading configuration and flushing caches\n")); reread_configuration (); cert_cache_deinit (0); crl_cache_deinit (); cert_cache_init (hkp_cacert_filenames); crl_cache_init (); reload_dns_stuff (0); ks_hkp_reload (); } /* This function is called if some network activity was done. At this * point we know the we have a network and we can decide whether to * run scheduled background tasks soon. The function should return * quickly and only trigger actions for another thread. */ static void netactivity_action (void) { network_activity_seen = 1; } /* The signal handler. */ #ifndef HAVE_W32_SYSTEM static void handle_signal (int signo) { switch (signo) { case SIGHUP: dirmngr_sighup_action (); break; case SIGUSR1: cert_cache_print_stats (); domaininfo_print_stats (); break; case SIGUSR2: log_info (_("SIGUSR2 received - no action defined\n")); break; case SIGTERM: if (!shutdown_pending) log_info (_("SIGTERM received - shutting down ...\n")); else log_info (_("SIGTERM received - still %d active connections\n"), active_connections); shutdown_pending++; if (shutdown_pending > 2) { log_info (_("shutdown forced\n")); log_info ("%s %s stopped\n", strusage(11), strusage(13) ); cleanup (); dirmngr_exit (0); } break; case SIGINT: log_info (_("SIGINT received - immediate shutdown\n")); log_info( "%s %s stopped\n", strusage(11), strusage(13)); cleanup (); dirmngr_exit (0); break; default: log_info (_("signal %d received - no action defined\n"), signo); } } #endif /*!HAVE_W32_SYSTEM*/ /* Thread to do the housekeeping. */ static void * housekeeping_thread (void *arg) { static int sentinel; - time_t curtime; struct server_control_s ctrlbuf; (void)arg; - curtime = gnupg_get_time (); if (sentinel) { log_info ("housekeeping is already going on\n"); return NULL; } sentinel++; if (opt.verbose > 1) log_info ("starting housekeeping\n"); memset (&ctrlbuf, 0, sizeof ctrlbuf); dirmngr_init_default_ctrl (&ctrlbuf); - ks_hkp_housekeeping (curtime); if (network_activity_seen) { network_activity_seen = 0; if (opt.allow_version_check) dirmngr_load_swdb (&ctrlbuf, 0); workqueue_run_global_tasks (&ctrlbuf, 1); } else workqueue_run_global_tasks (&ctrlbuf, 0); dirmngr_deinit_default_ctrl (&ctrlbuf); if (opt.verbose > 1) log_info ("ready with housekeeping\n"); sentinel--; return NULL; } #if GPGRT_GCC_HAVE_PUSH_PRAGMA # pragma GCC push_options # pragma GCC optimize ("no-strict-overflow") #endif static int time_for_housekeeping_p (time_t curtime) { static time_t last_housekeeping; if (!last_housekeeping) last_housekeeping = curtime; if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime || last_housekeeping > curtime /*(be prepared for y2038)*/) { last_housekeeping = curtime; return 1; } return 0; } #if GPGRT_GCC_HAVE_PUSH_PRAGMA # pragma GCC pop_options #endif /* This is the worker for the ticker. It is called every few seconds and may only do fast operations. */ static void handle_tick (void) { struct stat statbuf; if (time_for_housekeeping_p (gnupg_get_time ())) { npth_t thread; npth_attr_t tattr; int err; err = npth_attr_init (&tattr); if (err) log_error ("error preparing housekeeping thread: %s\n", strerror (err)); else { npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); err = npth_create (&thread, &tattr, housekeeping_thread, NULL); if (err) log_error ("error spawning housekeeping thread: %s\n", strerror (err)); npth_attr_destroy (&tattr); } } /* Check whether the homedir is still available. */ if (!shutdown_pending && stat (gnupg_homedir (), &statbuf) && errno == ENOENT) { shutdown_pending = 1; log_info ("homedir has been removed - shutting down\n"); } } /* Check the nonce on a new connection. This is a NOP unless we are using our Unix domain socket emulation under Windows. */ static int check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce) { if (assuan_sock_check_nonce (fd, nonce)) { log_info (_("error reading nonce on fd %d: %s\n"), FD2INT (fd), strerror (errno)); assuan_sock_close (fd); return -1; } else return 0; } /* Helper to call a connection's main function. */ static void * start_connection_thread (void *arg) { static unsigned int last_session_id; unsigned int session_id; union int_and_ptr_u argval; gnupg_fd_t fd; memset (&argval, 0, sizeof argval); argval.aptr = arg; fd = argval.afd; if (check_nonce (fd, &socket_nonce)) { log_error ("handler nonce check FAILED\n"); return NULL; } #ifndef HAVE_W32_SYSTEM npth_setspecific (my_tlskey_current_fd, argval.aptr); #endif active_connections++; if (opt.verbose) log_info (_("handler for fd %d started\n"), FD2INT (fd)); session_id = ++last_session_id; if (!session_id) session_id = ++last_session_id; start_command_handler (fd, session_id); if (opt.verbose) log_info (_("handler for fd %d terminated\n"), FD2INT (fd)); active_connections--; workqueue_run_post_session_tasks (session_id); #ifndef HAVE_W32_SYSTEM argval.afd = ASSUAN_INVALID_FD; npth_setspecific (my_tlskey_current_fd, argval.aptr); #endif return NULL; } #ifdef HAVE_INOTIFY_INIT /* Read an inotify event and return true if it matches NAME. */ static int my_inotify_is_name (int fd, const char *name) { union { struct inotify_event ev; char _buf[sizeof (struct inotify_event) + 100 + 1]; } buf; int n; const char *s; s = strrchr (name, '/'); if (s && s[1]) name = s + 1; n = npth_read (fd, &buf, sizeof buf); if (n < sizeof (struct inotify_event)) return 0; if (buf.ev.len < strlen (name)+1) return 0; if (strcmp (buf.ev.name, name)) return 0; /* Not the desired file. */ return 1; /* Found. */ } #endif /*HAVE_INOTIFY_INIT*/ /* Main loop in daemon mode. Note that LISTEN_FD will be owned by * this function. */ static void handle_connections (assuan_fd_t listen_fd) { npth_attr_t tattr; #ifndef HAVE_W32_SYSTEM int signo; #endif struct sockaddr_un paddr; socklen_t plen = sizeof( paddr ); int nfd, ret; fd_set fdset, read_fdset; struct timespec abstime; struct timespec curtime; struct timespec timeout; int saved_errno; int my_inotify_fd = -1; npth_attr_init (&tattr); npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED); #ifndef HAVE_W32_SYSTEM /* FIXME */ npth_sigev_init (); npth_sigev_add (SIGHUP); npth_sigev_add (SIGUSR1); npth_sigev_add (SIGUSR2); npth_sigev_add (SIGINT); npth_sigev_add (SIGTERM); npth_sigev_fini (); #endif #ifdef HAVE_INOTIFY_INIT if (disable_check_own_socket) my_inotify_fd = -1; else if ((my_inotify_fd = inotify_init ()) == -1) log_info ("error enabling fast daemon termination: %s\n", strerror (errno)); else { /* We need to watch the directory for the file because there * won't be an IN_DELETE_SELF for a socket file. */ char *slash = strrchr (socket_name, '/'); log_assert (slash && slash[1]); *slash = 0; if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1) { close (my_inotify_fd); my_inotify_fd = -1; } *slash = '/'; } #endif /*HAVE_INOTIFY_INIT*/ /* Setup the fdset. It has only one member. This is because we use pth_select instead of pth_accept to properly sync timeouts with to full second. */ FD_ZERO (&fdset); FD_SET (FD2INT (listen_fd), &fdset); nfd = FD2INT (listen_fd); if (my_inotify_fd != -1) { FD_SET (my_inotify_fd, &fdset); if (my_inotify_fd > nfd) nfd = my_inotify_fd; } npth_clock_gettime (&abstime); abstime.tv_sec += TIMERTICK_INTERVAL; /* Main loop. */ for (;;) { /* Shutdown test. */ if (shutdown_pending) { if (!active_connections) break; /* ready */ /* Do not accept new connections but keep on running the * loop to cope with the timer events. * * Note that we do not close the listening socket because a * client trying to connect to that socket would instead * restart a new dirmngr instance - which is unlikely the * intention of a shutdown. */ /* assuan_sock_close (listen_fd); */ /* listen_fd = -1; */ FD_ZERO (&fdset); nfd = -1; if (my_inotify_fd != -1) { FD_SET (my_inotify_fd, &fdset); nfd = my_inotify_fd; } } /* Take a copy of the fdset. */ read_fdset = fdset; npth_clock_gettime (&curtime); if (!(npth_timercmp (&curtime, &abstime, <))) { /* Timeout. When a shutdown is pending we use a shorter * interval to handle the shutdown more quickly. */ handle_tick (); npth_clock_gettime (&abstime); abstime.tv_sec += (shutdown_pending ? TIMERTICK_INTERVAL_SHUTDOWN : TIMERTICK_INTERVAL); } npth_timersub (&abstime, &curtime, &timeout); #ifndef HAVE_W32_SYSTEM ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout, npth_sigev_sigmask()); saved_errno = errno; while (npth_sigev_get_pending(&signo)) handle_signal (signo); #else ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL); saved_errno = errno; #endif if (ret == -1 && saved_errno != EINTR) { log_error (_("npth_pselect failed: %s - waiting 1s\n"), strerror (saved_errno)); npth_sleep (1); continue; } if (ret <= 0) { /* Interrupt or timeout. Will be handled when calculating the next timeout. */ continue; } if (shutdown_pending) { /* Do not anymore accept connections. */ continue; } #ifdef HAVE_INOTIFY_INIT if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset) && my_inotify_is_name (my_inotify_fd, socket_name)) { shutdown_pending = 1; log_info ("socket file has been removed - shutting down\n"); } #endif /*HAVE_INOTIFY_INIT*/ if (FD_ISSET (FD2INT (listen_fd), &read_fdset)) { gnupg_fd_t fd; plen = sizeof paddr; fd = INT2FD (npth_accept (FD2INT(listen_fd), (struct sockaddr *)&paddr, &plen)); if (fd == GNUPG_INVALID_FD) { log_error ("accept failed: %s\n", strerror (errno)); } else { char threadname[50]; union int_and_ptr_u argval; npth_t thread; memset (&argval, 0, sizeof argval); argval.afd = fd; snprintf (threadname, sizeof threadname, "conn fd=%d", FD2INT(fd)); ret = npth_create (&thread, &tattr, start_connection_thread, argval.aptr); if (ret) { log_error ("error spawning connection handler: %s\n", strerror (ret) ); assuan_sock_close (fd); } npth_setname_np (thread, threadname); } } } #ifdef HAVE_INOTIFY_INIT if (my_inotify_fd != -1) close (my_inotify_fd); #endif /*HAVE_INOTIFY_INIT*/ npth_attr_destroy (&tattr); if (listen_fd != GNUPG_INVALID_FD) assuan_sock_close (listen_fd); cleanup (); log_info ("%s %s stopped\n", strusage(11), strusage(13)); } const char* dirmngr_get_current_socket_name (void) { if (socket_name) return socket_name; else return dirmngr_socket_name (); } diff --git a/dirmngr/dirmngr.h b/dirmngr/dirmngr.h index 5189f93b1..c27f837a0 100644 --- a/dirmngr/dirmngr.h +++ b/dirmngr/dirmngr.h @@ -1,274 +1,273 @@ /* dirmngr.h - Common definitions for the dirmngr * Copyright (C) 2002 Klarälvdalens Datakonsult AB * Copyright (C) 2004, 2015 g10 Code GmbH * Copyright (C) 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . * * SPDX-License-Identifier: GPL-3.0+ */ #ifndef DIRMNGR_H #define DIRMNGR_H #include "./dirmngr-err.h" #define map_assuan_err(a) \ map_assuan_err_with_source (GPG_ERR_SOURCE_DEFAULT, (a)) #include #include #include #include "../common/util.h" #include "../common/membuf.h" #include "../common/sysutils.h" /* (gnupg_fd_t) */ #include "../common/asshelp.h" /* (assuan_context_t) */ #include "../common/i18n.h" #include "http.h" /* (parsed_uri_t) */ /* This objects keeps information about a particular LDAP server and is used as item of a single linked list of servers. */ struct ldap_server_s { struct ldap_server_s* next; char *host; int port; char *user; char *pass; char *base; }; typedef struct ldap_server_s *ldap_server_t; /* This objects is used to build a list of URI consisting of the original and the parsed URI. */ struct uri_item_s { struct uri_item_s *next; parsed_uri_t parsed_uri; /* The broken down URI. */ char uri[1]; /* The original URI. */ }; typedef struct uri_item_s *uri_item_t; /* A list of fingerprints. */ struct fingerprint_list_s; typedef struct fingerprint_list_s *fingerprint_list_t; struct fingerprint_list_s { fingerprint_list_t next; char hexfpr[20+20+1]; }; /* A large struct named "opt" to keep global flags. */ struct { unsigned int debug; /* debug flags (DBG_foo_VALUE) */ int verbose; /* verbosity level */ int quiet; /* be as quiet as possible */ int dry_run; /* don't change any persistent data */ int batch; /* batch mode */ const char *homedir_cache; /* Dir for cache files (/var/cache/dirmngr). */ char *config_filename; /* Name of a config file, which will be reread on a HUP if it is not NULL. */ char *ldap_wrapper_program; /* Override value for the LDAP wrapper program. */ char *http_wrapper_program; /* Override value for the HTTP wrapper program. */ int running_detached; /* We are running in detached mode. */ int allow_version_check; /* --allow-version-check is active. */ int force; /* Force loading outdated CRLs. */ unsigned int connect_timeout; /* Timeout for connect. */ unsigned int connect_quick_timeout; /* Shorter timeout for connect. */ int disable_http; /* Do not use HTTP at all. */ int disable_ldap; /* Do not use LDAP at all. */ int disable_ipv4; /* Do not use legacy IP addresses. */ int disable_ipv6; /* Do not use standard IP addresses. */ int honor_http_proxy; /* Honor the http_proxy env variable. */ const char *http_proxy; /* The default HTTP proxy. */ const char *ldap_proxy; /* Use given LDAP proxy. */ int only_ldap_proxy; /* Only use the LDAP proxy; no fallback. */ int ignore_http_dp; /* Ignore HTTP CRL distribution points. */ int ignore_ldap_dp; /* Ignore LDAP CRL distribution points. */ int ignore_ocsp_service_url; /* Ignore OCSP service URLs as given in the certificate. */ /* A list of certificate extension OIDs which are ignored so that one can claim that a critical extension has been handled. One OID per string. */ strlist_t ignored_cert_extensions; int allow_ocsp; /* Allow using OCSP. */ int max_replies; unsigned int ldaptimeout; ldap_server_t ldapservers; int add_new_ldapservers; const char *ocsp_responder; /* Standard OCSP responder's URL. */ fingerprint_list_t ocsp_signer; /* The list of fingerprints with allowed standard OCSP signer certificates. */ unsigned int ocsp_max_clock_skew; /* Allowed seconds of clocks skew. */ unsigned int ocsp_max_period; /* Seconds a response is at maximum considered valid after thisUpdate. */ unsigned int ocsp_current_period; /* Seconds a response is considered current after nextUpdate. */ strlist_t keyserver; /* List of default keyservers. */ } opt; #define DBG_X509_VALUE 1 /* debug x.509 parsing */ #define DBG_CRYPTO_VALUE 4 /* debug low level crypto */ #define DBG_DNS_VALUE 16 /* debug DNS calls. */ #define DBG_MEMORY_VALUE 32 /* debug memory allocation stuff */ #define DBG_CACHE_VALUE 64 /* debug the caching */ #define DBG_MEMSTAT_VALUE 128 /* show memory statistics */ #define DBG_HASHING_VALUE 512 /* debug hashing operations */ #define DBG_IPC_VALUE 1024 /* debug assuan communication */ #define DBG_NETWORK_VALUE 2048 /* debug network I/O. */ #define DBG_LOOKUP_VALUE 8192 /* debug lookup details */ #define DBG_EXTPROG_VALUE 16384 /* debug external program calls */ #define DBG_X509 (opt.debug & DBG_X509_VALUE) #define DBG_CRYPTO (opt.debug & DBG_CRYPTO_VALUE) #define DBG_DNS (opt.debug & DBG_DNS_VALUE) #define DBG_MEMORY (opt.debug & DBG_MEMORY_VALUE) #define DBG_CACHE (opt.debug & DBG_CACHE_VALUE) #define DBG_HASHING (opt.debug & DBG_HASHING_VALUE) #define DBG_IPC (opt.debug & DBG_IPC_VALUE) #define DBG_NETWORK (opt.debug & DBG_NETWORK_VALUE) #define DBG_LOOKUP (opt.debug & DBG_LOOKUP_VALUE) #define DBG_EXTPROG (opt.debug & DBG_EXTPROG_VALUE) /* A simple list of certificate references. FIXME: Better use certlist_t also for references (Store NULL at .cert) */ struct cert_ref_s { struct cert_ref_s *next; unsigned char fpr[20]; }; typedef struct cert_ref_s *cert_ref_t; /* Forward references; access only through server.c. */ struct server_local_s; #if SIZEOF_UNSIGNED_LONG == 8 # define SERVER_CONTROL_MAGIC 0x6469726d6e677220 #else # define SERVER_CONTROL_MAGIC 0x6469726d #endif /* Connection control structure. */ struct server_control_s { unsigned long magic;/* Always has SERVER_CONTROL_MAGIC. */ int refcount; /* Count additional references to this object. */ int no_server; /* We are not running under server control. */ int status_fd; /* Only for non-server mode. */ struct server_local_s *server_local; int force_crl_refresh; /* Always load a fresh CRL. */ int check_revocations_nest_level; /* Internal to check_revovations. */ cert_ref_t ocsp_certs; /* Certificates from the current OCSP response. */ int audit_events; /* Send audit events to client. */ char *http_proxy; /* The used http_proxy or NULL. */ unsigned int timeout; /* Timeout for connect calls in ms. */ unsigned int http_no_crl:1; /* Do not check CRLs for https. */ }; /*-- dirmngr.c --*/ void dirmngr_exit( int ); /* Wrapper for exit() */ void dirmngr_init_default_ctrl (ctrl_t ctrl); void dirmngr_deinit_default_ctrl (ctrl_t ctrl); void dirmngr_sighup_action (void); const char* dirmngr_get_current_socket_name (void); int dirmngr_use_tor (void); /*-- Various housekeeping functions. --*/ -void ks_hkp_housekeeping (time_t curtime); void ks_hkp_reload (void); /*-- server.c --*/ ldap_server_t get_ldapservers_from_ctrl (ctrl_t ctrl); ksba_cert_t get_cert_local (ctrl_t ctrl, const char *issuer); ksba_cert_t get_issuing_cert_local (ctrl_t ctrl, const char *issuer); ksba_cert_t get_cert_local_ski (ctrl_t ctrl, const char *name, ksba_sexp_t keyid); gpg_error_t get_istrusted_from_client (ctrl_t ctrl, const char *hexfpr); int dirmngr_assuan_log_monitor (assuan_context_t ctx, unsigned int cat, const char *msg); void start_command_handler (gnupg_fd_t fd, unsigned int session_id); gpg_error_t dirmngr_status (ctrl_t ctrl, const char *keyword, ...); gpg_error_t dirmngr_status_help (ctrl_t ctrl, const char *text); gpg_error_t dirmngr_status_helpf (ctrl_t ctrl, const char *format, ...) GPGRT_ATTR_PRINTF(2,3); gpg_error_t dirmngr_status_printf (ctrl_t ctrl, const char *keyword, const char *format, ...) GPGRT_ATTR_PRINTF(3,4); gpg_error_t dirmngr_tick (ctrl_t ctrl); /*-- http-ntbtls.c --*/ /* Note that we don't use a callback for gnutls. */ gpg_error_t gnupg_http_tls_verify_cb (void *opaque, http_t http, http_session_t session, unsigned int flags, void *tls_context); /*-- loadswdb.c --*/ gpg_error_t dirmngr_load_swdb (ctrl_t ctrl, int force); /*-- domaininfo.c --*/ void domaininfo_print_stats (void); int domaininfo_is_wkd_not_supported (const char *domain); void domaininfo_set_no_name (const char *domain); void domaininfo_set_wkd_supported (const char *domain); void domaininfo_set_wkd_not_supported (const char *domain); void domaininfo_set_wkd_not_found (const char *domain); /*-- workqueue.c --*/ typedef const char *(*wqtask_t)(ctrl_t ctrl, const char *args); void workqueue_dump_queue (ctrl_t ctrl); gpg_error_t workqueue_add_task (wqtask_t func, const char *args, unsigned int session_id, int need_network); void workqueue_run_global_tasks (ctrl_t ctrl, int with_network); void workqueue_run_post_session_tasks (unsigned int session_id); #endif /*DIRMNGR_H*/ diff --git a/dirmngr/ks-engine-hkp.c b/dirmngr/ks-engine-hkp.c index e67861c98..9ca1caef8 100644 --- a/dirmngr/ks-engine-hkp.c +++ b/dirmngr/ks-engine-hkp.c @@ -1,1786 +1,1784 @@ /* ks-engine-hkp.c - HKP keyserver engine * Copyright (C) 2011, 2012 Free Software Foundation, Inc. * Copyright (C) 2011, 2012, 2014 Werner Koch * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see . */ #include #include #include #include #include #ifdef HAVE_W32_SYSTEM # ifdef HAVE_WINSOCK2_H # include # endif # include #else /*!HAVE_W32_SYSTEM*/ # include # include # include #endif /*!HAVE_W32_SYSTEM*/ #include "dirmngr.h" #include "misc.h" #include "../common/userids.h" #include "dns-stuff.h" #include "ks-engine.h" /* Substitutes for missing Mingw macro. The EAI_SYSTEM mechanism seems not to be available (probably because there is only one set of error codes anyway). For now we use WSAEINVAL. */ #ifndef EAI_OVERFLOW # define EAI_OVERFLOW EAI_FAIL #endif #ifdef HAVE_W32_SYSTEM # ifndef EAI_SYSTEM # define EAI_SYSTEM WSAEINVAL # endif #endif /* Number of seconds after a host is marked as resurrected. */ #define RESURRECT_INTERVAL (3600+1800) /* 1.5 hours */ /* To match the behaviour of our old gpgkeys helper code we escape more characters than actually needed. */ #define EXTRA_ESCAPE_CHARS "@!\"#$%&'()*+,-./:;<=>?[\\]^_{|}~" /* How many redirections do we allow. */ #define MAX_REDIRECTS 2 /* Number of retries done for a dead host etc. */ #define SEND_REQUEST_RETRIES 3 /* Number of retries done in case of transient errors. */ #define SEND_REQUEST_EXTRA_RETRIES 5 enum ks_protocol { KS_PROTOCOL_HKP, KS_PROTOCOL_HKPS, KS_PROTOCOL_MAX }; /* Objects used to maintain information about hosts. */ struct hostinfo_s; typedef struct hostinfo_s *hostinfo_t; struct hostinfo_s { time_t lastfail; /* Time we tried to connect and failed. */ time_t lastused; /* Time of last use. */ int *pool; /* An array with indices into HOSTTABLE or NULL if NAME is not a pool name. */ size_t pool_len; /* Length of POOL. */ size_t pool_size; /* Allocated size of POOL. */ #define MAX_POOL_SIZE 128 int poolidx; /* Index into POOL with the used host. -1 if not set. */ unsigned int v4:1; /* Host supports AF_INET. */ unsigned int v6:1; /* Host supports AF_INET6. */ unsigned int onion:1;/* NAME is an onion (Tor HS) address. */ unsigned int dead:1; /* Host is currently unresponsive. */ unsigned int iporname_valid:1; /* The field IPORNAME below is valid */ /* (but may be NULL) */ unsigned int did_a_lookup:1; /* Have we done an A lookup yet? */ unsigned int did_srv_lookup:2; /* One bit per protocol indicating whether we already did a SRV lookup. */ time_t died_at; /* The time the host was marked dead. If this is 0 the host has been manually marked dead. */ char *cname; /* Canonical name of the host. Only set if this is a pool or NAME has a numerical IP address. */ char *iporname; /* Numeric IP address or name for printing. */ unsigned short port[KS_PROTOCOL_MAX]; /* The port used by the host for all protocols, 0 if unknown. */ char name[1]; /* The hostname. */ }; /* An array of hostinfo_t for all hosts requested by the caller or resolved from a pool name and its allocated size.*/ static hostinfo_t *hosttable; static int hosttable_size; /* The number of host slots we initially allocate for HOSTTABLE. */ #define INITIAL_HOSTTABLE_SIZE 50 /* Create a new hostinfo object, fill in NAME and put it into HOSTTABLE. Return the index into hosttable on success or -1 on error. */ static int create_new_hostinfo (const char *name) { hostinfo_t hi, *newtable; int newsize; int idx, rc; hi = xtrymalloc (sizeof *hi + strlen (name)); if (!hi) return -1; strcpy (hi->name, name); hi->pool = NULL; hi->pool_len = 0; hi->pool_size = 0; hi->poolidx = -1; hi->lastused = (time_t)(-1); hi->lastfail = (time_t)(-1); hi->v4 = 0; hi->v6 = 0; hi->onion = 0; hi->dead = 0; hi->did_a_lookup = 0; hi->did_srv_lookup = 0; hi->iporname_valid = 0; hi->died_at = 0; hi->cname = NULL; hi->iporname = NULL; hi->port[KS_PROTOCOL_HKP] = 0; hi->port[KS_PROTOCOL_HKPS] = 0; /* Add it to the hosttable. */ for (idx=0; idx < hosttable_size; idx++) if (!hosttable[idx]) { hosttable[idx] = hi; return idx; } /* Need to extend the hosttable. */ newsize = hosttable_size + INITIAL_HOSTTABLE_SIZE; newtable = xtryrealloc (hosttable, newsize * sizeof *hosttable); if (!newtable) { xfree (hi); return -1; } hosttable = newtable; idx = hosttable_size; hosttable_size = newsize; rc = idx; hosttable[idx++] = hi; while (idx < hosttable_size) hosttable[idx++] = NULL; return rc; } /* Find the host NAME in our table. Return the index into the hosttable or -1 if not found. */ static int find_hostinfo (const char *name) { int idx; for (idx=0; idx < hosttable_size; idx++) if (hosttable[idx] && !ascii_strcasecmp (hosttable[idx]->name, name)) return idx; return -1; } static int sort_hostpool (const void *xa, const void *xb) { int a = *(int *)xa; int b = *(int *)xb; assert (a >= 0 && a < hosttable_size); assert (b >= 0 && b < hosttable_size); assert (hosttable[a]); assert (hosttable[b]); return ascii_strcasecmp (hosttable[a]->name, hosttable[b]->name); } /* Return true if the host with the hosttable index TBLIDX is in HI->pool. */ static int host_in_pool_p (hostinfo_t hi, int tblidx) { int i, pidx; for (i = 0; i < hi->pool_len && (pidx = hi->pool[i]) != -1; i++) if (pidx == tblidx && hosttable[pidx]) return 1; return 0; } +static int +host_is_alive (hostinfo_t hi, time_t curtime) +{ + if (!hi) + return 0; + if (!hi->dead) + return 1; + if (!hi->died_at) + return 0; /* manually marked dead */ + if (hi->died_at + RESURRECT_INTERVAL <= curtime + || hi->died_at > curtime) + { + hi->dead = 0; + log_info ("resurrected host '%s'", hi->name); + return 1; + } + return 0; +} /* Select a random host. Consult HI->pool which indices into the global hosttable. Returns index into HI->pool or -1 if no host could be selected. */ static int select_random_host (hostinfo_t hi) { int *tbl = NULL; size_t tblsize = 0; int pidx, idx; + time_t curtime; + curtime = gnupg_get_time (); /* We create a new table so that we randomly select only from currently alive hosts. */ for (idx = 0; idx < hi->pool_len && (pidx = hi->pool[idx]) != -1; idx++) - if (hosttable[pidx] && !hosttable[pidx]->dead) + if (hosttable[pidx] && host_is_alive (hosttable[pidx], curtime)) { tblsize++; tbl = xtryrealloc(tbl, tblsize * sizeof *tbl); if (!tbl) return -1; /* memory allocation failed! */ tbl[tblsize-1] = pidx; } if (!tblsize) return -1; /* No hosts. */ if (tblsize == 1) /* Save a get_uint_nonce. */ pidx = tbl[0]; else pidx = tbl[get_uint_nonce () % tblsize]; xfree (tbl); return pidx; } /* Figure out if a set of DNS records looks like a pool. */ static int arecords_is_pool (dns_addrinfo_t aibuf) { dns_addrinfo_t ai; int n_v6, n_v4; n_v6 = n_v4 = 0; for (ai = aibuf; ai; ai = ai->next) { if (ai->family == AF_INET6) n_v6++; else if (ai->family == AF_INET) n_v4++; } return n_v6 > 1 || n_v4 > 1; } /* Print a warning iff Tor is not running but Tor has been requested. * Also return true if it is not running. */ static int tor_not_running_p (ctrl_t ctrl) { assuan_fd_t sock; if (!dirmngr_use_tor ()) return 0; sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR); if (sock != ASSUAN_INVALID_FD) { assuan_sock_close (sock); return 0; } log_info ("(it seems Tor is not running)\n"); dirmngr_status (ctrl, "WARNING", "tor_not_running 0", "Tor is enabled but the local Tor daemon" " seems to be down", NULL); return 1; } /* Add the host AI under the NAME into the HOSTTABLE. If PORT is not zero, it specifies which port to use to talk to the host for PROTOCOL. If NAME specifies a pool (as indicated by IS_POOL), update the given reference table accordingly. */ static void add_host (const char *name, int is_pool, const dns_addrinfo_t ai, enum ks_protocol protocol, unsigned short port) { gpg_error_t tmperr; char *tmphost; int idx, tmpidx; hostinfo_t host; int i; idx = find_hostinfo (name); host = hosttable[idx]; if (is_pool) { /* For a pool immediately convert the address to a string. */ tmperr = resolve_dns_addr (ai->addr, ai->addrlen, (DNS_NUMERICHOST | DNS_WITHBRACKET), &tmphost); } else if (!is_ip_address (name)) { /* This is a hostname. Use the name as given without going * through resolve_dns_addr. */ tmphost = xtrystrdup (name); if (!tmphost) tmperr = gpg_error_from_syserror (); else tmperr = 0; } else { /* Do a PTR lookup on AI. If a name was not found the function * returns the numeric address (with brackets). */ tmperr = resolve_dns_addr (ai->addr, ai->addrlen, DNS_WITHBRACKET, &tmphost); } if (tmperr) { log_info ("resolve_dns_addr failed while checking '%s': %s\n", name, gpg_strerror (tmperr)); } else if (host->pool_len + 1 >= MAX_POOL_SIZE) { log_error ("resolve_dns_addr for '%s': '%s'" " [index table full - ignored]\n", name, tmphost); } else { if (!is_pool && is_ip_address (name)) /* Update the original entry. */ tmpidx = idx; else tmpidx = find_hostinfo (tmphost); log_info ("resolve_dns_addr for '%s': '%s'%s\n", name, tmphost, tmpidx == -1? "" : " [already known]"); if (tmpidx == -1) /* Create a new entry. */ tmpidx = create_new_hostinfo (tmphost); if (tmpidx == -1) { log_error ("map_host for '%s' problem: %s - '%s' [ignored]\n", name, strerror (errno), tmphost); } else /* Set or update the entry. */ { if (port) hosttable[tmpidx]->port[protocol] = port; if (ai->family == AF_INET6) { hosttable[tmpidx]->v6 = 1; } else if (ai->family == AF_INET) { hosttable[tmpidx]->v4 = 1; } else BUG (); /* If we updated the main entry, we're done. */ if (idx == tmpidx) goto leave; /* If we updated an existing entry, we're done. */ for (i = 0; i < host->pool_len; i++) if (host->pool[i] == tmpidx) goto leave; /* Otherwise, we need to add it to the pool. Check if there is space. */ if (host->pool_len + 1 > host->pool_size) { int *new_pool; size_t new_size; if (host->pool_size == 0) new_size = 4; else new_size = host->pool_size * 2; new_pool = xtryrealloc (host->pool, new_size * sizeof *new_pool); if (new_pool == NULL) goto leave; host->pool = new_pool; host->pool_size = new_size; } /* Finally, add it. */ log_assert (host->pool_len < host->pool_size); host->pool[host->pool_len++] = tmpidx; } } leave: xfree (tmphost); } /* Sort the pool of the given hostinfo HI. */ static void hostinfo_sort_pool (hostinfo_t hi) { qsort (hi->pool, hi->pool_len, sizeof *hi->pool, sort_hostpool); } /* Map the host name NAME to the actual to be used host name. This * allows us to manage round robin DNS names. We use our own strategy * to choose one of the hosts. For example we skip those hosts which * failed for some time and we stick to one host for a time * independent of DNS retry times. If FORCE_RESELECT is true a new * host is always selected. If SRVTAG is NULL no service record * lookup will be done, if it is set that service name is used. The * selected host is stored as a malloced string at R_HOST; on error * NULL is stored. If we know the port used by the selected host from * a service record, a string representation is written to R_PORTSTR, * otherwise it is left untouched. If R_HTTPFLAGS is not NULL it will * receive flags which are to be passed to http_open. If R_HTTPHOST * is not NULL a malloced name of the host is stored there; this might * be different from R_HOST in case it has been selected from a * pool. */ static gpg_error_t map_host (ctrl_t ctrl, const char *name, const char *srvtag, int force_reselect, enum ks_protocol protocol, char **r_host, char *r_portstr, unsigned int *r_httpflags, char **r_httphost) { gpg_error_t err = 0; hostinfo_t hi; int idx; dns_addrinfo_t aibuf, ai; int is_pool; int new_hosts = 0; char *cname; + time_t curtime; *r_host = NULL; if (r_httpflags) *r_httpflags = 0; if (r_httphost) *r_httphost = NULL; /* No hostname means localhost. */ if (!name || !*name) { *r_host = xtrystrdup ("localhost"); return *r_host? 0 : gpg_error_from_syserror (); } /* See whether the host is in our table. */ idx = find_hostinfo (name); if (idx == -1) { idx = create_new_hostinfo (name); if (idx == -1) return gpg_error_from_syserror (); hi = hosttable[idx]; hi->onion = is_onion_address (name); } else hi = hosttable[idx]; + curtime = gnupg_get_time (); is_pool = hi->pool != NULL; if (srvtag && !is_ip_address (name) && ! hi->onion && ! (hi->did_srv_lookup & 1 << protocol)) { struct srventry *srvs; unsigned int srvscount; /* Check for SRV records. */ err = get_dns_srv (name, srvtag, NULL, &srvs, &srvscount); if (err) { if (gpg_err_code (err) == GPG_ERR_ECONNREFUSED) tor_not_running_p (ctrl); return err; } if (srvscount > 0) { int i; if (! is_pool) is_pool = srvscount > 1; for (i = 0; i < srvscount; i++) { err = resolve_dns_name (srvs[i].target, 0, AF_UNSPEC, SOCK_STREAM, &ai, &cname); if (err) continue; dirmngr_tick (ctrl); add_host (name, is_pool, ai, protocol, srvs[i].port); new_hosts = 1; } xfree (srvs); } hi->did_srv_lookup |= 1 << protocol; } if (! hi->did_a_lookup && ! hi->onion) { /* Find all A records for this entry and put them into the pool list - if any. */ err = resolve_dns_name (name, 0, 0, SOCK_STREAM, &aibuf, &cname); if (err) { log_error ("resolving '%s' failed: %s\n", name, gpg_strerror (err)); err = 0; } else { /* First figure out whether this is a pool. For a pool we use a different strategy than for a plain server: We use the canonical name of the pool as the virtual host along with the IP addresses. If it is not a pool, we use the specified name. */ if (! is_pool) is_pool = arecords_is_pool (aibuf); if (is_pool && cname) { hi->cname = cname; cname = NULL; } for (ai = aibuf; ai; ai = ai->next) { if (ai->family != AF_INET && ai->family != AF_INET6) continue; if (opt.disable_ipv4 && ai->family == AF_INET) continue; if (opt.disable_ipv6 && ai->family == AF_INET6) continue; dirmngr_tick (ctrl); add_host (name, is_pool, ai, 0, 0); new_hosts = 1; } hi->did_a_lookup = 1; } xfree (cname); free_dns_addrinfo (aibuf); } if (new_hosts) hostinfo_sort_pool (hi); if (hi->pool) { /* Deal with the pool name before selecting a host. */ if (r_httphost) { *r_httphost = xtrystrdup (hi->name); if (!*r_httphost) return gpg_error_from_syserror (); } /* If the currently selected host is now marked dead, force a re-selection . */ if (force_reselect) hi->poolidx = -1; else if (hi->poolidx >= 0 && hi->poolidx < hosttable_size - && hosttable[hi->poolidx] && hosttable[hi->poolidx]->dead) + && hosttable[hi->poolidx] && !host_is_alive (hosttable[hi->poolidx], curtime)) hi->poolidx = -1; /* Select a host if needed. */ if (hi->poolidx == -1) { hi->poolidx = select_random_host (hi); if (hi->poolidx == -1) { log_error ("no alive host found in pool '%s'\n", name); if (r_httphost) { xfree (*r_httphost); *r_httphost = NULL; } return gpg_error (GPG_ERR_NO_KEYSERVER); } } assert (hi->poolidx >= 0 && hi->poolidx < hosttable_size); hi = hosttable[hi->poolidx]; assert (hi); } else if (r_httphost && is_ip_address (hi->name)) { /* This is a numerical IP address and not a pool. We want to * find the canonical name so that it can be used in the HTTP * Host header. Fixme: We should store that name in the * hosttable. */ char *host; err = resolve_dns_name (hi->name, 0, 0, SOCK_STREAM, &aibuf, NULL); if (!err) { for (ai = aibuf; ai; ai = ai->next) { if ((!opt.disable_ipv6 && ai->family == AF_INET6) || (!opt.disable_ipv4 && ai->family == AF_INET)) { err = resolve_dns_addr (ai->addr, ai->addrlen, 0, &host); if (!err) { /* Okay, we return the first found name. */ *r_httphost = host; break; } } } } free_dns_addrinfo (aibuf); } - if (hi->dead) + if (!host_is_alive (hi, curtime)) { log_error ("host '%s' marked as dead\n", hi->name); if (r_httphost) { xfree (*r_httphost); *r_httphost = NULL; } return gpg_error (GPG_ERR_NO_KEYSERVER); } if (r_httpflags) { /* If the hosttable does not indicate that a certain host supports IPv, we explicit set the corresponding http flags. The reason for this is that a host might be listed in a pool as not v6 only but actually support v6 when later the name is resolved by our http layer. */ if (!hi->v4) *r_httpflags |= HTTP_FLAG_IGNORE_IPv4; if (!hi->v6) *r_httpflags |= HTTP_FLAG_IGNORE_IPv6; /* Note that we do not set the HTTP_FLAG_FORCE_TOR for onion addresses because the http module detects this itself. This also allows us to use an onion address without Tor mode being enabled. */ } *r_host = xtrystrdup (hi->name); if (!*r_host) { err = gpg_error_from_syserror (); if (r_httphost) { xfree (*r_httphost); *r_httphost = NULL; } return err; } if (hi->port[protocol]) snprintf (r_portstr, 6 /* five digits and the sentinel */, "%hu", hi->port[protocol]); return 0; } /* Mark the host NAME as dead. NAME may be given as an URL. Returns true if a host was really marked as dead or was already marked dead (e.g. by a concurrent session). */ static int mark_host_dead (const char *name) { const char *host; char *host_buffer = NULL; parsed_uri_t parsed_uri = NULL; int done = 0; if (name && *name && !http_parse_uri (&parsed_uri, name, 1)) { if (parsed_uri->v6lit) { host_buffer = strconcat ("[", parsed_uri->host, "]", NULL); if (!host_buffer) log_error ("out of core in mark_host_dead"); host = host_buffer; } else host = parsed_uri->host; } else host = name; if (host && *host && strcmp (host, "localhost")) { hostinfo_t hi; int idx; idx = find_hostinfo (host); if (idx != -1) { hi = hosttable[idx]; log_info ("marking host '%s' as dead%s\n", hi->name, hi->dead? " (again)":""); hi->dead = 1; hi->died_at = gnupg_get_time (); if (!hi->died_at) hi->died_at = 1; done = 1; } } http_release_parsed_uri (parsed_uri); xfree (host_buffer); return done; } /* Mark a host in the hosttable as dead or - if ALIVE is true - as alive. */ gpg_error_t ks_hkp_mark_host (ctrl_t ctrl, const char *name, int alive) { gpg_error_t err = 0; hostinfo_t hi, hi2; - int idx, idx2, idx3, n; + int idx, idx2, idx3, n, is_alive; + time_t curtime; if (!name || !*name || !strcmp (name, "localhost")) return 0; idx = find_hostinfo (name); if (idx == -1) return gpg_error (GPG_ERR_NOT_FOUND); + curtime = gnupg_get_time (); hi = hosttable[idx]; - if (alive && hi->dead) + is_alive = host_is_alive (hi, curtime); + if (alive && !is_alive) { hi->dead = 0; err = ks_printf_help (ctrl, "marking '%s' as alive", name); } - else if (!alive && !hi->dead) + else if (!alive && is_alive) { hi->dead = 1; hi->died_at = 0; /* Manually set dead. */ err = ks_printf_help (ctrl, "marking '%s' as dead", name); } /* If the host is a pool mark all member hosts. */ if (!err && hi->pool) { for (idx2 = 0; !err && idx2 < hi->pool_len && (n = hi->pool[idx2]) != -1; idx2++) { assert (n >= 0 && n < hosttable_size); if (!alive) { /* Do not mark a host from a pool dead if it is also a member in another pool. */ for (idx3=0; idx3 < hosttable_size; idx3++) { if (hosttable[idx3] && hosttable[idx3]->pool && idx3 != idx && host_in_pool_p (hosttable[idx3], n)) break; } if (idx3 < hosttable_size) continue; /* Host is also a member of another pool. */ } hi2 = hosttable[n]; if (!hi2) - ; - else if (alive && hi2->dead) + continue; + is_alive = host_is_alive (hi2, curtime); + if (alive && !is_alive) { hi2->dead = 0; err = ks_printf_help (ctrl, "marking '%s' as alive", hi2->name); } - else if (!alive && !hi2->dead) + else if (!alive && is_alive) { hi2->dead = 1; hi2->died_at = 0; /* Manually set dead. */ err = ks_printf_help (ctrl, "marking '%s' as dead", hi2->name); } } } return err; } /* Debug function to print the entire hosttable. */ gpg_error_t ks_hkp_print_hosttable (ctrl_t ctrl) { gpg_error_t err; int idx, idx2; hostinfo_t hi; membuf_t mb; time_t curtime; char *p, *died; const char *diedstr; err = ks_print_help (ctrl, "hosttable (idx, ipv6, ipv4, dead, name, time):"); if (err) return err; /* FIXME: We need a lock for the hosttable. */ curtime = gnupg_get_time (); for (idx=0; idx < hosttable_size; idx++) if ((hi=hosttable[idx])) { if (hi->dead && hi->died_at) { died = elapsed_time_string (hi->died_at, curtime); diedstr = died? died : "error"; } else diedstr = died = NULL; if (!hi->iporname_valid) { char *canon = NULL; xfree (hi->iporname); hi->iporname = NULL; /* Do a lookup just for the display purpose. */ if (hi->onion || hi->pool) ; else if (is_ip_address (hi->name)) { dns_addrinfo_t aibuf, ai; /* Turn the numerical IP address string into an AI and * then do a DNS PTR lookup. */ if (!resolve_dns_name (hi->name, 0, 0, SOCK_STREAM, &aibuf, &canon)) { if (canon && is_ip_address (canon)) { xfree (canon); canon = NULL; } for (ai = aibuf; !canon && ai; ai = ai->next) { resolve_dns_addr (ai->addr, ai->addrlen, DNS_WITHBRACKET, &canon); if (canon && is_ip_address (canon)) { /* We already have the numeric IP - no need to * display it a second time. */ xfree (canon); canon = NULL; } } } free_dns_addrinfo (aibuf); } else { dns_addrinfo_t aibuf, ai; /* Get the IP address as a string from a name. Note * that resolve_dns_addr allocates CANON on success * and thus terminates the loop. */ if (!resolve_dns_name (hi->name, 0, hi->v6? AF_INET6 : AF_INET, SOCK_STREAM, &aibuf, NULL)) { for (ai = aibuf; !canon && ai; ai = ai->next) { resolve_dns_addr (ai->addr, ai->addrlen, DNS_NUMERICHOST|DNS_WITHBRACKET, &canon); } } free_dns_addrinfo (aibuf); } hi->iporname = canon; hi->iporname_valid = 1; } err = ks_printf_help (ctrl, "%3d %s %s %s %s%s%s%s%s%s%s\n", idx, hi->onion? "O" : hi->v6? "6":" ", hi->v4? "4":" ", hi->dead? "d":" ", hi->name, hi->iporname? " (":"", hi->iporname? hi->iporname : "", hi->iporname? ")":"", diedstr? " (":"", diedstr? diedstr:"", diedstr? ")":"" ); xfree (died); if (err) return err; if (hi->cname) err = ks_printf_help (ctrl, " . %s", hi->cname); if (err) return err; if (hi->pool) { init_membuf (&mb, 256); put_membuf_printf (&mb, " . -->"); for (idx2 = 0; idx2 < hi->pool_len && hi->pool[idx2] != -1; idx2++) { put_membuf_printf (&mb, " %d", hi->pool[idx2]); if (hi->poolidx == hi->pool[idx2]) put_membuf_printf (&mb, "*"); } put_membuf( &mb, "", 1); p = get_membuf (&mb, NULL); if (!p) return gpg_error_from_syserror (); err = ks_print_help (ctrl, p); xfree (p); if (err) return err; } } return 0; } /* Print a help output for the schemata supported by this module. */ gpg_error_t ks_hkp_help (ctrl_t ctrl, parsed_uri_t uri) { const char data[] = "Handler for HKP URLs:\n" " hkp://\n" #if HTTP_USE_GNUTLS || HTTP_USE_NTBTLS " hkps://\n" #endif "Supported methods: search, get, put\n"; gpg_error_t err; #if HTTP_USE_GNUTLS || HTTP_USE_NTBTLS const char data2[] = " hkp\n hkps"; #else const char data2[] = " hkp"; #endif if (!uri) err = ks_print_help (ctrl, data2); else if (uri->is_http && (!strcmp (uri->scheme, "hkp") || !strcmp (uri->scheme, "hkps"))) err = ks_print_help (ctrl, data); else err = 0; return err; } /* Build the remote part of the URL from SCHEME, HOST and an optional * PORT. If NO_SRV is set no SRV record lookup will be done. Returns * an allocated string at R_HOSTPORT or NULL on failure. If * R_HTTPHOST is not NULL it receives a malloced string with the * hostname; this may be different from HOST if HOST is selected from * a pool. */ static gpg_error_t make_host_part (ctrl_t ctrl, const char *scheme, const char *host, unsigned short port, int force_reselect, int no_srv, char **r_hostport, unsigned int *r_httpflags, char **r_httphost) { gpg_error_t err; const char *srvtag; char portstr[10]; char *hostname; enum ks_protocol protocol; *r_hostport = NULL; if (!strcmp (scheme, "hkps") || !strcmp (scheme,"https")) { scheme = "https"; srvtag = no_srv? NULL : "pgpkey-https"; protocol = KS_PROTOCOL_HKPS; } else /* HKP or HTTP. */ { scheme = "http"; srvtag = no_srv? NULL : "pgpkey-http"; protocol = KS_PROTOCOL_HKP; } portstr[0] = 0; err = map_host (ctrl, host, srvtag, force_reselect, protocol, &hostname, portstr, r_httpflags, r_httphost); if (err) return err; /* If map_host did not return a port (from a SRV record) but a port * has been specified (implicitly or explicitly) then use that port. * In the case that a port was not specified (which is probably a * bug in https.c) we will set up defaults. */ if (*portstr) ; else if (!*portstr && port) snprintf (portstr, sizeof portstr, "%hu", port); else if (!strcmp (scheme,"https")) strcpy (portstr, "443"); else strcpy (portstr, "11371"); if (*hostname != '[' && is_ip_address (hostname) == 6) *r_hostport = strconcat (scheme, "://[", hostname, "]:", portstr, NULL); else *r_hostport = strconcat (scheme, "://", hostname, ":", portstr, NULL); xfree (hostname); if (!*r_hostport) { if (r_httphost) { xfree (*r_httphost); *r_httphost = NULL; } return gpg_error_from_syserror (); } return 0; } /* Resolve all known keyserver names and update the hosttable. This is mainly useful for debugging because the resolving is anyway done on demand. */ gpg_error_t ks_hkp_resolve (ctrl_t ctrl, parsed_uri_t uri) { gpg_error_t err; char *hostport = NULL; /* NB: With an explicitly given port we do not want to consult a * service record because that might be in conflict with the port * from such a service record. */ err = make_host_part (ctrl, uri->scheme, uri->host, uri->port, 1, uri->explicit_port, &hostport, NULL, NULL); if (err) { err = ks_printf_help (ctrl, "%s://%s:%hu: resolve failed: %s", uri->scheme, uri->host, uri->port, gpg_strerror (err)); } else { err = ks_printf_help (ctrl, "%s", hostport); xfree (hostport); } return err; } -/* Housekeeping function called from the housekeeping thread. It is - used to mark dead hosts alive so that they may be tried again after - some time. */ -void -ks_hkp_housekeeping (time_t curtime) -{ - int idx; - hostinfo_t hi; - - for (idx=0; idx < hosttable_size; idx++) - { - hi = hosttable[idx]; - if (!hi) - continue; - if (!hi->dead) - continue; - if (!hi->died_at) - continue; /* Do not resurrect manually shot hosts. */ - if (hi->died_at + RESURRECT_INTERVAL <= curtime - || hi->died_at > curtime) - { - hi->dead = 0; - log_info ("resurrected host '%s'", hi->name); - } - } -} - - /* Reload (SIGHUP) action for this module. We mark all host alive * even those which have been manually shot. */ void ks_hkp_reload (void) { int idx, count; hostinfo_t hi; for (idx=count=0; idx < hosttable_size; idx++) { hi = hosttable[idx]; if (!hi) continue; hi->iporname_valid = 0; if (!hi->dead) continue; hi->dead = 0; count++; } if (count) log_info ("number of resurrected hosts: %d", count); } /* Send an HTTP request. On success returns an estream object at R_FP. HOSTPORTSTR is only used for diagnostics. If HTTPHOST is not NULL it will be used as HTTP "Host" header. If POST_CB is not NULL a post request is used and that callback is called to allow writing the post data. If R_HTTP_STATUS is not NULL, the http status code will be stored there. */ static gpg_error_t send_request (ctrl_t ctrl, const char *request, const char *hostportstr, const char *httphost, unsigned int httpflags, gpg_error_t (*post_cb)(void *, http_t), void *post_cb_value, estream_t *r_fp, unsigned int *r_http_status) { gpg_error_t err; http_session_t session = NULL; http_t http = NULL; http_redir_info_t redirinfo = { MAX_REDIRECTS }; estream_t fp = NULL; char *request_buffer = NULL; parsed_uri_t uri = NULL; *r_fp = NULL; err = http_parse_uri (&uri, request, 0); if (err) goto leave; redirinfo.orig_url = request; redirinfo.orig_onion = uri->onion; redirinfo.allow_downgrade = 1; /* FIXME: I am not sure whey we allow a downgrade for hkp requests. * Needs at least an explanation here.. */ once_more: err = http_session_new (&session, httphost, ((ctrl->http_no_crl? HTTP_FLAG_NO_CRL : 0) | HTTP_FLAG_TRUST_DEF), gnupg_http_tls_verify_cb, ctrl); if (err) goto leave; http_session_set_log_cb (session, cert_log_cb); http_session_set_timeout (session, ctrl->timeout); err = http_open (&http, post_cb? HTTP_REQ_POST : HTTP_REQ_GET, request, httphost, /* fixme: AUTH */ NULL, (httpflags |(opt.honor_http_proxy? HTTP_FLAG_TRY_PROXY:0) |(dirmngr_use_tor ()? HTTP_FLAG_FORCE_TOR:0) |(opt.disable_ipv4? HTTP_FLAG_IGNORE_IPv4 : 0) |(opt.disable_ipv6? HTTP_FLAG_IGNORE_IPv6 : 0)), ctrl->http_proxy, session, NULL, /*FIXME curl->srvtag*/NULL); if (!err) { fp = http_get_write_ptr (http); /* Avoid caches to get the most recent copy of the key. We set both the Pragma and Cache-Control versions of the header, so we're good with both HTTP 1.0 and 1.1. */ es_fputs ("Pragma: no-cache\r\n" "Cache-Control: no-cache\r\n", fp); if (post_cb) err = post_cb (post_cb_value, http); if (!err) { http_start_data (http); if (es_ferror (fp)) err = gpg_error_from_syserror (); } } if (err) { /* Fixme: After a redirection we show the old host name. */ log_error (_("error connecting to '%s': %s\n"), hostportstr, gpg_strerror (err)); goto leave; } /* Wait for the response. */ dirmngr_tick (ctrl); err = http_wait_response (http); if (err) { log_error (_("error reading HTTP response for '%s': %s\n"), hostportstr, gpg_strerror (err)); goto leave; } if (http_get_tls_info (http, NULL)) { /* Update the httpflags so that a redirect won't fallback to an unencrypted connection. */ httpflags |= HTTP_FLAG_FORCE_TLS; } if (r_http_status) *r_http_status = http_get_status_code (http); switch (http_get_status_code (http)) { case 200: err = 0; break; /* Success. */ case 301: case 302: case 307: { xfree (request_buffer); err = http_prepare_redirect (&redirinfo, http_get_status_code (http), http_get_header (http, "Location"), &request_buffer); if (err) goto leave; request = request_buffer; http_close (http, 0); http = NULL; http_session_release (session); session = NULL; } goto once_more; case 501: err = gpg_error (GPG_ERR_NOT_IMPLEMENTED); goto leave; case 413: /* Payload too large */ err = gpg_error (GPG_ERR_TOO_LARGE); goto leave; default: log_error (_("error accessing '%s': http status %u\n"), request, http_get_status_code (http)); err = gpg_error (GPG_ERR_NO_DATA); goto leave; } /* FIXME: We should register a permanent redirection and whether a host has ever used TLS so that future calls will always use TLS. */ fp = http_get_read_ptr (http); if (!fp) { err = gpg_error (GPG_ERR_BUG); goto leave; } /* Return the read stream and close the HTTP context. */ *r_fp = fp; http_close (http, 1); http = NULL; leave: http_close (http, 0); http_session_release (session); xfree (request_buffer); http_release_parsed_uri (uri); return err; } /* Helper to evaluate the error code ERR from a send_request() call with REQUEST. The function returns true if the caller shall try again. TRIES_LEFT points to a variable to track the number of retries; this function decrements it and won't return true if it is down to zero. EXTRA_TRIES_LEFT does the same but only for transient http status codes. */ static int handle_send_request_error (ctrl_t ctrl, gpg_error_t err, const char *request, unsigned int http_status, unsigned int *tries_left, unsigned int *extra_tries_left) { int retry = 0; /* Fixme: Should we disable all hosts of a protocol family if a * request for an address of that familiy returned ENETDOWN? */ switch (gpg_err_code (err)) { case GPG_ERR_ECONNREFUSED: if (tor_not_running_p (ctrl)) break; /* A retry does not make sense. */ /* Okay: Tor is up or --use-tor is not used. */ /*FALLTHRU*/ case GPG_ERR_ENETUNREACH: case GPG_ERR_ENETDOWN: case GPG_ERR_UNKNOWN_HOST: case GPG_ERR_NETWORK: case GPG_ERR_EIO: /* Sometimes used by estream cookie functions. */ case GPG_ERR_EADDRNOTAVAIL: /* e.g. when IPv6 is disabled */ case GPG_ERR_EAFNOSUPPORT: /* e.g. when IPv6 is not compiled in */ if (mark_host_dead (request) && *tries_left) retry = 1; break; case GPG_ERR_ETIMEDOUT: if (*tries_left) { log_info ("selecting a different host due to a timeout\n"); retry = 1; } break; case GPG_ERR_EACCES: if (dirmngr_use_tor ()) { log_info ("(Tor configuration problem)\n"); dirmngr_status (ctrl, "WARNING", "tor_config_problem 0", "Please check that the \"SocksPort\" flag " "\"IPv6Traffic\" is set in torrc", NULL); } break; case GPG_ERR_NO_DATA: { switch (http_status) { case 502: /* Bad Gateway */ log_info ("marking host dead due to a %u (%s)\n", http_status, http_status2string (http_status)); if (mark_host_dead (request) && *tries_left) retry = 1; break; case 503: /* Service Unavailable */ case 504: /* Gateway Timeout */ if (*extra_tries_left) { log_info ("selecting a different host due to a %u (%s)", http_status, http_status2string (http_status)); retry = 2; } break; } } break; default: break; } if (retry == 2) { if (*extra_tries_left) --*extra_tries_left; } else { if (*tries_left) --*tries_left; } return retry; } /* Search the keyserver identified by URI for keys matching PATTERN. On success R_FP has an open stream to read the data. If R_HTTP_STATUS is not NULL, the http status code will be stored there. */ gpg_error_t ks_hkp_search (ctrl_t ctrl, parsed_uri_t uri, const char *pattern, estream_t *r_fp, unsigned int *r_http_status) { gpg_error_t err; KEYDB_SEARCH_DESC desc; char fprbuf[2+40+1]; char *hostport = NULL; char *request = NULL; estream_t fp = NULL; int reselect; unsigned int httpflags; char *httphost = NULL; unsigned int http_status; unsigned int tries = SEND_REQUEST_RETRIES; unsigned int extra_tries = SEND_REQUEST_EXTRA_RETRIES; *r_fp = NULL; /* Remove search type indicator and adjust PATTERN accordingly. Note that HKP keyservers like the 0x to be present when searching by keyid. We need to re-format the fingerprint and keyids so to remove the gpg specific force-use-of-this-key flag ("!"). */ err = classify_user_id (pattern, &desc, 1); if (err) return err; switch (desc.mode) { case KEYDB_SEARCH_MODE_EXACT: case KEYDB_SEARCH_MODE_SUBSTR: case KEYDB_SEARCH_MODE_MAIL: case KEYDB_SEARCH_MODE_MAILSUB: pattern = desc.u.name; break; case KEYDB_SEARCH_MODE_SHORT_KID: snprintf (fprbuf, sizeof fprbuf, "0x%08lX", (ulong)desc.u.kid[1]); pattern = fprbuf; break; case KEYDB_SEARCH_MODE_LONG_KID: snprintf (fprbuf, sizeof fprbuf, "0x%08lX%08lX", (ulong)desc.u.kid[0], (ulong)desc.u.kid[1]); pattern = fprbuf; break; case KEYDB_SEARCH_MODE_FPR16: fprbuf[0] = '0'; fprbuf[1] = 'x'; bin2hex (desc.u.fpr, 16, fprbuf+2); pattern = fprbuf; break; case KEYDB_SEARCH_MODE_FPR20: case KEYDB_SEARCH_MODE_FPR: fprbuf[0] = '0'; fprbuf[1] = 'x'; bin2hex (desc.u.fpr, 20, fprbuf+2); pattern = fprbuf; break; default: return gpg_error (GPG_ERR_INV_USER_ID); } /* Build the request string. */ reselect = 0; again: { char *searchkey; xfree (hostport); hostport = NULL; xfree (httphost); httphost = NULL; err = make_host_part (ctrl, uri->scheme, uri->host, uri->port, reselect, uri->explicit_port, &hostport, &httpflags, &httphost); if (err) goto leave; searchkey = http_escape_string (pattern, EXTRA_ESCAPE_CHARS); if (!searchkey) { err = gpg_error_from_syserror (); goto leave; } xfree (request); request = strconcat (hostport, "/pks/lookup?op=index&options=mr&search=", searchkey, NULL); xfree (searchkey); if (!request) { err = gpg_error_from_syserror (); goto leave; } } /* Send the request. */ err = send_request (ctrl, request, hostport, httphost, httpflags, NULL, NULL, &fp, &http_status); if (handle_send_request_error (ctrl, err, request, http_status, &tries, &extra_tries)) { reselect = 1; goto again; } if (r_http_status) *r_http_status = http_status; if (err) { if (gpg_err_code (err) == GPG_ERR_NO_DATA) dirmngr_status (ctrl, "SOURCE", hostport, NULL); goto leave; } err = dirmngr_status (ctrl, "SOURCE", hostport, NULL); if (err) goto leave; /* Peek at the response. */ { int c = es_getc (fp); if (c == -1) { err = es_ferror (fp)?gpg_error_from_syserror ():gpg_error (GPG_ERR_EOF); log_error ("error reading response: %s\n", gpg_strerror (err)); goto leave; } if (c == '<') { /* The document begins with a '<': Assume a HTML response, which we don't support. */ err = gpg_error (GPG_ERR_UNSUPPORTED_ENCODING); goto leave; } es_ungetc (c, fp); } /* Return the read stream. */ *r_fp = fp; fp = NULL; leave: es_fclose (fp); xfree (request); xfree (hostport); xfree (httphost); return err; } /* Get the key described key the KEYSPEC string from the keyserver identified by URI. On success R_FP has an open stream to read the data. The data will be provided in a format GnuPG can import (either a binary OpenPGP message or an armored one). */ gpg_error_t ks_hkp_get (ctrl_t ctrl, parsed_uri_t uri, const char *keyspec, estream_t *r_fp) { gpg_error_t err; KEYDB_SEARCH_DESC desc; char kidbuf[2+40+1]; const char *exactname = NULL; char *searchkey = NULL; char *hostport = NULL; char *request = NULL; estream_t fp = NULL; int reselect; char *httphost = NULL; unsigned int httpflags; unsigned int http_status; unsigned int tries = SEND_REQUEST_RETRIES; unsigned int extra_tries = SEND_REQUEST_EXTRA_RETRIES; *r_fp = NULL; /* Remove search type indicator and adjust PATTERN accordingly. Note that HKP keyservers like the 0x to be present when searching by keyid. We need to re-format the fingerprint and keyids so to remove the gpg specific force-use-of-this-key flag ("!"). */ err = classify_user_id (keyspec, &desc, 1); if (err) return err; switch (desc.mode) { case KEYDB_SEARCH_MODE_SHORT_KID: snprintf (kidbuf, sizeof kidbuf, "0x%08lX", (ulong)desc.u.kid[1]); break; case KEYDB_SEARCH_MODE_LONG_KID: snprintf (kidbuf, sizeof kidbuf, "0x%08lX%08lX", (ulong)desc.u.kid[0], (ulong)desc.u.kid[1]); break; case KEYDB_SEARCH_MODE_FPR20: case KEYDB_SEARCH_MODE_FPR: /* This is a v4 fingerprint. */ kidbuf[0] = '0'; kidbuf[1] = 'x'; bin2hex (desc.u.fpr, 20, kidbuf+2); break; case KEYDB_SEARCH_MODE_EXACT: exactname = desc.u.name; break; case KEYDB_SEARCH_MODE_FPR16: log_error ("HKP keyservers do not support v3 fingerprints\n"); /* fall through */ default: return gpg_error (GPG_ERR_INV_USER_ID); } searchkey = http_escape_string (exactname? exactname : kidbuf, EXTRA_ESCAPE_CHARS); if (!searchkey) { err = gpg_error_from_syserror (); goto leave; } reselect = 0; again: /* Build the request string. */ xfree (hostport); hostport = NULL; xfree (httphost); httphost = NULL; err = make_host_part (ctrl, uri->scheme, uri->host, uri->port, reselect, uri->explicit_port, &hostport, &httpflags, &httphost); if (err) goto leave; xfree (request); request = strconcat (hostport, "/pks/lookup?op=get&options=mr&search=", searchkey, exactname? "&exact=on":"", NULL); if (!request) { err = gpg_error_from_syserror (); goto leave; } /* Send the request. */ err = send_request (ctrl, request, hostport, httphost, httpflags, NULL, NULL, &fp, &http_status); if (handle_send_request_error (ctrl, err, request, http_status, &tries, &extra_tries)) { reselect = 1; goto again; } if (err) { if (gpg_err_code (err) == GPG_ERR_NO_DATA) dirmngr_status (ctrl, "SOURCE", hostport, NULL); goto leave; } err = dirmngr_status (ctrl, "SOURCE", hostport, NULL); if (err) goto leave; /* Return the read stream and close the HTTP context. */ *r_fp = fp; fp = NULL; leave: es_fclose (fp); xfree (request); xfree (hostport); xfree (httphost); xfree (searchkey); return err; } /* Callback parameters for put_post_cb. */ struct put_post_parm_s { char *datastring; }; /* Helper for ks_hkp_put. */ static gpg_error_t put_post_cb (void *opaque, http_t http) { struct put_post_parm_s *parm = opaque; gpg_error_t err = 0; estream_t fp; size_t len; fp = http_get_write_ptr (http); len = strlen (parm->datastring); es_fprintf (fp, "Content-Type: application/x-www-form-urlencoded\r\n" "Content-Length: %zu\r\n", len+8 /* 8 is for "keytext" */); http_start_data (http); if (es_fputs ("keytext=", fp) || es_write (fp, parm->datastring, len, NULL)) err = gpg_error_from_syserror (); return err; } /* Send the key in {DATA,DATALEN} to the keyserver identified by URI. */ gpg_error_t ks_hkp_put (ctrl_t ctrl, parsed_uri_t uri, const void *data, size_t datalen) { gpg_error_t err; char *hostport = NULL; char *request = NULL; estream_t fp = NULL; struct put_post_parm_s parm; char *armored = NULL; int reselect; char *httphost = NULL; unsigned int httpflags; unsigned int http_status; unsigned int tries = SEND_REQUEST_RETRIES; unsigned int extra_tries = SEND_REQUEST_EXTRA_RETRIES; parm.datastring = NULL; err = armor_data (&armored, data, datalen); if (err) goto leave; parm.datastring = http_escape_string (armored, EXTRA_ESCAPE_CHARS); if (!parm.datastring) { err = gpg_error_from_syserror (); goto leave; } xfree (armored); armored = NULL; /* Build the request string. */ reselect = 0; again: xfree (hostport); hostport = NULL; xfree (httphost); httphost = NULL; err = make_host_part (ctrl, uri->scheme, uri->host, uri->port, reselect, uri->explicit_port, &hostport, &httpflags, &httphost); if (err) goto leave; xfree (request); request = strconcat (hostport, "/pks/add", NULL); if (!request) { err = gpg_error_from_syserror (); goto leave; } /* Send the request. */ err = send_request (ctrl, request, hostport, httphost, 0, put_post_cb, &parm, &fp, &http_status); if (handle_send_request_error (ctrl, err, request, http_status, &tries, &extra_tries)) { reselect = 1; goto again; } if (err) goto leave; leave: es_fclose (fp); xfree (parm.datastring); xfree (armored); xfree (request); xfree (hostport); xfree (httphost); return err; }