removed %M printf handler, five more to go
[strongswan.git] / src / charon / daemon.c
1 /**
2 * @file daemon.c
3 *
4 * @brief Implementation of daemon_t and main of IKEv2-Daemon.
5 *
6 */
7
8 /*
9 * Copyright (C) 2006 Tobias Brunner, Daniel Roethlisberger
10 * Copyright (C) 2005-2006 Martin Willi
11 * Copyright (C) 2005 Jan Hutter
12 * Hochschule fuer Technik Rapperswil
13 *
14 * This program is free software; you can redistribute it and/or modify it
15 * under the terms of the GNU General Public License as published by the
16 * Free Software Foundation; either version 2 of the License, or (at your
17 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
18 *
19 * This program is distributed in the hope that it will be useful, but
20 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
21 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * for more details.
23 */
24
25 #include <stdio.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 #ifdef HAVE_BACKTRACE
36 # include <execinfo.h>
37 #endif /* HAVE_BACKTRACE */
38
39 #include "daemon.h"
40
41 #include <library.h>
42 #include <crypto/ca.h>
43 #include <utils/fetcher.h>
44 #include <config/credentials/local_credential_store.h>
45 #include <config/backends/local_backend.h>
46 #include <sa/authenticators/eap/eap_method.h>
47
48
49 typedef struct private_daemon_t private_daemon_t;
50
51 /**
52 * Private additions to daemon_t, contains threads and internal functions.
53 */
54 struct private_daemon_t {
55 /**
56 * Public members of daemon_t.
57 */
58 daemon_t public;
59
60 /**
61 * Signal set used for signal handling.
62 */
63 sigset_t signal_set;
64
65 /**
66 * The thread_id of main-thread.
67 */
68 pthread_t main_thread_id;
69 };
70
71 /**
72 * One and only instance of the daemon.
73 */
74 daemon_t *charon;
75
76 /**
77 * hook in library for debugging messages
78 */
79 extern void (*dbg) (int level, char *fmt, ...);
80
81 /**
82 * Logging hook for library logs, spreads debug message over bus
83 */
84 static void dbg_bus(int level, char *fmt, ...)
85 {
86 va_list args;
87
88 va_start(args, fmt);
89 charon->bus->vsignal(charon->bus, DBG_LIB, level, fmt, args);
90 va_end(args);
91 }
92
93 /**
94 * Logging hook for library logs, using stderr output
95 */
96 static void dbg_stderr(int level, char *fmt, ...)
97 {
98 va_list args;
99
100 va_start(args, fmt);
101 fprintf(stderr, "00[LIB] ");
102 vfprintf(stderr, fmt, args);
103 fprintf(stderr, "\n");
104 va_end(args);
105 }
106
107 /**
108 * Run the daemon and handle unix signals
109 */
110 static void run(private_daemon_t *this)
111 {
112 /* reselect signals for this thread */
113 sigemptyset(&(this->signal_set));
114 sigaddset(&(this->signal_set), SIGINT);
115 sigaddset(&(this->signal_set), SIGHUP);
116 sigaddset(&(this->signal_set), SIGTERM);
117 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
118
119 while(TRUE)
120 {
121 int signal_number;
122 int error;
123
124 error = sigwait(&(this->signal_set), &signal_number);
125 if(error)
126 {
127 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
128 return;
129 }
130 switch (signal_number)
131 {
132 case SIGHUP:
133 {
134 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
135 break;
136 }
137 case SIGINT:
138 {
139 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
140 return;
141 }
142 case SIGTERM:
143 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
144 return;
145 default:
146 {
147 DBG1(DBG_DMN, "unknown signal %d received. Ignored", signal_number);
148 break;
149 }
150 }
151 }
152 }
153
154 /**
155 * Clean up all daemon resources
156 */
157 static void destroy(private_daemon_t *this)
158 {
159 /* destruction is a non trivial task, we need to follow
160 * a strict order to prevent threading issues!
161 * Kill active threads first, except the sender, as
162 * the killed IKE_SA want to send delete messages.
163 */
164 /* we don't want to receive anything anymore... */
165 DESTROY_IF(this->public.receiver);
166 /* ignore all incoming user requests */
167 DESTROY_IF(this->public.stroke);
168 /* stop scheduing jobs */
169 DESTROY_IF(this->public.scheduler);
170 /* stop processing jobs */
171 DESTROY_IF(this->public.thread_pool);
172 /* shut down manager with all IKE SAs */
173 DESTROY_IF(this->public.ike_sa_manager);
174 /* all child SAs should be down now, so kill kernel interface */
175 DESTROY_IF(this->public.kernel_interface);
176 /* destroy other infrastructure */
177 DESTROY_IF(this->public.job_queue);
178 DESTROY_IF(this->public.event_queue);
179 DESTROY_IF(this->public.credentials);
180 DESTROY_IF(this->public.cfg_store);
181 DESTROY_IF(this->public.local_backend);
182 sched_yield();
183 /* we hope the sender could send the outstanding deletes, but
184 * we shut down here at any cost */
185 DESTROY_IF(this->public.sender);
186 DESTROY_IF(this->public.socket);
187 /* before destroying bus with its listeners, rehook library logs */
188 dbg = dbg_stderr;
189 DESTROY_IF(this->public.bus);
190 DESTROY_IF(this->public.outlog);
191 DESTROY_IF(this->public.syslog);
192 DESTROY_IF(this->public.authlog);
193 free(this);
194 }
195
196 /**
197 * Enforce daemon shutdown, with a given reason to do so.
198 */
199 static void kill_daemon(private_daemon_t *this, char *reason)
200 {
201 /* we send SIGTERM, so the daemon can cleanly shut down */
202 DBG1(DBG_DMN, "killing daemon: %s", reason);
203 if (this->main_thread_id == pthread_self())
204 {
205 /* initialization failed, terminate daemon */
206 destroy(this);
207 unlink(PID_FILE);
208 exit(-1);
209 }
210 else
211 {
212 DBG1(DBG_DMN, "sending SIGTERM to ourself");
213 raise(SIGTERM);
214 /* thread must die, since he produced a ciritcal failure and can't continue */
215 pthread_exit(NULL);
216 }
217 }
218
219 /**
220 * Initialize the daemon, optional with a strict crl policy
221 */
222 static void initialize(private_daemon_t *this, bool strict, bool syslog,
223 level_t levels[])
224 {
225 credential_store_t* credentials;
226 signal_t signal;
227
228 /* for uncritical pseudo random numbers */
229 srandom(time(NULL) + getpid());
230
231 /* setup bus and it's listeners first to enable log output */
232 this->public.bus = bus_create();
233 this->public.outlog = file_logger_create(stdout);
234 this->public.syslog = sys_logger_create(LOG_DAEMON);
235 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
236 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
237 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
238 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
239 this->public.authlog->set_level(this->public.authlog, SIG_ANY, LEVEL_AUDIT);
240 /* set up hook to log dbg message in library via charons message bus */
241 dbg = dbg_bus;
242
243 /* apply loglevels */
244 for (signal = 0; signal < DBG_MAX; signal++)
245 {
246 if (syslog)
247 {
248 this->public.syslog->set_level(this->public.syslog,
249 signal, levels[signal]);
250 }
251 else
252 {
253 this->public.outlog->set_level(this->public.outlog,
254 signal, levels[signal]);
255 }
256 }
257
258 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
259
260 this->public.socket = socket_create(IKEV2_UDP_PORT, IKEV2_NATT_PORT);
261 this->public.ike_sa_manager = ike_sa_manager_create();
262 this->public.job_queue = job_queue_create();
263 this->public.event_queue = event_queue_create();
264 this->public.credentials = (credential_store_t*)local_credential_store_create(strict);
265 this->public.cfg_store = cfg_store_create();
266 this->public.local_backend = local_backend_create();
267 this->public.cfg_store->register_backend(this->public.cfg_store,
268 &this->public.local_backend->backend);
269
270 /* initialize fetcher_t class */
271 fetcher_initialize();
272
273 /* load secrets, ca certificates and crls */
274 credentials = this->public.credentials;
275 credentials->load_ca_certificates(credentials);
276 credentials->load_ocsp_certificates(credentials);
277 credentials->load_crls(credentials);
278 credentials->load_secrets(credentials);
279
280 /* start building threads, we are multi-threaded NOW */
281 this->public.stroke = stroke_create(this->public.local_backend);
282 this->public.sender = sender_create();
283 this->public.receiver = receiver_create();
284 this->public.scheduler = scheduler_create();
285 this->public.kernel_interface = kernel_interface_create();
286 this->public.thread_pool = thread_pool_create(NUMBER_OF_WORKING_THREADS);
287 }
288
289 /**
290 * Handle SIGSEGV/SIGILL signals raised by threads
291 */
292 void signal_handler(int signal)
293 {
294 #ifdef HAVE_BACKTRACE
295 void *array[20];
296 size_t size;
297 char **strings;
298 size_t i;
299
300 size = backtrace(array, 20);
301 strings = backtrace_symbols(array, size);
302
303 DBG1(DBG_DMN, "thread %u received %s. Dumping %d frames from stack:",
304 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
305
306 for (i = 0; i < size; i++)
307 {
308 DBG1(DBG_DMN, " %s", strings[i]);
309 }
310 free (strings);
311 #else /* !HAVE_BACKTRACE */
312 DBG1(DBG_DMN, "thread %u received %s",
313 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
314 #endif /* HAVE_BACKTRACE */
315 DBG1(DBG_DMN, "killing ourself hard after SIGSEGV");
316 raise(SIGKILL);
317 }
318
319 /**
320 * Create the daemon.
321 */
322 private_daemon_t *daemon_create(void)
323 {
324 private_daemon_t *this = malloc_thing(private_daemon_t);
325 struct sigaction action;
326
327 /* assign methods */
328 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
329
330 /* NULL members for clean destruction */
331 this->public.socket = NULL;
332 this->public.ike_sa_manager = NULL;
333 this->public.job_queue = NULL;
334 this->public.event_queue = NULL;
335 this->public.credentials = NULL;
336 this->public.cfg_store = NULL;
337 this->public.local_backend = NULL;
338 this->public.sender= NULL;
339 this->public.receiver = NULL;
340 this->public.scheduler = NULL;
341 this->public.kernel_interface = NULL;
342 this->public.thread_pool = NULL;
343 this->public.stroke = NULL;
344 this->public.bus = NULL;
345 this->public.outlog = NULL;
346 this->public.syslog = NULL;
347 this->public.authlog = NULL;
348
349 this->main_thread_id = pthread_self();
350
351 /* setup signal handling for all threads */
352 sigemptyset(&(this->signal_set));
353 sigaddset(&(this->signal_set), SIGSEGV);
354 sigaddset(&(this->signal_set), SIGINT);
355 sigaddset(&(this->signal_set), SIGHUP);
356 sigaddset(&(this->signal_set), SIGTERM);
357 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
358
359 /* setup SIGSEGV handler for all threads */
360 action.sa_handler = signal_handler;
361 action.sa_mask = this->signal_set;
362 action.sa_flags = 0;
363 sigaction(SIGSEGV, &action, NULL);
364 sigaction(SIGILL, &action, NULL);
365 return this;
366 }
367
368 /**
369 * print command line usage and exit
370 */
371 static void usage(const char *msg)
372 {
373 if (msg != NULL && *msg != '\0')
374 {
375 fprintf(stderr, "%s\n", msg);
376 }
377 fprintf(stderr, "Usage: charon\n"
378 " [--help]\n"
379 " [--version]\n"
380 " [--strictcrlpolicy]\n"
381 " [--cachecrls]\n"
382 " [--crlcheckinterval <interval>]\n"
383 " [--eapdir <dir>]\n"
384 " [--use-syslog]\n"
385 " [--debug-<type> <level>]\n"
386 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
387 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
388 " 2 = controlmore, 3 = raw, 4 = private)\n"
389 "\n"
390 );
391 exit(msg == NULL? 0 : 1);
392 }
393
394 /**
395 * Main function, manages the daemon.
396 */
397 int main(int argc, char *argv[])
398 {
399 u_int crl_check_interval = 0;
400 bool strict_crl_policy = FALSE;
401 bool cache_crls = FALSE;
402 bool use_syslog = FALSE;
403 char *eapdir = IPSEC_EAPDIR;
404
405 private_daemon_t *private_charon;
406 FILE *pid_file;
407 struct stat stb;
408 linked_list_t *list;
409 host_t *host;
410 level_t levels[DBG_MAX];
411 int signal;
412
413 /* use CTRL loglevel for default */
414 for (signal = 0; signal < DBG_MAX; signal++)
415 {
416 levels[signal] = LEVEL_CTRL;
417 }
418
419 /* handle arguments */
420 for (;;)
421 {
422 struct option long_opts[] = {
423 { "help", no_argument, NULL, 'h' },
424 { "version", no_argument, NULL, 'v' },
425 { "use-syslog", no_argument, NULL, 'l' },
426 { "strictcrlpolicy", no_argument, NULL, 'r' },
427 { "cachecrls", no_argument, NULL, 'C' },
428 { "crlcheckinterval", required_argument, NULL, 'x' },
429 { "eapdir", required_argument, NULL, 'e' },
430 /* TODO: handle "debug-all" */
431 { "debug-dmn", required_argument, &signal, DBG_DMN },
432 { "debug-mgr", required_argument, &signal, DBG_MGR },
433 { "debug-ike", required_argument, &signal, DBG_IKE },
434 { "debug-chd", required_argument, &signal, DBG_CHD },
435 { "debug-job", required_argument, &signal, DBG_JOB },
436 { "debug-cfg", required_argument, &signal, DBG_CFG },
437 { "debug-knl", required_argument, &signal, DBG_KNL },
438 { "debug-net", required_argument, &signal, DBG_NET },
439 { "debug-enc", required_argument, &signal, DBG_ENC },
440 { "debug-lib", required_argument, &signal, DBG_LIB },
441 { 0,0,0,0 }
442 };
443
444 int c = getopt_long(argc, argv, "", long_opts, NULL);
445 switch (c)
446 {
447 case EOF:
448 break;
449 case 'h':
450 usage(NULL);
451 break;
452 case 'v':
453 printf("Linux strongSwan %s\n", VERSION);
454 exit(0);
455 case 'l':
456 use_syslog = TRUE;
457 continue;
458 case 'r':
459 strict_crl_policy = TRUE;
460 continue;
461 case 'C':
462 cache_crls = TRUE;
463 continue;
464 case 'x':
465 crl_check_interval = atoi(optarg);
466 continue;
467 case 'e':
468 eapdir = optarg;
469 continue;
470 case 0:
471 /* option is in signal */
472 levels[signal] = atoi(optarg);
473 continue;
474 default:
475 usage("");
476 break;
477 }
478 break;
479 }
480
481 private_charon = daemon_create();
482 charon = (daemon_t*)private_charon;
483
484 /* initialize daemon */
485 initialize(private_charon, strict_crl_policy, use_syslog, levels);
486
487 /* load pluggable EAP modules */
488 eap_method_load(eapdir);
489
490 /* set cache_crls and crl_check_interval options */
491 ca_info_set_options(cache_crls, crl_check_interval);
492
493 /* check/setup PID file */
494 if (stat(PID_FILE, &stb) == 0)
495 {
496 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
497 destroy(private_charon);
498 exit(-1);
499 }
500 pid_file = fopen(PID_FILE, "w");
501 if (pid_file)
502 {
503 fprintf(pid_file, "%d\n", getpid());
504 fclose(pid_file);
505 }
506
507 /* log socket info */
508 list = charon->kernel_interface->create_address_list(charon->kernel_interface);
509 DBG1(DBG_NET, "listening on %d addresses:", list->get_count(list));
510 while (list->remove_first(list, (void**)&host) == SUCCESS)
511 {
512 DBG1(DBG_NET, " %H", host);
513 host->destroy(host);
514 }
515 list->destroy(list);
516
517 /* run daemon */
518 run(private_charon);
519
520 eap_method_unload();
521 fetcher_finalize();
522 /* normal termination, cleanup and exit */
523 destroy(private_charon);
524 unlink(PID_FILE);
525
526 return 0;
527 }