2 * radiusd.c Main loop of the radius server.
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2000-2012 The FreeRADIUS server project
21 * Copyright 1999,2000 Miquel van Smoorenburg <miquels@cistron.nl>
22 * Copyright 2000 Alan DeKok <aland@ox.org>
23 * Copyright 2000 Alan Curry <pacman-radius@cqc.com>
24 * Copyright 2000 Jeff Carneal <jeff@apex.net>
25 * Copyright 2000 Chad Miller <cmiller@surfsouth.com>
30 #include <freeradius-devel/radiusd.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/state.h>
33 #include <freeradius-devel/rad_assert.h>
44 #ifdef HAVE_SYS_WAIT_H
45 # include <sys/wait.h>
48 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
51 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
57 char const *progname = NULL;
58 char const *radacct_dir = NULL;
59 char const *radlog_dir = NULL;
60 char const *radlib_dir = NULL;
61 bool log_stripped_names;
63 char const *radiusd_version = "FreeRADIUS Version " RADIUSD_VERSION_STRING
64 #ifdef RADIUSD_VERSION_COMMIT
65 " (git #" STRINGIFY(RADIUSD_VERSION_COMMIT) ")"
67 ", for host " HOSTINFO ", built on " __DATE__ " at " __TIME__;
69 static pid_t radius_pid;
72 * Configuration items.
78 static void usage(int);
80 static void sig_fatal (int);
82 static void sig_hup (int);
88 int main(int argc, char *argv[])
90 int rcode = EXIT_SUCCESS;
93 bool spawn_flag = true;
94 bool display_version = false;
96 int from_child[2] = {-1, -1};
97 fr_state_t *state = NULL;
100 * We probably don't want to free the talloc autofree context
101 * directly, so we'll allocate a new context beneath it, and
102 * free that before any leak reports.
104 TALLOC_CTX *autofree = talloc_init("main");
107 set_auth_parameters(argc, argv);
110 if ((progname = strrchr(argv[0], FR_DIR_SEP)) == NULL)
118 if (WSAStartup(MAKEWORD(2, 0), &wsaData)) {
119 fprintf(stderr, "%s: Unable to initialize socket library.\n", progname);
126 set_radius_dir(autofree, RADIUS_DIR);
129 * Ensure that the configuration is initialized.
131 memset(&main_config, 0, sizeof(main_config));
132 main_config.myip.af = AF_UNSPEC;
133 main_config.port = 0;
134 main_config.name = "radiusd";
135 main_config.daemonize = true;
138 * Don't put output anywhere until we get told a little
141 default_log.dst = L_DST_NULL;
143 main_config.log_file = NULL;
145 /* Process the options. */
146 while ((argval = getopt(argc, argv, "Cd:D:fhi:l:mMn:p:PstvxX")) != EOF) {
152 main_config.daemonize = false;
156 set_radius_dir(autofree, optarg);
160 main_config.dictionary_dir = talloc_typed_strdup(autofree, optarg);
164 main_config.daemonize = false;
172 if (strcmp(optarg, "stdout") == 0) {
175 main_config.log_file = strdup(optarg);
176 default_log.dst = L_DST_FILES;
177 default_log.fd = open(main_config.log_file,
178 O_WRONLY | O_APPEND | O_CREAT, 0640);
179 if (default_log.fd < 0) {
180 fprintf(stderr, "radiusd: Failed to open log file %s: %s\n", main_config.log_file, fr_syserror(errno));
183 fr_log_fp = fdopen(default_log.fd, "a");
187 if (ip_hton(&main_config.myip, AF_UNSPEC, optarg, false) < 0) {
188 fprintf(stderr, "radiusd: Invalid IP Address or hostname \"%s\"\n", optarg);
195 main_config.name = optarg;
199 main_config.debug_memory = true;
203 main_config.memory_report = true;
204 main_config.debug_memory = true;
211 port = strtoul(optarg, 0, 10);
212 if ((port == 0) || (port > UINT16_MAX)) {
213 fprintf(stderr, "radiusd: Invalid port number \"%s\"\n", optarg);
217 main_config.port = (uint16_t) port;
223 /* Force the PID to be written, even in -f mode */
224 main_config.write_pid = true;
227 case 's': /* Single process mode */
229 main_config.daemonize = false;
232 case 't': /* no child threads */
237 display_version = true;
242 main_config.daemonize = false;
244 main_config.log_auth = true;
245 main_config.log_auth_badpass = true;
246 main_config.log_auth_goodpass = true;
249 default_log.dst = L_DST_STDOUT;
250 default_log.fd = STDOUT_FILENO;
264 * Mismatch between the binary and the libraries it depends on.
266 if (fr_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) {
267 fr_perror("radiusd");
271 if (rad_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) exit(EXIT_FAILURE);
274 * Mismatch between build time OpenSSL and linked SSL, better to die
275 * here than segfault later.
277 #ifdef HAVE_OPENSSL_CRYPTO_H
278 if (ssl_check_consistency() < 0) exit(EXIT_FAILURE);
281 if (flag && (flag != 0x03)) {
282 fprintf(stderr, "radiusd: The options -i and -p cannot be used individually.\n");
287 * According to the talloc peeps, no two threads may modify any part of
288 * a ctx tree with a common root without synchronisation.
290 * So we can't run with a null context and threads.
292 if (main_config.memory_report) {
294 fprintf(stderr, "radiusd: The server cannot produce memory reports (-M) in threaded mode\n");
297 talloc_enable_null_tracking();
299 talloc_disable_null_tracking();
303 * Better here, so it doesn't matter whether we get passed -xv or -vx.
305 if (display_version) {
306 /* Don't print timestamps */
309 default_log.dst = L_DST_STDOUT;
310 default_log.fd = STDOUT_FILENO;
312 INFO("%s: %s", progname, radiusd_version);
317 if (rad_debug_lvl) version_print();
320 * Under linux CAP_SYS_PTRACE is usually only available before setuid/setguid,
321 * so we need to check whether we can attach before calling those functions
322 * (in main_config_init()).
324 fr_store_debug_state();
327 * Initialising OpenSSL once, here, is safer than having individual modules do it.
329 #ifdef HAVE_OPENSSL_CRYPTO_H
334 * Write the PID always if we're running as a daemon.
336 if (main_config.daemonize) main_config.write_pid = true;
339 * Read the configuration files, BEFORE doing anything else.
341 if (main_config_init() < 0) exit(EXIT_FAILURE);
344 * This is very useful in figuring out why the panic_action didn't fire.
346 INFO("%s", fr_debug_state_to_msg(fr_debug_state));
349 * Check for vulnerabilities in the version of libssl were linked against.
351 #if defined(HAVE_OPENSSL_CRYPTO_H) && defined(ENABLE_OPENSSL_VERSION_CHECK)
352 if (tls_global_version_check(main_config.allow_vulnerable_openssl) < 0) exit(EXIT_FAILURE);
355 fr_talloc_fault_setup();
358 * Set the panic action (if required)
361 char const *panic_action = NULL;
363 panic_action = getenv("PANIC_ACTION");
364 if (!panic_action) panic_action = main_config.panic_action;
366 if (panic_action && (fr_fault_setup(panic_action, argv[0]) < 0)) {
367 fr_perror("radiusd");
374 * Disconnect from session
376 if (main_config.daemonize) {
381 * Really weird things happen if we leave stdin open and call things like
384 devnull = open("/dev/null", O_RDWR);
386 ERROR("Failed opening /dev/null: %s", fr_syserror(errno));
389 dup2(devnull, STDIN_FILENO);
393 if (pipe(from_child) != 0) {
394 ERROR("Couldn't open pipe for child status: %s", fr_syserror(errno));
400 ERROR("Couldn't fork: %s", fr_syserror(errno));
405 * The parent exits, so the child can run in the background.
407 * As the child can still encounter an error during initialisation
408 * we do a blocking read on a pipe between it and the parent.
410 * Just before entering the event loop the child will send a success
411 * or failure message to the parent, via the pipe.
417 /* So the pipe is correctly widowed if the child exits */
418 close(from_child[1]);
421 * The child writes a 0x01 byte on success, and closes
424 if ((read(from_child[0], &ret, 1) < 0)) {
428 /* For cleanliness... */
429 close(from_child[0]);
431 /* Don't turn children into zombies */
433 waitpid(pid, &stat_loc, WNOHANG);
440 /* so the pipe is correctly widowed if the parent exits?! */
441 close(from_child[0]);
449 * Ensure that we're using the CORRECT pid after forking, NOT the one
452 radius_pid = getpid();
455 * Initialize any event loops just enough so module instantiations can
456 * add fd/event to them, but do not start them yet.
458 * This has to be done post-fork in case we're using kqueue, where the
459 * queue isn't inherited by the child process.
461 if (!radius_event_init(autofree)) exit(EXIT_FAILURE);
466 if (modules_init(main_config.config) < 0) exit(EXIT_FAILURE);
469 * Redirect stderr/stdout as appropriate.
471 if (radlog_init(&default_log, main_config.daemonize) < 0) {
472 ERROR("%s", fr_strerror());
476 event_loop_started = true;
479 * Start the event loop(s) and threads.
481 radius_event_start(main_config.config, spawn_flag);
484 * Now that we've set everything up, we can install the signal
485 * handlers. Before this, if we get any signal, we don't know
486 * what to do, so we might as well do the default, and die.
489 signal(SIGPIPE, SIG_IGN);
492 if ((fr_set_signal(SIGHUP, sig_hup) < 0) ||
493 (fr_set_signal(SIGTERM, sig_fatal) < 0)) {
494 ERROR("%s", fr_strerror());
499 * If we're debugging, then a CTRL-C will cause the server to die
500 * immediately. Use SIGTERM to shut down the server cleanly in
503 if (main_config.debug_memory || (rad_debug_lvl == 0)) {
504 if ((fr_set_signal(SIGINT, sig_fatal) < 0)
506 || (fr_set_signal(SIGQUIT, sig_fatal) < 0)
509 ERROR("%s", fr_strerror());
515 * Everything seems to have loaded OK, exit gracefully.
518 DEBUG("Configuration appears to be OK");
521 if (main_config.debug_memory) goto cleanup;
527 radius_stats_init(0);
531 * Write the PID after we've forked, so that we write the correct one.
533 if (main_config.write_pid) {
536 fp = fopen(main_config.pid_file, "w");
539 * @fixme What about following symlinks,
540 * and having it over-write a normal file?
542 fprintf(fp, "%d\n", (int) radius_pid);
545 ERROR("Failed creating PID file %s: %s", main_config.pid_file, fr_syserror(errno));
550 exec_trigger(NULL, NULL, "server.start", false);
553 * Inform the parent (who should still be waiting) that the rest of
554 * initialisation went OK, and that it should exit with a 0 status.
555 * If we don't get this far, then we just close the pipe on exit, and the
556 * parent gets a read failure.
558 if (main_config.daemonize) {
559 if (write(from_child[1], "\001", 1) < 0) {
560 WARN("Failed informing parent of successful start: %s",
563 close(from_child[1]);
567 * Clear the libfreeradius error buffer.
572 * Initialise the state rbtree (used to link multiple rounds of challenges).
574 state = fr_state_init(NULL);
577 * Process requests until HUP or exit.
579 while ((status = radius_event_process()) == 0x80) {
581 radius_stats_init(1);
586 ERROR("Exiting due to internal error: %s", fr_strerror());
587 rcode = EXIT_FAILURE;
589 INFO("Exiting normally");
593 * Ignore the TERM signal: we're about to die.
595 signal(SIGTERM, SIG_IGN);
598 * Fire signal and stop triggers after ignoring SIGTERM, so handlers are
599 * not killed with the rest of the process group, below.
601 if (status == 2) exec_trigger(NULL, NULL, "server.signal.term", true);
602 exec_trigger(NULL, NULL, "server.stop", false);
605 * Send a TERM signal to all associated processes
606 * (including us, which gets ignored.)
609 if (spawn_flag) kill(-radius_pid, SIGTERM);
613 * We're exiting, so we can delete the PID file.
614 * (If it doesn't exist, we can ignore the error returned by unlink)
616 if (main_config.daemonize) unlink(main_config.pid_file);
622 * Detach any modules.
626 xlat_free(); /* modules may have xlat's */
628 fr_state_delete(state);
631 * Free the configuration items.
639 #ifdef HAVE_OPENSSL_CRYPTO_H
640 tls_global_cleanup();
644 * So we don't see autofreed memory in the talloc report
646 talloc_free(autofree);
648 if (main_config.memory_report) {
649 INFO("Allocated memory at time of report:");
650 fr_log_talloc_report(NULL);
658 * Display the syntax for starting this program.
660 static void NEVER_RETURNS usage(int status)
662 FILE *output = status?stderr:stdout;
664 fprintf(output, "Usage: %s [options]\n", progname);
665 fprintf(output, "Options:\n");
666 fprintf(output, " -C Check configuration and exit.\n");
667 fprintf(stderr, " -d <raddb> Set configuration directory (defaults to " RADDBDIR ").\n");
668 fprintf(stderr, " -D <dictdir> Set main dictionary directory (defaults to " DICTDIR ").\n");
669 fprintf(output, " -f Run as a foreground process, not a daemon.\n");
670 fprintf(output, " -h Print this help message.\n");
671 fprintf(output, " -i <ipaddr> Listen on ipaddr ONLY.\n");
672 fprintf(output, " -l <log_file> Logging output will be written to this file.\n");
673 fprintf(output, " -m On SIGINT or SIGQUIT exit cleanly instead of immediately.\n");
674 fprintf(output, " -n <name> Read raddb/name.conf instead of raddb/radiusd.conf.\n");
675 fprintf(output, " -p <port> Listen on port ONLY.\n");
676 fprintf(output, " -P Always write out PID, even with -f.\n");
677 fprintf(output, " -s Do not spawn child processes to handle requests.\n");
678 fprintf(output, " -t Disable threads.\n");
679 fprintf(output, " -v Print server version information.\n");
680 fprintf(output, " -X Turn on full debugging.\n");
681 fprintf(output, " -x Turn on additional debugging. (-xx gives more debugging).\n");
687 * We got a fatal signal.
689 static void sig_fatal(int sig)
691 if (getpid() != radius_pid) _exit(sig);
695 radius_signal_self(RADIUS_SIGNAL_SELF_TERM);
702 if (main_config.debug_memory || main_config.memory_report) {
703 radius_signal_self(RADIUS_SIGNAL_SELF_TERM);
715 * We got the hangup signal.
716 * Re-read the configuration files.
718 static void sig_hup(UNUSED int sig)
720 reset_signal(SIGHUP, sig_hup);
722 radius_signal_self(RADIUS_SIGNAL_SELF_HUP);