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 int got_child = FALSE;
99 static time_t time_now;
100 static pid_t radius_pid;
103 * Configuration items.
105 static int dont_fork = FALSE;
106 static int needs_child_cleanup = 0;
107 static time_t start_time = 0;
108 static int spawn_flag = TRUE;
109 static int do_exit = 0;
114 static void usage(int);
116 static void sig_fatal (int);
117 static void sig_hup (int);
118 #ifdef HAVE_PTHREAD_H
119 static void sig_cleanup(int);
122 static int rad_status_server(REQUEST *request);
125 * Parse a string into a syslog facility level.
127 static int str2fac(const char *s)
130 if(!strcmp(s, "kern"))
135 if(!strcmp(s, "user"))
140 if(!strcmp(s, "mail"))
145 if(!strcmp(s, "daemon"))
150 if(!strcmp(s, "auth"))
155 if(!strcmp(s, "auth"))
160 if(!strcmp(s, "lpr"))
165 if(!strcmp(s, "news"))
170 if(!strcmp(s, "uucp"))
175 if(!strcmp(s, "cron"))
180 if(!strcmp(s, "authpriv"))
185 if(!strcmp(s, "ftp"))
190 if(!strcmp(s, "local0"))
195 if(!strcmp(s, "local1"))
200 if(!strcmp(s, "local2"))
205 if(!strcmp(s, "local3"))
210 if(!strcmp(s, "local4"))
215 if(!strcmp(s, "local5"))
220 if(!strcmp(s, "local6"))
225 if(!strcmp(s, "local7"))
230 fprintf(stderr, "%s: Error: Unknown syslog facility: %s\n",
235 /* this should never be reached */
241 * Check if an incoming request is "ok"
243 * It takes packets, not requests. It sees if the packet looks
244 * OK. If so, it does a number of sanity checks on it.
246 static RAD_REQUEST_FUNP packet_ok(RADIUS_PACKET *packet,
247 rad_listen_t *listener)
250 RAD_REQUEST_FUNP fun = NULL;
253 * Some sanity checks, based on the packet code.
255 switch(packet->code) {
256 case PW_AUTHENTICATION_REQUEST:
258 * Check for requests sent to the wrong
259 * port, and ignore them, if so.
261 if (listener->type != RAD_LISTEN_AUTH) {
262 RAD_SNMP_INC(rad_snmp.auth.total_packets_dropped);
263 radlog(L_ERR, "Authentication-Request sent to a non-authentication port from "
264 "client %s:%d - ID %d : IGNORED",
265 client_name(packet->src_ipaddr),
266 packet->src_port, packet->id);
269 fun = rad_authenticate;
272 case PW_ACCOUNTING_REQUEST:
274 * Check for requests sent to the wrong
275 * port, and ignore them, if so.
277 if (listener->type != RAD_LISTEN_ACCT) {
278 RAD_SNMP_INC(rad_snmp.acct.total_packets_dropped);
279 radlog(L_ERR, "Accounting-Request packet sent to a non-accounting port from "
280 "client %s:%d - ID %d : IGNORED",
281 client_name(packet->src_ipaddr),
282 packet->src_port, packet->id);
285 fun = rad_accounting;
288 case PW_AUTHENTICATION_ACK:
289 case PW_ACCESS_CHALLENGE:
290 case PW_AUTHENTICATION_REJECT:
292 * Replies NOT sent to the proxy port get
293 * an error message logged, and the
296 if (listener->type != RAD_LISTEN_PROXY) {
297 RAD_SNMP_INC(rad_snmp.auth.total_packets_dropped);
298 radlog(L_ERR, "Authentication reply packet code %d sent to a non-proxy reply port from "
299 "client %s:%d - ID %d : IGNORED",
301 client_name(packet->src_ipaddr),
302 packet->src_port, packet->id);
305 fun = rad_authenticate;
308 case PW_ACCOUNTING_RESPONSE:
310 * Replies NOT sent to the proxy port get
311 * an error message logged, and the
314 if (listener->type != RAD_LISTEN_PROXY) {
315 RAD_SNMP_INC(rad_snmp.acct.total_packets_dropped);
316 radlog(L_ERR, "Accounting reply packet code %d sent to a non-proxy reply port from "
317 "client %s:%d - ID %d : IGNORED",
319 client_name(packet->src_ipaddr),
320 packet->src_port, packet->id);
323 fun = rad_accounting;
326 case PW_STATUS_SERVER:
327 if (!mainconfig.status_server) {
328 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
331 fun = rad_status_server;
334 case PW_PASSWORD_REQUEST:
335 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
338 * We don't support this anymore.
340 radlog(L_ERR, "Deprecated password change request from client %s:%d - ID %d : IGNORED",
341 client_name(packet->src_ipaddr),
342 packet->src_port, packet->id);
347 RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
349 radlog(L_ERR, "Unknown packet code %d from client %s:%d "
350 "- ID %d : IGNORED", packet->code,
351 client_name(packet->src_ipaddr),
352 packet->src_port, packet->id);
356 } /* switch over packet types */
359 * Don't handle proxy replies here. They need to
360 * return the *old* request, so we can re-process it.
362 if (listener->type == RAD_LISTEN_PROXY) {
367 * If there is no existing request of id, code, etc.,
368 * then we can return, and let it be processed.
370 if ((curreq = rl_find(packet)) == NULL) {
372 * Count the total number of requests, to see if
373 * there are too many. If so, return with an
376 if (mainconfig.max_requests) {
377 int request_count = rl_num_requests();
380 * This is a new request. Let's see if
381 * it makes us go over our configured
384 if (request_count > mainconfig.max_requests) {
385 radlog(L_ERR, "Dropping request (%d is too many): "
386 "from client %s:%d - ID: %d", request_count,
387 client_name(packet->src_ipaddr),
388 packet->src_port, packet->id);
389 radlog(L_INFO, "WARNING: Please check the radiusd.conf file.\n"
390 "\tThe value for 'max_requests' is probably set too low.\n");
392 } /* else there were a small number of requests */
393 } /* else there was no configured limit for requests */
396 * FIXME: Add checks for system load. If the
397 * system is busy, start dropping requests...
399 * We can probably keep some statistics
400 * ourselves... if there are more requests
401 * coming in than we can handle, start dropping
409 * "fake" requests MUST NEVER be in the request list.
411 * They're used internally in the server. Any reply
412 * is a reply to the local server, and any proxied packet
413 * gets sent outside of the tunnel.
415 rad_assert((curreq->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0);
418 * The current request isn't finished, which
419 * means that the NAS sent us a new packet, while
420 * we are still processing the old request.
422 if (!curreq->finished) {
424 * If the authentication vectors are identical,
425 * then the NAS is re-transmitting it, trying to
426 * kick us into responding to the request.
428 if (memcmp(curreq->packet->vector, packet->vector,
429 sizeof(packet->vector)) == 0) {
430 RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
433 * It's not finished because the request
434 * was proxied, but there was no reply
435 * from the home server.
437 if (curreq->proxy && !curreq->proxy_reply) {
439 * We're taking care of sending
440 * duplicate proxied packets, so
441 * we ignore any duplicate
442 * requests from the NAS.
444 * FIXME: Make it ALWAYS synchronous!
446 if (!mainconfig.proxy_synchronous) {
447 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
449 DEBUG2("Ignoring duplicate packet from client "
450 "%s:%d - ID: %d, due to outstanding proxied request %d.",
451 client_name(packet->src_ipaddr),
452 packet->src_port, packet->id,
457 * We ARE proxying the request,
458 * and we have NOT received a
459 * proxy reply yet, and we ARE
460 * doing synchronous proxying.
462 * In that case, go kick
463 * the home RADIUS server
469 DEBUG2("Sending duplicate proxied request to home server %s:%d - ID: %d",
470 ip_ntoa(buffer, curreq->proxy->dst_ipaddr),
471 curreq->proxy->dst_port,
475 curreq->proxy_next_try = time_now + mainconfig.proxy_retry_delay;
476 rad_send(curreq->proxy, curreq->packet,
477 curreq->proxysecret);
479 } /* else the packet was not proxied */
482 * Someone's still working on it, so we
483 * ignore the duplicate request.
485 radlog(L_ERR, "Discarding duplicate request from "
486 "client %s:%d - ID: %d due to unfinished request %d",
487 client_name(packet->src_ipaddr),
488 packet->src_port, packet->id,
491 } /* else the authentication vectors were different */
494 * The authentication vectors are different, so
495 * the NAS has given up on us, as we've taken too
496 * long to process the request. This is a
499 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
501 radlog(L_ERR, "Dropping conflicting packet from "
502 "client %s:%d - ID: %d due to unfinished request %d",
503 client_name(packet->src_ipaddr),
504 packet->src_port, packet->id,
510 * The old request is finished. We now check the
511 * authentication vectors. If the client has sent us a
512 * request with identical code && ID, but different
513 * vector, then they MUST have gotten our response, so we
514 * can delete the original request, and process the new
517 * If the vectors are the same, then it's a duplicate
518 * request, and we can send a duplicate reply.
520 if (memcmp(curreq->packet->vector, packet->vector,
521 sizeof(packet->vector)) == 0) {
522 RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
525 * If the packet has been delayed, then silently
526 * send a response, and clear the delayed flag.
528 * Note that this means if the NAS kicks us while
529 * we're delaying a reject, then the reject may
530 * be sent sooner than otherwise.
532 * This COULD be construed as a bug. Maybe what
533 * we want to do is to ignore the duplicate
534 * packet, and send the reject later.
536 if (curreq->options & RAD_REQUEST_OPTION_DELAYED_REJECT) {
537 curreq->options &= ~RAD_REQUEST_OPTION_DELAYED_REJECT;
538 rad_send(curreq->reply, curreq->packet, curreq->secret);
543 * Maybe we've saved a reply packet. If so,
544 * re-send it. Otherwise, just complain.
546 if (curreq->reply->code != 0) {
547 DEBUG2("Sending duplicate reply "
548 "to client %s:%d - ID: %d",
549 client_name(packet->src_ipaddr),
550 packet->src_port, packet->id);
551 rad_send(curreq->reply, curreq->packet, curreq->secret);
556 * Else we never sent a reply to the NAS,
557 * as we decided somehow we didn't like the request.
559 * This shouldn't happen, in general...
561 DEBUG2("Discarding duplicate request from client %s:%d - ID: %d",
562 client_name(packet->src_ipaddr),
563 packet->src_port, packet->id);
565 } /* else the vectors were different, so we discard the old request. */
568 * 'packet' has the same source IP, source port, code,
569 * and Id as 'curreq', but a different authentication
570 * vector. We can therefore delete 'curreq', as we were
571 * only keeping it around to send out duplicate replies,
572 * if the first reply got lost in the network.
577 * The request is OK. We can process it...
579 * Don't bother checking the maximum nubmer of requests
580 * here. we've just deleted one, so we KNOW we're under
581 * the limit if we add one more.
588 * Do a proxy check of the REQUEST list when using the new proxy code.
590 static REQUEST *proxy_ok(RADIUS_PACKET *packet)
597 * Find the original request in the request list
599 oldreq = rl_find_proxy(packet);
602 * If we haven't found the original request which was
603 * sent, to get this reply. Complain, and discard this
604 * request, as there's no way for us to send it to a NAS.
607 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s:%d - ID %d",
608 ip_ntoa(buffer, packet->src_ipaddr),
609 packet->src_port, packet->id);
614 * The proxy reply has arrived too late, as the original
615 * (old) request has timed out, been rejected, and marked
616 * as finished. The client has already received a
617 * response, so there is nothing that can be done. Delete
618 * the tardy reply from the home server, and return NULL.
620 if ((oldreq->reply->code != 0) ||
621 (oldreq->finished)) {
622 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'",
623 ip_ntoa(buffer, packet->src_ipaddr),
624 packet->src_port, packet->id,
630 * If there is already a reply, maybe this one is a
633 if (oldreq->proxy_reply) {
634 if (memcmp(oldreq->proxy_reply->vector,
636 sizeof(oldreq->proxy_reply->vector)) == 0) {
637 radlog(L_ERR, "Discarding duplicate reply from home server %s:%d - ID: %d for request %d",
638 ip_ntoa(buffer, packet->src_ipaddr),
639 packet->src_port, packet->id,
643 * ? The home server gave us a new *
644 * proxy reply, which doesn't match * the
647 DEBUG2("Ignoring conflicting proxy reply");
651 * We've already received a reply, so
652 * we discard this one, as we don't want
653 * to do duplicate work.
656 } /* else there wasn't a proxy reply yet, so we can process it */
659 * Refresh the old request, and update it with the proxy
662 * ? Can we delete the proxy request here? * Is there
663 * any more need for it?
665 * FIXME: we probably shouldn't be updating the time
668 oldreq->timestamp = time_now;
669 oldreq->proxy_reply = packet;
672 * Now that we've verified the packet IS actually
673 * from that realm, and not forged, we can go mark the
674 * realms for this home server as active.
676 * If we had done this check in the 'find realm by IP address'
677 * function, then an attacker could force us to use a home
678 * server which was inactive, by forging reply packets
679 * which didn't match any request. We would think that
680 * the reply meant the home server was active, would
681 * re-activate the realms, and THEN bounce the packet
684 for (cl = mainconfig.realms; cl != NULL; cl = cl->next) {
685 if (oldreq->proxy_reply->src_ipaddr == cl->ipaddr) {
686 if (oldreq->proxy_reply->src_port == cl->auth_port) {
688 cl->last_reply = oldreq->timestamp;
689 } else if (oldreq->proxy_reply->src_port == cl->acct_port) {
690 cl->acct_active = TRUE;
691 cl->last_reply = oldreq->timestamp;
700 * Do more checks, this time on the REQUEST data structure.
702 * The main purpose of this code is to handle proxied requests.
704 static REQUEST *request_ok(RADIUS_PACKET *packet, uint8_t *secret,
705 rad_listen_t *listener)
707 REQUEST *request = NULL;
710 * If the request has come in on the proxy FD, then
711 * it's a proxy reply, so pass it through the code which
712 * tries to find the original request, which we should
713 * process, rather than processing the reply as a "new"
716 if (listener->type == RAD_LISTEN_PROXY) {
718 * Find the old request, based on the current
721 request = proxy_ok(packet);
725 rad_assert(request->magic == REQUEST_MAGIC);
728 * We must have passed through the code below
729 * for the original request, which adds the
730 * reply packet to it.
732 rad_assert(request->reply != NULL);
734 } else { /* remember the new request */
736 * A unique per-request counter.
738 static int request_num_counter = 0;
740 request = request_alloc(); /* never fails */
741 request->packet = packet;
742 request->number = request_num_counter++;
743 strNcpy(request->secret, (char *)secret,
744 sizeof(request->secret));
747 * Remember the request.
752 * ADD IN "server identifier" from "listen"
757 * The request passes many of our sanity checks.
758 * From here on in, if anything goes wrong, we
759 * send a reject message, instead of dropping the
762 * Build the reply template from the request
765 rad_assert(request->reply == NULL);
766 if ((request->reply = rad_alloc(0)) == NULL) {
767 radlog(L_ERR, "No memory");
770 request->reply->sockfd = request->packet->sockfd;
771 request->reply->dst_ipaddr = request->packet->src_ipaddr;
772 request->reply->src_ipaddr = request->packet->dst_ipaddr;
773 request->reply->dst_port = request->packet->src_port;
774 request->reply->src_port = request->packet->dst_port;
775 request->reply->id = request->packet->id;
776 request->reply->code = 0; /* UNKNOWN code */
777 memcpy(request->reply->vector, request->packet->vector,
778 sizeof(request->reply->vector));
779 request->reply->vps = NULL;
780 request->reply->data = NULL;
781 request->reply->data_len = 0;
791 int main(int argc, char *argv[])
794 RADIUS_PACKET *packet;
796 unsigned char buffer[4096];
802 struct timeval *tv = NULL;
803 #ifdef HAVE_SIGACTION
804 struct sigaction act;
806 rad_listen_t *listener;
808 syslog_facility = LOG_DAEMON;
811 set_auth_parameters(argc,argv);
814 if ((progname = strrchr(argv[0], '/')) == NULL)
821 radius_dir = strdup(RADIUS_DIR);
824 * Ensure that the configuration is initialized.
826 memset(&mainconfig, 0, sizeof(mainconfig));
827 #ifdef HAVE_SIGACTION
828 memset(&act, 0, sizeof(act));
830 sigemptyset( &act.sa_mask ) ;
833 /* Process the options. */
834 while ((argval = getopt(argc, argv, "Aa:bcd:fg:hi:l:p:sSvxXyz")) != EOF) {
839 log_auth_detail = TRUE;
843 if (radacct_dir) xfree(radacct_dir);
844 radacct_dir = strdup(optarg);
848 /* ignore for backwards compatibility with Cistron */
852 if (radius_dir) xfree(radius_dir);
853 radius_dir = strdup(optarg);
865 if ((mainconfig.myip = ip_getaddr(optarg)) == INADDR_NONE) {
866 fprintf(stderr, "radiusd: %s: host unknown\n",
873 radlog_dir = strdup(optarg);
877 * We should also have this as a configuration
881 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) {
1082 * Without threads, we ALWAYS run in single-server mode.
1088 * Use linebuffered or unbuffered stdout if
1089 * the debug flag is on.
1091 if (debug_flag == TRUE)
1095 * Print out which ports we're listening on.
1097 for (listener = mainconfig.listen;
1099 listener = listener->next) {
1100 if (listener->ipaddr == INADDR_ANY) {
1101 strcpy((char *)buffer, "*");
1103 ip_ntoa((char *)buffer, listener->ipaddr);
1106 switch (listener->type) {
1107 case RAD_LISTEN_AUTH:
1108 DEBUG("Listening on authentication %s:%d",
1109 buffer, listener->port);
1112 case RAD_LISTEN_ACCT:
1113 DEBUG("Listening on accounting %s:%d",
1114 buffer, listener->port);
1117 case RAD_LISTEN_PROXY:
1118 DEBUG("Listening on proxy %s:%d",
1119 buffer, listener->port);
1128 * Now that we've set everything up, we can install the signal
1129 * handlers. Before this, if we get any signal, we don't know
1130 * what to do, so we might as well do the default, and die.
1132 signal(SIGPIPE, SIG_IGN);
1133 #ifdef HAVE_SIGACTION
1134 act.sa_handler = sig_hup;
1135 sigaction(SIGHUP, &act, NULL);
1136 act.sa_handler = sig_fatal;
1137 sigaction(SIGTERM, &act, NULL);
1139 signal(SIGHUP, sig_hup);
1140 signal(SIGTERM, sig_fatal);
1143 * If we're debugging, then a CTRL-C will cause the
1144 * server to die immediately. Use SIGTERM to shut down
1145 * the server cleanly in that case.
1147 if (debug_flag == 0) {
1148 #ifdef HAVE_SIGACTION
1149 act.sa_handler = sig_fatal;
1150 sigaction(SIGINT, &act, NULL);
1151 sigaction(SIGQUIT, &act, NULL);
1153 signal(SIGINT, sig_fatal);
1154 signal(SIGQUIT, sig_fatal);
1158 #ifdef HAVE_PTHREAD_H
1160 * If we have pthreads, then the child threads block
1161 * SIGCHLD, and the main server thread catches it.
1163 * That way, the SIGCHLD handler can grab the exit status,
1164 * and save it for the child thread.
1166 * If we don't have pthreads, then each child process
1167 * will do a waitpid(), and we ignore SIGCHLD.
1169 * Once we have multiple child processes to handle
1170 * requests, and shared memory, then we've got to
1171 * re-enable SIGCHLD catching.
1173 #ifdef HAVE_SIGACTION
1174 act.sa_handler = sig_cleanup;
1175 sigaction(SIGCHLD, &act, NULL);
1177 signal(SIGCHLD, sig_cleanup);
1181 radlog(L_INFO, "Ready to process requests.");
1182 start_time = time(NULL);
1185 * Receive user requests
1189 * If we've been told to exit, then do so,
1190 * even if we have data waiting.
1193 DEBUG("Exiting...");
1196 * Ignore the TERM signal: we're about
1199 signal(SIGTERM, SIG_IGN);
1202 * Send a TERM signal to all associated
1203 * processes (including us, which gets
1206 kill(-radius_pid, SIGTERM);
1209 * FIXME: Kill child threads, and
1214 * Detach any modules.
1219 * FIXME: clean up any active REQUEST
1224 * We're exiting, so we can delete the PID
1225 * file. (If it doesn't exist, we can ignore
1226 * the error returned by unlink)
1228 if (dont_fork == FALSE) {
1229 unlink(mainconfig.pid_file);
1233 * Free the configuration items.
1238 * SIGTERM gets do_exit=0,
1239 * and we want to exit cleanly.
1241 * Other signals make us exit
1242 * with an error status.
1248 #ifdef HAVE_PTHREAD_H
1250 * Threads: wait for all threads to stop
1251 * processing before re-loading the
1252 * config, so we don't pull the rug out
1256 if (!spawn_flag) for(;;) {
1258 * Block until there are '0' threads
1259 * with a REQUEST handle.
1261 sig_hup_block = TRUE;
1262 if( (total_active_threads() == 0) ||
1264 sig_hup_block = FALSE;
1271 if (read_mainconfig(TRUE) < 0) {
1275 /* Reload the modules. */
1276 DEBUG2("radiusd: entering modules setup");
1277 if (setup_modules() < 0) {
1278 radlog(L_ERR|L_CONS, "Errors setting up modules");
1282 need_reload = FALSE;
1283 radlog(L_INFO, "Ready to process requests.");
1290 * Loop over all the listening FD's.
1292 for (listener = mainconfig.listen;
1294 listener = listener->next) {
1295 FD_SET(listener->fd, &readfds);
1296 if (listener->fd > max_fd) max_fd = listener->fd;
1300 if (mainconfig.do_snmp &&
1301 (rad_snmp.smux_fd >= 0)) {
1302 FD_SET(rad_snmp.smux_fd, &readfds);
1303 if (rad_snmp.smux_fd > max_fd) max_fd = rad_snmp.smux_fd;
1306 status = select(max_fd + 1, &readfds, NULL, NULL, tv);
1309 * On interrupts, we clean up the request
1310 * list. We then continue with the loop,
1311 * so that if we're supposed to exit,
1312 * then the code at the start of the loop
1313 * catches that, and exits.
1315 if (errno == EINTR) {
1316 tv = rl_clean_list(time(NULL));
1319 radlog(L_ERR, "Unexpected error in select(): %s",
1324 time_now = time(NULL);
1325 #ifndef HAVE_PTHREAD_H
1327 * If there are no child threads, then there may
1328 * be child processes. In that case, wait for
1329 * their exit status, and throw that exit status
1330 * away. This helps get rid of zxombie children.
1332 while (waitpid(-1, &argval, WNOHANG) > 0) {
1338 * Loop over the open socket FD's, reading any data.
1340 for (listener = mainconfig.listen;
1342 listener = listener->next) {
1343 RAD_REQUEST_FUNP fun;
1345 if (!FD_ISSET(listener->fd, &readfds))
1348 * Receive the packet.
1350 if (sig_hup_block != FALSE) {
1353 packet = rad_recv(listener->fd);
1354 if (packet == NULL) {
1355 radlog(L_ERR, "%s", librad_errstr);
1360 * If the destination IP is unknown, check
1361 * if the listener has a known IP. If so,
1364 if ((packet->dst_ipaddr == htonl(INADDR_ANY)) &&
1365 (packet->dst_ipaddr != listener->ipaddr)) {
1366 packet->dst_ipaddr = listener->ipaddr;
1370 * Fill in the destination port.
1372 packet->dst_port = listener->port;
1374 RAD_SNMP_TYPE_INC(listener, total_requests);
1377 * FIXME: Move this next check into
1378 * the packet_ok() function, and add
1379 * a 'secret' to the RAIDUS_PACKET
1380 * data structure. This involves changing
1381 * a bunch of code, but it's probably the
1386 * Check if we know this client for
1387 * authentication and accounting. Check if we know
1388 * this proxy for proxying.
1390 if (listener->type != RAD_LISTEN_PROXY) {
1392 if ((cl = client_find(packet->src_ipaddr)) == NULL) {
1393 RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
1395 radlog(L_ERR, "Ignoring request from unknown client %s:%d",
1396 ip_ntoa((char *)buffer, packet->src_ipaddr),
1401 secret = cl->secret;
1402 } else { /* It came in on the proxy port */
1404 if ((rl = realm_findbyaddr(packet->src_ipaddr,packet->src_port)) == NULL) {
1405 radlog(L_ERR, "Ignoring request from unknown home server %s:%d",
1406 ip_ntoa((char *)buffer, packet->src_ipaddr),
1413 * The secret isn't needed here,
1414 * as it's already in the old request
1420 * Do some simple checks before we process
1423 if ((fun = packet_ok(packet, listener)) == NULL) {
1429 * Allocate a new request for packets from
1430 * our clients, OR find the old request,
1431 * for packets which are replies from a home
1434 request = request_ok(packet, secret, listener);
1441 * Drop the request into the thread pool,
1442 * and let the thread pool take care of
1443 * doing something with it.
1445 #ifdef HAVE_PTHREAD_H
1447 if (!thread_pool_addrequest(request, fun)) {
1449 * FIXME: Maybe just drop
1450 * the packet on the floor?
1452 request_reject(request);
1453 request->finished = TRUE;
1457 rad_respond(request, fun);
1458 } /* loop over listening sockets*/
1461 if (mainconfig.do_snmp) {
1463 * After handling all authentication/accounting
1464 * requests, THEN process any pending SMUX/SNMP
1467 * Note that the handling is done in the main server,
1468 * which probably isn't a Good Thing. It really
1469 * should be wrapped, and handled in a thread pool.
1471 if ((rad_snmp.smux_fd >= 0) &&
1472 FD_ISSET(rad_snmp.smux_fd, &readfds) &&
1473 (rad_snmp.smux_event == SMUX_READ)) {
1478 * If we've got to re-connect, then do so now,
1479 * before calling select again.
1481 if (rad_snmp.smux_event == SMUX_CONNECT) {
1488 * After processing all new requests,
1489 * check if we've got to delete old requests
1490 * from the request list.
1492 tv = rl_clean_list(time_now);
1493 #ifdef HAVE_PTHREAD_H
1496 * Only clean the thread pool if we're spawning
1500 thread_pool_clean(time_now);
1505 } /* loop forever */
1510 * FIXME: The next two functions should all
1511 * be in a module. But not until we have
1512 * more control over module execution.
1517 * Lowercase the string value of a pair.
1519 static int rad_lowerpair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1524 rad_lowercase((char *)vp->strvalue);
1525 DEBUG2("rad_lowerpair: %s now '%s'", vp->name, vp->strvalue);
1530 * Remove spaces in a pair.
1532 static int rad_rmspace_pair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1537 rad_rmspace((char *)vp->strvalue);
1538 vp->length = strlen((char *)vp->strvalue);
1539 DEBUG2("rad_rmspace_pair: %s now '%s'", vp->name, vp->strvalue);
1545 * Respond to a request packet.
1547 * Maybe we reply, maybe we don't.
1548 * Maybe we proxy the request to another server, or else maybe
1549 * we replicate it to another server.
1551 int rad_respond(REQUEST *request, RAD_REQUEST_FUNP fun)
1553 RADIUS_PACKET *packet, *original;
1555 int finished = FALSE;
1558 rad_assert(request->magic == REQUEST_MAGIC);
1561 * Don't decode the packet if it's an internal "fake"
1562 * request. Instead, just skip ahead to processing it.
1564 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1569 * Put the decoded packet into it's proper place.
1571 if (request->proxy_reply != NULL) {
1572 packet = request->proxy_reply;
1573 secret = request->proxysecret;
1574 original = request->proxy;
1576 packet = request->packet;
1577 secret = request->secret;
1582 * Decode the packet, verifying it's signature,
1583 * and parsing the attributes into structures.
1585 * Note that we do this CPU-intensive work in
1586 * a child thread, not the master. This helps to
1587 * spread the load a little bit.
1589 * Internal requests (ones that never go on the
1590 * wire) have ->data==NULL (data is the wire
1591 * format) and don't need to be "decoded"
1593 if (packet->data && rad_decode(packet, original, secret) != 0) {
1594 radlog(L_ERR, "%s", librad_errstr);
1595 request_reject(request);
1596 goto finished_request;
1600 * For proxy replies, remove non-allowed
1601 * attributes from the list of VP's.
1603 if (request->proxy) {
1605 rcode = proxy_receive(request);
1607 default: /* Don't Do Anything */
1609 case RLM_MODULE_FAIL:
1610 /* on error just continue with next request */
1612 case RLM_MODULE_HANDLED:
1613 /* if this was a replicated request, mark it as
1614 * finished first, because it was postponed
1616 goto finished_request;
1621 * This is the initial incoming request which
1624 * Some requests do NOT get cached, as they
1625 * CANNOT possibly have duplicates. Set the
1626 * magic option here.
1628 * Status-Server messages are easy to generate,
1629 * so we toss them as soon as we see a reply.
1631 * Accounting-Request packets WITHOUT an
1632 * Acct-Delay-Time attribute are NEVER
1633 * duplicated, as RFC 2866 Section 4.1 says that
1634 * the Acct-Delay-Time MUST be updated when the
1635 * packet is re-sent, which means the packet
1636 * changes, so it MUST have a new identifier and
1637 * Request Authenticator. */
1638 if ((request->packet->code == PW_STATUS_SERVER) ||
1639 ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1640 (pairfind(request->packet->vps, PW_ACCT_DELAY_TIME) == NULL))) {
1641 request->options |= RAD_REQUEST_OPTION_DONT_CACHE;
1647 * We should have a User-Name attribute now.
1649 if (request->username == NULL) {
1650 request->username = pairfind(request->packet->vps,
1655 * FIXME: All this lowercase/nospace junk will be moved
1656 * into a module after module failover is fully in place
1658 * See if we have to lower user/pass before processing
1660 if(strcmp(mainconfig.do_lower_user, "before") == 0)
1661 rad_lowerpair(request, request->username);
1662 if(strcmp(mainconfig.do_lower_pass, "before") == 0)
1663 rad_lowerpair(request,
1664 pairfind(request->packet->vps, PW_PASSWORD));
1666 if(strcmp(mainconfig.do_nospace_user, "before") == 0)
1667 rad_rmspace_pair(request, request->username);
1668 if(strcmp(mainconfig.do_nospace_pass, "before") == 0)
1669 rad_rmspace_pair(request,
1670 pairfind(request->packet->vps, PW_PASSWORD));
1675 * If the request took too long to process, don't do
1678 if (request->options & RAD_REQUEST_OPTION_REJECTED) {
1680 goto postpone_request;
1684 * Reprocess if we rejected last time
1686 if ((fun == rad_authenticate) &&
1687 (request->reply->code == PW_AUTHENTICATION_REJECT)) {
1688 /* See if we have to lower user/pass after processing */
1689 if (strcmp(mainconfig.do_lower_user, "after") == 0) {
1690 rad_lowerpair(request, request->username);
1693 if (strcmp(mainconfig.do_lower_pass, "after") == 0) {
1694 rad_lowerpair(request,
1695 pairfind(request->packet->vps, PW_PASSWORD));
1698 if (strcmp(mainconfig.do_nospace_user, "after") == 0) {
1699 rad_rmspace_pair(request, request->username);
1702 if (strcmp(mainconfig.do_nospace_pass, "after") == 0) {
1703 rad_rmspace_pair(request,
1704 pairfind(request->packet->vps, PW_PASSWORD));
1709 * If we're re-processing the request, re-set it.
1712 pairfree(&request->config_items);
1713 pairfree(&request->reply->vps);
1714 request->reply->code = 0;
1720 * Status-Server requests NEVER get proxied.
1722 if (mainconfig.proxy_requests) {
1723 if ((request->packet->code != PW_STATUS_SERVER) &&
1724 ((request->options & RAD_REQUEST_OPTION_PROXIED) == 0)) {
1728 * Try to proxy this request.
1730 rcode = proxy_send(request);
1737 * There was an error trying to proxy the request.
1738 * Drop it on the floor.
1740 case RLM_MODULE_FAIL:
1741 DEBUG2("Error trying to proxy request %d: Rejecting it", request->number);
1742 request_reject(request);
1743 goto finished_request;
1747 * The pre-proxy module has decided to reject
1748 * the request. Do so.
1750 case RLM_MODULE_REJECT:
1751 DEBUG2("Request %d rejected in proxy_send.", request->number);
1752 request_reject(request);
1753 goto finished_request;
1757 * If the proxy code has handled the request,
1758 * then postpone more processing, until we get
1759 * the reply packet from the home server.
1761 case RLM_MODULE_HANDLED:
1762 goto postpone_request;
1767 * Else rcode==RLM_MODULE_NOOP
1768 * and the proxy code didn't do anything, so
1769 * we continue handling the request here.
1772 } else if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
1773 (request->reply->code == 0)) {
1775 * We're not configured to reply to the packet,
1776 * and we're not proxying, so the DEFAULT behaviour
1777 * is to REJECT the user.
1779 DEBUG2("There was no response configured: rejecting request %d", request->number);
1780 request_reject(request);
1781 goto finished_request;
1785 * If we have a reply to send, copy the Proxy-State
1786 * attributes from the request to the tail of the reply,
1787 * and send the packet.
1789 rad_assert(request->magic == REQUEST_MAGIC);
1790 if (request->reply->code != 0) {
1791 VALUE_PAIR *vp = NULL;
1794 * Perform RFC limitations on outgoing replies.
1796 rfc_clean(request->reply);
1799 * Need to copy Proxy-State from request->packet->vps
1801 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1802 if (vp) pairadd(&(request->reply->vps), vp);
1805 * If the request isn't an authentication reject, OR
1806 * it's a reject, but the reject_delay is zero, then
1807 * send it immediately.
1809 * Otherwise, delay the authentication reject to shut
1812 if ((request->reply->code != PW_AUTHENTICATION_REJECT) ||
1813 (mainconfig.reject_delay == 0)) {
1815 * Send the response. IF it's a real request.
1817 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0) {
1818 rad_send(request->reply, request->packet,
1822 * Otherwise, it's a tunneled request.
1823 * Don't do anything.
1826 DEBUG2("Delaying request %d for %d seconds",
1827 request->number, mainconfig.reject_delay);
1828 request->options |= RAD_REQUEST_OPTION_DELAYED_REJECT;
1833 * We're done processing the request, set the
1834 * request to be finished, clean up as necessary,
1835 * and forget about the request.
1841 * Don't decode the packet if it's an internal "fake"
1842 * request. Instead, just skip ahead to processing it.
1844 if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1849 * We're done handling the request. Free up the linked
1850 * lists of value pairs. This might take a long time,
1851 * so it's more efficient to do it in a child thread,
1852 * instead of in the main handler when it eventually
1853 * gets around to deleting the request.
1855 * Also, no one should be using these items after the
1856 * request is finished, and the reply is sent. Cleaning
1857 * them up here ensures that they're not being used again.
1859 * Hmm... cleaning them up in the child thread also seems
1860 * to make the server run more efficiently!
1862 * If we've delayed the REJECT, then do NOT clean up the request,
1863 * as we haven't created the REJECT message yet.
1865 if ((request->options & RAD_REQUEST_OPTION_DELAYED_REJECT) == 0) {
1866 if (request->packet) {
1867 pairfree(&request->packet->vps);
1868 request->username = NULL;
1869 request->password = NULL;
1873 * If we've sent a reply to the NAS, then this request is
1874 * pretty much finished, and we have no more need for any
1875 * of the value-pair's in it, including the proxy stuff.
1877 if (request->reply->code != 0) {
1878 pairfree(&request->reply->vps);
1882 pairfree(&request->config_items);
1883 if (request->proxy) {
1884 pairfree(&request->proxy->vps);
1886 if (request->proxy_reply) {
1887 pairfree(&request->proxy_reply->vps);
1891 DEBUG2("Finished request %d", request->number);
1895 * Go to the next request, without marking
1896 * the current one as finished.
1898 * Hmm... this may not be the brightest thing to do.
1901 DEBUG2("Going to the next request");
1904 #ifdef HAVE_PTHREAD_H
1906 * We are finished with the child thread. The thread is detached,
1907 * so that when it exits, there's nothing more for the server
1910 * If we're running with thread pools, then this frees up the
1911 * thread in the pool for another request.
1913 request->child_pid = NO_SUCH_CHILD_PID;
1915 request->finished = finished; /* do as the LAST thing before exiting */
1920 #ifdef HAVE_PTHREAD_H
1921 static void sig_cleanup(int sig)
1926 sig = sig; /* -Wunused */
1930 needs_child_cleanup = 0; /* reset the queued cleanup number */
1933 * Reset the signal handler, if required.
1935 reset_signal(SIGCHLD, sig_cleanup);
1938 * Wait for the child, without hanging.
1941 pid = waitpid((pid_t)-1, &status, WNOHANG);
1946 * Check to see if the child did a bad thing.
1947 * If so, kill ALL processes in the current
1948 * process group, to prevent further attacks.
1950 if (debug_flag && (WIFSIGNALED(status))) {
1951 radlog(L_ERR|L_CONS, "MASTER: Child PID %d failed to catch "
1952 "signal %d: killing all active servers.\n",
1953 pid, WTERMSIG(status));
1954 kill(-radius_pid, SIGTERM);
1959 * If we have pthreads, then the only children
1960 * are from Exec-Program. We don't care about them,
1961 * so once we've grabbed their PID's, we're done.
1963 #ifdef HAVE_PTHREAD_H
1964 rad_savepid(pid, status);
1965 #endif /* !defined HAVE_PTHREAD_H */
1968 #endif /* HAVE_PTHREAD_H */
1971 * Display the syntax for starting this program.
1973 static void usage(int status)
1975 FILE *output = status?stderr:stdout;
1978 "Usage: %s [-a acct_dir] [-d db_dir] [-l log_dir] [-i address] [-p port] [-AcfnsSvXxyz]\n", progname);
1979 fprintf(output, "Options:\n\n");
1980 fprintf(output, " -a acct_dir use accounting directory 'acct_dir'.\n");
1981 fprintf(output, " -A Log auth detail.\n");
1982 fprintf(output, " -d db_dir Use database directory 'db_dir'.\n");
1983 fprintf(output, " -f Run as a foreground process, not a daemon.\n");
1984 fprintf(output, " -h Print this help message.\n");
1985 fprintf(output, " -i address Listen only in the given IP address.\n");
1986 fprintf(output, " -l log_dir Log messages to 'log_dir'. Special values are:\n");
1987 fprintf(output, " stdout == log all messages to standard output.\n");
1988 fprintf(output, " syslog == log all messages to the system logger.\n");
1989 fprintf(output, " -p port Bind to 'port', and not to the radius/udp, or 1646/udp.\n");
1990 fprintf(output, " -s Do not spawn child processes to handle requests.\n");
1991 fprintf(output, " -S Log stripped names.\n");
1992 fprintf(output, " -v Print server version information.\n");
1993 fprintf(output, " -X Turn on full debugging. (Means: -sfxxyz -l stdout)\n");
1994 fprintf(output, " -x Turn on partial debugging. (-xx gives more debugging).\n");
1995 fprintf(output, " -y Log authentication failures, with password.\n");
1996 fprintf(output, " -z Log authentication successes, with password.\n");
2002 * We got a fatal signal.
2004 static void sig_fatal(int sig)
2018 * We got the hangup signal.
2019 * Re-read the configuration files.
2022 static void sig_hup(int sig)
2024 sig = sig; /* -Wunused */
2025 reset_signal(SIGHUP, sig_hup);
2028 * Only do the reload if we're the main server, both
2029 * for processes, and for threads.
2031 if (getpid() == radius_pid) {
2035 if (mainconfig.do_snmp) {
2036 rad_snmp.smux_failures = 0;
2037 rad_snmp.smux_event = SMUX_CONNECT;
2044 * Process and reply to a server-status request.
2045 * Like rad_authenticate and rad_accounting this should
2046 * live in it's own file but it's so small we don't bother.
2048 static int rad_status_server(REQUEST *request)
2055 * Reply with an ACK. We might want to add some more
2056 * interesting reply attributes, such as server uptime.
2058 t = request->timestamp - start_time;
2059 sprintf(reply_msg, "FreeRADIUS up %d day%s, %02d:%02d",
2060 (int)(t / 86400), (t / 86400) == 1 ? "" : "s",
2061 (int)((t / 3600) % 24), (int)(t / 60) % 60);
2062 request->reply->code = PW_AUTHENTICATION_ACK;
2064 vp = pairmake("Reply-Message", reply_msg, T_OP_SET);
2065 pairadd(&request->reply->vps, vp); /* don't need to check if !vp */