replaced mutex in leak detective with thread scheduling
[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 #include <stdio.h>
20 #include <linux/capability.h>
21 #include <sys/prctl.h>
22 #include <signal.h>
23 #include <pthread.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 #include <time.h>
28 #include <string.h>
29 #include <getopt.h>
30 #include <errno.h>
31 #ifdef HAVE_BACKTRACE
32 # include <execinfo.h>
33 #endif /* HAVE_BACKTRACE */
34
35 #include "daemon.h"
36
37 #include <library.h>
38 #include <credentials/credential_manager.h>
39 #include <config/backend_manager.h>
40 #include <config/traffic_selector.h>
41
42 /* on some distros, a capset definition is missing */
43 #ifdef NO_CAPSET_DEFINED
44 extern int capset(cap_user_header_t hdrp, const cap_user_data_t datap);
45 #endif /* NO_CAPSET_DEFINED */
46
47 #ifdef INTEGRITY_TEST
48 #include <fips/fips.h>
49 #include <fips_signature.h>
50 #endif /* INTEGRITY_TEST */
51
52 typedef struct private_daemon_t private_daemon_t;
53
54 /**
55 * Private additions to daemon_t, contains threads and internal functions.
56 */
57 struct private_daemon_t {
58 /**
59 * Public members of daemon_t.
60 */
61 daemon_t public;
62
63 /**
64 * Signal set used for signal handling.
65 */
66 sigset_t signal_set;
67
68 /**
69 * The thread_id of main-thread.
70 */
71 pthread_t main_thread_id;
72 };
73
74 /**
75 * One and only instance of the daemon.
76 */
77 daemon_t *charon;
78
79 /**
80 * hook in library for debugging messages
81 */
82 extern void (*dbg) (int level, char *fmt, ...);
83
84 /**
85 * Logging hook for library logs, spreads debug message over bus
86 */
87 static void dbg_bus(int level, char *fmt, ...)
88 {
89 va_list args;
90
91 va_start(args, fmt);
92 charon->bus->vsignal(charon->bus, DBG_LIB, level, fmt, args);
93 va_end(args);
94 }
95 /**
96 * Logging hook for library logs before logging facility initiated
97 */
98 static void dbg_silent(int level, char *fmt, ...)
99 {
100 }
101
102 /**
103 * Logging hook for library logs, using stderr output
104 */
105 static void dbg_stderr(int level, char *fmt, ...)
106 {
107 va_list args;
108
109 va_start(args, fmt);
110 fprintf(stderr, "00[LIB] ");
111 vfprintf(stderr, fmt, args);
112 fprintf(stderr, "\n");
113 va_end(args);
114 }
115
116 /**
117 * Run the daemon and handle unix signals
118 */
119 static void run(private_daemon_t *this)
120 {
121 sigset_t set;
122
123 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
124 sigemptyset(&set);
125 sigaddset(&set, SIGINT);
126 sigaddset(&set, SIGHUP);
127 sigaddset(&set, SIGTERM);
128
129 while (TRUE)
130 {
131 int sig;
132 int error;
133
134 error = sigwait(&set, &sig);
135 if (error)
136 {
137 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
138 return;
139 }
140 switch (sig)
141 {
142 case SIGHUP:
143 {
144 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
145 break;
146 }
147 case SIGINT:
148 {
149 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
150 return;
151 }
152 case SIGTERM:
153 {
154 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
155 return;
156 }
157 default:
158 {
159 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
160 break;
161 }
162 }
163 }
164 }
165
166 /**
167 * Clean up all daemon resources
168 */
169 static void destroy(private_daemon_t *this)
170 {
171 /* terminate all idle threads */
172 if (this->public.processor)
173 {
174 this->public.processor->set_threads(this->public.processor, 0);
175 }
176 /* close all IKE_SAs */
177 DESTROY_IF(this->public.plugins);
178 DESTROY_IF(this->public.ike_sa_manager);
179 DESTROY_IF(this->public.kernel_interface);
180 DESTROY_IF(this->public.scheduler);
181 DESTROY_IF(this->public.controller);
182 DESTROY_IF(this->public.eap);
183 #ifdef ME
184 DESTROY_IF(this->public.connect_manager);
185 DESTROY_IF(this->public.mediation_manager);
186 #endif /* ME */
187 DESTROY_IF(this->public.backends);
188 DESTROY_IF(this->public.credentials);
189 DESTROY_IF(this->public.sender);
190 DESTROY_IF(this->public.receiver);
191 DESTROY_IF(this->public.socket);
192 /* wait until all threads are gone */
193 DESTROY_IF(this->public.processor);
194
195 /* rehook library logging, shutdown logging */
196 dbg = dbg_stderr;
197 DESTROY_IF(this->public.bus);
198 DESTROY_IF(this->public.outlog);
199 DESTROY_IF(this->public.syslog);
200 DESTROY_IF(this->public.authlog);
201 free(this);
202 }
203
204 /**
205 * Enforce daemon shutdown, with a given reason to do so.
206 */
207 static void kill_daemon(private_daemon_t *this, char *reason)
208 {
209 /* we send SIGTERM, so the daemon can cleanly shut down */
210 DBG1(DBG_DMN, "killing daemon: %s", reason);
211 if (this->main_thread_id == pthread_self())
212 {
213 /* initialization failed, terminate daemon */
214 destroy(this);
215 unlink(PID_FILE);
216 exit(-1);
217 }
218 else
219 {
220 DBG1(DBG_DMN, "sending SIGTERM to ourself");
221 raise(SIGTERM);
222 /* thread must die, since he produced a ciritcal failure and can't continue */
223 pthread_exit(NULL);
224 }
225 }
226
227 /**
228 * drop daemon capabilities
229 */
230 static void drop_capabilities(private_daemon_t *this, bool full)
231 {
232 struct __user_cap_header_struct hdr;
233 struct __user_cap_data_struct data;
234
235 /* CAP_NET_ADMIN is needed to use netlink */
236 u_int32_t keep = (1<<CAP_NET_ADMIN) | (1<<CAP_SYS_NICE);
237
238 if (full)
239 {
240 # if IPSEC_GID
241 if (setgid(IPSEC_GID) != 0)
242 {
243 kill_daemon(this, "changing GID to unprivileged group failed");
244 }
245 # endif
246 # if IPSEC_UID
247 if (setuid(IPSEC_UID) != 0)
248 {
249 kill_daemon(this, "changing UID to unprivileged user failed");
250 }
251 # endif
252 }
253 else
254 {
255 /* CAP_NET_BIND_SERVICE to bind services below port 1024 */
256 keep |= (1<<CAP_NET_BIND_SERVICE);
257 /* CAP_NET_RAW to create RAW sockets */
258 keep |= (1<<CAP_NET_RAW);
259 /* CAP_DAC_READ_SEARCH to read ipsec.secrets */
260 keep |= (1<<CAP_DAC_READ_SEARCH);
261 /* CAP_CHOWN to change file permissions (socket permissions) */
262 keep |= (1<<CAP_CHOWN);
263 /* CAP_SETUID to call setuid() */
264 keep |= (1<<CAP_SETUID);
265 /* CAP_SETGID to call setgid() */
266 keep |= (1<<CAP_SETGID);
267 }
268
269 hdr.version = _LINUX_CAPABILITY_VERSION;
270 hdr.pid = 0;
271 data.inheritable = data.effective = data.permitted = keep;
272
273 if (capset(&hdr, &data))
274 {
275 kill_daemon(this, "unable to drop daemon capabilities");
276 }
277 }
278
279 /**
280 * Initialize the daemon
281 */
282 static bool initialize(private_daemon_t *this, bool syslog, level_t levels[])
283 {
284 signal_t signal;
285
286 /* for uncritical pseudo random numbers */
287 srandom(time(NULL) + getpid());
288
289 /* setup bus and it's listeners first to enable log output */
290 this->public.bus = bus_create();
291 this->public.outlog = file_logger_create(stdout);
292 this->public.syslog = sys_logger_create(LOG_DAEMON);
293 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
294 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
295 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
296 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
297 this->public.authlog->set_level(this->public.authlog, SIG_ANY, LEVEL_AUDIT);
298 /* set up hook to log dbg message in library via charons message bus */
299 dbg = dbg_bus;
300
301 /* apply loglevels */
302 for (signal = 0; signal < DBG_MAX; signal++)
303 {
304 this->public.syslog->set_level(this->public.syslog,
305 signal, levels[signal]);
306 if (!syslog)
307 {
308 this->public.outlog->set_level(this->public.outlog,
309 signal, levels[signal]);
310 }
311 }
312
313 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
314
315 #ifdef INTEGRITY_TEST
316 DBG1(DBG_DMN, "integrity test of libstrongswan code");
317 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
318 {
319 DBG1(DBG_DMN, " integrity test passed");
320 }
321 else
322 {
323 DBG1(DBG_DMN, " integrity test failed");
324 return FALSE;
325 }
326 #endif /* INTEGRITY_TEST */
327
328 this->public.ike_sa_manager = ike_sa_manager_create();
329 if (this->public.ike_sa_manager == NULL)
330 {
331 return FALSE;
332 }
333 this->public.processor = processor_create();
334 this->public.scheduler = scheduler_create();
335
336 /* load secrets, ca certificates and crls */
337 this->public.credentials = credential_manager_create();
338 this->public.controller = controller_create();
339 this->public.eap = eap_manager_create();
340 this->public.backends = backend_manager_create();
341 this->public.plugins = plugin_loader_create();
342 this->public.kernel_interface = kernel_interface_create();
343 this->public.socket = socket_create();
344 this->public.sender = sender_create();
345 this->public.receiver = receiver_create();
346 if (this->public.receiver == NULL)
347 {
348 return FALSE;
349 }
350
351 #ifdef ME
352 this->public.connect_manager = connect_manager_create();
353 if (this->public.connect_manager == NULL)
354 {
355 return FALSE;
356 }
357 this->public.mediation_manager = mediation_manager_create();
358 #endif /* ME */
359
360 this->public.plugins->load(this->public.plugins, IPSEC_PLUGINDIR, "libcharon-");
361
362 return TRUE;
363 }
364
365 /**
366 * Handle SIGSEGV/SIGILL signals raised by threads
367 */
368 static void segv_handler(int signal)
369 {
370 #ifdef HAVE_BACKTRACE
371 void *array[20];
372 size_t size;
373 char **strings;
374 size_t i;
375
376 size = backtrace(array, 20);
377 strings = backtrace_symbols(array, size);
378
379 DBG1(DBG_JOB, "thread %u received %s. Dumping %d frames from stack:",
380 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
381
382 for (i = 0; i < size; i++)
383 {
384 DBG1(DBG_DMN, " %s", strings[i]);
385 }
386 free (strings);
387 #else /* !HAVE_BACKTRACE */
388 DBG1(DBG_DMN, "thread %u received %s",
389 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
390 #endif /* HAVE_BACKTRACE */
391 DBG1(DBG_DMN, "killing ourself, received critical signal");
392 raise(SIGKILL);
393 }
394
395 /**
396 * Create the daemon.
397 */
398 private_daemon_t *daemon_create(void)
399 {
400 struct sigaction action;
401 private_daemon_t *this = malloc_thing(private_daemon_t);
402
403 /* assign methods */
404 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
405
406 /* NULL members for clean destruction */
407 this->public.socket = NULL;
408 this->public.ike_sa_manager = NULL;
409 this->public.credentials = NULL;
410 this->public.backends = NULL;
411 this->public.sender= NULL;
412 this->public.receiver = NULL;
413 this->public.scheduler = NULL;
414 this->public.kernel_interface = NULL;
415 this->public.processor = NULL;
416 this->public.controller = NULL;
417 this->public.eap = NULL;
418 this->public.plugins = NULL;
419 this->public.bus = NULL;
420 this->public.outlog = NULL;
421 this->public.syslog = NULL;
422 this->public.authlog = NULL;
423
424 this->main_thread_id = pthread_self();
425
426 /* add handler for SEGV and ILL,
427 * add handler for USR1 (cancellation).
428 * INT, TERM and HUP are handled by sigwait() in run() */
429 action.sa_handler = segv_handler;
430 action.sa_flags = 0;
431 sigemptyset(&action.sa_mask);
432 sigaddset(&action.sa_mask, SIGINT);
433 sigaddset(&action.sa_mask, SIGTERM);
434 sigaddset(&action.sa_mask, SIGHUP);
435 sigaction(SIGSEGV, &action, NULL);
436 sigaction(SIGILL, &action, NULL);
437 action.sa_handler = SIG_IGN;
438 sigaction(SIGPIPE, &action, NULL);
439
440 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
441
442 return this;
443 }
444
445 /**
446 * print command line usage and exit
447 */
448 static void usage(const char *msg)
449 {
450 if (msg != NULL && *msg != '\0')
451 {
452 fprintf(stderr, "%s\n", msg);
453 }
454 fprintf(stderr, "Usage: charon\n"
455 " [--help]\n"
456 " [--version]\n"
457 " [--strictcrlpolicy]\n"
458 " [--cachecrls]\n"
459 " [--crlcheckinterval <interval>]\n"
460 " [--use-syslog]\n"
461 " [--debug-<type> <level>]\n"
462 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
463 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
464 " 2 = controlmore, 3 = raw, 4 = private)\n"
465 "\n"
466 );
467 exit(msg == NULL? 0 : 1);
468 }
469
470 /**
471 * Main function, manages the daemon.
472 */
473 int main(int argc, char *argv[])
474 {
475 u_int crl_check_interval = 0;
476 bool cache_crls = FALSE;
477 bool use_syslog = FALSE;
478
479 private_daemon_t *private_charon;
480 FILE *pid_file;
481 struct stat stb;
482 level_t levels[DBG_MAX];
483 int signal;
484
485 /* silence the library during initialization, as we have no bus yet */
486 dbg = dbg_silent;
487
488 /* initialize library */
489 library_init(IPSEC_DIR "/strongswan.conf");
490 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR, "libstrongswan-");
491 lib->printf_hook->add_handler(lib->printf_hook, 'R',
492 traffic_selector_get_printf_hooks());
493 private_charon = daemon_create();
494 charon = (daemon_t*)private_charon;
495
496 /* drop the capabilities we won't need for initialization */
497 prctl(PR_SET_KEEPCAPS, 1);
498 drop_capabilities(private_charon, FALSE);
499
500 /* use CTRL loglevel for default */
501 for (signal = 0; signal < DBG_MAX; signal++)
502 {
503 levels[signal] = LEVEL_CTRL;
504 }
505
506 /* handle arguments */
507 for (;;)
508 {
509 struct option long_opts[] = {
510 { "help", no_argument, NULL, 'h' },
511 { "version", no_argument, NULL, 'v' },
512 { "use-syslog", no_argument, NULL, 'l' },
513 { "cachecrls", no_argument, NULL, 'C' },
514 { "crlcheckinterval", required_argument, NULL, 'x' },
515 /* TODO: handle "debug-all" */
516 { "debug-dmn", required_argument, &signal, DBG_DMN },
517 { "debug-mgr", required_argument, &signal, DBG_MGR },
518 { "debug-ike", required_argument, &signal, DBG_IKE },
519 { "debug-chd", required_argument, &signal, DBG_CHD },
520 { "debug-job", required_argument, &signal, DBG_JOB },
521 { "debug-cfg", required_argument, &signal, DBG_CFG },
522 { "debug-knl", required_argument, &signal, DBG_KNL },
523 { "debug-net", required_argument, &signal, DBG_NET },
524 { "debug-enc", required_argument, &signal, DBG_ENC },
525 { "debug-lib", required_argument, &signal, DBG_LIB },
526 { 0,0,0,0 }
527 };
528
529 int c = getopt_long(argc, argv, "", long_opts, NULL);
530 switch (c)
531 {
532 case EOF:
533 break;
534 case 'h':
535 usage(NULL);
536 break;
537 case 'v':
538 printf("Linux strongSwan %s\n", VERSION);
539 exit(0);
540 case 'l':
541 use_syslog = TRUE;
542 continue;
543 case 'C':
544 cache_crls = TRUE;
545 continue;
546 case 'x':
547 crl_check_interval = atoi(optarg);
548 continue;
549 case 0:
550 /* option is in signal */
551 levels[signal] = atoi(optarg);
552 continue;
553 default:
554 usage("");
555 break;
556 }
557 break;
558 }
559
560 /* initialize daemon */
561 if (!initialize(private_charon, use_syslog, levels))
562 {
563 DBG1(DBG_DMN, "initialization failed - aborting charon");
564 destroy(private_charon);
565 exit(-1);
566 }
567
568 /* check/setup PID file */
569 if (stat(PID_FILE, &stb) == 0)
570 {
571 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
572 destroy(private_charon);
573 exit(-1);
574 }
575 pid_file = fopen(PID_FILE, "w");
576 if (pid_file)
577 {
578 fprintf(pid_file, "%d\n", getpid());
579 fchown(fileno(pid_file), IPSEC_UID, IPSEC_GID);
580 fclose(pid_file);
581 }
582
583 /* drop additional capabilites (bind & root) */
584 drop_capabilities(private_charon, TRUE);
585
586 /* start the engine, go multithreaded */
587 charon->processor->set_threads(charon->processor,
588 lib->settings->get_int(lib->settings, "charon.threads",
589 DEFAULT_THREADS));
590
591 /* run daemon */
592 run(private_charon);
593
594 /* normal termination, cleanup and exit */
595 destroy(private_charon);
596 unlink(PID_FILE);
597
598 library_deinit();
599
600 return 0;
601 }
602