updated API doc for socket.h
[strongswan.git] / src / charon / daemon.c
1 /*
2 * Copyright (C) 2006-2007 Tobias Brunner
3 * Copyright (C) 2006 Daniel Roethlisberger
4 * Copyright (C) 2005-2008 Martin Willi
5 * Copyright (C) 2005 Jan Hutter
6 * Hochschule fuer Technik Rapperswil
7 *
8 * This program is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation; either version 2 of the License, or (at your
11 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 * for more details.
17 */
18
19 #include <stdio.h>
20 #include <sys/prctl.h>
21 #include <signal.h>
22 #include <pthread.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26 #include <time.h>
27 #include <string.h>
28 #include <getopt.h>
29 #include <errno.h>
30 #include <pwd.h>
31 #include <grp.h>
32 #ifdef CAPABILITIES
33 #include <sys/capability.h>
34 #endif /* CAPABILITIES */
35
36 #include "daemon.h"
37
38 #include <library.h>
39 #include <utils/backtrace.h>
40 #include <config/traffic_selector.h>
41 #include <config/proposal.h>
42
43 #ifdef INTEGRITY_TEST
44 #include <fips/fips.h>
45 #include <fips/fips_signature.h>
46 #endif /* INTEGRITY_TEST */
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 #ifdef CAPABILITIES
70 /**
71 * capabilities to keep
72 */
73 cap_t caps;
74 #endif /* CAPABILITIES */
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->vlog(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 if (level <= 1)
107 {
108 va_start(args, fmt);
109 fprintf(stderr, "00[LIB] ");
110 vfprintf(stderr, fmt, args);
111 fprintf(stderr, "\n");
112 va_end(args);
113 }
114 }
115
116 /**
117 * Run the daemon and handle unix signals
118 */
119 static void run(private_daemon_t *this)
120 {
121 sigset_t set;
122
123 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
124 sigemptyset(&set);
125 sigaddset(&set, SIGINT);
126 sigaddset(&set, SIGHUP);
127 sigaddset(&set, SIGTERM);
128
129 while (TRUE)
130 {
131 int sig;
132 int error;
133
134 error = sigwait(&set, &sig);
135 if (error)
136 {
137 DBG1(DBG_DMN, "error %d while waiting for a signal", error);
138 return;
139 }
140 switch (sig)
141 {
142 case SIGHUP:
143 {
144 DBG1(DBG_DMN, "signal of type SIGHUP received. Ignored");
145 break;
146 }
147 case SIGINT:
148 {
149 DBG1(DBG_DMN, "signal of type SIGINT received. Shutting down");
150 return;
151 }
152 case SIGTERM:
153 {
154 DBG1(DBG_DMN, "signal of type SIGTERM received. Shutting down");
155 return;
156 }
157 default:
158 {
159 DBG1(DBG_DMN, "unknown signal %d received. Ignored", sig);
160 break;
161 }
162 }
163 }
164 }
165
166 /**
167 * Clean up all daemon resources
168 */
169 static void destroy(private_daemon_t *this)
170 {
171 /* terminate all idle threads */
172 if (this->public.processor)
173 {
174 this->public.processor->set_threads(this->public.processor, 0);
175 }
176 /* close all IKE_SAs */
177 if (this->public.ike_sa_manager)
178 {
179 this->public.ike_sa_manager->flush(this->public.ike_sa_manager);
180 }
181 /* unload plugins to release threads */
182 lib->plugins->unload(lib->plugins);
183 #ifdef CAPABILITIES
184 cap_free(this->caps);
185 #endif /* CAPABILITIES */
186 DESTROY_IF(this->public.ike_sa_manager);
187 DESTROY_IF(this->public.kernel_interface);
188 DESTROY_IF(this->public.scheduler);
189 DESTROY_IF(this->public.controller);
190 DESTROY_IF(this->public.eap);
191 DESTROY_IF(this->public.sim);
192 #ifdef ME
193 DESTROY_IF(this->public.connect_manager);
194 DESTROY_IF(this->public.mediation_manager);
195 #endif /* ME */
196 DESTROY_IF(this->public.backends);
197 DESTROY_IF(this->public.attributes);
198 DESTROY_IF(this->public.credentials);
199 DESTROY_IF(this->public.sender);
200 DESTROY_IF(this->public.receiver);
201 DESTROY_IF(this->public.socket);
202 /* wait until all threads are gone */
203 DESTROY_IF(this->public.processor);
204
205 /* rehook library logging, shutdown logging */
206 dbg = dbg_stderr;
207 DESTROY_IF(this->public.bus);
208 this->public.file_loggers->destroy_offset(this->public.file_loggers,
209 offsetof(file_logger_t, destroy));
210 this->public.sys_loggers->destroy_offset(this->public.sys_loggers,
211 offsetof(sys_logger_t, destroy));
212 free(this);
213 }
214
215 /**
216 * Enforce daemon shutdown, with a given reason to do so.
217 */
218 static void kill_daemon(private_daemon_t *this, char *reason)
219 {
220 /* we send SIGTERM, so the daemon can cleanly shut down */
221 if (this->public.bus)
222 {
223 DBG1(DBG_DMN, "killing daemon: %s", reason);
224 }
225 else
226 {
227 fprintf(stderr, "killing daemon: %s\n", reason);
228 }
229 if (this->main_thread_id == pthread_self())
230 {
231 /* initialization failed, terminate daemon */
232 unlink(PID_FILE);
233 exit(-1);
234 }
235 else
236 {
237 DBG1(DBG_DMN, "sending SIGTERM to ourself");
238 raise(SIGTERM);
239 /* thread must die, since he produced a ciritcal failure and can't continue */
240 pthread_exit(NULL);
241 }
242 }
243
244 /**
245 * drop daemon capabilities
246 */
247 static void drop_capabilities(private_daemon_t *this)
248 {
249 prctl(PR_SET_KEEPCAPS, 1);
250
251 if (setgid(charon->gid) != 0)
252 {
253 kill_daemon(this, "change to unprivileged group failed");
254 }
255 if (setuid(charon->uid) != 0)
256 {
257 kill_daemon(this, "change to unprivileged user failed");
258 }
259
260 #ifdef CAPABILITIES
261 if (cap_set_proc(this->caps) != 0)
262 {
263 kill_daemon(this, "unable to drop daemon capabilities");
264 }
265 #endif /* CAPABILITIES */
266 }
267
268 /**
269 * Implementation of daemon_t.keep_cap
270 */
271 static void keep_cap(private_daemon_t *this, u_int cap)
272 {
273 #ifdef CAPABILITIES
274 cap_set_flag(this->caps, CAP_EFFECTIVE, 1, &cap, CAP_SET);
275 cap_set_flag(this->caps, CAP_INHERITABLE, 1, &cap, CAP_SET);
276 cap_set_flag(this->caps, CAP_PERMITTED, 1, &cap, CAP_SET);
277 #endif /* CAPABILITIES */
278 }
279
280 /**
281 * lookup UID and GID
282 */
283 static void lookup_uid_gid(private_daemon_t *this)
284 {
285 #ifdef IPSEC_USER
286 {
287 char buf[1024];
288 struct passwd passwd, *pwp;
289
290 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
291 pwp == NULL)
292 {
293 kill_daemon(this, "resolving user '"IPSEC_USER"' failed");
294 }
295 charon->uid = pwp->pw_uid;
296 }
297 #endif
298 #ifdef IPSEC_GROUP
299 {
300 char buf[1024];
301 struct group group, *grp;
302
303 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
304 grp == NULL)
305 {
306 kill_daemon(this, "reslvoing group '"IPSEC_GROUP"' failed");
307 }
308 charon->gid = grp->gr_gid;
309 }
310 #endif
311 }
312
313 /**
314 * Log loaded plugins
315 */
316 static void print_plugins()
317 {
318 char buf[512], *plugin;
319 int len = 0;
320 enumerator_t *enumerator;
321
322 enumerator = lib->plugins->create_plugin_enumerator(lib->plugins);
323 while (len < sizeof(buf) && enumerator->enumerate(enumerator, &plugin))
324 {
325 len += snprintf(&buf[len], sizeof(buf)-len, "%s ", plugin);
326 }
327 enumerator->destroy(enumerator);
328 DBG1(DBG_DMN, "loaded plugins: %s", buf);
329 }
330
331 /**
332 * Initialize logging
333 */
334 static void initialize_loggers(private_daemon_t *this, bool use_stderr,
335 level_t levels[])
336 {
337 sys_logger_t *sys_logger;
338 file_logger_t *file_logger;
339 enumerator_t *enumerator;
340 char *facility, *filename;
341 int loggers_defined = 0;
342 debug_t group;
343 level_t def;
344 bool append;
345 FILE *file;
346
347 /* setup sysloggers */
348 enumerator = lib->settings->create_section_enumerator(lib->settings,
349 "charon.syslog");
350 while (enumerator->enumerate(enumerator, &facility))
351 {
352 loggers_defined++;
353 if (streq(facility, "daemon"))
354 {
355 sys_logger = sys_logger_create(LOG_DAEMON);
356 }
357 else if (streq(facility, "auth"))
358 {
359 sys_logger = sys_logger_create(LOG_AUTHPRIV);
360 }
361 else
362 {
363 continue;
364 }
365 def = lib->settings->get_int(lib->settings,
366 "charon.syslog.%s.default", 1, facility);
367 for (group = 0; group < DBG_MAX; group++)
368 {
369 sys_logger->set_level(sys_logger, group,
370 lib->settings->get_int(lib->settings,
371 "charon.syslog.%s.%N", def,
372 facility, debug_lower_names, group));
373 }
374 this->public.sys_loggers->insert_last(this->public.sys_loggers,
375 sys_logger);
376 this->public.bus->add_listener(this->public.bus, &sys_logger->listener);
377 }
378 enumerator->destroy(enumerator);
379
380 /* and file loggers */
381 enumerator = lib->settings->create_section_enumerator(lib->settings,
382 "charon.filelog");
383 while (enumerator->enumerate(enumerator, &filename))
384 {
385 loggers_defined++;
386 if (streq(filename, "stderr"))
387 {
388 file = stderr;
389 }
390 else if (streq(filename, "stdout"))
391 {
392 file = stdout;
393 }
394 else
395 {
396 append = lib->settings->get_bool(lib->settings,
397 "charon.filelog.%s.append", TRUE, filename);
398 file = fopen(filename, append ? "a" : "w");
399 if (file == NULL)
400 {
401 DBG1(DBG_DMN, "opening file %s for logging failed: %s",
402 filename, strerror(errno));
403 continue;
404 }
405 }
406 file_logger = file_logger_create(file);
407 def = lib->settings->get_int(lib->settings,
408 "charon.filelog.%s.default", 1, filename);
409 for (group = 0; group < DBG_MAX; group++)
410 {
411 file_logger->set_level(file_logger, group,
412 lib->settings->get_int(lib->settings,
413 "charon.filelog.%s.%N", def,
414 filename, debug_lower_names, group));
415 }
416 this->public.file_loggers->insert_last(this->public.file_loggers,
417 file_logger);
418 this->public.bus->add_listener(this->public.bus, &file_logger->listener);
419
420 }
421 enumerator->destroy(enumerator);
422
423 /* setup legacy style default loggers provided via command-line */
424 if (!loggers_defined)
425 {
426 file_logger = file_logger_create(stdout);
427 sys_logger = sys_logger_create(LOG_DAEMON);
428 this->public.bus->add_listener(this->public.bus, &file_logger->listener);
429 this->public.bus->add_listener(this->public.bus, &sys_logger->listener);
430 this->public.file_loggers->insert_last(this->public.file_loggers,
431 file_logger);
432 this->public.sys_loggers->insert_last(this->public.sys_loggers,
433 sys_logger);
434 for (group = 0; group < DBG_MAX; group++)
435 {
436 sys_logger->set_level(sys_logger, group, levels[group]);
437 if (use_stderr)
438 {
439 file_logger->set_level(file_logger, group, levels[group]);
440 }
441 }
442 }
443 }
444
445 /**
446 * Initialize the daemon
447 */
448 static bool initialize(private_daemon_t *this, bool syslog, level_t levels[])
449 {
450 /* for uncritical pseudo random numbers */
451 srandom(time(NULL) + getpid());
452
453 /* setup bus and it's listeners first to enable log output */
454 this->public.bus = bus_create();
455 /* set up hook to log dbg message in library via charons message bus */
456 dbg = dbg_bus;
457
458 initialize_loggers(this, !syslog, levels);
459
460 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
461
462 /* load secrets, ca certificates and crls */
463 this->public.processor = processor_create();
464 this->public.scheduler = scheduler_create();
465 this->public.credentials = credential_manager_create();
466 this->public.controller = controller_create();
467 this->public.eap = eap_manager_create();
468 this->public.sim = sim_manager_create();
469 this->public.backends = backend_manager_create();
470 this->public.attributes = attribute_manager_create();
471 this->public.kernel_interface = kernel_interface_create();
472 this->public.socket = socket_create();
473
474 /* load plugins, further infrastructure may need it */
475 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
476 lib->settings->get_str(lib->settings, "charon.load", PLUGINS));
477
478 print_plugins();
479
480 /* create the kernel interfaces */
481 this->public.kernel_interface->create_interfaces(this->public.kernel_interface);
482
483 #ifdef INTEGRITY_TEST
484 DBG1(DBG_DMN, "integrity test of libstrongswan code");
485 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
486 {
487 DBG1(DBG_DMN, " integrity test passed");
488 }
489 else
490 {
491 DBG1(DBG_DMN, " integrity test failed");
492 return FALSE;
493 }
494 #endif /* INTEGRITY_TEST */
495
496 this->public.ike_sa_manager = ike_sa_manager_create();
497 if (this->public.ike_sa_manager == NULL)
498 {
499 return FALSE;
500 }
501 this->public.sender = sender_create();
502 this->public.receiver = receiver_create();
503 if (this->public.receiver == NULL)
504 {
505 return FALSE;
506 }
507
508 #ifdef ME
509 this->public.connect_manager = connect_manager_create();
510 if (this->public.connect_manager == NULL)
511 {
512 return FALSE;
513 }
514 this->public.mediation_manager = mediation_manager_create();
515 #endif /* ME */
516
517 return TRUE;
518 }
519
520 /**
521 * Handle SIGSEGV/SIGILL signals raised by threads
522 */
523 static void segv_handler(int signal)
524 {
525 backtrace_t *backtrace;
526
527 DBG1(DBG_DMN, "thread %u received %d", pthread_self(), signal);
528 backtrace = backtrace_create(2);
529 backtrace->log(backtrace, stderr);
530 backtrace->destroy(backtrace);
531
532 DBG1(DBG_DMN, "killing ourself, received critical signal");
533 raise(SIGKILL);
534 }
535
536 /**
537 * Create the daemon.
538 */
539 private_daemon_t *daemon_create(void)
540 {
541 struct sigaction action;
542 private_daemon_t *this = malloc_thing(private_daemon_t);
543
544 /* assign methods */
545 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
546 this->public.keep_cap = (void(*)(daemon_t*, u_int cap))keep_cap;
547
548 /* NULL members for clean destruction */
549 this->public.socket = NULL;
550 this->public.ike_sa_manager = NULL;
551 this->public.credentials = NULL;
552 this->public.backends = NULL;
553 this->public.attributes = NULL;
554 this->public.sender= NULL;
555 this->public.receiver = NULL;
556 this->public.scheduler = NULL;
557 this->public.kernel_interface = NULL;
558 this->public.processor = NULL;
559 this->public.controller = NULL;
560 this->public.eap = NULL;
561 this->public.sim = NULL;
562 this->public.bus = NULL;
563 this->public.file_loggers = linked_list_create();
564 this->public.sys_loggers = linked_list_create();
565 #ifdef ME
566 this->public.connect_manager = NULL;
567 this->public.mediation_manager = NULL;
568 #endif /* ME */
569 this->public.uid = 0;
570 this->public.gid = 0;
571
572 this->main_thread_id = pthread_self();
573 #ifdef CAPABILITIES
574 this->caps = cap_init();
575 keep_cap(this, CAP_NET_ADMIN);
576 if (lib->leak_detective)
577 {
578 keep_cap(this, CAP_SYS_NICE);
579 }
580 #endif /* CAPABILITIES */
581
582 /* add handler for SEGV and ILL,
583 * add handler for USR1 (cancellation).
584 * INT, TERM and HUP are handled by sigwait() in run() */
585 action.sa_handler = segv_handler;
586 action.sa_flags = 0;
587 sigemptyset(&action.sa_mask);
588 sigaddset(&action.sa_mask, SIGINT);
589 sigaddset(&action.sa_mask, SIGTERM);
590 sigaddset(&action.sa_mask, SIGHUP);
591 sigaction(SIGSEGV, &action, NULL);
592 sigaction(SIGILL, &action, NULL);
593 sigaction(SIGBUS, &action, NULL);
594 action.sa_handler = SIG_IGN;
595 sigaction(SIGPIPE, &action, NULL);
596
597 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
598
599 return this;
600 }
601
602 /**
603 * print command line usage and exit
604 */
605 static void usage(const char *msg)
606 {
607 if (msg != NULL && *msg != '\0')
608 {
609 fprintf(stderr, "%s\n", msg);
610 }
611 fprintf(stderr, "Usage: charon\n"
612 " [--help]\n"
613 " [--version]\n"
614 " [--use-syslog]\n"
615 " [--debug-<type> <level>]\n"
616 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
617 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
618 " 2 = controlmore, 3 = raw, 4 = private)\n"
619 "\n"
620 );
621 exit(msg == NULL? 0 : 1);
622 }
623
624 /**
625 * Main function, manages the daemon.
626 */
627 int main(int argc, char *argv[])
628 {
629 bool use_syslog = FALSE;
630
631 private_daemon_t *private_charon;
632 FILE *pid_file;
633 struct stat stb;
634 level_t levels[DBG_MAX];
635 int group;
636
637 /* logging for library during initialization, as we have no bus yet */
638 dbg = dbg_stderr;
639
640 /* initialize library */
641 library_init(STRONGSWAN_CONF);
642 lib->printf_hook->add_handler(lib->printf_hook, 'R',
643 traffic_selector_get_printf_hooks());
644 lib->printf_hook->add_handler(lib->printf_hook, 'P',
645 proposal_get_printf_hooks());
646 private_charon = daemon_create();
647 charon = (daemon_t*)private_charon;
648
649 lookup_uid_gid(private_charon);
650
651 /* use CTRL loglevel for default */
652 for (group = 0; group < DBG_MAX; group++)
653 {
654 levels[group] = LEVEL_CTRL;
655 }
656
657 /* handle arguments */
658 for (;;)
659 {
660 struct option long_opts[] = {
661 { "help", no_argument, NULL, 'h' },
662 { "version", no_argument, NULL, 'v' },
663 { "use-syslog", no_argument, NULL, 'l' },
664 /* TODO: handle "debug-all" */
665 { "debug-dmn", required_argument, &group, DBG_DMN },
666 { "debug-mgr", required_argument, &group, DBG_MGR },
667 { "debug-ike", required_argument, &group, DBG_IKE },
668 { "debug-chd", required_argument, &group, DBG_CHD },
669 { "debug-job", required_argument, &group, DBG_JOB },
670 { "debug-cfg", required_argument, &group, DBG_CFG },
671 { "debug-knl", required_argument, &group, DBG_KNL },
672 { "debug-net", required_argument, &group, DBG_NET },
673 { "debug-enc", required_argument, &group, DBG_ENC },
674 { "debug-lib", required_argument, &group, DBG_LIB },
675 { 0,0,0,0 }
676 };
677
678 int c = getopt_long(argc, argv, "", long_opts, NULL);
679 switch (c)
680 {
681 case EOF:
682 break;
683 case 'h':
684 usage(NULL);
685 break;
686 case 'v':
687 printf("Linux strongSwan %s\n", VERSION);
688 exit(0);
689 case 'l':
690 use_syslog = TRUE;
691 continue;
692 case 0:
693 /* option is in group */
694 levels[group] = atoi(optarg);
695 continue;
696 default:
697 usage("");
698 break;
699 }
700 break;
701 }
702
703 /* initialize daemon */
704 if (!initialize(private_charon, use_syslog, levels))
705 {
706 DBG1(DBG_DMN, "initialization failed - aborting charon");
707 destroy(private_charon);
708 exit(-1);
709 }
710
711 /* check/setup PID file */
712 if (stat(PID_FILE, &stb) == 0)
713 {
714 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
715 destroy(private_charon);
716 exit(-1);
717 }
718 pid_file = fopen(PID_FILE, "w");
719 if (pid_file)
720 {
721 fprintf(pid_file, "%d\n", getpid());
722 ignore_result(fchown(fileno(pid_file), charon->uid, charon->gid));
723 fclose(pid_file);
724 }
725
726 /* drop the capabilities we won't need */
727 drop_capabilities(private_charon);
728
729 /* start the engine, go multithreaded */
730 charon->processor->set_threads(charon->processor,
731 lib->settings->get_int(lib->settings, "charon.threads",
732 DEFAULT_THREADS));
733
734 /* run daemon */
735 run(private_charon);
736
737 /* normal termination, cleanup and exit */
738 destroy(private_charon);
739 unlink(PID_FILE);
740
741 library_deinit();
742
743 return 0;
744 }
745