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>
23 #define _POSIX_PTHREAD_SEMANTICS /* for two param sigwait on OpenSolaris */
25 #undef _POSIX_PTHREAD_SEMANTICS
28 #include <sys/types.h>
37 #include <sys/capability.h>
38 #endif /* CAPABILITIES */
43 #include <utils/backtrace.h>
44 #include <config/traffic_selector.h>
45 #include <config/proposal.h>
47 #ifndef LOG_AUTHPRIV /* not defined on OpenSolaris */
48 #define LOG_AUTHPRIV LOG_AUTH
51 typedef struct private_daemon_t private_daemon_t
;
54 * Private additions to daemon_t, contains threads and internal functions.
56 struct private_daemon_t
{
58 * Public members of daemon_t.
63 * Signal set used for signal handling.
69 * capabilities to keep
72 #endif /* CAPABILITIES */
76 * One and only instance of the daemon.
81 * hook in library for debugging messages
83 extern void (*dbg
) (int level
, char *fmt
, ...);
86 * Logging hook for library logs, spreads debug message over bus
88 static void dbg_bus(int level
, char *fmt
, ...)
93 charon
->bus
->vlog(charon
->bus
, DBG_LIB
, level
, fmt
, args
);
98 * Logging hook for library logs, using stderr output
100 static void dbg_stderr(int level
, char *fmt
, ...)
107 fprintf(stderr
, "00[LIB] ");
108 vfprintf(stderr
, fmt
, args
);
109 fprintf(stderr
, "\n");
115 * Run the daemon and handle unix signals
117 static void run(private_daemon_t
*this)
121 /* handle SIGINT, SIGHUP ans SIGTERM in this handler */
123 sigaddset(&set
, SIGINT
);
124 sigaddset(&set
, SIGHUP
);
125 sigaddset(&set
, SIGTERM
);
132 error
= sigwait(&set
, &sig
);
135 DBG1(DBG_DMN
, "error %d while waiting for a signal", error
);
142 DBG1(DBG_DMN
, "signal of type SIGHUP received. Ignored");
147 DBG1(DBG_DMN
, "signal of type SIGINT received. Shutting down");
148 charon
->bus
->alert(charon
->bus
, ALERT_SHUTDOWN_SIGNAL
, sig
);
153 DBG1(DBG_DMN
, "signal of type SIGTERM received. Shutting down");
154 charon
->bus
->alert(charon
->bus
, ALERT_SHUTDOWN_SIGNAL
, sig
);
159 DBG1(DBG_DMN
, "unknown signal %d received. Ignored", sig
);
167 * Clean up all daemon resources
169 static void destroy(private_daemon_t
*this)
171 /* terminate all idle threads */
172 if (this->public.processor
)
174 this->public.processor
->set_threads(this->public.processor
, 0);
176 /* close all IKE_SAs */
177 if (this->public.ike_sa_manager
)
179 this->public.ike_sa_manager
->flush(this->public.ike_sa_manager
);
181 /* unload plugins to release threads */
182 lib
->plugins
->unload(lib
->plugins
);
184 cap_free(this->caps
);
185 #endif /* CAPABILITIES */
186 DESTROY_IF(this->public.traps
);
187 DESTROY_IF(this->public.ike_sa_manager
);
188 DESTROY_IF(this->public.kernel_interface
);
189 DESTROY_IF(this->public.scheduler
);
190 DESTROY_IF(this->public.controller
);
191 DESTROY_IF(this->public.eap
);
192 DESTROY_IF(this->public.sim
);
194 DESTROY_IF(this->public.connect_manager
);
195 DESTROY_IF(this->public.mediation_manager
);
197 DESTROY_IF(this->public.backends
);
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
);
205 /* rehook library logging, shutdown logging */
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
));
216 * Enforce daemon shutdown, with a given reason to do so.
218 static void kill_daemon(private_daemon_t
*this, char *reason
)
220 /* we send SIGTERM, so the daemon can cleanly shut down */
221 if (this->public.bus
)
223 DBG1(DBG_DMN
, "killing daemon: %s", reason
);
227 fprintf(stderr
, "killing daemon: %s\n", reason
);
229 if (this->public.main_thread_id
== pthread_self())
231 /* initialization failed, terminate daemon */
237 DBG1(DBG_DMN
, "sending SIGTERM to ourself");
238 pthread_kill(this->public.main_thread_id
, SIGTERM
);
239 /* thread must die, since he produced a ciritcal failure and can't continue */
245 * drop daemon capabilities
247 static void drop_capabilities(private_daemon_t
*this)
250 prctl(PR_SET_KEEPCAPS
, 1);
253 if (setgid(charon
->gid
) != 0)
255 kill_daemon(this, "change to unprivileged group failed");
257 if (setuid(charon
->uid
) != 0)
259 kill_daemon(this, "change to unprivileged user failed");
263 if (cap_set_proc(this->caps
) != 0)
265 kill_daemon(this, "unable to drop daemon capabilities");
267 #endif /* CAPABILITIES */
271 * Implementation of daemon_t.keep_cap
273 static void keep_cap(private_daemon_t
*this, u_int cap
)
276 cap_set_flag(this->caps
, CAP_EFFECTIVE
, 1, &cap
, CAP_SET
);
277 cap_set_flag(this->caps
, CAP_INHERITABLE
, 1, &cap
, CAP_SET
);
278 cap_set_flag(this->caps
, CAP_PERMITTED
, 1, &cap
, CAP_SET
);
279 #endif /* CAPABILITIES */
285 static void lookup_uid_gid(private_daemon_t
*this)
290 struct passwd passwd
, *pwp
;
292 if (getpwnam_r(IPSEC_USER
, &passwd
, buf
, sizeof(buf
), &pwp
) != 0 ||
295 kill_daemon(this, "resolving user '"IPSEC_USER
"' failed");
297 charon
->uid
= pwp
->pw_uid
;
303 struct group group
, *grp
;
305 if (getgrnam_r(IPSEC_GROUP
, &group
, buf
, sizeof(buf
), &grp
) != 0 ||
308 kill_daemon(this, "resolving group '"IPSEC_GROUP
"' failed");
310 charon
->gid
= grp
->gr_gid
;
318 static void print_plugins()
320 char buf
[512], *plugin
;
322 enumerator_t
*enumerator
;
325 enumerator
= lib
->plugins
->create_plugin_enumerator(lib
->plugins
);
326 while (len
< sizeof(buf
) && enumerator
->enumerate(enumerator
, &plugin
))
328 len
+= snprintf(&buf
[len
], sizeof(buf
)-len
, "%s ", plugin
);
330 enumerator
->destroy(enumerator
);
331 DBG1(DBG_DMN
, "loaded plugins: %s", buf
);
337 static void initialize_loggers(private_daemon_t
*this, bool use_stderr
,
340 sys_logger_t
*sys_logger
;
341 file_logger_t
*file_logger
;
342 enumerator_t
*enumerator
;
343 char *facility
, *filename
;
344 int loggers_defined
= 0;
350 /* setup sysloggers */
351 enumerator
= lib
->settings
->create_section_enumerator(lib
->settings
,
353 while (enumerator
->enumerate(enumerator
, &facility
))
356 if (streq(facility
, "daemon"))
358 sys_logger
= sys_logger_create(LOG_DAEMON
);
360 else if (streq(facility
, "auth"))
362 sys_logger
= sys_logger_create(LOG_AUTHPRIV
);
368 def
= lib
->settings
->get_int(lib
->settings
,
369 "charon.syslog.%s.default", 1, facility
);
370 for (group
= 0; group
< DBG_MAX
; group
++)
372 sys_logger
->set_level(sys_logger
, group
,
373 lib
->settings
->get_int(lib
->settings
,
374 "charon.syslog.%s.%N", def
,
375 facility
, debug_lower_names
, group
));
377 this->public.sys_loggers
->insert_last(this->public.sys_loggers
,
379 this->public.bus
->add_listener(this->public.bus
, &sys_logger
->listener
);
381 enumerator
->destroy(enumerator
);
383 /* and file loggers */
384 enumerator
= lib
->settings
->create_section_enumerator(lib
->settings
,
386 while (enumerator
->enumerate(enumerator
, &filename
))
389 if (streq(filename
, "stderr"))
393 else if (streq(filename
, "stdout"))
399 append
= lib
->settings
->get_bool(lib
->settings
,
400 "charon.filelog.%s.append", TRUE
, filename
);
401 file
= fopen(filename
, append
? "a" : "w");
404 DBG1(DBG_DMN
, "opening file %s for logging failed: %s",
405 filename
, strerror(errno
));
409 file_logger
= file_logger_create(file
);
410 def
= lib
->settings
->get_int(lib
->settings
,
411 "charon.filelog.%s.default", 1, filename
);
412 for (group
= 0; group
< DBG_MAX
; group
++)
414 file_logger
->set_level(file_logger
, group
,
415 lib
->settings
->get_int(lib
->settings
,
416 "charon.filelog.%s.%N", def
,
417 filename
, debug_lower_names
, group
));
419 this->public.file_loggers
->insert_last(this->public.file_loggers
,
421 this->public.bus
->add_listener(this->public.bus
, &file_logger
->listener
);
424 enumerator
->destroy(enumerator
);
426 /* set up legacy style default loggers provided via command-line */
427 if (!loggers_defined
)
429 /* set up default stdout file_logger */
430 file_logger
= file_logger_create(stdout
);
431 this->public.bus
->add_listener(this->public.bus
, &file_logger
->listener
);
432 this->public.file_loggers
->insert_last(this->public.file_loggers
,
434 /* set up default daemon sys_logger */
435 sys_logger
= sys_logger_create(LOG_DAEMON
);
436 this->public.bus
->add_listener(this->public.bus
, &sys_logger
->listener
);
437 this->public.sys_loggers
->insert_last(this->public.sys_loggers
,
439 for (group
= 0; group
< DBG_MAX
; group
++)
441 sys_logger
->set_level(sys_logger
, group
, levels
[group
]);
444 file_logger
->set_level(file_logger
, group
, levels
[group
]);
448 /* set up default auth sys_logger */
449 sys_logger
= sys_logger_create(LOG_AUTHPRIV
);
450 this->public.bus
->add_listener(this->public.bus
, &sys_logger
->listener
);
451 this->public.sys_loggers
->insert_last(this->public.sys_loggers
,
453 sys_logger
->set_level(sys_logger
, DBG_ANY
, LEVEL_AUDIT
);
458 * Initialize the daemon
460 static bool initialize(private_daemon_t
*this, bool syslog
, level_t levels
[])
462 /* for uncritical pseudo random numbers */
463 srandom(time(NULL
) + getpid());
465 /* setup bus and it's listeners first to enable log output */
466 this->public.bus
= bus_create();
467 /* set up hook to log dbg message in library via charons message bus */
470 initialize_loggers(this, !syslog
, levels
);
472 DBG1(DBG_DMN
, "Starting IKEv2 charon daemon (strongSwan "VERSION
")");
476 DBG1(DBG_DMN
, "integrity tests enabled:");
477 DBG1(DBG_DMN
, "lib 'libstrongswan': passed file and segment integrity tests");
478 DBG1(DBG_DMN
, "daemon 'charon': passed file integrity test");
481 /* load secrets, ca certificates and crls */
482 this->public.processor
= processor_create();
483 this->public.scheduler
= scheduler_create();
484 this->public.credentials
= credential_manager_create();
485 this->public.controller
= controller_create();
486 this->public.eap
= eap_manager_create();
487 this->public.sim
= sim_manager_create();
488 this->public.backends
= backend_manager_create();
489 this->public.kernel_interface
= kernel_interface_create();
490 this->public.socket
= socket_create();
491 this->public.traps
= trap_manager_create();
493 /* load plugins, further infrastructure may need it */
494 if (!lib
->plugins
->load(lib
->plugins
, NULL
,
495 lib
->settings
->get_str(lib
->settings
, "charon.load", PLUGINS
)))
502 this->public.ike_sa_manager
= ike_sa_manager_create();
503 if (this->public.ike_sa_manager
== NULL
)
507 this->public.sender
= sender_create();
508 this->public.receiver
= receiver_create();
509 if (this->public.receiver
== NULL
)
515 this->public.connect_manager
= connect_manager_create();
516 if (this->public.connect_manager
== NULL
)
520 this->public.mediation_manager
= mediation_manager_create();
527 * Handle SIGSEGV/SIGILL signals raised by threads
529 static void segv_handler(int signal
)
531 backtrace_t
*backtrace
;
533 DBG1(DBG_DMN
, "thread %u received %d", pthread_self(), signal
);
534 backtrace
= backtrace_create(2);
535 backtrace
->log(backtrace
, stderr
);
536 backtrace
->destroy(backtrace
);
538 DBG1(DBG_DMN
, "killing ourself, received critical signal");
545 private_daemon_t
*daemon_create(void)
547 struct sigaction action
;
548 private_daemon_t
*this = malloc_thing(private_daemon_t
);
551 this->public.kill
= (void (*) (daemon_t
*,char*))kill_daemon
;
552 this->public.keep_cap
= (void(*)(daemon_t
*, u_int cap
))keep_cap
;
554 /* NULL members for clean destruction */
555 this->public.socket
= NULL
;
556 this->public.ike_sa_manager
= NULL
;
557 this->public.traps
= NULL
;
558 this->public.credentials
= NULL
;
559 this->public.backends
= NULL
;
560 this->public.sender
= NULL
;
561 this->public.receiver
= NULL
;
562 this->public.scheduler
= NULL
;
563 this->public.kernel_interface
= NULL
;
564 this->public.processor
= NULL
;
565 this->public.controller
= NULL
;
566 this->public.eap
= NULL
;
567 this->public.sim
= NULL
;
568 this->public.bus
= NULL
;
569 this->public.file_loggers
= linked_list_create();
570 this->public.sys_loggers
= linked_list_create();
572 this->public.connect_manager
= NULL
;
573 this->public.mediation_manager
= NULL
;
575 this->public.uid
= 0;
576 this->public.gid
= 0;
578 this->public.main_thread_id
= pthread_self();
580 this->caps
= cap_init();
581 keep_cap(this, CAP_NET_ADMIN
);
582 if (lib
->leak_detective
)
584 keep_cap(this, CAP_SYS_NICE
);
586 #endif /* CAPABILITIES */
588 /* add handler for SEGV and ILL,
589 * add handler for USR1 (cancellation).
590 * INT, TERM and HUP are handled by sigwait() in run() */
591 action
.sa_handler
= segv_handler
;
593 sigemptyset(&action
.sa_mask
);
594 sigaddset(&action
.sa_mask
, SIGINT
);
595 sigaddset(&action
.sa_mask
, SIGTERM
);
596 sigaddset(&action
.sa_mask
, SIGHUP
);
597 sigaction(SIGSEGV
, &action
, NULL
);
598 sigaction(SIGILL
, &action
, NULL
);
599 sigaction(SIGBUS
, &action
, NULL
);
600 action
.sa_handler
= SIG_IGN
;
601 sigaction(SIGPIPE
, &action
, NULL
);
603 pthread_sigmask(SIG_SETMASK
, &action
.sa_mask
, 0);
609 * Check/create PID file, return TRUE if already running
611 static bool check_pidfile()
616 if (stat(PID_FILE
, &stb
) == 0)
618 file
= fopen(PID_FILE
, "r");
624 memset(buf
, 0, sizeof(buf
));
625 if (fread(buf
, 1, sizeof(buf
), file
))
630 if (pid
&& kill(pid
, 0) == 0)
631 { /* such a process is running */
635 DBG1(DBG_DMN
, "removing pidfile '"PID_FILE
"', process not running");
639 /* create new pidfile */
640 file
= fopen(PID_FILE
, "w");
643 fprintf(file
, "%d\n", getpid());
644 ignore_result(fchown(fileno(file
), charon
->uid
, charon
->gid
));
651 * print command line usage and exit
653 static void usage(const char *msg
)
655 if (msg
!= NULL
&& *msg
!= '\0')
657 fprintf(stderr
, "%s\n", msg
);
659 fprintf(stderr
, "Usage: charon\n"
663 " [--debug-<type> <level>]\n"
664 " <type>: log context type (dmn|mgr|ike|chd|job|cfg|knl|net|enc|lib)\n"
665 " <level>: log verbosity (-1 = silent, 0 = audit, 1 = control,\n"
666 " 2 = controlmore, 3 = raw, 4 = private)\n"
669 exit(msg
== NULL
? 0 : 1);
673 * Main function, manages the daemon.
675 int main(int argc
, char *argv
[])
677 bool use_syslog
= FALSE
;
678 private_daemon_t
*private_charon
;
679 level_t levels
[DBG_MAX
];
682 /* logging for library during initialization, as we have no bus yet */
685 /* initialize library */
686 if (!library_init(NULL
))
689 exit(SS_RC_LIBSTRONGSWAN_INTEGRITY
);
692 if (lib
->integrity
&&
693 !lib
->integrity
->check_file(lib
->integrity
, "charon", argv
[0]))
695 dbg_stderr(1, "integrity check of charon failed");
697 exit(SS_RC_DAEMON_INTEGRITY
);
700 lib
->printf_hook
->add_handler(lib
->printf_hook
, 'R',
701 traffic_selector_printf_hook
,
702 PRINTF_HOOK_ARGTYPE_POINTER
,
703 PRINTF_HOOK_ARGTYPE_END
);
704 lib
->printf_hook
->add_handler(lib
->printf_hook
, 'P',
705 proposal_printf_hook
,
706 PRINTF_HOOK_ARGTYPE_POINTER
,
707 PRINTF_HOOK_ARGTYPE_END
);
708 private_charon
= daemon_create();
709 charon
= (daemon_t
*)private_charon
;
711 lookup_uid_gid(private_charon
);
713 /* use CTRL loglevel for default */
714 for (group
= 0; group
< DBG_MAX
; group
++)
716 levels
[group
] = LEVEL_CTRL
;
719 /* handle arguments */
722 struct option long_opts
[] = {
723 { "help", no_argument
, NULL
, 'h' },
724 { "version", no_argument
, NULL
, 'v' },
725 { "use-syslog", no_argument
, NULL
, 'l' },
726 /* TODO: handle "debug-all" */
727 { "debug-dmn", required_argument
, &group
, DBG_DMN
},
728 { "debug-mgr", required_argument
, &group
, DBG_MGR
},
729 { "debug-ike", required_argument
, &group
, DBG_IKE
},
730 { "debug-chd", required_argument
, &group
, DBG_CHD
},
731 { "debug-job", required_argument
, &group
, DBG_JOB
},
732 { "debug-cfg", required_argument
, &group
, DBG_CFG
},
733 { "debug-knl", required_argument
, &group
, DBG_KNL
},
734 { "debug-net", required_argument
, &group
, DBG_NET
},
735 { "debug-enc", required_argument
, &group
, DBG_ENC
},
736 { "debug-lib", required_argument
, &group
, DBG_LIB
},
740 int c
= getopt_long(argc
, argv
, "", long_opts
, NULL
);
749 printf("Linux strongSwan %s\n", VERSION
);
755 /* option is in group */
756 levels
[group
] = atoi(optarg
);
765 /* initialize daemon */
766 if (!initialize(private_charon
, use_syslog
, levels
))
768 DBG1(DBG_DMN
, "initialization failed - aborting charon");
769 destroy(private_charon
);
771 exit(SS_RC_INITIALIZATION_FAILED
);
776 DBG1(DBG_DMN
, "charon already running (\""PID_FILE
"\" exists)");
777 destroy(private_charon
);
782 /* drop the capabilities we won't need */
783 drop_capabilities(private_charon
);
785 /* start the engine, go multithreaded */
786 charon
->processor
->set_threads(charon
->processor
,
787 lib
->settings
->get_int(lib
->settings
, "charon.threads",
793 /* normal termination, cleanup and exit */
794 destroy(private_charon
);