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