]> git.ipfire.org Git - thirdparty/strongswan.git/blob - src/charon/daemon.c
7671aea860332f13453a1ed35cf352672079fd72
[thirdparty/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/connections/local_connection_store.h>
46 #include <config/policies/local_policy_store.h>
47 #include <sa/authenticators/eap/eap_method.h>
48
49
50 typedef struct private_daemon_t private_daemon_t;
51
52 /**
53 * Private additions to daemon_t, contains threads and internal functions.
54 */
55 struct private_daemon_t {
56 /**
57 * Public members of daemon_t.
58 */
59 daemon_t public;
60
61 /**
62 * Signal set used for signal handling.
63 */
64 sigset_t signal_set;
65
66 /**
67 * The thread_id of main-thread.
68 */
69 pthread_t main_thread_id;
70 };
71
72 /**
73 * One and only instance of the daemon.
74 */
75 daemon_t *charon;
76
77 /**
78 * hook in library for debugging messages
79 */
80 extern void (*dbg) (int level, char *fmt, ...);
81
82 /**
83 * Logging hook for library logs, spreads debug message over bus
84 */
85 static void dbg_bus(int level, char *fmt, ...)
86 {
87 va_list args;
88
89 va_start(args, fmt);
90 charon->bus->vsignal(charon->bus, DBG_LIB, level, fmt, args);
91 va_end(args);
92 }
93
94 /**
95 * Logging hook for library logs, using stderr output
96 */
97 static void dbg_stderr(int level, char *fmt, ...)
98 {
99 va_list args;
100
101 va_start(args, fmt);
102 fprintf(stderr, "00[LIB] ");
103 vfprintf(stderr, fmt, args);
104 fprintf(stderr, "\n");
105 va_end(args);
106 }
107
108 /**
109 * Run the daemon and handle unix signals
110 */
111 static void run(private_daemon_t *this)
112 {
113 /* reselect signals for this thread */
114 sigemptyset(&(this->signal_set));
115 sigaddset(&(this->signal_set), SIGINT);
116 sigaddset(&(this->signal_set), SIGHUP);
117 sigaddset(&(this->signal_set), SIGTERM);
118 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
119
120 while(TRUE)
121 {
122 int signal_number;
123 int error;
124
125 error = sigwait(&(this->signal_set), &signal_number);
126 if(error)
127 {
128 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
129 return;
130 }
131 switch (signal_number)
132 {
133 case SIGHUP:
134 {
135 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
136 break;
137 }
138 case SIGINT:
139 {
140 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
141 return;
142 }
143 case SIGTERM:
144 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
145 return;
146 default:
147 {
148 DBG1(DBG_DMN, "unknown signal %d received. Ignored", signal_number);
149 break;
150 }
151 }
152 }
153 }
154
155 /**
156 * Clean up all daemon resources
157 */
158 static void destroy(private_daemon_t *this)
159 {
160 /* destruction is a non trivial task, we need to follow
161 * a strict order to prevent threading issues!
162 * Kill active threads first, except the sender, as
163 * the killed IKE_SA want to send delete messages.
164 */
165 /* we don't want to receive anything anymore... */
166 DESTROY_IF(this->public.receiver);
167 /* ignore all incoming user requests */
168 DESTROY_IF(this->public.stroke);
169 /* stop scheduing jobs */
170 DESTROY_IF(this->public.scheduler);
171 /* stop processing jobs */
172 DESTROY_IF(this->public.thread_pool);
173 /* shut down manager with all IKE SAs */
174 DESTROY_IF(this->public.ike_sa_manager);
175 /* all child SAs should be down now, so kill kernel interface */
176 DESTROY_IF(this->public.kernel_interface);
177 /* destroy other infrastructure */
178 DESTROY_IF(this->public.job_queue);
179 DESTROY_IF(this->public.event_queue);
180 DESTROY_IF(this->public.configuration);
181 DESTROY_IF(this->public.credentials);
182 DESTROY_IF(this->public.connections);
183 DESTROY_IF(this->public.policies);
184 sched_yield();
185 /* we hope the sender could send the outstanding deletes, but
186 * we shut down here at any cost */
187 DESTROY_IF(this->public.sender);
188 DESTROY_IF(this->public.socket);
189 /* before destroying bus with its listeners, rehook library logs */
190 dbg = dbg_stderr;
191 DESTROY_IF(this->public.bus);
192 DESTROY_IF(this->public.outlog);
193 DESTROY_IF(this->public.syslog);
194 DESTROY_IF(this->public.authlog);
195 free(this);
196 }
197
198 /**
199 * Enforce daemon shutdown, with a given reason to do so.
200 */
201 static void kill_daemon(private_daemon_t *this, char *reason)
202 {
203 /* we send SIGTERM, so the daemon can cleanly shut down */
204 DBG1(DBG_DMN, "killing daemon: %s", reason);
205 if (this->main_thread_id == pthread_self())
206 {
207 /* initialization failed, terminate daemon */
208 destroy(this);
209 unlink(PID_FILE);
210 exit(-1);
211 }
212 else
213 {
214 DBG1(DBG_DMN, "sending SIGTERM to ourself");
215 raise(SIGTERM);
216 /* thread must die, since he produced a ciritcal failure and can't continue */
217 pthread_exit(NULL);
218 }
219 }
220
221 /**
222 * Initialize the daemon, optional with a strict crl policy
223 */
224 static void initialize(private_daemon_t *this, bool strict, bool syslog,
225 level_t levels[])
226 {
227 credential_store_t* credentials;
228 signal_t signal;
229
230 /* for uncritical pseudo random numbers */
231 srandom(time(NULL) + getpid());
232
233 /* setup bus and it's listeners first to enable log output */
234 this->public.bus = bus_create();
235 this->public.outlog = file_logger_create(stdout);
236 this->public.syslog = sys_logger_create(LOG_DAEMON);
237 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
238 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
239 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
240 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
241 this->public.authlog->set_level(this->public.authlog, SIG_ANY, LEVEL_AUDIT);
242 /* set up hook to log dbg message in library via charons message bus */
243 dbg = dbg_bus;
244
245 /* apply loglevels */
246 for (signal = 0; signal < DBG_MAX; signal++)
247 {
248 if (syslog)
249 {
250 this->public.syslog->set_level(this->public.syslog,
251 signal, levels[signal]);
252 }
253 else
254 {
255 this->public.outlog->set_level(this->public.outlog,
256 signal, levels[signal]);
257 }
258 }
259
260 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
261
262 this->public.configuration = configuration_create();
263 this->public.socket = socket_create(IKEV2_UDP_PORT, IKEV2_NATT_PORT);
264 this->public.ike_sa_manager = ike_sa_manager_create();
265 this->public.job_queue = job_queue_create();
266 this->public.event_queue = event_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 /* initialize fetcher_t class */
272 fetcher_initialize();
273
274 /* load secrets, ca certificates and crls */
275 credentials = this->public.credentials;
276 credentials->load_ca_certificates(credentials);
277 credentials->load_ocsp_certificates(credentials);
278 credentials->load_crls(credentials);
279 credentials->load_secrets(credentials);
280
281 /* start building threads, we are multi-threaded NOW */
282 this->public.stroke = stroke_create();
283 this->public.sender = sender_create();
284 this->public.receiver = receiver_create();
285 this->public.scheduler = scheduler_create();
286 this->public.kernel_interface = kernel_interface_create();
287 this->public.thread_pool = thread_pool_create(NUMBER_OF_WORKING_THREADS);
288 }
289
290 /**
291 * Handle SIGSEGV/SIGILL signals raised by threads
292 */
293 void signal_handler(int signal)
294 {
295 #ifdef HAVE_BACKTRACE
296 void *array[20];
297 size_t size;
298 char **strings;
299 size_t i;
300
301 size = backtrace(array, 20);
302 strings = backtrace_symbols(array, size);
303
304 DBG1(DBG_DMN, "thread %u received %s. Dumping %d frames from stack:",
305 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
306
307 for (i = 0; i < size; i++)
308 {
309 DBG1(DBG_DMN, " %s", strings[i]);
310 }
311 free (strings);
312 #else /* !HAVE_BACKTRACE */
313 DBG1(DBG_DMN, "thread %u received %s",
314 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
315 #endif /* HAVE_BACKTRACE */
316 DBG1(DBG_DMN, "killing ourself hard after SIGSEGV");
317 raise(SIGKILL);
318 }
319
320 /**
321 * Create the daemon.
322 */
323 private_daemon_t *daemon_create(void)
324 {
325 private_daemon_t *this = malloc_thing(private_daemon_t);
326 struct sigaction action;
327
328 /* assign methods */
329 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
330
331 /* NULL members for clean destruction */
332 this->public.socket = NULL;
333 this->public.ike_sa_manager = NULL;
334 this->public.job_queue = NULL;
335 this->public.event_queue = NULL;
336 this->public.configuration = NULL;
337 this->public.credentials = NULL;
338 this->public.connections = NULL;
339 this->public.policies = NULL;
340 this->public.sender= NULL;
341 this->public.receiver = NULL;
342 this->public.scheduler = NULL;
343 this->public.kernel_interface = NULL;
344 this->public.thread_pool = NULL;
345 this->public.stroke = NULL;
346 this->public.bus = NULL;
347 this->public.outlog = NULL;
348 this->public.syslog = NULL;
349 this->public.authlog = NULL;
350
351 this->main_thread_id = pthread_self();
352
353 /* setup signal handling for all threads */
354 sigemptyset(&(this->signal_set));
355 sigaddset(&(this->signal_set), SIGSEGV);
356 sigaddset(&(this->signal_set), SIGINT);
357 sigaddset(&(this->signal_set), SIGHUP);
358 sigaddset(&(this->signal_set), SIGTERM);
359 pthread_sigmask(SIG_BLOCK, &(this->signal_set), 0);
360
361 /* setup SIGSEGV handler for all threads */
362 action.sa_handler = signal_handler;
363 action.sa_mask = this->signal_set;
364 action.sa_flags = 0;
365 sigaction(SIGSEGV, &action, NULL);
366 sigaction(SIGILL, &action, NULL);
367 return this;
368 }
369
370 /**
371 * print command line usage and exit
372 */
373 static void usage(const char *msg)
374 {
375 if (msg != NULL && *msg != '\0')
376 {
377 fprintf(stderr, "%s\n", msg);
378 }
379 fprintf(stderr, "Usage: charon\n"
380 " [--help]\n"
381 " [--version]\n"
382 " [--strictcrlpolicy]\n"
383 " [--cachecrls]\n"
384 " [--crlcheckinterval <interval>]\n"
385 " [--eapdir <dir>]\n"
386 " [--use-syslog]\n"
387 " [--debug-<type> <level>]\n"
388 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
389 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
390 " 2 = controlmore, 3 = raw, 4 = private)\n"
391 "\n"
392 );
393 exit(msg == NULL? 0 : 1);
394 }
395
396 /**
397 * Main function, manages the daemon.
398 */
399 int main(int argc, char *argv[])
400 {
401 u_int crl_check_interval = 0;
402 bool strict_crl_policy = FALSE;
403 bool cache_crls = FALSE;
404 bool use_syslog = FALSE;
405 char *eapdir = IPSEC_EAPDIR;
406
407 private_daemon_t *private_charon;
408 FILE *pid_file;
409 struct stat stb;
410 linked_list_t *list;
411 host_t *host;
412 level_t levels[DBG_MAX];
413 int signal;
414
415 /* use CTRL loglevel for default */
416 for (signal = 0; signal < DBG_MAX; signal++)
417 {
418 levels[signal] = LEVEL_CTRL;
419 }
420
421 /* handle arguments */
422 for (;;)
423 {
424 struct option long_opts[] = {
425 { "help", no_argument, NULL, 'h' },
426 { "version", no_argument, NULL, 'v' },
427 { "use-syslog", no_argument, NULL, 'l' },
428 { "strictcrlpolicy", no_argument, NULL, 'r' },
429 { "cachecrls", no_argument, NULL, 'C' },
430 { "crlcheckinterval", required_argument, NULL, 'x' },
431 { "eapdir", required_argument, NULL, 'e' },
432 /* TODO: handle "debug-all" */
433 { "debug-dmn", required_argument, &signal, DBG_DMN },
434 { "debug-mgr", required_argument, &signal, DBG_MGR },
435 { "debug-ike", required_argument, &signal, DBG_IKE },
436 { "debug-chd", required_argument, &signal, DBG_CHD },
437 { "debug-job", required_argument, &signal, DBG_JOB },
438 { "debug-cfg", required_argument, &signal, DBG_CFG },
439 { "debug-knl", required_argument, &signal, DBG_KNL },
440 { "debug-net", required_argument, &signal, DBG_NET },
441 { "debug-enc", required_argument, &signal, DBG_ENC },
442 { "debug-lib", required_argument, &signal, DBG_LIB },
443 { 0,0,0,0 }
444 };
445
446 int c = getopt_long(argc, argv, "", long_opts, NULL);
447 switch (c)
448 {
449 case EOF:
450 break;
451 case 'h':
452 usage(NULL);
453 break;
454 case 'v':
455 printf("Linux strongSwan %s\n", VERSION);
456 exit(0);
457 case 'l':
458 use_syslog = TRUE;
459 continue;
460 case 'r':
461 strict_crl_policy = TRUE;
462 continue;
463 case 'C':
464 cache_crls = TRUE;
465 continue;
466 case 'x':
467 crl_check_interval = atoi(optarg);
468 continue;
469 case 'e':
470 eapdir = optarg;
471 continue;
472 case 0:
473 /* option is in signal */
474 levels[signal] = atoi(optarg);
475 continue;
476 default:
477 usage("");
478 break;
479 }
480 break;
481 }
482
483 private_charon = daemon_create();
484 charon = (daemon_t*)private_charon;
485
486 /* initialize daemon */
487 initialize(private_charon, strict_crl_policy, use_syslog, levels);
488
489 /* load pluggable EAP modules */
490 eap_method_load(eapdir);
491
492 /* set cache_crls and crl_check_interval options */
493 ca_info_set_options(cache_crls, crl_check_interval);
494
495 /* check/setup PID file */
496 if (stat(PID_FILE, &stb) == 0)
497 {
498 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
499 destroy(private_charon);
500 exit(-1);
501 }
502 pid_file = fopen(PID_FILE, "w");
503 if (pid_file)
504 {
505 fprintf(pid_file, "%d\n", getpid());
506 fclose(pid_file);
507 }
508
509 /* log socket info */
510 list = charon->kernel_interface->create_address_list(charon->kernel_interface);
511 DBG1(DBG_NET, "listening on %d addresses:", list->get_count(list));
512 while (list->remove_first(list, (void**)&host) == SUCCESS)
513 {
514 DBG1(DBG_NET, " %H", host);
515 host->destroy(host);
516 }
517 list->destroy(list);
518
519 /* run daemon */
520 run(private_charon);
521
522 eap_method_unload();
523 fetcher_finalize();
524 /* normal termination, cleanup and exit */
525 destroy(private_charon);
526 unlink(PID_FILE);
527
528 return 0;
529 }