import 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 time_t time_now;
99 static pid_t radius_pid;
100
101 /*
102  *  Configuration items.
103  */
104 static int dont_fork = FALSE;
105 static time_t start_time = 0;
106 static int spawn_flag = TRUE;
107 static int do_exit = 0;
108
109 /*
110  *      Static functions.
111  */
112 static void usage(int);
113
114 static void sig_fatal (int);
115 static void sig_hup (int);
116
117 static int rad_status_server(REQUEST *request);
118
119 /*
120  *  Parse a string into a syslog facility level.
121  */
122 static int str2fac(const char *s)
123 {
124 #ifdef LOG_KERN
125         if(!strcmp(s, "kern"))
126                 return LOG_KERN;
127         else
128 #endif
129 #ifdef LOG_USER
130         if(!strcmp(s, "user"))
131                 return LOG_USER;
132         else
133 #endif
134 #ifdef LOG_MAIL
135         if(!strcmp(s, "mail"))
136                 return LOG_MAIL;
137         else
138 #endif
139 #ifdef LOG_DAEMON
140         if(!strcmp(s, "daemon"))
141                 return LOG_DAEMON;
142         else
143 #endif
144 #ifdef LOG_AUTH
145         if(!strcmp(s, "auth"))
146                 return LOG_AUTH;
147         else
148 #endif
149 #ifdef LOG_SYSLOG
150         if(!strcmp(s, "auth"))
151                 return LOG_AUTH;
152         else
153 #endif
154 #ifdef LOG_LPR
155         if(!strcmp(s, "lpr"))
156                 return LOG_LPR;
157         else
158 #endif
159 #ifdef LOG_NEWS
160         if(!strcmp(s, "news"))
161                 return LOG_NEWS;
162         else
163 #endif
164 #ifdef LOG_UUCP
165         if(!strcmp(s, "uucp"))
166                 return LOG_UUCP;
167         else
168 #endif
169 #ifdef LOG_CRON
170         if(!strcmp(s, "cron"))
171                 return LOG_CRON;
172         else
173 #endif
174 #ifdef LOG_AUTHPRIV
175         if(!strcmp(s, "authpriv"))
176                 return LOG_AUTHPRIV;
177         else
178 #endif
179 #ifdef LOG_FTP
180         if(!strcmp(s, "ftp"))
181                 return LOG_FTP;
182         else
183 #endif
184 #ifdef LOG_LOCAL0
185         if(!strcmp(s, "local0"))
186                 return LOG_LOCAL0;
187         else
188 #endif
189 #ifdef LOG_LOCAL1
190         if(!strcmp(s, "local1"))
191                 return LOG_LOCAL1;
192         else
193 #endif
194 #ifdef LOG_LOCAL2
195         if(!strcmp(s, "local2"))
196                 return LOG_LOCAL2;
197         else
198 #endif
199 #ifdef LOG_LOCAL3
200         if(!strcmp(s, "local3"))
201                 return LOG_LOCAL3;
202         else
203 #endif
204 #ifdef LOG_LOCAL4
205         if(!strcmp(s, "local4"))
206                 return LOG_LOCAL4;
207         else
208 #endif
209 #ifdef LOG_LOCAL5
210         if(!strcmp(s, "local5"))
211                 return LOG_LOCAL5;
212         else
213 #endif
214 #ifdef LOG_LOCAL6
215         if(!strcmp(s, "local6"))
216                 return LOG_LOCAL6;
217         else
218 #endif
219 #ifdef LOG_LOCAL7
220         if(!strcmp(s, "local7"))
221                 return LOG_LOCAL7;
222         else
223 #endif
224         {
225                 fprintf(stderr, "%s: Error: Unknown syslog facility: %s\n",
226                         progname, s);
227                 exit(1);
228         }
229
230         /* this should never be reached */
231         return LOG_DAEMON;
232 }
233
234
235 /*
236  *      Check if an incoming request is "ok"
237  *
238  *      It takes packets, not requests.  It sees if the packet looks
239  *      OK.  If so, it does a number of sanity checks on it.
240   */
241 static RAD_REQUEST_FUNP packet_ok(RADIUS_PACKET *packet,
242                                   rad_listen_t *listener)
243 {
244         REQUEST         *curreq;
245         RAD_REQUEST_FUNP fun = NULL;
246
247         /*
248          *      Some sanity checks, based on the packet code.
249          */
250         switch(packet->code) {
251                 case PW_AUTHENTICATION_REQUEST:
252                         /*
253                          *      Check for requests sent to the wrong
254                          *      port, and ignore them, if so.
255                          */
256                         if (listener->type != RAD_LISTEN_AUTH) {
257                                 RAD_SNMP_INC(rad_snmp.auth.total_packets_dropped);
258                                 radlog(L_ERR, "Authentication-Request sent to a non-authentication port from "
259                                         "client %s:%d - ID %d : IGNORED",
260                                         client_name(packet->src_ipaddr),
261                                        packet->src_port, packet->id);
262                                 return NULL;
263                         }
264                         fun = rad_authenticate;
265                         break;
266
267                 case PW_ACCOUNTING_REQUEST:
268                         /*
269                          *      Check for requests sent to the wrong
270                          *      port, and ignore them, if so.
271                          */
272                         if (listener->type != RAD_LISTEN_ACCT) {
273                                 RAD_SNMP_INC(rad_snmp.acct.total_packets_dropped);
274                                 radlog(L_ERR, "Accounting-Request packet sent to a non-accounting port from "
275                                        "client %s:%d - ID %d : IGNORED",
276                                        client_name(packet->src_ipaddr),
277                                        packet->src_port, packet->id);
278                                 return NULL;
279                         }
280                         fun = rad_accounting;
281                         break;
282
283                 case PW_AUTHENTICATION_ACK:
284                 case PW_ACCESS_CHALLENGE:
285                 case PW_AUTHENTICATION_REJECT:
286                         /*
287                          *      Replies NOT sent to the proxy port get
288                          *      an error message logged, and the
289                          *      packet is dropped.
290                          */
291                         if (listener->type != RAD_LISTEN_PROXY) {
292                                 RAD_SNMP_INC(rad_snmp.auth.total_packets_dropped);
293                                 radlog(L_ERR, "Authentication reply packet code %d sent to a non-proxy reply port from "
294                                        "client %s:%d - ID %d : IGNORED",
295                                        packet->code,
296                                        client_name(packet->src_ipaddr),
297                                        packet->src_port, packet->id);
298                                 return NULL;
299                         }
300                         fun = rad_authenticate;
301                         break;
302
303                 case PW_ACCOUNTING_RESPONSE:
304                         /*
305                          *      Replies NOT sent to the proxy port get
306                          *      an error message logged, and the
307                          *      packet is dropped.
308                          */
309                         if (listener->type != RAD_LISTEN_PROXY) {
310                                 RAD_SNMP_INC(rad_snmp.acct.total_packets_dropped);
311                                 radlog(L_ERR, "Accounting reply packet code %d sent to a non-proxy reply port from "
312                                        "client %s:%d - ID %d : IGNORED",
313                                        packet->code,
314                                        client_name(packet->src_ipaddr),
315                                        packet->src_port, packet->id);
316                                 return 0;
317                         }
318                         fun = rad_accounting;
319                         break;
320
321                 case PW_STATUS_SERVER:
322                         if (!mainconfig.status_server) {
323                                 DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
324                                 return NULL;
325                         }
326                         fun = rad_status_server;
327                         break;
328
329                 case PW_PASSWORD_REQUEST:
330                         RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
331
332                         /*
333                          *  We don't support this anymore.
334                          */
335                         radlog(L_ERR, "Deprecated password change request from client %s:%d - ID %d : IGNORED",
336                                         client_name(packet->src_ipaddr),
337                                packet->src_port, packet->id);
338                         return NULL;
339                         break;
340
341                 default:
342                         RAD_SNMP_INC(rad_snmp.auth.total_unknown_types);
343
344                         radlog(L_ERR, "Unknown packet code %d from client %s:%d "
345                                "- ID %d : IGNORED", packet->code,
346                                client_name(packet->src_ipaddr),
347                                packet->src_port, packet->id);
348                         return NULL;
349                         break;
350
351         } /* switch over packet types */
352
353         /*
354          *      Don't handle proxy replies here.  They need to
355          *      return the *old* request, so we can re-process it.
356          */
357         if (listener->type == RAD_LISTEN_PROXY) {
358                 return fun;
359         }
360
361         /*
362          *      If there is no existing request of id, code, etc.,
363          *      then we can return, and let it be processed.
364          */
365         if ((curreq = rl_find(packet)) == NULL) {
366                 /*
367                  *      Count the total number of requests, to see if
368                  *      there are too many.  If so, return with an
369                  *      error.
370                  */
371                 if (mainconfig.max_requests) {
372                         int request_count = rl_num_requests();
373
374                         /*
375                          *      This is a new request.  Let's see if
376                          *      it makes us go over our configured
377                          *      bounds.
378                          */
379                         if (request_count > mainconfig.max_requests) {
380                                 radlog(L_ERR, "Dropping request (%d is too many): "
381                                        "from client %s:%d - ID: %d", request_count,
382                                        client_name(packet->src_ipaddr),
383                                        packet->src_port, packet->id);
384                                 radlog(L_INFO, "WARNING: Please check the radiusd.conf file.\n"
385                                        "\tThe value for 'max_requests' is probably set too low.\n");
386                                 return NULL;
387                         } /* else there were a small number of requests */
388                 } /* else there was no configured limit for requests */
389
390                 /*
391                  *      FIXME: Add checks for system load.  If the
392                  *      system is busy, start dropping requests...
393                  *
394                  *      We can probably keep some statistics
395                  *      ourselves...  if there are more requests
396                  *      coming in than we can handle, start dropping
397                  *      some.
398                  */
399
400                 return fun;
401         }
402
403         /*
404          *      "fake" requests MUST NEVER be in the request list.
405          *
406          *      They're used internally in the server.  Any reply
407          *      is a reply to the local server, and any proxied packet
408          *      gets sent outside of the tunnel.
409          */
410         rad_assert((curreq->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0);
411
412         /*
413          *      The current request isn't finished, which
414          *      means that the NAS sent us a new packet, while
415          *      we are still processing the old request.
416          */
417         if (!curreq->finished) {
418                 /*
419                  *      If the authentication vectors are identical,
420                  *      then the NAS is re-transmitting it, trying to
421                  *      kick us into responding to the request.
422                  */
423                 if (memcmp(curreq->packet->vector, packet->vector,
424                            sizeof(packet->vector)) == 0) {
425                         RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
426
427                         /*
428                          *      It's not finished because the request
429                          *      was proxied, but there was no reply
430                          *      from the home server.
431                          */
432                         if (curreq->proxy && !curreq->proxy_reply) {
433                                 /*
434                                  *      We're taking care of sending
435                                  *      duplicate proxied packets, so
436                                  *      we ignore any duplicate
437                                  *      requests from the NAS.
438                                  *
439                                  *      FIXME: Make it ALWAYS synchronous!
440                                  */
441                                 if (!mainconfig.proxy_synchronous) {
442                                         RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
443
444                                         DEBUG2("Ignoring duplicate packet from client "
445                                                "%s:%d - ID: %d, due to outstanding proxied request %d.",
446                                                client_name(packet->src_ipaddr),
447                                                packet->src_port, packet->id,
448                                                curreq->number);
449                                         return NULL;
450
451                                         /*
452                                          *      We ARE proxying the request,
453                                          *      and we have NOT received a
454                                          *      proxy reply yet, and we ARE
455                                          *      doing synchronous proxying.
456                                          *
457                                          *      In that case, go kick
458                                          *      the home RADIUS server
459                                          *      again.
460                                          */
461                                 } else {
462                                         char buffer[64];
463
464                                         DEBUG2("Sending duplicate proxied request to home server %s:%d - ID: %d",
465                                                ip_ntoa(buffer, curreq->proxy->dst_ipaddr),
466                                                curreq->proxy->dst_port,
467
468                                                curreq->proxy->id);
469                                 }
470                                 curreq->proxy_next_try = time_now + mainconfig.proxy_retry_delay;
471                                 rad_send(curreq->proxy, curreq->packet,
472                                          curreq->proxysecret);
473                                 return NULL;
474                         } /* else the packet was not proxied */
475
476                         /*
477                          *      Someone's still working on it, so we
478                          *      ignore the duplicate request.
479                          */
480                         radlog(L_ERR, "Discarding duplicate request from "
481                                "client %s:%d - ID: %d due to unfinished request %d",
482                                client_name(packet->src_ipaddr),
483                                packet->src_port, packet->id,
484                                curreq->number);
485                         return NULL;
486                 } /* else the authentication vectors were different */
487
488                 /*
489                  *      The authentication vectors are different, so
490                  *      the NAS has given up on us, as we've taken too
491                  *      long to process the request.  This is a
492                  *      SERIOUS problem!
493                  */
494                 RAD_SNMP_TYPE_INC(listener, total_packets_dropped);
495
496                 radlog(L_ERR, "Dropping conflicting packet from "
497                        "client %s:%d - ID: %d due to unfinished request %d",
498                        client_name(packet->src_ipaddr),
499                        packet->src_port, packet->id,
500                        curreq->number);
501                 return NULL;
502         }
503
504         /*
505          *      The old request is finished.  We now check the
506          *      authentication vectors.  If the client has sent us a
507          *      request with identical code && ID, but different
508          *      vector, then they MUST have gotten our response, so we
509          *      can delete the original request, and process the new
510          *      one.
511          *
512          *      If the vectors are the same, then it's a duplicate
513          *      request, and we can send a duplicate reply.
514          */
515         if (memcmp(curreq->packet->vector, packet->vector,
516                    sizeof(packet->vector)) == 0) {
517                 RAD_SNMP_INC(rad_snmp.auth.total_dup_requests);
518
519                 /*
520                  *      If the packet has been delayed, then silently
521                  *      send a response, and clear the delayed flag.
522                  *
523                  *      Note that this means if the NAS kicks us while
524                  *      we're delaying a reject, then the reject may
525                  *      be sent sooner than otherwise.
526                  *
527                  *      This COULD be construed as a bug.  Maybe what
528                  *      we want to do is to ignore the duplicate
529                  *      packet, and send the reject later.
530                  */
531                 if (curreq->options & RAD_REQUEST_OPTION_DELAYED_REJECT) {
532                         curreq->options &= ~RAD_REQUEST_OPTION_DELAYED_REJECT;
533                         rad_send(curreq->reply, curreq->packet, curreq->secret);
534                         return NULL;
535                 }
536
537                 /*
538                  *      Maybe we've saved a reply packet.  If so,
539                  *      re-send it.  Otherwise, just complain.
540                  */
541                 if (curreq->reply->code != 0) {
542                         DEBUG2("Sending duplicate reply "
543                                "to client %s:%d - ID: %d",
544                                client_name(packet->src_ipaddr),
545                                packet->src_port, packet->id);
546                         rad_send(curreq->reply, curreq->packet, curreq->secret);
547                         return NULL;
548                 }
549
550                 /*
551                  *      Else we never sent a reply to the NAS,
552                  *      as we decided somehow we didn't like the request.
553                  *
554                  *      This shouldn't happen, in general...
555                  */
556                 DEBUG2("Discarding duplicate request from client %s:%d - ID: %d",
557                        client_name(packet->src_ipaddr),
558                        packet->src_port, packet->id);
559                 return NULL;
560         } /* else the vectors were different, so we discard the old request. */
561
562         /*
563          *      'packet' has the same source IP, source port, code,
564          *      and Id as 'curreq', but a different authentication
565          *      vector.  We can therefore delete 'curreq', as we were
566          *      only keeping it around to send out duplicate replies,
567          *      if the first reply got lost in the network.
568          */
569         rl_delete(curreq);
570
571         /*
572          *      The request is OK.  We can process it...
573          *
574          *      Don't bother checking the maximum nubmer of requests
575          *      here.  we've just deleted one, so we KNOW we're under
576          *      the limit if we add one more.
577          */
578         return fun;
579 }
580
581
582 /*
583  *  Do a proxy check of the REQUEST list when using the new proxy code.
584  */
585 static REQUEST *proxy_ok(RADIUS_PACKET *packet)
586 {
587         REALM *cl;
588         REQUEST *oldreq;
589         char buffer[32];
590
591         /*
592          *      Find the original request in the request list
593          */
594         oldreq = rl_find_proxy(packet);
595
596         /*
597          *      If we haven't found the original request which was
598          *      sent, to get this reply.  Complain, and discard this
599          *      request, as there's no way for us to send it to a NAS.
600          */
601         if (!oldreq) {
602                 radlog(L_PROXY, "No outstanding request was found for proxy reply from home server %s:%d - ID %d",
603                        ip_ntoa(buffer, packet->src_ipaddr),
604                        packet->src_port, packet->id);
605                 return NULL;
606         }
607
608         /*
609          *      The proxy reply has arrived too late, as the original
610          *      (old) request has timed out, been rejected, and marked
611          *      as finished.  The client has already received a
612          *      response, so there is nothing that can be done. Delete
613          *      the tardy reply from the home server, and return NULL.
614          */
615         if ((oldreq->reply->code != 0) ||
616             (oldreq->finished)) {
617                 radlog(L_ERR, "Reply from home server %s:%d  - ID: %d arrived too late for request %d. Try increasing 'retry_delay' or 'max_request_time'",
618                        ip_ntoa(buffer, packet->src_ipaddr),
619                        packet->src_port, packet->id,
620                        oldreq->number);
621                 return NULL;
622         }
623
624         /*
625          *      If there is already a reply, maybe this one is a
626          *      duplicate?
627          */
628         if (oldreq->proxy_reply) {
629                 if (memcmp(oldreq->proxy_reply->vector,
630                            packet->vector,
631                            sizeof(oldreq->proxy_reply->vector)) == 0) {
632                         radlog(L_ERR, "Discarding duplicate reply from home server %s:%d  - ID: %d for request %d",
633                                ip_ntoa(buffer, packet->src_ipaddr),
634                                packet->src_port, packet->id,
635                                oldreq->number);
636                 } else {
637                         /*
638                          *      ? The home server gave us a new *
639                          *      proxy reply, which doesn't match * the
640                          *      old one.  Delete it
641                          !  */
642                         DEBUG2("Ignoring conflicting proxy reply");
643                 }
644
645                 /*
646                  *      We've already received a reply, so
647                  *      we discard this one, as we don't want
648                  *      to do duplicate work.
649                  */
650                 return NULL;
651         } /* else there wasn't a proxy reply yet, so we can process it */
652
653         /*
654          *       Refresh the old request, and update it with the proxy
655          *       reply.
656          *
657          *      ? Can we delete the proxy request here?  * Is there
658          *      any more need for it?
659          *
660          *      FIXME: we probably shouldn't be updating the time
661          *      stamp here.
662          */
663         oldreq->timestamp = time_now;
664         oldreq->proxy_reply = packet;
665
666         /*
667          *      Now that we've verified the packet IS actually
668          *      from that realm, and not forged, we can go mark the
669          *      realms for this home server as active.
670          *
671          *      If we had done this check in the 'find realm by IP address'
672          *      function, then an attacker could force us to use a home
673          *      server which was inactive, by forging reply packets
674          *      which didn't match any request.  We would think that
675          *      the reply meant the home server was active, would
676          *      re-activate the realms, and THEN bounce the packet
677          *      as garbage.
678          */
679         for (cl = mainconfig.realms; cl != NULL; cl = cl->next) {
680                 if (oldreq->proxy_reply->src_ipaddr == cl->ipaddr) {
681                         if (oldreq->proxy_reply->src_port == cl->auth_port) {
682                                 cl->active = TRUE;
683                                 cl->last_reply = oldreq->timestamp;
684                         } else if (oldreq->proxy_reply->src_port == cl->acct_port) {
685                                 cl->acct_active = TRUE;
686                                 cl->last_reply = oldreq->timestamp;
687                         }
688                 }
689         }
690
691         return oldreq;
692 }
693
694 /*
695  *      Do more checks, this time on the REQUEST data structure.
696  *
697  *      The main purpose of this code is to handle proxied requests.
698  */
699 static REQUEST *request_ok(RADIUS_PACKET *packet, uint8_t *secret,
700                            rad_listen_t *listener)
701 {
702         REQUEST         *request = NULL;
703
704         /*
705          *      If the request has come in on the proxy FD, then
706          *      it's a proxy reply, so pass it through the code which
707          *      tries to find the original request, which we should
708          *      process, rather than processing the reply as a "new"
709          *      request.
710          */
711         if (listener->type == RAD_LISTEN_PROXY) {
712                 /*
713                  *      Find the old request, based on the current
714                  *      packet.
715                  */
716                 request = proxy_ok(packet);
717                 if (!request) {
718                         return NULL;
719                 }
720                 rad_assert(request->magic == REQUEST_MAGIC);
721
722                 /*
723                  *      We must have passed through the code below
724                  *      for the original request, which adds the
725                  *      reply packet to it.
726                  */
727                 rad_assert(request->reply != NULL);
728
729         } else {                /* remember the new request */
730                 /*
731                  *      A unique per-request counter.
732                  */
733                 static int request_num_counter = 0;
734
735                 request = request_alloc(); /* never fails */
736                 request->packet = packet;
737                 request->number = request_num_counter++;
738                 strNcpy(request->secret, (char *)secret,
739                         sizeof(request->secret));
740
741                 /*
742                  *      Remember the request.
743                  */
744                 rl_add(request);
745
746                 /*
747                  *      ADD IN "server identifier" from "listen"
748                  *      directive!
749                  */
750
751                 /*
752                  *      The request passes many of our sanity checks.
753                  *      From here on in, if anything goes wrong, we
754                  *      send a reject message, instead of dropping the
755                  *      packet.
756                  *
757                  *      Build the reply template from the request
758                  *      template.
759                  */
760                 rad_assert(request->reply == NULL);
761                 if ((request->reply = rad_alloc(0)) == NULL) {
762                         radlog(L_ERR, "No memory");
763                         exit(1);
764                 }
765                 request->reply->sockfd = request->packet->sockfd;
766                 request->reply->dst_ipaddr = request->packet->src_ipaddr;
767                 request->reply->src_ipaddr = request->packet->dst_ipaddr;
768                 request->reply->dst_port = request->packet->src_port;
769                 request->reply->src_port = request->packet->dst_port;
770                 request->reply->id = request->packet->id;
771                 request->reply->code = 0; /* UNKNOWN code */
772                 memcpy(request->reply->vector, request->packet->vector,
773                        sizeof(request->reply->vector));
774                 request->reply->vps = NULL;
775                 request->reply->data = NULL;
776                 request->reply->data_len = 0;
777         }
778
779         return request;
780 }
781
782
783 /*
784  *      The main guy.
785  */
786 int main(int argc, char *argv[])
787 {
788         REQUEST *request;
789         RADIUS_PACKET *packet;
790         u_char *secret;
791         unsigned char buffer[4096];
792         fd_set readfds;
793         int argval;
794         int pid;
795         int max_fd;
796         int status;
797         struct timeval *tv = NULL;
798 #ifdef HAVE_SIGACTION
799         struct sigaction act;
800 #endif
801         rad_listen_t *listener;
802
803         syslog_facility = LOG_DAEMON;
804
805 #ifdef OSFC2
806         set_auth_parameters(argc,argv);
807 #endif
808
809         if ((progname = strrchr(argv[0], '/')) == NULL)
810                 progname = argv[0];
811         else
812                 progname++;
813
814         debug_flag = 0;
815         spawn_flag = TRUE;
816         radius_dir = strdup(RADIUS_DIR);
817
818         /*
819          *      Ensure that the configuration is initialized.
820          */
821         memset(&mainconfig, 0, sizeof(mainconfig));
822 #ifdef HAVE_SIGACTION
823         memset(&act, 0, sizeof(act));
824         act.sa_flags = 0 ;
825         sigemptyset( &act.sa_mask ) ;
826 #endif
827
828         /*  Process the options.  */
829         while ((argval = getopt(argc, argv, "Aa:bcd:fg:hi:l:p:sSvxXyz")) != EOF) {
830
831                 switch(argval) {
832
833                         case 'A':
834                                 log_auth_detail = TRUE;
835                                 break;
836
837                         case 'a':
838                                 if (radacct_dir) xfree(radacct_dir);
839                                 radacct_dir = strdup(optarg);
840                                 break;
841
842                         case 'c':
843                                 /* ignore for backwards compatibility with Cistron */
844                                 break;
845
846                         case 'd':
847                                 if (radius_dir) xfree(radius_dir);
848                                 radius_dir = strdup(optarg);
849                                 break;
850
851                         case 'f':
852                                 dont_fork = TRUE;
853                                 break;
854
855                         case 'h':
856                                 usage(0);
857                                 break;
858
859                         case 'i':
860                                 if ((mainconfig.myip = ip_getaddr(optarg)) == INADDR_NONE) {
861                                         fprintf(stderr, "radiusd: %s: host unknown\n",
862                                                 optarg);
863                                         exit(1);
864                                 }
865                                 break;
866
867                         case 'l':
868                                 radlog_dir = strdup(optarg);
869                                 break;
870
871                                 /*
872                                  *  We should also have this as a configuration
873                                  *  file directive.
874                                  */
875                         case 'g':
876                                 syslog_facility = str2fac(optarg);
877                                 break;
878
879                         case 'S':
880                                 log_stripped_names++;
881                                 break;
882
883                         case 'p':
884                                 fprintf(stderr, "Ignoring deprecated command-line option -p");
885                                 break;
886
887                         case 's':       /* Single process mode */
888                                 spawn_flag = FALSE;
889                                 dont_fork = TRUE;
890                                 break;
891
892                         case 'v':
893                                 version();
894                                 break;
895
896                                 /*
897                                  *  BIG debugging mode for users who are
898                                  *  TOO LAZY to type '-sfxxyz -l stdout' themselves.
899                                  */
900                         case 'X':
901                                 spawn_flag = FALSE;
902                                 dont_fork = TRUE;
903                                 debug_flag += 2;
904                                 mainconfig.log_auth = TRUE;
905                                 mainconfig.log_auth_badpass = TRUE;
906                                 mainconfig.log_auth_goodpass = TRUE;
907                                 radlog_dir = strdup("stdout");
908                                 break;
909
910                         case 'x':
911                                 debug_flag++;
912                                 break;
913
914                         case 'y':
915                                 mainconfig.log_auth = TRUE;
916                                 mainconfig.log_auth_badpass = TRUE;
917                                 break;
918
919                         case 'z':
920                                 mainconfig.log_auth_badpass = TRUE;
921                                 mainconfig.log_auth_goodpass = TRUE;
922                                 break;
923
924                         default:
925                                 usage(1);
926                                 break;
927                 }
928         }
929
930         /*
931          *      Get our PID.
932          */
933         radius_pid = getpid();
934
935         /*  Read the configuration files, BEFORE doing anything else.  */
936         if (read_mainconfig(0) < 0) {
937                 exit(1);
938         }
939
940         /*
941          *      If we're NOT debugging, trap fatal signals, so we can
942          *      easily clean up after ourselves.
943          *
944          *      If we ARE debugging, don't trap them, so we can
945          *      dump core.
946          */
947         if ((mainconfig.allow_core_dumps == FALSE) && (debug_flag == 0)) {
948 #ifdef SIGSEGV
949 #ifdef HAVE_SIGACTION
950                 act.sa_handler = sig_fatal;
951                 sigaction(SIGSEGV, &act, NULL);
952 #else
953                 signal(SIGSEGV, sig_fatal);
954 #endif
955 #endif
956         }
957
958         /*  Reload the modules.  */
959         DEBUG2("radiusd:  entering modules setup");
960         if (setup_modules() < 0) {
961                 radlog(L_ERR|L_CONS, "Errors setting up modules");
962                 exit(1);
963         }
964
965 #ifdef HAVE_SYSLOG_H
966         /*
967          *  If they asked for syslog, then give it to them.
968          *  Also, initialize the logging facility with the
969          *  configuration that they asked for.
970          */
971         if (strcmp(radlog_dir, "syslog") == 0) {
972                 openlog(progname, LOG_PID, syslog_facility);
973                 radlog_dest = RADLOG_SYSLOG;
974         }
975         /* Do you want a warning if -g is used without a -l to activate it? */
976 #endif
977         if (strcmp(radlog_dir, "stdout") == 0) {
978                 radlog_dest = RADLOG_STDOUT;
979         } else if (strcmp(radlog_dir, "stderr") == 0) {
980                 radlog_dest = RADLOG_STDERR;
981         }
982
983         /*  Initialize the request list.  */
984         rl_init();
985
986         /*
987          *  Register built-in compare functions.
988          */
989         pair_builtincompare_init();
990
991 #ifdef WITH_SNMP
992         if (mainconfig.do_snmp) radius_snmp_init();
993 #endif
994
995         /*
996          *  Disconnect from session
997          */
998         if (debug_flag == 0 && dont_fork == FALSE) {
999                 pid = fork();
1000                 if(pid < 0) {
1001                         radlog(L_ERR|L_CONS, "Couldn't fork");
1002                         exit(1);
1003                 }
1004
1005                 /*
1006                  *  The parent exits, so the child can run in the background.
1007                  */
1008                 if(pid > 0) {
1009                         exit(0);
1010                 }
1011 #ifdef HAVE_SETSID
1012                 setsid();
1013 #endif
1014         }
1015
1016         /*
1017          *  Ensure that we're using the CORRECT pid after forking,
1018          *  NOT the one we started with.
1019          */
1020         radius_pid = getpid();
1021
1022
1023         /*
1024          *  Only write the PID file if we're running as a daemon.
1025          *
1026          *  And write it AFTER we've forked, so that we write the
1027          *  correct PID.
1028          */
1029         if (dont_fork == FALSE) {
1030                 FILE *fp;
1031
1032                 fp = fopen(mainconfig.pid_file, "w");
1033                 if (fp != NULL) {
1034                         /*
1035                          *      FIXME: What about following symlinks,
1036                          *      and having it over-write a normal file?
1037                          */
1038                         fprintf(fp, "%d\n", (int) radius_pid);
1039                         fclose(fp);
1040                 } else {
1041                         radlog(L_ERR|L_CONS, "Failed creating PID file %s: %s\n",
1042                                mainconfig.pid_file, strerror(errno));
1043                         exit(1);
1044                 }
1045         }
1046
1047         /*
1048          *      If we're running as a daemon, close the default file
1049          *      descriptors, AFTER forking.
1050          */
1051         if (debug_flag == FALSE) {
1052                 int devnull;
1053
1054                 devnull = open("/dev/null", O_RDWR);
1055                 if (devnull < 0) {
1056                         radlog(L_ERR|L_CONS, "Failed opening /dev/null: %s\n",
1057                                strerror(errno));
1058                         exit(1);
1059                 }
1060                 dup2(devnull, STDIN_FILENO);
1061                 dup2(devnull, STDOUT_FILENO);
1062                 dup2(devnull, STDERR_FILENO);
1063                 close(devnull);
1064         }
1065
1066 #ifdef HAVE_PTHREAD_H
1067         /*
1068          *  If we're spawning children, set up the thread pool.
1069          */
1070         if (spawn_flag == TRUE) {
1071                 thread_pool_init();
1072         }
1073 #else
1074         /*
1075          *      Without threads, we ALWAYS run in single-server mode.
1076          */
1077         spawn_flag = FALSE;
1078 #endif
1079
1080         /*
1081          *  Use linebuffered or unbuffered stdout if
1082          *  the debug flag is on.
1083          */
1084         if (debug_flag == TRUE)
1085                 setlinebuf(stdout);
1086
1087         /*
1088          *      Print out which ports we're listening on.
1089          */
1090         for (listener = mainconfig.listen;
1091              listener != NULL;
1092              listener = listener->next) {
1093                 if (listener->ipaddr == INADDR_ANY) {
1094                         strcpy((char *)buffer, "*");
1095                 } else {
1096                         ip_ntoa((char *)buffer, listener->ipaddr);
1097                 }
1098                 
1099                 switch (listener->type) {
1100                 case RAD_LISTEN_AUTH:
1101                         DEBUG("Listening on authentication %s:%d",
1102                               buffer, listener->port);
1103                         break;
1104
1105                 case RAD_LISTEN_ACCT:
1106                         DEBUG("Listening on accounting %s:%d",
1107                               buffer, listener->port);
1108                         break;
1109
1110                 case RAD_LISTEN_PROXY:
1111                         DEBUG("Listening on proxy %s:%d",
1112                               buffer, listener->port);
1113                         break;
1114
1115                 default:
1116                         break;
1117                 }
1118         }
1119
1120         /*
1121          *      Now that we've set everything up, we can install the signal
1122          *      handlers.  Before this, if we get any signal, we don't know
1123          *      what to do, so we might as well do the default, and die.
1124          */
1125         signal(SIGPIPE, SIG_IGN);
1126 #ifdef HAVE_SIGACTION
1127         act.sa_handler = sig_hup;
1128         sigaction(SIGHUP, &act, NULL);
1129         act.sa_handler = sig_fatal;
1130         sigaction(SIGTERM, &act, NULL);
1131 #else
1132         signal(SIGHUP, sig_hup);
1133         signal(SIGTERM, sig_fatal);
1134 #endif
1135         /*
1136          *      If we're debugging, then a CTRL-C will cause the
1137          *      server to die immediately.  Use SIGTERM to shut down
1138          *      the server cleanly in that case.
1139          */
1140         if (debug_flag == 0) {
1141 #ifdef HAVE_SIGACTION
1142                 act.sa_handler = sig_fatal;
1143                 sigaction(SIGINT, &act, NULL);
1144                 sigaction(SIGQUIT, &act, NULL);
1145 #else
1146                 signal(SIGINT, sig_fatal);
1147                 signal(SIGQUIT, sig_fatal);
1148 #endif
1149         }
1150
1151         radlog(L_INFO, "Ready to process requests.");
1152         start_time = time(NULL);
1153
1154         /*
1155          *  Receive user requests
1156          */
1157         for (;;) {
1158                 /*
1159                  *      If we've been told to exit, then do so,
1160                  *      even if we have data waiting.
1161                  */
1162                 if (do_exit) {
1163                         DEBUG("Exiting...");
1164
1165                         /*
1166                          *      Ignore the TERM signal: we're about
1167                          *      to die.
1168                          */
1169                         signal(SIGTERM, SIG_IGN);
1170
1171                         /*
1172                          *      Send a TERM signal to all associated
1173                          *      processes (including us, which gets
1174                          *      ignored.)
1175                          */
1176                         kill(-radius_pid, SIGTERM);
1177
1178                         /*
1179                          *      FIXME: Kill child threads, and
1180                          *      clean up?
1181                          */
1182
1183                         /*
1184                          *      Detach any modules.
1185                          */
1186                         detach_modules();
1187
1188                         /*
1189                          *      FIXME: clean up any active REQUEST
1190                          *      handles.
1191                          */
1192
1193                         /*
1194                          *      We're exiting, so we can delete the PID
1195                          *      file.  (If it doesn't exist, we can ignore
1196                          *      the error returned by unlink)
1197                          */
1198                         if (dont_fork == FALSE) {
1199                                 unlink(mainconfig.pid_file);
1200                         }
1201
1202                         /*
1203                          *      Free the configuration items.
1204                          */
1205                         free_mainconfig();
1206
1207                         /*
1208                          *      SIGTERM gets do_exit=0,
1209                          *      and we want to exit cleanly.
1210                          *
1211                          *      Other signals make us exit
1212                          *      with an error status.
1213                          */
1214                         exit(do_exit - 1);
1215                 }
1216
1217                 if (need_reload) {
1218 #ifdef HAVE_PTHREAD_H
1219                         /*
1220                          *      Threads: wait for all threads to stop
1221                          *      processing before re-loading the
1222                          *      config, so we don't pull the rug out
1223                          *      from under them.
1224                          */
1225                         int max_wait = 0;
1226                         if (spawn_flag) for(;;) {
1227                                 /*
1228                                  * Block until there are '0' threads
1229                                  * with a REQUEST handle.
1230                                  */
1231                                 sig_hup_block = TRUE;
1232                                 if( (total_active_threads() == 0) ||
1233                                      (max_wait >= 5) ) {
1234                                   sig_hup_block = FALSE;
1235                                   break;
1236                                 }
1237                                 sleep(1);
1238                                 max_wait++;
1239                         }
1240 #endif
1241                         if (read_mainconfig(TRUE) < 0) {
1242                                 exit(1);
1243                         }
1244
1245                         /*  Reload the modules.  */
1246                         DEBUG2("radiusd:  entering modules setup");
1247                         if (setup_modules() < 0) {
1248                                 radlog(L_ERR|L_CONS, "Errors setting up modules");
1249                                 exit(1);
1250                         }
1251
1252                         need_reload = FALSE;
1253                         radlog(L_INFO, "Ready to process requests.");
1254                 }
1255
1256                 FD_ZERO(&readfds);
1257                 max_fd = 0;
1258
1259                 /*
1260                  *      Loop over all the listening FD's.
1261                  */
1262                 for (listener = mainconfig.listen;
1263                      listener != NULL;
1264                      listener = listener->next) {
1265                         FD_SET(listener->fd, &readfds);
1266                         if (listener->fd > max_fd) max_fd = listener->fd;
1267                 }
1268
1269 #ifdef WITH_SNMP
1270                 if (mainconfig.do_snmp &&
1271                     (rad_snmp.smux_fd >= 0)) {
1272                         FD_SET(rad_snmp.smux_fd, &readfds);
1273                         if (rad_snmp.smux_fd > max_fd) max_fd = rad_snmp.smux_fd;
1274                 }
1275 #endif
1276                 status = select(max_fd + 1, &readfds, NULL, NULL, tv);
1277                 if (status == -1) {
1278                         /*
1279                          *      On interrupts, we clean up the request
1280                          *      list.  We then continue with the loop,
1281                          *      so that if we're supposed to exit,
1282                          *      then the code at the start of the loop
1283                          *      catches that, and exits.
1284                          */
1285                         if (errno == EINTR) {
1286                                 tv = rl_clean_list(time(NULL));
1287                                 continue;
1288                         }
1289                         radlog(L_ERR, "Unexpected error in select(): %s",
1290                                         strerror(errno));
1291                         exit(1);
1292                 }
1293
1294                 time_now = time(NULL);
1295 #ifndef HAVE_PTHREAD_H
1296                 /*
1297                  *      If there are no child threads, then there may
1298                  *      be child processes.  In that case, wait for
1299                  *      their exit status, and throw that exit status
1300                  *      away.  This helps get rid of zxombie children.
1301                  */
1302                 while (waitpid(-1, &argval, WNOHANG) > 0) {
1303                         /* do nothing */
1304                 }
1305 #endif
1306
1307                 /*
1308                  *      Loop over the open socket FD's, reading any data.
1309                  */
1310                 for (listener = mainconfig.listen;
1311                      listener != NULL;
1312                      listener = listener->next) {
1313                         RAD_REQUEST_FUNP fun;
1314
1315                         if (!FD_ISSET(listener->fd, &readfds))
1316                                 continue;
1317                         /*
1318                          *  Receive the packet.
1319                          */
1320                         if (sig_hup_block != FALSE) {
1321                           continue;
1322                         }
1323                         packet = rad_recv(listener->fd);
1324                         if (packet == NULL) {
1325                                 radlog(L_ERR, "%s", librad_errstr);
1326                                 continue;
1327                         }
1328
1329                         /*
1330                          *      If the destination IP is unknown, check
1331                          *      if the listener has a known IP.  If so,
1332                          *      use that.
1333                          */
1334                         if ((packet->dst_ipaddr == htonl(INADDR_ANY)) &&
1335                             (packet->dst_ipaddr != listener->ipaddr)) {
1336                                 packet->dst_ipaddr = listener->ipaddr;
1337                         }
1338
1339                         /*
1340                          *      Fill in the destination port.
1341                          */
1342                         packet->dst_port = listener->port;
1343
1344                         RAD_SNMP_TYPE_INC(listener, total_requests);
1345
1346                         /*
1347                          *      FIXME: Move this next check into
1348                          *      the packet_ok() function, and add
1349                          *      a 'secret' to the RAIDUS_PACKET
1350                          *      data structure.  This involves changing
1351                          *      a bunch of code, but it's probably the
1352                          *      best thing to do.
1353                          */
1354
1355                         /*
1356                          *  Check if we know this client for
1357                          *  authentication and accounting.  Check if we know
1358                          *  this proxy for proxying.
1359                          */
1360                         if (listener->type != RAD_LISTEN_PROXY) {
1361                                 RADCLIENT *cl;
1362                                 if ((cl = client_find(packet->src_ipaddr)) == NULL) {
1363                                         RAD_SNMP_TYPE_INC(listener, total_invalid_requests);
1364
1365                                         radlog(L_ERR, "Ignoring request from unknown client %s:%d",
1366                                         ip_ntoa((char *)buffer, packet->src_ipaddr),
1367                                         packet->src_port);
1368                                         rad_free(&packet);
1369                                         continue;
1370                                 }
1371                                 secret = cl->secret;
1372                         } else {    /* It came in on the proxy port */
1373                                 REALM *rl;
1374                                 if ((rl = realm_findbyaddr(packet->src_ipaddr,packet->src_port)) == NULL) {
1375                                         radlog(L_ERR, "Ignoring request from unknown home server %s:%d",
1376                                         ip_ntoa((char *)buffer, packet->src_ipaddr),
1377                                         packet->src_port);
1378                                         rad_free(&packet);
1379                                         continue;
1380                                 }
1381
1382                                 /*
1383                                  *      The secret isn't needed here,
1384                                  *      as it's already in the old request
1385                                  */
1386                                 secret = NULL;
1387                         }
1388
1389                         /*
1390                          *      Do some simple checks before we process
1391                          *      the request.
1392                          */
1393                         if ((fun = packet_ok(packet, listener)) == NULL) {
1394                                 rad_free(&packet);
1395                                 continue;
1396                         }
1397                         
1398                         /*
1399                          *      Allocate a new request for packets from
1400                          *      our clients, OR find the old request,
1401                          *      for packets which are replies from a home
1402                          *      server.
1403                          */
1404                         request = request_ok(packet, secret, listener);
1405                         if (!request) {
1406                                 rad_free(&packet);
1407                                 continue;
1408                         }
1409
1410                         /*
1411                          *      Drop the request into the thread pool,
1412                          *      and let the thread pool take care of
1413                          *      doing something with it.
1414                          */
1415 #ifdef HAVE_PTHREAD_H
1416                         if (spawn_flag) {
1417                                 if (!thread_pool_addrequest(request, fun)) {
1418                                         /*
1419                                          *      FIXME: Maybe just drop
1420                                          *      the packet on the floor?
1421                                          */
1422                                         request_reject(request);
1423                                         request->finished = TRUE;
1424                                 }
1425                         } else
1426 #endif
1427                                 rad_respond(request, fun);
1428                 } /* loop over listening sockets*/
1429
1430 #ifdef WITH_SNMP
1431                 if (mainconfig.do_snmp) {
1432                         /*
1433                          *  After handling all authentication/accounting
1434                          *  requests, THEN process any pending SMUX/SNMP
1435                          *  queries.
1436                          *
1437                          *  Note that the handling is done in the main server,
1438                          *  which probably isn't a Good Thing.  It really
1439                          *  should be wrapped, and handled in a thread pool.
1440                          */
1441                         if ((rad_snmp.smux_fd >= 0) &&
1442                             FD_ISSET(rad_snmp.smux_fd, &readfds) &&
1443                             (rad_snmp.smux_event == SMUX_READ)) {
1444                                 smux_read();
1445                         }
1446
1447                         /*
1448                          *  If we've got to re-connect, then do so now,
1449                          *  before calling select again.
1450                          */
1451                         if (rad_snmp.smux_event == SMUX_CONNECT) {
1452                                 smux_connect();
1453                         }
1454                 }
1455 #endif
1456
1457                 /*
1458                  *  After processing all new requests,
1459                  *  check if we've got to delete old requests
1460                  *  from the request list.
1461                  */
1462                 tv = rl_clean_list(time_now);
1463 #ifdef HAVE_PTHREAD_H
1464
1465                 /*
1466                  *      Only clean the thread pool if we're spawning
1467                  *      child threads. 
1468                  */
1469                 if (spawn_flag) {
1470                         thread_pool_clean(time_now);
1471                 }
1472 #endif
1473
1474
1475         } /* loop forever */
1476 }
1477
1478
1479 /*
1480  * FIXME:  The next two functions should all
1481  * be in a module.  But not until we have
1482  * more control over module execution.
1483  * -jcarneal
1484  */
1485
1486 /*
1487  *  Lowercase the string value of a pair.
1488  */
1489 static int rad_lowerpair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1490         if (vp == NULL) {
1491                 return -1;
1492         }
1493
1494         rad_lowercase((char *)vp->strvalue);
1495         DEBUG2("rad_lowerpair:  %s now '%s'", vp->name, vp->strvalue);
1496         return 0;
1497 }
1498
1499 /*
1500  *  Remove spaces in a pair.
1501  */
1502 static int rad_rmspace_pair(REQUEST *request UNUSED, VALUE_PAIR *vp) {
1503         if (vp == NULL) {
1504                 return -1;
1505         }
1506
1507         rad_rmspace((char *)vp->strvalue);
1508         vp->length = strlen((char *)vp->strvalue);
1509         DEBUG2("rad_rmspace_pair:  %s now '%s'", vp->name, vp->strvalue);
1510
1511         return 0;
1512 }
1513
1514 /*
1515  *  Respond to a request packet.
1516  *
1517  *  Maybe we reply, maybe we don't.
1518  *  Maybe we proxy the request to another server, or else maybe
1519  *  we replicate it to another server.
1520  */
1521 int rad_respond(REQUEST *request, RAD_REQUEST_FUNP fun)
1522 {
1523         RADIUS_PACKET *packet, *original;
1524         const char *secret;
1525         int finished = FALSE;
1526         int reprocess = 0;
1527
1528         rad_assert(request->magic == REQUEST_MAGIC);
1529
1530         /*
1531          *      Don't decode the packet if it's an internal "fake"
1532          *      request.  Instead, just skip ahead to processing it.
1533          */
1534         if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1535                 goto skip_decode;
1536         }
1537
1538         /*
1539          *  Put the decoded packet into it's proper place.
1540          */
1541         if (request->proxy_reply != NULL) {
1542                 packet = request->proxy_reply;
1543                 secret = request->proxysecret;
1544                 original = request->proxy;
1545         } else {
1546                 packet = request->packet;
1547                 secret = request->secret;
1548                 original = NULL;
1549         }
1550
1551         /*
1552          *  Decode the packet, verifying it's signature,
1553          *  and parsing the attributes into structures.
1554          *
1555          *  Note that we do this CPU-intensive work in
1556          *  a child thread, not the master.  This helps to
1557          *  spread the load a little bit.
1558          *
1559          *  Internal requests (ones that never go on the
1560          *  wire) have ->data==NULL (data is the wire
1561          *  format) and don't need to be "decoded"
1562          */
1563         if (packet->data && rad_decode(packet, original, secret) != 0) {
1564                 radlog(L_ERR, "%s", librad_errstr);
1565                 request_reject(request);
1566                 goto finished_request;
1567         }
1568
1569         /*
1570          *  For proxy replies, remove non-allowed
1571          *  attributes from the list of VP's.
1572          */
1573         if (request->proxy) {
1574                 int rcode;
1575                 rcode = proxy_receive(request);
1576                 switch (rcode) {
1577                 default:  /* Don't Do Anything */
1578                         break;
1579                 case RLM_MODULE_FAIL:
1580                         /* on error just continue with next request */
1581                         goto next_request;
1582                 case RLM_MODULE_HANDLED:
1583                         /* if this was a replicated request, mark it as
1584                          * finished first, because it was postponed
1585                          */
1586                         goto finished_request;
1587                 }
1588
1589         } else {
1590                 /*
1591                  *      This is the initial incoming request which
1592                  *      we're processing.
1593                  *
1594                  *      Some requests do NOT get cached, as they
1595                  *      CANNOT possibly have duplicates.  Set the
1596                  *      magic option here.
1597                  *
1598                  *      Status-Server messages are easy to generate,
1599                  *      so we toss them as soon as we see a reply.
1600                  *
1601                  *      Accounting-Request packets WITHOUT an
1602                  *      Acct-Delay-Time attribute are NEVER
1603                  *      duplicated, as RFC 2866 Section 4.1 says that
1604                  *      the Acct-Delay-Time MUST be updated when the
1605                  *      packet is re-sent, which means the packet
1606                  *      changes, so it MUST have a new identifier and
1607                  *      Request Authenticator.  */
1608                 if ((request->packet->code == PW_STATUS_SERVER) ||
1609                     ((request->packet->code == PW_ACCOUNTING_REQUEST) &&
1610                      (pairfind(request->packet->vps, PW_ACCT_DELAY_TIME) == NULL))) {
1611                         request->options |= RAD_REQUEST_OPTION_DONT_CACHE;
1612                 }
1613         }
1614
1615  skip_decode:
1616         /*
1617          *      We should have a User-Name attribute now.
1618          */
1619         if (request->username == NULL) {
1620                 request->username = pairfind(request->packet->vps,
1621                                 PW_USER_NAME);
1622         }
1623
1624         /*
1625          *  FIXME:  All this lowercase/nospace junk will be moved
1626          *  into a module after module failover is fully in place
1627          *
1628          *  See if we have to lower user/pass before processing
1629          */
1630         if(strcmp(mainconfig.do_lower_user, "before") == 0)
1631                 rad_lowerpair(request, request->username);
1632         if(strcmp(mainconfig.do_lower_pass, "before") == 0)
1633                 rad_lowerpair(request,
1634                               pairfind(request->packet->vps, PW_PASSWORD));
1635
1636         if(strcmp(mainconfig.do_nospace_user, "before") == 0)
1637                 rad_rmspace_pair(request, request->username);
1638         if(strcmp(mainconfig.do_nospace_pass, "before") == 0)
1639                 rad_rmspace_pair(request,
1640                                  pairfind(request->packet->vps, PW_PASSWORD));
1641
1642         (*fun)(request);
1643
1644         /*
1645          *      If the request took too long to process, don't do
1646          *      anything else.
1647          */
1648         if (request->options & RAD_REQUEST_OPTION_REJECTED) {
1649                 finished = TRUE;
1650                 goto postpone_request;
1651         }
1652
1653         /*
1654          *      Reprocess if we rejected last time
1655          */
1656         if ((fun == rad_authenticate) &&
1657             (request->reply->code == PW_AUTHENTICATION_REJECT)) {
1658           /* See if we have to lower user/pass after processing */
1659           if (strcmp(mainconfig.do_lower_user, "after") == 0) {
1660                   rad_lowerpair(request, request->username);
1661                   reprocess = 1;
1662           }
1663           if (strcmp(mainconfig.do_lower_pass, "after") == 0) {
1664                 rad_lowerpair(request,
1665                               pairfind(request->packet->vps, PW_PASSWORD));
1666                 reprocess = 1;
1667           }
1668           if (strcmp(mainconfig.do_nospace_user, "after") == 0) {
1669                   rad_rmspace_pair(request, request->username);
1670                   reprocess = 1;
1671           }
1672           if (strcmp(mainconfig.do_nospace_pass, "after") == 0) {
1673                   rad_rmspace_pair(request,
1674                                    pairfind(request->packet->vps, PW_PASSWORD));
1675                   reprocess = 1;
1676           }
1677
1678           /*
1679            *    If we're re-processing the request, re-set it.
1680            */
1681           if (reprocess) {
1682                   pairfree(&request->config_items);
1683                   pairfree(&request->reply->vps);
1684                   request->reply->code = 0;
1685                   (*fun)(request);
1686           }
1687         }
1688
1689         /*
1690          *      Status-Server requests NEVER get proxied.
1691          */
1692         if (mainconfig.proxy_requests) {
1693                 if ((request->packet->code != PW_STATUS_SERVER) &&
1694                     ((request->options & RAD_REQUEST_OPTION_PROXIED) == 0)) {
1695                         int rcode;
1696
1697                         /*
1698                          *      Try to proxy this request.
1699                          */
1700                         rcode = proxy_send(request);
1701
1702                         switch (rcode) {
1703                         default:
1704                                 break;
1705
1706                         /*
1707                          *  There was an error trying to proxy the request.
1708                          *  Drop it on the floor.
1709                          */
1710                         case RLM_MODULE_FAIL:
1711                                 DEBUG2("Error trying to proxy request %d: Rejecting it", request->number);
1712                                 request_reject(request);
1713                                 goto finished_request;
1714                                 break;
1715
1716                         /*
1717                          *  The pre-proxy module has decided to reject
1718                          *  the request.  Do so.
1719                          */
1720                         case RLM_MODULE_REJECT:
1721                                 DEBUG2("Request %d rejected in proxy_send.", request->number);
1722                                 request_reject(request);
1723                                 goto finished_request;
1724                                 break;
1725
1726                         /*
1727                          *  If the proxy code has handled the request,
1728                          *  then postpone more processing, until we get
1729                          *  the reply packet from the home server.
1730                          */
1731                         case RLM_MODULE_HANDLED:
1732                                 goto postpone_request;
1733                                 break;
1734                         }
1735
1736                         /*
1737                          *  Else rcode==RLM_MODULE_NOOP
1738                          *  and the proxy code didn't do anything, so
1739                          *  we continue handling the request here.
1740                          */
1741                 }
1742         } else if ((request->packet->code == PW_AUTHENTICATION_REQUEST) &&
1743                    (request->reply->code == 0)) {
1744                 /*
1745                  *  We're not configured to reply to the packet,
1746                  *  and we're not proxying, so the DEFAULT behaviour
1747                  *  is to REJECT the user.
1748                  */
1749                 DEBUG2("There was no response configured: rejecting request %d", request->number);
1750                 request_reject(request);
1751                 goto finished_request;
1752         }
1753
1754         /*
1755          *  If we have a reply to send, copy the Proxy-State
1756          *  attributes from the request to the tail of the reply,
1757          *  and send the packet.
1758          */
1759         rad_assert(request->magic == REQUEST_MAGIC);
1760         if (request->reply->code != 0) {
1761                 VALUE_PAIR *vp = NULL;
1762
1763                 /*
1764                  *      Perform RFC limitations on outgoing replies.
1765                  */
1766                 rfc_clean(request->reply);
1767
1768                 /*
1769                  *      Need to copy Proxy-State from request->packet->vps
1770                  */
1771                 vp = paircopy2(request->packet->vps, PW_PROXY_STATE);
1772                 if (vp) pairadd(&(request->reply->vps), vp);
1773
1774                 /*
1775                  *  If the request isn't an authentication reject, OR
1776                  *  it's a reject, but the reject_delay is zero, then
1777                  *  send it immediately.
1778                  *
1779                  *  Otherwise, delay the authentication reject to shut
1780                  *  up DoS attacks.
1781                  */
1782                 if ((request->reply->code != PW_AUTHENTICATION_REJECT) ||
1783                     (mainconfig.reject_delay == 0)) {
1784                         /*
1785                          *      Send the response. IF it's a real request.
1786                          */
1787                         if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) == 0) {
1788                                 rad_send(request->reply, request->packet,
1789                                          request->secret);
1790                         }
1791                         /*
1792                          *      Otherwise, it's a tunneled request.
1793                          *      Don't do anything.
1794                          */
1795                 } else {
1796                         DEBUG2("Delaying request %d for %d seconds",
1797                                request->number, mainconfig.reject_delay);
1798                         request->options |= RAD_REQUEST_OPTION_DELAYED_REJECT;
1799                 }
1800         }
1801
1802         /*
1803          *  We're done processing the request, set the
1804          *  request to be finished, clean up as necessary,
1805          *  and forget about the request.
1806          */
1807
1808 finished_request:
1809
1810         /*
1811          *      Don't decode the packet if it's an internal "fake"
1812          *      request.  Instead, just skip ahead to processing it.
1813          */
1814         if ((request->options & RAD_REQUEST_OPTION_FAKE_REQUEST) != 0) {
1815                 goto skip_free;
1816         }
1817
1818         /*
1819          *  We're done handling the request.  Free up the linked
1820          *  lists of value pairs.  This might take a long time,
1821          *  so it's more efficient to do it in a child thread,
1822          *  instead of in the main handler when it eventually
1823          *  gets around to deleting the request.
1824          *
1825          *  Also, no one should be using these items after the
1826          *  request is finished, and the reply is sent.  Cleaning
1827          *  them up here ensures that they're not being used again.
1828          *
1829          *  Hmm... cleaning them up in the child thread also seems
1830          *  to make the server run more efficiently!
1831          *
1832          *  If we've delayed the REJECT, then do NOT clean up the request,
1833          *  as we haven't created the REJECT message yet.
1834          */
1835         if ((request->options & RAD_REQUEST_OPTION_DELAYED_REJECT) == 0) {
1836                 if (request->packet) {
1837                         pairfree(&request->packet->vps);
1838                         request->username = NULL;
1839                         request->password = NULL;
1840                 }
1841
1842                 /*
1843                  *  If we've sent a reply to the NAS, then this request is
1844                  *  pretty much finished, and we have no more need for any
1845                  *  of the value-pair's in it, including the proxy stuff.
1846                  */
1847                 if (request->reply->code != 0) {
1848                         pairfree(&request->reply->vps);
1849                 }
1850         }
1851
1852         pairfree(&request->config_items);
1853         if (request->proxy) {
1854                 pairfree(&request->proxy->vps);
1855         }
1856         if (request->proxy_reply) {
1857                 pairfree(&request->proxy_reply->vps);
1858         }
1859
1860  skip_free:
1861         DEBUG2("Finished request %d", request->number);
1862         finished = TRUE;
1863
1864         /*
1865          *  Go to the next request, without marking
1866          *  the current one as finished.
1867          *
1868          *  Hmm... this may not be the brightest thing to do.
1869          */
1870 next_request:
1871         DEBUG2("Going to the next request");
1872
1873 postpone_request:
1874 #ifdef HAVE_PTHREAD_H
1875         /*
1876          *  We are finished with the child thread.  The thread is detached,
1877          *  so that when it exits, there's nothing more for the server
1878          *  to do.
1879          *
1880          *  If we're running with thread pools, then this frees up the
1881          *  thread in the pool for another request.
1882          */
1883         request->child_pid = NO_SUCH_CHILD_PID;
1884 #endif
1885         request->finished = finished; /* do as the LAST thing before exiting */
1886         return 0;
1887 }
1888
1889
1890 /*
1891  *  Display the syntax for starting this program.
1892  */
1893 static void NEVER_RETURNS usage(int status)
1894 {
1895         FILE *output = status?stderr:stdout;
1896
1897         fprintf(output,
1898                         "Usage: %s [-a acct_dir] [-d db_dir] [-l log_dir] [-i address] [-p port] [-AcfnsSvXxyz]\n", progname);
1899         fprintf(output, "Options:\n\n");
1900         fprintf(output, "  -a acct_dir     use accounting directory 'acct_dir'.\n");
1901         fprintf(output, "  -A              Log auth detail.\n");
1902         fprintf(output, "  -d db_dir       Use database directory 'db_dir'.\n");
1903         fprintf(output, "  -f              Run as a foreground process, not a daemon.\n");
1904         fprintf(output, "  -h              Print this help message.\n");
1905         fprintf(output, "  -i address      Listen only in the given IP address.\n");
1906         fprintf(output, "  -l log_dir      Log messages to 'log_dir'.  Special values are:\n");
1907         fprintf(output, "                  stdout == log all messages to standard output.\n");
1908         fprintf(output, "                  syslog == log all messages to the system logger.\n");
1909         fprintf(output, "  -p port         Bind to 'port', and not to the radius/udp, or 1646/udp.\n");
1910         fprintf(output, "  -s              Do not spawn child processes to handle requests.\n");
1911         fprintf(output, "  -S              Log stripped names.\n");
1912         fprintf(output, "  -v              Print server version information.\n");
1913         fprintf(output, "  -X              Turn on full debugging. (Means: -sfxxyz -l stdout)\n");
1914         fprintf(output, "  -x              Turn on partial debugging. (-xx gives more debugging).\n");
1915         fprintf(output, "  -y              Log authentication failures, with password.\n");
1916         fprintf(output, "  -z              Log authentication successes, with password.\n");
1917         exit(status);
1918 }
1919
1920
1921 /*
1922  *      We got a fatal signal.
1923  */
1924 static void sig_fatal(int sig)
1925 {
1926         switch(sig) {
1927                 case SIGTERM:
1928                         do_exit = 1;
1929                         break;
1930                 default:
1931                         do_exit = 2;
1932                         break;
1933         }
1934 }
1935
1936
1937 /*
1938  *  We got the hangup signal.
1939  *  Re-read the configuration files.
1940  */
1941 /*ARGSUSED*/
1942 static void sig_hup(int sig)
1943 {
1944         sig = sig; /* -Wunused */
1945         reset_signal(SIGHUP, sig_hup);
1946
1947         /*
1948          *  Only do the reload if we're the main server, both
1949          *  for processes, and for threads.
1950          */
1951         if (getpid() == radius_pid) {
1952                 need_reload = TRUE;
1953         }
1954 #ifdef WITH_SNMP
1955         if (mainconfig.do_snmp) {
1956                 rad_snmp.smux_failures = 0;
1957                 rad_snmp.smux_event = SMUX_CONNECT;
1958         }
1959 #endif
1960 }
1961
1962
1963 /*
1964  *      Process and reply to a server-status request.
1965  *      Like rad_authenticate and rad_accounting this should
1966  *      live in it's own file but it's so small we don't bother.
1967  */
1968 static int rad_status_server(REQUEST *request)
1969 {
1970         char            reply_msg[64];
1971         time_t          t;
1972         VALUE_PAIR      *vp;
1973
1974         /*
1975          *      Reply with an ACK. We might want to add some more
1976          *      interesting reply attributes, such as server uptime.
1977          */
1978         t = request->timestamp - start_time;
1979         sprintf(reply_msg, "FreeRADIUS up %d day%s, %02d:%02d",
1980                 (int)(t / 86400), (t / 86400) == 1 ? "" : "s",
1981                 (int)((t / 3600) % 24), (int)(t / 60) % 60);
1982         request->reply->code = PW_AUTHENTICATION_ACK;
1983
1984         vp = pairmake("Reply-Message", reply_msg, T_OP_SET);
1985         pairadd(&request->reply->vps, vp); /* don't need to check if !vp */
1986
1987         return 0;
1988 }