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;
108 static int debug_memory = 0;
113 static void usage(int);
115 static void sig_fatal (int);
116 static void sig_hup (int);
118 static int rad_status_server(REQUEST *request);
121 * Parse a string into a syslog facility level.
123 static int str2fac(const char *s)
126 if(!strcmp(s, "kern"))
131 if(!strcmp(s, "user"))
136 if(!strcmp(s, "mail"))
141 if(!strcmp(s, "daemon"))
146 if(!strcmp(s, "auth"))
151 if(!strcmp(s, "auth"))
156 if(!strcmp(s, "lpr"))
161 if(!strcmp(s, "news"))
166 if(!strcmp(s, "uucp"))
171 if(!strcmp(s, "cron"))
176 if(!strcmp(s, "authpriv"))
181 if(!strcmp(s, "ftp"))
186 if(!strcmp(s, "local0"))
191 if(!strcmp(s, "local1"))
196 if(!strcmp(s, "local2"))
201 if(!strcmp(s, "local3"))
206 if(!strcmp(s, "local4"))
211 if(!strcmp(s, "local5"))
216 if(!strcmp(s, "local6"))
221 if(!strcmp(s, "local7"))
226 fprintf(stderr, "%s: Error: Unknown syslog facility: %s\n",
231 /* this should never be reached */
237 * Check if an incoming request is "ok"
239 * It takes packets, not requests. It sees if the packet looks
240 * OK. If so, it does a number of sanity checks on it.
242 static RAD_REQUEST_FUNP packet_ok(RADIUS_PACKET *packet,
243 rad_listen_t *listener)
246 RAD_REQUEST_FUNP fun = NULL;
249 * Some sanity checks, based on the packet code.
251 switch(packet->code) {
252 case PW_AUTHENTICATION_REQUEST:
254 * Check for requests sent to the wrong
255 * port, and ignore them, if so.
257 if (listener->type != RAD_LISTEN_AUTH) {
258 RAD_SNMP_INC(rad_snmp.auth.total_packets_dropped);
259 radlog(L_ERR, "Authentication-Request sent to a non-authentication port from "
260 "client %s:%d - ID %d : IGNORED",
261 client_name(packet->src_ipaddr),
262 packet->src_port, packet->id);
265 fun = rad_authenticate;
268 case PW_ACCOUNTING_REQUEST:
270 * Check for requests sent to the wrong
271 * port, and ignore them, if so.
273 if (listener->type != RAD_LISTEN_ACCT) {
274 RAD_SNMP_INC(rad_snmp.acct.total_packets_dropped);
275 radlog(L_ERR, "Accounting-Request packet sent to a non-accounting port from "
276 "client %s:%d - ID %d : IGNORED",
277 client_name(packet->src_ipaddr),
278 packet->src_port, packet->id);
281 fun = rad_accounting;
284 case PW_AUTHENTICATION_ACK:
285 case PW_ACCESS_CHALLENGE:
286 case PW_AUTHENTICATION_REJECT:
288 * Replies NOT sent to the proxy port get
289 * an error message logged, and the
292 if (listener->type != RAD_LISTEN_PROXY) {
293 RAD_SNMP_INC(rad_snmp.auth.total_packets_dropped);
294 radlog(L_ERR, "Authentication reply packet code %d sent to a non-proxy reply port from "
295 "client %s:%d - ID %d : IGNORED",
297 client_name(packet->src_ipaddr),
298 packet->src_port, packet->id);
301 fun = rad_authenticate;
304 case PW_ACCOUNTING_RESPONSE:
306 * Replies NOT sent to the proxy port get
307 * an error message logged, and the
310 if (listener->type != RAD_LISTEN_PROXY) {
311 RAD_SNMP_INC(rad_snmp.acct.total_packets_dropped);
312 radlog(L_ERR, "Accounting reply packet code %d sent to a non-proxy reply port from "
313 "client %s:%d - ID %d : IGNORED",
315 client_name(packet->src_ipaddr),
316 packet->src_port, packet->id);
319 fun = rad_accounting;
322 case PW_STATUS_SERVER:
323 if (!mainconfig.status_server) {
324 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
327 fun = rad_status_server;
330 case PW_PASSWORD_REQUEST:
331 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
334 * We don't support this anymore.
336 radlog(L_ERR, "Deprecated password change request from client %s:%d - ID %d : IGNORED",
337 client_name(packet->src_ipaddr),
338 packet->src_port, packet->id);
343 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
345 radlog(L_ERR, "Unknown packet code %d from client %s:%d "
346 "- ID %d : IGNORED", packet->code,
347 client_name(packet->src_ipaddr),
348 packet->src_port, packet->id);
352 } /* switch over packet types */
355 * Don't handle proxy replies here. They need to
356 * return the *old* request, so we can re-process it.
358 if (listener->type == RAD_LISTEN_PROXY) {
363 * If there is no existing request of id, code, etc.,
364 * then we can return, and let it be processed.
366 if ((curreq = rl_find(packet)) == NULL) {
368 * Count the total number of requests, to see if
369 * there are too many. If so, return with an
372 if (mainconfig.max_requests) {
373 int request_count = rl_num_requests();
376 * This is a new request. Let's see if
377 * it makes us go over our configured
380 if (request_count > mainconfig.max_requests) {
381 radlog(L_ERR, "Dropping request (%d is too many): "
382 "from client %s:%d - ID: %d", request_count,
383 client_name(packet->src_ipaddr),
384 packet->src_port, packet->id);
385 radlog(L_INFO, "WARNING: Please check the radiusd.conf file.\n"
386 "\tThe value for 'max_requests' is probably set too low.\n");
388 } /* else there were a small number of requests */
389 } /* else there was no configured limit for requests */
392 * FIXME: Add checks for system load. If the
393 * system is busy, start dropping requests...
395 * We can probably keep some statistics
396 * ourselves... if there are more requests
397 * coming in than we can handle, start dropping
405 * "fake" requests MUST NEVER be in the request list.
407 * They're used internally in the server. Any reply
408 * is a reply to the local server, and any proxied packet
409 * gets sent outside of the tunnel.
411 rad_assert((curreq->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0);
414 * The current request isn't finished, which
415 * means that the NAS sent us a new packet, while
416 * we are still processing the old request.
418 if (!curreq->finished) {
420 * If the authentication vectors are identical,
421 * then the NAS is re-transmitting it, trying to
422 * kick us into responding to the request.
424 if (memcmp(curreq->packet->vector, packet->vector,
425 sizeof(packet->vector)) == 0) {
426 RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
429 * It's not finished because the request
430 * was proxied, but there was no reply
431 * from the home server.
433 if (curreq->proxy && !curreq->proxy_reply) {
435 * We're taking care of sending
436 * duplicate proxied packets, so
437 * we ignore any duplicate
438 * requests from the NAS.
440 * FIXME: Make it ALWAYS synchronous!
442 if (!mainconfig.proxy_synchronous) {
443 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
445 DEBUG2("Ignoring duplicate packet from client "
446 "%s:%d - ID: %d, due to outstanding proxied request %d.",
447 client_name(packet->src_ipaddr),
448 packet->src_port, packet->id,
453 * We ARE proxying the request,
454 * and we have NOT received a
455 * proxy reply yet, and we ARE
456 * doing synchronous proxying.
458 * In that case, go kick
459 * the home RADIUS server
465 DEBUG2("Sending duplicate proxied request to home server %s:%d - ID: %d",
466 ip_ntoa(buffer, curreq->proxy->dst_ipaddr),
467 curreq->proxy->dst_port,
471 curreq->proxy_next_try = time_now + mainconfig.proxy_retry_delay;
472 rad_send(curreq->proxy, curreq->packet,
473 curreq->proxysecret);
475 } /* else the packet was not proxied */
478 * Someone's still working on it, so we
479 * ignore the duplicate request.
481 radlog(L_ERR, "Discarding duplicate request from "
482 "client %s:%d - ID: %d due to unfinished request %d",
483 client_name(packet->src_ipaddr),
484 packet->src_port, packet->id,
487 } /* else the authentication vectors were different */
490 * The authentication vectors are different, so
491 * the NAS has given up on us, as we've taken too
492 * long to process the request. This is a
495 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
497 radlog(L_ERR, "Dropping conflicting packet from "
498 "client %s:%d - ID: %d due to unfinished request %d",
499 client_name(packet->src_ipaddr),
500 packet->src_port, packet->id,
506 * The old request is finished. We now check the
507 * authentication vectors. If the client has sent us a
508 * request with identical code && ID, but different
509 * vector, then they MUST have gotten our response, so we
510 * can delete the original request, and process the new
513 * If the vectors are the same, then it's a duplicate
514 * request, and we can send a duplicate reply.
516 if (memcmp(curreq->packet->vector, packet->vector,
517 sizeof(packet->vector)) == 0) {
518 RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
521 * If the packet has been delayed, then silently
522 * send a response, and clear the delayed flag.
524 * Note that this means if the NAS kicks us while
525 * we're delaying a reject, then the reject may
526 * be sent sooner than otherwise.
528 * This COULD be construed as a bug. Maybe what
529 * we want to do is to ignore the duplicate
530 * packet, and send the reject later.
532 if (curreq->options & RAD_REQUEST_OPTION_DELAYED_REJECT) {
533 curreq->options &= ~RAD_REQUEST_OPTION_DELAYED_REJECT;
534 rad_send(curreq->reply, curreq->packet, curreq->secret);
539 * Maybe we've saved a reply packet. If so,
540 * re-send it. Otherwise, just complain.
542 if (curreq->reply->code != 0) {
543 DEBUG2("Sending duplicate reply "
544 "to client %s:%d - ID: %d",
545 client_name(packet->src_ipaddr),
546 packet->src_port, packet->id);
547 rad_send(curreq->reply, curreq->packet, curreq->secret);
552 * Else we never sent a reply to the NAS,
553 * as we decided somehow we didn't like the request.
555 * This shouldn't happen, in general...
557 DEBUG2("Discarding duplicate request from client %s:%d - ID: %d",
558 client_name(packet->src_ipaddr),
559 packet->src_port, packet->id);
561 } /* else the vectors were different, so we discard the old request. */
564 * 'packet' has the same source IP, source port, code,
565 * and Id as 'curreq', but a different authentication
566 * vector. We can therefore delete 'curreq', as we were
567 * only keeping it around to send out duplicate replies,
568 * if the first reply got lost in the network.
573 * The request is OK. We can process it...
575 * Don't bother checking the maximum nubmer of requests
576 * here. we've just deleted one, so we KNOW we're under
577 * the limit if we add one more.
584 * Do a proxy check of the REQUEST list when using the new proxy code.
586 static REQUEST *proxy_ok(RADIUS_PACKET *packet)
593 * Find the original request in the request list
595 oldreq = rl_find_proxy(packet);
598 * If we haven't found the original request which was
599 * sent, to get this reply. Complain, and discard this
600 * request, as there's no way for us to send it to a NAS.
603 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s:%d - ID %d",
604 ip_ntoa(buffer, packet->src_ipaddr),
605 packet->src_port, packet->id);
610 * The proxy reply has arrived too late, as the original
611 * (old) request has timed out, been rejected, and marked
612 * as finished. The client has already received a
613 * response, so there is nothing that can be done. Delete
614 * the tardy reply from the home server, and return NULL.
616 if ((oldreq->reply->code != 0) ||
617 (oldreq->finished)) {
618 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'",
619 ip_ntoa(buffer, packet->src_ipaddr),
620 packet->src_port, packet->id,
626 * If there is already a reply, maybe this one is a
629 if (oldreq->proxy_reply) {
630 if (memcmp(oldreq->proxy_reply->vector,
632 sizeof(oldreq->proxy_reply->vector)) == 0) {
633 radlog(L_ERR, "Discarding duplicate reply from home server %s:%d - ID: %d for request %d",
634 ip_ntoa(buffer, packet->src_ipaddr),
635 packet->src_port, packet->id,
639 * ? The home server gave us a new *
640 * proxy reply, which doesn't match * the
643 DEBUG2("Ignoring conflicting proxy reply");
647 * We've already received a reply, so
648 * we discard this one, as we don't want
649 * to do duplicate work.
652 } /* else there wasn't a proxy reply yet, so we can process it */
655 * Refresh the old request, and update it with the proxy
658 * ? Can we delete the proxy request here? * Is there
659 * any more need for it?
661 * FIXME: we probably shouldn't be updating the time
664 oldreq->timestamp = time_now;
665 oldreq->proxy_reply = packet;
668 * Now that we've verified the packet IS actually
669 * from that realm, and not forged, we can go mark the
670 * realms for this home server as active.
672 * If we had done this check in the 'find realm by IP address'
673 * function, then an attacker could force us to use a home
674 * server which was inactive, by forging reply packets
675 * which didn't match any request. We would think that
676 * the reply meant the home server was active, would
677 * re-activate the realms, and THEN bounce the packet
680 for (cl = mainconfig.realms; cl != NULL; cl = cl->next) {
681 if (oldreq->proxy_reply->src_ipaddr == cl->ipaddr) {
682 if (oldreq->proxy_reply->src_port == cl->auth_port) {
684 cl->last_reply = oldreq->timestamp;
685 } else if (oldreq->proxy_reply->src_port == cl->acct_port) {
686 cl->acct_active = TRUE;
687 cl->last_reply = oldreq->timestamp;
696 * Do more checks, this time on the REQUEST data structure.
698 * The main purpose of this code is to handle proxied requests.
700 static REQUEST *request_ok(RADIUS_PACKET *packet, uint8_t *secret,
701 rad_listen_t *listener)
703 REQUEST *request = NULL;
706 * If the request has come in on the proxy FD, then
707 * it's a proxy reply, so pass it through the code which
708 * tries to find the original request, which we should
709 * process, rather than processing the reply as a "new"
712 if (listener->type == RAD_LISTEN_PROXY) {
714 * Find the old request, based on the current
717 request = proxy_ok(packet);
721 rad_assert(request->magic == REQUEST_MAGIC);
724 * We must have passed through the code below
725 * for the original request, which adds the
726 * reply packet to it.
728 rad_assert(request->reply != NULL);
730 } else { /* remember the new request */
732 * A unique per-request counter.
734 static int request_num_counter = 0;
736 request = request_alloc(); /* never fails */
737 request->packet = packet;
738 request->number = request_num_counter++;
739 strNcpy(request->secret, (char *)secret,
740 sizeof(request->secret));
743 * Remember the request.
748 * ADD IN "server identifier" from "listen"
753 * The request passes many of our sanity checks.
754 * From here on in, if anything goes wrong, we
755 * send a reject message, instead of dropping the
758 * Build the reply template from the request
761 rad_assert(request->reply == NULL);
762 if ((request->reply = rad_alloc(0)) == NULL) {
763 radlog(L_ERR, "No memory");
766 request->reply->sockfd = request->packet->sockfd;
767 request->reply->dst_ipaddr = request->packet->src_ipaddr;
768 request->reply->src_ipaddr = request->packet->dst_ipaddr;
769 request->reply->dst_port = request->packet->src_port;
770 request->reply->src_port = request->packet->dst_port;
771 request->reply->id = request->packet->id;
772 request->reply->code = 0; /* UNKNOWN code */
773 memcpy(request->reply->vector, request->packet->vector,
774 sizeof(request->reply->vector));
775 request->reply->vps = NULL;
776 request->reply->data = NULL;
777 request->reply->data_len = 0;
787 int main(int argc, char *argv[])
790 RADIUS_PACKET *packet;
792 unsigned char buffer[4096];
798 struct timeval *tv = NULL;
799 #ifdef HAVE_SIGACTION
800 struct sigaction act;
802 rad_listen_t *listener;
804 syslog_facility = LOG_DAEMON;
807 set_auth_parameters(argc,argv);
810 if ((progname = strrchr(argv[0], '/')) == NULL)
817 radius_dir = strdup(RADIUS_DIR);
820 * Ensure that the configuration is initialized.
822 memset(&mainconfig, 0, sizeof(mainconfig));
823 #ifdef HAVE_SIGACTION
824 memset(&act, 0, sizeof(act));
826 sigemptyset( &act.sa_mask ) ;
829 /* Process the options. */
830 while ((argval = getopt(argc, argv, "Aa:bcd:fg:hi:l:mp:sSvxXyz")) != EOF) {
835 log_auth_detail = TRUE;
839 if (radacct_dir) xfree(radacct_dir);
840 radacct_dir = strdup(optarg);
844 /* ignore for backwards compatibility with Cistron */
848 if (radius_dir) xfree(radius_dir);
849 radius_dir = strdup(optarg);
861 if ((mainconfig.myip = ip_getaddr(optarg)) == INADDR_NONE) {
862 fprintf(stderr, "radiusd: %s: host unknown\n",
869 radlog_dir = strdup(optarg);
873 * We should also have this as a configuration
877 syslog_facility = str2fac(optarg);
885 log_stripped_names++;
889 fprintf(stderr, "Ignoring deprecated command-line option -p");
892 case 's': /* Single process mode */
902 * BIG debugging mode for users who are
903 * TOO LAZY to type '-sfxxyz -l stdout' themselves.
909 mainconfig.log_auth = TRUE;
910 mainconfig.log_auth_badpass = TRUE;
911 mainconfig.log_auth_goodpass = TRUE;
912 radlog_dir = strdup("stdout");
920 mainconfig.log_auth = TRUE;
921 mainconfig.log_auth_badpass = TRUE;
925 mainconfig.log_auth_badpass = TRUE;
926 mainconfig.log_auth_goodpass = TRUE;
938 radius_pid = getpid();
940 /* Read the configuration files, BEFORE doing anything else. */
941 if (read_mainconfig(0) < 0) {
946 * If we're NOT debugging, trap fatal signals, so we can
947 * easily clean up after ourselves.
949 * If we ARE debugging, don't trap them, so we can
952 if ((mainconfig.allow_core_dumps == FALSE) && (debug_flag == 0)) {
954 #ifdef HAVE_SIGACTION
955 act.sa_handler = sig_fatal;
956 sigaction(SIGSEGV, &act, NULL);
958 signal(SIGSEGV, sig_fatal);
963 /* Reload the modules. */
964 DEBUG2("radiusd: entering modules setup");
965 if (setup_modules() < 0) {
966 radlog(L_ERR|L_CONS, "Errors setting up modules");
972 * If they asked for syslog, then give it to them.
973 * Also, initialize the logging facility with the
974 * configuration that they asked for.
976 if (strcmp(radlog_dir, "syslog") == 0) {
977 openlog(progname, LOG_PID, syslog_facility);
978 radlog_dest = RADLOG_SYSLOG;
980 /* Do you want a warning if -g is used without a -l to activate it? */
982 if (strcmp(radlog_dir, "stdout") == 0) {
983 radlog_dest = RADLOG_STDOUT;
984 } else if (strcmp(radlog_dir, "stderr") == 0) {
985 radlog_dest = RADLOG_STDERR;
988 /* Initialize the request list. */
992 * Register built-in compare functions.
994 pair_builtincompare_init();
997 if (mainconfig.do_snmp) radius_snmp_init();
1001 * Disconnect from session
1003 if (debug_flag == 0 && dont_fork == FALSE) {
1006 radlog(L_ERR|L_CONS, "Couldn't fork");
1011 * The parent exits, so the child can run in the background.
1022 * Ensure that we're using the CORRECT pid after forking,
1023 * NOT the one we started with.
1025 radius_pid = getpid();
1029 * Only write the PID file if we're running as a daemon.
1031 * And write it AFTER we've forked, so that we write the
1034 if (dont_fork == FALSE) {
1037 fp = fopen(mainconfig.pid_file, "w");
1040 * FIXME: What about following symlinks,
1041 * and having it over-write a normal file?
1043 fprintf(fp, "%d\n", (int) radius_pid);
1046 radlog(L_ERR|L_CONS, "Failed creating PID file %s: %s\n",
1047 mainconfig.pid_file, strerror(errno));
1053 * If we're running as a daemon, close the default file
1054 * descriptors, AFTER forking.
1056 if (debug_flag == FALSE) {
1059 devnull = open("/dev/null", O_RDWR);
1061 radlog(L_ERR|L_CONS, "Failed opening /dev/null: %s\n",
1065 dup2(devnull, STDIN_FILENO);
1066 dup2(devnull, STDOUT_FILENO);
1067 dup2(devnull, STDERR_FILENO);
1071 #ifdef HAVE_PTHREAD_H
1073 * If we're spawning children, set up the thread pool.
1075 if (spawn_flag == TRUE) {
1080 * Without threads, we ALWAYS run in single-server mode.
1086 * Use linebuffered or unbuffered stdout if
1087 * the debug flag is on.
1089 if (debug_flag == TRUE)
1093 * Print out which ports we're listening on.
1095 for (listener = mainconfig.listen;
1097 listener = listener->next) {
1098 if (listener->ipaddr == INADDR_ANY) {
1099 strcpy((char *)buffer, "*");
1101 ip_ntoa((char *)buffer, listener->ipaddr);
1104 switch (listener->type) {
1105 case RAD_LISTEN_AUTH:
1106 DEBUG("Listening on authentication %s:%d",
1107 buffer, listener->port);
1110 case RAD_LISTEN_ACCT:
1111 DEBUG("Listening on accounting %s:%d",
1112 buffer, listener->port);
1115 case RAD_LISTEN_PROXY:
1116 DEBUG("Listening on proxy %s:%d",
1117 buffer, listener->port);
1126 * Now that we've set everything up, we can install the signal
1127 * handlers. Before this, if we get any signal, we don't know
1128 * what to do, so we might as well do the default, and die.
1130 signal(SIGPIPE, SIG_IGN);
1131 #ifdef HAVE_SIGACTION
1132 act.sa_handler = sig_hup;
1133 sigaction(SIGHUP, &act, NULL);
1134 act.sa_handler = sig_fatal;
1135 sigaction(SIGTERM, &act, NULL);
1137 signal(SIGHUP, sig_hup);
1138 signal(SIGTERM, sig_fatal);
1141 * If we're debugging, then a CTRL-C will cause the
1142 * server to die immediately. Use SIGTERM to shut down
1143 * the server cleanly in that case.
1145 if ((debug_memory == 1) || (debug_flag == 0)) {
1146 #ifdef HAVE_SIGACTION
1147 act.sa_handler = sig_fatal;
1148 sigaction(SIGINT, &act, NULL);
1149 sigaction(SIGQUIT, &act, NULL);
1151 signal(SIGINT, sig_fatal);
1152 signal(SIGQUIT, sig_fatal);
1156 radlog(L_INFO, "Ready to process requests.");
1157 start_time = time(NULL);
1160 * Receive user requests
1164 * If we've been told to exit, then do so,
1165 * even if we have data waiting.
1168 DEBUG("Exiting...");
1171 * Ignore the TERM signal: we're about
1174 signal(SIGTERM, SIG_IGN);
1177 * Send a TERM signal to all associated
1178 * processes (including us, which gets
1181 kill(-radius_pid, SIGTERM);
1184 * FIXME: Kill child threads, and
1189 * Detach any modules.
1194 * FIXME: clean up any active REQUEST
1199 * We're exiting, so we can delete the PID
1200 * file. (If it doesn't exist, we can ignore
1201 * the error returned by unlink)
1203 if (dont_fork == FALSE) {
1204 unlink(mainconfig.pid_file);
1208 * Free the configuration items.
1214 * SIGTERM gets do_exit=0,
1215 * and we want to exit cleanly.
1217 * Other signals make us exit
1218 * with an error status.
1224 #ifdef HAVE_PTHREAD_H
1226 * Threads: wait for all threads to stop
1227 * processing before re-loading the
1228 * config, so we don't pull the rug out
1232 if (spawn_flag) for(;;) {
1234 * Block until there are '0' threads
1235 * with a REQUEST handle.
1237 sig_hup_block = TRUE;
1238 if( (total_active_threads() == 0) ||
1240 sig_hup_block = FALSE;
1247 if (read_mainconfig(TRUE) < 0) {
1251 /* Reload the modules. */
1252 DEBUG2("radiusd: entering modules setup");
1253 if (setup_modules() < 0) {
1254 radlog(L_ERR|L_CONS, "Errors setting up modules");
1258 need_reload = FALSE;
1259 radlog(L_INFO, "Ready to process requests.");
1266 * Loop over all the listening FD's.
1268 for (listener = mainconfig.listen;
1270 listener = listener->next) {
1271 FD_SET(listener->fd, &readfds);
1272 if (listener->fd > max_fd) max_fd = listener->fd;
1276 if (mainconfig.do_snmp &&
1277 (rad_snmp.smux_fd >= 0)) {
1278 FD_SET(rad_snmp.smux_fd, &readfds);
1279 if (rad_snmp.smux_fd > max_fd) max_fd = rad_snmp.smux_fd;
1282 status = select(max_fd + 1, &readfds, NULL, NULL, tv);
1285 * On interrupts, we clean up the request
1286 * list. We then continue with the loop,
1287 * so that if we're supposed to exit,
1288 * then the code at the start of the loop
1289 * catches that, and exits.
1291 if (errno == EINTR) {
1292 tv = rl_clean_list(time(NULL));
1295 radlog(L_ERR, "Unexpected error in select(): %s",
1300 time_now = time(NULL);
1301 #ifndef HAVE_PTHREAD_H
1303 * If there are no child threads, then there may
1304 * be child processes. In that case, wait for
1305 * their exit status, and throw that exit status
1306 * away. This helps get rid of zxombie children.
1308 while (waitpid(-1, &argval, WNOHANG) > 0) {
1314 * Loop over the open socket FD's, reading any data.
1316 for (listener = mainconfig.listen;
1318 listener = listener->next) {
1319 RAD_REQUEST_FUNP fun;
1321 if (!FD_ISSET(listener->fd, &readfds))
1324 * Receive the packet.
1326 if (sig_hup_block != FALSE) {
1329 packet = rad_recv(listener->fd);
1330 if (packet == NULL) {
1331 radlog(L_ERR, "%s", librad_errstr);
1336 * If the destination IP is unknown, check
1337 * if the listener has a known IP. If so,
1340 if ((packet->dst_ipaddr == htonl(INADDR_ANY)) &&
1341 (packet->dst_ipaddr != listener->ipaddr)) {
1342 packet->dst_ipaddr = listener->ipaddr;
1346 * Fill in the destination port.
1348 packet->dst_port = listener->port;
1350 RAD_SNMP_TYPE_INC(listener, total_requests);
1353 * FIXME: Move this next check into
1354 * the packet_ok() function, and add
1355 * a 'secret' to the RAIDUS_PACKET
1356 * data structure. This involves changing
1357 * a bunch of code, but it's probably the
1362 * Check if we know this client for
1363 * authentication and accounting. Check if we know
1364 * this proxy for proxying.
1366 if (listener->type != RAD_LISTEN_PROXY) {
1368 if ((cl = client_find(packet->src_ipaddr)) == NULL) {
1369 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
1371 radlog(L_ERR, "Ignoring request from unknown client %s:%d",
1372 ip_ntoa((char *)buffer, packet->src_ipaddr),
1377 secret = cl->secret;
1378 } else { /* It came in on the proxy port */
1380 if ((rl = realm_findbyaddr(packet->src_ipaddr,packet->src_port)) == NULL) {
1381 radlog(L_ERR, "Ignoring request from unknown home server %s:%d",
1382 ip_ntoa((char *)buffer, packet->src_ipaddr),
1389 * The secret isn't needed here,
1390 * as it's already in the old request
1396 * Do some simple checks before we process
1399 if ((fun = packet_ok(packet, listener)) == NULL) {
1405 * Allocate a new request for packets from
1406 * our clients, OR find the old request,
1407 * for packets which are replies from a home
1410 request = request_ok(packet, secret, listener);
1417 * Drop the request into the thread pool,
1418 * and let the thread pool take care of
1419 * doing something with it.
1421 #ifdef HAVE_PTHREAD_H
1423 if (!thread_pool_addrequest(request, fun)) {
1425 * FIXME: Maybe just drop
1426 * the packet on the floor?
1428 request_reject(request);
1429 request->finished = TRUE;
1434 rad_respond(request, fun);
1437 * Requests that care about child
1438 * process exit codes have already
1439 * either called rad_waitpid(), or
1444 } /* loop over listening sockets*/
1447 if (mainconfig.do_snmp) {
1449 * After handling all authentication/accounting
1450 * requests, THEN process any pending SMUX/SNMP
1453 * Note that the handling is done in the main server,
1454 * which probably isn't a Good Thing. It really
1455 * should be wrapped, and handled in a thread pool.
1457 if ((rad_snmp.smux_fd >= 0) &&
1458 FD_ISSET(rad_snmp.smux_fd, &readfds) &&
1459 (rad_snmp.smux_event == SMUX_READ)) {
1464 * If we've got to re-connect, then do so now,
1465 * before calling select again.
1467 if (rad_snmp.smux_event == SMUX_CONNECT) {
1474 * After processing all new requests,
1475 * check if we've got to delete old requests
1476 * from the request list.
1478 tv = rl_clean_list(time_now);
1479 #ifdef HAVE_PTHREAD_H
1482 * Only clean the thread pool if we're spawning
1486 thread_pool_clean(time_now);
1491 } /* loop forever */
1496 * FIXME: The next two functions should all
1497 * be in a module. But not until we have
1498 * more control over module execution.
1503 * Lowercase the string value of a pair.
1505 static int rad_lowerpair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1510 rad_lowercase((char *)vp->strvalue);
1511 DEBUG2("rad_lowerpair: %s now '%s'", vp->name, vp->strvalue);
1516 * Remove spaces in a pair.
1518 static int rad_rmspace_pair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1523 rad_rmspace((char *)vp->strvalue);
1524 vp->length = strlen((char *)vp->strvalue);
1525 DEBUG2("rad_rmspace_pair: %s now '%s'", vp->name, vp->strvalue);
1531 * Respond to a request packet.
1533 * Maybe we reply, maybe we don't.
1534 * Maybe we proxy the request to another server, or else maybe
1535 * we replicate it to another server.
1537 int rad_respond(REQUEST *request, RAD_REQUEST_FUNP fun)
1539 RADIUS_PACKET *packet, *original;
1541 int finished = FALSE;
1544 rad_assert(request->magic == REQUEST_MAGIC);
1547 * Don't decode the packet if it's an internal "fake"
1548 * request. Instead, just skip ahead to processing it.
1550 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1555 * Put the decoded packet into it's proper place.
1557 if (request->proxy_reply != NULL) {
1558 packet = request->proxy_reply;
1559 secret = request->proxysecret;
1560 original = request->proxy;
1562 packet = request->packet;
1563 secret = request->secret;
1568 * Decode the packet, verifying it's signature,
1569 * and parsing the attributes into structures.
1571 * Note that we do this CPU-intensive work in
1572 * a child thread, not the master. This helps to
1573 * spread the load a little bit.
1575 * Internal requests (ones that never go on the
1576 * wire) have ->data==NULL (data is the wire
1577 * format) and don't need to be "decoded"
1580 if (rad_verify(packet, original, secret) < 0) {
1581 radlog(L_ERR, "%s Dropping packet without response.", librad_errstr);
1582 /* Since accounting packets get this set in
1583 * request_reject but no response is sent...
1585 request->options |= RAD_REQUEST_OPTION_REJECTED;
1586 goto finished_request;
1589 if (rad_decode(packet, original, secret) < 0) {
1590 radlog(L_ERR, "%s", librad_errstr);
1591 request_reject(request);
1592 goto finished_request;
1597 * For proxy replies, remove non-allowed
1598 * attributes from the list of VP's.
1600 if (request->proxy) {
1602 rcode = proxy_receive(request);
1604 default: /* Don't Do Anything */
1606 case RLM_MODULE_FAIL:
1607 /* on error just continue with next request */
1609 case RLM_MODULE_HANDLED:
1610 /* if this was a replicated request, mark it as
1611 * finished first, because it was postponed
1613 goto finished_request;
1618 * This is the initial incoming request which
1621 * Some requests do NOT get cached, as they
1622 * CANNOT possibly have duplicates. Set the
1623 * magic option here.
1625 * Status-Server messages are easy to generate,
1626 * so we toss them as soon as we see a reply.
1628 * Accounting-Request packets WITHOUT an
1629 * Acct-Delay-Time attribute are NEVER
1630 * duplicated, as RFC 2866 Section 4.1 says that
1631 * the Acct-Delay-Time MUST be updated when the
1632 * packet is re-sent, which means the packet
1633 * changes, so it MUST have a new identifier and
1634 * Request Authenticator. */
1635 if ((request->packet->code == PW_STATUS_SERVER) ||
1636 ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1637 (pairfind(request->packet->vps, PW_ACCT_DELAY_TIME) == NULL))) {
1638 request->options |= RAD_REQUEST_OPTION_DONT_CACHE;
1644 * We should have a User-Name attribute now.
1646 if (request->username == NULL) {
1647 request->username = pairfind(request->packet->vps,
1652 * FIXME: All this lowercase/nospace junk will be moved
1653 * into a module after module failover is fully in place
1655 * See if we have to lower user/pass before processing
1657 if(strcmp(mainconfig.do_lower_user, "before") == 0)
1658 rad_lowerpair(request, request->username);
1659 if(strcmp(mainconfig.do_lower_pass, "before") == 0)
1660 rad_lowerpair(request,
1661 pairfind(request->packet->vps, PW_PASSWORD));
1663 if(strcmp(mainconfig.do_nospace_user, "before") == 0)
1664 rad_rmspace_pair(request, request->username);
1665 if(strcmp(mainconfig.do_nospace_pass, "before") == 0)
1666 rad_rmspace_pair(request,
1667 pairfind(request->packet->vps, PW_PASSWORD));
1672 * If the request took too long to process, don't do
1675 if (request->options & RAD_REQUEST_OPTION_REJECTED) {
1677 goto postpone_request;
1681 * Reprocess if we rejected last time
1683 if ((fun == rad_authenticate) &&
1684 (request->reply->code == PW_AUTHENTICATION_REJECT)) {
1685 /* See if we have to lower user/pass after processing */
1686 if (strcmp(mainconfig.do_lower_user, "after") == 0) {
1687 rad_lowerpair(request, request->username);
1690 if (strcmp(mainconfig.do_lower_pass, "after") == 0) {
1691 rad_lowerpair(request,
1692 pairfind(request->packet->vps, PW_PASSWORD));
1695 if (strcmp(mainconfig.do_nospace_user, "after") == 0) {
1696 rad_rmspace_pair(request, request->username);
1699 if (strcmp(mainconfig.do_nospace_pass, "after") == 0) {
1700 rad_rmspace_pair(request,
1701 pairfind(request->packet->vps, PW_PASSWORD));
1706 * If we're re-processing the request, re-set it.
1709 pairfree(&request->config_items);
1710 pairfree(&request->reply->vps);
1711 request->reply->code = 0;
1717 * Status-Server requests NEVER get proxied.
1719 if (mainconfig.proxy_requests) {
1720 if ((request->packet->code != PW_STATUS_SERVER) &&
1721 ((request->options & RAD_REQUEST_OPTION_PROXIED) == 0)) {
1725 * Try to proxy this request.
1727 rcode = proxy_send(request);
1734 * There was an error trying to proxy the request.
1735 * Drop it on the floor.
1737 case RLM_MODULE_FAIL:
1738 DEBUG2("Error trying to proxy request %d: Rejecting it", request->number);
1739 request_reject(request);
1740 goto finished_request;
1744 * The pre-proxy module has decided to reject
1745 * the request. Do so.
1747 case RLM_MODULE_REJECT:
1748 DEBUG2("Request %d rejected in proxy_send.", request->number);
1749 request_reject(request);
1750 goto finished_request;
1754 * If the proxy code has handled the request,
1755 * then postpone more processing, until we get
1756 * the reply packet from the home server.
1758 case RLM_MODULE_HANDLED:
1759 goto postpone_request;
1764 * Else rcode==RLM_MODULE_NOOP
1765 * and the proxy code didn't do anything, so
1766 * we continue handling the request here.
1769 } else if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
1770 (request->reply->code == 0)) {
1772 * We're not configured to reply to the packet,
1773 * and we're not proxying, so the DEFAULT behaviour
1774 * is to REJECT the user.
1776 DEBUG2("There was no response configured: rejecting request %d", request->number);
1777 request_reject(request);
1778 goto finished_request;
1782 * If we have a reply to send, copy the Proxy-State
1783 * attributes from the request to the tail of the reply,
1784 * and send the packet.
1786 rad_assert(request->magic == REQUEST_MAGIC);
1787 if (request->reply->code != 0) {
1788 VALUE_PAIR *vp = NULL;
1791 * Perform RFC limitations on outgoing replies.
1793 rfc_clean(request->reply);
1796 * Need to copy Proxy-State from request->packet->vps
1798 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1799 if (vp) pairadd(&(request->reply->vps), vp);
1802 * If the request isn't an authentication reject, OR
1803 * it's a reject, but the reject_delay is zero, then
1804 * send it immediately.
1806 * Otherwise, delay the authentication reject to shut
1809 if ((request->reply->code != PW_AUTHENTICATION_REJECT) ||
1810 (mainconfig.reject_delay == 0)) {
1812 * Send the response. IF it's a real request.
1814 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0) {
1815 rad_send(request->reply, request->packet,
1819 * Otherwise, it's a tunneled request.
1820 * Don't do anything.
1823 DEBUG2("Delaying request %d for %d seconds",
1824 request->number, mainconfig.reject_delay);
1825 request->options |= RAD_REQUEST_OPTION_DELAYED_REJECT;
1830 * We're done processing the request, set the
1831 * request to be finished, clean up as necessary,
1832 * and forget about the request.
1838 * Don't decode the packet if it's an internal "fake"
1839 * request. Instead, just skip ahead to processing it.
1841 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1846 * We're done handling the request. Free up the linked
1847 * lists of value pairs. This might take a long time,
1848 * so it's more efficient to do it in a child thread,
1849 * instead of in the main handler when it eventually
1850 * gets around to deleting the request.
1852 * Also, no one should be using these items after the
1853 * request is finished, and the reply is sent. Cleaning
1854 * them up here ensures that they're not being used again.
1856 * Hmm... cleaning them up in the child thread also seems
1857 * to make the server run more efficiently!
1859 * If we've delayed the REJECT, then do NOT clean up the request,
1860 * as we haven't created the REJECT message yet.
1862 if ((request->options & RAD_REQUEST_OPTION_DELAYED_REJECT) == 0) {
1863 if (request->packet) {
1864 pairfree(&request->packet->vps);
1865 request->username = NULL;
1866 request->password = NULL;
1870 * If we've sent a reply to the NAS, then this request is
1871 * pretty much finished, and we have no more need for any
1872 * of the value-pair's in it, including the proxy stuff.
1874 if (request->reply->code != 0) {
1875 pairfree(&request->reply->vps);
1879 pairfree(&request->config_items);
1880 if (request->proxy) {
1881 pairfree(&request->proxy->vps);
1883 if (request->proxy_reply) {
1884 pairfree(&request->proxy_reply->vps);
1888 DEBUG2("Finished request %d", request->number);
1892 * Go to the next request, without marking
1893 * the current one as finished.
1895 * Hmm... this may not be the brightest thing to do.
1898 DEBUG2("Going to the next request");
1901 #ifdef HAVE_PTHREAD_H
1903 * We are finished with the child thread. The thread is detached,
1904 * so that when it exits, there's nothing more for the server
1907 * If we're running with thread pools, then this frees up the
1908 * thread in the pool for another request.
1910 request->child_pid = NO_SUCH_CHILD_PID;
1912 request->finished = finished; /* do as the LAST thing before exiting */
1918 * Display the syntax for starting this program.
1920 static void NEVER_RETURNS usage(int status)
1922 FILE *output = status?stderr:stdout;
1925 "Usage: %s [-a acct_dir] [-d db_dir] [-l log_dir] [-i address] [-p port] [-AcfnsSvXxyz]\n", progname);
1926 fprintf(output, "Options:\n\n");
1927 fprintf(output, " -a acct_dir use accounting directory 'acct_dir'.\n");
1928 fprintf(output, " -A Log auth detail.\n");
1929 fprintf(output, " -d db_dir Use database directory 'db_dir'.\n");
1930 fprintf(output, " -f Run as a foreground process, not a daemon.\n");
1931 fprintf(output, " -h Print this help message.\n");
1932 fprintf(output, " -i address Listen only in the given IP address.\n");
1933 fprintf(output, " -l log_dir Log messages to 'log_dir'. Special values are:\n");
1934 fprintf(output, " stdout == log all messages to standard output.\n");
1935 fprintf(output, " syslog == log all messages to the system logger.\n");
1936 fprintf(output, " -p port Bind to 'port', and not to the radius/udp, or 1646/udp.\n");
1937 fprintf(output, " -s Do not spawn child processes to handle requests.\n");
1938 fprintf(output, " -S Log stripped names.\n");
1939 fprintf(output, " -v Print server version information.\n");
1940 fprintf(output, " -X Turn on full debugging. (Means: -sfxxyz -l stdout)\n");
1941 fprintf(output, " -x Turn on partial debugging. (-xx gives more debugging).\n");
1942 fprintf(output, " -y Log authentication failures, with password.\n");
1943 fprintf(output, " -z Log authentication successes, with password.\n");
1949 * We got a fatal signal.
1951 static void sig_fatal(int sig)
1972 * We got the hangup signal.
1973 * Re-read the configuration files.
1976 static void sig_hup(int sig)
1978 sig = sig; /* -Wunused */
1979 reset_signal(SIGHUP, sig_hup);
1982 * Only do the reload if we're the main server, both
1983 * for processes, and for threads.
1985 if (getpid() == radius_pid) {
1989 if (mainconfig.do_snmp) {
1990 rad_snmp.smux_failures = 0;
1991 rad_snmp.smux_event = SMUX_CONNECT;
1998 * Process and reply to a server-status request.
1999 * Like rad_authenticate and rad_accounting this should
2000 * live in it's own file but it's so small we don't bother.
2002 static int rad_status_server(REQUEST *request)
2009 * Reply with an ACK. We might want to add some more
2010 * interesting reply attributes, such as server uptime.
2012 t = request->timestamp - start_time;
2013 sprintf(reply_msg, "FreeRADIUS up %d day%s, %02d:%02d",
2014 (int)(t / 86400), (t / 86400) == 1 ? "" : "s",
2015 (int)((t / 3600) % 24), (int)(t / 60) % 60);
2016 request->reply->code = PW_AUTHENTICATION_ACK;
2018 vp = pairmake("Reply-Message", reply_msg, T_OP_SET);
2019 pairadd(&request->reply->vps, vp); /* don't need to check if !vp */