1 /* dirmngr.c - Keyserver and X.509 LDAP access
2  * Copyright (C) 2002 Klarälvdalens Datakonsult AB
3  * Copyright (C) 2003-2004, 2006-2007, 2008, 2010-2011, 2020 g10 Code GmbH
4  * Copyright (C) 2014 Werner Koch
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  * SPDX-License-Identifier: GPL-3.0-or-later
21  */
22 
23 #include <config.h>
24 
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stddef.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <assert.h>
32 #include <time.h>
33 #include <fcntl.h>
34 #ifndef HAVE_W32_SYSTEM
35 #include <sys/socket.h>
36 #include <sys/un.h>
37 #endif
38 #include <sys/stat.h>
39 #include <unistd.h>
40 #ifdef HAVE_SIGNAL_H
41 # include <signal.h>
42 #endif
43 #ifdef HAVE_INOTIFY_INIT
44 # include <sys/inotify.h>
45 #endif /*HAVE_INOTIFY_INIT*/
46 #include <npth.h>
47 
48 #include "dirmngr-err.h"
49 
50 #if  HTTP_USE_NTBTLS
51 # include <ntbtls.h>
52 #elif HTTP_USE_GNUTLS
53 # include <gnutls/gnutls.h>
54 #endif /*HTTP_USE_GNUTLS*/
55 
56 
57 #define INCLUDED_BY_MAIN_MODULE 1
58 #define GNUPG_COMMON_NEED_AFLOCAL
59 #include "dirmngr.h"
60 
61 #include <assuan.h>
62 
63 #include "certcache.h"
64 #include "crlcache.h"
65 #include "crlfetch.h"
66 #include "misc.h"
67 #if USE_LDAP
68 # include "ldapserver.h"
69 #endif
70 #include "../common/asshelp.h"
71 #if USE_LDAP
72 # include "ldap-wrapper.h"
73 #endif
74 #include "../common/comopt.h"
75 #include "../common/init.h"
76 #include "../common/gc-opt-flags.h"
77 #include "dns-stuff.h"
78 #include "http-common.h"
79 
80 #ifndef ENAMETOOLONG
81 # define ENAMETOOLONG EINVAL
82 #endif
83 
84 
85 enum cmd_and_opt_values {
86   aNull = 0,
87   oCsh		  = 'c',
88   oQuiet	  = 'q',
89   oSh		  = 's',
90   oVerbose	  = 'v',
91   oNoVerbose = 500,
92 
93   aServer,
94   aDaemon,
95   aSupervised,
96   aListCRLs,
97   aLoadCRL,
98   aFetchCRL,
99   aShutdown,
100   aFlush,
101   aGPGConfList,
102   aGPGConfTest,
103   aGPGConfVersions,
104 
105   oOptions,
106   oDebug,
107   oDebugAll,
108   oDebugWait,
109   oDebugLevel,
110   oGnutlsDebug,
111   oNoGreeting,
112   oNoOptions,
113   oHomedir,
114   oNoDetach,
115   oLogFile,
116   oBatch,
117   oDisableHTTP,
118   oDisableLDAP,
119   oDisableIPv4,
120   oDisableIPv6,
121   oIgnoreLDAPDP,
122   oIgnoreHTTPDP,
123   oIgnoreOCSPSvcUrl,
124   oHonorHTTPProxy,
125   oHTTPProxy,
126   oLDAPProxy,
127   oOnlyLDAPProxy,
128   oLDAPServer,
129   oLDAPFile,
130   oLDAPTimeout,
131   oLDAPAddServers,
132   oOCSPResponder,
133   oOCSPSigner,
134   oOCSPMaxClockSkew,
135   oOCSPMaxPeriod,
136   oOCSPCurrentPeriod,
137   oMaxReplies,
138   oHkpCaCert,
139   oFakedSystemTime,
140   oForce,
141   oAllowOCSP,
142   oAllowVersionCheck,
143   oSocketName,
144   oLDAPWrapperProgram,
145   oHTTPWrapperProgram,
146   oIgnoreCert,
147   oIgnoreCertExtension,
148   oUseTor,
149   oNoUseTor,
150   oKeyServer,
151   oNameServer,
152   oDisableCheckOwnSocket,
153   oStandardResolver,
154   oRecursiveResolver,
155   oResolverTimeout,
156   oConnectTimeout,
157   oConnectQuickTimeout,
158   oListenBacklog,
159   aTest
160 };
161 
162 
163 
164 static gpgrt_opt_t opts[] = {
165 
166   ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
167   ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
168   ARGPARSE_c (aGPGConfVersions, "gpgconf-versions", "@"),
169 
170   ARGPARSE_group (300, N_("@Commands:\n ")),
171 
172   ARGPARSE_c (aServer,   "server",  N_("run in server mode (foreground)") ),
173   ARGPARSE_c (aDaemon,   "daemon",  N_("run in daemon mode (background)") ),
174 #ifndef HAVE_W32_SYSTEM
175   ARGPARSE_c (aSupervised,  "supervised", N_("run in supervised mode")),
176 #endif
177   ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")),
178   ARGPARSE_c (aLoadCRL,  "load-crl", N_("|FILE|load CRL from FILE into cache")),
179   ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")),
180   ARGPARSE_c (aShutdown, "shutdown",  N_("shutdown the dirmngr")),
181   ARGPARSE_c (aFlush,    "flush",     N_("flush the cache")),
182 
183 
184   ARGPARSE_header (NULL, N_("Options used for startup")),
185 
186   ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
187   ARGPARSE_s_n (oSh,       "sh",        N_("sh-style command output")),
188   ARGPARSE_s_n (oCsh,      "csh",       N_("csh-style command output")),
189   ARGPARSE_s_s (oHomedir, "homedir", "@"),
190   ARGPARSE_conffile (oOptions,  "options", N_("|FILE|read options from FILE")),
191   ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
192 
193 
194   ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
195 
196   ARGPARSE_s_n (oVerbose,  "verbose",   N_("verbose")),
197   ARGPARSE_s_n (oQuiet,    "quiet",     N_("be somewhat more quiet")),
198   ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
199   ARGPARSE_s_s (oDebugLevel, "debug-level",
200                 N_("|LEVEL|set the debugging level to LEVEL")),
201   ARGPARSE_s_s (oDebug,    "debug", "@"),
202   ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
203   ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"),
204   ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"),
205   ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
206   ARGPARSE_s_s (oLogFile,  "log-file",
207                 N_("|FILE|write server mode logs to FILE")),
208 
209 
210   ARGPARSE_header ("Configuration",
211                    N_("Options controlling the configuration")),
212 
213   ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check",
214                 N_("allow online software version check")),
215   ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
216   ARGPARSE_s_i (oMaxReplies, "max-replies",
217                 N_("|N|do not return more than N items in one query")),
218   ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/
219   ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
220   ARGPARSE_s_s (oIgnoreCert,"ignore-cert", "@"),
221   ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"),
222 
223 
224   ARGPARSE_header ("Network", N_("Network related options")),
225 
226   ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")),
227   ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"),
228   ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"),
229   ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"),
230   ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"),
231   ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"),
232   ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"),
233   ARGPARSE_s_s (oNameServer, "nameserver", "@"),
234   ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"),
235   ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"),
236 
237 
238   ARGPARSE_header ("Keyserver", N_("Configuration for Keyservers")),
239 
240   ARGPARSE_s_s (oKeyServer, "keyserver",
241                 N_("|URL|use keyserver at URL")),
242   ARGPARSE_s_s (oHkpCaCert, "hkp-cacert",
243                 N_("|FILE|use the CA certificates in FILE for HKP over TLS")),
244 
245   ARGPARSE_header ("HTTP", N_("Configuration for HTTP servers")),
246 
247   ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")),
248   ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp",
249                 N_("ignore HTTP CRL distribution points")),
250   ARGPARSE_s_s (oHTTPProxy,  "http-proxy",
251                 N_("|URL|redirect all HTTP requests to URL")),
252   ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy",
253                 N_("use system's HTTP proxy setting")),
254   ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"),
255 
256 
257   ARGPARSE_header ("LDAP", N_("Configuration of LDAP servers to use")),
258 
259   ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")),
260   ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp",
261                 N_("ignore LDAP CRL distribution points")),
262   ARGPARSE_s_s (oLDAPProxy,  "ldap-proxy",
263                 N_("|HOST|use HOST for LDAP queries")),
264   ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy",
265                 N_("do not use fallback hosts with --ldap-proxy")),
266   ARGPARSE_s_s (oLDAPServer, "ldapserver",
267                 N_("|SPEC|use this keyserver to lookup keys")),
268   ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file",
269                 N_("|FILE|read LDAP server list from FILE")),
270   ARGPARSE_s_n (oLDAPAddServers, "add-servers",
271                 N_("add new servers discovered in CRL distribution"
272                    " points to serverlist")),
273   ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout",
274                 N_("|N|set LDAP timeout to N seconds")),
275 
276 
277   ARGPARSE_header ("OCSP", N_("Configuration for OCSP")),
278 
279   ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")),
280   ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url",
281                 N_("ignore certificate contained OCSP service URLs")),
282   ARGPARSE_s_s (oOCSPResponder, "ocsp-responder",
283                 N_("|URL|use OCSP responder at URL")),
284   ARGPARSE_s_s (oOCSPSigner, "ocsp-signer",
285                 N_("|FPR|OCSP response signed by FPR")),
286   ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"),
287   ARGPARSE_s_i (oOCSPMaxPeriod,    "ocsp-max-period", "@"),
288   ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"),
289 
290 
291   ARGPARSE_header (NULL, N_("Other options")),
292 
293   ARGPARSE_s_n (oForce,    "force",    N_("force loading of outdated CRLs")),
294   ARGPARSE_s_s (oSocketName, "socket-name", "@"),  /* Only for debugging.  */
295 
296 
297   ARGPARSE_header (NULL, ""),  /* Stop the header group.  */
298 
299   /* Not yet used options.  */
300   ARGPARSE_s_n (oBatch,    "batch",       "@"),
301   ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"),
302 
303 
304   ARGPARSE_group (302,N_("@\n(See the \"info\" manual for a complete listing "
305                          "of all commands and options)\n")),
306 
307   ARGPARSE_end ()
308 };
309 
310 /* The list of supported debug flags.  */
311 static struct debug_flags_s debug_flags [] =
312   {
313     { DBG_X509_VALUE   , "x509"    },
314     { DBG_CRYPTO_VALUE , "crypto"  },
315     { DBG_MEMORY_VALUE , "memory"  },
316     { DBG_CACHE_VALUE  , "cache"   },
317     { DBG_MEMSTAT_VALUE, "memstat" },
318     { DBG_HASHING_VALUE, "hashing" },
319     { DBG_IPC_VALUE    , "ipc"     },
320     { DBG_DNS_VALUE    , "dns"     },
321     { DBG_NETWORK_VALUE, "network" },
322     { DBG_LOOKUP_VALUE , "lookup"  },
323     { DBG_EXTPROG_VALUE, "extprog" },
324     { 77, NULL } /* 77 := Do not exit on "help" or "?".  */
325   };
326 
327 #define DEFAULT_MAX_REPLIES 10
328 #define DEFAULT_LDAP_TIMEOUT 15  /* seconds */
329 
330 #define DEFAULT_CONNECT_TIMEOUT       (15*1000)  /* 15 seconds */
331 #define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000)  /*  2 seconds */
332 
333 /* For the cleanup handler we need to keep track of the socket's name.  */
334 static const char *socket_name;
335 /* If the socket has been redirected, this is the name of the
336    redirected socket..  */
337 static const char *redir_socket_name;
338 
339 /* We need to keep track of the server's nonces (these are dummies for
340    POSIX systems). */
341 static assuan_sock_nonce_t socket_nonce;
342 
343 /* Value for the listen() backlog argument.
344  * Change at runtime with --listen-backlog.  */
345 static int listen_backlog = 64;
346 
347 /* Only if this flag has been set will we remove the socket file.  */
348 static int cleanup_socket;
349 
350 /* Keep track of the current log file so that we can avoid updating
351    the log file after a SIGHUP if it didn't changed. Malloced. */
352 static char *current_logfile;
353 
354 /* Helper to implement --debug-level. */
355 static const char *debug_level;
356 
357 /* Helper to set the NTBTLS or GNUTLS log level.  */
358 static int opt_gnutls_debug = -1;
359 
360 /* Flag indicating that a shutdown has been requested.  */
361 static volatile int shutdown_pending;
362 
363 /* Flags to indicate that we shall not watch our own socket. */
364 static int disable_check_own_socket;
365 
366 /* Flag to control the Tor mode.  */
367 static enum
368   { TOR_MODE_AUTO = 0,  /* Switch to NO or YES         */
369     TOR_MODE_NEVER,     /* Never use Tor.              */
370     TOR_MODE_NO,        /* Do not use Tor              */
371     TOR_MODE_YES,       /* Use Tor                     */
372     TOR_MODE_FORCE      /* Force using Tor             */
373   } tor_mode;
374 
375 
376 /* Counter for the active connections.  */
377 static int active_connections;
378 
379 /* This flag is set by any network access and used by the housekeeping
380  * thread to run background network tasks.  */
381 static int network_activity_seen;
382 
383 /* A list of filenames registered with --hkp-cacert.  */
384 static strlist_t hkp_cacert_filenames;
385 
386 /* A flag used to clear the list of ldapservers iff --ldapserver is
387  * given on the command line or one of the conf files. In this case we
388  * want to clear all old specifications through the legacy
389  * dirmngr_ldapservers.conf. */
390 static int ldapserver_list_needs_reset;
391 
392 /* The timer tick used for housekeeping stuff.  The second constant is used when a shutdown is pending.  */
393 #define TIMERTICK_INTERVAL           (60)
394 #define TIMERTICK_INTERVAL_SHUTDOWN  (4)
395 
396 /* How oft to run the housekeeping.  */
397 #define HOUSEKEEPING_INTERVAL      (600)
398 
399 
400 /* This union is used to avoid compiler warnings in case a pointer is
401    64 bit and an int 32 bit.  We store an integer in a pointer and get
402    it back later (npth_getspecific et al.).  */
403 union int_and_ptr_u
404 {
405   int  aint;
406   assuan_fd_t afd;
407   void *aptr;
408 };
409 
410 
411 
412 /* The key used to store the current file descriptor in the thread
413    local storage.  We use this in conjunction with the
414    log_set_pid_suffix_cb feature.  */
415 #ifndef HAVE_W32_SYSTEM
416 static npth_key_t my_tlskey_current_fd;
417 #endif
418 
419 /* Prototypes. */
420 static void cleanup (void);
421 #if USE_LDAP
422 static ldap_server_t parse_ldapserver_file (const char* filename, int ienoent);
423 #endif /*USE_LDAP*/
424 static fingerprint_list_t parse_fingerprint_item (const char *string,
425                                                   const  char *optionname,
426                                                   int want_binary);
427 static void netactivity_action (void);
428 static void handle_connections (assuan_fd_t listen_fd);
429 static void gpgconf_versions (void);
430 
431 
432 /* NPth wrapper function definitions. */
433 ASSUAN_SYSTEM_NPTH_IMPL;
434 
435 static const char *
my_strusage(int level)436 my_strusage( int level )
437 {
438   const char *p;
439   switch ( level )
440     {
441     case  9: p = "GPL-3.0-or-later"; break;
442     case 11: p = "@DIRMNGR@ (@GNUPG@)";
443       break;
444     case 13: p = VERSION; break;
445     case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
446     case 17: p = PRINTABLE_OS_NAME; break;
447       /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
448          reporting address.  This is so that we can change the
449          reporting address without breaking the translations.  */
450     case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
451     case 49: p = PACKAGE_BUGREPORT; break;
452     case 1:
453     case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)");
454       break;
455     case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n"
456                    "Keyserver, CRL, and OCSP access for @GNUPG@\n");
457       break;
458 
459     default: p = NULL;
460     }
461   return p;
462 }
463 
464 
465 /* Callback from libksba to hash a provided buffer.  Our current
466    implementation does only allow SHA-1 for hashing. This may be
467    extended by mapping the name, testing for algorithm availability
468    and adjust the length checks accordingly. */
469 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)470 my_ksba_hash_buffer (void *arg, const char *oid,
471                      const void *buffer, size_t length, size_t resultsize,
472                      unsigned char *result, size_t *resultlen)
473 {
474   (void)arg;
475 
476   if (oid && strcmp (oid, "1.3.14.3.2.26"))
477     return gpg_error (GPG_ERR_NOT_SUPPORTED);
478   if (resultsize < 20)
479     return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
480   gcry_md_hash_buffer (2, result, buffer, length);
481   *resultlen = 20;
482   return 0;
483 }
484 
485 
486 /* GNUTLS log function callback.  */
487 #ifdef HTTP_USE_GNUTLS
488 static void
my_gnutls_log(int level,const char * text)489 my_gnutls_log (int level, const char *text)
490 {
491   int n;
492 
493   n = strlen (text);
494   while (n && text[n-1] == '\n')
495     n--;
496 
497   log_debug ("gnutls:L%d: %.*s\n", level, n, text);
498 }
499 #endif /*HTTP_USE_GNUTLS*/
500 
501 /* Setup the debugging.  With a LEVEL of NULL only the active debug
502    flags are propagated to the subsystems.  With LEVEL set, a specific
503    set of debug flags is set; thus overriding all flags already
504    set. */
505 static void
set_debug(void)506 set_debug (void)
507 {
508   int numok = (debug_level && digitp (debug_level));
509   int numlvl = numok? atoi (debug_level) : 0;
510 
511   if (!debug_level)
512     ;
513   else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
514     opt.debug = 0;
515   else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
516     opt.debug = DBG_IPC_VALUE;
517   else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
518     opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE);
519   else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
520     opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE
521                  |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
522   else if (!strcmp (debug_level, "guru") || numok)
523     {
524       opt.debug = ~0;
525       /* Unless the "guru" string has been used we don't want to allow
526          hashing debugging.  The rationale is that people tend to
527          select the highest debug value and would then clutter their
528          disk with debug files which may reveal confidential data.  */
529       if (numok)
530         opt.debug &= ~(DBG_HASHING_VALUE);
531     }
532   else
533     {
534       log_error (_("invalid debug-level '%s' given\n"), debug_level);
535       log_info (_("valid debug levels are: %s\n"),
536                 "none, basic, advanced, expert, guru");
537       opt.debug = 0; /* Reset debugging, so that prior debug
538                         statements won't have an undesired effect. */
539     }
540 
541 
542   if (opt.debug && !opt.verbose)
543     {
544       opt.verbose = 1;
545       gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
546     }
547   if (opt.debug && opt.quiet)
548     opt.quiet = 0;
549 
550   if (opt.debug & DBG_CRYPTO_VALUE )
551     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
552 
553 #if HTTP_USE_NTBTLS
554   if (opt_gnutls_debug >= 0)
555     {
556       ntbtls_set_debug (opt_gnutls_debug, NULL, NULL);
557     }
558 #elif HTTP_USE_GNUTLS
559   if (opt_gnutls_debug >= 0)
560     {
561       gnutls_global_set_log_function (my_gnutls_log);
562       gnutls_global_set_log_level (opt_gnutls_debug);
563     }
564 #endif /*HTTP_USE_GNUTLS*/
565 
566   if (opt.debug)
567     parse_debug_flag (NULL, &opt.debug, debug_flags);
568 }
569 
570 
571 static void
set_tor_mode(void)572 set_tor_mode (void)
573 {
574   if (dirmngr_use_tor ())
575     {
576       /* Enable Tor mode and when called again force a new circuit
577        * (e.g. on SIGHUP).  */
578       enable_dns_tormode (1);
579       if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
580         {
581           log_error ("error enabling Tor mode: %s\n", strerror (errno));
582           log_info ("(is your Libassuan recent enough?)\n");
583         }
584     }
585   else
586     disable_dns_tormode ();
587 }
588 
589 
590 /* Return true if Tor shall be used.  */
591 int
dirmngr_use_tor(void)592 dirmngr_use_tor (void)
593 {
594   if (tor_mode == TOR_MODE_AUTO)
595     {
596       /* Figure out whether Tor is running.  */
597       assuan_fd_t sock;
598 
599       sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR);
600       if (sock == ASSUAN_INVALID_FD)
601         tor_mode = TOR_MODE_NO;
602       else
603         {
604           tor_mode = TOR_MODE_YES;
605           assuan_sock_close (sock);
606         }
607     }
608 
609   if (tor_mode == TOR_MODE_FORCE)
610     return 2; /* Use Tor (using 2 to indicate force mode) */
611   else if (tor_mode == TOR_MODE_YES)
612     return 1; /* Use Tor */
613   else
614     return 0; /* Do not use Tor.  */
615 }
616 
617 
618 static void
wrong_args(const char * text)619 wrong_args (const char *text)
620 {
621   es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME);
622   es_fputs (text, es_stderr);
623   es_putc ('\n', es_stderr);
624   dirmngr_exit (2);
625 }
626 
627 
628 /* Helper to stop the reaper thread for the ldap wrapper.  */
629 static void
shutdown_reaper(void)630 shutdown_reaper (void)
631 {
632 #if USE_LDAP
633   ldap_wrapper_wait_connections ();
634 #endif
635 }
636 
637 
638 /* Handle options which are allowed to be reset after program start.
639    Return true if the current option in PARGS could be handled and
640    false if not.  As a special feature, passing a value of NULL for
641    PARGS, resets the options to the default.  REREAD should be set
642    true if it is not the initial option parsing. */
643 static int
parse_rereadable_options(gpgrt_argparse_t * pargs,int reread)644 parse_rereadable_options (gpgrt_argparse_t *pargs, int reread)
645 {
646   if (!pargs)
647     { /* Reset mode. */
648       opt.quiet = 0;
649       opt.verbose = 0;
650       opt.debug = 0;
651       opt.ldap_wrapper_program = NULL;
652       opt.disable_http = 0;
653       opt.disable_ldap = 0;
654       opt.honor_http_proxy = 0;
655       opt.http_proxy = NULL;
656       opt.ldap_proxy = NULL;
657       opt.only_ldap_proxy = 0;
658       opt.ignore_http_dp = 0;
659       opt.ignore_ldap_dp = 0;
660       opt.ignore_ocsp_service_url = 0;
661       opt.allow_ocsp = 0;
662       opt.allow_version_check = 0;
663       opt.ocsp_responder = NULL;
664       opt.ocsp_max_clock_skew = 10 * 60;      /* 10 minutes.  */
665       opt.ocsp_max_period = 90 * 86400;       /* 90 days.  */
666       opt.ocsp_current_period = 3 * 60 * 60;  /* 3 hours. */
667       opt.max_replies = DEFAULT_MAX_REPLIES;
668       while (opt.ocsp_signer)
669         {
670           fingerprint_list_t tmp = opt.ocsp_signer->next;
671           xfree (opt.ocsp_signer);
672           opt.ocsp_signer = tmp;
673         }
674       while (opt.ignored_certs)
675         {
676           fingerprint_list_t tmp = opt.ignored_certs->next;
677           xfree (opt.ignored_certs);
678           opt.ignored_certs = tmp;
679         }
680       FREE_STRLIST (opt.ignored_cert_extensions);
681       http_register_tls_ca (NULL);
682       FREE_STRLIST (hkp_cacert_filenames);
683       FREE_STRLIST (opt.keyserver);
684       /* Note: We do not allow resetting of TOR_MODE_FORCE at runtime.  */
685       if (tor_mode != TOR_MODE_FORCE)
686         tor_mode = TOR_MODE_AUTO;
687       disable_check_own_socket = 0;
688       enable_standard_resolver (0);
689       set_dns_timeout (0);
690       opt.connect_timeout = 0;
691       opt.connect_quick_timeout = 0;
692       opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
693       ldapserver_list_needs_reset = 1;
694       return 1;
695     }
696 
697   switch (pargs->r_opt)
698     {
699     case oQuiet:   opt.quiet = 1; break;
700     case oVerbose: opt.verbose++; break;
701     case oDebug:
702       parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
703       break;
704     case oDebugAll: opt.debug = ~0; break;
705     case oDebugLevel: debug_level = pargs->r.ret_str; break;
706     case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break;
707 
708     case oLogFile:
709       if (!reread)
710         return 0; /* Not handled. */
711       if (!current_logfile || !pargs->r.ret_str
712           || strcmp (current_logfile, pargs->r.ret_str))
713         {
714           log_set_file (pargs->r.ret_str);
715           xfree (current_logfile);
716           current_logfile = xtrystrdup (pargs->r.ret_str);
717         }
718       break;
719 
720     case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
721 
722     case oLDAPWrapperProgram:
723       opt.ldap_wrapper_program = pargs->r.ret_str;
724       break;
725     case oHTTPWrapperProgram:
726       opt.http_wrapper_program = pargs->r.ret_str;
727       break;
728 
729     case oDisableHTTP: opt.disable_http = 1; break;
730     case oDisableLDAP: opt.disable_ldap = 1; break;
731     case oDisableIPv4: opt.disable_ipv4 = 1; break;
732     case oDisableIPv6: opt.disable_ipv6 = 1; break;
733     case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
734     case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
735     case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
736     case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
737     case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
738     case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
739     case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
740 
741     case oAllowOCSP: opt.allow_ocsp = 1; break;
742     case oAllowVersionCheck: opt.allow_version_check = 1; break;
743     case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
744     case oOCSPSigner:
745       opt.ocsp_signer = parse_fingerprint_item (pargs->r.ret_str,
746                                                 "--ocsp-signer", 0);
747       break;
748     case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
749     case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
750     case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
751 
752     case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
753 
754     case oHkpCaCert:
755       {
756         /* We need to register the filenames with gnutls (http.c) and
757          * also for our own cert cache.  */
758         char *tmpname;
759 
760         /* Do tilde expansion and make path absolute.  */
761         tmpname = make_absfilename (pargs->r.ret_str, NULL);
762         http_register_tls_ca (tmpname);
763         add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str);
764         xfree (tmpname);
765       }
766       break;
767 
768     case oIgnoreCert:
769       {
770         fingerprint_list_t item, r;
771         item = parse_fingerprint_item (pargs->r.ret_str, "--ignore-cert", 20);
772         if (item)
773           {  /* Append  */
774             if (!opt.ignored_certs)
775               opt.ignored_certs = item;
776             else
777               {
778                 for (r = opt.ignored_certs; r->next; r = r->next)
779                   ;
780                 r->next = item;
781               }
782           }
783       }
784       break;
785 
786     case oIgnoreCertExtension:
787       add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
788       break;
789 
790     case oUseTor:
791       tor_mode = TOR_MODE_FORCE;
792       break;
793     case oNoUseTor:
794       if (tor_mode != TOR_MODE_FORCE)
795         tor_mode = TOR_MODE_NEVER;
796       break;
797 
798     case oStandardResolver: enable_standard_resolver (1); break;
799     case oRecursiveResolver: enable_recursive_resolver (1); break;
800 
801     case oLDAPServer:
802 #if USE_LDAP
803       {
804         ldap_server_t server;
805         char *p;
806 
807         p = pargs->r.ret_str;
808         if (!strncmp (p, "ldap:", 5) && !(p[5] == '/' && p[6] == '/'))
809           p += 5;
810 
811         server = ldapserver_parse_one (p, NULL, 0);
812         if (server)
813           {
814             if (ldapserver_list_needs_reset)
815               {
816                 ldapserver_list_needs_reset = 0;
817                 ldapserver_list_free (opt.ldapservers);
818                 opt.ldapservers = NULL;
819               }
820             server->next = opt.ldapservers;
821             opt.ldapservers = server;
822           }
823       }
824 #endif
825       break;
826 
827     case oKeyServer:
828       if (*pargs->r.ret_str)
829         add_to_strlist (&opt.keyserver, pargs->r.ret_str);
830       break;
831 
832     case oNameServer:
833       set_dns_nameserver (pargs->r.ret_str);
834       break;
835 
836     case oResolverTimeout:
837       set_dns_timeout (pargs->r.ret_int);
838       break;
839 
840     case oConnectTimeout:
841       opt.connect_timeout = pargs->r.ret_ulong * 1000;
842       break;
843 
844     case oConnectQuickTimeout:
845       opt.connect_quick_timeout = pargs->r.ret_ulong * 1000;
846       break;
847 
848     case oLDAPTimeout:
849       opt.ldaptimeout = pargs->r.ret_int;
850       break;
851 
852     default:
853       return 0; /* Not handled. */
854     }
855 
856   set_dns_verbose (opt.verbose, !!DBG_DNS);
857   http_set_verbose (opt.verbose, !!DBG_NETWORK);
858   set_dns_disable_ipv4 (opt.disable_ipv4);
859   set_dns_disable_ipv6 (opt.disable_ipv6);
860 
861   return 1; /* Handled. */
862 }
863 
864 
865 /* This function is called after option parsing to adjust some values
866  * and call option setup functions.  */
867 static void
post_option_parsing(void)868 post_option_parsing (void)
869 {
870   /* It would be too surpirsing if the quick timeout is larger than
871    * the standard value.  */
872   if (opt.connect_quick_timeout > opt.connect_timeout)
873     opt.connect_quick_timeout = opt.connect_timeout;
874 
875   set_debug ();
876 }
877 
878 
879 #ifndef HAVE_W32_SYSTEM
880 static int
pid_suffix_callback(unsigned long * r_suffix)881 pid_suffix_callback (unsigned long *r_suffix)
882 {
883   union int_and_ptr_u value;
884 
885   memset (&value, 0, sizeof value);
886   value.aptr = npth_getspecific (my_tlskey_current_fd);
887   *r_suffix = value.aint;
888   return (*r_suffix != -1);  /* Use decimal representation.  */
889 }
890 #endif /*!HAVE_W32_SYSTEM*/
891 
892 #if HTTP_USE_NTBTLS
893 static void
my_ntbtls_log_handler(void * opaque,int level,const char * fmt,va_list argv)894 my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv)
895 {
896   (void)opaque;
897 
898   if (level == -1)
899     log_logv_prefix (GPGRT_LOGLVL_INFO, "ntbtls: ", fmt, argv);
900   else
901     {
902       char prefix[10+20];
903       snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level);
904       log_logv_prefix (GPGRT_LOGLVL_DEBUG, prefix, fmt, argv);
905     }
906 }
907 #endif
908 
909 
910 static void
thread_init(void)911 thread_init (void)
912 {
913   npth_init ();
914   assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
915   gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
916 
917   /* Now with NPth running we can set the logging callback.  Our
918      windows implementation does not yet feature the NPth TLS
919      functions.  */
920 #ifndef HAVE_W32_SYSTEM
921   if (npth_key_create (&my_tlskey_current_fd, NULL) == 0)
922     if (npth_setspecific (my_tlskey_current_fd, NULL) == 0)
923       log_set_pid_suffix_cb (pid_suffix_callback);
924 #endif /*!HAVE_W32_SYSTEM*/
925 }
926 
927 
928 int
main(int argc,char ** argv)929 main (int argc, char **argv)
930 {
931   enum cmd_and_opt_values cmd = 0;
932   gpgrt_argparse_t pargs;
933   int orig_argc;
934   char **orig_argv;
935   char *last_configname = NULL;
936   const char *configname = NULL;
937   const char *shell;
938   int debug_argparser = 0;
939   int greeting = 0;
940   int nogreeting = 0;
941   int nodetach = 0;
942   int csh_style = 0;
943   char *logfile = NULL;
944 #if USE_LDAP
945   char *ldapfile = NULL;
946 #endif /*USE_LDAP*/
947   int debug_wait = 0;
948   int rc;
949   struct assuan_malloc_hooks malloc_hooks;
950 
951   early_system_init ();
952   gpgrt_set_strusage (my_strusage);
953   log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
954 
955   /* Make sure that our subsystems are ready.  */
956   i18n_init ();
957   init_common_subsystems (&argc, &argv);
958 
959   gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
960 
961  /* Check that the libraries are suitable.  Do it here because
962     the option parsing may need services of the libraries. */
963   if (!ksba_check_version (NEED_KSBA_VERSION) )
964     log_fatal( _("%s is too old (need %s, have %s)\n"), "libksba",
965                NEED_KSBA_VERSION, ksba_check_version (NULL) );
966 
967   ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
968   ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
969 
970   /* Init TLS library.  */
971 #if HTTP_USE_NTBTLS
972   if (!ntbtls_check_version (NEED_NTBTLS_VERSION) )
973     log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls",
974                NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) );
975 #elif HTTP_USE_GNUTLS
976   rc = gnutls_global_init ();
977   if (rc)
978     log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));
979 #endif /*HTTP_USE_GNUTLS*/
980 
981   /* Init Assuan. */
982   malloc_hooks.malloc = gcry_malloc;
983   malloc_hooks.realloc = gcry_realloc;
984   malloc_hooks.free = gcry_free;
985   assuan_set_malloc_hooks (&malloc_hooks);
986   assuan_set_assuan_log_prefix (log_get_prefix (NULL));
987   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
988   assuan_sock_init ();
989   setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor);
990 
991   setup_libgcrypt_logging ();
992 
993 #if HTTP_USE_NTBTLS
994   ntbtls_set_log_handler (my_ntbtls_log_handler, NULL);
995 #endif
996 
997   /* Setup defaults. */
998   shell = getenv ("SHELL");
999   if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
1000     csh_style = 1;
1001 
1002   /* Reset rereadable options to default values. */
1003   parse_rereadable_options (NULL, 0);
1004 
1005   /* Default TCP timeouts.  */
1006   opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT;
1007   opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT;
1008 
1009   /* LDAP defaults.  */
1010   opt.add_new_ldapservers = 0;
1011   opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
1012 
1013   /* Other defaults.  */
1014 
1015   /* Check whether we have a config file given on the commandline */
1016   orig_argc = argc;
1017   orig_argv = argv;
1018   pargs.argc = &argc;
1019   pargs.argv = &argv;
1020   pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1021   while (gpgrt_argparse (NULL, &pargs, opts))
1022     {
1023       switch (pargs.r_opt)
1024         {
1025         case oDebug:
1026         case oDebugAll:
1027           debug_argparser++;
1028           break;
1029         case oHomedir:
1030           gnupg_set_homedir (pargs.r.ret_str);
1031           break;
1032         }
1033     }
1034   /* Reset the flags.  */
1035   pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
1036 
1037   socket_name = dirmngr_socket_name ();
1038 
1039   /* The configuraton directories for use by gpgrt_argparser.  */
1040   gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
1041   gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
1042 
1043   /* We are re-using the struct, thus the reset flag.  We OR the
1044    * flags so that the internal intialized flag won't be cleared. */
1045   argc = orig_argc;
1046   argv = orig_argv;
1047   pargs.argc = &argc;
1048   pargs.argv = &argv;
1049   pargs.flags |=  (ARGPARSE_FLAG_RESET
1050                    | ARGPARSE_FLAG_KEEP
1051                    | ARGPARSE_FLAG_SYS
1052                    | ARGPARSE_FLAG_USER);
1053   while (gpgrt_argparser (&pargs, opts, DIRMNGR_NAME EXTSEP_S "conf"))
1054     {
1055       if (pargs.r_opt == ARGPARSE_CONFFILE)
1056         {
1057           if (debug_argparser)
1058             log_info (_("reading options from '%s'\n"),
1059                       pargs.r_type? pargs.r.ret_str: "[cmdline]");
1060           if (pargs.r_type)
1061             {
1062               xfree (last_configname);
1063               last_configname = xstrdup (pargs.r.ret_str);
1064               configname = last_configname;
1065             }
1066           else
1067             configname = NULL;
1068           continue;
1069         }
1070       if (parse_rereadable_options (&pargs, 0))
1071         continue; /* Already handled */
1072       switch (pargs.r_opt)
1073         {
1074         case aServer:
1075         case aDaemon:
1076         case aSupervised:
1077         case aShutdown:
1078         case aFlush:
1079 	case aListCRLs:
1080 	case aLoadCRL:
1081         case aFetchCRL:
1082 	case aGPGConfList:
1083 	case aGPGConfTest:
1084 	case aGPGConfVersions:
1085           cmd = pargs.r_opt;
1086           break;
1087 
1088         case oQuiet: opt.quiet = 1; break;
1089         case oVerbose: opt.verbose++; break;
1090         case oBatch: opt.batch=1; break;
1091 
1092         case oDebugWait: debug_wait = pargs.r.ret_int; break;
1093 
1094         case oNoGreeting: nogreeting = 1; break;
1095         case oNoVerbose: opt.verbose = 0; break;
1096         case oHomedir: /* Ignore this option here. */; break;
1097         case oNoDetach: nodetach = 1; break;
1098         case oLogFile: logfile = pargs.r.ret_str; break;
1099         case oCsh: csh_style = 1; break;
1100         case oSh: csh_style = 0; break;
1101 	case oLDAPFile:
1102 #        if USE_LDAP
1103           ldapfile = pargs.r.ret_str;
1104 #        endif /*USE_LDAP*/
1105           break;
1106 	case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
1107 
1108         case oFakedSystemTime:
1109           gnupg_set_time ((time_t)pargs.r.ret_ulong, 0);
1110           break;
1111 
1112         case oForce: opt.force = 1; break;
1113 
1114         case oSocketName: socket_name = pargs.r.ret_str; break;
1115 
1116         case oListenBacklog:
1117           listen_backlog = pargs.r.ret_int;
1118           break;
1119 
1120         default:
1121           if (configname)
1122             pargs.err = ARGPARSE_PRINT_WARNING;
1123           else
1124             pargs.err = ARGPARSE_PRINT_ERROR;
1125           break;
1126 	}
1127     }
1128   gpgrt_argparse (NULL, &pargs, NULL);  /* Release internal state.  */
1129 
1130   if (!last_configname)
1131     opt.config_filename = gpgrt_fnameconcat (gnupg_homedir (),
1132                                              DIRMNGR_NAME EXTSEP_S "conf",
1133                                              NULL);
1134   else
1135     {
1136       opt.config_filename = last_configname;
1137       last_configname = NULL;
1138     }
1139 
1140   if (log_get_errorcount(0))
1141     exit(2);
1142 
1143   /* Get a default log file from common.conf.  */
1144   if (!logfile && !parse_comopt (GNUPG_MODULE_NAME_DIRMNGR, debug_argparser))
1145     {
1146       logfile = comopt.logfile;
1147       comopt.logfile = NULL;
1148     }
1149 
1150   if (nogreeting )
1151     greeting = 0;
1152 
1153   if (!opt.homedir_cache)
1154     opt.homedir_cache = xstrdup (gnupg_homedir ());
1155 
1156   if (greeting)
1157     {
1158       es_fprintf (es_stderr, "%s %s; %s\n",
1159                   gpgrt_strusage(11), gpgrt_strusage(13), gpgrt_strusage(14));
1160       es_fprintf (es_stderr, "%s\n", gpgrt_strusage(15));
1161     }
1162 
1163 #ifdef IS_DEVELOPMENT_VERSION
1164   log_info ("NOTE: this is a development version!\n");
1165 #endif
1166 
1167   /* Print a warning if an argument looks like an option.  */
1168   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1169     {
1170       int i;
1171 
1172       for (i=0; i < argc; i++)
1173         if (argv[i][0] == '-' && argv[i][1] == '-')
1174           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1175     }
1176 
1177   if (!gnupg_access ("/etc/"DIRMNGR_NAME, F_OK)
1178       && !strncmp (gnupg_homedir (), "/etc/", 5))
1179     log_info
1180       ("NOTE: DirMngr is now a proper part of %s.  The configuration and"
1181        " other directory names changed.  Please check that no other version"
1182        " of dirmngr is still installed.  To disable this warning, remove the"
1183        " directory '/etc/dirmngr'.\n", GNUPG_NAME);
1184 
1185   if (gnupg_faked_time_p ())
1186     {
1187       gnupg_isotime_t tbuf;
1188 
1189       log_info (_("WARNING: running with faked system time: "));
1190       gnupg_get_isotime (tbuf);
1191       dump_isotime (tbuf);
1192       log_printf ("\n");
1193     }
1194 
1195   /* Note that we do not run set_tor_mode in --gpgconf-list mode
1196    * because it will attempt to connect to the tor client and that can
1197    * be time consuming.  */
1198   post_option_parsing ();
1199   if (cmd != aGPGConfTest && cmd != aGPGConfList && cmd != aGPGConfVersions)
1200     set_tor_mode ();
1201 
1202   /* Get LDAP server list from file unless --ldapserver has been used.  */
1203 #if USE_LDAP
1204   if (opt.ldapservers)
1205     ;
1206   else if (!ldapfile)
1207     {
1208       ldapfile = make_filename (gnupg_homedir (),
1209                                 "dirmngr_ldapservers.conf",
1210                                 NULL);
1211       opt.ldapservers = parse_ldapserver_file (ldapfile, 1);
1212       xfree (ldapfile);
1213     }
1214   else
1215     opt.ldapservers = parse_ldapserver_file (ldapfile, 0);
1216 #endif /*USE_LDAP*/
1217 
1218 #ifndef HAVE_W32_SYSTEM
1219   /* We need to ignore the PIPE signal because the we might log to a
1220      socket and that code handles EPIPE properly.  The ldap wrapper
1221      also requires us to ignore this silly signal. Assuan would set
1222      this signal to ignore anyway.*/
1223   signal (SIGPIPE, SIG_IGN);
1224 #endif
1225 
1226   /* Ready.  Now to our duties. */
1227   if (!cmd)
1228     cmd = aServer;
1229   rc = 0;
1230 
1231   if (cmd == aServer)
1232     {
1233       /* Note that this server mode is mainly useful for debugging.  */
1234       if (argc)
1235         wrong_args ("--server");
1236 
1237       if (logfile)
1238         {
1239           log_set_file (logfile);
1240           log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
1241         }
1242 
1243       if (debug_wait)
1244         {
1245           log_debug ("waiting for debugger - my pid is %u .....\n",
1246                      (unsigned int)getpid());
1247           gnupg_sleep (debug_wait);
1248           log_debug ("... okay\n");
1249         }
1250 
1251 
1252       thread_init ();
1253       cert_cache_init (hkp_cacert_filenames);
1254       crl_cache_init ();
1255       ks_hkp_init ();
1256       http_register_netactivity_cb (netactivity_action);
1257       start_command_handler (ASSUAN_INVALID_FD, 0);
1258       shutdown_reaper ();
1259     }
1260 #ifndef HAVE_W32_SYSTEM
1261   else if (cmd == aSupervised)
1262     {
1263       /* In supervised mode, we expect file descriptor 3 to be an
1264          already opened, listening socket.
1265 
1266          We will also not detach from the controlling process or close
1267          stderr; the supervisor should handle all of that.  */
1268       struct stat statbuf;
1269       if (fstat (3, &statbuf) == -1 && errno == EBADF)
1270         {
1271           log_error ("file descriptor 3 must be validin --supervised mode\n");
1272           dirmngr_exit (1);
1273         }
1274       socket_name = gnupg_get_socket_name (3);
1275 
1276       /* Now start with logging to a file if this is desired. */
1277       if (logfile)
1278         {
1279           log_set_file (logfile);
1280           log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1281                                  |GPGRT_LOG_WITH_TIME
1282                                  |GPGRT_LOG_WITH_PID));
1283           current_logfile = xstrdup (logfile);
1284         }
1285       else
1286         log_set_prefix (NULL, 0);
1287 
1288       thread_init ();
1289       cert_cache_init (hkp_cacert_filenames);
1290       crl_cache_init ();
1291       ks_hkp_init ();
1292       http_register_netactivity_cb (netactivity_action);
1293       handle_connections (3);
1294       shutdown_reaper ();
1295     }
1296 #endif /*HAVE_W32_SYSTEM*/
1297   else if (cmd == aDaemon)
1298     {
1299       assuan_fd_t fd;
1300       pid_t pid;
1301       int len;
1302       struct sockaddr_un serv_addr;
1303 
1304       if (argc)
1305         wrong_args ("--daemon");
1306 
1307       /* Now start with logging to a file if this is desired. */
1308       if (logfile)
1309         {
1310           log_set_file (logfile);
1311           log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
1312                                  |GPGRT_LOG_WITH_TIME
1313                                  |GPGRT_LOG_WITH_PID));
1314           current_logfile = xstrdup (logfile);
1315         }
1316 
1317       if (debug_wait)
1318         {
1319           log_debug ("waiting for debugger - my pid is %u .....\n",
1320                      (unsigned int)getpid());
1321           gnupg_sleep (debug_wait);
1322           log_debug ("... okay\n");
1323         }
1324 
1325 #ifndef HAVE_W32_SYSTEM
1326       if (strchr (socket_name, ':'))
1327         {
1328           log_error (_("colons are not allowed in the socket name\n"));
1329           dirmngr_exit (1);
1330         }
1331 #endif
1332       fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1333       if (fd == ASSUAN_INVALID_FD)
1334         {
1335           log_error (_("can't create socket: %s\n"), strerror (errno));
1336           cleanup ();
1337           dirmngr_exit (1);
1338         }
1339 
1340       {
1341         int redirected;
1342 
1343         if (assuan_sock_set_sockaddr_un (socket_name,
1344                                          (struct sockaddr*)&serv_addr,
1345                                          &redirected))
1346           {
1347             if (errno == ENAMETOOLONG)
1348               log_error (_("socket name '%s' is too long\n"), socket_name);
1349             else
1350               log_error ("error preparing socket '%s': %s\n",
1351                          socket_name,
1352                          gpg_strerror (gpg_error_from_syserror ()));
1353             dirmngr_exit (1);
1354           }
1355         if (redirected)
1356           {
1357             redir_socket_name = xstrdup (serv_addr.sun_path);
1358             if (opt.verbose)
1359               log_info ("redirecting socket '%s' to '%s'\n",
1360                         socket_name, redir_socket_name);
1361           }
1362       }
1363 
1364       len = SUN_LEN (&serv_addr);
1365 
1366       rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1367       if (rc == -1
1368           && (errno == EADDRINUSE
1369 #ifdef HAVE_W32_SYSTEM
1370               || errno == EEXIST
1371 #endif
1372               ))
1373 	{
1374           /* Fixme: We should test whether a dirmngr is already running. */
1375 	  gnupg_remove (redir_socket_name? redir_socket_name : socket_name);
1376 	  rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1377 	}
1378       if (rc != -1
1379 	  && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
1380 	log_error (_("error getting nonce for the socket\n"));
1381       if (rc == -1)
1382         {
1383           log_error (_("error binding socket to '%s': %s\n"),
1384                      serv_addr.sun_path,
1385                      gpg_strerror (gpg_error_from_syserror ()));
1386           assuan_sock_close (fd);
1387           dirmngr_exit (1);
1388         }
1389       cleanup_socket = 1;
1390 
1391       if (gnupg_chmod (serv_addr.sun_path, "-rwx"))
1392         log_error (_("can't set permissions of '%s': %s\n"),
1393                    serv_addr.sun_path, strerror (errno));
1394 
1395       if (listen (FD2INT (fd), listen_backlog) == -1)
1396         {
1397           log_error ("listen(fd,%d) failed: %s\n",
1398                      listen_backlog, strerror (errno));
1399           assuan_sock_close (fd);
1400           dirmngr_exit (1);
1401         }
1402 
1403       if (opt.verbose)
1404         log_info (_("listening on socket '%s'\n"), serv_addr.sun_path);
1405 
1406       es_fflush (NULL);
1407 
1408       /* Note: We keep the dirmngr_info output only for the sake of
1409          existing scripts which might use this to detect a successful
1410          start of the dirmngr.  */
1411 #ifdef HAVE_W32_SYSTEM
1412       (void)csh_style;
1413       (void)nodetach;
1414 
1415       pid = getpid ();
1416       es_printf ("set %s=%s;%lu;1\n",
1417                  DIRMNGR_INFO_NAME, socket_name, (ulong) pid);
1418 #else
1419       pid = fork();
1420       if (pid == (pid_t)-1)
1421         {
1422           log_fatal (_("error forking process: %s\n"), strerror (errno));
1423           dirmngr_exit (1);
1424         }
1425 
1426       if (pid)
1427         { /* We are the parent */
1428           char *infostr;
1429 
1430           /* Don't let cleanup() remove the socket - the child is
1431              responsible for doing that.  */
1432           cleanup_socket = 0;
1433 
1434           close (fd);
1435 
1436           /* Create the info string: <name>:<pid>:<protocol_version> */
1437           if (asprintf (&infostr, "%s=%s:%lu:1",
1438                         DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0)
1439             {
1440               log_error (_("out of core\n"));
1441               kill (pid, SIGTERM);
1442               dirmngr_exit (1);
1443             }
1444           /* Print the environment string, so that the caller can use
1445              shell's eval to set it.  But see above.  */
1446           if (csh_style)
1447             {
1448               *strchr (infostr, '=') = ' ';
1449               es_printf ( "setenv %s;\n", infostr);
1450             }
1451           else
1452             {
1453               es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME);
1454             }
1455           free (infostr);
1456           exit (0);
1457           /*NEVER REACHED*/
1458         } /* end parent */
1459 
1460 
1461       /*
1462          This is the child
1463        */
1464 
1465       /* Detach from tty and put process into a new session */
1466       if (!nodetach )
1467         {
1468           int i;
1469           unsigned int oldflags;
1470 
1471           /* Close stdin, stdout and stderr unless it is the log stream */
1472           for (i=0; i <= 2; i++)
1473             {
1474               if (!log_test_fd (i) && i != fd )
1475                 {
1476                   if ( !close (i)
1477                        && open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
1478                     {
1479                       log_error ("failed to open '%s': %s\n",
1480                                  "/dev/null", strerror (errno));
1481                       cleanup ();
1482                       dirmngr_exit (1);
1483                     }
1484                 }
1485             }
1486 
1487           if (setsid() == -1)
1488             {
1489               log_error ("setsid() failed: %s\n", strerror(errno) );
1490               dirmngr_exit (1);
1491             }
1492 
1493           log_get_prefix (&oldflags);
1494           log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
1495           opt.running_detached = 1;
1496 
1497         }
1498 #endif
1499 
1500       if (!nodetach )
1501         {
1502           if (gnupg_chdir (gnupg_daemon_rootdir ()))
1503             {
1504               log_error ("chdir to '%s' failed: %s\n",
1505                          gnupg_daemon_rootdir (), strerror (errno));
1506               dirmngr_exit (1);
1507             }
1508         }
1509 
1510       thread_init ();
1511       cert_cache_init (hkp_cacert_filenames);
1512       crl_cache_init ();
1513       ks_hkp_init ();
1514       http_register_netactivity_cb (netactivity_action);
1515       handle_connections (fd);
1516       shutdown_reaper ();
1517     }
1518   else if (cmd == aListCRLs)
1519     {
1520       /* Just list the CRL cache and exit. */
1521       if (argc)
1522         wrong_args ("--list-crls");
1523       crl_cache_init ();
1524       crl_cache_list (es_stdout);
1525     }
1526   else if (cmd == aLoadCRL)
1527     {
1528       struct server_control_s ctrlbuf;
1529 
1530       memset (&ctrlbuf, 0, sizeof ctrlbuf);
1531       dirmngr_init_default_ctrl (&ctrlbuf);
1532 
1533       thread_init ();
1534       cert_cache_init (hkp_cacert_filenames);
1535       crl_cache_init ();
1536       ks_hkp_init ();
1537       if (!argc)
1538         rc = crl_cache_load (&ctrlbuf, NULL);
1539       else
1540         {
1541           for (; !rc && argc; argc--, argv++)
1542             rc = crl_cache_load (&ctrlbuf, *argv);
1543         }
1544       dirmngr_deinit_default_ctrl (&ctrlbuf);
1545     }
1546   else if (cmd == aFetchCRL)
1547     {
1548       ksba_reader_t reader;
1549       struct server_control_s ctrlbuf;
1550 
1551       if (argc != 1)
1552         wrong_args ("--fetch-crl URL");
1553 
1554       memset (&ctrlbuf, 0, sizeof ctrlbuf);
1555       dirmngr_init_default_ctrl (&ctrlbuf);
1556 
1557       thread_init ();
1558       cert_cache_init (hkp_cacert_filenames);
1559       crl_cache_init ();
1560       ks_hkp_init ();
1561       rc = crl_fetch (&ctrlbuf, argv[0], &reader);
1562       if (rc)
1563         log_error (_("fetching CRL from '%s' failed: %s\n"),
1564                      argv[0], gpg_strerror (rc));
1565       else
1566         {
1567           rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
1568           if (rc)
1569             log_error (_("processing CRL from '%s' failed: %s\n"),
1570                        argv[0], gpg_strerror (rc));
1571           crl_close_reader (reader);
1572         }
1573       dirmngr_deinit_default_ctrl (&ctrlbuf);
1574     }
1575   else if (cmd == aFlush)
1576     {
1577       /* Delete cache and exit. */
1578       if (argc)
1579         wrong_args ("--flush");
1580       rc = crl_cache_flush();
1581     }
1582   else if (cmd == aGPGConfTest)
1583     dirmngr_exit (0);
1584   else if (cmd == aGPGConfList)
1585     {
1586       unsigned long flags = 0;
1587       char *filename_esc;
1588 
1589       es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
1590       es_printf ("ldaptimeout:%lu:%u\n",
1591                  flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
1592       es_printf ("max-replies:%lu:%u\n",
1593                  flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
1594 
1595       filename_esc = percent_escape (get_default_keyserver (0), NULL);
1596       es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT,
1597                  filename_esc);
1598       xfree (filename_esc);
1599 
1600       es_printf ("resolver-timeout:%lu:%u\n",
1601                  flags | GC_OPT_FLAG_DEFAULT, 0);
1602     }
1603   else if (cmd == aGPGConfVersions)
1604     gpgconf_versions ();
1605 
1606   cleanup ();
1607   return !!rc;
1608 }
1609 
1610 
1611 static void
cleanup(void)1612 cleanup (void)
1613 {
1614   crl_cache_deinit ();
1615   cert_cache_deinit (1);
1616   reload_dns_stuff (1);
1617 
1618 #if USE_LDAP
1619   ldapserver_list_free (opt.ldapservers);
1620 #endif /*USE_LDAP*/
1621   opt.ldapservers = NULL;
1622 
1623   if (cleanup_socket)
1624     {
1625       cleanup_socket = 0;
1626       if (redir_socket_name)
1627         gnupg_remove (redir_socket_name);
1628       else if (socket_name && *socket_name)
1629         gnupg_remove (socket_name);
1630     }
1631 }
1632 
1633 
1634 void
dirmngr_exit(int rc)1635 dirmngr_exit (int rc)
1636 {
1637   cleanup ();
1638   exit (rc);
1639 }
1640 
1641 
1642 void
dirmngr_init_default_ctrl(ctrl_t ctrl)1643 dirmngr_init_default_ctrl (ctrl_t ctrl)
1644 {
1645   ctrl->magic = SERVER_CONTROL_MAGIC;
1646   if (opt.http_proxy)
1647     ctrl->http_proxy = xstrdup (opt.http_proxy);
1648   ctrl->http_no_crl = 1;
1649   ctrl->timeout = opt.connect_timeout;
1650 }
1651 
1652 
1653 void
dirmngr_deinit_default_ctrl(ctrl_t ctrl)1654 dirmngr_deinit_default_ctrl (ctrl_t ctrl)
1655 {
1656   if (!ctrl)
1657     return;
1658   ctrl->magic = 0xdeadbeef;
1659 
1660   xfree (ctrl->http_proxy);
1661   ctrl->http_proxy = NULL;
1662 }
1663 
1664 
1665 /* Create a list of LDAP servers from the file FILENAME. Returns the
1666    list or NULL in case of errors.
1667 
1668    The format of such a file is line oriented where empty lines and
1669    lines starting with a hash mark are ignored.  All other lines are
1670    assumed to be colon seprated with these fields:
1671 
1672    1. field: Hostname
1673    2. field: Portnumber
1674    3. field: Username
1675    4. field: Password
1676    5. field: Base DN
1677 
1678 */
1679 #if USE_LDAP
1680 static ldap_server_t
parse_ldapserver_file(const char * filename,int ignore_enoent)1681 parse_ldapserver_file (const char* filename, int ignore_enoent)
1682 {
1683   char buffer[1024];
1684   char *p;
1685   ldap_server_t server, serverstart, *serverend;
1686   int c;
1687   unsigned int lineno = 0;
1688   estream_t fp;
1689 
1690   fp = es_fopen (filename, "r");
1691   if (!fp)
1692     {
1693       if (ignore_enoent && gpg_err_code_from_syserror () == GPG_ERR_ENOENT)
1694         ;
1695       else
1696         log_info ("failed to open '%s': %s\n", filename, strerror (errno));
1697       return NULL;
1698     }
1699 
1700   serverstart = NULL;
1701   serverend = &serverstart;
1702   while (es_fgets (buffer, sizeof buffer, fp))
1703     {
1704       lineno++;
1705       if (!*buffer || buffer[strlen(buffer)-1] != '\n')
1706         {
1707           if (*buffer && es_feof (fp))
1708             ; /* Last line not terminated - continue. */
1709           else
1710             {
1711               log_error (_("%s:%u: line too long - skipped\n"),
1712                          filename, lineno);
1713               while ( (c=es_fgetc (fp)) != EOF && c != '\n')
1714                 ; /* Skip until end of line. */
1715               continue;
1716             }
1717         }
1718       /* Skip empty and comment lines.*/
1719       for (p=buffer; spacep (p); p++)
1720         ;
1721       if (!*p || *p == '\n' || *p == '#')
1722         continue;
1723 
1724       /* Parse the colon separated fields. */
1725       server = ldapserver_parse_one (buffer, filename, lineno);
1726       if (server)
1727         {
1728           *serverend = server;
1729           serverend = &server->next;
1730         }
1731     }
1732 
1733   if (es_ferror (fp))
1734     log_error (_("error reading '%s': %s\n"), filename, strerror (errno));
1735   es_fclose (fp);
1736 
1737   return serverstart;
1738 }
1739 #endif /*USE_LDAP*/
1740 
1741 
1742 /* Parse a fingerprint entry as used by --ocsc-signer.  OPTIONNAME as
1743  * a description on the options used.  WANT_BINARY requests to store a
1744  * binary fingerprint.  Returns NULL on error and logs that error. */
1745 static fingerprint_list_t
parse_fingerprint_item(const char * string,const char * optionname,int want_binary)1746 parse_fingerprint_item (const char *string,
1747                         const char *optionname, int want_binary)
1748 {
1749   gpg_error_t err;
1750   char *fname;
1751   estream_t fp;
1752   char line[256];
1753   char *p;
1754   fingerprint_list_t list, *list_tail, item;
1755   unsigned int lnr = 0;
1756   int c, i, j;
1757   int errflag = 0;
1758 
1759 
1760   /* Check whether this is not a filename and treat it as a direct
1761      fingerprint specification.  */
1762   if (!strpbrk (string, "/.~\\"))
1763     {
1764       item = xcalloc (1, sizeof *item);
1765       for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
1766         if ( string[i] != ':' )
1767           item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
1768       item->hexfpr[j] = 0;
1769       if (j != 40 || !(spacep (string+i) || !string[i]))
1770         {
1771           log_error (_("%s:%u: invalid fingerprint detected\n"),
1772                      optionname, 0);
1773           xfree (item);
1774           return NULL;
1775         }
1776       if (want_binary)
1777         {
1778           item->binlen = 20;
1779           hex2bin (item->hexfpr, item->hexfpr, 20);
1780         }
1781       return item;
1782     }
1783 
1784   /* Well, it is a filename.  */
1785   if (*string == '/' || (*string == '~' && string[1] == '/'))
1786     fname = make_filename (string, NULL);
1787   else
1788     {
1789       if (string[0] == '.' && string[1] == '/' )
1790         string += 2;
1791       fname = make_filename (gnupg_homedir (), string, NULL);
1792     }
1793 
1794   fp = es_fopen (fname, "r");
1795   if (!fp)
1796     {
1797       err = gpg_error_from_syserror ();
1798       log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
1799       xfree (fname);
1800       return NULL;
1801     }
1802 
1803   list = NULL;
1804   list_tail = &list;
1805   for (;;)
1806     {
1807       if (!es_fgets (line, DIM(line)-1, fp) )
1808         {
1809           if (!es_feof (fp))
1810             {
1811               err = gpg_error_from_syserror ();
1812               log_error (_("%s:%u: read error: %s\n"),
1813                          fname, lnr, gpg_strerror (err));
1814               errflag = 1;
1815             }
1816           es_fclose (fp);
1817           if (errflag)
1818             {
1819               while (list)
1820                 {
1821                   fingerprint_list_t tmp = list->next;
1822                   xfree (list);
1823                   list = tmp;
1824                 }
1825             }
1826           xfree (fname);
1827           return list; /* Ready.  */
1828         }
1829 
1830       lnr++;
1831       if (!*line || line[strlen(line)-1] != '\n')
1832         {
1833           /* Eat until end of line. */
1834           while ( (c=es_getc (fp)) != EOF && c != '\n')
1835             ;
1836           err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
1837                            /* */: GPG_ERR_INCOMPLETE_LINE);
1838           log_error (_("%s:%u: read error: %s\n"),
1839                      fname, lnr, gpg_strerror (err));
1840           errflag = 1;
1841           continue;
1842         }
1843 
1844       /* Allow for empty lines and spaces */
1845       for (p=line; spacep (p); p++)
1846         ;
1847       if (!*p || *p == '\n' || *p == '#')
1848         continue;
1849 
1850       item = xcalloc (1, sizeof *item);
1851       *list_tail = item;
1852       list_tail = &item->next;
1853 
1854       for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
1855         if ( p[i] != ':' )
1856           item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
1857       item->hexfpr[j] = 0;
1858       if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
1859         {
1860           log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
1861           errflag = 1;
1862         }
1863       else if (want_binary)
1864         {
1865           item->binlen = 20;
1866           hex2bin (item->hexfpr, item->hexfpr, 20);
1867         }
1868 
1869       i++;
1870       while (spacep (p+i))
1871         i++;
1872       if (p[i] && p[i] != '\n')
1873         log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
1874     }
1875   /*NOTREACHED*/
1876 }
1877 
1878 
1879 
1880 
1881 /*
1882    Stuff used in daemon mode.
1883  */
1884 
1885 
1886 
1887 /* Reread parts of the configuration.  Note, that this function is
1888    obviously not thread-safe and should only be called from the NPTH
1889    signal handler.
1890 
1891    Fixme: Due to the way the argument parsing works, we create a
1892    memory leak here for all string type arguments.  There is currently
1893    no clean way to tell whether the memory for the argument has been
1894    allocated or points into the process's original arguments.  Unless
1895    we have a mechanism to tell this, we need to live on with this. */
1896 static void
reread_configuration(void)1897 reread_configuration (void)
1898 {
1899   gpgrt_argparse_t pargs;
1900   char *twopart;
1901   int dummy;
1902   int logfile_seen = 0;
1903 
1904   if (!opt.config_filename)
1905     goto finish; /* No config file. */
1906 
1907   twopart = strconcat (DIRMNGR_NAME EXTSEP_S "conf" PATHSEP_S,
1908                        opt.config_filename, NULL);
1909   if (!twopart)
1910     return;  /* Out of core.  */
1911 
1912   parse_rereadable_options (NULL, 1); /* Start from the default values. */
1913 
1914   memset (&pargs, 0, sizeof pargs);
1915   dummy = 0;
1916   pargs.argc = &dummy;
1917   pargs.flags = (ARGPARSE_FLAG_KEEP
1918                  |ARGPARSE_FLAG_SYS
1919                  |ARGPARSE_FLAG_USER);
1920   while (gpgrt_argparser (&pargs, opts, twopart))
1921     {
1922       if (pargs.r_opt == ARGPARSE_CONFFILE)
1923         {
1924           log_info (_("reading options from '%s'\n"),
1925                     pargs.r_type? pargs.r.ret_str: "[cmdline]");
1926         }
1927       else if (pargs.r_opt < -1)
1928         pargs.err = ARGPARSE_PRINT_WARNING;
1929       else /* Try to parse this option - ignore unchangeable ones. */
1930         {
1931           if (pargs.r_opt == oLogFile)
1932             logfile_seen = 1;
1933           parse_rereadable_options (&pargs, 1);
1934         }
1935     }
1936   gpgrt_argparse (NULL, &pargs, NULL);  /* Release internal state.  */
1937   xfree (twopart);
1938   post_option_parsing ();
1939 
1940  finish:
1941   /* Get a default log file from common.conf.  */
1942   if (!logfile_seen && !parse_comopt (GNUPG_MODULE_NAME_DIRMNGR, !!opt.debug))
1943     {
1944       if (!current_logfile || !comopt.logfile
1945           || strcmp (current_logfile, comopt.logfile))
1946         {
1947           log_set_file (comopt.logfile);
1948           xfree (current_logfile);
1949           current_logfile = comopt.logfile? xtrystrdup (comopt.logfile) : NULL;
1950         }
1951     }
1952 }
1953 
1954 
1955 /* A global function which allows us to trigger the reload stuff from
1956    other places.  */
1957 void
dirmngr_sighup_action(void)1958 dirmngr_sighup_action (void)
1959 {
1960   log_info (_("SIGHUP received - "
1961               "re-reading configuration and flushing caches\n"));
1962   reread_configuration ();
1963   set_tor_mode ();
1964   cert_cache_deinit (0);
1965   crl_cache_deinit ();
1966   cert_cache_init (hkp_cacert_filenames);
1967   crl_cache_init ();
1968   reload_dns_stuff (0);
1969   ks_hkp_reload ();
1970 }
1971 
1972 
1973 /* This function is called if some network activity was done.  At this
1974  * point we know the we have a network and we can decide whether to
1975  * run scheduled background tasks soon.  The function should return
1976  * quickly and only trigger actions for another thread. */
1977 static void
netactivity_action(void)1978 netactivity_action (void)
1979 {
1980   network_activity_seen = 1;
1981 }
1982 
1983 
1984 /* The signal handler. */
1985 #ifndef HAVE_W32_SYSTEM
1986 static void
handle_signal(int signo)1987 handle_signal (int signo)
1988 {
1989   switch (signo)
1990     {
1991     case SIGHUP:
1992       dirmngr_sighup_action ();
1993       break;
1994 
1995     case SIGUSR1:
1996       cert_cache_print_stats ();
1997       domaininfo_print_stats ();
1998       break;
1999 
2000     case SIGUSR2:
2001       log_info (_("SIGUSR2 received - no action defined\n"));
2002       break;
2003 
2004     case SIGTERM:
2005       if (!shutdown_pending)
2006         log_info (_("SIGTERM received - shutting down ...\n"));
2007       else
2008         log_info (_("SIGTERM received - still %d active connections\n"),
2009                   active_connections);
2010       shutdown_pending++;
2011       if (shutdown_pending > 2)
2012         {
2013           log_info (_("shutdown forced\n"));
2014           log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2015           cleanup ();
2016           dirmngr_exit (0);
2017 	}
2018       break;
2019 
2020     case SIGINT:
2021       log_info (_("SIGINT received - immediate shutdown\n"));
2022       log_info( "%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2023       cleanup ();
2024       dirmngr_exit (0);
2025       break;
2026 
2027     default:
2028       log_info (_("signal %d received - no action defined\n"), signo);
2029     }
2030 }
2031 #endif /*!HAVE_W32_SYSTEM*/
2032 
2033 
2034 /* Thread to do the housekeeping.  */
2035 static void *
housekeeping_thread(void * arg)2036 housekeeping_thread (void *arg)
2037 {
2038   static int sentinel;
2039   time_t curtime;
2040   struct server_control_s ctrlbuf;
2041 
2042   (void)arg;
2043 
2044   curtime = gnupg_get_time ();
2045   if (sentinel)
2046     {
2047       log_info ("housekeeping is already going on\n");
2048       return NULL;
2049     }
2050   sentinel++;
2051   if (opt.verbose > 1)
2052     log_info ("starting housekeeping\n");
2053 
2054   memset (&ctrlbuf, 0, sizeof ctrlbuf);
2055   dirmngr_init_default_ctrl (&ctrlbuf);
2056 
2057   dns_stuff_housekeeping ();
2058   ks_hkp_housekeeping (curtime);
2059   if (network_activity_seen)
2060     {
2061       network_activity_seen = 0;
2062       if (opt.allow_version_check)
2063         dirmngr_load_swdb (&ctrlbuf, 0);
2064       workqueue_run_global_tasks (&ctrlbuf, 1);
2065     }
2066   else
2067     workqueue_run_global_tasks (&ctrlbuf, 0);
2068 
2069   dirmngr_deinit_default_ctrl (&ctrlbuf);
2070 
2071   if (opt.verbose > 1)
2072     log_info ("ready with housekeeping\n");
2073   sentinel--;
2074   return NULL;
2075 
2076 }
2077 
2078 
2079 /* We try to enable correct overflow handling for signed int (commonly
2080  * used for time_t). With gcc 4.2 -fno-strict-overflow was introduced
2081  * and used here as a pragma.  Later gcc versions (gcc 6?) removed
2082  * this as a pragma and -fwrapv was then suggested as a replacement
2083  * for -fno-strict-overflow.  */
2084 #if GPGRT_HAVE_PRAGMA_GCC_PUSH
2085 # pragma GCC push_options
2086 # pragma GCC optimize ("wrapv")
2087 #endif
2088 static int
time_for_housekeeping_p(time_t curtime)2089 time_for_housekeeping_p (time_t curtime)
2090 {
2091   static time_t last_housekeeping;
2092 
2093   if (!last_housekeeping)
2094     last_housekeeping = curtime;
2095 
2096   if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime
2097       || last_housekeeping > curtime /*(be prepared for y2038)*/)
2098     {
2099       last_housekeeping = curtime;
2100       return 1;
2101     }
2102   return 0;
2103 }
2104 #if GPGRT_HAVE_PRAGMA_GCC_PUSH
2105 # pragma GCC pop_options
2106 #endif
2107 
2108 
2109 /* This is the worker for the ticker.  It is called every few seconds
2110    and may only do fast operations. */
2111 static void
handle_tick(void)2112 handle_tick (void)
2113 {
2114   struct stat statbuf;
2115 
2116   if (time_for_housekeeping_p (gnupg_get_time ()))
2117     {
2118       npth_t thread;
2119       npth_attr_t tattr;
2120       int err;
2121 
2122       err = npth_attr_init (&tattr);
2123       if (err)
2124         log_error ("error preparing housekeeping thread: %s\n", strerror (err));
2125       else
2126         {
2127           npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2128           err = npth_create (&thread, &tattr, housekeeping_thread, NULL);
2129           if (err)
2130             log_error ("error spawning housekeeping thread: %s\n",
2131                        strerror (err));
2132           npth_attr_destroy (&tattr);
2133         }
2134     }
2135 
2136   /* Check whether the homedir is still available.  */
2137   if (!shutdown_pending
2138       && gnupg_stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
2139     {
2140       shutdown_pending = 1;
2141       log_info ("homedir has been removed - shutting down\n");
2142     }
2143 }
2144 
2145 
2146 /* Check the nonce on a new connection.  This is a NOP unless we are
2147    using our Unix domain socket emulation under Windows.  */
2148 static int
check_nonce(assuan_fd_t fd,assuan_sock_nonce_t * nonce)2149 check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
2150 {
2151   if (assuan_sock_check_nonce (fd, nonce))
2152     {
2153       log_info (_("error reading nonce on fd %d: %s\n"),
2154                 FD2INT (fd), strerror (errno));
2155       assuan_sock_close (fd);
2156       return -1;
2157     }
2158   else
2159     return 0;
2160 }
2161 
2162 
2163 /* Helper to call a connection's main function. */
2164 static void *
start_connection_thread(void * arg)2165 start_connection_thread (void *arg)
2166 {
2167   static unsigned int last_session_id;
2168   unsigned int session_id;
2169   union int_and_ptr_u argval;
2170   gnupg_fd_t fd;
2171 
2172   memset (&argval, 0, sizeof argval);
2173   argval.aptr = arg;
2174   fd = argval.afd;
2175 
2176   if (check_nonce (fd, &socket_nonce))
2177     {
2178       log_error ("handler nonce check FAILED\n");
2179       return NULL;
2180     }
2181 
2182 #ifndef HAVE_W32_SYSTEM
2183   npth_setspecific (my_tlskey_current_fd, argval.aptr);
2184 #endif
2185 
2186   active_connections++;
2187   if (opt.verbose)
2188     log_info (_("handler for fd %d started\n"), FD2INT (fd));
2189 
2190   session_id = ++last_session_id;
2191   if (!session_id)
2192     session_id = ++last_session_id;
2193   start_command_handler (fd, session_id);
2194 
2195   if (opt.verbose)
2196     log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
2197   active_connections--;
2198 
2199   workqueue_run_post_session_tasks (session_id);
2200 
2201 #ifndef HAVE_W32_SYSTEM
2202   argval.afd = ASSUAN_INVALID_FD;
2203   npth_setspecific (my_tlskey_current_fd, argval.aptr);
2204 #endif
2205 
2206   return NULL;
2207 }
2208 
2209 
2210 #ifdef HAVE_INOTIFY_INIT
2211 /* Read an inotify event and return true if it matches NAME.  */
2212 static int
my_inotify_is_name(int fd,const char * name)2213 my_inotify_is_name (int fd, const char *name)
2214 {
2215   union {
2216     struct inotify_event ev;
2217     char _buf[sizeof (struct inotify_event) + 100 + 1];
2218   } buf;
2219   int n;
2220   const char *s;
2221 
2222   s = strrchr (name, '/');
2223   if (s && s[1])
2224     name = s + 1;
2225 
2226   n = npth_read (fd, &buf, sizeof buf);
2227   if (n < sizeof (struct inotify_event))
2228     return 0;
2229   if (buf.ev.len < strlen (name)+1)
2230     return 0;
2231   if (strcmp (buf.ev.name, name))
2232     return 0; /* Not the desired file.  */
2233 
2234   return 1; /* Found.  */
2235 }
2236 #endif /*HAVE_INOTIFY_INIT*/
2237 
2238 
2239 /* Main loop in daemon mode.  Note that LISTEN_FD will be owned by
2240  * this function. */
2241 static void
handle_connections(assuan_fd_t listen_fd)2242 handle_connections (assuan_fd_t listen_fd)
2243 {
2244   npth_attr_t tattr;
2245 #ifndef HAVE_W32_SYSTEM
2246   int signo;
2247 #endif
2248   struct sockaddr_un paddr;
2249   socklen_t plen = sizeof( paddr );
2250   int nfd, ret;
2251   fd_set fdset, read_fdset;
2252   struct timespec abstime;
2253   struct timespec curtime;
2254   struct timespec timeout;
2255   int saved_errno;
2256   int my_inotify_fd = -1;
2257 
2258   npth_attr_init (&tattr);
2259   npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
2260 
2261 #ifndef HAVE_W32_SYSTEM /* FIXME */
2262   npth_sigev_init ();
2263   npth_sigev_add (SIGHUP);
2264   npth_sigev_add (SIGUSR1);
2265   npth_sigev_add (SIGUSR2);
2266   npth_sigev_add (SIGINT);
2267   npth_sigev_add (SIGTERM);
2268   npth_sigev_fini ();
2269 #endif
2270 
2271 #ifdef HAVE_INOTIFY_INIT
2272   if (disable_check_own_socket)
2273     my_inotify_fd = -1;
2274   else if ((my_inotify_fd = inotify_init ()) == -1)
2275     log_info ("error enabling fast daemon termination: %s\n",
2276               strerror (errno));
2277   else
2278     {
2279       /* We need to watch the directory for the file because there
2280        * won't be an IN_DELETE_SELF for a socket file.  */
2281       char *slash = strrchr (socket_name, '/');
2282       log_assert (slash && slash[1]);
2283       *slash = 0;
2284       if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1)
2285         {
2286           close (my_inotify_fd);
2287           my_inotify_fd = -1;
2288         }
2289       *slash = '/';
2290     }
2291 #endif /*HAVE_INOTIFY_INIT*/
2292 
2293 
2294   /* Setup the fdset.  It has only one member.  This is because we use
2295      pth_select instead of pth_accept to properly sync timeouts with
2296      to full second.  */
2297   FD_ZERO (&fdset);
2298   FD_SET (FD2INT (listen_fd), &fdset);
2299   nfd = FD2INT (listen_fd);
2300   if (my_inotify_fd != -1)
2301     {
2302       FD_SET (my_inotify_fd, &fdset);
2303       if (my_inotify_fd > nfd)
2304         nfd = my_inotify_fd;
2305     }
2306 
2307   npth_clock_gettime (&abstime);
2308   abstime.tv_sec += TIMERTICK_INTERVAL;
2309 
2310   /* Main loop.  */
2311   for (;;)
2312     {
2313       /* Shutdown test.  */
2314       if (shutdown_pending)
2315         {
2316           if (!active_connections)
2317             break; /* ready */
2318 
2319           /* Do not accept new connections but keep on running the
2320            * loop to cope with the timer events.
2321            *
2322            * Note that we do not close the listening socket because a
2323            * client trying to connect to that socket would instead
2324            * restart a new dirmngr instance - which is unlikely the
2325            * intention of a shutdown. */
2326           /* assuan_sock_close (listen_fd); */
2327           /* listen_fd = -1; */
2328           FD_ZERO (&fdset);
2329           nfd = -1;
2330           if (my_inotify_fd != -1)
2331             {
2332               FD_SET (my_inotify_fd, &fdset);
2333               nfd = my_inotify_fd;
2334             }
2335 	}
2336 
2337       /* Take a copy of the fdset.  */
2338       read_fdset = fdset;
2339 
2340       npth_clock_gettime (&curtime);
2341       if (!(npth_timercmp (&curtime, &abstime, <)))
2342 	{
2343 	  /* Timeout.  When a shutdown is pending we use a shorter
2344            * interval to handle the shutdown more quickly.  */
2345 	  handle_tick ();
2346 	  npth_clock_gettime (&abstime);
2347 	  abstime.tv_sec += (shutdown_pending
2348                              ? TIMERTICK_INTERVAL_SHUTDOWN
2349                              : TIMERTICK_INTERVAL);
2350 	}
2351       npth_timersub (&abstime, &curtime, &timeout);
2352 
2353 #ifndef HAVE_W32_SYSTEM
2354       ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
2355                           npth_sigev_sigmask());
2356       saved_errno = errno;
2357 
2358       while (npth_sigev_get_pending(&signo))
2359 	handle_signal (signo);
2360 #else
2361       ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
2362       saved_errno = errno;
2363 #endif
2364 
2365       if (ret == -1 && saved_errno != EINTR)
2366 	{
2367           log_error (_("npth_pselect failed: %s - waiting 1s\n"),
2368                      strerror (saved_errno));
2369           gnupg_sleep (1);
2370           continue;
2371 	}
2372 
2373       if (ret <= 0)
2374         {
2375           /* Interrupt or timeout.  Will be handled when calculating the
2376              next timeout.  */
2377           continue;
2378         }
2379 
2380       if (shutdown_pending)
2381         {
2382           /* Do not anymore accept connections.  */
2383           continue;
2384         }
2385 
2386 #ifdef HAVE_INOTIFY_INIT
2387       if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset)
2388           && my_inotify_is_name (my_inotify_fd, socket_name))
2389         {
2390           shutdown_pending = 1;
2391           log_info ("socket file has been removed - shutting down\n");
2392         }
2393 #endif /*HAVE_INOTIFY_INIT*/
2394 
2395       if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
2396 	{
2397           gnupg_fd_t fd;
2398 
2399           plen = sizeof paddr;
2400 	  fd = INT2FD (npth_accept (FD2INT(listen_fd),
2401 				    (struct sockaddr *)&paddr, &plen));
2402 	  if (fd == GNUPG_INVALID_FD)
2403 	    {
2404 	      log_error ("accept failed: %s\n", strerror (errno));
2405 	    }
2406           else
2407             {
2408               char threadname[50];
2409               union int_and_ptr_u argval;
2410 	      npth_t thread;
2411 
2412               memset (&argval, 0, sizeof argval);
2413               argval.afd = fd;
2414               snprintf (threadname, sizeof threadname,
2415                         "conn fd=%d", FD2INT(fd));
2416 
2417               ret = npth_create (&thread, &tattr,
2418                                  start_connection_thread, argval.aptr);
2419 	      if (ret)
2420                 {
2421                   log_error ("error spawning connection handler: %s\n",
2422                              strerror (ret) );
2423                   assuan_sock_close (fd);
2424                 }
2425 	      npth_setname_np (thread, threadname);
2426             }
2427 	}
2428     }
2429 
2430 #ifdef HAVE_INOTIFY_INIT
2431   if (my_inotify_fd != -1)
2432     close (my_inotify_fd);
2433 #endif /*HAVE_INOTIFY_INIT*/
2434   npth_attr_destroy (&tattr);
2435   if (listen_fd != GNUPG_INVALID_FD)
2436     assuan_sock_close (listen_fd);
2437   cleanup ();
2438   log_info ("%s %s stopped\n", gpgrt_strusage(11), gpgrt_strusage(13));
2439 }
2440 
2441 const char*
dirmngr_get_current_socket_name(void)2442 dirmngr_get_current_socket_name (void)
2443 {
2444   if (socket_name)
2445     return socket_name;
2446   else
2447     return dirmngr_socket_name ();
2448 }
2449 
2450 
2451 
2452 /* Parse the revision part from the extended version blurb.  */
2453 static const char *
get_revision_from_blurb(const char * blurb,int * r_len)2454 get_revision_from_blurb (const char *blurb, int *r_len)
2455 {
2456   const char *s = blurb? blurb : "";
2457   int n;
2458 
2459   for (; *s; s++)
2460     if (*s == '\n' && s[1] == '(')
2461       break;
2462   if (*s)
2463     {
2464       s += 2;
2465       for (n=0; s[n] && s[n] != ' '; n++)
2466         ;
2467     }
2468   else
2469     {
2470       s = "?";
2471       n = 1;
2472     }
2473   *r_len = n;
2474   return s;
2475 }
2476 
2477 
2478 /* Print versions of dirmngr and used libraries.  This is used by
2479  * "gpgconf --show-versions" so that there is no need to link gpgconf
2480  * against all these libraries.  This is an internal API and should
2481  * not be relied upon.  */
2482 static void
gpgconf_versions(void)2483 gpgconf_versions (void)
2484 {
2485   const char *s;
2486   int n;
2487 
2488   /* Unfortunately Npth has no way to get the version.  */
2489 
2490   s = get_revision_from_blurb (assuan_check_version ("\x01\x01"), &n);
2491   es_fprintf (es_stdout, "* Libassuan %s (%.*s)\n\n",
2492               assuan_check_version (NULL), n, s);
2493 
2494   s = get_revision_from_blurb (ksba_check_version ("\x01\x01"), &n);
2495   es_fprintf (es_stdout, "* KSBA %s (%.*s)\n\n",
2496               ksba_check_version (NULL), n, s);
2497 
2498 #ifdef HTTP_USE_NTBTLS
2499   s = get_revision_from_blurb (ntbtls_check_version ("\x01\x01"), &n);
2500   es_fprintf (es_stdout, "* NTBTLS %s (%.*s)\n\n",
2501               ntbtls_check_version (NULL), n, s);
2502 #elif HTTP_USE_GNUTLS
2503   es_fprintf (es_stdout, "* GNUTLS %s\n\n",
2504               gnutls_check_version (NULL));
2505 #endif
2506 
2507 }
2508