documentation fixes and updates
[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 sigset_t set;
119
120 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
121 sigemptyset(&set);
122 sigaddset(&set, SIGINT);
123 sigaddset(&set, SIGHUP);
124 sigaddset(&set, SIGTERM);
125
126 while (TRUE)
127 {
128 int sig;
129 int error;
130
131 error = sigwait(&set, &sig);
132 if (error)
133 {
134 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
135 return;
136 }
137 switch (sig)
138 {
139 case SIGHUP:
140 {
141 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
142 break;
143 }
144 case SIGINT:
145 {
146 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
147 return;
148 }
149 case SIGTERM:
150 {
151 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
152 return;
153 }
154 default:
155 {
156 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
157 break;
158 }
159 }
160 }
161 }
162
163 /**
164 * Clean up all daemon resources
165 */
166 static void destroy(private_daemon_t *this)
167 {
168 /* terminate all idle threads */
169 this->public.processor->set_threads(this->public.processor, 0);
170 /* close all IKE_SAs */
171 DESTROY_IF(this->public.ike_sa_manager);
172 DESTROY_IF(this->public.scheduler);
173 DESTROY_IF(this->public.interfaces);
174 DESTROY_IF(this->public.backends);
175 DESTROY_IF(this->public.credentials);
176 DESTROY_IF(this->public.kernel_interface);
177 DESTROY_IF(this->public.sender);
178 DESTROY_IF(this->public.receiver);
179 DESTROY_IF(this->public.socket);
180 /* wait until all threads are gone */
181 DESTROY_IF(this->public.processor);
182
183 /* rehook library logging, shutdown logging */
184 dbg = dbg_stderr;
185 DESTROY_IF(this->public.bus);
186 DESTROY_IF(this->public.outlog);
187 DESTROY_IF(this->public.syslog);
188 DESTROY_IF(this->public.authlog);
189 free(this);
190 }
191
192 /**
193 * Enforce daemon shutdown, with a given reason to do so.
194 */
195 static void kill_daemon(private_daemon_t *this, char *reason)
196 {
197 /* we send SIGTERM, so the daemon can cleanly shut down */
198 DBG1(DBG_DMN, "killing daemon: %s", reason);
199 if (this->main_thread_id == pthread_self())
200 {
201 /* initialization failed, terminate daemon */
202 destroy(this);
203 unlink(PID_FILE);
204 exit(-1);
205 }
206 else
207 {
208 DBG1(DBG_DMN, "sending SIGTERM to ourself");
209 raise(SIGTERM);
210 /* thread must die, since he produced a ciritcal failure and can't continue */
211 pthread_exit(NULL);
212 }
213 }
214
215 /**
216 * drop daemon capabilities
217 */
218 static void drop_capabilities(private_daemon_t *this, bool full)
219 {
220 struct __user_cap_header_struct hdr;
221 struct __user_cap_data_struct data;
222
223 /* CAP_NET_ADMIN is needed to use netlink */
224 u_int32_t keep = (1<<CAP_NET_ADMIN);
225
226 if (full)
227 {
228 # if IPSEC_GID
229 setgid(IPSEC_GID);
230 # endif
231 # if IPSEC_UID
232 setuid(IPSEC_UID);
233 # endif
234 }
235 else
236 {
237 /* CAP_NET_BIND_SERVICE to bind services below port 1024 */
238 keep |= (1<<CAP_NET_BIND_SERVICE);
239 /* CAP_NET_RAW to create RAW sockets */
240 keep |= (1<<CAP_NET_RAW);
241 /* CAP_DAC_READ_SEARCH to read ipsec.secrets */
242 keep |= (1<<CAP_DAC_READ_SEARCH);
243 }
244
245 hdr.version = _LINUX_CAPABILITY_VERSION;
246 hdr.pid = 0;
247 data.effective = data.permitted = keep;
248 data.inheritable = 0;
249
250 if (capset(&hdr, &data))
251 {
252 kill_daemon(this, "unable to drop daemon capabilities");
253 }
254 }
255
256 /**
257 * Initialize the daemon, optional with a strict crl policy
258 */
259 static void initialize(private_daemon_t *this, bool syslog, level_t levels[])
260 {
261 signal_t signal;
262
263 /* for uncritical pseudo random numbers */
264 srandom(time(NULL) + getpid());
265
266 /* setup bus and it's listeners first to enable log output */
267 this->public.bus = bus_create();
268 this->public.outlog = file_logger_create(stdout);
269 this->public.syslog = sys_logger_create(LOG_DAEMON);
270 this->public.authlog = sys_logger_create(LOG_AUTHPRIV);
271 this->public.bus->add_listener(this->public.bus, &this->public.syslog->listener);
272 this->public.bus->add_listener(this->public.bus, &this->public.outlog->listener);
273 this->public.bus->add_listener(this->public.bus, &this->public.authlog->listener);
274 this->public.authlog->set_level(this->public.authlog, SIG_ANY, LEVEL_AUDIT);
275 /* set up hook to log dbg message in library via charons message bus */
276 dbg = dbg_bus;
277
278 /* apply loglevels */
279 for (signal = 0; signal < DBG_MAX; signal++)
280 {
281 this->public.syslog->set_level(this->public.syslog,
282 signal, levels[signal]);
283 if (!syslog)
284 {
285 this->public.outlog->set_level(this->public.outlog,
286 signal, levels[signal]);
287 }
288 }
289
290 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
291
292 this->public.ike_sa_manager = ike_sa_manager_create();
293 this->public.processor = processor_create();
294 this->public.scheduler = scheduler_create();
295
296 /* load secrets, ca certificates and crls */
297 this->public.credentials = (credential_store_t*)local_credential_store_create();
298 this->public.credentials->load_ca_certificates(this->public.credentials);
299 this->public.credentials->load_aa_certificates(this->public.credentials);
300 this->public.credentials->load_attr_certificates(this->public.credentials);
301 this->public.credentials->load_ocsp_certificates(this->public.credentials);
302 this->public.credentials->load_crls(this->public.credentials);
303 this->public.credentials->load_secrets(this->public.credentials);
304
305 this->public.interfaces = interface_manager_create();
306 this->public.backends = backend_manager_create();
307 this->public.kernel_interface = kernel_interface_create();
308 this->public.socket = socket_create(IKEV2_UDP_PORT, IKEV2_NATT_PORT);
309 this->public.sender = sender_create();
310 this->public.receiver = receiver_create();
311
312 }
313
314 /**
315 * Handle SIGSEGV/SIGILL signals raised by threads
316 */
317 static void segv_handler(int signal)
318 {
319 #ifdef HAVE_BACKTRACE
320 void *array[20];
321 size_t size;
322 char **strings;
323 size_t i;
324
325 size = backtrace(array, 20);
326 strings = backtrace_symbols(array, size);
327
328 DBG1(DBG_JOB, "thread %u received %s. Dumping %d frames from stack:",
329 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL", size);
330
331 for (i = 0; i < size; i++)
332 {
333 DBG1(DBG_DMN, " %s", strings[i]);
334 }
335 free (strings);
336 #else /* !HAVE_BACKTRACE */
337 DBG1(DBG_DMN, "thread %u received %s",
338 pthread_self(), signal == SIGSEGV ? "SIGSEGV" : "SIGILL");
339 #endif /* HAVE_BACKTRACE */
340 DBG1(DBG_DMN, "killing ourself, received critical signal");
341 raise(SIGKILL);
342 }
343
344 /**
345 * Create the daemon.
346 */
347 private_daemon_t *daemon_create(void)
348 {
349 struct sigaction action;
350 private_daemon_t *this = malloc_thing(private_daemon_t);
351
352 /* assign methods */
353 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
354
355 /* NULL members for clean destruction */
356 this->public.socket = NULL;
357 this->public.ike_sa_manager = NULL;
358 this->public.credentials = NULL;
359 this->public.backends = NULL;
360 this->public.sender= NULL;
361 this->public.receiver = NULL;
362 this->public.scheduler = NULL;
363 this->public.kernel_interface = NULL;
364 this->public.processor = NULL;
365 this->public.interfaces = NULL;
366 this->public.bus = NULL;
367 this->public.outlog = NULL;
368 this->public.syslog = NULL;
369 this->public.authlog = NULL;
370
371 this->main_thread_id = pthread_self();
372
373 /* add handler for SEGV and ILL,
374 * add handler for USR1 (cancellation).
375 * INT, TERM and HUP are handled by sigwait() in run() */
376 action.sa_handler = segv_handler;
377 action.sa_flags = 0;
378 sigemptyset(&action.sa_mask);
379 sigaddset(&action.sa_mask, SIGINT);
380 sigaddset(&action.sa_mask, SIGTERM);
381 sigaddset(&action.sa_mask, SIGHUP);
382 sigaction(SIGSEGV, &action, NULL);
383 sigaction(SIGILL, &action, NULL);
384 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
385
386 return this;
387 }
388
389 /**
390 * print command line usage and exit
391 */
392 static void usage(const char *msg)
393 {
394 if (msg != NULL && *msg != '\0')
395 {
396 fprintf(stderr, "%s\n", msg);
397 }
398 fprintf(stderr, "Usage: charon\n"
399 " [--help]\n"
400 " [--version]\n"
401 " [--strictcrlpolicy]\n"
402 " [--cachecrls]\n"
403 " [--crlcheckinterval <interval>]\n"
404 " [--eapdir <dir>]\n"
405 " [--use-syslog]\n"
406 " [--debug-<type> <level>]\n"
407 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
408 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
409 " 2 = controlmore, 3 = raw, 4 = private)\n"
410 "\n"
411 );
412 exit(msg == NULL? 0 : 1);
413 }
414
415 /**
416 * Main function, manages the daemon.
417 */
418 int main(int argc, char *argv[])
419 {
420 u_int crl_check_interval = 0;
421 strict_t strict_crl_policy = STRICT_NO;
422 bool cache_crls = FALSE;
423 bool use_syslog = FALSE;
424 char *eapdir = IPSEC_EAPDIR;
425
426 private_daemon_t *private_charon;
427 FILE *pid_file;
428 struct stat stb;
429 linked_list_t *list;
430 host_t *host;
431 level_t levels[DBG_MAX];
432 int signal;
433
434 private_charon = daemon_create();
435 charon = (daemon_t*)private_charon;
436
437 /* drop the capabilities we won't need for initialization */
438 prctl(PR_SET_KEEPCAPS, 1);
439 drop_capabilities(private_charon, FALSE);
440
441 /* use CTRL loglevel for default */
442 for (signal = 0; signal < DBG_MAX; signal++)
443 {
444 levels[signal] = LEVEL_CTRL;
445 }
446
447 /* handle arguments */
448 for (;;)
449 {
450 struct option long_opts[] = {
451 { "help", no_argument, NULL, 'h' },
452 { "version", no_argument, NULL, 'v' },
453 { "use-syslog", no_argument, NULL, 'l' },
454 { "strictcrlpolicy", required_argument, NULL, 'r' },
455 { "cachecrls", no_argument, NULL, 'C' },
456 { "crlcheckinterval", required_argument, NULL, 'x' },
457 { "eapdir", required_argument, NULL, 'e' },
458 /* TODO: handle "debug-all" */
459 { "debug-dmn", required_argument, &signal, DBG_DMN },
460 { "debug-mgr", required_argument, &signal, DBG_MGR },
461 { "debug-ike", required_argument, &signal, DBG_IKE },
462 { "debug-chd", required_argument, &signal, DBG_CHD },
463 { "debug-job", required_argument, &signal, DBG_JOB },
464 { "debug-cfg", required_argument, &signal, DBG_CFG },
465 { "debug-knl", required_argument, &signal, DBG_KNL },
466 { "debug-net", required_argument, &signal, DBG_NET },
467 { "debug-enc", required_argument, &signal, DBG_ENC },
468 { "debug-lib", required_argument, &signal, DBG_LIB },
469 { 0,0,0,0 }
470 };
471
472 int c = getopt_long(argc, argv, "", long_opts, NULL);
473 switch (c)
474 {
475 case EOF:
476 break;
477 case 'h':
478 usage(NULL);
479 break;
480 case 'v':
481 printf("Linux strongSwan %s\n", VERSION);
482 exit(0);
483 case 'l':
484 use_syslog = TRUE;
485 continue;
486 case 'r':
487 strict_crl_policy = atoi(optarg);
488 continue;
489 case 'C':
490 cache_crls = TRUE;
491 continue;
492 case 'x':
493 crl_check_interval = atoi(optarg);
494 continue;
495 case 'e':
496 eapdir = optarg;
497 continue;
498 case 0:
499 /* option is in signal */
500 levels[signal] = atoi(optarg);
501 continue;
502 default:
503 usage("");
504 break;
505 }
506 break;
507 }
508
509 /* initialize daemon */
510 initialize(private_charon, use_syslog, levels);
511 /* initialize fetcher_t class */
512 fetcher_initialize();
513 /* load pluggable EAP modules */
514 eap_method_load(eapdir);
515
516 /* set strict_crl_policy, cache_crls and crl_check_interval options */
517 ca_info_set_options(strict_crl_policy, cache_crls, crl_check_interval);
518
519 /* check/setup PID file */
520 if (stat(PID_FILE, &stb) == 0)
521 {
522 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
523 destroy(private_charon);
524 exit(-1);
525 }
526 pid_file = fopen(PID_FILE, "w");
527 if (pid_file)
528 {
529 fprintf(pid_file, "%d\n", getpid());
530 fclose(pid_file);
531 }
532
533 /* log socket info */
534 list = charon->kernel_interface->create_address_list(charon->kernel_interface);
535 DBG1(DBG_NET, "listening on %d addresses:", list->get_count(list));
536 while (list->remove_first(list, (void**)&host) == SUCCESS)
537 {
538 DBG1(DBG_NET, " %H", host);
539 host->destroy(host);
540 }
541 list->destroy(list);
542
543 /* drop additional capabilites (bind & root) */
544 drop_capabilities(private_charon, TRUE);
545
546 /* start the engine, go multithreaded */
547 charon->processor->set_threads(charon->processor, WORKER_THREADS);
548
549 /* run daemon */
550 run(private_charon);
551
552 eap_method_unload();
553 fetcher_finalize();
554 /* normal termination, cleanup and exit */
555 destroy(private_charon);
556 unlink(PID_FILE);
557
558 return 0;
559 }
560