2 * Copyright (C) 2006-2009 Tobias Brunner
3 * Copyright (C) 2005-2009 Martin Willi
4 * Copyright (C) 2006 Daniel Roethlisberger
5 * Copyright (C) 2005 Jan Hutter
6 * Hochschule fuer Technik Rapperswil
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>.
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
21 #include <sys/prctl.h>
26 #include <sys/types.h>
35 #include <sys/capability.h>
36 #endif /* CAPABILITIES */
41 #include <utils/backtrace.h>
42 #include <config/traffic_selector.h>
43 #include <config/proposal.h>
46 #include <fips/fips.h>
47 #include <fips/fips_signature.h>
48 #endif /* INTEGRITY_TEST */
50 typedef struct private_daemon_t private_daemon_t
;
53 * Private additions to daemon_t, contains threads and internal functions.
55 struct private_daemon_t
{
57 * Public members of daemon_t.
62 * Signal set used for signal handling.
68 * capabilities to keep
71 #endif /* CAPABILITIES */
75 * One and only instance of the daemon.
80 * hook in library for debugging messages
82 extern void (*dbg
) (int level
, char *fmt
, ...);
85 * Logging hook for library logs, spreads debug message over bus
87 static void dbg_bus(int level
, char *fmt
, ...)
92 charon
->bus
->vlog(charon
->bus
, DBG_LIB
, level
, fmt
, args
);
97 * Logging hook for library logs, using stderr output
99 static void dbg_stderr(int level
, char *fmt
, ...)
106 fprintf(stderr
, "00[LIB] ");
107 vfprintf(stderr
, fmt
, args
);
108 fprintf(stderr
, "\n");
114 * Run the daemon and handle unix signals
116 static void run(private_daemon_t
*this)
120 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
122 sigaddset(&set
, SIGINT
);
123 sigaddset(&set
, SIGHUP
);
124 sigaddset(&set
, SIGTERM
);
131 error
= sigwait(&set
, &sig
);
134 DBG1(DBG_DMN
, "error %d while waiting for a signal", error
);
141 DBG1(DBG_DMN
, "signal of type SIGHUP received. Ignored");
146 DBG1(DBG_DMN
, "signal of type SIGINT received. Shutting down");
151 DBG1(DBG_DMN
, "signal of type SIGTERM received. Shutting down");
156 DBG1(DBG_DMN
, "unknown signal %d received. Ignored", sig
);
164 * Clean up all daemon resources
166 static void destroy(private_daemon_t
*this)
168 /* terminate all idle threads */
169 if (this->public.processor
)
171 this->public.processor
->set_threads(this->public.processor
, 0);
173 /* close all IKE_SAs */
174 if (this->public.ike_sa_manager
)
176 this->public.ike_sa_manager
->flush(this->public.ike_sa_manager
);
178 /* unload plugins to release threads */
179 lib
->plugins
->unload(lib
->plugins
);
181 cap_free(this->caps
);
182 #endif /* CAPABILITIES */
183 DESTROY_IF(this->public.traps
);
184 DESTROY_IF(this->public.ike_sa_manager
);
185 DESTROY_IF(this->public.kernel_interface
);
186 DESTROY_IF(this->public.scheduler
);
187 DESTROY_IF(this->public.controller
);
188 DESTROY_IF(this->public.eap
);
189 DESTROY_IF(this->public.sim
);
191 DESTROY_IF(this->public.connect_manager
);
192 DESTROY_IF(this->public.mediation_manager
);
194 DESTROY_IF(this->public.backends
);
195 DESTROY_IF(this->public.attributes
);
196 DESTROY_IF(this->public.credentials
);
197 DESTROY_IF(this->public.sender
);
198 DESTROY_IF(this->public.receiver
);
199 DESTROY_IF(this->public.socket
);
200 /* wait until all threads are gone */
201 DESTROY_IF(this->public.processor
);
203 /* rehook library logging, shutdown logging */
205 DESTROY_IF(this->public.bus
);
206 this->public.file_loggers
->destroy_offset(this->public.file_loggers
,
207 offsetof(file_logger_t
, destroy
));
208 this->public.sys_loggers
->destroy_offset(this->public.sys_loggers
,
209 offsetof(sys_logger_t
, destroy
));
214 * Enforce daemon shutdown, with a given reason to do so.
216 static void kill_daemon(private_daemon_t
*this, char *reason
)
218 /* we send SIGTERM, so the daemon can cleanly shut down */
219 if (this->public.bus
)
221 DBG1(DBG_DMN
, "killing daemon: %s", reason
);
225 fprintf(stderr
, "killing daemon: %s\n", reason
);
227 if (this->public.main_thread_id
== pthread_self())
229 /* initialization failed, terminate daemon */
235 DBG1(DBG_DMN
, "sending SIGTERM to ourself");
236 pthread_kill(this->public.main_thread_id
, SIGTERM
);
237 /* thread must die, since he produced a ciritcal failure and can't continue */
243 * drop daemon capabilities
245 static void drop_capabilities(private_daemon_t
*this)
248 prctl(PR_SET_KEEPCAPS
, 1);
251 if (setgid(charon
->gid
) != 0)
253 kill_daemon(this, "change to unprivileged group failed");
255 if (setuid(charon
->uid
) != 0)
257 kill_daemon(this, "change to unprivileged user failed");
261 if (cap_set_proc(this->caps
) != 0)
263 kill_daemon(this, "unable to drop daemon capabilities");
265 #endif /* CAPABILITIES */
269 * Implementation of daemon_t.keep_cap
271 static void keep_cap(private_daemon_t
*this, u_int cap
)
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 */
283 static void lookup_uid_gid(private_daemon_t
*this)
288 struct passwd passwd
, *pwp
;
290 if (getpwnam_r(IPSEC_USER
, &passwd
, buf
, sizeof(buf
), &pwp
) != 0 ||
293 kill_daemon(this, "resolving user '"IPSEC_USER
"' failed");
295 charon
->uid
= pwp
->pw_uid
;
301 struct group group
, *grp
;
303 if (getgrnam_r(IPSEC_GROUP
, &group
, buf
, sizeof(buf
), &grp
) != 0 ||
306 kill_daemon(this, "resolving group '"IPSEC_GROUP
"' failed");
308 charon
->gid
= grp
->gr_gid
;
316 static void print_plugins()
318 char buf
[512], *plugin
;
320 enumerator_t
*enumerator
;
323 enumerator
= lib
->plugins
->create_plugin_enumerator(lib
->plugins
);
324 while (len
< sizeof(buf
) && enumerator
->enumerate(enumerator
, &plugin
))
326 len
+= snprintf(&buf
[len
], sizeof(buf
)-len
, "%s ", plugin
);
328 enumerator
->destroy(enumerator
);
329 DBG1(DBG_DMN
, "loaded plugins: %s", buf
);
335 static void initialize_loggers(private_daemon_t
*this, bool use_stderr
,
338 sys_logger_t
*sys_logger
;
339 file_logger_t
*file_logger
;
340 enumerator_t
*enumerator
;
341 char *facility
, *filename
;
342 int loggers_defined
= 0;
348 /* setup sysloggers */
349 enumerator
= lib
->settings
->create_section_enumerator(lib
->settings
,
351 while (enumerator
->enumerate(enumerator
, &facility
))
354 if (streq(facility
, "daemon"))
356 sys_logger
= sys_logger_create(LOG_DAEMON
);
358 else if (streq(facility
, "auth"))
360 sys_logger
= sys_logger_create(LOG_AUTHPRIV
);
366 def
= lib
->settings
->get_int(lib
->settings
,
367 "charon.syslog.%s.default", 1, facility
);
368 for (group
= 0; group
< DBG_MAX
; group
++)
370 sys_logger
->set_level(sys_logger
, group
,
371 lib
->settings
->get_int(lib
->settings
,
372 "charon.syslog.%s.%N", def
,
373 facility
, debug_lower_names
, group
));
375 this->public.sys_loggers
->insert_last(this->public.sys_loggers
,
377 this->public.bus
->add_listener(this->public.bus
, &sys_logger
->listener
);
379 enumerator
->destroy(enumerator
);
381 /* and file loggers */
382 enumerator
= lib
->settings
->create_section_enumerator(lib
->settings
,
384 while (enumerator
->enumerate(enumerator
, &filename
))
387 if (streq(filename
, "stderr"))
391 else if (streq(filename
, "stdout"))
397 append
= lib
->settings
->get_bool(lib
->settings
,
398 "charon.filelog.%s.append", TRUE
, filename
);
399 file
= fopen(filename
, append ?
"a" : "w");
402 DBG1(DBG_DMN
, "opening file %s for logging failed: %s",
403 filename
, strerror(errno
));
407 file_logger
= file_logger_create(file
);
408 def
= lib
->settings
->get_int(lib
->settings
,
409 "charon.filelog.%s.default", 1, filename
);
410 for (group
= 0; group
< DBG_MAX
; group
++)
412 file_logger
->set_level(file_logger
, group
,
413 lib
->settings
->get_int(lib
->settings
,
414 "charon.filelog.%s.%N", def
,
415 filename
, debug_lower_names
, group
));
417 this->public.file_loggers
->insert_last(this->public.file_loggers
,
419 this->public.bus
->add_listener(this->public.bus
, &file_logger
->listener
);
422 enumerator
->destroy(enumerator
);
424 /* set up legacy style default loggers provided via command-line */
425 if (!loggers_defined
)
427 /* set up default stdout file_logger */
428 file_logger
= file_logger_create(stdout
);
429 this->public.bus
->add_listener(this->public.bus
, &file_logger
->listener
);
430 this->public.file_loggers
->insert_last(this->public.file_loggers
,
432 /* set up default daemon sys_logger */
433 sys_logger
= sys_logger_create(LOG_DAEMON
);
434 this->public.bus
->add_listener(this->public.bus
, &sys_logger
->listener
);
435 this->public.sys_loggers
->insert_last(this->public.sys_loggers
,
437 for (group
= 0; group
< DBG_MAX
; group
++)
439 sys_logger
->set_level(sys_logger
, group
, levels
[group
]);
442 file_logger
->set_level(file_logger
, group
, levels
[group
]);
446 /* set up default auth sys_logger */
447 sys_logger
= sys_logger_create(LOG_AUTHPRIV
);
448 this->public.bus
->add_listener(this->public.bus
, &sys_logger
->listener
);
449 this->public.sys_loggers
->insert_last(this->public.sys_loggers
,
451 sys_logger
->set_level(sys_logger
, DBG_ANY
, LEVEL_AUDIT
);
456 * Initialize the daemon
458 static bool initialize(private_daemon_t
*this, bool syslog
, level_t levels
[])
460 /* for uncritical pseudo random numbers */
461 srandom(time(NULL
) + getpid());
463 /* setup bus and it's listeners first to enable log output */
464 this->public.bus
= bus_create();
465 /* set up hook to log dbg message in library via charons message bus */
468 initialize_loggers(this, !syslog
, levels
);
470 DBG1(DBG_DMN
, "starting charon (strongSwan Version %s)", VERSION
);
472 /* load secrets, ca certificates and crls */
473 this->public.processor
= processor_create();
474 this->public.scheduler
= scheduler_create();
475 this->public.credentials
= credential_manager_create();
476 this->public.controller
= controller_create();
477 this->public.eap
= eap_manager_create();
478 this->public.sim
= sim_manager_create();
479 this->public.backends
= backend_manager_create();
480 this->public.attributes
= attribute_manager_create();
481 this->public.kernel_interface
= kernel_interface_create();
482 this->public.socket
= socket_create();
484 /* load plugins, further infrastructure may need it */
485 lib
->plugins
->load(lib
->plugins
, IPSEC_PLUGINDIR
,
486 lib
->settings
->get_str(lib
->settings
, "charon.load", PLUGINS
));
490 /* create the kernel interfaces */
491 this->public.kernel_interface
->create_interfaces(this->public.kernel_interface
);
493 #ifdef INTEGRITY_TEST
494 DBG1(DBG_DMN
, "integrity test of libstrongswan code");
495 if (fips_verify_hmac_signature(hmac_key
, hmac_signature
))
497 DBG1(DBG_DMN
, " integrity test passed");
501 DBG1(DBG_DMN
, " integrity test failed");
504 #endif /* INTEGRITY_TEST */
506 this->public.ike_sa_manager
= ike_sa_manager_create();
507 if (this->public.ike_sa_manager
== NULL
)
511 this->public.traps
= trap_manager_create();
512 this->public.sender
= sender_create();
513 this->public.receiver
= receiver_create();
514 if (this->public.receiver
== NULL
)
520 this->public.connect_manager
= connect_manager_create();
521 if (this->public.connect_manager
== NULL
)
525 this->public.mediation_manager
= mediation_manager_create();
532 * Handle SIGSEGV/SIGILL signals raised by threads
534 static void segv_handler(int signal
)
536 backtrace_t
*backtrace
;
538 DBG1(DBG_DMN
, "thread %u received %d", pthread_self(), signal
);
539 backtrace
= backtrace_create(2);
540 backtrace
->log(backtrace
, stderr
);
541 backtrace
->destroy(backtrace
);
543 DBG1(DBG_DMN
, "killing ourself, received critical signal");
550 private_daemon_t
*daemon_create(void)
552 struct sigaction action
;
553 private_daemon_t
*this = malloc_thing(private_daemon_t
);
556 this->public.kill
= (void (*) (daemon_t
*,char*))kill_daemon
;
557 this->public.keep_cap
= (void(*)(daemon_t
*, u_int cap
))keep_cap
;
559 /* NULL members for clean destruction */
560 this->public.socket
= NULL
;
561 this->public.ike_sa_manager
= NULL
;
562 this->public.traps
= NULL
;
563 this->public.credentials
= NULL
;
564 this->public.backends
= NULL
;
565 this->public.attributes
= NULL
;
566 this->public.sender
= NULL
;
567 this->public.receiver
= NULL
;
568 this->public.scheduler
= NULL
;
569 this->public.kernel_interface
= NULL
;
570 this->public.processor
= NULL
;
571 this->public.controller
= NULL
;
572 this->public.eap
= NULL
;
573 this->public.sim
= NULL
;
574 this->public.bus
= NULL
;
575 this->public.file_loggers
= linked_list_create();
576 this->public.sys_loggers
= linked_list_create();
578 this->public.connect_manager
= NULL
;
579 this->public.mediation_manager
= NULL
;
581 this->public.uid
= 0;
582 this->public.gid
= 0;
584 this->public.main_thread_id
= pthread_self();
586 this->caps
= cap_init();
587 keep_cap(this, CAP_NET_ADMIN
);
588 if (lib
->leak_detective
)
590 keep_cap(this, CAP_SYS_NICE
);
592 #endif /* CAPABILITIES */
594 /* add handler for SEGV and ILL,
595 * add handler for USR1 (cancellation).
596 * INT, TERM and HUP are handled by sigwait() in run() */
597 action
.sa_handler
= segv_handler
;
599 sigemptyset(&action
.sa_mask
);
600 sigaddset(&action
.sa_mask
, SIGINT
);
601 sigaddset(&action
.sa_mask
, SIGTERM
);
602 sigaddset(&action
.sa_mask
, SIGHUP
);
603 sigaction(SIGSEGV
, &action
, NULL
);
604 sigaction(SIGILL
, &action
, NULL
);
605 sigaction(SIGBUS
, &action
, NULL
);
606 action
.sa_handler
= SIG_IGN
;
607 sigaction(SIGPIPE
, &action
, NULL
);
609 pthread_sigmask(SIG_SETMASK
, &action
.sa_mask
, 0);
615 * Check/create PID file, return TRUE if already running
617 static bool check_pidfile()
622 if (stat(PID_FILE
, &stb
) == 0)
624 file
= fopen(PID_FILE
, "r");
630 memset(buf
, 0, sizeof(buf
));
631 if (fread(buf
, 1, sizeof(buf
), file
))
636 if (pid
&& kill(pid
, 0) == 0)
637 { /* such a process is running */
641 DBG1(DBG_DMN
, "removing pidfile '"PID_FILE
"', process not running");
645 /* create new pidfile */
646 file
= fopen(PID_FILE
, "w");
649 fprintf(file
, "%d\n", getpid());
650 ignore_result(fchown(fileno(file
), charon
->uid
, charon
->gid
));
657 * print command line usage and exit
659 static void usage(const char *msg
)
661 if (msg
!= NULL
&& *msg
!= '\0')
663 fprintf(stderr
, "%s\n", msg
);
665 fprintf(stderr
, "Usage: charon\n"
669 " [--debug-<type> <level>]\n"
670 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
671 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
672 " 2 = controlmore, 3 = raw, 4 = private)\n"
675 exit(msg
== NULL?
0 : 1);
679 * Main function, manages the daemon.
681 int main(int argc
, char *argv
[])
683 bool use_syslog
= FALSE
;
684 private_daemon_t
*private_charon
;
685 level_t levels
[DBG_MAX
];
688 /* logging for library during initialization, as we have no bus yet */
691 /* initialize library */
692 library_init(STRONGSWAN_CONF
);
693 lib
->printf_hook
->add_handler(lib
->printf_hook
, 'R',
694 traffic_selector_printf_hook
,
695 PRINTF_HOOK_ARGTYPE_POINTER
,
696 PRINTF_HOOK_ARGTYPE_END
);
697 lib
->printf_hook
->add_handler(lib
->printf_hook
, 'P',
698 proposal_printf_hook
,
699 PRINTF_HOOK_ARGTYPE_POINTER
,
700 PRINTF_HOOK_ARGTYPE_END
);
701 private_charon
= daemon_create();
702 charon
= (daemon_t
*)private_charon
;
704 lookup_uid_gid(private_charon
);
706 /* use CTRL loglevel for default */
707 for (group
= 0; group
< DBG_MAX
; group
++)
709 levels
[group
] = LEVEL_CTRL
;
712 /* handle arguments */
715 struct option long_opts
[] = {
716 { "help", no_argument
, NULL
, 'h' },
717 { "version", no_argument
, NULL
, 'v' },
718 { "use-syslog", no_argument
, NULL
, 'l' },
719 /* TODO: handle "debug-all" */
720 { "debug-dmn", required_argument
, &group
, DBG_DMN
},
721 { "debug-mgr", required_argument
, &group
, DBG_MGR
},
722 { "debug-ike", required_argument
, &group
, DBG_IKE
},
723 { "debug-chd", required_argument
, &group
, DBG_CHD
},
724 { "debug-job", required_argument
, &group
, DBG_JOB
},
725 { "debug-cfg", required_argument
, &group
, DBG_CFG
},
726 { "debug-knl", required_argument
, &group
, DBG_KNL
},
727 { "debug-net", required_argument
, &group
, DBG_NET
},
728 { "debug-enc", required_argument
, &group
, DBG_ENC
},
729 { "debug-lib", required_argument
, &group
, DBG_LIB
},
733 int c
= getopt_long(argc
, argv
, "", long_opts
, NULL
);
742 printf("Linux strongSwan %s\n", VERSION
);
748 /* option is in group */
749 levels
[group
] = atoi(optarg
);
758 /* initialize daemon */
759 if (!initialize(private_charon
, use_syslog
, levels
))
761 DBG1(DBG_DMN
, "initialization failed - aborting charon");
762 destroy(private_charon
);
768 DBG1(DBG_DMN
, "charon already running (\""PID_FILE
"\" exists)");
769 destroy(private_charon
);
773 /* drop the capabilities we won't need */
774 drop_capabilities(private_charon
);
776 /* start the engine, go multithreaded */
777 charon
->processor
->set_threads(charon
->processor
,
778 lib
->settings
->get_int(lib
->settings
, "charon.threads",
784 /* normal termination, cleanup and exit */
785 destroy(private_charon
);