get rid of unused iterator hook functions
[strongswan.git] / src / charon / daemon.c
1 /*
2 * Copyright (C) 2006-2007 Tobias Brunner
3 * Copyright (C) 2006 Daniel Roethlisberger
4 * Copyright (C) 2005-2008 Martin Willi
5 * Copyright (C) 2005 Jan Hutter
6 * Hochschule fuer Technik Rapperswil
7 *
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation; either version 2 of the License, or (at your
11 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 * for more details.
17 */
18
19 #ifdef HAVE_DLADDR
20 # define _GNU_SOURCE
21 # include <dlfcn.h>
22 #endif /* HAVE_DLADDR */
23
24 #include <stdio.h>
25 #include <sys/prctl.h>
26 #include <signal.h>
27 #include <pthread.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <unistd.h>
31 #include <time.h>
32 #include <string.h>
33 #include <getopt.h>
34 #include <errno.h>
35 #include <pwd.h>
36 #include <grp.h>
37 #ifdef HAVE_BACKTRACE
38 # include <execinfo.h>
39 #endif /* HAVE_BACKTRACE */
40 #ifdef CAPABILITIES
41 #include <sys/capability.h>
42 #endif /* CAPABILITIES */
43
44 #include "daemon.h"
45
46 #include <library.h>
47 #include <config/traffic_selector.h>
48 #include <config/proposal.h>
49
50 #ifdef INTEGRITY_TEST
51 #include <fips/fips.h>
52 #include <fips/fips_signature.h>
53 #endif /* INTEGRITY_TEST */
54
55 typedef struct private_daemon_t private_daemon_t;
56
57 /**
58 * Private additions to daemon_t, contains threads and internal functions.
59 */
60 struct private_daemon_t {
61 /**
62 * Public members of daemon_t.
63 */
64 daemon_t public;
65
66 /**
67 * Signal set used for signal handling.
68 */
69 sigset_t signal_set;
70
71 /**
72 * The thread_id of main-thread.
73 */
74 pthread_t main_thread_id;
75
76 #ifdef CAPABILITIES
77 /**
78 * capabilities to keep
79 */
80 cap_t caps;
81 #endif /* CAPABILITIES */
82 };
83
84 /**
85 * One and only instance of the daemon.
86 */
87 daemon_t *charon;
88
89 /**
90 * hook in library for debugging messages
91 */
92 extern void (*dbg) (int level, char *fmt, ...);
93
94 /**
95 * Logging hook for library logs, spreads debug message over bus
96 */
97 static void dbg_bus(int level, char *fmt, ...)
98 {
99 va_list args;
100
101 va_start(args, fmt);
102 charon->bus->vlog(charon->bus, DBG_LIB, level, fmt, args);
103 va_end(args);
104 }
105
106 /**
107 * Logging hook for library logs, using stderr output
108 */
109 static void dbg_stderr(int level, char *fmt, ...)
110 {
111 va_list args;
112
113 if (level <= 1)
114 {
115 va_start(args, fmt);
116 fprintf(stderr, "00[LIB] ");
117 vfprintf(stderr, fmt, args);
118 fprintf(stderr, "\n");
119 va_end(args);
120 }
121 }
122
123 /**
124 * Run the daemon and handle unix signals
125 */
126 static void run(private_daemon_t *this)
127 {
128 sigset_t set;
129
130 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
131 sigemptyset(&set);
132 sigaddset(&set, SIGINT);
133 sigaddset(&set, SIGHUP);
134 sigaddset(&set, SIGTERM);
135
136 while (TRUE)
137 {
138 int sig;
139 int error;
140
141 error = sigwait(&set, &sig);
142 if (error)
143 {
144 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
145 return;
146 }
147 switch (sig)
148 {
149 case SIGHUP:
150 {
151 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
152 break;
153 }
154 case SIGINT:
155 {
156 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
157 return;
158 }
159 case SIGTERM:
160 {
161 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
162 return;
163 }
164 default:
165 {
166 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
167 break;
168 }
169 }
170 }
171 }
172
173 /**
174 * Clean up all daemon resources
175 */
176 static void destroy(private_daemon_t *this)
177 {
178 /* terminate all idle threads */
179 if (this->public.processor)
180 {
181 this->public.processor->set_threads(this->public.processor, 0);
182 }
183 /* close all IKE_SAs */
184 if (this->public.ike_sa_manager)
185 {
186 this->public.ike_sa_manager->flush(this->public.ike_sa_manager);
187 }
188 /* unload plugins to release threads */
189 lib->plugins->unload(lib->plugins);
190 #ifdef CAPABILITIES
191 cap_free(this->caps);
192 #endif /* CAPABILITIES */
193 DESTROY_IF(this->public.ike_sa_manager);
194 DESTROY_IF(this->public.kernel_interface);
195 DESTROY_IF(this->public.scheduler);
196 DESTROY_IF(this->public.controller);
197 DESTROY_IF(this->public.eap);
198 DESTROY_IF(this->public.sim);
199 #ifdef ME
200 DESTROY_IF(this->public.connect_manager);
201 DESTROY_IF(this->public.mediation_manager);
202 #endif /* ME */
203 DESTROY_IF(this->public.backends);
204 DESTROY_IF(this->public.attributes);
205 DESTROY_IF(this->public.credentials);
206 DESTROY_IF(this->public.sender);
207 DESTROY_IF(this->public.receiver);
208 DESTROY_IF(this->public.socket);
209 /* wait until all threads are gone */
210 DESTROY_IF(this->public.processor);
211
212 /* rehook library logging, shutdown logging */
213 dbg = dbg_stderr;
214 DESTROY_IF(this->public.bus);
215 DESTROY_IF(this->public.outlog);
216 DESTROY_IF(this->public.syslog);
217 DESTROY_IF(this->public.authlog);
218 free(this);
219 }
220
221 /**
222 * Enforce daemon shutdown, with a given reason to do so.
223 */
224 static void kill_daemon(private_daemon_t *this, char *reason)
225 {
226 /* we send SIGTERM, so the daemon can cleanly shut down */
227 if (this->public.bus)
228 {
229 DBG1(DBG_DMN, "killing daemon: %s", reason);
230 }
231 else
232 {
233 fprintf(stderr, "killing daemon: %s\n", reason);
234 }
235 if (this->main_thread_id == pthread_self())
236 {
237 /* initialization failed, terminate daemon */
238 unlink(PID_FILE);
239 exit(-1);
240 }
241 else
242 {
243 DBG1(DBG_DMN, "sending SIGTERM to ourself");
244 raise(SIGTERM);
245 /* thread must die, since he produced a ciritcal failure and can't continue */
246 pthread_exit(NULL);
247 }
248 }
249
250 /**
251 * drop daemon capabilities
252 */
253 static void drop_capabilities(private_daemon_t *this)
254 {
255 prctl(PR_SET_KEEPCAPS, 1);
256
257 if (setgid(charon->gid) != 0)
258 {
259 kill_daemon(this, "change to unprivileged group failed");
260 }
261 if (setuid(charon->uid) != 0)
262 {
263 kill_daemon(this, "change to unprivileged user failed");
264 }
265
266 #ifdef CAPABILITIES
267 if (cap_set_proc(this->caps) != 0)
268 {
269 kill_daemon(this, "unable to drop daemon capabilities");
270 }
271 #endif /* CAPABILITIES */
272 }
273
274 /**
275 * Implementation of daemon_t.keep_cap
276 */
277 static void keep_cap(private_daemon_t *this, u_int cap)
278 {
279 #ifdef CAPABILITIES
280 cap_set_flag(this->caps, CAP_EFFECTIVE, 1, &cap, CAP_SET);
281 cap_set_flag(this->caps, CAP_INHERITABLE, 1, &cap, CAP_SET);
282 cap_set_flag(this->caps, CAP_PERMITTED, 1, &cap, CAP_SET);
283 #endif /* CAPABILITIES */
284 }
285
286 /**
287 * lookup UID and GID
288 */
289 static void lookup_uid_gid(private_daemon_t *this)
290 {
291 #ifdef IPSEC_USER
292 {
293 char buf[1024];
294 struct passwd passwd, *pwp;
295
296 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
297 pwp == NULL)
298 {
299 kill_daemon(this, "resolving user '"IPSEC_USER"' failed");
300 }
301 charon->uid = pwp->pw_uid;
302 }
303 #endif
304 #ifdef IPSEC_GROUP
305 {
306 char buf[1024];
307 struct group group, *grp;
308
309 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
310 grp == NULL)
311 {
312 kill_daemon(this, "reslvoing group '"IPSEC_GROUP"' failed");
313 }
314 charon->gid = grp->gr_gid;
315 }
316 #endif
317 }
318
319 /**
320 * Log loaded plugins
321 */
322 static void print_plugins()
323 {
324 char buf[512], *plugin;
325 int len = 0;
326 enumerator_t *enumerator;
327
328 enumerator = lib->plugins->create_plugin_enumerator(lib->plugins);
329 while (len < sizeof(buf) && enumerator->enumerate(enumerator, &plugin))
330 {
331 len += snprintf(&buf[len], sizeof(buf)-len, "%s ", plugin);
332 }
333 enumerator->destroy(enumerator);
334 DBG1(DBG_DMN, "loaded plugins: %s", buf);
335 }
336
337 /**
338 * Initialize the daemon
339 */
340 static bool initialize(private_daemon_t *this, bool syslog, level_t levels[])
341 {
342 debug_t group;
343
344 /* for uncritical pseudo random numbers */
345 srandom(time(NULL) + getpid());
346
347 /* setup bus and it's listeners first to enable log output */
348 this->public.bus = bus_create();
349 this->public.outlog = file_logger_create(stdout);
350 this->public.syslog = sys_logger_create(LOG_DAEMON);
351 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
352 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
353 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
354 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
355 this->public.authlog->set_level(this->public.authlog, DBG_ANY, LEVEL_AUDIT);
356 /* set up hook to log dbg message in library via charons message bus */
357 dbg = dbg_bus;
358
359 /* apply loglevels */
360 for (group = 0; group < DBG_MAX; group++)
361 {
362 this->public.syslog->set_level(this->public.syslog,
363 group, levels[group]);
364 if (!syslog)
365 {
366 this->public.outlog->set_level(this->public.outlog,
367 group, levels[group]);
368 }
369 }
370
371 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
372
373 /* load secrets, ca certificates and crls */
374 this->public.processor = processor_create();
375 this->public.scheduler = scheduler_create();
376 this->public.credentials = credential_manager_create();
377 this->public.controller = controller_create();
378 this->public.eap = eap_manager_create();
379 this->public.sim = sim_manager_create();
380 this->public.backends = backend_manager_create();
381 this->public.attributes = attribute_manager_create();
382 this->public.kernel_interface = kernel_interface_create();
383 this->public.socket = socket_create();
384
385 /* load plugins, further infrastructure may need it */
386 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
387 lib->settings->get_str(lib->settings, "charon.load", PLUGINS));
388
389 print_plugins();
390
391 /* create the kernel interfaces */
392 this->public.kernel_interface->create_interfaces(this->public.kernel_interface);
393
394 #ifdef INTEGRITY_TEST
395 DBG1(DBG_DMN, "integrity test of libstrongswan code");
396 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
397 {
398 DBG1(DBG_DMN, " integrity test passed");
399 }
400 else
401 {
402 DBG1(DBG_DMN, " integrity test failed");
403 return FALSE;
404 }
405 #endif /* INTEGRITY_TEST */
406
407 this->public.ike_sa_manager = ike_sa_manager_create();
408 if (this->public.ike_sa_manager == NULL)
409 {
410 return FALSE;
411 }
412 this->public.sender = sender_create();
413 this->public.receiver = receiver_create();
414 if (this->public.receiver == NULL)
415 {
416 return FALSE;
417 }
418
419 #ifdef ME
420 this->public.connect_manager = connect_manager_create();
421 if (this->public.connect_manager == NULL)
422 {
423 return FALSE;
424 }
425 this->public.mediation_manager = mediation_manager_create();
426 #endif /* ME */
427
428 return TRUE;
429 }
430
431 /**
432 * Handle SIGSEGV/SIGILL signals raised by threads
433 */
434 static void segv_handler(int signal)
435 {
436 #ifdef HAVE_BACKTRACE
437 void *array[20];
438 size_t size;
439 char **strings;
440 size_t i;
441
442 size = backtrace(array, 20);
443 strings = backtrace_symbols(array, size);
444
445 DBG1(DBG_JOB, "thread %u received %s. Dumping %d frames from stack:",
446 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
447
448 for (i = 0; i < size; i++)
449 {
450 #ifdef HAVE_DLADDR
451 Dl_info info;
452
453 if (dladdr(array[i], &info))
454 {
455 void *ptr = array[i];
456 if (strstr(info.dli_fname, ".so"))
457 {
458 ptr = (void*)(array[i] - info.dli_fbase);
459 }
460 DBG1(DBG_DMN, " %s [%p]", info.dli_fname, ptr);
461 }
462 else
463 {
464 #endif /* HAVE_DLADDR */
465 DBG1(DBG_DMN, " %s", strings[i]);
466 #ifdef HAVE_DLADDR
467 }
468 #endif /* HAVE_DLADDR */
469 }
470 free (strings);
471 #else /* !HAVE_BACKTRACE */
472 DBG1(DBG_DMN, "thread %u received %s",
473 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
474 #endif /* HAVE_BACKTRACE */
475 DBG1(DBG_DMN, "killing ourself, received critical signal");
476 raise(SIGKILL);
477 }
478
479 /**
480 * Create the daemon.
481 */
482 private_daemon_t *daemon_create(void)
483 {
484 struct sigaction action;
485 private_daemon_t *this = malloc_thing(private_daemon_t);
486
487 /* assign methods */
488 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
489 this->public.keep_cap = (void(*)(daemon_t*, u_int cap))keep_cap;
490
491 /* NULL members for clean destruction */
492 this->public.socket = NULL;
493 this->public.ike_sa_manager = NULL;
494 this->public.credentials = NULL;
495 this->public.backends = NULL;
496 this->public.attributes = NULL;
497 this->public.sender= NULL;
498 this->public.receiver = NULL;
499 this->public.scheduler = NULL;
500 this->public.kernel_interface = NULL;
501 this->public.processor = NULL;
502 this->public.controller = NULL;
503 this->public.eap = NULL;
504 this->public.sim = NULL;
505 this->public.bus = NULL;
506 this->public.outlog = NULL;
507 this->public.syslog = NULL;
508 this->public.authlog = NULL;
509 #ifdef ME
510 this->public.connect_manager = NULL;
511 this->public.mediation_manager = NULL;
512 #endif /* ME */
513 this->public.uid = 0;
514 this->public.gid = 0;
515
516 this->main_thread_id = pthread_self();
517 #ifdef CAPABILITIES
518 this->caps = cap_init();
519 keep_cap(this, CAP_NET_ADMIN);
520 if (lib->leak_detective)
521 {
522 keep_cap(this, CAP_SYS_NICE);
523 }
524 #endif /* CAPABILITIES */
525
526 /* add handler for SEGV and ILL,
527 * add handler for USR1 (cancellation).
528 * INT, TERM and HUP are handled by sigwait() in run() */
529 action.sa_handler = segv_handler;
530 action.sa_flags = 0;
531 sigemptyset(&action.sa_mask);
532 sigaddset(&action.sa_mask, SIGINT);
533 sigaddset(&action.sa_mask, SIGTERM);
534 sigaddset(&action.sa_mask, SIGHUP);
535 sigaction(SIGSEGV, &action, NULL);
536 sigaction(SIGILL, &action, NULL);
537 action.sa_handler = SIG_IGN;
538 sigaction(SIGPIPE, &action, NULL);
539
540 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
541
542 return this;
543 }
544
545 /**
546 * print command line usage and exit
547 */
548 static void usage(const char *msg)
549 {
550 if (msg != NULL && *msg != '\0')
551 {
552 fprintf(stderr, "%s\n", msg);
553 }
554 fprintf(stderr, "Usage: charon\n"
555 " [--help]\n"
556 " [--version]\n"
557 " [--use-syslog]\n"
558 " [--debug-<type> <level>]\n"
559 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
560 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
561 " 2 = controlmore, 3 = raw, 4 = private)\n"
562 "\n"
563 );
564 exit(msg == NULL? 0 : 1);
565 }
566
567 /**
568 * Main function, manages the daemon.
569 */
570 int main(int argc, char *argv[])
571 {
572 bool use_syslog = FALSE;
573
574 private_daemon_t *private_charon;
575 FILE *pid_file;
576 struct stat stb;
577 level_t levels[DBG_MAX];
578 int group;
579
580 /* logging for library during initialization, as we have no bus yet */
581 dbg = dbg_stderr;
582
583 /* initialize library */
584 library_init(STRONGSWAN_CONF);
585 lib->printf_hook->add_handler(lib->printf_hook, 'R',
586 traffic_selector_get_printf_hooks());
587 lib->printf_hook->add_handler(lib->printf_hook, 'P',
588 proposal_get_printf_hooks());
589 private_charon = daemon_create();
590 charon = (daemon_t*)private_charon;
591
592 lookup_uid_gid(private_charon);
593
594 /* use CTRL loglevel for default */
595 for (group = 0; group < DBG_MAX; group++)
596 {
597 levels[group] = LEVEL_CTRL;
598 }
599
600 /* handle arguments */
601 for (;;)
602 {
603 struct option long_opts[] = {
604 { "help", no_argument, NULL, 'h' },
605 { "version", no_argument, NULL, 'v' },
606 { "use-syslog", no_argument, NULL, 'l' },
607 /* TODO: handle "debug-all" */
608 { "debug-dmn", required_argument, &group, DBG_DMN },
609 { "debug-mgr", required_argument, &group, DBG_MGR },
610 { "debug-ike", required_argument, &group, DBG_IKE },
611 { "debug-chd", required_argument, &group, DBG_CHD },
612 { "debug-job", required_argument, &group, DBG_JOB },
613 { "debug-cfg", required_argument, &group, DBG_CFG },
614 { "debug-knl", required_argument, &group, DBG_KNL },
615 { "debug-net", required_argument, &group, DBG_NET },
616 { "debug-enc", required_argument, &group, DBG_ENC },
617 { "debug-lib", required_argument, &group, DBG_LIB },
618 { 0,0,0,0 }
619 };
620
621 int c = getopt_long(argc, argv, "", long_opts, NULL);
622 switch (c)
623 {
624 case EOF:
625 break;
626 case 'h':
627 usage(NULL);
628 break;
629 case 'v':
630 printf("Linux strongSwan %s\n", VERSION);
631 exit(0);
632 case 'l':
633 use_syslog = TRUE;
634 continue;
635 case 0:
636 /* option is in group */
637 levels[group] = atoi(optarg);
638 continue;
639 default:
640 usage("");
641 break;
642 }
643 break;
644 }
645
646 /* initialize daemon */
647 if (!initialize(private_charon, use_syslog, levels))
648 {
649 DBG1(DBG_DMN, "initialization failed - aborting charon");
650 destroy(private_charon);
651 exit(-1);
652 }
653
654 /* check/setup PID file */
655 if (stat(PID_FILE, &stb) == 0)
656 {
657 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
658 destroy(private_charon);
659 exit(-1);
660 }
661 pid_file = fopen(PID_FILE, "w");
662 if (pid_file)
663 {
664 fprintf(pid_file, "%d\n", getpid());
665 fchown(fileno(pid_file), charon->uid, charon->gid);
666 fclose(pid_file);
667 }
668
669 /* drop the capabilities we won't need */
670 drop_capabilities(private_charon);
671
672 /* start the engine, go multithreaded */
673 charon->processor->set_threads(charon->processor,
674 lib->settings->get_int(lib->settings, "charon.threads",
675 DEFAULT_THREADS));
676
677 /* run daemon */
678 run(private_charon);
679
680 /* normal termination, cleanup and exit */
681 destroy(private_charon);
682 unlink(PID_FILE);
683
684 library_deinit();
685
686 return 0;
687 }
688