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