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