fixed typo
[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 #include <sa/authenticators/eap/eap_method.h>
46
47
48 typedef struct private_daemon_t private_daemon_t;
49
50 /**
51 * Private additions to daemon_t, contains threads and internal functions.
52 */
53 struct private_daemon_t {
54 /**
55 * Public members of daemon_t.
56 */
57 daemon_t public;
58
59 /**
60 * Signal set used for signal handling.
61 */
62 sigset_t signal_set;
63
64 /**
65 * The thread_id of main-thread.
66 */
67 pthread_t main_thread_id;
68 };
69
70 /**
71 * One and only instance of the daemon.
72 */
73 daemon_t *charon;
74
75 /**
76 * hook in library for debugging messages
77 */
78 extern void (*dbg) (int level, char *fmt, ...);
79
80 /**
81 * Logging hook for library logs, spreads debug message over bus
82 */
83 static void dbg_bus(int level, char *fmt, ...)
84 {
85 va_list args;
86
87 va_start(args, fmt);
88 charon->bus->vsignal(charon->bus, DBG_LIB, level, fmt, args);
89 va_end(args);
90 }
91
92 /**
93 * Logging hook for library logs, using stderr output
94 */
95 static void dbg_stderr(int level, char *fmt, ...)
96 {
97 va_list args;
98
99 va_start(args, fmt);
100 fprintf(stderr, "00[LIB] ");
101 vfprintf(stderr, fmt, args);
102 fprintf(stderr, "\n");
103 va_end(args);
104 }
105
106 /**
107 * Run the daemon and handle unix signals
108 */
109 static void run(private_daemon_t *this)
110 {
111 /* reselect signals for this thread */
112 sigemptyset(&(this->signal_set));
113 sigaddset(&(this->signal_set), SIGINT);
114 sigaddset(&(this->signal_set), SIGHUP);
115 sigaddset(&(this->signal_set), SIGTERM);
116 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
117
118 while(TRUE)
119 {
120 int signal_number;
121 int error;
122
123 error = sigwait(&(this->signal_set), &signal_number);
124 if(error)
125 {
126 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
127 return;
128 }
129 switch (signal_number)
130 {
131 case SIGHUP:
132 {
133 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
134 break;
135 }
136 case SIGINT:
137 {
138 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
139 return;
140 }
141 case SIGTERM:
142 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
143 return;
144 default:
145 {
146 DBG1(DBG_DMN, "unknown signal %d received. Ignored", signal_number);
147 break;
148 }
149 }
150 }
151 }
152
153 /**
154 * Clean up all daemon resources
155 */
156 static void destroy(private_daemon_t *this)
157 {
158 /* destruction is a non trivial task, we need to follow
159 * a strict order to prevent threading issues!
160 * Kill active threads first, except the sender, as
161 * the killed IKE_SA want to send delete messages.
162 */
163 /* we don't want to receive anything anymore... */
164 DESTROY_IF(this->public.receiver);
165 /* ignore all incoming user requests */
166 DESTROY_IF(this->public.stroke);
167 /* stop scheduing jobs */
168 DESTROY_IF(this->public.scheduler);
169 /* stop processing jobs */
170 DESTROY_IF(this->public.thread_pool);
171 /* shut down manager with all IKE SAs */
172 DESTROY_IF(this->public.ike_sa_manager);
173 /* all child SAs should be down now, so kill kernel interface */
174 DESTROY_IF(this->public.kernel_interface);
175 /* destroy other infrastructure */
176 DESTROY_IF(this->public.job_queue);
177 DESTROY_IF(this->public.event_queue);
178 DESTROY_IF(this->public.configuration);
179 DESTROY_IF(this->public.credentials);
180 DESTROY_IF(this->public.connections);
181 DESTROY_IF(this->public.policies);
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.send_queue);
187 DESTROY_IF(this->public.socket);
188 /* before destroying bus with its listeners, rehook library logs */
189 dbg = dbg_stderr;
190 DESTROY_IF(this->public.bus);
191 DESTROY_IF(this->public.outlog);
192 DESTROY_IF(this->public.syslog);
193 DESTROY_IF(this->public.authlog);
194 free(this);
195 }
196
197 /**
198 * Enforce daemon shutdown, with a given reason to do so.
199 */
200 static void kill_daemon(private_daemon_t *this, char *reason)
201 {
202 /* we send SIGTERM, so the daemon can cleanly shut down */
203 DBG1(DBG_DMN, "killing daemon: %s", reason);
204 if (this->main_thread_id == pthread_self())
205 {
206 /* initialization failed, terminate daemon */
207 destroy(this);
208 unlink(PID_FILE);
209 exit(-1);
210 }
211 else
212 {
213 DBG1(DBG_DMN, "sending SIGTERM to ourself");
214 raise(SIGTERM);
215 /* thread must die, since he produced a ciritcal failure and can't continue */
216 pthread_exit(NULL);
217 }
218 }
219
220 /**
221 * Initialize the daemon, optional with a strict crl policy
222 */
223 static void initialize(private_daemon_t *this, bool strict, bool syslog,
224 level_t levels[])
225 {
226 credential_store_t* credentials;
227 signal_t signal;
228
229 /* for uncritical pseudo random numbers */
230 srandom(time(NULL) + getpid());
231
232 /* setup bus and it's listeners first to enable log output */
233 this->public.bus = bus_create();
234 this->public.outlog = file_logger_create(stdout);
235 this->public.syslog = sys_logger_create(LOG_DAEMON);
236 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
237 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
238 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
239 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
240 this->public.authlog->set_level(this->public.authlog, SIG_ANY, LEVEL_AUDIT);
241 /* set up hook to log dbg message in library via charons message bus */
242 dbg = dbg_bus;
243
244 /* apply loglevels */
245 for (signal = 0; signal < DBG_MAX; signal++)
246 {
247 if (syslog)
248 {
249 this->public.syslog->set_level(this->public.syslog,
250 signal, levels[signal]);
251 }
252 else
253 {
254 this->public.outlog->set_level(this->public.outlog,
255 signal, levels[signal]);
256 }
257 }
258
259 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
260
261 this->public.configuration = configuration_create();
262 this->public.socket = socket_create(IKEV2_UDP_PORT, IKEV2_NATT_PORT);
263 this->public.ike_sa_manager = ike_sa_manager_create();
264 this->public.job_queue = job_queue_create();
265 this->public.event_queue = event_queue_create();
266 this->public.send_queue = send_queue_create();
267 this->public.connections = (connection_store_t*)local_connection_store_create();
268 this->public.policies = (policy_store_t*)local_policy_store_create();
269 this->public.credentials = (credential_store_t*)local_credential_store_create(strict);
270
271 /* load secrets, ca certificates and crls */
272 credentials = this->public.credentials;
273 credentials->load_ca_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.stroke = stroke_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.send_queue = NULL;
333 this->public.configuration = NULL;
334 this->public.credentials = NULL;
335 this->public.connections = NULL;
336 this->public.policies = NULL;
337 this->public.sender= NULL;
338 this->public.receiver = NULL;
339 this->public.scheduler = NULL;
340 this->public.kernel_interface = NULL;
341 this->public.thread_pool = NULL;
342 this->public.stroke = NULL;
343 this->public.bus = NULL;
344 this->public.outlog = NULL;
345 this->public.syslog = NULL;
346 this->public.authlog = NULL;
347
348 this->main_thread_id = pthread_self();
349
350 /* setup signal handling for all threads */
351 sigemptyset(&(this->signal_set));
352 sigaddset(&(this->signal_set), SIGSEGV);
353 sigaddset(&(this->signal_set), SIGINT);
354 sigaddset(&(this->signal_set), SIGHUP);
355 sigaddset(&(this->signal_set), SIGTERM);
356 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
357
358 /* setup SIGSEGV handler for all threads */
359 action.sa_handler = signal_handler;
360 action.sa_mask = this->signal_set;
361 action.sa_flags = 0;
362 sigaction(SIGSEGV, &action, NULL);
363 sigaction(SIGILL, &action, NULL);
364 return this;
365 }
366
367 /**
368 * print command line usage and exit
369 */
370 static void usage(const char *msg)
371 {
372 if (msg != NULL && *msg != '\0')
373 {
374 fprintf(stderr, "%s\n", msg);
375 }
376 fprintf(stderr, "Usage: charon\n"
377 " [--help]\n"
378 " [--version]\n"
379 " [--strictcrlpolicy]\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 bool strict_crl_policy = FALSE;
396 bool use_syslog = FALSE;
397 char *eapdir = IPSEC_EAPDIR;
398
399 private_daemon_t *private_charon;
400 FILE *pid_file;
401 struct stat stb;
402 linked_list_t *list;
403 host_t *host;
404 level_t levels[DBG_MAX];
405 int signal;
406
407 /* use CTRL loglevel for default */
408 for (signal = 0; signal < DBG_MAX; signal++)
409 {
410 levels[signal] = LEVEL_CTRL;
411 }
412
413 /* handle arguments */
414 for (;;)
415 {
416 struct option long_opts[] = {
417 { "help", no_argument, NULL, 'h' },
418 { "version", no_argument, NULL, 'v' },
419 { "use-syslog", no_argument, NULL, 'l' },
420 { "strictcrlpolicy", no_argument, NULL, 'r' },
421 { "eapdir", required_argument, NULL, 'e' },
422 /* TODO: handle "debug-all" */
423 { "debug-dmn", required_argument, &signal, DBG_DMN },
424 { "debug-mgr", required_argument, &signal, DBG_MGR },
425 { "debug-ike", required_argument, &signal, DBG_IKE },
426 { "debug-chd", required_argument, &signal, DBG_CHD },
427 { "debug-job", required_argument, &signal, DBG_JOB },
428 { "debug-cfg", required_argument, &signal, DBG_CFG },
429 { "debug-knl", required_argument, &signal, DBG_KNL },
430 { "debug-net", required_argument, &signal, DBG_NET },
431 { "debug-enc", required_argument, &signal, DBG_ENC },
432 { "debug-lib", required_argument, &signal, DBG_LIB },
433 { 0,0,0,0 }
434 };
435
436 int c = getopt_long(argc, argv, "", long_opts, NULL);
437 switch (c)
438 {
439 case EOF:
440 break;
441 case 'h':
442 usage(NULL);
443 break;
444 case 'v':
445 printf("Linux strongSwan %s\n", VERSION);
446 exit(0);
447 case 'l':
448 use_syslog = TRUE;
449 continue;
450 case 'r':
451 strict_crl_policy = TRUE;
452 continue;
453 case 'e':
454 eapdir = optarg;
455 continue;
456 case 0:
457 /* option is in signal */
458 levels[signal] = atoi(optarg);
459 continue;
460 default:
461 usage("");
462 break;
463 }
464 break;
465 }
466
467 private_charon = daemon_create();
468 charon = (daemon_t*)private_charon;
469
470 /* initialize daemon */
471 initialize(private_charon, strict_crl_policy, use_syslog, levels);
472 /* load pluggable EAP modules */
473 eap_method_load(eapdir);
474
475 /* check/setup PID file */
476 if (stat(PID_FILE, &stb) == 0)
477 {
478 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
479 destroy(private_charon);
480 exit(-1);
481 }
482 pid_file = fopen(PID_FILE, "w");
483 if (pid_file)
484 {
485 fprintf(pid_file, "%d\n", getpid());
486 fclose(pid_file);
487 }
488
489 /* log socket info */
490 list = charon->kernel_interface->create_address_list(charon->kernel_interface);
491 DBG1(DBG_NET, "listening on %d addresses:", list->get_count(list));
492 while (list->remove_first(list, (void**)&host) == SUCCESS)
493 {
494 DBG1(DBG_NET, " %H", host);
495 host->destroy(host);
496 }
497 list->destroy(list);
498
499 /* run daemon */
500 run(private_charon);
501
502 eap_method_unload();
503 /* normal termination, cleanup and exit */
504 destroy(private_charon);
505 unlink(PID_FILE);
506
507 return 0;
508 }