some improvements in signaling code
[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 <types.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 void *array[20];
289 size_t size;
290 char **strings;
291 size_t i;
292
293 size = backtrace(array, 20);
294 strings = backtrace_symbols(array, size);
295
296 DBG1(DBG_DMN, "thread %u received %s. Dumping %d frames from stack:",
297 signal == SIGSEGV ? "SIGSEGV" : "SIGILL", pthread_self(), size);
298
299 for (i = 0; i < size; i++)
300 {
301 DBG1(DBG_DMN, " %s", strings[i]);
302 }
303 free (strings);
304 DBG1(DBG_DMN, "killing ourself hard after SIGSEGV");
305 raise(SIGKILL);
306 }
307
308 /**
309 * Create the daemon.
310 */
311 private_daemon_t *daemon_create(void)
312 {
313 private_daemon_t *this = malloc_thing(private_daemon_t);
314 struct sigaction action;
315
316 /* assign methods */
317 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
318
319 /* NULL members for clean destruction */
320 this->public.socket = NULL;
321 this->public.ike_sa_manager = NULL;
322 this->public.job_queue = NULL;
323 this->public.event_queue = NULL;
324 this->public.send_queue = NULL;
325 this->public.configuration = NULL;
326 this->public.credentials = NULL;
327 this->public.connections = NULL;
328 this->public.policies = NULL;
329 this->public.sender= NULL;
330 this->public.receiver = NULL;
331 this->public.scheduler = NULL;
332 this->public.kernel_interface = NULL;
333 this->public.thread_pool = NULL;
334 this->public.stroke = NULL;
335 this->public.bus = NULL;
336 this->public.outlog = NULL;
337 this->public.syslog = NULL;
338 this->public.authlog = NULL;
339
340 this->main_thread_id = pthread_self();
341
342 /* setup signal handling for all threads */
343 sigemptyset(&(this->signal_set));
344 sigaddset(&(this->signal_set), SIGSEGV);
345 sigaddset(&(this->signal_set), SIGINT);
346 sigaddset(&(this->signal_set), SIGHUP);
347 sigaddset(&(this->signal_set), SIGTERM);
348 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
349
350 /* setup SIGSEGV handler for all threads */
351 action.sa_handler = signal_handler;
352 action.sa_mask = this->signal_set;
353 action.sa_flags = 0;
354 sigaction(SIGSEGV, &action, NULL);
355 sigaction(SIGILL, &action, NULL);
356 return this;
357 }
358
359 /**
360 * print command line usage and exit
361 */
362 static void usage(const char *msg)
363 {
364 if (msg != NULL && *msg != '\0')
365 {
366 fprintf(stderr, "%s\n", msg);
367 }
368 fprintf(stderr, "Usage: charon\n"
369 " [--help]\n"
370 " [--version]\n"
371 " [--strictcrlpolicy]\n"
372 " [--use-syslog]\n"
373 " [--debug-<type> <level>]\n"
374 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
375 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
376 " 2 = controlmore, 3 = raw, 4 = private)\n"
377 "\n"
378 );
379 exit(msg == NULL? 0 : 1);
380 }
381
382 /**
383 * Main function, manages the daemon.
384 */
385 int main(int argc, char *argv[])
386 {
387 bool strict_crl_policy = FALSE;
388 bool use_syslog = FALSE;
389
390 private_daemon_t *private_charon;
391 FILE *pid_file;
392 struct stat stb;
393 linked_list_t *list;
394 host_t *host;
395 level_t levels[DBG_MAX];
396 int signal;
397
398 /* use CTRL loglevel for default */
399 for (signal = 0; signal < DBG_MAX; signal++)
400 {
401 levels[signal] = LEVEL_CTRL;
402 }
403
404 /* handle arguments */
405 for (;;)
406 {
407 struct option long_opts[] = {
408 { "help", no_argument, NULL, 'h' },
409 { "version", no_argument, NULL, 'v' },
410 { "use-syslog", no_argument, NULL, 'l' },
411 { "strictcrlpolicy", no_argument, NULL, 'r' },
412 /* TODO: handle "debug-all" */
413 { "debug-dmn", required_argument, &signal, DBG_DMN },
414 { "debug-mgr", required_argument, &signal, DBG_MGR },
415 { "debug-ike", required_argument, &signal, DBG_IKE },
416 { "debug-chd", required_argument, &signal, DBG_CHD },
417 { "debug-job", required_argument, &signal, DBG_JOB },
418 { "debug-cfg", required_argument, &signal, DBG_CFG },
419 { "debug-knl", required_argument, &signal, DBG_KNL },
420 { "debug-net", required_argument, &signal, DBG_NET },
421 { "debug-enc", required_argument, &signal, DBG_ENC },
422 { "debug-lib", required_argument, &signal, DBG_LIB },
423 { 0,0,0,0 }
424 };
425
426 int c = getopt_long(argc, argv, "", long_opts, NULL);
427 switch (c)
428 {
429 case EOF:
430 break;
431 case 'h':
432 usage(NULL);
433 break;
434 case 'v':
435 printf("Linux strongSwan %s\n", VERSION);
436 exit(0);
437 case 'l':
438 use_syslog = TRUE;
439 continue;
440 case 'r':
441 strict_crl_policy = TRUE;
442 continue;
443 case 0:
444 /* option is in signal */
445 levels[signal] = atoi(optarg);
446 continue;
447 default:
448 usage("");
449 break;
450 }
451 break;
452 }
453
454 private_charon = daemon_create();
455 charon = (daemon_t*)private_charon;
456
457 /* initialize daemon */
458 initialize(private_charon, strict_crl_policy, use_syslog, levels);
459
460 /* check/setup PID file */
461 if (stat(PID_FILE, &stb) == 0)
462 {
463 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
464 destroy(private_charon);
465 exit(-1);
466 }
467 pid_file = fopen(PID_FILE, "w");
468 if (pid_file)
469 {
470 fprintf(pid_file, "%d\n", getpid());
471 fclose(pid_file);
472 }
473 /* log socket info */
474 list = charon->socket->create_local_address_list(charon->socket);
475 DBG1(DBG_NET, "listening on %d addresses:", list->get_count(list));
476 while (list->remove_first(list, (void**)&host) == SUCCESS)
477 {
478 DBG1(DBG_NET, " %H", host);
479 host->destroy(host);
480 }
481 list->destroy(list);
482
483 /* run daemon */
484 run(private_charon);
485
486 /* normal termination, cleanup and exit */
487 destroy(private_charon);
488 unlink(PID_FILE);
489
490 return 0;
491 }