1 /* dirmngr.c - LDAP access
2 * Copyright (C) 2002 Klarälvdalens Datakonsult AB
3 * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2010 g10 Code GmbH
4 *
5 * This file is part of DirMngr.
6 *
7 * DirMngr is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * DirMngr is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 * 02110-1301, USA.
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 #include <signal.h>
41 #include <pth.h>
42
43 #include <gcrypt.h>
44 #include <ksba.h>
45 #include <assuan.h> /* Needed for the malloc and socket hooks */
46
47 #define JNLIB_NEED_LOG_LOGV
48 #include "dirmngr.h"
49 #include "certcache.h"
50 #include "crlcache.h"
51 #include "crlfetch.h"
52 #include "misc.h"
53 #include "i18n.h"
54 #include "ldapserver.h"
55
56 #ifdef HAVE_W32_SYSTEM
57 #define sleep _sleep
58 #define FD2INT(h) ((unsigned int) (h))
59 #else
60 #define FD2INT(h) (h)
61 #endif
62
63 enum cmd_and_opt_values
64 { aNull = 0,
65 oCsh = 'c',
66 oQuiet = 'q',
67 oSh = 's',
68 oVerbose = 'v',
69 oNoVerbose = 500,
70
71 aServer,
72 aDaemon,
73 aService,
74 aListCRLs,
75 aLoadCRL,
76 aFetchCRL,
77 aShutdown,
78 aFlush,
79 aGPGConfList,
80 aGPGConfTest,
81
82 oOptions,
83 oDebug,
84 oDebugAll,
85 oDebugWait,
86 oDebugLevel,
87 oNoGreeting,
88 oNoOptions,
89 oHomedir,
90 oNoDetach,
91 oLogFile,
92 oBatch,
93 oDisableHTTP,
94 oDisableLDAP,
95 oIgnoreLDAPDP,
96 oIgnoreHTTPDP,
97 oIgnoreOCSPSvcUrl,
98 oHonorHTTPProxy,
99 oHTTPProxy,
100 oLDAPProxy,
101 oOnlyLDAPProxy,
102 oLDAPFile,
103 oLDAPTimeout,
104 oLDAPAddServers,
105 oOCSPResponder,
106 oOCSPSigner,
107 oOCSPMaxClockSkew,
108 oOCSPMaxPeriod,
109 oOCSPCurrentPeriod,
110 oMaxReplies,
111 oFakedSystemTime,
112 oForce,
113 oAllowOCSP,
114 oSocketName,
115 oLDAPWrapperProgram,
116 oHTTPWrapperProgram,
117 oIgnoreCertExtension,
118 aTest };
119
120
121
122 static ARGPARSE_OPTS opts[] = {
123
124 { 300, NULL, 0, N_("@Commands:\n ") },
125
126 { aServer, "server", 256, N_("run in server mode (foreground)") },
127 { aDaemon, "daemon", 256, N_("run in daemon mode (background)") },
128 #ifdef HAVE_W32_SYSTEM
129 { aService, "service", 256, N_("run as windows service (background)") },
130 #endif
131 { aListCRLs, "list-crls", 256, N_("list the contents of the CRL cache")},
132 { aLoadCRL, "load-crl", 256, N_("|FILE|load CRL from FILE into cache")},
133 { aFetchCRL, "fetch-crl", 256, N_("|URL|fetch a CRL from URL")},
134 { aShutdown, "shutdown", 256, N_("shutdown the dirmngr")},
135 { aFlush, "flush", 256, N_("flush the cache")},
136 { aGPGConfList, "gpgconf-list", 256, "@" },
137 { aGPGConfTest, "gpgconf-test", 256, "@" },
138
139 { 301, NULL, 0, N_("@\nOptions:\n ") },
140
141 { oVerbose, "verbose", 0, N_("verbose") },
142 { oQuiet, "quiet", 0, N_("be somewhat more quiet") },
143 { oSh, "sh", 0, N_("sh-style command output") },
144 { oCsh, "csh", 0, N_("csh-style command output") },
145 { oOptions, "options" , 2, N_("|FILE|read options from FILE")},
146 { oDebugLevel, "debug-level",2,
147 N_("|LEVEL|set the debugging level to LEVEL")},
148 { oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
149 { oLogFile, "log-file" ,2, N_("|FILE|write server mode logs to FILE")},
150 { oBatch , "batch" ,0, N_("run without asking a user")},
151 { oForce, "force" ,0, N_("force loading of outdated CRLs")},
152 { oAllowOCSP, "allow-ocsp",0,N_("allow sending OCSP requests")},
153 { oDisableHTTP, "disable-http", 0, N_("inhibit the use of HTTP")},
154 { oDisableLDAP, "disable-ldap", 0, N_("inhibit the use of LDAP")},
155 { oIgnoreHTTPDP,"ignore-http-dp", 0,
156 N_("ignore HTTP CRL distribution points")},
157 { oIgnoreLDAPDP,"ignore-ldap-dp", 0,
158 N_("ignore LDAP CRL distribution points")},
159 { oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url", 0,
160 N_("ignore certificate contained OCSP service URLs")},
161 /* Note: The next one is to fix a typo in gpgconf - should be
162 removed eventually. */
163 { oIgnoreOCSPSvcUrl, "ignore-ocsp-servic-url", 0, "@"},
164
165 { oHTTPProxy, "http-proxy", 2,
166 N_("|URL|redirect all HTTP requests to URL")},
167 { oLDAPProxy, "ldap-proxy", 2,
168 N_("|HOST|use HOST for LDAP queries")},
169 { oOnlyLDAPProxy, "only-ldap-proxy", 0,
170 N_("do not use fallback hosts with --ldap-proxy")},
171
172 { oLDAPFile, "ldapserverlist-file", 2,
173 N_("|FILE|read LDAP server list from FILE")},
174 { oLDAPAddServers, "add-servers", 0,
175 N_("add new servers discovered in CRL distribution points to serverlist")},
176 { oLDAPTimeout, "ldaptimeout", 1,
177 N_("|N|set LDAP timeout to N seconds")},
178
179 { oOCSPResponder, "ocsp-responder", 2, N_("|URL|use OCSP responder at URL")},
180 { oOCSPSigner, "ocsp-signer", 2, N_("|FPR|OCSP response signed by FPR")},
181 { oOCSPMaxClockSkew, "ocsp-max-clock-skew", 1, "@" },
182 { oOCSPMaxPeriod, "ocsp-max-period", 1, "@" },
183 { oOCSPCurrentPeriod, "ocsp-current-period", 1, "@" },
184
185 { oMaxReplies, "max-replies", 1,
186 N_("|N|do not return more than N items in one query")},
187
188 { oSocketName, "socket-name", 2, N_("|FILE|listen on socket FILE") },
189
190 { oFakedSystemTime, "faked-system-time", 4, "@" }, /* (epoch time) */
191 { oDebug, "debug" ,4|16, "@"},
192 { oDebugAll, "debug-all" ,0, "@"},
193 { oDebugWait, "debug-wait", 1, "@"},
194 { oNoGreeting, "no-greeting", 0, "@"},
195 { oHomedir, "homedir", 2, "@" },
196 { oLDAPWrapperProgram, "ldap-wrapper-program", 2, "@"},
197 { oHTTPWrapperProgram, "http-wrapper-program", 2, "@"},
198 { oHonorHTTPProxy, "honor-http-proxy", 0, "@" },
199 { oIgnoreCertExtension,"ignore-cert-extension", 2, "@"},
200
201 { 302, NULL, 0, N_("@\n(See the \"info\" manual for a complete listing "
202 "of all commands and options)\n")},
203
204 { 0, NULL, 0, NULL }
205 };
206
207 #define DEFAULT_MAX_REPLIES 10
208 #define DEFAULT_LDAP_TIMEOUT 100 /* arbitrary large timeout */
209
210 /* For the cleanup handler we need to keep track of the socket's name. */
211 static const char *socket_name;
212
213 /* We need to keep track of the server's nonces (these are dummies for
214 POSIX systems). */
215 static assuan_sock_nonce_t socket_nonce;
216
217 /* Only if this flag has been set we will remove the socket file. */
218 static int cleanup_socket;
219
220 /* Keep track of the current log file so that we can avoid updating
221 the log file after a SIGHUP if it didn't changed. Malloced. */
222 static char *current_logfile;
223
224 /* Helper to implement --debug-level. */
225 static const char *debug_level;
226
227 /* Flag indicating that a shutdown has been requested. */
228 static volatile int shutdown_pending;
229
230 /* Counter for the active connections. */
231 static int active_connections;
232
233 /* The timer tick used for housekeeping stuff. For Windows we use a
234 longer period as the SetWaitableTimer seems to signal earlier than
235 the 2 seconds. */
236 #ifdef HAVE_W32_SYSTEM
237 #define TIMERTICK_INTERVAL (4)
238 #else
239 #define TIMERTICK_INTERVAL (2) /* Seconds. */
240 #endif
241
242 /* This union is used to avoid compiler warnings in case a pointer is
243 64 bit and an int 32 bit. We store an integer in a pointer and get
244 it back later (pth_key_getdata et al.). */
245 union int_and_ptr_u
246 {
247 int aint;
248 assuan_fd_t afd;
249 void *aptr;
250 };
251
252
253
254 /* The key used to store the current file descriptor in the thread
255 local storage. We use this in conjunction with the
256 log_set_pid_suffix_cb feature.. */
257 #ifndef HAVE_W32_SYSTEM
258 static int my_tlskey_current_fd;
259 #endif
260
261 /* Prototypes. */
262 static void cleanup (void);
263 static ldap_server_t parse_ldapserver_file (const char* filename);
264 static fingerprint_list_t parse_ocsp_signer (const char *string);
265 static void handle_connections (assuan_fd_t listen_fd);
266
267 /* Pth wrapper function definitions. */
268 ASSUAN_SYSTEM_PTH_IMPL;
269
270 GCRY_THREAD_OPTION_PTH_IMPL;
271
272 static const char *
my_strusage(int level)273 my_strusage( int level )
274 {
275 const char *p;
276 switch ( level )
277 {
278 case 11: p = "dirmngr";
279 break;
280 case 13: p = VERSION; break;
281 case 14: p = "Copyright (C) " COPYRIGHT_YEAR_NAME; break;
282 case 17: p = PRINTABLE_OS_NAME; break;
283 /* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
284 reporting address. This is so that we can change the
285 reporting address without breaking the translations. */
286 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
287 case 49: p = PACKAGE_BUGREPORT; break;
288 case 1:
289 case 40: p = _("Usage: dirmngr [options] (-h for help)");
290 break;
291 case 41: p = _("Syntax: dirmngr [options] [command [args]]\n"
292 "LDAP and OCSP access for GnuPG\n");
293 break;
294
295 default: p = NULL;
296 }
297 return p;
298 }
299
300
301 /* Used by gcry for logging. */
302 static void
my_gcry_logger(void * dummy,int level,const char * fmt,va_list arg_ptr)303 my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr)
304 {
305 (void)dummy;
306
307 /* Translate the log levels. */
308 switch (level)
309 {
310 case GCRY_LOG_CONT: level = JNLIB_LOG_CONT; break;
311 case GCRY_LOG_INFO: level = JNLIB_LOG_INFO; break;
312 case GCRY_LOG_WARN: level = JNLIB_LOG_WARN; break;
313 case GCRY_LOG_ERROR:level = JNLIB_LOG_ERROR; break;
314 case GCRY_LOG_FATAL:level = JNLIB_LOG_FATAL; break;
315 case GCRY_LOG_BUG: level = JNLIB_LOG_BUG; break;
316 case GCRY_LOG_DEBUG:level = JNLIB_LOG_DEBUG; break;
317 default: level = JNLIB_LOG_ERROR; break;
318 }
319 log_logv (level, fmt, arg_ptr);
320 }
321
322
323 /* Callback from libksba to hash a provided buffer. Our current
324 implementation does only allow SHA-1 for hashing. This may be
325 extended by mapping the name, testing for algorithm availibility
326 and adjust the length checks accordingly. */
327 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)328 my_ksba_hash_buffer (void *arg, const char *oid,
329 const void *buffer, size_t length, size_t resultsize,
330 unsigned char *result, size_t *resultlen)
331 {
332 (void)arg;
333
334 if (oid && strcmp (oid, "1.3.14.3.2.26"))
335 return gpg_error (GPG_ERR_NOT_SUPPORTED);
336 if (resultsize < 20)
337 return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
338 gcry_md_hash_buffer (2, result, buffer, length);
339 *resultlen = 20;
340 return 0;
341 }
342
343
344 /* Setup the debugging. With a LEVEL of NULL only the active debug
345 flags are propagated to the subsystems. With LEVEL set, a specific
346 set of debug flags is set; thus overriding all flags already
347 set. */
348 static void
set_debug(void)349 set_debug (void)
350 {
351 int numok = (debug_level && digitp (debug_level));
352 int numlvl = numok? atoi (debug_level) : 0;
353
354 if (!debug_level)
355 ;
356 else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
357 opt.debug = 0;
358 else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
359 opt.debug = DBG_ASSUAN_VALUE;
360 else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
361 opt.debug = (DBG_ASSUAN_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE);
362 else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
363 opt.debug = (DBG_ASSUAN_VALUE|DBG_X509_VALUE|DBG_LOOKUP_VALUE
364 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
365 else if (!strcmp (debug_level, "guru") || numok)
366 {
367 opt.debug = ~0;
368 /* Unless the "guru" string has been used we don't want to allow
369 hashing debugging. The rationale is that people tend to
370 select the highest debug value and would then clutter their
371 disk with debug files which may reveal confidential data. */
372 if (numok)
373 opt.debug &= ~(DBG_HASHING_VALUE);
374 }
375 else
376 {
377 log_error (_("invalid debug-level `%s' given\n"), debug_level);
378 log_info (_("valid debug levels are: %s\n"),
379 "none, basic, advanced, expert, guru");
380 opt.debug = 0; /* Reset debugging, so that prior debug
381 statements won't have an undesired effect. */
382 }
383
384
385 if (opt.debug && !opt.verbose)
386 {
387 opt.verbose = 1;
388 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
389 }
390 if (opt.debug && opt.quiet)
391 opt.quiet = 0;
392
393 if (opt.debug & DBG_CRYPTO_VALUE )
394 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
395 }
396
397
398 static void
i18n_init(void)399 i18n_init(void)
400 {
401 #ifdef USE_SIMPLE_GETTEXT
402 set_gettext_file (PACKAGE);
403 #else
404 # ifdef ENABLE_NLS
405 setlocale (LC_ALL, "" );
406 bindtextdomain (PACKAGE, LOCALEDIR);
407 textdomain (PACKAGE);
408 # endif
409 #endif
410 }
411
412
413 static void
wrong_args(const char * text)414 wrong_args (const char *text)
415 {
416 fputs (_("usage: dirmngr [options] "), stderr);
417 fputs (text, stderr);
418 putc ('\n', stderr);
419 dirmngr_exit (2);
420 }
421
422
423 /* Helper to start the reaper thread for the ldap wrapper. */
424 static void
launch_reaper_thread(void)425 launch_reaper_thread (void)
426 {
427 static int done;
428 pth_attr_t tattr;
429
430 if (done)
431 return;
432 done = 1;
433
434 tattr = pth_attr_new();
435 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
436 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 256*1024);
437 pth_attr_set (tattr, PTH_ATTR_NAME, "ldap-reaper");
438
439 if (!pth_spawn (tattr, ldap_wrapper_thread, NULL))
440 {
441 log_error (_("error spawning ldap wrapper reaper thread: %s\n"),
442 strerror (errno) );
443 dirmngr_exit (1);
444 }
445 pth_attr_destroy (tattr);
446 }
447
448 /* Helper to stop the reaper thread for the ldap wrapper. */
449 static void
shutdown_reaper(void)450 shutdown_reaper (void)
451 {
452 ldap_wrapper_wait_connections ();
453 }
454
455 /* Handle options which are allowed to be reset after program start.
456 Return true if the current option in PARGS could be handled and
457 false if not. As a special feature, passing a value of NULL for
458 PARGS, resets the options to the default. REREAD should be set
459 true if it is not the initial option parsing. */
460 static int
parse_rereadable_options(ARGPARSE_ARGS * pargs,int reread)461 parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
462 {
463 if (!pargs)
464 { /* Reset mode. */
465 opt.quiet = 0;
466 opt.verbose = 0;
467 opt.debug = 0;
468 opt.ldap_wrapper_program = NULL;
469 opt.disable_http = 0;
470 opt.disable_ldap = 0;
471 opt.honor_http_proxy = 0;
472 opt.http_proxy = NULL;
473 opt.ldap_proxy = NULL;
474 opt.only_ldap_proxy = 0;
475 opt.ignore_http_dp = 0;
476 opt.ignore_ldap_dp = 0;
477 opt.ignore_ocsp_service_url = 0;
478 opt.allow_ocsp = 0;
479 opt.ocsp_responder = NULL;
480 opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */
481 opt.ocsp_max_period = 90 * 86400; /* 90 days. */
482 opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */
483 opt.max_replies = DEFAULT_MAX_REPLIES;
484 while (opt.ocsp_signer)
485 {
486 fingerprint_list_t tmp = opt.ocsp_signer->next;
487 xfree (opt.ocsp_signer);
488 opt.ocsp_signer = tmp;
489 }
490 FREE_STRLIST (opt.ignored_cert_extensions);
491 return 1;
492 }
493
494 switch (pargs->r_opt)
495 {
496 case oQuiet: opt.quiet = 1; break;
497 case oVerbose: opt.verbose++; break;
498 case oDebug: opt.debug |= pargs->r.ret_ulong; break;
499 case oDebugAll: opt.debug = ~0; break;
500 case oDebugLevel: debug_level = pargs->r.ret_str; break;
501
502 case oLogFile:
503 if (!reread)
504 return 0; /* Not handled. */
505 if (!current_logfile || !pargs->r.ret_str
506 || strcmp (current_logfile, pargs->r.ret_str))
507 {
508 log_set_file (pargs->r.ret_str);
509 xfree (current_logfile);
510 current_logfile = xtrystrdup (pargs->r.ret_str);
511 }
512 break;
513
514 case oLDAPWrapperProgram:
515 opt.ldap_wrapper_program = pargs->r.ret_str;
516 break;
517 case oHTTPWrapperProgram:
518 opt.http_wrapper_program = pargs->r.ret_str;
519 break;
520
521 case oDisableHTTP: opt.disable_http = 1; break;
522 case oDisableLDAP: opt.disable_ldap = 1; break;
523 case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
524 case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
525 case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
526 case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
527 case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
528 case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
529 case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
530
531 case oAllowOCSP: opt.allow_ocsp = 1; break;
532 case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
533 case oOCSPSigner:
534 opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str);
535 break;
536 case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
537 case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
538 case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
539
540 case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
541
542 case oIgnoreCertExtension:
543 add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
544 break;
545
546 default:
547 return 0; /* Not handled. */
548 }
549
550 return 1; /* Handled. */
551 }
552
553
554 #ifdef HAVE_W32_SYSTEM
555 /* The global status of our service. */
556 SERVICE_STATUS_HANDLE service_handle;
557 SERVICE_STATUS service_status;
558
559 DWORD WINAPI
w32_service_control(DWORD control,DWORD event_type,LPVOID event_data,LPVOID context)560 w32_service_control (DWORD control, DWORD event_type, LPVOID event_data,
561 LPVOID context)
562 {
563 /* event_type and event_data are not used here. */
564 switch (control)
565 {
566 case SERVICE_CONTROL_SHUTDOWN:
567 /* For shutdown we will try to force termination. */
568 service_status.dwCurrentState = SERVICE_STOP_PENDING;
569 SetServiceStatus (service_handle, &service_status);
570 shutdown_pending = 3;
571 break;
572
573 case SERVICE_CONTROL_STOP:
574 service_status.dwCurrentState = SERVICE_STOP_PENDING;
575 SetServiceStatus (service_handle, &service_status);
576 shutdown_pending = 1;
577 break;
578
579 default:
580 break;
581 }
582 return 0;
583 }
584 #endif /*HAVE_W32_SYSTEM*/
585
586 #ifndef HAVE_W32_SYSTEM
587 static int
pid_suffix_callback(int * r_suffix)588 pid_suffix_callback (int *r_suffix)
589 {
590 union int_and_ptr_u value;
591
592 value.aptr = pth_key_getdata (my_tlskey_current_fd);
593 *r_suffix = value.aint;
594 return (*r_suffix != -1);
595 }
596 #endif /*!HAVE_W32_SYSTEM*/
597
598
599 #ifdef HAVE_W32_SYSTEM
600 #define main real_main
601 #endif
602 int
main(int argc,char ** argv)603 main (int argc, char **argv)
604 {
605 #ifdef HAVE_W32_SYSTEM
606 #undef main
607 #endif
608 enum cmd_and_opt_values cmd = 0;
609 ARGPARSE_ARGS pargs;
610 int orig_argc;
611 char **orig_argv;
612 FILE *configfp = NULL;
613 char *configname = NULL;
614 const char *shell;
615 unsigned configlineno;
616 int parse_debug = 0;
617 int default_config =1;
618 int greeting = 0;
619 int nogreeting = 0;
620 int nodetach = 0;
621 int csh_style = 0;
622 char *logfile = NULL;
623 char *ldapfile = NULL;
624 int debug_wait = 0;
625 int rc;
626 int homedir_seen = 0;
627 struct assuan_malloc_hooks malloc_hooks;
628
629 #ifdef HAVE_W32_SYSTEM
630 /* The option will be set by main() below if we should run as a
631 system daemon. */
632 if (opt.system_service)
633 {
634 service_handle
635 = RegisterServiceCtrlHandlerEx ("DirMngr",
636 &w32_service_control, NULL /*FIXME*/);
637 if (service_handle == 0)
638 log_error ("failed to register service control handler: ec=%d",
639 (int) GetLastError ());
640 service_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
641 service_status.dwCurrentState = SERVICE_START_PENDING;
642 service_status.dwControlsAccepted
643 = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
644 service_status.dwWin32ExitCode = NO_ERROR;
645 service_status.dwServiceSpecificExitCode = NO_ERROR;
646 service_status.dwCheckPoint = 0;
647 service_status.dwWaitHint = 10000; /* 10 seconds timeout. */
648 SetServiceStatus (service_handle, &service_status);
649 }
650 #endif /*HAVE_W32_SYSTEM*/
651
652 set_strusage (my_strusage);
653 log_set_prefix ("dirmngr", 1|4);
654
655 /* Check that the libraries are suitable. Do it here because
656 the option parsing may need services of the libraries. */
657
658 /* Libgcrypt requires us to register the threading model first.
659 Note that this will also do the pth_init. */
660
661 /* Init Libgcrypt. */
662 rc = gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pth);
663 if (rc)
664 {
665 log_fatal ("can't register GNU Pth with Libgcrypt: %s\n",
666 gpg_strerror (rc));
667 }
668 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
669 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
670 {
671 log_fatal (_("%s is too old (need %s, have %s)\n"),
672 "libgcrypt",
673 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
674 }
675 gcry_set_log_handler (my_gcry_logger, NULL);
676 gcry_control (GCRYCTL_INITIALIZATION_FINISHED);
677
678 /* Init KSBA. */
679 if (!ksba_check_version (NEED_KSBA_VERSION) )
680 {
681 log_fatal( _("%s is too old (need %s, have %s)\n"),
682 "libksba",
683 NEED_KSBA_VERSION, ksba_check_version (NULL) );
684 }
685 ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
686 ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
687
688
689 /* Init Assuan. */
690 malloc_hooks.malloc = gcry_malloc;
691 malloc_hooks.realloc = gcry_realloc;
692 malloc_hooks.free = gcry_free;
693 assuan_set_malloc_hooks (&malloc_hooks);
694 assuan_set_assuan_log_prefix (log_get_prefix (NULL));
695 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
696 assuan_set_system_hooks (ASSUAN_SYSTEM_PTH);
697 assuan_sock_init ();
698
699 /* Setup I18N. */
700 i18n_init();
701
702 /* Setup defaults. */
703 shell = getenv ("SHELL");
704 if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
705 csh_style = 1;
706
707 opt.homedir = default_homedir ();
708
709 /* Now with Pth running we can set the logging callback. Our
710 windows implementation does not yet feature the PTh tls
711 functions. */
712 #ifndef HAVE_W32_SYSTEM
713 if (pth_key_create (&my_tlskey_current_fd, NULL))
714 if (pth_key_setdata (my_tlskey_current_fd, NULL))
715 log_set_pid_suffix_cb (pid_suffix_callback);
716 #endif /*!HAVE_W32_SYSTEM*/
717
718 /* Reset rereadable options to default values. */
719 parse_rereadable_options (NULL, 0);
720
721 /* LDAP defaults. */
722 opt.add_new_ldapservers = 0;
723 opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
724
725 /* Other defaults. */
726 socket_name = default_socket_name ();
727
728 /* Check whether we have a config file given on the commandline */
729 orig_argc = argc;
730 orig_argv = argv;
731 pargs.argc = &argc;
732 pargs.argv = &argv;
733 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
734 while (arg_parse( &pargs, opts))
735 {
736 if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
737 parse_debug++;
738 else if (pargs.r_opt == oOptions)
739 { /* Yes there is one, so we do not try the default one, but
740 read the option file when it is encountered at the
741 commandline */
742 default_config = 0;
743 }
744 else if (pargs.r_opt == oNoOptions)
745 default_config = 0; /* --no-options */
746 else if (pargs.r_opt == oHomedir)
747 {
748 opt.homedir = pargs.r.ret_str;
749 homedir_seen = 1;
750 }
751 else if (pargs.r_opt == aDaemon)
752 opt.system_daemon = 1;
753 else if (pargs.r_opt == aService)
754 {
755 /* Redundant. The main function takes care of it. */
756 opt.system_service = 1;
757 opt.system_daemon = 1;
758 }
759 #ifdef HAVE_W32_SYSTEM
760 else if (pargs.r_opt == aGPGConfList || pargs.r_opt == aGPGConfTest)
761 /* We set this so we switch to the system configuration
762 directory below. This is a crutch to solve the problem
763 that the user configuration is never used on Windows. Also
764 see below at aGPGConfList. */
765 opt.system_daemon = 1;
766 #endif
767 }
768
769 /* If --daemon has been given on the command line but not --homedir,
770 we switch to /etc/dirmngr as default home directory. Note, that
771 this also overrides the GNUPGHOME environment variable. */
772 if (opt.system_daemon && !homedir_seen)
773 {
774 opt.homedir = dirmngr_sysconfdir ();
775 opt.homedir_data = dirmngr_datadir ();
776 opt.homedir_cache = dirmngr_cachedir ();
777 }
778
779 if (default_config)
780 configname = make_filename (opt.homedir, "dirmngr.conf", NULL );
781
782 argc = orig_argc;
783 argv = orig_argv;
784 pargs.argc = &argc;
785 pargs.argv = &argv;
786 pargs.flags= 1; /* do not remove the args */
787 next_pass:
788 if (configname)
789 {
790 configlineno = 0;
791 configfp = fopen (configname, "r");
792 if (!configfp)
793 {
794 if (default_config)
795 {
796 if( parse_debug )
797 log_info (_("NOTE: no default option file `%s'\n"),
798 configname );
799 }
800 else
801 {
802 log_error (_("option file `%s': %s\n"),
803 configname, strerror(errno) );
804 exit(2);
805 }
806 xfree (configname);
807 configname = NULL;
808 }
809 if (parse_debug && configname )
810 log_info (_("reading options from `%s'\n"), configname );
811 default_config = 0;
812 }
813
814 while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
815 {
816 if (parse_rereadable_options (&pargs, 0))
817 continue; /* Already handled */
818 switch (pargs.r_opt)
819 {
820 case aServer:
821 case aDaemon:
822 case aService:
823 case aShutdown:
824 case aFlush:
825 case aListCRLs:
826 case aLoadCRL:
827 case aFetchCRL:
828 case aGPGConfList:
829 case aGPGConfTest:
830 cmd = pargs.r_opt;
831 break;
832
833 case oQuiet: opt.quiet = 1; break;
834 case oVerbose: opt.verbose++; break;
835 case oBatch: opt.batch=1; break;
836
837 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
838 case oDebugAll: opt.debug = ~0; break;
839 case oDebugLevel: debug_level = pargs.r.ret_str; break;
840 case oDebugWait: debug_wait = pargs.r.ret_int; break;
841
842 case oOptions:
843 /* Config files may not be nested (silently ignore them) */
844 if (!configfp)
845 {
846 xfree(configname);
847 configname = xstrdup(pargs.r.ret_str);
848 goto next_pass;
849 }
850 break;
851 case oNoGreeting: nogreeting = 1; break;
852 case oNoVerbose: opt.verbose = 0; break;
853 case oNoOptions: break; /* no-options */
854 case oHomedir: /* Ignore this option here. */; break;
855 case oNoDetach: nodetach = 1; break;
856 case oLogFile: logfile = pargs.r.ret_str; break;
857 case oCsh: csh_style = 1; break;
858 case oSh: csh_style = 0; break;
859 case oLDAPFile: ldapfile = pargs.r.ret_str; break;
860 case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
861 case oLDAPTimeout:
862 opt.ldaptimeout = pargs.r.ret_int;
863 break;
864
865 case oFakedSystemTime:
866 set_time ( (time_t)pargs.r.ret_ulong, 0);
867 break;
868
869 case oForce: opt.force = 1; break;
870
871 case oSocketName: socket_name = pargs.r.ret_str; break;
872
873 default : pargs.err = configfp? 1:2; break;
874 }
875 }
876 if (configfp)
877 {
878 fclose( configfp );
879 configfp = NULL;
880 /* Keep a copy of the name so that it can be read on SIGHUP. */
881 opt.config_filename = configname;
882 configname = NULL;
883 goto next_pass;
884 }
885 xfree (configname);
886 configname = NULL;
887 if (log_get_errorcount(0))
888 exit(2);
889 if (nogreeting )
890 greeting = 0;
891
892 if (!opt.homedir_data)
893 opt.homedir_data = opt.homedir;
894 if (!opt.homedir_cache)
895 opt.homedir_cache = opt.homedir;
896
897 if (greeting)
898 {
899 fprintf (stderr, "%s %s; %s\n",
900 strusage(11), strusage(13), strusage(14) );
901 fprintf (stderr, "%s\n", strusage(15) );
902 }
903
904 #ifdef IS_DEVELOPMENT_VERSION
905 log_info ("NOTE: this is a development version!\n");
906 #endif
907
908 if (faked_time_p ())
909 {
910 dirmngr_isotime_t tbuf;
911 get_isotime (tbuf);
912 log_info (_("WARNING: running with faked system time %s\n"), tbuf);
913 }
914
915 set_debug ();
916
917 /* Get LDAP server list from file. */
918 if (!ldapfile)
919 {
920 ldapfile = make_filename (opt.homedir,
921 opt.system_daemon?
922 "ldapservers.conf":"dirmngr_ldapservers.conf",
923 NULL);
924 opt.ldapservers = parse_ldapserver_file (ldapfile);
925 xfree (ldapfile);
926 }
927 else
928 opt.ldapservers = parse_ldapserver_file (ldapfile);
929
930 #ifndef HAVE_W32_SYSTEM
931 /* We need to ignore the PIPE signal because the we might log to a
932 socket and that code handles EPIPE properly. The ldap wrapper
933 also requires us to ignore this silly signal. Assuan would set
934 this signal to ignore anyway.*/
935 signal (SIGPIPE, SIG_IGN);
936 #endif
937
938 /* Ready. Now to our duties. */
939 if (!cmd && opt.system_service)
940 cmd = aDaemon;
941 else if (!cmd)
942 cmd = aServer;
943 rc = 0;
944
945 if (cmd == aServer)
946 {
947 if (argc)
948 wrong_args ("--server");
949
950 if (logfile)
951 {
952 log_set_file (logfile);
953 log_set_prefix (NULL, 2|4);
954 }
955
956 if (debug_wait)
957 {
958 log_debug ("waiting for debugger - my pid is %u .....\n",
959 (unsigned int)getpid());
960 sleep (debug_wait);
961 log_debug ("... okay\n");
962 }
963
964 launch_reaper_thread ();
965 cert_cache_init ();
966 crl_cache_init ();
967 start_command_handler (ASSUAN_INVALID_FD);
968 shutdown_reaper ();
969 }
970 else if (cmd == aDaemon)
971 {
972 assuan_fd_t fd;
973 pid_t pid;
974 int len;
975 struct sockaddr_un serv_addr;
976
977 if (argc)
978 wrong_args ("--daemon");
979
980 /* Now start with logging to a file if this is desired. */
981 if (logfile)
982 {
983 log_set_file (logfile);
984 log_set_prefix (NULL, (JNLIB_LOG_WITH_PREFIX
985 |JNLIB_LOG_WITH_TIME
986 |JNLIB_LOG_WITH_PID));
987 current_logfile = xstrdup (logfile);
988 }
989
990 #ifndef HAVE_W32_SYSTEM
991 if (strchr (socket_name, ':'))
992 {
993 log_error (_("colons are not allowed in the socket name\n"));
994 dirmngr_exit (1);
995 }
996 #endif
997 if (strlen (socket_name)+1 >= sizeof serv_addr.sun_path )
998 {
999 log_error (_("name of socket too long\n"));
1000 dirmngr_exit (1);
1001 }
1002
1003 fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
1004 if (fd == ASSUAN_INVALID_FD)
1005 {
1006 log_error (_("can't create socket: %s\n"), strerror (errno));
1007 cleanup ();
1008 dirmngr_exit (1);
1009 }
1010
1011 memset (&serv_addr, 0, sizeof serv_addr);
1012 serv_addr.sun_family = AF_UNIX;
1013 strcpy (serv_addr.sun_path, socket_name);
1014 len = (offsetof (struct sockaddr_un, sun_path)
1015 + strlen (serv_addr.sun_path) + 1);
1016
1017 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1018 if (rc == -1 && errno == EADDRINUSE)
1019 {
1020 remove (socket_name);
1021 rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
1022 }
1023 if (rc != -1
1024 && (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
1025 log_error (_("error getting nonce for the socket\n"));
1026 if (rc == -1)
1027 {
1028 log_error (_("error binding socket to `%s': %s\n"),
1029 serv_addr.sun_path, gpg_strerror (gpg_error_from_errno (errno)));
1030 assuan_sock_close (fd);
1031 dirmngr_exit (1);
1032 }
1033 cleanup_socket = 1;
1034
1035 if (listen (FD2INT (fd), 5) == -1)
1036 {
1037 log_error (_("listen() failed: %s\n"), strerror (errno));
1038 assuan_sock_close (fd);
1039 dirmngr_exit (1);
1040 }
1041
1042 if (opt.verbose)
1043 log_info (_("listening on socket `%s'\n"), socket_name );
1044
1045 fflush (NULL);
1046
1047 #ifdef HAVE_W32_SYSTEM
1048 pid = getpid ();
1049 printf ("set DIRMNGR_INFO=%s;%lu;1\n", socket_name, (ulong) pid);
1050 #else
1051 pid = pth_fork ();
1052 if (pid == (pid_t)-1)
1053 {
1054 log_fatal (_("fork failed: %s\n"), strerror (errno) );
1055 dirmngr_exit (1);
1056 }
1057
1058 if (pid)
1059 { /* We are the parent */
1060 char *infostr;
1061
1062 /* Don't let cleanup() remove the socket - the child is
1063 responsible for doing that. */
1064 cleanup_socket = 0;
1065
1066 close (fd);
1067
1068 /* Create the info string: <name>:<pid>:<protocol_version> */
1069 if (asprintf (&infostr, "DIRMNGR_INFO=%s:%lu:1",
1070 socket_name, (ulong)pid ) < 0)
1071 {
1072 log_error (_("out of core\n"));
1073 kill (pid, SIGTERM);
1074 dirmngr_exit (1);
1075 }
1076 /* Print the environment string, so that the caller can use
1077 shell's eval to set it */
1078 if (csh_style)
1079 {
1080 *strchr (infostr, '=') = ' ';
1081 printf ( "setenv %s\n", infostr);
1082 }
1083 else
1084 {
1085 printf ( "%s; export DIRMNGR_INFO;\n", infostr);
1086 }
1087 free (infostr);
1088 exit (0);
1089 /*NEVER REACHED*/
1090 } /* end parent */
1091
1092
1093 /*
1094 This is the child
1095 */
1096
1097 /* Detach from tty and put process into a new session */
1098 if (!nodetach )
1099 {
1100 int i;
1101 unsigned int oldflags;
1102
1103 /* Close stdin, stdout and stderr unless it is the log stream */
1104 for (i=0; i <= 2; i++)
1105 {
1106 if (!log_test_fd (i) && i != fd )
1107 close (i);
1108 }
1109 if (setsid() == -1)
1110 {
1111 log_error (_("setsid() failed: %s\n"), strerror(errno) );
1112 dirmngr_exit (1);
1113 }
1114
1115 log_get_prefix (&oldflags);
1116 log_set_prefix (NULL, oldflags | JNLIB_LOG_RUN_DETACHED);
1117 opt.running_detached = 1;
1118
1119 if (chdir("/"))
1120 {
1121 log_error (_("chdir to / failed: %s\n"), strerror (errno));
1122 dirmngr_exit (1);
1123 }
1124 }
1125 #endif
1126
1127 launch_reaper_thread ();
1128 cert_cache_init ();
1129 crl_cache_init ();
1130 #ifdef HAVE_W32_SYSTEM
1131 if (opt.system_service)
1132 {
1133 service_status.dwCurrentState = SERVICE_RUNNING;
1134 SetServiceStatus (service_handle, &service_status);
1135 }
1136 #endif
1137 handle_connections (fd);
1138 assuan_sock_close (fd);
1139 shutdown_reaper ();
1140 #ifdef HAVE_W32_SYSTEM
1141 if (opt.system_service)
1142 {
1143 service_status.dwCurrentState = SERVICE_STOPPED;
1144 SetServiceStatus (service_handle, &service_status);
1145 }
1146 #endif
1147 }
1148 else if (cmd == aListCRLs)
1149 {
1150 /* Just list the CRL cache and exit. */
1151 if (argc)
1152 wrong_args ("--list-crls");
1153 launch_reaper_thread ();
1154 crl_cache_init ();
1155 crl_cache_list (stdout);
1156 }
1157 else if (cmd == aLoadCRL)
1158 {
1159 struct server_control_s ctrlbuf;
1160
1161 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1162 dirmngr_init_default_ctrl (&ctrlbuf);
1163
1164 launch_reaper_thread ();
1165 cert_cache_init ();
1166 crl_cache_init ();
1167 if (!argc)
1168 rc = crl_cache_load (&ctrlbuf, NULL);
1169 else
1170 {
1171 for (; !rc && argc; argc--, argv++)
1172 rc = crl_cache_load (&ctrlbuf, *argv);
1173 }
1174 }
1175 else if (cmd == aFetchCRL)
1176 {
1177 ksba_reader_t reader;
1178 struct server_control_s ctrlbuf;
1179
1180 if (argc != 1)
1181 wrong_args ("--fetch-crl URL");
1182
1183 memset (&ctrlbuf, 0, sizeof ctrlbuf);
1184 dirmngr_init_default_ctrl (&ctrlbuf);
1185
1186 launch_reaper_thread ();
1187 cert_cache_init ();
1188 crl_cache_init ();
1189 rc = crl_fetch (&ctrlbuf, argv[0], &reader);
1190 if (rc)
1191 log_error (_("fetching CRL from `%s' failed: %s\n"),
1192 argv[0], gpg_strerror (rc));
1193 else
1194 {
1195 rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
1196 if (rc)
1197 log_error (_("processing CRL from `%s' failed: %s\n"),
1198 argv[0], gpg_strerror (rc));
1199 crl_close_reader (reader);
1200 }
1201 }
1202 else if (cmd == aFlush)
1203 {
1204 /* Delete cache and exit. */
1205 if (argc)
1206 wrong_args ("--flush");
1207 rc = crl_cache_flush();
1208 }
1209 else if (cmd == aGPGConfTest)
1210 dirmngr_exit (0);
1211 else if (cmd == aGPGConfList)
1212 {
1213 unsigned long flags = 0;
1214 char *filename;
1215 char *filename_esc;
1216
1217 /* List options and default values in the GPG Conf format. */
1218
1219 /* The following list is taken from gnupg/tools/gpgconf-comp.c. */
1220 /* Option flags. YOU MUST NOT CHANGE THE NUMBERS OF THE EXISTING
1221 FLAGS, AS THEY ARE PART OF THE EXTERNAL INTERFACE. */
1222 #define GC_OPT_FLAG_NONE 0UL
1223 /* The DEFAULT flag for an option indicates that the option has a
1224 default value. */
1225 #define GC_OPT_FLAG_DEFAULT (1UL << 4)
1226 /* The DEF_DESC flag for an option indicates that the option has a
1227 default, which is described by the value of the default field. */
1228 #define GC_OPT_FLAG_DEF_DESC (1UL << 5)
1229 /* The NO_ARG_DESC flag for an option indicates that the argument has
1230 a default, which is described by the value of the ARGDEF field. */
1231 #define GC_OPT_FLAG_NO_ARG_DESC (1UL << 6)
1232 #define GC_OPT_FLAG_NO_CHANGE (1UL <<7)
1233
1234 #ifdef HAVE_W32_SYSTEM
1235 /* On Windows systems, dirmngr always runs as system daemon, and
1236 the per-user configuration is never used. So we short-cut
1237 everything to use the global system configuration of dirmngr
1238 above, and here we set the no change flag to make these
1239 read-only. */
1240 flags |= GC_OPT_FLAG_NO_CHANGE;
1241 #endif
1242
1243 /* First the configuration file. This is not an option, but it
1244 is vital information for GPG Conf. */
1245 if (!opt.config_filename)
1246 opt.config_filename = make_filename (opt.homedir,
1247 "dirmngr.conf", NULL );
1248
1249 filename = percent_escape (opt.config_filename, NULL);
1250 printf ("gpgconf-dirmngr.conf:%lu:\"%s\n",
1251 GC_OPT_FLAG_DEFAULT, filename);
1252 xfree (filename);
1253
1254 printf ("verbose:%lu:\n", flags | GC_OPT_FLAG_NONE);
1255 printf ("quiet:%lu:\n", flags | GC_OPT_FLAG_NONE);
1256 printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
1257 printf ("log-file:%lu:\n", flags | GC_OPT_FLAG_NONE);
1258 printf ("force:%lu:\n", flags | GC_OPT_FLAG_NONE);
1259
1260 /* --csh and --sh are mutually exclusive, something we can not
1261 express in GPG Conf. --options is only usable from the
1262 command line, really. --debug-all interacts with --debug,
1263 and having both of them is thus problematic. --no-detach is
1264 also only usable on the command line. --batch is unused. */
1265
1266 filename = make_filename (opt.homedir,
1267 opt.system_daemon?
1268 "ldapservers.conf":"dirmngr_ldapservers.conf",
1269 NULL);
1270 filename_esc = percent_escape (filename, NULL);
1271 printf ("ldapserverlist-file:%lu:\"%s\n", flags | GC_OPT_FLAG_DEFAULT,
1272 filename_esc);
1273 xfree (filename_esc);
1274 xfree (filename);
1275
1276 printf ("ldaptimeout:%lu:%u\n",
1277 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
1278 printf ("max-replies:%lu:%u\n",
1279 flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
1280 printf ("allow-ocsp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1281 printf ("ocsp-responder:%lu:\n", flags | GC_OPT_FLAG_NONE);
1282 printf ("ocsp-signer:%lu:\n", flags | GC_OPT_FLAG_NONE);
1283
1284 printf ("faked-system-time:%lu:\n", flags | GC_OPT_FLAG_NONE);
1285 printf ("no-greeting:%lu:\n", flags | GC_OPT_FLAG_NONE);
1286
1287 printf ("disable-http:%lu:\n", flags | GC_OPT_FLAG_NONE);
1288 printf ("disable-ldap:%lu:\n", flags | GC_OPT_FLAG_NONE);
1289 printf ("honor-http-proxy:%lu\n", flags | GC_OPT_FLAG_NONE);
1290 printf ("http-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1291 printf ("ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1292 printf ("only-ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
1293 printf ("ignore-ldap-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1294 printf ("ignore-http-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
1295 printf ("ignore-ocsp-service-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1296 /* Note: The next one is to fix a typo in gpgconf - should be
1297 removed eventually. */
1298 printf ("ignore-ocsp-servic-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
1299 }
1300 cleanup ();
1301 return !!rc;
1302 }
1303
1304
1305 #ifdef HAVE_W32_SYSTEM
1306 int
main(int argc,char * argv[])1307 main (int argc, char *argv[])
1308 {
1309 int i;
1310
1311 /* Find out if we run in daemon mode or on the command line. */
1312 for (i = 1; i < argc; i++)
1313 if (!strcmp (argv[i], "--service"))
1314 {
1315 opt.system_service = 1;
1316 opt.system_daemon = 1;
1317 break;
1318 }
1319
1320 if (!opt.system_service)
1321 return real_main (argc, argv);
1322 else
1323 {
1324 SERVICE_TABLE_ENTRY DispatchTable [] =
1325 {
1326 /* Ignore warning. */
1327 { "DirMngr", &real_main },
1328 { NULL, NULL }
1329 };
1330
1331 if (!StartServiceCtrlDispatcher (DispatchTable))
1332 return 1;
1333 return 0;
1334 }
1335 }
1336 #endif
1337
1338
1339 static void
cleanup(void)1340 cleanup (void)
1341 {
1342 crl_cache_deinit ();
1343 cert_cache_deinit (1);
1344
1345 ldapserver_list_free (opt.ldapservers);
1346 opt.ldapservers = NULL;
1347
1348 if (cleanup_socket)
1349 {
1350 cleanup_socket = 0;
1351 if (socket_name && *socket_name)
1352 remove (socket_name);
1353 }
1354 }
1355
1356
1357 void
dirmngr_exit(int rc)1358 dirmngr_exit (int rc)
1359 {
1360 cleanup ();
1361 exit (rc);
1362 }
1363
1364
1365 void
dirmngr_init_default_ctrl(ctrl_t ctrl)1366 dirmngr_init_default_ctrl (ctrl_t ctrl)
1367 {
1368 (void)ctrl;
1369
1370 /* Nothing for now. */
1371 }
1372
1373
1374 /* Create a list of LDAP servers from the file FILENAME. Returns the
1375 list or NULL in case of errors.
1376
1377 The format fo such a file is line oriented where empty lines and
1378 lines starting with a hash mark are ignored. All other lines are
1379 assumed to be colon seprated with these fields:
1380
1381 1. field: Hostname
1382 2. field: Portnumber
1383 3. field: Username
1384 4. field: Password
1385 5. field: Base DN
1386
1387 */
1388 static ldap_server_t
parse_ldapserver_file(const char * filename)1389 parse_ldapserver_file (const char* filename)
1390 {
1391 char buffer[1024];
1392 char *p;
1393 ldap_server_t server, serverstart, *serverend;
1394 int c;
1395 unsigned int lineno = 0;
1396 FILE *fp;
1397
1398 fp = fopen (filename, "r");
1399 if (!fp)
1400 {
1401 log_error (_("error opening `%s': %s\n"), filename, strerror (errno));
1402 return NULL;
1403 }
1404
1405 serverstart = NULL;
1406 serverend = &serverstart;
1407 while (fgets (buffer, sizeof buffer, fp))
1408 {
1409 lineno++;
1410 if (!*buffer || buffer[strlen(buffer)-1] != '\n')
1411 {
1412 if (*buffer && feof (fp))
1413 ; /* Last line not terminated - continue. */
1414 else
1415 {
1416 log_error (_("%s:%u: line too long - skipped\n"),
1417 filename, lineno);
1418 while ( (c=fgetc (fp)) != EOF && c != '\n')
1419 ; /* Skip until end of line. */
1420 continue;
1421 }
1422 }
1423 /* Skip empty and comment lines.*/
1424 for (p=buffer; spacep (p); p++)
1425 ;
1426 if (!*p || *p == '\n' || *p == '#')
1427 continue;
1428
1429 /* Parse the colon separated fields. */
1430 server = ldapserver_parse_one (buffer, filename, lineno);
1431 if (server)
1432 {
1433 *serverend = server;
1434 serverend = &server->next;
1435 }
1436 }
1437
1438 if (ferror (fp))
1439 log_error (_("error reading `%s': %s\n"), filename, strerror (errno));
1440 fclose (fp);
1441
1442 return serverstart;
1443 }
1444
1445
1446 static fingerprint_list_t
parse_ocsp_signer(const char * string)1447 parse_ocsp_signer (const char *string)
1448 {
1449 gpg_error_t err;
1450 char *fname;
1451 FILE *fp;
1452 char line[256];
1453 char *p;
1454 fingerprint_list_t list, *list_tail, item;
1455 unsigned int lnr = 0;
1456 int c, i, j;
1457 int errflag = 0;
1458
1459
1460 /* Check whether this is not a filename and treat it as a direct
1461 fingerprint specification. */
1462 if (!strpbrk (string, "/.~\\"))
1463 {
1464 item = xcalloc (1, sizeof *item);
1465 for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
1466 if ( string[i] != ':' )
1467 item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
1468 item->hexfpr[j] = 0;
1469 if (j != 40 || !(spacep (string+i) || !string[i]))
1470 {
1471 log_error (_("%s:%u: invalid fingerprint detected\n"),
1472 "--ocsp-signer", 0);
1473 xfree (item);
1474 return NULL;
1475 }
1476 return item;
1477 }
1478
1479 /* Well, it is a filename. */
1480 if (*string == '/' || (*string == '~' && string[1] == '/'))
1481 fname = make_filename (string, NULL);
1482 else
1483 {
1484 if (string[0] == '.' && string[1] == '/' )
1485 string += 2;
1486 fname = make_filename (opt.homedir, string, NULL);
1487 }
1488
1489 fp = fopen (fname, "r");
1490 if (!fp)
1491 {
1492 err = gpg_error_from_syserror ();
1493 log_error (_("can't open `%s': %s\n"), fname, gpg_strerror (err));
1494 xfree (fname);
1495 return NULL;
1496 }
1497
1498 list = NULL;
1499 list_tail = &list;
1500 for (;;)
1501 {
1502 if (!fgets (line, DIM(line)-1, fp) )
1503 {
1504 if (!feof (fp))
1505 {
1506 err = gpg_error_from_syserror ();
1507 log_error (_("%s:%u: read error: %s\n"),
1508 fname, lnr, gpg_strerror (err));
1509 errflag = 1;
1510 }
1511 fclose (fp);
1512 if (errflag)
1513 {
1514 while (list)
1515 {
1516 fingerprint_list_t tmp = list->next;
1517 xfree (list);
1518 list = tmp;
1519 }
1520 }
1521 xfree (fname);
1522 return list; /* Ready. */
1523 }
1524
1525 lnr++;
1526 if (!*line || line[strlen(line)-1] != '\n')
1527 {
1528 /* Eat until end of line. */
1529 while ( (c=getc (fp)) != EOF && c != '\n')
1530 ;
1531 err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
1532 /* */: GPG_ERR_INCOMPLETE_LINE);
1533 log_error (_("%s:%u: read error: %s\n"),
1534 fname, lnr, gpg_strerror (err));
1535 errflag = 1;
1536 continue;
1537 }
1538
1539 /* Allow for empty lines and spaces */
1540 for (p=line; spacep (p); p++)
1541 ;
1542 if (!*p || *p == '\n' || *p == '#')
1543 continue;
1544
1545 item = xcalloc (1, sizeof *item);
1546 *list_tail = item;
1547 list_tail = &item->next;
1548
1549 for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
1550 if ( p[i] != ':' )
1551 item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
1552 item->hexfpr[j] = 0;
1553 if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
1554 {
1555 log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
1556 errflag = 1;
1557 }
1558 i++;
1559 while (spacep (p+i))
1560 i++;
1561 if (p[i] && p[i] != '\n')
1562 log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
1563 }
1564 /*NOTREACHED*/
1565 }
1566
1567
1568
1569
1570 /*
1571 Stuff used in daemon mode.
1572 */
1573
1574
1575
1576 /* Reread parts of the configuration. Note, that this function is
1577 obviously not thread-safe and should only be called from the PTH
1578 signal handler.
1579
1580 Fixme: Due to the way the argument parsing works, we create a
1581 memory leak here for all string type arguments. There is currently
1582 no clean way to tell whether the memory for the argument has been
1583 allocated or points into the process' original arguments. Unless
1584 we have a mechanism to tell this, we need to live on with this. */
1585 static void
reread_configuration(void)1586 reread_configuration (void)
1587 {
1588 ARGPARSE_ARGS pargs;
1589 FILE *fp;
1590 unsigned int configlineno = 0;
1591 int dummy;
1592
1593 if (!opt.config_filename)
1594 return; /* No config file. */
1595
1596 fp = fopen (opt.config_filename, "r");
1597 if (!fp)
1598 {
1599 log_error (_("option file `%s': %s\n"),
1600 opt.config_filename, strerror(errno) );
1601 return;
1602 }
1603
1604 parse_rereadable_options (NULL, 1); /* Start from the default values. */
1605
1606 memset (&pargs, 0, sizeof pargs);
1607 dummy = 0;
1608 pargs.argc = &dummy;
1609 pargs.flags = 1; /* do not remove the args */
1610 while (optfile_parse (fp, opt.config_filename, &configlineno, &pargs, opts) )
1611 {
1612 if (pargs.r_opt < -1)
1613 pargs.err = 1; /* Print a warning. */
1614 else /* Try to parse this option - ignore unchangeable ones. */
1615 parse_rereadable_options (&pargs, 1);
1616 }
1617 fclose (fp);
1618
1619 set_debug ();
1620 }
1621
1622
1623
1624 /* The signal handler. */
1625 static void
handle_signal(int signo)1626 handle_signal (int signo)
1627 {
1628 switch (signo)
1629 {
1630 #ifndef HAVE_W32_SYSTEM
1631 case SIGHUP:
1632 log_info (_("SIGHUP received - "
1633 "re-reading configuration and flushing caches\n"));
1634 reread_configuration ();
1635 cert_cache_deinit (0);
1636 crl_cache_deinit ();
1637 cert_cache_init ();
1638 crl_cache_init ();
1639 break;
1640
1641 case SIGUSR1:
1642 cert_cache_print_stats ();
1643 break;
1644
1645 case SIGUSR2:
1646 log_info (_("SIGUSR2 received - no action defined\n"));
1647 break;
1648
1649 case SIGTERM:
1650 if (!shutdown_pending)
1651 log_info (_("SIGTERM received - shutting down ...\n"));
1652 else
1653 log_info (_("SIGTERM received - still %d active connections\n"),
1654 active_connections);
1655 shutdown_pending++;
1656 if (shutdown_pending > 2)
1657 {
1658 log_info (_("shutdown forced\n"));
1659 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1660 cleanup ();
1661 dirmngr_exit (0);
1662 }
1663 break;
1664
1665 case SIGINT:
1666 log_info (_("SIGINT received - immediate shutdown\n"));
1667 log_info( "%s %s stopped\n", strusage(11), strusage(13));
1668 cleanup ();
1669 dirmngr_exit (0);
1670 break;
1671 #endif
1672 default:
1673 log_info (_("signal %d received - no action defined\n"), signo);
1674 }
1675 }
1676
1677
1678 /* This is the worker for the ticker. It is called every few seconds
1679 and may only do fast operations. */
1680 static void
handle_tick(void)1681 handle_tick (void)
1682 {
1683 /* Nothing real to do right now. Actually we need the timeout only
1684 for W32 where we don't use signals and need a way for the loop to
1685 check for the shutdown flag. */
1686 #ifdef HAVE_W32_SYSTEM
1687 if (shutdown_pending)
1688 log_info (_("SIGTERM received - shutting down ...\n"));
1689 if (shutdown_pending > 2)
1690 {
1691 log_info (_("shutdown forced\n"));
1692 log_info ("%s %s stopped\n", strusage(11), strusage(13) );
1693 cleanup ();
1694 dirmngr_exit (0);
1695 }
1696 #endif /*HAVE_W32_SYSTEM*/
1697 }
1698
1699
1700 /* Check the nonce on a new connection. This is a NOP unless we we
1701 are using our Unix domain socket emulation under Windows. */
1702 static int
check_nonce(assuan_fd_t fd,assuan_sock_nonce_t * nonce)1703 check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
1704 {
1705 if (assuan_sock_check_nonce (fd, nonce))
1706 {
1707 log_info (_("error reading nonce on fd %d: %s\n"),
1708 FD2INT (fd), strerror (errno));
1709 assuan_sock_close (fd);
1710 return -1;
1711 }
1712 else
1713 return 0;
1714 }
1715
1716
1717 /* Helper to call a connection's main fucntion. */
1718 static void *
start_connection_thread(void * arg)1719 start_connection_thread (void *arg)
1720 {
1721 union int_and_ptr_u argval;
1722 assuan_fd_t fd;
1723
1724 argval.aptr = arg;
1725 fd = argval.afd;
1726
1727 if (check_nonce (fd, &socket_nonce))
1728 return NULL;
1729
1730 #ifndef HAVE_W32_SYSTEM
1731 pth_key_setdata (my_tlskey_current_fd, argval.aptr);
1732 #endif
1733
1734 active_connections++;
1735 if (opt.verbose)
1736 log_info (_("handler for fd %d started\n"), FD2INT (fd));
1737
1738 start_command_handler (fd);
1739
1740 if (opt.verbose)
1741 log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
1742 active_connections--;
1743
1744 #ifndef HAVE_W32_SYSTEM
1745 argval.afd = ASSUAN_INVALID_FD;
1746 pth_key_setdata (my_tlskey_current_fd, argval.aptr);
1747 #endif
1748
1749 return NULL;
1750 }
1751
1752
1753 /* Main loop in daemon mode. */
1754 static void
handle_connections(assuan_fd_t listen_fd)1755 handle_connections (assuan_fd_t listen_fd)
1756 {
1757 pth_attr_t tattr;
1758 pth_event_t ev, time_ev;
1759 sigset_t sigs, oldsigs;
1760 int signo;
1761 struct sockaddr_un paddr;
1762 socklen_t plen = sizeof( paddr );
1763 assuan_fd_t fd;
1764
1765 tattr = pth_attr_new();
1766 pth_attr_set (tattr, PTH_ATTR_JOINABLE, 0);
1767 pth_attr_set (tattr, PTH_ATTR_STACK_SIZE, 1024*1024);
1768 pth_attr_set (tattr, PTH_ATTR_NAME, "dirmngr");
1769
1770 #ifndef HAVE_W32_SYSTEM /* FIXME */
1771 sigemptyset (&sigs );
1772 sigaddset (&sigs, SIGHUP);
1773 sigaddset (&sigs, SIGUSR1);
1774 sigaddset (&sigs, SIGUSR2);
1775 sigaddset (&sigs, SIGINT);
1776 sigaddset (&sigs, SIGTERM);
1777 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1778 #else
1779 sigs = 0;
1780 ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
1781 #endif
1782 time_ev = NULL;
1783
1784 for (;;)
1785 {
1786 if (shutdown_pending)
1787 {
1788 if (!active_connections)
1789 break; /* ready */
1790
1791 /* Do not accept anymore connections but wait for existing
1792 connections to terminate. */
1793 signo = 0;
1794 pth_wait (ev);
1795 if (pth_event_occurred (ev) && signo)
1796 handle_signal (signo);
1797 continue;
1798 }
1799
1800 if (!time_ev)
1801 time_ev = pth_event (PTH_EVENT_TIME,
1802 pth_timeout (TIMERTICK_INTERVAL, 0));
1803
1804 if (time_ev)
1805 pth_event_concat (ev, time_ev, NULL);
1806 fd = (assuan_fd_t) pth_accept_ev (FD2INT (listen_fd), (struct sockaddr *)&paddr, &plen, ev);
1807 if (time_ev)
1808 pth_event_isolate (time_ev);
1809
1810 if (fd == ASSUAN_INVALID_FD)
1811 {
1812 if (pth_event_occurred (ev)
1813 || (time_ev && pth_event_occurred (time_ev)) )
1814 {
1815 if (pth_event_occurred (ev))
1816 handle_signal (signo);
1817 if (time_ev && pth_event_occurred (time_ev))
1818 {
1819 pth_event_free (time_ev, PTH_FREE_ALL);
1820 time_ev = NULL;
1821 handle_tick ();
1822 }
1823 continue;
1824 }
1825 log_error (_("accept failed: %s - waiting 1s\n"), strerror (errno));
1826 pth_sleep (1);
1827 continue;
1828 }
1829
1830 if (pth_event_occurred (ev))
1831 {
1832 handle_signal (signo);
1833 }
1834
1835 if (time_ev && pth_event_occurred (time_ev))
1836 {
1837 pth_event_free (time_ev, PTH_FREE_ALL);
1838 time_ev = NULL;
1839 handle_tick ();
1840 }
1841
1842
1843 /* We now might create a new thread and because we don't want
1844 any signals (as we are handling them here) to be delivered to
1845 a new thread we need to block those signals. */
1846 pth_sigmask (SIG_BLOCK, &sigs, &oldsigs);
1847
1848 /* Create thread to handle this connection. */
1849 {
1850 union int_and_ptr_u argval;
1851
1852 argval.afd = fd;
1853 if (!pth_spawn (tattr, start_connection_thread, argval.aptr))
1854 {
1855 log_error (_("error spawning connection handler: %s\n"),
1856 strerror (errno) );
1857 assuan_sock_close (fd);
1858 }
1859 }
1860
1861 /* Restore the signal mask. */
1862 pth_sigmask (SIG_SETMASK, &oldsigs, NULL);
1863 }
1864
1865 pth_event_free (ev, PTH_FREE_ALL);
1866 if (time_ev)
1867 pth_event_free (time_ev, PTH_FREE_ALL);
1868 pth_attr_destroy (tattr);
1869 cleanup ();
1870 log_info ("%s %s stopped\n", strusage(11), strusage(13));
1871 }
1872