fixed casting
[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.interfaces);
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.backends);
181 sched_yield();
182 /* we hope the sender could send the outstanding deletes, but
183 * we shut down here at any cost */
184 DESTROY_IF(this->public.sender);
185 DESTROY_IF(this->public.socket);
186 /* before destroying bus with its listeners, rehook library logs */
187 dbg = dbg_stderr;
188 DESTROY_IF(this->public.bus);
189 DESTROY_IF(this->public.outlog);
190 DESTROY_IF(this->public.syslog);
191 DESTROY_IF(this->public.authlog);
192 free(this);
193 }
194
195 /**
196 * Enforce daemon shutdown, with a given reason to do so.
197 */
198 static void kill_daemon(private_daemon_t *this, char *reason)
199 {
200 /* we send SIGTERM, so the daemon can cleanly shut down */
201 DBG1(DBG_DMN, "killing daemon: %s", reason);
202 if (this->main_thread_id == pthread_self())
203 {
204 /* initialization failed, terminate daemon */
205 destroy(this);
206 unlink(PID_FILE);
207 exit(-1);
208 }
209 else
210 {
211 DBG1(DBG_DMN, "sending SIGTERM to ourself");
212 raise(SIGTERM);
213 /* thread must die, since he produced a ciritcal failure and can't continue */
214 pthread_exit(NULL);
215 }
216 }
217
218 /**
219 * Initialize the daemon, optional with a strict crl policy
220 */
221 static void initialize(private_daemon_t *this, bool syslog, level_t levels[])
222 {
223 credential_store_t* credentials;
224 signal_t signal;
225
226 /* for uncritical pseudo random numbers */
227 srandom(time(NULL) + getpid());
228
229 /* setup bus and it's listeners first to enable log output */
230 this->public.bus = bus_create();
231 this->public.outlog = file_logger_create(stdout);
232 this->public.syslog = sys_logger_create(LOG_DAEMON);
233 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
234 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
235 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
236 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
237 this->public.authlog->set_level(this->public.authlog, SIG_ANY, LEVEL_AUDIT);
238 /* set up hook to log dbg message in library via charons message bus */
239 dbg = dbg_bus;
240
241 /* apply loglevels */
242 for (signal = 0; signal < DBG_MAX; signal++)
243 {
244 if (syslog)
245 {
246 this->public.syslog->set_level(this->public.syslog,
247 signal, levels[signal]);
248 }
249 else
250 {
251 this->public.outlog->set_level(this->public.outlog,
252 signal, levels[signal]);
253 }
254 }
255
256 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
257
258 this->public.socket = socket_create(IKEV2_UDP_PORT, IKEV2_NATT_PORT);
259 this->public.ike_sa_manager = ike_sa_manager_create();
260 this->public.job_queue = job_queue_create();
261 this->public.event_queue = event_queue_create();
262 this->public.credentials = (credential_store_t*)local_credential_store_create();
263 this->public.backends = backend_manager_create();
264
265 /* initialize fetcher_t class */
266 fetcher_initialize();
267
268 /* load secrets, ca certificates and crls */
269 credentials = this->public.credentials;
270 credentials->load_ca_certificates(credentials);
271 credentials->load_aa_certificates(credentials);
272 credentials->load_attr_certificates(credentials);
273 credentials->load_ocsp_certificates(credentials);
274 credentials->load_crls(credentials);
275 credentials->load_secrets(credentials);
276
277 /* start building threads, we are multi-threaded NOW */
278 this->public.interfaces = interface_manager_create();
279 this->public.sender = sender_create();
280 this->public.receiver = receiver_create();
281 this->public.scheduler = scheduler_create();
282 this->public.kernel_interface = kernel_interface_create();
283 this->public.thread_pool = thread_pool_create(NUMBER_OF_WORKING_THREADS);
284 }
285
286 /**
287 * Handle SIGSEGV/SIGILL signals raised by threads
288 */
289 void signal_handler(int signal)
290 {
291 #ifdef HAVE_BACKTRACE
292 void *array[20];
293 size_t size;
294 char **strings;
295 size_t i;
296
297 size = backtrace(array, 20);
298 strings = backtrace_symbols(array, size);
299
300 DBG1(DBG_DMN, "thread %u received %s. Dumping %d frames from stack:",
301 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
302
303 for (i = 0; i < size; i++)
304 {
305 DBG1(DBG_DMN, " %s", strings[i]);
306 }
307 free (strings);
308 #else /* !HAVE_BACKTRACE */
309 DBG1(DBG_DMN, "thread %u received %s",
310 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
311 #endif /* HAVE_BACKTRACE */
312 DBG1(DBG_DMN, "killing ourself hard after SIGSEGV");
313 raise(SIGKILL);
314 }
315
316 /**
317 * Create the daemon.
318 */
319 private_daemon_t *daemon_create(void)
320 {
321 private_daemon_t *this = malloc_thing(private_daemon_t);
322 struct sigaction action;
323
324 /* assign methods */
325 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
326
327 /* NULL members for clean destruction */
328 this->public.socket = NULL;
329 this->public.ike_sa_manager = NULL;
330 this->public.job_queue = NULL;
331 this->public.event_queue = NULL;
332 this->public.credentials = NULL;
333 this->public.backends = NULL;
334 this->public.sender= NULL;
335 this->public.receiver = NULL;
336 this->public.scheduler = NULL;
337 this->public.kernel_interface = NULL;
338 this->public.thread_pool = NULL;
339 this->public.interfaces = NULL;
340 this->public.bus = NULL;
341 this->public.outlog = NULL;
342 this->public.syslog = NULL;
343 this->public.authlog = NULL;
344
345 this->main_thread_id = pthread_self();
346
347 /* setup signal handling for all threads */
348 sigemptyset(&(this->signal_set));
349 sigaddset(&(this->signal_set), SIGSEGV);
350 sigaddset(&(this->signal_set), SIGINT);
351 sigaddset(&(this->signal_set), SIGHUP);
352 sigaddset(&(this->signal_set), SIGTERM);
353 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
354
355 /* setup SIGSEGV handler for all threads */
356 action.sa_handler = signal_handler;
357 action.sa_mask = this->signal_set;
358 action.sa_flags = 0;
359 sigaction(SIGSEGV, &action, NULL);
360 sigaction(SIGILL, &action, NULL);
361 return this;
362 }
363
364 /**
365 * print command line usage and exit
366 */
367 static void usage(const char *msg)
368 {
369 if (msg != NULL && *msg != '\0')
370 {
371 fprintf(stderr, "%s\n", msg);
372 }
373 fprintf(stderr, "Usage: charon\n"
374 " [--help]\n"
375 " [--version]\n"
376 " [--strictcrlpolicy]\n"
377 " [--cachecrls]\n"
378 " [--crlcheckinterval <interval>]\n"
379 " [--eapdir <dir>]\n"
380 " [--use-syslog]\n"
381 " [--debug-<type> <level>]\n"
382 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
383 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
384 " 2 = controlmore, 3 = raw, 4 = private)\n"
385 "\n"
386 );
387 exit(msg == NULL? 0 : 1);
388 }
389
390 /**
391 * Main function, manages the daemon.
392 */
393 int main(int argc, char *argv[])
394 {
395 u_int crl_check_interval = 0;
396 strict_t strict_crl_policy = STRICT_NO;
397 bool cache_crls = FALSE;
398 bool use_syslog = FALSE;
399 char *eapdir = IPSEC_EAPDIR;
400
401 private_daemon_t *private_charon;
402 FILE *pid_file;
403 struct stat stb;
404 linked_list_t *list;
405 host_t *host;
406 level_t levels[DBG_MAX];
407 int signal;
408
409 /* use CTRL loglevel for default */
410 for (signal = 0; signal < DBG_MAX; signal++)
411 {
412 levels[signal] = LEVEL_CTRL;
413 }
414
415 /* handle arguments */
416 for (;;)
417 {
418 struct option long_opts[] = {
419 { "help", no_argument, NULL, 'h' },
420 { "version", no_argument, NULL, 'v' },
421 { "use-syslog", no_argument, NULL, 'l' },
422 { "strictcrlpolicy", required_argument, NULL, 'r' },
423 { "cachecrls", no_argument, NULL, 'C' },
424 { "crlcheckinterval", required_argument, NULL, 'x' },
425 { "eapdir", required_argument, NULL, 'e' },
426 /* TODO: handle "debug-all" */
427 { "debug-dmn", required_argument, &signal, DBG_DMN },
428 { "debug-mgr", required_argument, &signal, DBG_MGR },
429 { "debug-ike", required_argument, &signal, DBG_IKE },
430 { "debug-chd", required_argument, &signal, DBG_CHD },
431 { "debug-job", required_argument, &signal, DBG_JOB },
432 { "debug-cfg", required_argument, &signal, DBG_CFG },
433 { "debug-knl", required_argument, &signal, DBG_KNL },
434 { "debug-net", required_argument, &signal, DBG_NET },
435 { "debug-enc", required_argument, &signal, DBG_ENC },
436 { "debug-lib", required_argument, &signal, DBG_LIB },
437 { 0,0,0,0 }
438 };
439
440 int c = getopt_long(argc, argv, "", long_opts, NULL);
441 switch (c)
442 {
443 case EOF:
444 break;
445 case 'h':
446 usage(NULL);
447 break;
448 case 'v':
449 printf("Linux strongSwan %s\n", VERSION);
450 exit(0);
451 case 'l':
452 use_syslog = TRUE;
453 continue;
454 case 'r':
455 strict_crl_policy = atoi(optarg);
456 continue;
457 case 'C':
458 cache_crls = TRUE;
459 continue;
460 case 'x':
461 crl_check_interval = atoi(optarg);
462 continue;
463 case 'e':
464 eapdir = optarg;
465 continue;
466 case 0:
467 /* option is in signal */
468 levels[signal] = atoi(optarg);
469 continue;
470 default:
471 usage("");
472 break;
473 }
474 break;
475 }
476
477 private_charon = daemon_create();
478 charon = (daemon_t*)private_charon;
479
480 /* initialize daemon */
481 initialize(private_charon, use_syslog, levels);
482
483 /* load pluggable EAP modules */
484 eap_method_load(eapdir);
485
486 /* set strict_crl_policy, cache_crls and crl_check_interval options */
487 ca_info_set_options(strict_crl_policy, cache_crls, crl_check_interval);
488
489 /* check/setup PID file */
490 if (stat(PID_FILE, &stb) == 0)
491 {
492 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
493 destroy(private_charon);
494 exit(-1);
495 }
496 pid_file = fopen(PID_FILE, "w");
497 if (pid_file)
498 {
499 fprintf(pid_file, "%d\n", getpid());
500 fclose(pid_file);
501 }
502
503 /* log socket info */
504 list = charon->kernel_interface->create_address_list(charon->kernel_interface);
505 DBG1(DBG_NET, "listening on %d addresses:", list->get_count(list));
506 while (list->remove_first(list, (void**)&host) == SUCCESS)
507 {
508 DBG1(DBG_NET, " %H", host);
509 host->destroy(host);
510 }
511 list->destroy(list);
512
513 /* run daemon */
514 run(private_charon);
515
516 eap_method_unload();
517 fetcher_finalize();
518 /* normal termination, cleanup and exit */
519 destroy(private_charon);
520 unlink(PID_FILE);
521
522 return 0;
523 }