properly initialize buffer when printing loaded plugins.
[strongswan.git] / src / charon / daemon.c
1 /*
2 * Copyright (C) 2006-2009 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 #ifdef HAVE_PRCTL
21 #include <sys/prctl.h>
22 #endif
23 #include <signal.h>
24 #include <pthread.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28 #include <time.h>
29 #include <string.h>
30 #include <getopt.h>
31 #include <errno.h>
32 #include <pwd.h>
33 #include <grp.h>
34 #ifdef CAPABILITIES
35 #include <sys/capability.h>
36 #endif /* CAPABILITIES */
37
38 #include "daemon.h"
39
40 #include <library.h>
41 #include <utils/backtrace.h>
42 #include <config/traffic_selector.h>
43 #include <config/proposal.h>
44
45 #ifdef INTEGRITY_TEST
46 #include <fips/fips.h>
47 #include <fips/fips_signature.h>
48 #endif /* INTEGRITY_TEST */
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 #ifdef CAPABILITIES
67 /**
68 * capabilities to keep
69 */
70 cap_t caps;
71 #endif /* CAPABILITIES */
72 };
73
74 /**
75 * One and only instance of the daemon.
76 */
77 daemon_t *charon;
78
79 /**
80 * hook in library for debugging messages
81 */
82 extern void (*dbg) (int level, char *fmt, ...);
83
84 /**
85 * Logging hook for library logs, spreads debug message over bus
86 */
87 static void dbg_bus(int level, char *fmt, ...)
88 {
89 va_list args;
90
91 va_start(args, fmt);
92 charon->bus->vlog(charon->bus, DBG_LIB, level, fmt, args);
93 va_end(args);
94 }
95
96 /**
97 * Logging hook for library logs, using stderr output
98 */
99 static void dbg_stderr(int level, char *fmt, ...)
100 {
101 va_list args;
102
103 if (level <= 1)
104 {
105 va_start(args, fmt);
106 fprintf(stderr, "00[LIB] ");
107 vfprintf(stderr, fmt, args);
108 fprintf(stderr, "\n");
109 va_end(args);
110 }
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 if (this->public.processor)
170 {
171 this->public.processor->set_threads(this->public.processor, 0);
172 }
173 /* close all IKE_SAs */
174 if (this->public.ike_sa_manager)
175 {
176 this->public.ike_sa_manager->flush(this->public.ike_sa_manager);
177 }
178 /* unload plugins to release threads */
179 lib->plugins->unload(lib->plugins);
180 #ifdef CAPABILITIES
181 cap_free(this->caps);
182 #endif /* CAPABILITIES */
183 DESTROY_IF(this->public.ike_sa_manager);
184 DESTROY_IF(this->public.kernel_interface);
185 DESTROY_IF(this->public.scheduler);
186 DESTROY_IF(this->public.controller);
187 DESTROY_IF(this->public.eap);
188 DESTROY_IF(this->public.sim);
189 #ifdef ME
190 DESTROY_IF(this->public.connect_manager);
191 DESTROY_IF(this->public.mediation_manager);
192 #endif /* ME */
193 DESTROY_IF(this->public.backends);
194 DESTROY_IF(this->public.attributes);
195 DESTROY_IF(this->public.credentials);
196 DESTROY_IF(this->public.sender);
197 DESTROY_IF(this->public.receiver);
198 DESTROY_IF(this->public.socket);
199 /* wait until all threads are gone */
200 DESTROY_IF(this->public.processor);
201
202 /* rehook library logging, shutdown logging */
203 dbg = dbg_stderr;
204 DESTROY_IF(this->public.bus);
205 this->public.file_loggers->destroy_offset(this->public.file_loggers,
206 offsetof(file_logger_t, destroy));
207 this->public.sys_loggers->destroy_offset(this->public.sys_loggers,
208 offsetof(sys_logger_t, destroy));
209 free(this);
210 }
211
212 /**
213 * Enforce daemon shutdown, with a given reason to do so.
214 */
215 static void kill_daemon(private_daemon_t *this, char *reason)
216 {
217 /* we send SIGTERM, so the daemon can cleanly shut down */
218 if (this->public.bus)
219 {
220 DBG1(DBG_DMN, "killing daemon: %s", reason);
221 }
222 else
223 {
224 fprintf(stderr, "killing daemon: %s\n", reason);
225 }
226 if (this->public.main_thread_id == pthread_self())
227 {
228 /* initialization failed, terminate daemon */
229 unlink(PID_FILE);
230 exit(-1);
231 }
232 else
233 {
234 DBG1(DBG_DMN, "sending SIGTERM to ourself");
235 pthread_kill(this->public.main_thread_id, SIGTERM);
236 /* thread must die, since he produced a ciritcal failure and can't continue */
237 pthread_exit(NULL);
238 }
239 }
240
241 /**
242 * drop daemon capabilities
243 */
244 static void drop_capabilities(private_daemon_t *this)
245 {
246 #ifdef HAVE_PRCTL
247 prctl(PR_SET_KEEPCAPS, 1);
248 #endif
249
250 if (setgid(charon->gid) != 0)
251 {
252 kill_daemon(this, "change to unprivileged group failed");
253 }
254 if (setuid(charon->uid) != 0)
255 {
256 kill_daemon(this, "change to unprivileged user failed");
257 }
258
259 #ifdef CAPABILITIES
260 if (cap_set_proc(this->caps) != 0)
261 {
262 kill_daemon(this, "unable to drop daemon capabilities");
263 }
264 #endif /* CAPABILITIES */
265 }
266
267 /**
268 * Implementation of daemon_t.keep_cap
269 */
270 static void keep_cap(private_daemon_t *this, u_int cap)
271 {
272 #ifdef CAPABILITIES
273 cap_set_flag(this->caps, CAP_EFFECTIVE, 1, &cap, CAP_SET);
274 cap_set_flag(this->caps, CAP_INHERITABLE, 1, &cap, CAP_SET);
275 cap_set_flag(this->caps, CAP_PERMITTED, 1, &cap, CAP_SET);
276 #endif /* CAPABILITIES */
277 }
278
279 /**
280 * lookup UID and GID
281 */
282 static void lookup_uid_gid(private_daemon_t *this)
283 {
284 #ifdef IPSEC_USER
285 {
286 char buf[1024];
287 struct passwd passwd, *pwp;
288
289 if (getpwnam_r(IPSEC_USER, &passwd, buf, sizeof(buf), &pwp) != 0 ||
290 pwp == NULL)
291 {
292 kill_daemon(this, "resolving user '"IPSEC_USER"' failed");
293 }
294 charon->uid = pwp->pw_uid;
295 }
296 #endif
297 #ifdef IPSEC_GROUP
298 {
299 char buf[1024];
300 struct group group, *grp;
301
302 if (getgrnam_r(IPSEC_GROUP, &group, buf, sizeof(buf), &grp) != 0 ||
303 grp == NULL)
304 {
305 kill_daemon(this, "resolving group '"IPSEC_GROUP"' failed");
306 }
307 charon->gid = grp->gr_gid;
308 }
309 #endif
310 }
311
312 /**
313 * Log loaded plugins
314 */
315 static void print_plugins()
316 {
317 char buf[512], *plugin;
318 int len = 0;
319 enumerator_t *enumerator;
320
321 buf[0] = '\0';
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 /* set up legacy style default loggers provided via command-line */
424 if (!loggers_defined)
425 {
426 /* set up default stdout file_logger */
427 file_logger = file_logger_create(stdout);
428 this->public.bus->add_listener(this->public.bus, &file_logger->listener);
429 this->public.file_loggers->insert_last(this->public.file_loggers,
430 file_logger);
431 /* set up default daemon sys_logger */
432 sys_logger = sys_logger_create(LOG_DAEMON);
433 this->public.bus->add_listener(this->public.bus, &sys_logger->listener);
434 this->public.sys_loggers->insert_last(this->public.sys_loggers,
435 sys_logger);
436 for (group = 0; group < DBG_MAX; group++)
437 {
438 sys_logger->set_level(sys_logger, group, levels[group]);
439 if (use_stderr)
440 {
441 file_logger->set_level(file_logger, group, levels[group]);
442 }
443 }
444
445 /* set up default auth sys_logger */
446 sys_logger = sys_logger_create(LOG_AUTHPRIV);
447 this->public.bus->add_listener(this->public.bus, &sys_logger->listener);
448 this->public.sys_loggers->insert_last(this->public.sys_loggers,
449 sys_logger);
450 sys_logger->set_level(sys_logger, DBG_ANY, LEVEL_AUDIT);
451 }
452 }
453
454 /**
455 * Initialize the daemon
456 */
457 static bool initialize(private_daemon_t *this, bool syslog, level_t levels[])
458 {
459 /* for uncritical pseudo random numbers */
460 srandom(time(NULL) + getpid());
461
462 /* setup bus and it's listeners first to enable log output */
463 this->public.bus = bus_create();
464 /* set up hook to log dbg message in library via charons message bus */
465 dbg = dbg_bus;
466
467 initialize_loggers(this, !syslog, levels);
468
469 DBG1(DBG_DMN, "starting charon (strongSwan Version %s)", VERSION);
470
471 /* load secrets, ca certificates and crls */
472 this->public.processor = processor_create();
473 this->public.scheduler = scheduler_create();
474 this->public.credentials = credential_manager_create();
475 this->public.controller = controller_create();
476 this->public.eap = eap_manager_create();
477 this->public.sim = sim_manager_create();
478 this->public.backends = backend_manager_create();
479 this->public.attributes = attribute_manager_create();
480 this->public.kernel_interface = kernel_interface_create();
481 this->public.socket = socket_create();
482
483 /* load plugins, further infrastructure may need it */
484 lib->plugins->load(lib->plugins, IPSEC_PLUGINDIR,
485 lib->settings->get_str(lib->settings, "charon.load", PLUGINS));
486
487 print_plugins();
488
489 /* create the kernel interfaces */
490 this->public.kernel_interface->create_interfaces(this->public.kernel_interface);
491
492 #ifdef INTEGRITY_TEST
493 DBG1(DBG_DMN, "integrity test of libstrongswan code");
494 if (fips_verify_hmac_signature(hmac_key, hmac_signature))
495 {
496 DBG1(DBG_DMN, " integrity test passed");
497 }
498 else
499 {
500 DBG1(DBG_DMN, " integrity test failed");
501 return FALSE;
502 }
503 #endif /* INTEGRITY_TEST */
504
505 this->public.ike_sa_manager = ike_sa_manager_create();
506 if (this->public.ike_sa_manager == NULL)
507 {
508 return FALSE;
509 }
510 this->public.sender = sender_create();
511 this->public.receiver = receiver_create();
512 if (this->public.receiver == NULL)
513 {
514 return FALSE;
515 }
516
517 #ifdef ME
518 this->public.connect_manager = connect_manager_create();
519 if (this->public.connect_manager == NULL)
520 {
521 return FALSE;
522 }
523 this->public.mediation_manager = mediation_manager_create();
524 #endif /* ME */
525
526 return TRUE;
527 }
528
529 /**
530 * Handle SIGSEGV/SIGILL signals raised by threads
531 */
532 static void segv_handler(int signal)
533 {
534 backtrace_t *backtrace;
535
536 DBG1(DBG_DMN, "thread %u received %d", pthread_self(), signal);
537 backtrace = backtrace_create(2);
538 backtrace->log(backtrace, stderr);
539 backtrace->destroy(backtrace);
540
541 DBG1(DBG_DMN, "killing ourself, received critical signal");
542 raise(SIGKILL);
543 }
544
545 /**
546 * Create the daemon.
547 */
548 private_daemon_t *daemon_create(void)
549 {
550 struct sigaction action;
551 private_daemon_t *this = malloc_thing(private_daemon_t);
552
553 /* assign methods */
554 this->public.kill = (void (*) (daemon_t*,char*))kill_daemon;
555 this->public.keep_cap = (void(*)(daemon_t*, u_int cap))keep_cap;
556
557 /* NULL members for clean destruction */
558 this->public.socket = NULL;
559 this->public.ike_sa_manager = NULL;
560 this->public.credentials = NULL;
561 this->public.backends = NULL;
562 this->public.attributes = NULL;
563 this->public.sender= NULL;
564 this->public.receiver = NULL;
565 this->public.scheduler = NULL;
566 this->public.kernel_interface = NULL;
567 this->public.processor = NULL;
568 this->public.controller = NULL;
569 this->public.eap = NULL;
570 this->public.sim = NULL;
571 this->public.bus = NULL;
572 this->public.file_loggers = linked_list_create();
573 this->public.sys_loggers = linked_list_create();
574 #ifdef ME
575 this->public.connect_manager = NULL;
576 this->public.mediation_manager = NULL;
577 #endif /* ME */
578 this->public.uid = 0;
579 this->public.gid = 0;
580
581 this->public.main_thread_id = pthread_self();
582 #ifdef CAPABILITIES
583 this->caps = cap_init();
584 keep_cap(this, CAP_NET_ADMIN);
585 if (lib->leak_detective)
586 {
587 keep_cap(this, CAP_SYS_NICE);
588 }
589 #endif /* CAPABILITIES */
590
591 /* add handler for SEGV and ILL,
592 * add handler for USR1 (cancellation).
593 * INT, TERM and HUP are handled by sigwait() in run() */
594 action.sa_handler = segv_handler;
595 action.sa_flags = 0;
596 sigemptyset(&action.sa_mask);
597 sigaddset(&action.sa_mask, SIGINT);
598 sigaddset(&action.sa_mask, SIGTERM);
599 sigaddset(&action.sa_mask, SIGHUP);
600 sigaction(SIGSEGV, &action, NULL);
601 sigaction(SIGILL, &action, NULL);
602 sigaction(SIGBUS, &action, NULL);
603 action.sa_handler = SIG_IGN;
604 sigaction(SIGPIPE, &action, NULL);
605
606 pthread_sigmask(SIG_SETMASK, &action.sa_mask, 0);
607
608 return this;
609 }
610
611 /**
612 * print command line usage and exit
613 */
614 static void usage(const char *msg)
615 {
616 if (msg != NULL && *msg != '\0')
617 {
618 fprintf(stderr, "%s\n", msg);
619 }
620 fprintf(stderr, "Usage: charon\n"
621 " [--help]\n"
622 " [--version]\n"
623 " [--use-syslog]\n"
624 " [--debug-<type> <level>]\n"
625 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
626 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
627 " 2 = controlmore, 3 = raw, 4 = private)\n"
628 "\n"
629 );
630 exit(msg == NULL? 0 : 1);
631 }
632
633 /**
634 * Main function, manages the daemon.
635 */
636 int main(int argc, char *argv[])
637 {
638 bool use_syslog = FALSE;
639
640 private_daemon_t *private_charon;
641 FILE *pid_file;
642 struct stat stb;
643 level_t levels[DBG_MAX];
644 int group;
645
646 /* logging for library during initialization, as we have no bus yet */
647 dbg = dbg_stderr;
648
649 /* initialize library */
650 library_init(STRONGSWAN_CONF);
651 lib->printf_hook->add_handler(lib->printf_hook, 'R',
652 traffic_selector_printf_hook,
653 PRINTF_HOOK_ARGTYPE_POINTER,
654 PRINTF_HOOK_ARGTYPE_END);
655 lib->printf_hook->add_handler(lib->printf_hook, 'P',
656 proposal_printf_hook,
657 PRINTF_HOOK_ARGTYPE_POINTER,
658 PRINTF_HOOK_ARGTYPE_END);
659 private_charon = daemon_create();
660 charon = (daemon_t*)private_charon;
661
662 lookup_uid_gid(private_charon);
663
664 /* use CTRL loglevel for default */
665 for (group = 0; group < DBG_MAX; group++)
666 {
667 levels[group] = LEVEL_CTRL;
668 }
669
670 /* handle arguments */
671 for (;;)
672 {
673 struct option long_opts[] = {
674 { "help", no_argument, NULL, 'h' },
675 { "version", no_argument, NULL, 'v' },
676 { "use-syslog", no_argument, NULL, 'l' },
677 /* TODO: handle "debug-all" */
678 { "debug-dmn", required_argument, &group, DBG_DMN },
679 { "debug-mgr", required_argument, &group, DBG_MGR },
680 { "debug-ike", required_argument, &group, DBG_IKE },
681 { "debug-chd", required_argument, &group, DBG_CHD },
682 { "debug-job", required_argument, &group, DBG_JOB },
683 { "debug-cfg", required_argument, &group, DBG_CFG },
684 { "debug-knl", required_argument, &group, DBG_KNL },
685 { "debug-net", required_argument, &group, DBG_NET },
686 { "debug-enc", required_argument, &group, DBG_ENC },
687 { "debug-lib", required_argument, &group, DBG_LIB },
688 { 0,0,0,0 }
689 };
690
691 int c = getopt_long(argc, argv, "", long_opts, NULL);
692 switch (c)
693 {
694 case EOF:
695 break;
696 case 'h':
697 usage(NULL);
698 break;
699 case 'v':
700 printf("Linux strongSwan %s\n", VERSION);
701 exit(0);
702 case 'l':
703 use_syslog = TRUE;
704 continue;
705 case 0:
706 /* option is in group */
707 levels[group] = atoi(optarg);
708 continue;
709 default:
710 usage("");
711 break;
712 }
713 break;
714 }
715
716 /* initialize daemon */
717 if (!initialize(private_charon, use_syslog, levels))
718 {
719 DBG1(DBG_DMN, "initialization failed - aborting charon");
720 destroy(private_charon);
721 exit(-1);
722 }
723
724 /* check/setup PID file */
725 if (stat(PID_FILE, &stb) == 0)
726 {
727 DBG1(DBG_DMN, "charon already running (\""PID_FILE"\" exists)");
728 destroy(private_charon);
729 exit(-1);
730 }
731 pid_file = fopen(PID_FILE, "w");
732 if (pid_file)
733 {
734 fprintf(pid_file, "%d\n", getpid());
735 ignore_result(fchown(fileno(pid_file), charon->uid, charon->gid));
736 fclose(pid_file);
737 }
738
739 /* drop the capabilities we won't need */
740 drop_capabilities(private_charon);
741
742 /* start the engine, go multithreaded */
743 charon->processor->set_threads(charon->processor,
744 lib->settings->get_int(lib->settings, "charon.threads",
745 DEFAULT_THREADS));
746
747 /* run daemon */
748 run(private_charon);
749
750 /* normal termination, cleanup and exit */
751 destroy(private_charon);
752 unlink(PID_FILE);
753
754 library_deinit();
755
756 return 0;
757 }
758