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"
1564 if (rad_verify(packet, original, secret) < 0) {
1565 radlog(L_ERR, "%s Dropping packet without response.", librad_errstr);
1566 /* Since accounting packets get this set in
1567 * request_reject but no response is sent...
1569 request->options |= RAD_REQUEST_OPTION_REJECTED;
1570 goto finished_request;
1573 if (rad_decode(packet, original, secret) < 0) {
1574 radlog(L_ERR, "%s", librad_errstr);
1575 request_reject(request);
1576 goto finished_request;
1581 * For proxy replies, remove non-allowed
1582 * attributes from the list of VP's.
1584 if (request->proxy) {
1586 rcode = proxy_receive(request);
1588 default: /* Don't Do Anything */
1590 case RLM_MODULE_FAIL:
1591 /* on error just continue with next request */
1593 case RLM_MODULE_HANDLED:
1594 /* if this was a replicated request, mark it as
1595 * finished first, because it was postponed
1597 goto finished_request;
1602 * This is the initial incoming request which
1605 * Some requests do NOT get cached, as they
1606 * CANNOT possibly have duplicates. Set the
1607 * magic option here.
1609 * Status-Server messages are easy to generate,
1610 * so we toss them as soon as we see a reply.
1612 * Accounting-Request packets WITHOUT an
1613 * Acct-Delay-Time attribute are NEVER
1614 * duplicated, as RFC 2866 Section 4.1 says that
1615 * the Acct-Delay-Time MUST be updated when the
1616 * packet is re-sent, which means the packet
1617 * changes, so it MUST have a new identifier and
1618 * Request Authenticator. */
1619 if ((request->packet->code == PW_STATUS_SERVER) ||
1620 ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1621 (pairfind(request->packet->vps, PW_ACCT_DELAY_TIME) == NULL))) {
1622 request->options |= RAD_REQUEST_OPTION_DONT_CACHE;
1628 * We should have a User-Name attribute now.
1630 if (request->username == NULL) {
1631 request->username = pairfind(request->packet->vps,
1636 * FIXME: All this lowercase/nospace junk will be moved
1637 * into a module after module failover is fully in place
1639 * See if we have to lower user/pass before processing
1641 if(strcmp(mainconfig.do_lower_user, "before") == 0)
1642 rad_lowerpair(request, request->username);
1643 if(strcmp(mainconfig.do_lower_pass, "before") == 0)
1644 rad_lowerpair(request,
1645 pairfind(request->packet->vps, PW_PASSWORD));
1647 if(strcmp(mainconfig.do_nospace_user, "before") == 0)
1648 rad_rmspace_pair(request, request->username);
1649 if(strcmp(mainconfig.do_nospace_pass, "before") == 0)
1650 rad_rmspace_pair(request,
1651 pairfind(request->packet->vps, PW_PASSWORD));
1656 * If the request took too long to process, don't do
1659 if (request->options & RAD_REQUEST_OPTION_REJECTED) {
1661 goto postpone_request;
1665 * Reprocess if we rejected last time
1667 if ((fun == rad_authenticate) &&
1668 (request->reply->code == PW_AUTHENTICATION_REJECT)) {
1669 /* See if we have to lower user/pass after processing */
1670 if (strcmp(mainconfig.do_lower_user, "after") == 0) {
1671 rad_lowerpair(request, request->username);
1674 if (strcmp(mainconfig.do_lower_pass, "after") == 0) {
1675 rad_lowerpair(request,
1676 pairfind(request->packet->vps, PW_PASSWORD));
1679 if (strcmp(mainconfig.do_nospace_user, "after") == 0) {
1680 rad_rmspace_pair(request, request->username);
1683 if (strcmp(mainconfig.do_nospace_pass, "after") == 0) {
1684 rad_rmspace_pair(request,
1685 pairfind(request->packet->vps, PW_PASSWORD));
1690 * If we're re-processing the request, re-set it.
1693 pairfree(&request->config_items);
1694 pairfree(&request->reply->vps);
1695 request->reply->code = 0;
1701 * Status-Server requests NEVER get proxied.
1703 if (mainconfig.proxy_requests) {
1704 if ((request->packet->code != PW_STATUS_SERVER) &&
1705 ((request->options & RAD_REQUEST_OPTION_PROXIED) == 0)) {
1709 * Try to proxy this request.
1711 rcode = proxy_send(request);
1718 * There was an error trying to proxy the request.
1719 * Drop it on the floor.
1721 case RLM_MODULE_FAIL:
1722 DEBUG2("Error trying to proxy request %d: Rejecting it", request->number);
1723 request_reject(request);
1724 goto finished_request;
1728 * The pre-proxy module has decided to reject
1729 * the request. Do so.
1731 case RLM_MODULE_REJECT:
1732 DEBUG2("Request %d rejected in proxy_send.", request->number);
1733 request_reject(request);
1734 goto finished_request;
1738 * If the proxy code has handled the request,
1739 * then postpone more processing, until we get
1740 * the reply packet from the home server.
1742 case RLM_MODULE_HANDLED:
1743 goto postpone_request;
1748 * Else rcode==RLM_MODULE_NOOP
1749 * and the proxy code didn't do anything, so
1750 * we continue handling the request here.
1753 } else if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
1754 (request->reply->code == 0)) {
1756 * We're not configured to reply to the packet,
1757 * and we're not proxying, so the DEFAULT behaviour
1758 * is to REJECT the user.
1760 DEBUG2("There was no response configured: rejecting request %d", request->number);
1761 request_reject(request);
1762 goto finished_request;
1766 * If we have a reply to send, copy the Proxy-State
1767 * attributes from the request to the tail of the reply,
1768 * and send the packet.
1770 rad_assert(request->magic == REQUEST_MAGIC);
1771 if (request->reply->code != 0) {
1772 VALUE_PAIR *vp = NULL;
1775 * Perform RFC limitations on outgoing replies.
1777 rfc_clean(request->reply);
1780 * Need to copy Proxy-State from request->packet->vps
1782 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1783 if (vp) pairadd(&(request->reply->vps), vp);
1786 * If the request isn't an authentication reject, OR
1787 * it's a reject, but the reject_delay is zero, then
1788 * send it immediately.
1790 * Otherwise, delay the authentication reject to shut
1793 if ((request->reply->code != PW_AUTHENTICATION_REJECT) ||
1794 (mainconfig.reject_delay == 0)) {
1796 * Send the response. IF it's a real request.
1798 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0) {
1799 rad_send(request->reply, request->packet,
1803 * Otherwise, it's a tunneled request.
1804 * Don't do anything.
1807 DEBUG2("Delaying request %d for %d seconds",
1808 request->number, mainconfig.reject_delay);
1809 request->options |= RAD_REQUEST_OPTION_DELAYED_REJECT;
1814 * We're done processing the request, set the
1815 * request to be finished, clean up as necessary,
1816 * and forget about the request.
1822 * Don't decode the packet if it's an internal "fake"
1823 * request. Instead, just skip ahead to processing it.
1825 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1830 * We're done handling the request. Free up the linked
1831 * lists of value pairs. This might take a long time,
1832 * so it's more efficient to do it in a child thread,
1833 * instead of in the main handler when it eventually
1834 * gets around to deleting the request.
1836 * Also, no one should be using these items after the
1837 * request is finished, and the reply is sent. Cleaning
1838 * them up here ensures that they're not being used again.
1840 * Hmm... cleaning them up in the child thread also seems
1841 * to make the server run more efficiently!
1843 * If we've delayed the REJECT, then do NOT clean up the request,
1844 * as we haven't created the REJECT message yet.
1846 if ((request->options & RAD_REQUEST_OPTION_DELAYED_REJECT) == 0) {
1847 if (request->packet) {
1848 pairfree(&request->packet->vps);
1849 request->username = NULL;
1850 request->password = NULL;
1854 * If we've sent a reply to the NAS, then this request is
1855 * pretty much finished, and we have no more need for any
1856 * of the value-pair's in it, including the proxy stuff.
1858 if (request->reply->code != 0) {
1859 pairfree(&request->reply->vps);
1863 pairfree(&request->config_items);
1864 if (request->proxy) {
1865 pairfree(&request->proxy->vps);
1867 if (request->proxy_reply) {
1868 pairfree(&request->proxy_reply->vps);
1872 DEBUG2("Finished request %d", request->number);
1876 * Go to the next request, without marking
1877 * the current one as finished.
1879 * Hmm... this may not be the brightest thing to do.
1882 DEBUG2("Going to the next request");
1885 #ifdef HAVE_PTHREAD_H
1887 * We are finished with the child thread. The thread is detached,
1888 * so that when it exits, there's nothing more for the server
1891 * If we're running with thread pools, then this frees up the
1892 * thread in the pool for another request.
1894 request->child_pid = NO_SUCH_CHILD_PID;
1896 request->finished = finished; /* do as the LAST thing before exiting */
1902 * Display the syntax for starting this program.
1904 static void NEVER_RETURNS usage(int status)
1906 FILE *output = status?stderr:stdout;
1909 "Usage: %s [-a acct_dir] [-d db_dir] [-l log_dir] [-i address] [-p port] [-AcfnsSvXxyz]\n", progname);
1910 fprintf(output, "Options:\n\n");
1911 fprintf(output, " -a acct_dir use accounting directory 'acct_dir'.\n");
1912 fprintf(output, " -A Log auth detail.\n");
1913 fprintf(output, " -d db_dir Use database directory 'db_dir'.\n");
1914 fprintf(output, " -f Run as a foreground process, not a daemon.\n");
1915 fprintf(output, " -h Print this help message.\n");
1916 fprintf(output, " -i address Listen only in the given IP address.\n");
1917 fprintf(output, " -l log_dir Log messages to 'log_dir'. Special values are:\n");
1918 fprintf(output, " stdout == log all messages to standard output.\n");
1919 fprintf(output, " syslog == log all messages to the system logger.\n");
1920 fprintf(output, " -p port Bind to 'port', and not to the radius/udp, or 1646/udp.\n");
1921 fprintf(output, " -s Do not spawn child processes to handle requests.\n");
1922 fprintf(output, " -S Log stripped names.\n");
1923 fprintf(output, " -v Print server version information.\n");
1924 fprintf(output, " -X Turn on full debugging. (Means: -sfxxyz -l stdout)\n");
1925 fprintf(output, " -x Turn on partial debugging. (-xx gives more debugging).\n");
1926 fprintf(output, " -y Log authentication failures, with password.\n");
1927 fprintf(output, " -z Log authentication successes, with password.\n");
1933 * We got a fatal signal.
1935 static void sig_fatal(int sig)
1949 * We got the hangup signal.
1950 * Re-read the configuration files.
1953 static void sig_hup(int sig)
1955 sig = sig; /* -Wunused */
1956 reset_signal(SIGHUP, sig_hup);
1959 * Only do the reload if we're the main server, both
1960 * for processes, and for threads.
1962 if (getpid() == radius_pid) {
1966 if (mainconfig.do_snmp) {
1967 rad_snmp.smux_failures = 0;
1968 rad_snmp.smux_event = SMUX_CONNECT;
1975 * Process and reply to a server-status request.
1976 * Like rad_authenticate and rad_accounting this should
1977 * live in it's own file but it's so small we don't bother.
1979 static int rad_status_server(REQUEST *request)
1986 * Reply with an ACK. We might want to add some more
1987 * interesting reply attributes, such as server uptime.
1989 t = request->timestamp - start_time;
1990 sprintf(reply_msg, "FreeRADIUS up %d day%s, %02d:%02d",
1991 (int)(t / 86400), (t / 86400) == 1 ? "" : "s",
1992 (int)((t / 3600) % 24), (int)(t / 60) % 60);
1993 request->reply->code = PW_AUTHENTICATION_ACK;
1995 vp = pairmake("Reply-Message", reply_msg, T_OP_SET);
1996 pairadd(&request->reply->vps, vp); /* don't need to check if !vp */