backport from HEAD
[freeradius.git] / src / main / radiusd.c
1 /*
2  * radiusd.c    Main loop of the radius server.
3  *
4  * Version:     $Id$
5  *
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.
10  *
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.
15  *
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
19  *
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>
26  */
27
28 /* don't look here for the version, run radiusd -v or look in version.c */
29 static const char rcsid[] =
30 "$Id$";
31
32 #include "autoconf.h"
33 #include "libradius.h"
34
35 #include <sys/file.h>
36
37 #ifdef HAVE_NETINET_IN_H
38 #       include <netinet/in.h>
39 #endif
40
41 #include <stdlib.h>
42 #include <string.h>
43 #include <fcntl.h>
44 #include <ctype.h>
45
46 #ifdef HAVE_UNISTD_H
47 #       include <unistd.h>
48 #endif
49
50 #include <signal.h>
51
52 #ifdef HAVE_GETOPT_H
53 #       include <getopt.h>
54 #endif
55
56 #ifdef HAVE_SYS_SELECT_H
57 #       include <sys/select.h>
58 #endif
59
60 #ifdef HAVE_SYSLOG_H
61 #       include <syslog.h>
62 #endif
63
64 #ifdef HAVE_SYS_WAIT_H
65 #       include <sys/wait.h>
66 #endif
67 #ifndef WEXITSTATUS
68 #       define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
69 #endif
70 #ifndef WIFEXITED
71 #       define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
72 #endif
73
74 #include "radiusd.h"
75 #include "rad_assert.h"
76 #include "conffile.h"
77 #include "modules.h"
78 #include "request_list.h"
79 #include "radius_snmp.h"
80
81 /*
82  *  Global variables.
83  */
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;
90 int syslog_facility;
91 int log_stripped_names;
92 int debug_flag = 0;
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__;
97
98 static int got_child = FALSE;
99 static time_t time_now;
100 static pid_t radius_pid;
101
102 /*
103  *  Configuration items.
104  */
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;
110
111 /*
112  *      Static functions.
113  */
114 static void usage(int);
115
116 static void sig_fatal (int);
117 static void sig_hup (int);
118 #ifdef HAVE_PTHREAD_H
119 static void sig_cleanup(int);
120 #endif
121
122 static int rad_status_server(REQUEST *request);
123
124 /*
125  *  Parse a string into a syslog facility level.
126  */
127 static int str2fac(const char *s)
128 {
129 #ifdef LOG_KERN
130         if(!strcmp(s, "kern"))
131                 return LOG_KERN;
132         else
133 #endif
134 #ifdef LOG_USER
135         if(!strcmp(s, "user"))
136                 return LOG_USER;
137         else
138 #endif
139 #ifdef LOG_MAIL
140         if(!strcmp(s, "mail"))
141                 return LOG_MAIL;
142         else
143 #endif
144 #ifdef LOG_DAEMON
145         if(!strcmp(s, "daemon"))
146                 return LOG_DAEMON;
147         else
148 #endif
149 #ifdef LOG_AUTH
150         if(!strcmp(s, "auth"))
151                 return LOG_AUTH;
152         else
153 #endif
154 #ifdef LOG_SYSLOG
155         if(!strcmp(s, "auth"))
156                 return LOG_AUTH;
157         else
158 #endif
159 #ifdef LOG_LPR
160         if(!strcmp(s, "lpr"))
161                 return LOG_LPR;
162         else
163 #endif
164 #ifdef LOG_NEWS
165         if(!strcmp(s, "news"))
166                 return LOG_NEWS;
167         else
168 #endif
169 #ifdef LOG_UUCP
170         if(!strcmp(s, "uucp"))
171                 return LOG_UUCP;
172         else
173 #endif
174 #ifdef LOG_CRON
175         if(!strcmp(s, "cron"))
176                 return LOG_CRON;
177         else
178 #endif
179 #ifdef LOG_AUTHPRIV
180         if(!strcmp(s, "authpriv"))
181                 return LOG_AUTHPRIV;
182         else
183 #endif
184 #ifdef LOG_FTP
185         if(!strcmp(s, "ftp"))
186                 return LOG_FTP;
187         else
188 #endif
189 #ifdef LOG_LOCAL0
190         if(!strcmp(s, "local0"))
191                 return LOG_LOCAL0;
192         else
193 #endif
194 #ifdef LOG_LOCAL1
195         if(!strcmp(s, "local1"))
196                 return LOG_LOCAL1;
197         else
198 #endif
199 #ifdef LOG_LOCAL2
200         if(!strcmp(s, "local2"))
201                 return LOG_LOCAL2;
202         else
203 #endif
204 #ifdef LOG_LOCAL3
205         if(!strcmp(s, "local3"))
206                 return LOG_LOCAL3;
207         else
208 #endif
209 #ifdef LOG_LOCAL4
210         if(!strcmp(s, "local4"))
211                 return LOG_LOCAL4;
212         else
213 #endif
214 #ifdef LOG_LOCAL5
215         if(!strcmp(s, "local5"))
216                 return LOG_LOCAL5;
217         else
218 #endif
219 #ifdef LOG_LOCAL6
220         if(!strcmp(s, "local6"))
221                 return LOG_LOCAL6;
222         else
223 #endif
224 #ifdef LOG_LOCAL7
225         if(!strcmp(s, "local7"))
226                 return LOG_LOCAL7;
227         else
228 #endif
229         {
230                 fprintf(stderr, "%s: Error: Unknown syslog facility: %s\n",
231                         progname, s);
232                 exit(1);
233         }
234
235         /* this should never be reached */
236         return LOG_DAEMON;
237 }
238
239
240 /*
241  *      Check if an incoming request is "ok"
242  *
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.
245   */
246 static RAD_REQUEST_FUNP packet_ok(RADIUS_PACKET *packet,
247                                   rad_listen_t *listener)
248 {
249         REQUEST         *curreq;
250         RAD_REQUEST_FUNP fun = NULL;
251
252         /*
253          *      Some sanity checks, based on the packet code.
254          */
255         switch(packet->code) {
256                 case PW_AUTHENTICATION_REQUEST:
257                         /*
258                          *      Check for requests sent to the wrong
259                          *      port, and ignore them, if so.
260                          */
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);
267                                 return NULL;
268                         }
269                         fun = rad_authenticate;
270                         break;
271
272                 case PW_ACCOUNTING_REQUEST:
273                         /*
274                          *      Check for requests sent to the wrong
275                          *      port, and ignore them, if so.
276                          */
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);
283                                 return NULL;
284                         }
285                         fun = rad_accounting;
286                         break;
287
288                 case PW_AUTHENTICATION_ACK:
289                 case PW_ACCESS_CHALLENGE:
290                 case PW_AUTHENTICATION_REJECT:
291                         /*
292                          *      Replies NOT sent to the proxy port get
293                          *      an error message logged, and the
294                          *      packet is dropped.
295                          */
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",
300                                        packet->code,
301                                        client_name(packet->src_ipaddr),
302                                        packet->src_port, packet->id);
303                                 return NULL;
304                         }
305                         fun = rad_authenticate;
306                         break;
307
308                 case PW_ACCOUNTING_RESPONSE:
309                         /*
310                          *      Replies NOT sent to the proxy port get
311                          *      an error message logged, and the
312                          *      packet is dropped.
313                          */
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",
318                                        packet->code,
319                                        client_name(packet->src_ipaddr),
320                                        packet->src_port, packet->id);
321                                 return 0;
322                         }
323                         fun = rad_accounting;
324                         break;
325
326                 case PW_STATUS_SERVER:
327                         if (!mainconfig.status_server) {
328                                 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
329                                 return NULL;
330                         }
331                         fun = rad_status_server;
332                         break;
333
334                 case PW_PASSWORD_REQUEST:
335                         RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
336
337                         /*
338                          *  We don't support this anymore.
339                          */
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);
343                         return NULL;
344                         break;
345
346                 default:
347                         RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
348
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);
353                         return NULL;
354                         break;
355
356         } /* switch over packet types */
357
358         /*
359          *      Don't handle proxy replies here.  They need to
360          *      return the *old* request, so we can re-process it.
361          */
362         if (listener->type == RAD_LISTEN_PROXY) {
363                 return fun;
364         }
365
366         /*
367          *      If there is no existing request of id, code, etc.,
368          *      then we can return, and let it be processed.
369          */
370         if ((curreq = rl_find(packet)) == NULL) {
371                 /*
372                  *      Count the total number of requests, to see if
373                  *      there are too many.  If so, return with an
374                  *      error.
375                  */
376                 if (mainconfig.max_requests) {
377                         int request_count = rl_num_requests();
378
379                         /*
380                          *      This is a new request.  Let's see if
381                          *      it makes us go over our configured
382                          *      bounds.
383                          */
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");
391                                 return NULL;
392                         } /* else there were a small number of requests */
393                 } /* else there was no configured limit for requests */
394
395                 /*
396                  *      FIXME: Add checks for system load.  If the
397                  *      system is busy, start dropping requests...
398                  *
399                  *      We can probably keep some statistics
400                  *      ourselves...  if there are more requests
401                  *      coming in than we can handle, start dropping
402                  *      some.
403                  */
404
405                 return fun;
406         }
407
408         /*
409          *      "fake" requests MUST NEVER be in the request list.
410          *
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.
414          */
415         rad_assert((curreq->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0);
416
417         /*
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.
421          */
422         if (!curreq->finished) {
423                 /*
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.
427                  */
428                 if (memcmp(curreq->packet->vector, packet->vector,
429                            sizeof(packet->vector)) == 0) {
430                         RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
431
432                         /*
433                          *      It's not finished because the request
434                          *      was proxied, but there was no reply
435                          *      from the home server.
436                          */
437                         if (curreq->proxy && !curreq->proxy_reply) {
438                                 /*
439                                  *      We're taking care of sending
440                                  *      duplicate proxied packets, so
441                                  *      we ignore any duplicate
442                                  *      requests from the NAS.
443                                  *
444                                  *      FIXME: Make it ALWAYS synchronous!
445                                  */
446                                 if (!mainconfig.proxy_synchronous) {
447                                         RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
448
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,
453                                                curreq->number);
454                                         return NULL;
455
456                                         /*
457                                          *      We ARE proxying the request,
458                                          *      and we have NOT received a
459                                          *      proxy reply yet, and we ARE
460                                          *      doing synchronous proxying.
461                                          *
462                                          *      In that case, go kick
463                                          *      the home RADIUS server
464                                          *      again.
465                                          */
466                                 } else {
467                                         char buffer[64];
468
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,
472
473                                                curreq->proxy->id);
474                                 }
475                                 curreq->proxy_next_try = time_now + mainconfig.proxy_retry_delay;
476                                 rad_send(curreq->proxy, curreq->packet,
477                                          curreq->proxysecret);
478                                 return NULL;
479                         } /* else the packet was not proxied */
480
481                         /*
482                          *      Someone's still working on it, so we
483                          *      ignore the duplicate request.
484                          */
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,
489                                curreq->number);
490                         return NULL;
491                 } /* else the authentication vectors were different */
492
493                 /*
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
497                  *      SERIOUS problem!
498                  */
499                 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
500
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,
505                        curreq->number);
506                 return NULL;
507         }
508
509         /*
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
515          *      one.
516          *
517          *      If the vectors are the same, then it's a duplicate
518          *      request, and we can send a duplicate reply.
519          */
520         if (memcmp(curreq->packet->vector, packet->vector,
521                    sizeof(packet->vector)) == 0) {
522                 RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
523
524                 /*
525                  *      If the packet has been delayed, then silently
526                  *      send a response, and clear the delayed flag.
527                  *
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.
531                  *
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.
535                  */
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);
539                         return NULL;
540                 }
541
542                 /*
543                  *      Maybe we've saved a reply packet.  If so,
544                  *      re-send it.  Otherwise, just complain.
545                  */
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);
552                         return NULL;
553                 }
554
555                 /*
556                  *      Else we never sent a reply to the NAS,
557                  *      as we decided somehow we didn't like the request.
558                  *
559                  *      This shouldn't happen, in general...
560                  */
561                 DEBUG2("Discarding duplicate request from client %s:%d - ID: %d",
562                        client_name(packet->src_ipaddr),
563                        packet->src_port, packet->id);
564                 return NULL;
565         } /* else the vectors were different, so we discard the old request. */
566
567         /*
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.
573          */
574         rl_delete(curreq);
575
576         /*
577          *      The request is OK.  We can process it...
578          *
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.
582          */
583         return fun;
584 }
585
586
587 /*
588  *  Do a proxy check of the REQUEST list when using the new proxy code.
589  */
590 static REQUEST *proxy_ok(RADIUS_PACKET *packet)
591 {
592         REALM *cl;
593         REQUEST *oldreq;
594         char buffer[32];
595
596         /*
597          *      Find the original request in the request list
598          */
599         oldreq = rl_find_proxy(packet);
600
601         /*
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.
605          */
606         if (!oldreq) {
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);
610                 return NULL;
611         }
612
613         /*
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.
619          */
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,
625                        oldreq->number);
626                 return NULL;
627         }
628
629         /*
630          *      If there is already a reply, maybe this one is a
631          *      duplicate?
632          */
633         if (oldreq->proxy_reply) {
634                 if (memcmp(oldreq->proxy_reply->vector,
635                            packet->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,
640                                oldreq->number);
641                 } else {
642                         /*
643                          *      ? The home server gave us a new *
644                          *      proxy reply, which doesn't match * the
645                          *      old one.  Delete it
646                          !  */
647                         DEBUG2("Ignoring conflicting proxy reply");
648                 }
649
650                 /*
651                  *      We've already received a reply, so
652                  *      we discard this one, as we don't want
653                  *      to do duplicate work.
654                  */
655                 return NULL;
656         } /* else there wasn't a proxy reply yet, so we can process it */
657
658         /*
659          *       Refresh the old request, and update it with the proxy
660          *       reply.
661          *
662          *      ? Can we delete the proxy request here?  * Is there
663          *      any more need for it?
664          *
665          *      FIXME: we probably shouldn't be updating the time
666          *      stamp here.
667          */
668         oldreq->timestamp = time_now;
669         oldreq->proxy_reply = packet;
670
671         /*
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.
675          *
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
682          *      as garbage.
683          */
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) {
687                                 cl->active = TRUE;
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;
692                         }
693                 }
694         }
695
696         return oldreq;
697 }
698
699 /*
700  *      Do more checks, this time on the REQUEST data structure.
701  *
702  *      The main purpose of this code is to handle proxied requests.
703  */
704 static REQUEST *request_ok(RADIUS_PACKET *packet, uint8_t *secret,
705                            rad_listen_t *listener)
706 {
707         REQUEST         *request = NULL;
708
709         /*
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"
714          *      request.
715          */
716         if (listener->type == RAD_LISTEN_PROXY) {
717                 /*
718                  *      Find the old request, based on the current
719                  *      packet.
720                  */
721                 request = proxy_ok(packet);
722                 if (!request) {
723                         return NULL;
724                 }
725                 rad_assert(request->magic == REQUEST_MAGIC);
726
727                 /*
728                  *      We must have passed through the code below
729                  *      for the original request, which adds the
730                  *      reply packet to it.
731                  */
732                 rad_assert(request->reply != NULL);
733
734         } else {                /* remember the new request */
735                 /*
736                  *      A unique per-request counter.
737                  */
738                 static int request_num_counter = 0;
739
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));
745
746                 /*
747                  *      Remember the request.
748                  */
749                 rl_add(request);
750
751                 /*
752                  *      ADD IN "server identifier" from "listen"
753                  *      directive!
754                  */
755
756                 /*
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
760                  *      packet.
761                  *
762                  *      Build the reply template from the request
763                  *      template.
764                  */
765                 rad_assert(request->reply == NULL);
766                 if ((request->reply = rad_alloc(0)) == NULL) {
767                         radlog(L_ERR, "No memory");
768                         exit(1);
769                 }
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;
782         }
783
784         return request;
785 }
786
787
788 /*
789  *      The main guy.
790  */
791 int main(int argc, char *argv[])
792 {
793         REQUEST *request;
794         RADIUS_PACKET *packet;
795         u_char *secret;
796         unsigned char buffer[4096];
797         fd_set readfds;
798         int argval;
799         int pid;
800         int max_fd;
801         int status;
802         struct timeval *tv = NULL;
803 #ifdef HAVE_SIGACTION
804         struct sigaction act;
805 #endif
806         rad_listen_t *listener;
807
808         syslog_facility = LOG_DAEMON;
809
810 #ifdef OSFC2
811         set_auth_parameters(argc,argv);
812 #endif
813
814         if ((progname = strrchr(argv[0], '/')) == NULL)
815                 progname = argv[0];
816         else
817                 progname++;
818
819         debug_flag = 0;
820         spawn_flag = TRUE;
821         radius_dir = strdup(RADIUS_DIR);
822
823         /*
824          *      Ensure that the configuration is initialized.
825          */
826         memset(&mainconfig, 0, sizeof(mainconfig));
827 #ifdef HAVE_SIGACTION
828         memset(&act, 0, sizeof(act));
829         act.sa_flags = 0 ;
830         sigemptyset( &act.sa_mask ) ;
831 #endif
832
833         /*  Process the options.  */
834         while ((argval = getopt(argc, argv, "Aa:bcd:fg:hi:l:p:sSvxXyz")) != EOF) {
835
836                 switch(argval) {
837
838                         case 'A':
839                                 log_auth_detail = TRUE;
840                                 break;
841
842                         case 'a':
843                                 if (radacct_dir) xfree(radacct_dir);
844                                 radacct_dir = strdup(optarg);
845                                 break;
846
847                         case 'c':
848                                 /* ignore for backwards compatibility with Cistron */
849                                 break;
850
851                         case 'd':
852                                 if (radius_dir) xfree(radius_dir);
853                                 radius_dir = strdup(optarg);
854                                 break;
855
856                         case 'f':
857                                 dont_fork = TRUE;
858                                 break;
859
860                         case 'h':
861                                 usage(0);
862                                 break;
863
864                         case 'i':
865                                 if ((mainconfig.myip = ip_getaddr(optarg)) == INADDR_NONE) {
866                                         fprintf(stderr, "radiusd: %s: host unknown\n",
867                                                 optarg);
868                                         exit(1);
869                                 }
870                                 break;
871
872                         case 'l':
873                                 radlog_dir = strdup(optarg);
874                                 break;
875
876                                 /*
877                                  *  We should also have this as a configuration
878                                  *  file directive.
879                                  */
880                         case 'g':
881                                 syslog_facility = str2fac(optarg);
882                                 break;
883
884                         case 'S':
885                                 log_stripped_names++;
886                                 break;
887
888                         case 'p':
889                                 fprintf(stderr, "Ignoring deprecated command-line option -p");
890                                 break;
891
892                         case 's':       /* Single process mode */
893                                 spawn_flag = FALSE;
894                                 dont_fork = TRUE;
895                                 break;
896
897                         case 'v':
898                                 version();
899                                 break;
900
901                                 /*
902                                  *  BIG debugging mode for users who are
903                                  *  TOO LAZY to type '-sfxxyz -l stdout' themselves.
904                                  */
905                         case 'X':
906                                 spawn_flag = FALSE;
907                                 dont_fork = TRUE;
908                                 debug_flag += 2;
909                                 mainconfig.log_auth = TRUE;
910                                 mainconfig.log_auth_badpass = TRUE;
911                                 mainconfig.log_auth_goodpass = TRUE;
912                                 radlog_dir = strdup("stdout");
913                                 break;
914
915                         case 'x':
916                                 debug_flag++;
917                                 break;
918
919                         case 'y':
920                                 mainconfig.log_auth = TRUE;
921                                 mainconfig.log_auth_badpass = TRUE;
922                                 break;
923
924                         case 'z':
925                                 mainconfig.log_auth_badpass = TRUE;
926                                 mainconfig.log_auth_goodpass = TRUE;
927                                 break;
928
929                         default:
930                                 usage(1);
931                                 break;
932                 }
933         }
934
935         /*
936          *      Get our PID.
937          */
938         radius_pid = getpid();
939
940         /*  Read the configuration files, BEFORE doing anything else.  */
941         if (read_mainconfig(0) < 0) {
942                 exit(1);
943         }
944
945         /*
946          *      If we're NOT debugging, trap fatal signals, so we can
947          *      easily clean up after ourselves.
948          *
949          *      If we ARE debugging, don't trap them, so we can
950          *      dump core.
951          */
952         if ((mainconfig.allow_core_dumps == FALSE) && (debug_flag == 0)) {
953 #ifdef SIGSEGV
954 #ifdef HAVE_SIGACTION
955                 act.sa_handler = sig_fatal;
956                 sigaction(SIGSEGV, &act, NULL);
957 #else
958                 signal(SIGSEGV, sig_fatal);
959 #endif
960 #endif
961         }
962
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");
967                 exit(1);
968         }
969
970 #ifdef HAVE_SYSLOG_H
971         /*
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.
975          */
976         if (strcmp(radlog_dir, "syslog") == 0) {
977                 openlog(progname, LOG_PID, syslog_facility);
978                 radlog_dest = RADLOG_SYSLOG;
979         }
980         /* Do you want a warning if -g is used without a -l to activate it? */
981 #endif
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;
986         }
987
988         /*  Initialize the request list.  */
989         rl_init();
990
991         /*
992          *  Register built-in compare functions.
993          */
994         pair_builtincompare_init();
995
996 #ifdef WITH_SNMP
997         if (mainconfig.do_snmp) radius_snmp_init();
998 #endif
999
1000         /*
1001          *  Disconnect from session
1002          */
1003         if (debug_flag == 0 && dont_fork == FALSE) {
1004                 pid = fork();
1005                 if(pid < 0) {
1006                         radlog(L_ERR|L_CONS, "Couldn't fork");
1007                         exit(1);
1008                 }
1009
1010                 /*
1011                  *  The parent exits, so the child can run in the background.
1012                  */
1013                 if(pid > 0) {
1014                         exit(0);
1015                 }
1016 #ifdef HAVE_SETSID
1017                 setsid();
1018 #endif
1019         }
1020
1021         /*
1022          *  Ensure that we're using the CORRECT pid after forking,
1023          *  NOT the one we started with.
1024          */
1025         radius_pid = getpid();
1026
1027
1028         /*
1029          *  Only write the PID file if we're running as a daemon.
1030          *
1031          *  And write it AFTER we've forked, so that we write the
1032          *  correct PID.
1033          */
1034         if (dont_fork == FALSE) {
1035                 FILE *fp;
1036
1037                 fp = fopen(mainconfig.pid_file, "w");
1038                 if (fp != NULL) {
1039                         /*
1040                          *      FIXME: What about following symlinks,
1041                          *      and having it over-write a normal file?
1042                          */
1043                         fprintf(fp, "%d\n", (int) radius_pid);
1044                         fclose(fp);
1045                 } else {
1046                         radlog(L_ERR|L_CONS, "Failed creating PID file %s: %s\n",
1047                                mainconfig.pid_file, strerror(errno));
1048                         exit(1);
1049                 }
1050         }
1051
1052         /*
1053          *      If we're running as a daemon, close the default file
1054          *      descriptors, AFTER forking.
1055          */
1056         if (debug_flag == FALSE) {
1057                 int devnull;
1058
1059                 devnull = open("/dev/null", O_RDWR);
1060                 if (devnull < 0) {
1061                         radlog(L_ERR|L_CONS, "Failed opening /dev/null: %s\n",
1062                                strerror(errno));
1063                         exit(1);
1064                 }
1065                 dup2(devnull, STDIN_FILENO);
1066                 dup2(devnull, STDOUT_FILENO);
1067                 dup2(devnull, STDERR_FILENO);
1068                 close(devnull);
1069         }
1070
1071 #ifdef HAVE_PTHREAD_H
1072         /*
1073          *  If we're spawning children, set up the thread pool.
1074          */
1075         if (spawn_flag == TRUE) {
1076                 thread_pool_init();
1077         }
1078
1079         rad_exec_init();
1080 #else
1081         /*
1082          *      Without threads, we ALWAYS run in single-server mode.
1083          */
1084         spawn_flag = FALSE;
1085 #endif
1086
1087         /*
1088          *  Use linebuffered or unbuffered stdout if
1089          *  the debug flag is on.
1090          */
1091         if (debug_flag == TRUE)
1092                 setlinebuf(stdout);
1093
1094         /*
1095          *      Print out which ports we're listening on.
1096          */
1097         for (listener = mainconfig.listen;
1098              listener != NULL;
1099              listener = listener->next) {
1100                 if (listener->ipaddr == INADDR_ANY) {
1101                         strcpy((char *)buffer, "*");
1102                 } else {
1103                         ip_ntoa((char *)buffer, listener->ipaddr);
1104                 }
1105                 
1106                 switch (listener->type) {
1107                 case RAD_LISTEN_AUTH:
1108                         DEBUG("Listening on authentication %s:%d",
1109                               buffer, listener->port);
1110                         break;
1111
1112                 case RAD_LISTEN_ACCT:
1113                         DEBUG("Listening on accounting %s:%d",
1114                               buffer, listener->port);
1115                         break;
1116
1117                 case RAD_LISTEN_PROXY:
1118                         DEBUG("Listening on proxy %s:%d",
1119                               buffer, listener->port);
1120                         break;
1121
1122                 default:
1123                         break;
1124                 }
1125         }
1126
1127         /*
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.
1131          */
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);
1138 #else
1139         signal(SIGHUP, sig_hup);
1140         signal(SIGTERM, sig_fatal);
1141 #endif
1142         /*
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.
1146          */
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);
1152 #else
1153                 signal(SIGINT, sig_fatal);
1154                 signal(SIGQUIT, sig_fatal);
1155 #endif
1156         }
1157
1158 #ifdef HAVE_PTHREAD_H
1159         /*
1160          *      If we have pthreads, then the child threads block
1161          *      SIGCHLD, and the main server thread catches it.
1162          *
1163          *      That way, the SIGCHLD handler can grab the exit status,
1164          *      and save it for the child thread.
1165          *
1166          *      If we don't have pthreads, then each child process
1167          *      will do a waitpid(), and we ignore SIGCHLD.
1168          *
1169          *      Once we have multiple child processes to handle
1170          *      requests, and shared memory, then we've got to
1171          *      re-enable SIGCHLD catching.
1172          */
1173 #ifdef HAVE_SIGACTION
1174         act.sa_handler = sig_cleanup;
1175         sigaction(SIGCHLD, &act, NULL);
1176 #else
1177         signal(SIGCHLD, sig_cleanup);
1178 #endif
1179 #endif
1180
1181         radlog(L_INFO, "Ready to process requests.");
1182         start_time = time(NULL);
1183
1184         /*
1185          *  Receive user requests
1186          */
1187         for (;;) {
1188                 /*
1189                  *      If we've been told to exit, then do so,
1190                  *      even if we have data waiting.
1191                  */
1192                 if (do_exit) {
1193                         DEBUG("Exiting...");
1194
1195                         /*
1196                          *      Ignore the TERM signal: we're about
1197                          *      to die.
1198                          */
1199                         signal(SIGTERM, SIG_IGN);
1200
1201                         /*
1202                          *      Send a TERM signal to all associated
1203                          *      processes (including us, which gets
1204                          *      ignored.)
1205                          */
1206                         kill(-radius_pid, SIGTERM);
1207
1208                         /*
1209                          *      FIXME: Kill child threads, and
1210                          *      clean up?
1211                          */
1212
1213                         /*
1214                          *      Detach any modules.
1215                          */
1216                         detach_modules();
1217
1218                         /*
1219                          *      FIXME: clean up any active REQUEST
1220                          *      handles.
1221                          */
1222
1223                         /*
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)
1227                          */
1228                         if (dont_fork == FALSE) {
1229                                 unlink(mainconfig.pid_file);
1230                         }
1231
1232                         /*
1233                          *      Free the configuration items.
1234                          */
1235                         free_mainconfig();
1236
1237                         /*
1238                          *      SIGTERM gets do_exit=0,
1239                          *      and we want to exit cleanly.
1240                          *
1241                          *      Other signals make us exit
1242                          *      with an error status.
1243                          */
1244                         exit(do_exit - 1);
1245                 }
1246
1247                 if (need_reload) {
1248 #ifdef HAVE_PTHREAD_H
1249                         /*
1250                          *      Threads: wait for all threads to stop
1251                          *      processing before re-loading the
1252                          *      config, so we don't pull the rug out
1253                          *      from under them.
1254                          */
1255                         int max_wait = 0;
1256                         if (!spawn_flag) for(;;) {
1257                                 /*
1258                                  * Block until there are '0' threads
1259                                  * with a REQUEST handle.
1260                                  */
1261                                 sig_hup_block = TRUE;
1262                                 if( (total_active_threads() == 0) ||
1263                                      (max_wait >= 5) ) {
1264                                   sig_hup_block = FALSE;
1265                                   break;
1266                                 }
1267                                 sleep(1);
1268                                 max_wait++;
1269                         }
1270 #endif
1271                         if (read_mainconfig(TRUE) < 0) {
1272                                 exit(1);
1273                         }
1274
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");
1279                                 exit(1);
1280                         }
1281
1282                         need_reload = FALSE;
1283                         radlog(L_INFO, "Ready to process requests.");
1284                 }
1285
1286                 FD_ZERO(&readfds);
1287                 max_fd = 0;
1288
1289                 /*
1290                  *      Loop over all the listening FD's.
1291                  */
1292                 for (listener = mainconfig.listen;
1293                      listener != NULL;
1294                      listener = listener->next) {
1295                         FD_SET(listener->fd, &readfds);
1296                         if (listener->fd > max_fd) max_fd = listener->fd;
1297                 }
1298
1299 #ifdef WITH_SNMP
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;
1304                 }
1305 #endif
1306                 status = select(max_fd + 1, &readfds, NULL, NULL, tv);
1307                 if (status == -1) {
1308                         /*
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.
1314                          */
1315                         if (errno == EINTR) {
1316                                 tv = rl_clean_list(time(NULL));
1317                                 continue;
1318                         }
1319                         radlog(L_ERR, "Unexpected error in select(): %s",
1320                                         strerror(errno));
1321                         exit(1);
1322                 }
1323
1324                 time_now = time(NULL);
1325 #ifndef HAVE_PTHREAD_H
1326                 /*
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.
1331                  */
1332                 while (waitpid(-1, &argval, WNOHANG) > 0) {
1333                         /* do nothing */
1334                 }
1335 #endif
1336
1337                 /*
1338                  *      Loop over the open socket FD's, reading any data.
1339                  */
1340                 for (listener = mainconfig.listen;
1341                      listener != NULL;
1342                      listener = listener->next) {
1343                         RAD_REQUEST_FUNP fun;
1344
1345                         if (!FD_ISSET(listener->fd, &readfds))
1346                                 continue;
1347                         /*
1348                          *  Receive the packet.
1349                          */
1350                         if (sig_hup_block != FALSE) {
1351                           continue;
1352                         }
1353                         packet = rad_recv(listener->fd);
1354                         if (packet == NULL) {
1355                                 radlog(L_ERR, "%s", librad_errstr);
1356                                 continue;
1357                         }
1358
1359                         /*
1360                          *      If the destination IP is unknown, check
1361                          *      if the listener has a known IP.  If so,
1362                          *      use that.
1363                          */
1364                         if ((packet->dst_ipaddr == htonl(INADDR_ANY)) &&
1365                             (packet->dst_ipaddr != listener->ipaddr)) {
1366                                 packet->dst_ipaddr = listener->ipaddr;
1367                         }
1368
1369                         /*
1370                          *      Fill in the destination port.
1371                          */
1372                         packet->dst_port = listener->port;
1373
1374                         RAD_SNMP_TYPE_INC(listener, total_requests);
1375
1376                         /*
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
1382                          *      best thing to do.
1383                          */
1384
1385                         /*
1386                          *  Check if we know this client for
1387                          *  authentication and accounting.  Check if we know
1388                          *  this proxy for proxying.
1389                          */
1390                         if (listener->type != RAD_LISTEN_PROXY) {
1391                                 RADCLIENT *cl;
1392                                 if ((cl = client_find(packet->src_ipaddr)) == NULL) {
1393                                         RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
1394
1395                                         radlog(L_ERR, "Ignoring request from unknown client %s:%d",
1396                                         ip_ntoa((char *)buffer, packet->src_ipaddr),
1397                                         packet->src_port);
1398                                         rad_free(&packet);
1399                                         continue;
1400                                 }
1401                                 secret = cl->secret;
1402                         } else {    /* It came in on the proxy port */
1403                                 REALM *rl;
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),
1407                                         packet->src_port);
1408                                         rad_free(&packet);
1409                                         continue;
1410                                 }
1411
1412                                 /*
1413                                  *      The secret isn't needed here,
1414                                  *      as it's already in the old request
1415                                  */
1416                                 secret = NULL;
1417                         }
1418
1419                         /*
1420                          *      Do some simple checks before we process
1421                          *      the request.
1422                          */
1423                         if ((fun = packet_ok(packet, listener)) == NULL) {
1424                                 rad_free(&packet);
1425                                 continue;
1426                         }
1427                         
1428                         /*
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
1432                          *      server.
1433                          */
1434                         request = request_ok(packet, secret, listener);
1435                         if (!request) {
1436                                 rad_free(&packet);
1437                                 continue;
1438                         }
1439
1440                         /*
1441                          *      Drop the request into the thread pool,
1442                          *      and let the thread pool take care of
1443                          *      doing something with it.
1444                          */
1445 #ifdef HAVE_PTHREAD_H
1446                         if (spawn_flag) {
1447                                 if (!thread_pool_addrequest(request, fun)) {
1448                                         /*
1449                                          *      FIXME: Maybe just drop
1450                                          *      the packet on the floor?
1451                                          */
1452                                         request_reject(request);
1453                                         request->finished = TRUE;
1454                                 }
1455                         } else
1456 #endif
1457                                 rad_respond(request, fun);
1458                 } /* loop over listening sockets*/
1459
1460 #ifdef WITH_SNMP
1461                 if (mainconfig.do_snmp) {
1462                         /*
1463                          *  After handling all authentication/accounting
1464                          *  requests, THEN process any pending SMUX/SNMP
1465                          *  queries.
1466                          *
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.
1470                          */
1471                         if ((rad_snmp.smux_fd >= 0) &&
1472                             FD_ISSET(rad_snmp.smux_fd, &readfds) &&
1473                             (rad_snmp.smux_event == SMUX_READ)) {
1474                                 smux_read();
1475                         }
1476
1477                         /*
1478                          *  If we've got to re-connect, then do so now,
1479                          *  before calling select again.
1480                          */
1481                         if (rad_snmp.smux_event == SMUX_CONNECT) {
1482                                 smux_connect();
1483                         }
1484                 }
1485 #endif
1486
1487                 /*
1488                  *  After processing all new requests,
1489                  *  check if we've got to delete old requests
1490                  *  from the request list.
1491                  */
1492                 tv = rl_clean_list(time_now);
1493 #ifdef HAVE_PTHREAD_H
1494
1495                 /*
1496                  *      Only clean the thread pool if we're spawning
1497                  *      child threads. 
1498                  */
1499                 if (spawn_flag) {
1500                         thread_pool_clean(time_now);
1501                 }
1502 #endif
1503
1504
1505         } /* loop forever */
1506 }
1507
1508
1509 /*
1510  * FIXME:  The next two functions should all
1511  * be in a module.  But not until we have
1512  * more control over module execution.
1513  * -jcarneal
1514  */
1515
1516 /*
1517  *  Lowercase the string value of a pair.
1518  */
1519 static int rad_lowerpair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1520         if (vp == NULL) {
1521                 return -1;
1522         }
1523
1524         rad_lowercase((char *)vp->strvalue);
1525         DEBUG2("rad_lowerpair:  %s now '%s'", vp->name, vp->strvalue);
1526         return 0;
1527 }
1528
1529 /*
1530  *  Remove spaces in a pair.
1531  */
1532 static int rad_rmspace_pair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1533         if (vp == NULL) {
1534                 return -1;
1535         }
1536
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);
1540
1541         return 0;
1542 }
1543
1544 /*
1545  *  Respond to a request packet.
1546  *
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.
1550  */
1551 int rad_respond(REQUEST *request, RAD_REQUEST_FUNP fun)
1552 {
1553         RADIUS_PACKET *packet, *original;
1554         const char *secret;
1555         int finished = FALSE;
1556         int reprocess = 0;
1557
1558         rad_assert(request->magic == REQUEST_MAGIC);
1559
1560         /*
1561          *      Don't decode the packet if it's an internal "fake"
1562          *      request.  Instead, just skip ahead to processing it.
1563          */
1564         if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1565                 goto skip_decode;
1566         }
1567
1568         /*
1569          *  Put the decoded packet into it's proper place.
1570          */
1571         if (request->proxy_reply != NULL) {
1572                 packet = request->proxy_reply;
1573                 secret = request->proxysecret;
1574                 original = request->proxy;
1575         } else {
1576                 packet = request->packet;
1577                 secret = request->secret;
1578                 original = NULL;
1579         }
1580
1581         /*
1582          *  Decode the packet, verifying it's signature,
1583          *  and parsing the attributes into structures.
1584          *
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.
1588          *
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"
1592          */
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;
1597         }
1598
1599         /*
1600          *  For proxy replies, remove non-allowed
1601          *  attributes from the list of VP's.
1602          */
1603         if (request->proxy) {
1604                 int rcode;
1605                 rcode = proxy_receive(request);
1606                 switch (rcode) {
1607                 default:  /* Don't Do Anything */
1608                         break;
1609                 case RLM_MODULE_FAIL:
1610                         /* on error just continue with next request */
1611                         goto next_request;
1612                 case RLM_MODULE_HANDLED:
1613                         /* if this was a replicated request, mark it as
1614                          * finished first, because it was postponed
1615                          */
1616                         goto finished_request;
1617                 }
1618
1619         } else {
1620                 /*
1621                  *      This is the initial incoming request which
1622                  *      we're processing.
1623                  *
1624                  *      Some requests do NOT get cached, as they
1625                  *      CANNOT possibly have duplicates.  Set the
1626                  *      magic option here.
1627                  *
1628                  *      Status-Server messages are easy to generate,
1629                  *      so we toss them as soon as we see a reply.
1630                  *
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;
1642                 }
1643         }
1644
1645  skip_decode:
1646         /*
1647          *      We should have a User-Name attribute now.
1648          */
1649         if (request->username == NULL) {
1650                 request->username = pairfind(request->packet->vps,
1651                                 PW_USER_NAME);
1652         }
1653
1654         /*
1655          *  FIXME:  All this lowercase/nospace junk will be moved
1656          *  into a module after module failover is fully in place
1657          *
1658          *  See if we have to lower user/pass before processing
1659          */
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));
1665
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));
1671
1672         (*fun)(request);
1673
1674         /*
1675          *      If the request took too long to process, don't do
1676          *      anything else.
1677          */
1678         if (request->options & RAD_REQUEST_OPTION_REJECTED) {
1679                 finished = TRUE;
1680                 goto postpone_request;
1681         }
1682
1683         /*
1684          *      Reprocess if we rejected last time
1685          */
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);
1691                   reprocess = 1;
1692           }
1693           if (strcmp(mainconfig.do_lower_pass, "after") == 0) {
1694                 rad_lowerpair(request,
1695                               pairfind(request->packet->vps, PW_PASSWORD));
1696                 reprocess = 1;
1697           }
1698           if (strcmp(mainconfig.do_nospace_user, "after") == 0) {
1699                   rad_rmspace_pair(request, request->username);
1700                   reprocess = 1;
1701           }
1702           if (strcmp(mainconfig.do_nospace_pass, "after") == 0) {
1703                   rad_rmspace_pair(request,
1704                                    pairfind(request->packet->vps, PW_PASSWORD));
1705                   reprocess = 1;
1706           }
1707
1708           /*
1709            *    If we're re-processing the request, re-set it.
1710            */
1711           if (reprocess) {
1712                   pairfree(&request->config_items);
1713                   pairfree(&request->reply->vps);
1714                   request->reply->code = 0;
1715                   (*fun)(request);
1716           }
1717         }
1718
1719         /*
1720          *      Status-Server requests NEVER get proxied.
1721          */
1722         if (mainconfig.proxy_requests) {
1723                 if ((request->packet->code != PW_STATUS_SERVER) &&
1724                     ((request->options & RAD_REQUEST_OPTION_PROXIED) == 0)) {
1725                         int rcode;
1726
1727                         /*
1728                          *      Try to proxy this request.
1729                          */
1730                         rcode = proxy_send(request);
1731
1732                         switch (rcode) {
1733                         default:
1734                                 break;
1735
1736                         /*
1737                          *  There was an error trying to proxy the request.
1738                          *  Drop it on the floor.
1739                          */
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;
1744                                 break;
1745
1746                         /*
1747                          *  The pre-proxy module has decided to reject
1748                          *  the request.  Do so.
1749                          */
1750                         case RLM_MODULE_REJECT:
1751                                 DEBUG2("Request %d rejected in proxy_send.", request->number);
1752                                 request_reject(request);
1753                                 goto finished_request;
1754                                 break;
1755
1756                         /*
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.
1760                          */
1761                         case RLM_MODULE_HANDLED:
1762                                 goto postpone_request;
1763                                 break;
1764                         }
1765
1766                         /*
1767                          *  Else rcode==RLM_MODULE_NOOP
1768                          *  and the proxy code didn't do anything, so
1769                          *  we continue handling the request here.
1770                          */
1771                 }
1772         } else if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
1773                    (request->reply->code == 0)) {
1774                 /*
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.
1778                  */
1779                 DEBUG2("There was no response configured: rejecting request %d", request->number);
1780                 request_reject(request);
1781                 goto finished_request;
1782         }
1783
1784         /*
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.
1788          */
1789         rad_assert(request->magic == REQUEST_MAGIC);
1790         if (request->reply->code != 0) {
1791                 VALUE_PAIR *vp = NULL;
1792
1793                 /*
1794                  *      Perform RFC limitations on outgoing replies.
1795                  */
1796                 rfc_clean(request->reply);
1797
1798                 /*
1799                  *      Need to copy Proxy-State from request->packet->vps
1800                  */
1801                 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1802                 if (vp) pairadd(&(request->reply->vps), vp);
1803
1804                 /*
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.
1808                  *
1809                  *  Otherwise, delay the authentication reject to shut
1810                  *  up DoS attacks.
1811                  */
1812                 if ((request->reply->code != PW_AUTHENTICATION_REJECT) ||
1813                     (mainconfig.reject_delay == 0)) {
1814                         /*
1815                          *      Send the response. IF it's a real request.
1816                          */
1817                         if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0) {
1818                                 rad_send(request->reply, request->packet,
1819                                          request->secret);
1820                         }
1821                         /*
1822                          *      Otherwise, it's a tunneled request.
1823                          *      Don't do anything.
1824                          */
1825                 } else {
1826                         DEBUG2("Delaying request %d for %d seconds",
1827                                request->number, mainconfig.reject_delay);
1828                         request->options |= RAD_REQUEST_OPTION_DELAYED_REJECT;
1829                 }
1830         }
1831
1832         /*
1833          *  We're done processing the request, set the
1834          *  request to be finished, clean up as necessary,
1835          *  and forget about the request.
1836          */
1837
1838 finished_request:
1839
1840         /*
1841          *      Don't decode the packet if it's an internal "fake"
1842          *      request.  Instead, just skip ahead to processing it.
1843          */
1844         if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1845                 goto skip_free;
1846         }
1847
1848         /*
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.
1854          *
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.
1858          *
1859          *  Hmm... cleaning them up in the child thread also seems
1860          *  to make the server run more efficiently!
1861          *
1862          *  If we've delayed the REJECT, then do NOT clean up the request,
1863          *  as we haven't created the REJECT message yet.
1864          */
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;
1870                 }
1871
1872                 /*
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.
1876                  */
1877                 if (request->reply->code != 0) {
1878                         pairfree(&request->reply->vps);
1879                 }
1880         }
1881
1882         pairfree(&request->config_items);
1883         if (request->proxy) {
1884                 pairfree(&request->proxy->vps);
1885         }
1886         if (request->proxy_reply) {
1887                 pairfree(&request->proxy_reply->vps);
1888         }
1889
1890  skip_free:
1891         DEBUG2("Finished request %d", request->number);
1892         finished = TRUE;
1893
1894         /*
1895          *  Go to the next request, without marking
1896          *  the current one as finished.
1897          *
1898          *  Hmm... this may not be the brightest thing to do.
1899          */
1900 next_request:
1901         DEBUG2("Going to the next request");
1902
1903 postpone_request:
1904 #ifdef HAVE_PTHREAD_H
1905         /*
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
1908          *  to do.
1909          *
1910          *  If we're running with thread pools, then this frees up the
1911          *  thread in the pool for another request.
1912          */
1913         request->child_pid = NO_SUCH_CHILD_PID;
1914 #endif
1915         request->finished = finished; /* do as the LAST thing before exiting */
1916         return 0;
1917 }
1918
1919
1920 #ifdef HAVE_PTHREAD_H
1921 static void sig_cleanup(int sig)
1922 {
1923         int status;
1924         pid_t pid;
1925
1926         sig = sig; /* -Wunused */
1927
1928         got_child = FALSE;
1929
1930         needs_child_cleanup = 0;  /* reset the queued cleanup number */
1931
1932         /*
1933          *  Reset the signal handler, if required.
1934          */
1935         reset_signal(SIGCHLD, sig_cleanup);
1936
1937         /*
1938          *      Wait for the child, without hanging.
1939          */
1940         for (;;) {
1941                 pid = waitpid((pid_t)-1, &status, WNOHANG);
1942                 if (pid <= 0)
1943                         return;
1944
1945                 /*
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.
1949                  */
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);
1955                         exit(1);
1956                 }
1957
1958                 /*
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.
1962                  */
1963 #ifdef HAVE_PTHREAD_H
1964                 rad_savepid(pid, status);
1965 #endif /* !defined HAVE_PTHREAD_H */
1966         }
1967 }
1968 #endif /* HAVE_PTHREAD_H */
1969
1970 /*
1971  *  Display the syntax for starting this program.
1972  */
1973 static void usage(int status)
1974 {
1975         FILE *output = status?stderr:stdout;
1976
1977         fprintf(output,
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");
1997         exit(status);
1998 }
1999
2000
2001 /*
2002  *      We got a fatal signal.
2003  */
2004 static void sig_fatal(int sig)
2005 {
2006         switch(sig) {
2007                 case SIGTERM:
2008                         do_exit = 1;
2009                         break;
2010                 default:
2011                         do_exit = 2;
2012                         break;
2013         }
2014 }
2015
2016
2017 /*
2018  *  We got the hangup signal.
2019  *  Re-read the configuration files.
2020  */
2021 /*ARGSUSED*/
2022 static void sig_hup(int sig)
2023 {
2024         sig = sig; /* -Wunused */
2025         reset_signal(SIGHUP, sig_hup);
2026
2027         /*
2028          *  Only do the reload if we're the main server, both
2029          *  for processes, and for threads.
2030          */
2031         if (getpid() == radius_pid) {
2032                 need_reload = TRUE;
2033         }
2034 #ifdef WITH_SNMP
2035         if (mainconfig.do_snmp) {
2036                 rad_snmp.smux_failures = 0;
2037                 rad_snmp.smux_event = SMUX_CONNECT;
2038         }
2039 #endif
2040 }
2041
2042
2043 /*
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.
2047  */
2048 static int rad_status_server(REQUEST *request)
2049 {
2050         char            reply_msg[64];
2051         time_t          t;
2052         VALUE_PAIR      *vp;
2053
2054         /*
2055          *      Reply with an ACK. We might want to add some more
2056          *      interesting reply attributes, such as server uptime.
2057          */
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;
2063
2064         vp = pairmake("Reply-Message", reply_msg, T_OP_SET);
2065         pairadd(&request->reply->vps, vp); /* don't need to check if !vp */
2066
2067         return 0;
2068 }