fixed HAVE_BACKTRACE checks
[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 <config/credentials/local_credential_store.h>
43 #include <config/connections/local_connection_store.h>
44 #include <config/policies/local_policy_store.h>
45
46
47 typedef struct private_daemon_t private_daemon_t;
48
49 /**
50 * Private additions to daemon_t, contains threads and internal functions.
51 */
52 struct private_daemon_t {
53 /**
54 * Public members of daemon_t.
55 */
56 daemon_t public;
57
58 /**
59 * Signal set used for signal handling.
60 */
61 sigset_t signal_set;
62
63 /**
64 * The thread_id of main-thread.
65 */
66 pthread_t main_thread_id;
67 };
68
69 /**
70 * One and only instance of the daemon.
71 */
72 daemon_t *charon;
73
74 /**
75 * hook in library for debugging messages
76 */
77 extern void (*dbg) (int level, char *fmt, ...);
78
79 /**
80 * Logging hook for library logs, spreads debug message over bus
81 */
82 static void dbg_bus(int level, char *fmt, ...)
83 {
84 va_list args;
85
86 va_start(args, fmt);
87 charon->bus->vsignal(charon->bus, DBG_LIB, level, fmt, args);
88 va_end(args);
89 }
90
91 /**
92 * Logging hook for library logs, using stderr output
93 */
94 static void dbg_stderr(int level, char *fmt, ...)
95 {
96 va_list args;
97
98 va_start(args, fmt);
99 fprintf(stderr, "00[LIB] ");
100 vfprintf(stderr, fmt, args);
101 fprintf(stderr, "\n");
102 va_end(args);
103 }
104
105 /**
106 * Run the daemon and handle unix signals
107 */
108 static void run(private_daemon_t *this)
109 {
110 /* reselect signals for this thread */
111 sigemptyset(&(this->signal_set));
112 sigaddset(&(this->signal_set), SIGINT);
113 sigaddset(&(this->signal_set), SIGHUP);
114 sigaddset(&(this->signal_set), SIGTERM);
115 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
116
117 while(TRUE)
118 {
119 int signal_number;
120 int error;
121
122 error = sigwait(&(this->signal_set), &signal_number);
123 if(error)
124 {
125 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
126 return;
127 }
128 switch (signal_number)
129 {
130 case SIGHUP:
131 {
132 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
133 break;
134 }
135 case SIGINT:
136 {
137 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
138 return;
139 }
140 case SIGTERM:
141 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
142 return;
143 default:
144 {
145 DBG1(DBG_DMN, "unknown signal %d received. Ignored", signal_number);
146 break;
147 }
148 }
149 }
150 }
151
152 /**
153 * Clean up all daemon resources
154 */
155 static void destroy(private_daemon_t *this)
156 {
157 /* destruction is a non trivial task, we need to follow
158 * a strict order to prevent threading issues!
159 * Kill active threads first, except the sender, as
160 * the killed IKE_SA want to send delete messages.
161 */
162 /* we don't want to receive anything anymore... */
163 DESTROY_IF(this->public.receiver);
164 /* ignore all incoming user requests */
165 DESTROY_IF(this->public.stroke);
166 /* stop scheduing jobs */
167 DESTROY_IF(this->public.scheduler);
168 /* stop processing jobs */
169 DESTROY_IF(this->public.thread_pool);
170 /* shut down manager with all IKE SAs */
171 DESTROY_IF(this->public.ike_sa_manager);
172 /* all child SAs should be down now, so kill kernel interface */
173 DESTROY_IF(this->public.kernel_interface);
174 /* destroy other infrastructure */
175 DESTROY_IF(this->public.job_queue);
176 DESTROY_IF(this->public.event_queue);
177 DESTROY_IF(this->public.configuration);
178 DESTROY_IF(this->public.credentials);
179 DESTROY_IF(this->public.connections);
180 DESTROY_IF(this->public.policies);
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.send_queue);
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.configuration = configuration_create();
261 this->public.socket = socket_create(IKEV2_UDP_PORT, IKEV2_NATT_PORT);
262 this->public.ike_sa_manager = ike_sa_manager_create();
263 this->public.job_queue = job_queue_create();
264 this->public.event_queue = event_queue_create();
265 this->public.send_queue = send_queue_create();
266 this->public.connections = (connection_store_t*)local_connection_store_create();
267 this->public.policies = (policy_store_t*)local_policy_store_create();
268 this->public.credentials = (credential_store_t*)local_credential_store_create(strict);
269
270 /* load secrets, ca certificates and crls */
271 credentials = this->public.credentials;
272 credentials->load_ca_certificates(credentials);
273 credentials->load_crls(credentials);
274 credentials->load_secrets(credentials);
275
276 /* start building threads, we are multi-threaded NOW */
277 this->public.stroke = stroke_create();
278 this->public.sender = sender_create();
279 this->public.receiver = receiver_create();
280 this->public.scheduler = scheduler_create();
281 this->public.kernel_interface = kernel_interface_create();
282 this->public.thread_pool = thread_pool_create(NUMBER_OF_WORKING_THREADS);
283 }
284
285 /**
286 * Handle SIGSEGV/SIGILL signals raised by threads
287 */
288 void signal_handler(int signal)
289 {
290 #ifdef HAVE_BACKTRACE
291 void *array[20];
292 size_t size;
293 char **strings;
294 size_t i;
295
296 size = backtrace(array, 20);
297 strings = backtrace_symbols(array, size);
298
299 DBG1(DBG_DMN, "thread %u received %s. Dumping %d frames from stack:",
300 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
301
302 for (i = 0; i < size; i++)
303 {
304 DBG1(DBG_DMN, " %s", strings[i]);
305 }
306 free (strings);
307 #else /* !HAVE_BACKTRACE */
308 DBG1(DBG_DMN, "thread %u received %s",
309 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
310 #endif /* HAVE_BACKTRACE */
311 DBG1(DBG_DMN, "killing ourself hard after SIGSEGV");
312 raise(SIGKILL);
313 }
314
315 /**
316 * Create the daemon.
317 */
318 private_daemon_t *daemon_create(void)
319 {
320 private_daemon_t *this = malloc_thing(private_daemon_t);
321 struct sigaction action;
322
323 /* assign methods */
324 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
325
326 /* NULL members for clean destruction */
327 this->public.socket = NULL;
328 this->public.ike_sa_manager = NULL;
329 this->public.job_queue = NULL;
330 this->public.event_queue = NULL;
331 this->public.send_queue = NULL;
332 this->public.configuration = NULL;
333 this->public.credentials = NULL;
334 this->public.connections = NULL;
335 this->public.policies = NULL;
336 this->public.sender= NULL;
337 this->public.receiver = NULL;
338 this->public.scheduler = NULL;
339 this->public.kernel_interface = NULL;
340 this->public.thread_pool = NULL;
341 this->public.stroke = NULL;
342 this->public.bus = NULL;
343 this->public.outlog = NULL;
344 this->public.syslog = NULL;
345 this->public.authlog = NULL;
346
347 this->main_thread_id = pthread_self();
348
349 /* setup signal handling for all threads */
350 sigemptyset(&(this->signal_set));
351 sigaddset(&(this->signal_set), SIGSEGV);
352 sigaddset(&(this->signal_set), SIGINT);
353 sigaddset(&(this->signal_set), SIGHUP);
354 sigaddset(&(this->signal_set), SIGTERM);
355 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
356
357 /* setup SIGSEGV handler for all threads */
358 action.sa_handler = signal_handler;
359 action.sa_mask = this->signal_set;
360 action.sa_flags = 0;
361 sigaction(SIGSEGV, &action, NULL);
362 sigaction(SIGILL, &action, NULL);
363 return this;
364 }
365
366 /**
367 * print command line usage and exit
368 */
369 static void usage(const char *msg)
370 {
371 if (msg != NULL && *msg != '\0')
372 {
373 fprintf(stderr, "%s\n", msg);
374 }
375 fprintf(stderr, "Usage: charon\n"
376 " [--help]\n"
377 " [--version]\n"
378 " [--strictcrlpolicy]\n"
379 " [--use-syslog]\n"
380 " [--debug-<type> <level>]\n"
381 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
382 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
383 " 2 = controlmore, 3 = raw, 4 = private)\n"
384 "\n"
385 );
386 exit(msg == NULL? 0 : 1);
387 }
388
389 /**
390 * Main function, manages the daemon.
391 */
392 int main(int argc, char *argv[])
393 {
394 bool strict_crl_policy = FALSE;
395 bool use_syslog = FALSE;
396
397 private_daemon_t *private_charon;
398 FILE *pid_file;
399 struct stat stb;
400 linked_list_t *list;
401 host_t *host;
402 level_t levels[DBG_MAX];
403 int signal;
404
405 /* use CTRL loglevel for default */
406 for (signal = 0; signal < DBG_MAX; signal++)
407 {
408 levels[signal] = LEVEL_CTRL;
409 }
410
411 /* handle arguments */
412 for (;;)
413 {
414 struct option long_opts[] = {
415 { "help", no_argument, NULL, 'h' },
416 { "version", no_argument, NULL, 'v' },
417 { "use-syslog", no_argument, NULL, 'l' },
418 { "strictcrlpolicy", no_argument, NULL, 'r' },
419 /* TODO: handle "debug-all" */
420 { "debug-dmn", required_argument, &signal, DBG_DMN },
421 { "debug-mgr", required_argument, &signal, DBG_MGR },
422 { "debug-ike", required_argument, &signal, DBG_IKE },
423 { "debug-chd", required_argument, &signal, DBG_CHD },
424 { "debug-job", required_argument, &signal, DBG_JOB },
425 { "debug-cfg", required_argument, &signal, DBG_CFG },
426 { "debug-knl", required_argument, &signal, DBG_KNL },
427 { "debug-net", required_argument, &signal, DBG_NET },
428 { "debug-enc", required_argument, &signal, DBG_ENC },
429 { "debug-lib", required_argument, &signal, DBG_LIB },
430 { 0,0,0,0 }
431 };
432
433 int c = getopt_long(argc, argv, "", long_opts, NULL);
434 switch (c)
435 {
436 case EOF:
437 break;
438 case 'h':
439 usage(NULL);
440 break;
441 case 'v':
442 printf("Linux strongSwan %s\n", VERSION);
443 exit(0);
444 case 'l':
445 use_syslog = TRUE;
446 continue;
447 case 'r':
448 strict_crl_policy = TRUE;
449 continue;
450 case 0:
451 /* option is in signal */
452 levels[signal] = atoi(optarg);
453 continue;
454 default:
455 usage("");
456 break;
457 }
458 break;
459 }
460
461 private_charon = daemon_create();
462 charon = (daemon_t*)private_charon;
463
464 /* initialize daemon */
465 initialize(private_charon, strict_crl_policy, use_syslog, levels);
466
467 /* check/setup PID file */
468 if (stat(PID_FILE, &stb) == 0)
469 {
470 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
471 destroy(private_charon);
472 exit(-1);
473 }
474 pid_file = fopen(PID_FILE, "w");
475 if (pid_file)
476 {
477 fprintf(pid_file, "%d\n", getpid());
478 fclose(pid_file);
479 }
480 /* log socket info */
481 list = charon->socket->create_local_address_list(charon->socket);
482 DBG1(DBG_NET, "listening on %d addresses:", list->get_count(list));
483 while (list->remove_first(list, (void**)&host) == SUCCESS)
484 {
485 DBG1(DBG_NET, " %H", host);
486 host->destroy(host);
487 }
488 list->destroy(list);
489
490 /* run daemon */
491 run(private_charon);
492
493 /* normal termination, cleanup and exit */
494 destroy(private_charon);
495 unlink(PID_FILE);
496
497 return 0;
498 }