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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * Copyright 2000,2001,2002,2003,2004 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>
28 /* don't look here for the version, run radiusd -v or look in version.c */
29 static const char rcsid[] =
33 #include "libradius.h"
37 #ifdef HAVE_NETINET_IN_H
38 # include <netinet/in.h>
56 #ifdef HAVE_SYS_SELECT_H
57 # include <sys/select.h>
64 #ifdef HAVE_SYS_WAIT_H
65 # include <sys/wait.h>
68 # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
71 # define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
75 #include "rad_assert.h"
78 #include "request_list.h"
79 #include "radius_snmp.h"
84 const char *progname = NULL;
85 const char *radius_dir = NULL;
86 const char *radacct_dir = NULL;
87 const char *radlog_dir = NULL;
88 radlog_dest_t radlog_dest = RADLOG_FILES;
89 const char *radlib_dir = NULL;
91 int log_stripped_names;
93 int log_auth_detail = FALSE;
94 int need_reload = FALSE;
95 int sig_hup_block = FALSE;
96 const char *radiusd_version = "FreeRADIUS Version " RADIUSD_VERSION ", for host " HOSTINFO ", built on " __DATE__ " at " __TIME__;
98 static time_t time_now;
99 static pid_t radius_pid;
102 * Configuration items.
104 static int dont_fork = FALSE;
105 static time_t start_time = 0;
106 static int spawn_flag = TRUE;
107 static int do_exit = 0;
112 static void usage(int);
114 static void sig_fatal (int);
115 static void sig_hup (int);
117 static int rad_status_server(REQUEST *request);
120 * Parse a string into a syslog facility level.
122 static int str2fac(const char *s)
125 if(!strcmp(s, "kern"))
130 if(!strcmp(s, "user"))
135 if(!strcmp(s, "mail"))
140 if(!strcmp(s, "daemon"))
145 if(!strcmp(s, "auth"))
150 if(!strcmp(s, "auth"))
155 if(!strcmp(s, "lpr"))
160 if(!strcmp(s, "news"))
165 if(!strcmp(s, "uucp"))
170 if(!strcmp(s, "cron"))
175 if(!strcmp(s, "authpriv"))
180 if(!strcmp(s, "ftp"))
185 if(!strcmp(s, "local0"))
190 if(!strcmp(s, "local1"))
195 if(!strcmp(s, "local2"))
200 if(!strcmp(s, "local3"))
205 if(!strcmp(s, "local4"))
210 if(!strcmp(s, "local5"))
215 if(!strcmp(s, "local6"))
220 if(!strcmp(s, "local7"))
225 fprintf(stderr, "%s: Error: Unknown syslog facility: %s\n",
230 /* this should never be reached */
236 * Check if an incoming request is "ok"
238 * It takes packets, not requests. It sees if the packet looks
239 * OK. If so, it does a number of sanity checks on it.
241 static RAD_REQUEST_FUNP packet_ok(RADIUS_PACKET *packet,
242 rad_listen_t *listener)
245 RAD_REQUEST_FUNP fun = NULL;
248 * Some sanity checks, based on the packet code.
250 switch(packet->code) {
251 case PW_AUTHENTICATION_REQUEST:
253 * Check for requests sent to the wrong
254 * port, and ignore them, if so.
256 if (listener->type != RAD_LISTEN_AUTH) {
257 RAD_SNMP_INC(rad_snmp.auth.total_packets_dropped);
258 radlog(L_ERR, "Authentication-Request sent to a non-authentication port from "
259 "client %s:%d - ID %d : IGNORED",
260 client_name(packet->src_ipaddr),
261 packet->src_port, packet->id);
264 fun = rad_authenticate;
267 case PW_ACCOUNTING_REQUEST:
269 * Check for requests sent to the wrong
270 * port, and ignore them, if so.
272 if (listener->type != RAD_LISTEN_ACCT) {
273 RAD_SNMP_INC(rad_snmp.acct.total_packets_dropped);
274 radlog(L_ERR, "Accounting-Request packet sent to a non-accounting port from "
275 "client %s:%d - ID %d : IGNORED",
276 client_name(packet->src_ipaddr),
277 packet->src_port, packet->id);
280 fun = rad_accounting;
283 case PW_AUTHENTICATION_ACK:
284 case PW_ACCESS_CHALLENGE:
285 case PW_AUTHENTICATION_REJECT:
287 * Replies NOT sent to the proxy port get
288 * an error message logged, and the
291 if (listener->type != RAD_LISTEN_PROXY) {
292 RAD_SNMP_INC(rad_snmp.auth.total_packets_dropped);
293 radlog(L_ERR, "Authentication reply packet code %d sent to a non-proxy reply port from "
294 "client %s:%d - ID %d : IGNORED",
296 client_name(packet->src_ipaddr),
297 packet->src_port, packet->id);
300 fun = rad_authenticate;
303 case PW_ACCOUNTING_RESPONSE:
305 * Replies NOT sent to the proxy port get
306 * an error message logged, and the
309 if (listener->type != RAD_LISTEN_PROXY) {
310 RAD_SNMP_INC(rad_snmp.acct.total_packets_dropped);
311 radlog(L_ERR, "Accounting reply packet code %d sent to a non-proxy reply port from "
312 "client %s:%d - ID %d : IGNORED",
314 client_name(packet->src_ipaddr),
315 packet->src_port, packet->id);
318 fun = rad_accounting;
321 case PW_STATUS_SERVER:
322 if (!mainconfig.status_server) {
323 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
326 fun = rad_status_server;
329 case PW_PASSWORD_REQUEST:
330 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
333 * We don't support this anymore.
335 radlog(L_ERR, "Deprecated password change request from client %s:%d - ID %d : IGNORED",
336 client_name(packet->src_ipaddr),
337 packet->src_port, packet->id);
342 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
344 radlog(L_ERR, "Unknown packet code %d from client %s:%d "
345 "- ID %d : IGNORED", packet->code,
346 client_name(packet->src_ipaddr),
347 packet->src_port, packet->id);
351 } /* switch over packet types */
354 * Don't handle proxy replies here. They need to
355 * return the *old* request, so we can re-process it.
357 if (listener->type == RAD_LISTEN_PROXY) {
362 * If there is no existing request of id, code, etc.,
363 * then we can return, and let it be processed.
365 if ((curreq = rl_find(packet)) == NULL) {
367 * Count the total number of requests, to see if
368 * there are too many. If so, return with an
371 if (mainconfig.max_requests) {
372 int request_count = rl_num_requests();
375 * This is a new request. Let's see if
376 * it makes us go over our configured
379 if (request_count > mainconfig.max_requests) {
380 radlog(L_ERR, "Dropping request (%d is too many): "
381 "from client %s:%d - ID: %d", request_count,
382 client_name(packet->src_ipaddr),
383 packet->src_port, packet->id);
384 radlog(L_INFO, "WARNING: Please check the radiusd.conf file.\n"
385 "\tThe value for 'max_requests' is probably set too low.\n");
387 } /* else there were a small number of requests */
388 } /* else there was no configured limit for requests */
391 * FIXME: Add checks for system load. If the
392 * system is busy, start dropping requests...
394 * We can probably keep some statistics
395 * ourselves... if there are more requests
396 * coming in than we can handle, start dropping
404 * "fake" requests MUST NEVER be in the request list.
406 * They're used internally in the server. Any reply
407 * is a reply to the local server, and any proxied packet
408 * gets sent outside of the tunnel.
410 rad_assert((curreq->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0);
413 * The current request isn't finished, which
414 * means that the NAS sent us a new packet, while
415 * we are still processing the old request.
417 if (!curreq->finished) {
419 * If the authentication vectors are identical,
420 * then the NAS is re-transmitting it, trying to
421 * kick us into responding to the request.
423 if (memcmp(curreq->packet->vector, packet->vector,
424 sizeof(packet->vector)) == 0) {
425 RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
428 * It's not finished because the request
429 * was proxied, but there was no reply
430 * from the home server.
432 if (curreq->proxy && !curreq->proxy_reply) {
434 * We're taking care of sending
435 * duplicate proxied packets, so
436 * we ignore any duplicate
437 * requests from the NAS.
439 * FIXME: Make it ALWAYS synchronous!
441 if (!mainconfig.proxy_synchronous) {
442 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
444 DEBUG2("Ignoring duplicate packet from client "
445 "%s:%d - ID: %d, due to outstanding proxied request %d.",
446 client_name(packet->src_ipaddr),
447 packet->src_port, packet->id,
452 * We ARE proxying the request,
453 * and we have NOT received a
454 * proxy reply yet, and we ARE
455 * doing synchronous proxying.
457 * In that case, go kick
458 * the home RADIUS server
464 DEBUG2("Sending duplicate proxied request to home server %s:%d - ID: %d",
465 ip_ntoa(buffer, curreq->proxy->dst_ipaddr),
466 curreq->proxy->dst_port,
470 curreq->proxy_next_try = time_now + mainconfig.proxy_retry_delay;
471 rad_send(curreq->proxy, curreq->packet,
472 curreq->proxysecret);
474 } /* else the packet was not proxied */
477 * Someone's still working on it, so we
478 * ignore the duplicate request.
480 radlog(L_ERR, "Discarding duplicate request from "
481 "client %s:%d - ID: %d due to unfinished request %d",
482 client_name(packet->src_ipaddr),
483 packet->src_port, packet->id,
486 } /* else the authentication vectors were different */
489 * The authentication vectors are different, so
490 * the NAS has given up on us, as we've taken too
491 * long to process the request. This is a
494 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
496 radlog(L_ERR, "Dropping conflicting packet from "
497 "client %s:%d - ID: %d due to unfinished request %d",
498 client_name(packet->src_ipaddr),
499 packet->src_port, packet->id,
505 * The old request is finished. We now check the
506 * authentication vectors. If the client has sent us a
507 * request with identical code && ID, but different
508 * vector, then they MUST have gotten our response, so we
509 * can delete the original request, and process the new
512 * If the vectors are the same, then it's a duplicate
513 * request, and we can send a duplicate reply.
515 if (memcmp(curreq->packet->vector, packet->vector,
516 sizeof(packet->vector)) == 0) {
517 RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
520 * If the packet has been delayed, then silently
521 * send a response, and clear the delayed flag.
523 * Note that this means if the NAS kicks us while
524 * we're delaying a reject, then the reject may
525 * be sent sooner than otherwise.
527 * This COULD be construed as a bug. Maybe what
528 * we want to do is to ignore the duplicate
529 * packet, and send the reject later.
531 if (curreq->options & RAD_REQUEST_OPTION_DELAYED_REJECT) {
532 curreq->options &= ~RAD_REQUEST_OPTION_DELAYED_REJECT;
533 rad_send(curreq->reply, curreq->packet, curreq->secret);
538 * Maybe we've saved a reply packet. If so,
539 * re-send it. Otherwise, just complain.
541 if (curreq->reply->code != 0) {
542 DEBUG2("Sending duplicate reply "
543 "to client %s:%d - ID: %d",
544 client_name(packet->src_ipaddr),
545 packet->src_port, packet->id);
546 rad_send(curreq->reply, curreq->packet, curreq->secret);
551 * Else we never sent a reply to the NAS,
552 * as we decided somehow we didn't like the request.
554 * This shouldn't happen, in general...
556 DEBUG2("Discarding duplicate request from client %s:%d - ID: %d",
557 client_name(packet->src_ipaddr),
558 packet->src_port, packet->id);
560 } /* else the vectors were different, so we discard the old request. */
563 * 'packet' has the same source IP, source port, code,
564 * and Id as 'curreq', but a different authentication
565 * vector. We can therefore delete 'curreq', as we were
566 * only keeping it around to send out duplicate replies,
567 * if the first reply got lost in the network.
572 * The request is OK. We can process it...
574 * Don't bother checking the maximum nubmer of requests
575 * here. we've just deleted one, so we KNOW we're under
576 * the limit if we add one more.
583 * Do a proxy check of the REQUEST list when using the new proxy code.
585 static REQUEST *proxy_ok(RADIUS_PACKET *packet)
592 * Find the original request in the request list
594 oldreq = rl_find_proxy(packet);
597 * If we haven't found the original request which was
598 * sent, to get this reply. Complain, and discard this
599 * request, as there's no way for us to send it to a NAS.
602 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s:%d - ID %d",
603 ip_ntoa(buffer, packet->src_ipaddr),
604 packet->src_port, packet->id);
609 * The proxy reply has arrived too late, as the original
610 * (old) request has timed out, been rejected, and marked
611 * as finished. The client has already received a
612 * response, so there is nothing that can be done. Delete
613 * the tardy reply from the home server, and return NULL.
615 if ((oldreq->reply->code != 0) ||
616 (oldreq->finished)) {
617 radlog(L_ERR, "Reply from home server %s:%d - ID: %d arrived too late for request %d. Try increasing 'retry_delay' or 'max_request_time'",
618 ip_ntoa(buffer, packet->src_ipaddr),
619 packet->src_port, packet->id,
625 * If there is already a reply, maybe this one is a
628 if (oldreq->proxy_reply) {
629 if (memcmp(oldreq->proxy_reply->vector,
631 sizeof(oldreq->proxy_reply->vector)) == 0) {
632 radlog(L_ERR, "Discarding duplicate reply from home server %s:%d - ID: %d for request %d",
633 ip_ntoa(buffer, packet->src_ipaddr),
634 packet->src_port, packet->id,
638 * ? The home server gave us a new *
639 * proxy reply, which doesn't match * the
642 DEBUG2("Ignoring conflicting proxy reply");
646 * We've already received a reply, so
647 * we discard this one, as we don't want
648 * to do duplicate work.
651 } /* else there wasn't a proxy reply yet, so we can process it */
654 * Refresh the old request, and update it with the proxy
657 * ? Can we delete the proxy request here? * Is there
658 * any more need for it?
660 * FIXME: we probably shouldn't be updating the time
663 oldreq->timestamp = time_now;
664 oldreq->proxy_reply = packet;
667 * Now that we've verified the packet IS actually
668 * from that realm, and not forged, we can go mark the
669 * realms for this home server as active.
671 * If we had done this check in the 'find realm by IP address'
672 * function, then an attacker could force us to use a home
673 * server which was inactive, by forging reply packets
674 * which didn't match any request. We would think that
675 * the reply meant the home server was active, would
676 * re-activate the realms, and THEN bounce the packet
679 for (cl = mainconfig.realms; cl != NULL; cl = cl->next) {
680 if (oldreq->proxy_reply->src_ipaddr == cl->ipaddr) {
681 if (oldreq->proxy_reply->src_port == cl->auth_port) {
683 cl->last_reply = oldreq->timestamp;
684 } else if (oldreq->proxy_reply->src_port == cl->acct_port) {
685 cl->acct_active = TRUE;
686 cl->last_reply = oldreq->timestamp;
695 * Do more checks, this time on the REQUEST data structure.
697 * The main purpose of this code is to handle proxied requests.
699 static REQUEST *request_ok(RADIUS_PACKET *packet, uint8_t *secret,
700 rad_listen_t *listener)
702 REQUEST *request = NULL;
705 * If the request has come in on the proxy FD, then
706 * it's a proxy reply, so pass it through the code which
707 * tries to find the original request, which we should
708 * process, rather than processing the reply as a "new"
711 if (listener->type == RAD_LISTEN_PROXY) {
713 * Find the old request, based on the current
716 request = proxy_ok(packet);
720 rad_assert(request->magic == REQUEST_MAGIC);
723 * We must have passed through the code below
724 * for the original request, which adds the
725 * reply packet to it.
727 rad_assert(request->reply != NULL);
729 } else { /* remember the new request */
731 * A unique per-request counter.
733 static int request_num_counter = 0;
735 request = request_alloc(); /* never fails */
736 request->packet = packet;
737 request->number = request_num_counter++;
738 strNcpy(request->secret, (char *)secret,
739 sizeof(request->secret));
742 * Remember the request.
747 * ADD IN "server identifier" from "listen"
752 * The request passes many of our sanity checks.
753 * From here on in, if anything goes wrong, we
754 * send a reject message, instead of dropping the
757 * Build the reply template from the request
760 rad_assert(request->reply == NULL);
761 if ((request->reply = rad_alloc(0)) == NULL) {
762 radlog(L_ERR, "No memory");
765 request->reply->sockfd = request->packet->sockfd;
766 request->reply->dst_ipaddr = request->packet->src_ipaddr;
767 request->reply->src_ipaddr = request->packet->dst_ipaddr;
768 request->reply->dst_port = request->packet->src_port;
769 request->reply->src_port = request->packet->dst_port;
770 request->reply->id = request->packet->id;
771 request->reply->code = 0; /* UNKNOWN code */
772 memcpy(request->reply->vector, request->packet->vector,
773 sizeof(request->reply->vector));
774 request->reply->vps = NULL;
775 request->reply->data = NULL;
776 request->reply->data_len = 0;
786 int main(int argc, char *argv[])
789 RADIUS_PACKET *packet;
791 unsigned char buffer[4096];
797 struct timeval *tv = NULL;
798 #ifdef HAVE_SIGACTION
799 struct sigaction act;
801 rad_listen_t *listener;
803 syslog_facility = LOG_DAEMON;
806 set_auth_parameters(argc,argv);
809 if ((progname = strrchr(argv[0], '/')) == NULL)
816 radius_dir = strdup(RADIUS_DIR);
819 * Ensure that the configuration is initialized.
821 memset(&mainconfig, 0, sizeof(mainconfig));
822 #ifdef HAVE_SIGACTION
823 memset(&act, 0, sizeof(act));
825 sigemptyset( &act.sa_mask ) ;
828 /* Process the options. */
829 while ((argval = getopt(argc, argv, "Aa:bcd:fg:hi:l:p:sSvxXyz")) != EOF) {
834 log_auth_detail = TRUE;
838 if (radacct_dir) xfree(radacct_dir);
839 radacct_dir = strdup(optarg);
843 /* ignore for backwards compatibility with Cistron */
847 if (radius_dir) xfree(radius_dir);
848 radius_dir = strdup(optarg);
860 if ((mainconfig.myip = ip_getaddr(optarg)) == INADDR_NONE) {
861 fprintf(stderr, "radiusd: %s: host unknown\n",
868 radlog_dir = strdup(optarg);
872 * We should also have this as a configuration
876 syslog_facility = str2fac(optarg);
880 log_stripped_names++;
884 fprintf(stderr, "Ignoring deprecated command-line option -p");
887 case 's': /* Single process mode */
897 * BIG debugging mode for users who are
898 * TOO LAZY to type '-sfxxyz -l stdout' themselves.
904 mainconfig.log_auth = TRUE;
905 mainconfig.log_auth_badpass = TRUE;
906 mainconfig.log_auth_goodpass = TRUE;
907 radlog_dir = strdup("stdout");
915 mainconfig.log_auth = TRUE;
916 mainconfig.log_auth_badpass = TRUE;
920 mainconfig.log_auth_badpass = TRUE;
921 mainconfig.log_auth_goodpass = TRUE;
933 radius_pid = getpid();
935 /* Read the configuration files, BEFORE doing anything else. */
936 if (read_mainconfig(0) < 0) {
941 * If we're NOT debugging, trap fatal signals, so we can
942 * easily clean up after ourselves.
944 * If we ARE debugging, don't trap them, so we can
947 if ((mainconfig.allow_core_dumps == FALSE) && (debug_flag == 0)) {
949 #ifdef HAVE_SIGACTION
950 act.sa_handler = sig_fatal;
951 sigaction(SIGSEGV, &act, NULL);
953 signal(SIGSEGV, sig_fatal);
958 /* Reload the modules. */
959 DEBUG2("radiusd: entering modules setup");
960 if (setup_modules() < 0) {
961 radlog(L_ERR|L_CONS, "Errors setting up modules");
967 * If they asked for syslog, then give it to them.
968 * Also, initialize the logging facility with the
969 * configuration that they asked for.
971 if (strcmp(radlog_dir, "syslog") == 0) {
972 openlog(progname, LOG_PID, syslog_facility);
973 radlog_dest = RADLOG_SYSLOG;
975 /* Do you want a warning if -g is used without a -l to activate it? */
977 if (strcmp(radlog_dir, "stdout") == 0) {
978 radlog_dest = RADLOG_STDOUT;
979 } else if (strcmp(radlog_dir, "stderr") == 0) {
980 radlog_dest = RADLOG_STDERR;
983 /* Initialize the request list. */
987 * Register built-in compare functions.
989 pair_builtincompare_init();
992 if (mainconfig.do_snmp) radius_snmp_init();
996 * Disconnect from session
998 if (debug_flag == 0 && dont_fork == FALSE) {
1001 radlog(L_ERR|L_CONS, "Couldn't fork");
1006 * The parent exits, so the child can run in the background.
1017 * Ensure that we're using the CORRECT pid after forking,
1018 * NOT the one we started with.
1020 radius_pid = getpid();
1024 * Only write the PID file if we're running as a daemon.
1026 * And write it AFTER we've forked, so that we write the
1029 if (dont_fork == FALSE) {
1032 fp = fopen(mainconfig.pid_file, "w");
1035 * FIXME: What about following symlinks,
1036 * and having it over-write a normal file?
1038 fprintf(fp, "%d\n", (int) radius_pid);
1041 radlog(L_ERR|L_CONS, "Failed creating PID file %s: %s\n",
1042 mainconfig.pid_file, strerror(errno));
1048 * If we're running as a daemon, close the default file
1049 * descriptors, AFTER forking.
1051 if (debug_flag == FALSE) {
1054 devnull = open("/dev/null", O_RDWR);
1056 radlog(L_ERR|L_CONS, "Failed opening /dev/null: %s\n",
1060 dup2(devnull, STDIN_FILENO);
1061 dup2(devnull, STDOUT_FILENO);
1062 dup2(devnull, STDERR_FILENO);
1066 #ifdef HAVE_PTHREAD_H
1068 * If we're spawning children, set up the thread pool.
1070 if (spawn_flag == TRUE) {
1075 * Without threads, we ALWAYS run in single-server mode.
1081 * Use linebuffered or unbuffered stdout if
1082 * the debug flag is on.
1084 if (debug_flag == TRUE)
1088 * Print out which ports we're listening on.
1090 for (listener = mainconfig.listen;
1092 listener = listener->next) {
1093 if (listener->ipaddr == INADDR_ANY) {
1094 strcpy((char *)buffer, "*");
1096 ip_ntoa((char *)buffer, listener->ipaddr);
1099 switch (listener->type) {
1100 case RAD_LISTEN_AUTH:
1101 DEBUG("Listening on authentication %s:%d",
1102 buffer, listener->port);
1105 case RAD_LISTEN_ACCT:
1106 DEBUG("Listening on accounting %s:%d",
1107 buffer, listener->port);
1110 case RAD_LISTEN_PROXY:
1111 DEBUG("Listening on proxy %s:%d",
1112 buffer, listener->port);
1121 * Now that we've set everything up, we can install the signal
1122 * handlers. Before this, if we get any signal, we don't know
1123 * what to do, so we might as well do the default, and die.
1125 signal(SIGPIPE, SIG_IGN);
1126 #ifdef HAVE_SIGACTION
1127 act.sa_handler = sig_hup;
1128 sigaction(SIGHUP, &act, NULL);
1129 act.sa_handler = sig_fatal;
1130 sigaction(SIGTERM, &act, NULL);
1132 signal(SIGHUP, sig_hup);
1133 signal(SIGTERM, sig_fatal);
1136 * If we're debugging, then a CTRL-C will cause the
1137 * server to die immediately. Use SIGTERM to shut down
1138 * the server cleanly in that case.
1140 if (debug_flag == 0) {
1141 #ifdef HAVE_SIGACTION
1142 act.sa_handler = sig_fatal;
1143 sigaction(SIGINT, &act, NULL);
1144 sigaction(SIGQUIT, &act, NULL);
1146 signal(SIGINT, sig_fatal);
1147 signal(SIGQUIT, sig_fatal);
1151 radlog(L_INFO, "Ready to process requests.");
1152 start_time = time(NULL);
1155 * Receive user requests
1159 * If we've been told to exit, then do so,
1160 * even if we have data waiting.
1163 DEBUG("Exiting...");
1166 * Ignore the TERM signal: we're about
1169 signal(SIGTERM, SIG_IGN);
1172 * Send a TERM signal to all associated
1173 * processes (including us, which gets
1176 kill(-radius_pid, SIGTERM);
1179 * FIXME: Kill child threads, and
1184 * Detach any modules.
1189 * FIXME: clean up any active REQUEST
1194 * We're exiting, so we can delete the PID
1195 * file. (If it doesn't exist, we can ignore
1196 * the error returned by unlink)
1198 if (dont_fork == FALSE) {
1199 unlink(mainconfig.pid_file);
1203 * Free the configuration items.
1208 * SIGTERM gets do_exit=0,
1209 * and we want to exit cleanly.
1211 * Other signals make us exit
1212 * with an error status.
1218 #ifdef HAVE_PTHREAD_H
1220 * Threads: wait for all threads to stop
1221 * processing before re-loading the
1222 * config, so we don't pull the rug out
1226 if (spawn_flag) for(;;) {
1228 * Block until there are '0' threads
1229 * with a REQUEST handle.
1231 sig_hup_block = TRUE;
1232 if( (total_active_threads() == 0) ||
1234 sig_hup_block = FALSE;
1241 if (read_mainconfig(TRUE) < 0) {
1245 /* Reload the modules. */
1246 DEBUG2("radiusd: entering modules setup");
1247 if (setup_modules() < 0) {
1248 radlog(L_ERR|L_CONS, "Errors setting up modules");
1252 need_reload = FALSE;
1253 radlog(L_INFO, "Ready to process requests.");
1260 * Loop over all the listening FD's.
1262 for (listener = mainconfig.listen;
1264 listener = listener->next) {
1265 FD_SET(listener->fd, &readfds);
1266 if (listener->fd > max_fd) max_fd = listener->fd;
1270 if (mainconfig.do_snmp &&
1271 (rad_snmp.smux_fd >= 0)) {
1272 FD_SET(rad_snmp.smux_fd, &readfds);
1273 if (rad_snmp.smux_fd > max_fd) max_fd = rad_snmp.smux_fd;
1276 status = select(max_fd + 1, &readfds, NULL, NULL, tv);
1279 * On interrupts, we clean up the request
1280 * list. We then continue with the loop,
1281 * so that if we're supposed to exit,
1282 * then the code at the start of the loop
1283 * catches that, and exits.
1285 if (errno == EINTR) {
1286 tv = rl_clean_list(time(NULL));
1289 radlog(L_ERR, "Unexpected error in select(): %s",
1294 time_now = time(NULL);
1295 #ifndef HAVE_PTHREAD_H
1297 * If there are no child threads, then there may
1298 * be child processes. In that case, wait for
1299 * their exit status, and throw that exit status
1300 * away. This helps get rid of zxombie children.
1302 while (waitpid(-1, &argval, WNOHANG) > 0) {
1308 * Loop over the open socket FD's, reading any data.
1310 for (listener = mainconfig.listen;
1312 listener = listener->next) {
1313 RAD_REQUEST_FUNP fun;
1315 if (!FD_ISSET(listener->fd, &readfds))
1318 * Receive the packet.
1320 if (sig_hup_block != FALSE) {
1323 packet = rad_recv(listener->fd);
1324 if (packet == NULL) {
1325 radlog(L_ERR, "%s", librad_errstr);
1330 * If the destination IP is unknown, check
1331 * if the listener has a known IP. If so,
1334 if ((packet->dst_ipaddr == htonl(INADDR_ANY)) &&
1335 (packet->dst_ipaddr != listener->ipaddr)) {
1336 packet->dst_ipaddr = listener->ipaddr;
1340 * Fill in the destination port.
1342 packet->dst_port = listener->port;
1344 RAD_SNMP_TYPE_INC(listener, total_requests);
1347 * FIXME: Move this next check into
1348 * the packet_ok() function, and add
1349 * a 'secret' to the RAIDUS_PACKET
1350 * data structure. This involves changing
1351 * a bunch of code, but it's probably the
1356 * Check if we know this client for
1357 * authentication and accounting. Check if we know
1358 * this proxy for proxying.
1360 if (listener->type != RAD_LISTEN_PROXY) {
1362 if ((cl = client_find(packet->src_ipaddr)) == NULL) {
1363 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
1365 radlog(L_ERR, "Ignoring request from unknown client %s:%d",
1366 ip_ntoa((char *)buffer, packet->src_ipaddr),
1371 secret = cl->secret;
1372 } else { /* It came in on the proxy port */
1374 if ((rl = realm_findbyaddr(packet->src_ipaddr,packet->src_port)) == NULL) {
1375 radlog(L_ERR, "Ignoring request from unknown home server %s:%d",
1376 ip_ntoa((char *)buffer, packet->src_ipaddr),
1383 * The secret isn't needed here,
1384 * as it's already in the old request
1390 * Do some simple checks before we process
1393 if ((fun = packet_ok(packet, listener)) == NULL) {
1399 * Allocate a new request for packets from
1400 * our clients, OR find the old request,
1401 * for packets which are replies from a home
1404 request = request_ok(packet, secret, listener);
1411 * Drop the request into the thread pool,
1412 * and let the thread pool take care of
1413 * doing something with it.
1415 #ifdef HAVE_PTHREAD_H
1417 if (!thread_pool_addrequest(request, fun)) {
1419 * FIXME: Maybe just drop
1420 * the packet on the floor?
1422 request_reject(request);
1423 request->finished = TRUE;
1427 rad_respond(request, fun);
1428 } /* loop over listening sockets*/
1431 if (mainconfig.do_snmp) {
1433 * After handling all authentication/accounting
1434 * requests, THEN process any pending SMUX/SNMP
1437 * Note that the handling is done in the main server,
1438 * which probably isn't a Good Thing. It really
1439 * should be wrapped, and handled in a thread pool.
1441 if ((rad_snmp.smux_fd >= 0) &&
1442 FD_ISSET(rad_snmp.smux_fd, &readfds) &&
1443 (rad_snmp.smux_event == SMUX_READ)) {
1448 * If we've got to re-connect, then do so now,
1449 * before calling select again.
1451 if (rad_snmp.smux_event == SMUX_CONNECT) {
1458 * After processing all new requests,
1459 * check if we've got to delete old requests
1460 * from the request list.
1462 tv = rl_clean_list(time_now);
1463 #ifdef HAVE_PTHREAD_H
1466 * Only clean the thread pool if we're spawning
1470 thread_pool_clean(time_now);
1475 } /* loop forever */
1480 * FIXME: The next two functions should all
1481 * be in a module. But not until we have
1482 * more control over module execution.
1487 * Lowercase the string value of a pair.
1489 static int rad_lowerpair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1494 rad_lowercase((char *)vp->strvalue);
1495 DEBUG2("rad_lowerpair: %s now '%s'", vp->name, vp->strvalue);
1500 * Remove spaces in a pair.
1502 static int rad_rmspace_pair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1507 rad_rmspace((char *)vp->strvalue);
1508 vp->length = strlen((char *)vp->strvalue);
1509 DEBUG2("rad_rmspace_pair: %s now '%s'", vp->name, vp->strvalue);
1515 * Respond to a request packet.
1517 * Maybe we reply, maybe we don't.
1518 * Maybe we proxy the request to another server, or else maybe
1519 * we replicate it to another server.
1521 int rad_respond(REQUEST *request, RAD_REQUEST_FUNP fun)
1523 RADIUS_PACKET *packet, *original;
1525 int finished = FALSE;
1528 rad_assert(request->magic == REQUEST_MAGIC);
1531 * Don't decode the packet if it's an internal "fake"
1532 * request. Instead, just skip ahead to processing it.
1534 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1539 * Put the decoded packet into it's proper place.
1541 if (request->proxy_reply != NULL) {
1542 packet = request->proxy_reply;
1543 secret = request->proxysecret;
1544 original = request->proxy;
1546 packet = request->packet;
1547 secret = request->secret;
1552 * Decode the packet, verifying it's signature,
1553 * and parsing the attributes into structures.
1555 * Note that we do this CPU-intensive work in
1556 * a child thread, not the master. This helps to
1557 * spread the load a little bit.
1559 * Internal requests (ones that never go on the
1560 * wire) have ->data==NULL (data is the wire
1561 * format) and don't need to be "decoded"
1563 if (packet->data && rad_decode(packet, original, secret) != 0) {
1564 radlog(L_ERR, "%s", librad_errstr);
1565 request_reject(request);
1566 goto finished_request;
1570 * For proxy replies, remove non-allowed
1571 * attributes from the list of VP's.
1573 if (request->proxy) {
1575 rcode = proxy_receive(request);
1577 default: /* Don't Do Anything */
1579 case RLM_MODULE_FAIL:
1580 /* on error just continue with next request */
1582 case RLM_MODULE_HANDLED:
1583 /* if this was a replicated request, mark it as
1584 * finished first, because it was postponed
1586 goto finished_request;
1591 * This is the initial incoming request which
1594 * Some requests do NOT get cached, as they
1595 * CANNOT possibly have duplicates. Set the
1596 * magic option here.
1598 * Status-Server messages are easy to generate,
1599 * so we toss them as soon as we see a reply.
1601 * Accounting-Request packets WITHOUT an
1602 * Acct-Delay-Time attribute are NEVER
1603 * duplicated, as RFC 2866 Section 4.1 says that
1604 * the Acct-Delay-Time MUST be updated when the
1605 * packet is re-sent, which means the packet
1606 * changes, so it MUST have a new identifier and
1607 * Request Authenticator. */
1608 if ((request->packet->code == PW_STATUS_SERVER) ||
1609 ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1610 (pairfind(request->packet->vps, PW_ACCT_DELAY_TIME) == NULL))) {
1611 request->options |= RAD_REQUEST_OPTION_DONT_CACHE;
1617 * We should have a User-Name attribute now.
1619 if (request->username == NULL) {
1620 request->username = pairfind(request->packet->vps,
1625 * FIXME: All this lowercase/nospace junk will be moved
1626 * into a module after module failover is fully in place
1628 * See if we have to lower user/pass before processing
1630 if(strcmp(mainconfig.do_lower_user, "before") == 0)
1631 rad_lowerpair(request, request->username);
1632 if(strcmp(mainconfig.do_lower_pass, "before") == 0)
1633 rad_lowerpair(request,
1634 pairfind(request->packet->vps, PW_PASSWORD));
1636 if(strcmp(mainconfig.do_nospace_user, "before") == 0)
1637 rad_rmspace_pair(request, request->username);
1638 if(strcmp(mainconfig.do_nospace_pass, "before") == 0)
1639 rad_rmspace_pair(request,
1640 pairfind(request->packet->vps, PW_PASSWORD));
1645 * If the request took too long to process, don't do
1648 if (request->options & RAD_REQUEST_OPTION_REJECTED) {
1650 goto postpone_request;
1654 * Reprocess if we rejected last time
1656 if ((fun == rad_authenticate) &&
1657 (request->reply->code == PW_AUTHENTICATION_REJECT)) {
1658 /* See if we have to lower user/pass after processing */
1659 if (strcmp(mainconfig.do_lower_user, "after") == 0) {
1660 rad_lowerpair(request, request->username);
1663 if (strcmp(mainconfig.do_lower_pass, "after") == 0) {
1664 rad_lowerpair(request,
1665 pairfind(request->packet->vps, PW_PASSWORD));
1668 if (strcmp(mainconfig.do_nospace_user, "after") == 0) {
1669 rad_rmspace_pair(request, request->username);
1672 if (strcmp(mainconfig.do_nospace_pass, "after") == 0) {
1673 rad_rmspace_pair(request,
1674 pairfind(request->packet->vps, PW_PASSWORD));
1679 * If we're re-processing the request, re-set it.
1682 pairfree(&request->config_items);
1683 pairfree(&request->reply->vps);
1684 request->reply->code = 0;
1690 * Status-Server requests NEVER get proxied.
1692 if (mainconfig.proxy_requests) {
1693 if ((request->packet->code != PW_STATUS_SERVER) &&
1694 ((request->options & RAD_REQUEST_OPTION_PROXIED) == 0)) {
1698 * Try to proxy this request.
1700 rcode = proxy_send(request);
1707 * There was an error trying to proxy the request.
1708 * Drop it on the floor.
1710 case RLM_MODULE_FAIL:
1711 DEBUG2("Error trying to proxy request %d: Rejecting it", request->number);
1712 request_reject(request);
1713 goto finished_request;
1717 * The pre-proxy module has decided to reject
1718 * the request. Do so.
1720 case RLM_MODULE_REJECT:
1721 DEBUG2("Request %d rejected in proxy_send.", request->number);
1722 request_reject(request);
1723 goto finished_request;
1727 * If the proxy code has handled the request,
1728 * then postpone more processing, until we get
1729 * the reply packet from the home server.
1731 case RLM_MODULE_HANDLED:
1732 goto postpone_request;
1737 * Else rcode==RLM_MODULE_NOOP
1738 * and the proxy code didn't do anything, so
1739 * we continue handling the request here.
1742 } else if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
1743 (request->reply->code == 0)) {
1745 * We're not configured to reply to the packet,
1746 * and we're not proxying, so the DEFAULT behaviour
1747 * is to REJECT the user.
1749 DEBUG2("There was no response configured: rejecting request %d", request->number);
1750 request_reject(request);
1751 goto finished_request;
1755 * If we have a reply to send, copy the Proxy-State
1756 * attributes from the request to the tail of the reply,
1757 * and send the packet.
1759 rad_assert(request->magic == REQUEST_MAGIC);
1760 if (request->reply->code != 0) {
1761 VALUE_PAIR *vp = NULL;
1764 * Perform RFC limitations on outgoing replies.
1766 rfc_clean(request->reply);
1769 * Need to copy Proxy-State from request->packet->vps
1771 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1772 if (vp) pairadd(&(request->reply->vps), vp);
1775 * If the request isn't an authentication reject, OR
1776 * it's a reject, but the reject_delay is zero, then
1777 * send it immediately.
1779 * Otherwise, delay the authentication reject to shut
1782 if ((request->reply->code != PW_AUTHENTICATION_REJECT) ||
1783 (mainconfig.reject_delay == 0)) {
1785 * Send the response. IF it's a real request.
1787 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0) {
1788 rad_send(request->reply, request->packet,
1792 * Otherwise, it's a tunneled request.
1793 * Don't do anything.
1796 DEBUG2("Delaying request %d for %d seconds",
1797 request->number, mainconfig.reject_delay);
1798 request->options |= RAD_REQUEST_OPTION_DELAYED_REJECT;
1803 * We're done processing the request, set the
1804 * request to be finished, clean up as necessary,
1805 * and forget about the request.
1811 * Don't decode the packet if it's an internal "fake"
1812 * request. Instead, just skip ahead to processing it.
1814 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1819 * We're done handling the request. Free up the linked
1820 * lists of value pairs. This might take a long time,
1821 * so it's more efficient to do it in a child thread,
1822 * instead of in the main handler when it eventually
1823 * gets around to deleting the request.
1825 * Also, no one should be using these items after the
1826 * request is finished, and the reply is sent. Cleaning
1827 * them up here ensures that they're not being used again.
1829 * Hmm... cleaning them up in the child thread also seems
1830 * to make the server run more efficiently!
1832 * If we've delayed the REJECT, then do NOT clean up the request,
1833 * as we haven't created the REJECT message yet.
1835 if ((request->options & RAD_REQUEST_OPTION_DELAYED_REJECT) == 0) {
1836 if (request->packet) {
1837 pairfree(&request->packet->vps);
1838 request->username = NULL;
1839 request->password = NULL;
1843 * If we've sent a reply to the NAS, then this request is
1844 * pretty much finished, and we have no more need for any
1845 * of the value-pair's in it, including the proxy stuff.
1847 if (request->reply->code != 0) {
1848 pairfree(&request->reply->vps);
1852 pairfree(&request->config_items);
1853 if (request->proxy) {
1854 pairfree(&request->proxy->vps);
1856 if (request->proxy_reply) {
1857 pairfree(&request->proxy_reply->vps);
1861 DEBUG2("Finished request %d", request->number);
1865 * Go to the next request, without marking
1866 * the current one as finished.
1868 * Hmm... this may not be the brightest thing to do.
1871 DEBUG2("Going to the next request");
1874 #ifdef HAVE_PTHREAD_H
1876 * We are finished with the child thread. The thread is detached,
1877 * so that when it exits, there's nothing more for the server
1880 * If we're running with thread pools, then this frees up the
1881 * thread in the pool for another request.
1883 request->child_pid = NO_SUCH_CHILD_PID;
1885 request->finished = finished; /* do as the LAST thing before exiting */
1891 * Display the syntax for starting this program.
1893 static void NEVER_RETURNS usage(int status)
1895 FILE *output = status?stderr:stdout;
1898 "Usage: %s [-a acct_dir] [-d db_dir] [-l log_dir] [-i address] [-p port] [-AcfnsSvXxyz]\n", progname);
1899 fprintf(output, "Options:\n\n");
1900 fprintf(output, " -a acct_dir use accounting directory 'acct_dir'.\n");
1901 fprintf(output, " -A Log auth detail.\n");
1902 fprintf(output, " -d db_dir Use database directory 'db_dir'.\n");
1903 fprintf(output, " -f Run as a foreground process, not a daemon.\n");
1904 fprintf(output, " -h Print this help message.\n");
1905 fprintf(output, " -i address Listen only in the given IP address.\n");
1906 fprintf(output, " -l log_dir Log messages to 'log_dir'. Special values are:\n");
1907 fprintf(output, " stdout == log all messages to standard output.\n");
1908 fprintf(output, " syslog == log all messages to the system logger.\n");
1909 fprintf(output, " -p port Bind to 'port', and not to the radius/udp, or 1646/udp.\n");
1910 fprintf(output, " -s Do not spawn child processes to handle requests.\n");
1911 fprintf(output, " -S Log stripped names.\n");
1912 fprintf(output, " -v Print server version information.\n");
1913 fprintf(output, " -X Turn on full debugging. (Means: -sfxxyz -l stdout)\n");
1914 fprintf(output, " -x Turn on partial debugging. (-xx gives more debugging).\n");
1915 fprintf(output, " -y Log authentication failures, with password.\n");
1916 fprintf(output, " -z Log authentication successes, with password.\n");
1922 * We got a fatal signal.
1924 static void sig_fatal(int sig)
1938 * We got the hangup signal.
1939 * Re-read the configuration files.
1942 static void sig_hup(int sig)
1944 sig = sig; /* -Wunused */
1945 reset_signal(SIGHUP, sig_hup);
1948 * Only do the reload if we're the main server, both
1949 * for processes, and for threads.
1951 if (getpid() == radius_pid) {
1955 if (mainconfig.do_snmp) {
1956 rad_snmp.smux_failures = 0;
1957 rad_snmp.smux_event = SMUX_CONNECT;
1964 * Process and reply to a server-status request.
1965 * Like rad_authenticate and rad_accounting this should
1966 * live in it's own file but it's so small we don't bother.
1968 static int rad_status_server(REQUEST *request)
1975 * Reply with an ACK. We might want to add some more
1976 * interesting reply attributes, such as server uptime.
1978 t = request->timestamp - start_time;
1979 sprintf(reply_msg, "FreeRADIUS up %d day%s, %02d:%02d",
1980 (int)(t / 86400), (t / 86400) == 1 ? "" : "s",
1981 (int)((t / 3600) % 24), (int)(t / 60) % 60);
1982 request->reply->code = PW_AUTHENTICATION_ACK;
1984 vp = pairmake("Reply-Message", reply_msg, T_OP_SET);
1985 pairadd(&request->reply->vps, vp); /* don't need to check if !vp */