54dc3a692f0b430bfbd28413534436b0e6872c47
[freeradius.git] / src / main / listen.c
1 /*
2  * listen.c     Handle socket stuff
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2005,2006  The FreeRADIUS server project
21  * Copyright 2005  Alan DeKok <aland@ox.org>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/modules.h>
29 #include <freeradius-devel/rad_assert.h>
30 #include <freeradius-devel/vqp.h>
31 #include <freeradius-devel/dhcp.h>
32
33 #include <freeradius-devel/vmps.h>
34 #include <freeradius-devel/detail.h>
35
36 #ifdef WITH_UDPFROMTO
37 #include <freeradius-devel/udpfromto.h>
38 #endif
39
40 #ifdef HAVE_SYS_RESOURCE_H
41 #include <sys/resource.h>
42 #endif
43
44 #ifdef HAVE_NET_IF_H
45 #include <net/if.h>
46 #endif
47
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51
52
53 void print_packet(RADIUS_PACKET *packet)
54 {
55         char src[256], dst[256];
56
57         ip_ntoh(&packet->src_ipaddr, src, sizeof(src));
58         ip_ntoh(&packet->dst_ipaddr, dst, sizeof(dst));
59
60         fprintf(stderr, "ID %d: %s %d -> %s %d\n", packet->id,
61                 src, packet->src_port, dst, packet->dst_port);
62
63 }
64
65
66 /*
67  *      We'll use this below.
68  */
69 typedef int (*rad_listen_parse_t)(CONF_SECTION *, rad_listen_t *);
70 typedef void (*rad_listen_free_t)(rad_listen_t *);
71
72 typedef struct rad_listen_master_t {
73         rad_listen_parse_t      parse;
74         rad_listen_free_t       free;
75         rad_listen_recv_t       recv;
76         rad_listen_send_t       send;
77         rad_listen_print_t      print;
78         rad_listen_encode_t     encode;
79         rad_listen_decode_t     decode;
80 } rad_listen_master_t;
81
82 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type);
83
84 /*
85  *      Find a per-socket client.
86  */
87 RADCLIENT *client_listener_find(const rad_listen_t *listener,
88                                 const fr_ipaddr_t *ipaddr, int src_port)
89 {
90 #ifdef WITH_DYNAMIC_CLIENTS
91         int rcode;
92         REQUEST *request;
93         RADCLIENT *created;
94 #endif
95         time_t now;
96         RADCLIENT *client;
97         RADCLIENT_LIST *clients;
98         listen_socket_t *sock;
99
100         rad_assert(listener != NULL);
101         rad_assert(ipaddr != NULL);
102
103         sock = listener->data;
104         clients = sock->clients;
105
106         /*
107          *      This HAS to have been initialized previously.
108          */
109         rad_assert(clients != NULL);
110
111         client = client_find(clients, ipaddr,sock->proto);
112         if (!client) {
113                 char name[256], buffer[128];
114                                         
115 #ifdef WITH_DYNAMIC_CLIENTS
116         unknown:                /* used only for dynamic clients */
117 #endif
118
119                 /*
120                  *      DoS attack quenching, but only in daemon mode.
121                  *      If they're running in debug mode, show them
122                  *      every packet.
123                  */
124                 if (debug_flag == 0) {
125                         static time_t last_printed = 0;
126
127                         now = time(NULL);
128                         if (last_printed == now) return NULL;
129                         
130                         last_printed = now;
131                 }
132
133                 listener->print(listener, name, sizeof(name));
134
135                 radlog(L_ERR, "Ignoring request to %s from unknown client %s port %d"
136 #ifdef WITH_TCP
137                        " proto %s"
138 #endif
139                        , name, inet_ntop(ipaddr->af, &ipaddr->ipaddr,
140                                          buffer, sizeof(buffer)), src_port
141 #ifdef WITH_TCP
142                        , (sock->proto == IPPROTO_UDP) ? "udp" : "tcp"
143 #endif
144                        );
145                 return NULL;
146         }
147
148 #ifndef WITH_DYNAMIC_CLIENTS
149         return client;          /* return the found client. */
150 #else
151
152         /*
153          *      No server defined, and it's not dynamic.  Return it.
154          */
155         if (!client->client_server && !client->dynamic) return client;
156
157         now = time(NULL);
158         
159         /*
160          *      It's a dynamically generated client, check it.
161          */
162         if (client->dynamic && (src_port != 0)) {
163                 /*
164                  *      Lives forever.  Return it.
165                  */
166                 if (client->lifetime == 0) return client;
167                 
168                 /*
169                  *      Rate-limit the deletion of known clients.
170                  *      This makes them last a little longer, but
171                  *      prevents the server from melting down if (say)
172                  *      10k clients all expire at once.
173                  */
174                 if (now == client->last_new_client) return client;
175
176                 /*
177                  *      It's not dead yet.  Return it.
178                  */
179                 if ((client->created + client->lifetime) > now) return client;
180                 
181                 /*
182                  *      This really puts them onto a queue for later
183                  *      deletion.
184                  */
185                 client_delete(clients, client);
186
187                 /*
188                  *      Go find the enclosing network again.
189                  */
190                 client = client_find(clients, ipaddr, sock->proto);
191
192                 /*
193                  *      WTF?
194                  */
195                 if (!client) goto unknown;
196                 if (!client->client_server) goto unknown;
197
198                 /*
199                  *      At this point, 'client' is the enclosing
200                  *      network that configures where dynamic clients
201                  *      can be defined.
202                  */
203                 rad_assert(client->dynamic == 0);
204
205         } else if (!client->dynamic && client->rate_limit) {
206                 /*
207                  *      The IP is unknown, so we've found an enclosing
208                  *      network.  Enable DoS protection.  We only
209                  *      allow one new client per second.  Known
210                  *      clients aren't subject to this restriction.
211                  */
212                 if (now == client->last_new_client) goto unknown;
213         }
214
215         client->last_new_client = now;
216
217         request = request_alloc();
218         if (!request) goto unknown;
219
220         request->listener = listener;
221         request->client = client;
222         request->packet = rad_recv(listener->fd, 0x02); /* MSG_PEEK */
223         if (!request->packet) {                         /* badly formed, etc */
224                 request_free(&request);
225                 goto unknown;
226         }
227         request->reply = rad_alloc_reply(request->packet);
228         if (!request->reply) {
229                 request_free(&request);
230                 goto unknown;
231         }
232         request->packet->timestamp = request->timestamp;
233         request->number = 0;
234         request->priority = listener->type;
235         request->server = client->client_server;
236         request->root = &mainconfig;
237
238         /*
239          *      Run a fake request through the given virtual server.
240          *      Look for FreeRADIUS-Client-IP-Address
241          *               FreeRADIUS-Client-Secret
242          *              ...
243          *
244          *      and create the RADCLIENT structure from that.
245          */
246         DEBUG("server %s {", request->server);
247
248         rcode = module_authorize(0, request);
249
250         DEBUG("} # server %s", request->server);
251
252         if (rcode != RLM_MODULE_OK) {
253                 request_free(&request);
254                 goto unknown;
255         }
256
257         /*
258          *      If the client was updated by rlm_dynamic_clients,
259          *      don't create the client from attribute-value pairs.
260          */
261         if (request->client == client) {
262                 created = client_create(clients, request);
263         } else {
264                 created = request->client;
265
266                 /*
267                  *      This frees the client if it isn't valid.
268                  */
269                 if (!client_validate(clients, client, created)) goto unknown;
270         }
271         request_free(&request);
272
273         if (!created) goto unknown;
274
275         return created;
276 #endif
277 }
278
279 static int listen_bind(rad_listen_t *this);
280
281
282 /*
283  *      Process and reply to a server-status request.
284  *      Like rad_authenticate and rad_accounting this should
285  *      live in it's own file but it's so small we don't bother.
286  */
287 static int rad_status_server(REQUEST *request)
288 {
289         int rcode = RLM_MODULE_OK;
290         DICT_VALUE *dval;
291
292         switch (request->listener->type) {
293 #ifdef WITH_STATS
294         case RAD_LISTEN_NONE:
295 #endif
296         case RAD_LISTEN_AUTH:
297                 dval = dict_valbyname(PW_AUTZ_TYPE, 0, "Status-Server");
298                 if (dval) {
299                         rcode = module_authorize(dval->value, request);
300                 } else {
301                         rcode = RLM_MODULE_OK;
302                 }
303
304                 switch (rcode) {
305                 case RLM_MODULE_OK:
306                 case RLM_MODULE_UPDATED:
307                         request->reply->code = PW_AUTHENTICATION_ACK;
308                         break;
309
310                 case RLM_MODULE_FAIL:
311                 case RLM_MODULE_HANDLED:
312                         request->reply->code = 0; /* don't reply */
313                         break;
314
315                 default:
316                 case RLM_MODULE_REJECT:
317                         request->reply->code = PW_AUTHENTICATION_REJECT;
318                         break;
319                 }
320                 break;
321
322 #ifdef WITH_ACCOUNTING
323         case RAD_LISTEN_ACCT:
324                 dval = dict_valbyname(PW_ACCT_TYPE, 0, "Status-Server");
325                 if (dval) {
326                         rcode = module_accounting(dval->value, request);
327                 } else {
328                         rcode = RLM_MODULE_OK;
329                 }
330
331                 switch (rcode) {
332                 case RLM_MODULE_OK:
333                 case RLM_MODULE_UPDATED:
334                         request->reply->code = PW_ACCOUNTING_RESPONSE;
335                         break;
336
337                 default:
338                         request->reply->code = 0; /* don't reply */
339                         break;
340                 }
341                 break;
342 #endif
343
344 #ifdef WITH_COA
345                 /*
346                  *      This is a vendor extension.  Suggested by Glen
347                  *      Zorn in IETF 72, and rejected by the rest of
348                  *      the WG.  We like it, so it goes in here.
349                  */
350         case RAD_LISTEN_COA:
351                 dval = dict_valbyname(PW_RECV_COA_TYPE, 0, "Status-Server");
352                 if (dval) {
353                         rcode = module_recv_coa(dval->value, request);
354                 } else {
355                         rcode = RLM_MODULE_OK;
356                 }
357
358                 switch (rcode) {
359                 case RLM_MODULE_OK:
360                 case RLM_MODULE_UPDATED:
361                         request->reply->code = PW_COA_ACK;
362                         break;
363
364                 default:
365                         request->reply->code = 0; /* don't reply */
366                         break;
367                 }
368                 break;
369 #endif
370
371         default:
372                 return 0;
373         }
374
375 #ifdef WITH_STATS
376         /*
377          *      Full statistics are available only on a statistics
378          *      socket.
379          */
380         if (request->listener->type == RAD_LISTEN_NONE) {
381                 request_stats_reply(request);
382         }
383 #endif
384
385         return 0;
386 }
387
388 #ifdef WITH_TCP
389 static int auth_tcp_recv(rad_listen_t *listener,
390                          RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
391 {
392         int rcode;
393         RADIUS_PACKET   *packet;
394         RAD_REQUEST_FUNP fun = NULL;
395         listen_socket_t *sock = listener->data;
396         RADCLIENT       *client = sock->client;
397
398         /*
399          *      Allocate a packet for partial reads.
400          */
401         if (!sock->packet) {
402                 sock->packet = rad_alloc(0);
403                 if (!sock->packet) return 0;
404
405                 sock->packet->sockfd = listener->fd;
406                 sock->packet->src_ipaddr = sock->other_ipaddr;
407                 sock->packet->src_port = sock->other_port;
408                 sock->packet->dst_ipaddr = sock->my_ipaddr;
409                 sock->packet->dst_port = sock->my_port;
410         }
411         
412         /*
413          *      Grab the packet currently being processed.
414          */
415         packet = sock->packet;
416
417         rcode = fr_tcp_read_packet(packet, 0);
418
419         /*
420          *      Still only a partial packet.  Put it back, and return,
421          *      so that we'll read more data when it's ready.
422          */
423         if (rcode == 0) {
424                 return 0;
425         }
426
427         if (rcode == -1) {      /* error reading packet */
428                 char buffer[256];
429
430                 radlog(L_ERR, "Invalid packet from %s port %d: closing socket",
431                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
432                        packet->src_port);
433         }
434
435         if (rcode < 0) {        /* error or connection reset */
436                 listener->status = RAD_LISTEN_STATUS_REMOVE_FD;
437
438                 /*
439                  *      Decrement the number of connections.
440                  */
441                 if (sock->parent->num_connections > 0) {
442                         sock->parent->num_connections--;
443                 }
444                 if (sock->client->num_connections > 0) {
445                         sock->client->num_connections--;
446                 }
447
448                 /*
449                  *      Tell the event handler that an FD has disappeared.
450                  */
451                 DEBUG("Client has closed connection");
452                 event_new_fd(listener);
453
454                 /*
455                  *      Do NOT free the listener here.  It's in use by
456                  *      a request, and will need to hang around until
457                  *      all of the requests are done.
458                  *
459                  *      It is instead free'd in remove_from_request_hash()
460                  */
461                 return 0;
462         }
463
464         RAD_STATS_TYPE_INC(listener, total_requests);
465
466         /*
467          *      Some sanity checks, based on the packet code.
468          */
469         switch(packet->code) {
470         case PW_AUTHENTICATION_REQUEST:
471                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
472                 fun = rad_authenticate;
473                 break;
474
475         case PW_STATUS_SERVER:
476                 if (!mainconfig.status_server) {
477                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
478                         RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
479                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
480                         rad_free(&sock->packet);
481                         return 0;
482                 }
483                 fun = rad_status_server;
484                 break;
485
486         default:
487                 RAD_STATS_INC(radius_auth_stats.total_unknown_types);
488                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
489
490                 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
491                       packet->code, client->shortname, packet->src_port);
492                 rad_free(&sock->packet);
493                 return 0;
494         } /* switch over packet types */
495
496         if (!received_request(listener, packet, prequest, sock->client)) {
497                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
498                 RAD_STATS_CLIENT_INC(listener, sock->client, total_packets_dropped);
499                 rad_free(&sock->packet);
500                 return 0;
501         }
502
503         *pfun = fun;
504         sock->packet = NULL;    /* we have no need for more partial reads */
505         return 1;
506 }
507
508 static int auth_tcp_accept(rad_listen_t *listener,
509                            UNUSED RAD_REQUEST_FUNP *pfun,
510                            UNUSED REQUEST **prequest)
511 {
512         int newfd, src_port;
513         rad_listen_t *this;
514         socklen_t salen;
515         struct sockaddr_storage src;
516         listen_socket_t *sock;
517         fr_ipaddr_t src_ipaddr;
518         RADCLIENT *client;
519         
520         salen = sizeof(src);
521
522         DEBUG2(" ... new connection request on TCP socket.");
523         
524         newfd = accept(listener->fd, (struct sockaddr *) &src, &salen);
525         if (newfd < 0) {
526                 /*
527                  *      Non-blocking sockets must handle this.
528                  */
529                 if (errno == EWOULDBLOCK) {
530                         return 0;
531                 }
532
533                 DEBUG2(" ... failed to accept connection.");
534                 return -1;
535         }
536
537         if (!fr_sockaddr2ipaddr(&src, salen, &src_ipaddr, &src_port)) {
538                 DEBUG2(" ... unknown address family.");
539                 return 0;
540         }
541
542         /*
543          *      Enforce client IP address checks on accept, not on
544          *      every packet.
545          */
546         if ((client = client_listener_find(listener,
547                                            &src_ipaddr, src_port)) == NULL) {
548                 close(newfd);
549                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
550                 return 0;
551         }
552
553         /*
554          *      Enforce max_connectionsx on client && listen section.
555          */
556         if ((client->max_connections != 0) &&
557             (client->max_connections == client->num_connections)) {
558                 /*
559                  *      FIXME: Print client IP/port, and server IP/port.
560                  */
561                 radlog(L_INFO, "Ignoring new connection due to client max_connections (%d)", client->max_connections);
562                 close(newfd);
563                 return 0;
564         }
565
566         sock = listener->data;
567         if ((sock->max_connections != 0) &&
568             (sock->max_connections == sock->num_connections)) {
569                 /*
570                  *      FIXME: Print client IP/port, and server IP/port.
571                  */
572                 radlog(L_INFO, "Ignoring new connection due to socket max_connections");
573                 close(newfd);
574                 return 0;
575         }
576         client->num_connections++;
577         sock->num_connections++;
578
579         /*
580          *      Add the new listener.
581          */
582         this = listen_alloc(listener->type);
583         if (!this) return -1;
584
585         /*
586          *      Copy everything, including the pointer to the socket
587          *      information.
588          */
589         sock = this->data;
590         memcpy(this->data, listener->data, sizeof(*sock));
591         memcpy(this, listener, sizeof(*this));
592         this->next = NULL;
593         this->data = sock;      /* fix it back */
594
595         sock->parent = listener->data;
596         sock->other_ipaddr = src_ipaddr;
597         sock->other_port = src_port;
598         sock->client = client;
599
600         this->fd = newfd;
601         this->status = RAD_LISTEN_STATUS_INIT;
602         this->recv = auth_tcp_recv;
603
604         /*
605          *      FIXME: set O_NONBLOCK on the accept'd fd.
606          *      See djb's portability rants for details.
607          */
608
609         /*
610          *      Tell the event loop that we have a new FD.
611          *      This can be called from a child thread...
612          */
613         event_new_fd(this);
614
615         return 0;
616 }
617 #endif
618
619
620 /*
621  *      This function is stupid and complicated.
622  */
623 static int socket_print(const rad_listen_t *this, char *buffer, size_t bufsize)
624 {
625         size_t len;
626         listen_socket_t *sock = this->data;
627         const char *name;
628
629         switch (this->type) {
630 #ifdef WITH_STATS
631         case RAD_LISTEN_NONE:   /* what a hack... */
632                 name = "status";
633                 break;
634 #endif
635
636         case RAD_LISTEN_AUTH:
637                 name = "authentication";
638                 break;
639
640 #ifdef WITH_ACCOUNTING
641         case RAD_LISTEN_ACCT:
642                 name = "accounting";
643                 break;
644 #endif
645
646 #ifdef WITH_PROXY
647         case RAD_LISTEN_PROXY:
648                 name = "proxy";
649                 break;
650 #endif
651
652 #ifdef WITH_VMPS
653         case RAD_LISTEN_VQP:
654                 name = "vmps";
655                 break;
656 #endif
657
658 #ifdef WITH_DHCP
659         case RAD_LISTEN_DHCP:
660                 name = "dhcp";
661                 break;
662 #endif
663
664 #ifdef WITH_COA
665         case RAD_LISTEN_COA:
666                 name = "coa";
667                 break;
668 #endif
669
670         default:
671                 name = "??";
672                 break;
673         }
674
675 #define FORWARD len = strlen(buffer); if (len >= (bufsize + 1)) return 0;buffer += len;bufsize -= len
676 #define ADDSTRING(_x) strlcpy(buffer, _x, bufsize);FORWARD
677
678         ADDSTRING(name);
679
680         if (sock->interface) {
681                 ADDSTRING(" interface ");
682                 ADDSTRING(sock->interface);
683         }
684
685 #ifdef WITH_TCP
686         if (this->recv == auth_tcp_accept) {
687                 ADDSTRING(" proto tcp");
688         }
689 #endif
690
691 #ifdef WITH_TCP
692         /*
693          *      TCP sockets get printed a little differently, to make
694          *      it clear what's going on.
695          */
696         if (sock->client) {
697                 ADDSTRING(" from client (");
698                 ip_ntoh(&sock->other_ipaddr, buffer, bufsize);
699                 FORWARD;
700
701                 ADDSTRING(", ");
702                 snprintf(buffer, bufsize, "%d", sock->other_port);
703                 FORWARD;
704                 ADDSTRING(") -> (");
705
706                 if ((sock->my_ipaddr.af == AF_INET) &&
707                     (sock->my_ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
708                         strlcpy(buffer, "*", bufsize);
709                 } else {
710                         ip_ntoh(&sock->my_ipaddr, buffer, bufsize);
711                 }
712                 FORWARD;
713                 
714                 ADDSTRING(", ");
715                 snprintf(buffer, bufsize, "%d", sock->my_port);
716                 FORWARD;
717
718                 if (this->server) {
719                         ADDSTRING(", virtual-server=");
720                         ADDSTRING(this->server);
721                 }
722
723                 ADDSTRING(")");
724
725                 return 1;
726         }
727
728 #ifdef WITH_PROXY
729         /*
730          *      Maybe it's a socket that we opened to a home server.
731          */
732         if ((sock->proto == IPPROTO_TCP) &&
733             (this->type == RAD_LISTEN_PROXY)) {
734                 ADDSTRING(" (");
735                 ip_ntoh(&sock->my_ipaddr, buffer, bufsize);
736                 FORWARD;
737
738                 ADDSTRING(", ");
739                 snprintf(buffer, bufsize, "%d", sock->my_port);
740                 FORWARD;
741                 ADDSTRING(") -> home_server (");
742
743                 if ((sock->other_ipaddr.af == AF_INET) &&
744                     (sock->other_ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
745                         strlcpy(buffer, "*", bufsize);
746                 } else {
747                         ip_ntoh(&sock->other_ipaddr, buffer, bufsize);
748                 }
749                 FORWARD;
750                 
751                 ADDSTRING(", ");
752                 snprintf(buffer, bufsize, "%d", sock->other_port);
753                 FORWARD;
754
755                 ADDSTRING(")");
756
757                 return 1;
758         }
759 #endif  /* WITH_PROXY */
760 #endif  /* WITH_TCP */
761
762         ADDSTRING(" address ");
763         
764         if ((sock->my_ipaddr.af == AF_INET) &&
765             (sock->my_ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
766                 strlcpy(buffer, "*", bufsize);
767         } else {
768                 ip_ntoh(&sock->my_ipaddr, buffer, bufsize);
769         }
770         FORWARD;
771
772         ADDSTRING(" port ");
773         snprintf(buffer, bufsize, "%d", sock->my_port);
774         FORWARD;
775
776         if (this->server) {
777                 ADDSTRING(" as server ");
778                 ADDSTRING(this->server);
779         }
780
781 #undef ADDSTRING
782 #undef FORWARD
783
784         return 1;
785 }
786
787 extern int check_config;        /* radiusd.c */
788
789
790 /*
791  *      Parse an authentication or accounting socket.
792  */
793 static int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
794 {
795         int             rcode;
796         int             listen_port;
797         fr_ipaddr_t     ipaddr;
798         listen_socket_t *sock = this->data;
799         char            *section_name = NULL;
800         CONF_SECTION    *client_cs, *parentcs;
801
802         /*
803          *      Try IPv4 first
804          */
805         ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
806         rcode = cf_item_parse(cs, "ipaddr", PW_TYPE_IPADDR,
807                               &ipaddr.ipaddr.ip4addr, NULL);
808         if (rcode < 0) return -1;
809
810         if (rcode == 0) { /* successfully parsed IPv4 */
811                 ipaddr.af = AF_INET;
812
813         } else {        /* maybe IPv6? */
814                 rcode = cf_item_parse(cs, "ipv6addr", PW_TYPE_IPV6ADDR,
815                                       &ipaddr.ipaddr.ip6addr, NULL);
816                 if (rcode < 0) return -1;
817
818                 if (rcode == 1) {
819                         cf_log_err(cf_sectiontoitem(cs),
820                                    "No address specified in listen section");
821                         return -1;
822                 }
823                 ipaddr.af = AF_INET6;
824         }
825
826         rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
827                               &listen_port, "0");
828         if (rcode < 0) return -1;
829
830         if ((listen_port < 0) || (listen_port > 65535)) {
831                         cf_log_err(cf_sectiontoitem(cs),
832                                    "Invalid value for \"port\"");
833                         return -1;
834         }
835
836         sock->proto = IPPROTO_UDP;
837
838         if (cf_pair_find(cs, "proto")) {
839 #ifndef WITH_TCP
840                 cf_log_err(cf_sectiontoitem(cs),
841                            "System does not support the TCP protocol.  Delete this line from the configuration file.");
842                 return -1;
843 #else
844                 char *proto = NULL;
845
846
847                 rcode = cf_item_parse(cs, "proto", PW_TYPE_STRING_PTR,
848                                       &proto, "udp");
849                 if (rcode < 0) return -1;
850
851                 if (strcmp(proto, "udp") == 0) {
852                         sock->proto = IPPROTO_UDP;
853
854                 } else if (strcmp(proto, "tcp") == 0) {
855                         sock->proto = IPPROTO_TCP;
856
857                         rcode = cf_item_parse(cs, "max_connections", PW_TYPE_INTEGER,
858                                               &sock->max_connections, "64");
859                         if (rcode < 0) return -1;
860
861                 } else {
862                         cf_log_err(cf_sectiontoitem(cs),
863                                    "Unknown proto name \"%s\"", proto);
864                         free(proto);
865                         return -1;
866                 }
867                 free(proto);
868
869                 /*
870                  *      TCP requires a destination IP for sockets.
871                  *      UDP doesn't, so it's allowed.
872                  */
873 #ifdef WITH_PROXY
874                 if ((this->type == RAD_LISTEN_PROXY) &&
875                     (sock->proto != IPPROTO_UDP)) {
876                         cf_log_err(cf_sectiontoitem(cs),
877                                    "Proxy listeners can only listen on proto = udp");
878                         return -1;
879                 }
880 #endif  /* WITH_PROXY */
881 #endif  /* WITH_TCP */
882         }
883
884         sock->my_ipaddr = ipaddr;
885         sock->my_port = listen_port;
886
887         if (check_config) {
888                 if (home_server_find(&sock->my_ipaddr, sock->my_port, sock->proto)) {
889                                 char buffer[128];
890                                 
891                                 DEBUG("ERROR: We have been asked to listen on %s port %d, which is also listed as a home server.  This can create a proxy loop.",
892                                       ip_ntoh(&sock->my_ipaddr, buffer, sizeof(buffer)),
893                                       sock->my_port);
894                                 return -1;
895                 }
896
897                 return 0;       /* don't do anything */
898         }
899
900         /*
901          *      If we can bind to interfaces, do so,
902          *      else don't.
903          */
904         if (cf_pair_find(cs, "interface")) {
905                 const char *value;
906                 CONF_PAIR *cp = cf_pair_find(cs, "interface");
907
908                 rad_assert(cp != NULL);
909                 value = cf_pair_value(cp);
910                 if (!value) {
911                         cf_log_err(cf_sectiontoitem(cs),
912                                    "No interface name given");
913                         return -1;
914                 }
915                 sock->interface = value;
916         }
917
918 #ifdef WITH_DHCP
919         /*
920          *      If we can do broadcasts..
921          */
922         if (cf_pair_find(cs, "broadcast")) {
923 #ifndef SO_BROADCAST
924                 cf_log_err(cf_sectiontoitem(cs),
925                            "System does not support broadcast sockets.  Delete this line from the configuration file.");
926                 return -1;
927 #else
928                 const char *value;
929                 CONF_PAIR *cp = cf_pair_find(cs, "broadcast");
930
931                 if (this->type != RAD_LISTEN_DHCP) {
932                         cf_log_err(cf_pairtoitem(cp),
933                                    "Broadcast can only be set for DHCP listeners.  Delete this line from the configuration file.");
934                         return -1;
935                 }
936                 
937                 rad_assert(cp != NULL);
938                 value = cf_pair_value(cp);
939                 if (!value) {
940                         cf_log_err(cf_sectiontoitem(cs),
941                                    "No broadcast value given");
942                         return -1;
943                 }
944
945                 /*
946                  *      Hack... whatever happened to cf_section_parse?
947                  */
948                 sock->broadcast = (strcmp(value, "yes") == 0);
949 #endif
950         }
951 #endif
952
953         /*
954          *      And bind it to the port.
955          */
956         if (listen_bind(this) < 0) {
957                 char buffer[128];
958                 cf_log_err(cf_sectiontoitem(cs),
959                            "Error binding to port for %s port %d",
960                            ip_ntoh(&sock->my_ipaddr, buffer, sizeof(buffer)),
961                            sock->my_port);
962                 return -1;
963         }
964
965 #ifdef WITH_PROXY
966         /*
967          *      Proxy sockets don't have clients.
968          */
969         if (this->type == RAD_LISTEN_PROXY) return 0;
970 #endif
971         
972         /*
973          *      The more specific configurations are preferred to more
974          *      generic ones.
975          */
976         client_cs = NULL;
977         parentcs = cf_top_section(cs);
978         rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
979                               &section_name, NULL);
980         if (rcode < 0) return -1; /* bad string */
981         if (rcode == 0) {
982                 /*
983                  *      Explicit list given: use it.
984                  */
985                 client_cs = cf_section_sub_find_name2(parentcs,
986                                                       "clients",
987                                                       section_name);
988                 if (!client_cs) {
989                         client_cs = cf_section_find(section_name);
990                 }
991                 if (!client_cs) {
992                         cf_log_err(cf_sectiontoitem(cs),
993                                    "Failed to find clients %s {...}",
994                                    section_name);
995                         free(section_name);
996                         return -1;
997                 }
998                 free(section_name);
999         } /* else there was no "clients = " entry. */
1000
1001         if (!client_cs) {
1002                 CONF_SECTION *server_cs;
1003
1004                 server_cs = cf_section_sub_find_name2(parentcs,
1005                                                       "server",
1006                                                       this->server);
1007                 /*
1008                  *      Found a "server foo" section.  If there are clients
1009                  *      in it, use them.
1010                  */
1011                 if (server_cs &&
1012                     (cf_section_sub_find(server_cs, "client") != NULL)) {
1013                         client_cs = server_cs;
1014                 }
1015         }
1016
1017         /*
1018          *      Still nothing.  Look for global clients.
1019          */
1020         if (!client_cs) client_cs = parentcs;
1021
1022         sock->clients = clients_parse_section(client_cs);
1023         if (!sock->clients) {
1024                 cf_log_err(cf_sectiontoitem(cs),
1025                            "Failed to load clients for this listen section");
1026                 return -1;
1027         }
1028
1029 #ifdef WITH_TCP
1030         if (sock->proto == IPPROTO_TCP) {
1031                 /*
1032                  *      Re-write the listener receive function to
1033                  *      allow us to accept the socket.
1034                  */
1035                 this->recv = auth_tcp_accept;
1036         }
1037 #endif
1038
1039         return 0;
1040 }
1041
1042 /*
1043  *      Send an authentication response packet
1044  */
1045 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
1046 {
1047         rad_assert(request->listener == listener);
1048         rad_assert(listener->send == auth_socket_send);
1049
1050         return rad_send(request->reply, request->packet,
1051                         request->client->secret);
1052 }
1053
1054
1055 #ifdef WITH_ACCOUNTING
1056 /*
1057  *      Send an accounting response packet (or not)
1058  */
1059 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
1060 {
1061         rad_assert(request->listener == listener);
1062         rad_assert(listener->send == acct_socket_send);
1063
1064         /*
1065          *      Accounting reject's are silently dropped.
1066          *
1067          *      We do it here to avoid polluting the rest of the
1068          *      code with this knowledge
1069          */
1070         if (request->reply->code == 0) return 0;
1071
1072         return rad_send(request->reply, request->packet,
1073                         request->client->secret);
1074 }
1075 #endif
1076
1077 #ifdef WITH_PROXY
1078 /*
1079  *      Send a packet to a home server.
1080  *
1081  *      FIXME: have different code for proxy auth & acct!
1082  */
1083 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
1084 {
1085         rad_assert(request->proxy_listener == listener);
1086         rad_assert(listener->send == proxy_socket_send);
1087
1088         return rad_send(request->proxy, request->packet,
1089                         request->home_server->secret);
1090 }
1091 #endif
1092
1093 #ifdef WITH_STATS
1094 /*
1095  *      Check if an incoming request is "ok"
1096  *
1097  *      It takes packets, not requests.  It sees if the packet looks
1098  *      OK.  If so, it does a number of sanity checks on it.
1099   */
1100 static int stats_socket_recv(rad_listen_t *listener,
1101                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1102 {
1103         ssize_t         rcode;
1104         int             code, src_port;
1105         RADIUS_PACKET   *packet;
1106         RADCLIENT       *client;
1107         fr_ipaddr_t     src_ipaddr;
1108
1109         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1110         if (rcode < 0) return 0;
1111
1112         RAD_STATS_TYPE_INC(listener, total_requests);
1113
1114         if (rcode < 20) {       /* AUTH_HDR_LEN */
1115                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1116                 return 0;
1117         }
1118
1119         if ((client = client_listener_find(listener,
1120                                            &src_ipaddr, src_port)) == NULL) {
1121                 rad_recv_discard(listener->fd);
1122                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
1123                 return 0;
1124         }
1125
1126         /*
1127          *      We only understand Status-Server on this socket.
1128          */
1129         if (code != PW_STATUS_SERVER) {
1130                 DEBUG("Ignoring packet code %d sent to Status-Server port",
1131                       code);
1132                 rad_recv_discard(listener->fd);
1133                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
1134                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
1135                 return 0;
1136         }
1137
1138         /*
1139          *      Now that we've sanity checked everything, receive the
1140          *      packet.
1141          */
1142         packet = rad_recv(listener->fd, 1); /* require message authenticator */
1143         if (!packet) {
1144                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1145                 DEBUG("%s", fr_strerror());
1146                 return 0;
1147         }
1148
1149         if (!received_request(listener, packet, prequest, client)) {
1150                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1151                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
1152                 rad_free(&packet);
1153                 return 0;
1154         }
1155
1156         *pfun = rad_status_server;
1157         return 1;
1158 }
1159 #endif
1160
1161
1162 /*
1163  *      Check if an incoming request is "ok"
1164  *
1165  *      It takes packets, not requests.  It sees if the packet looks
1166  *      OK.  If so, it does a number of sanity checks on it.
1167   */
1168 static int auth_socket_recv(rad_listen_t *listener,
1169                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1170 {
1171         ssize_t         rcode;
1172         int             code, src_port;
1173         RADIUS_PACKET   *packet;
1174         RAD_REQUEST_FUNP fun = NULL;
1175         RADCLIENT       *client;
1176         fr_ipaddr_t     src_ipaddr;
1177
1178         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1179         if (rcode < 0) return 0;
1180
1181         RAD_STATS_TYPE_INC(listener, total_requests);
1182
1183         if (rcode < 20) {       /* AUTH_HDR_LEN */
1184                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1185                 return 0;
1186         }
1187
1188         if ((client = client_listener_find(listener,
1189                                            &src_ipaddr, src_port)) == NULL) {
1190                 rad_recv_discard(listener->fd);
1191                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
1192                 return 0;
1193         }
1194
1195         /*
1196          *      Some sanity checks, based on the packet code.
1197          */
1198         switch(code) {
1199         case PW_AUTHENTICATION_REQUEST:
1200                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
1201                 fun = rad_authenticate;
1202                 break;
1203
1204         case PW_STATUS_SERVER:
1205                 if (!mainconfig.status_server) {
1206                         rad_recv_discard(listener->fd);
1207                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1208                         RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
1209                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
1210                         return 0;
1211                 }
1212                 fun = rad_status_server;
1213                 break;
1214
1215         default:
1216                 rad_recv_discard(listener->fd);
1217                 RAD_STATS_INC(radius_auth_stats.total_unknown_types);
1218                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
1219
1220                 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
1221                       code, client->shortname, src_port);
1222                 return 0;
1223                 break;
1224         } /* switch over packet types */
1225
1226         /*
1227          *      Now that we've sanity checked everything, receive the
1228          *      packet.
1229          */
1230         packet = rad_recv(listener->fd, client->message_authenticator);
1231         if (!packet) {
1232                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1233                 DEBUG("%s", fr_strerror());
1234                 return 0;
1235         }
1236
1237         if (!received_request(listener, packet, prequest, client)) {
1238                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1239                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
1240                 rad_free(&packet);
1241                 return 0;
1242         }
1243
1244         *pfun = fun;
1245         return 1;
1246 }
1247
1248
1249 #ifdef WITH_ACCOUNTING
1250 /*
1251  *      Receive packets from an accounting socket
1252  */
1253 static int acct_socket_recv(rad_listen_t *listener,
1254                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1255 {
1256         ssize_t         rcode;
1257         int             code, src_port;
1258         RADIUS_PACKET   *packet;
1259         RAD_REQUEST_FUNP fun = NULL;
1260         RADCLIENT       *client;
1261         fr_ipaddr_t     src_ipaddr;
1262
1263         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1264         if (rcode < 0) return 0;
1265
1266         RAD_STATS_TYPE_INC(listener, total_requests);
1267
1268         if (rcode < 20) {       /* AUTH_HDR_LEN */
1269                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1270                 return 0;
1271         }
1272
1273         if ((client = client_listener_find(listener,
1274                                            &src_ipaddr, src_port)) == NULL) {
1275                 rad_recv_discard(listener->fd);
1276                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
1277                 return 0;
1278         }
1279
1280         /*
1281          *      Some sanity checks, based on the packet code.
1282          */
1283         switch(code) {
1284         case PW_ACCOUNTING_REQUEST:
1285                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
1286                 fun = rad_accounting;
1287                 break;
1288
1289         case PW_STATUS_SERVER:
1290                 if (!mainconfig.status_server) {
1291                         rad_recv_discard(listener->fd);
1292                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1293                         RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
1294
1295                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
1296                         return 0;
1297                 }
1298                 fun = rad_status_server;
1299                 break;
1300
1301         default:
1302                 rad_recv_discard(listener->fd);
1303                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
1304                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
1305
1306                 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
1307                       code, client->shortname, src_port);
1308                 return 0;
1309         } /* switch over packet types */
1310
1311         /*
1312          *      Now that we've sanity checked everything, receive the
1313          *      packet.
1314          */
1315         packet = rad_recv(listener->fd, 0);
1316         if (!packet) {
1317                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1318                 radlog(L_ERR, "%s", fr_strerror());
1319                 return 0;
1320         }
1321
1322         /*
1323          *      There can be no duplicate accounting packets.
1324          */
1325         if (!received_request(listener, packet, prequest, client)) {
1326                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1327                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
1328                 rad_free(&packet);
1329                 return 0;
1330         }
1331
1332         *pfun = fun;
1333         return 1;
1334 }
1335 #endif
1336
1337
1338 #ifdef WITH_COA
1339 /*
1340  *      For now, all CoA requests are *only* originated, and not
1341  *      proxied.  So all of the necessary work is done in the
1342  *      post-proxy section, which is automatically handled by event.c.
1343  *      As a result, we don't have to do anything here.
1344  */
1345 static int rad_coa_reply(REQUEST *request)
1346 {
1347         VALUE_PAIR *s1, *s2;
1348
1349         /*
1350          *      Inform the user about RFC requirements.
1351          */
1352         s1 = pairfind(request->proxy->vps, PW_STATE, 0);
1353         if (s1) {
1354                 s2 = pairfind(request->proxy_reply->vps, PW_STATE, 0);
1355
1356                 if (!s2) {
1357                         DEBUG("WARNING: Client was sent State in CoA, and did not respond with State.");
1358
1359                 } else if ((s1->length != s2->length) ||
1360                            (memcmp(s1->vp_octets, s2->vp_octets,
1361                                    s1->length) != 0)) {
1362                         DEBUG("WARNING: Client was sent State in CoA, and did not respond with the same State.");
1363                 }
1364         }
1365
1366         return RLM_MODULE_OK;
1367 }
1368
1369 /*
1370  *      Receive a CoA packet.
1371  */
1372 static int rad_coa_recv(REQUEST *request)
1373 {
1374         int rcode = RLM_MODULE_OK;
1375         int ack, nak;
1376         VALUE_PAIR *vp;
1377
1378         /*
1379          *      Get the correct response
1380          */
1381         switch (request->packet->code) {
1382         case PW_COA_REQUEST:
1383                 ack = PW_COA_ACK;
1384                 nak = PW_COA_NAK;
1385                 break;
1386
1387         case PW_DISCONNECT_REQUEST:
1388                 ack = PW_DISCONNECT_ACK;
1389                 nak = PW_DISCONNECT_NAK;
1390                 break;
1391
1392         default:                /* shouldn't happen */
1393                 return RLM_MODULE_FAIL;
1394         }
1395
1396 #ifdef WITH_PROXY
1397 #define WAS_PROXIED (request->proxy)
1398 #else
1399 #define WAS_PROXIED (0)
1400 #endif
1401
1402         if (!WAS_PROXIED) {
1403                 /*
1404                  *      RFC 5176 Section 3.3.  If we have a CoA-Request
1405                  *      with Service-Type = Authorize-Only, it MUST
1406                  *      have a State attribute in it.
1407                  */
1408                 vp = pairfind(request->packet->vps, PW_SERVICE_TYPE, 0);
1409                 if (request->packet->code == PW_COA_REQUEST) {
1410                         if (vp && (vp->vp_integer == 17)) {
1411                                 vp = pairfind(request->packet->vps, PW_STATE, 0);
1412                                 if (!vp || (vp->length == 0)) {
1413                                         RDEBUG("ERROR: CoA-Request with Service-Type = Authorize-Only MUST contain a State attribute");
1414                                         request->reply->code = PW_COA_NAK;
1415                                         return RLM_MODULE_FAIL;
1416                                 }
1417                         }
1418                 } else if (vp) {
1419                         /*
1420                          *      RFC 5176, Section 3.2.
1421                          */
1422                         RDEBUG("ERROR: Disconnect-Request MUST NOT contain a Service-Type attribute");
1423                         request->reply->code = PW_DISCONNECT_NAK;
1424                         return RLM_MODULE_FAIL;
1425                 }
1426
1427                 rcode = module_recv_coa(0, request);
1428                 switch (rcode) {
1429                 case RLM_MODULE_FAIL:
1430                 case RLM_MODULE_INVALID:
1431                 case RLM_MODULE_REJECT:
1432                 case RLM_MODULE_USERLOCK:
1433                 default:
1434                         request->reply->code = nak;
1435                         break;
1436                         
1437                 case RLM_MODULE_HANDLED:
1438                         return rcode;
1439                         
1440                 case RLM_MODULE_NOOP:
1441                 case RLM_MODULE_NOTFOUND:
1442                 case RLM_MODULE_OK:
1443                 case RLM_MODULE_UPDATED:
1444                         request->reply->code = ack;
1445                         break;
1446                 }
1447         } else {
1448                 /*
1449                  *      Start the reply code with the proxy reply
1450                  *      code.
1451                  */
1452                 request->reply->code = request->proxy_reply->code;
1453         }
1454
1455         /*
1456          *      Copy State from the request to the reply.
1457          *      See RFC 5176 Section 3.3.
1458          */
1459         vp = paircopy2(request->packet->vps, PW_STATE, 0);
1460         if (vp) pairadd(&request->reply->vps, vp);
1461
1462         /*
1463          *      We may want to over-ride the reply.
1464          */
1465         rcode = module_send_coa(0, request);
1466         switch (rcode) {
1467                 /*
1468                  *      We need to send CoA-NAK back if Service-Type
1469                  *      is Authorize-Only.  Rely on the user's policy
1470                  *      to do that.  We're not a real NAS, so this
1471                  *      restriction doesn't (ahem) apply to us.
1472                  */
1473                 case RLM_MODULE_FAIL:
1474                 case RLM_MODULE_INVALID:
1475                 case RLM_MODULE_REJECT:
1476                 case RLM_MODULE_USERLOCK:
1477                 default:
1478                         /*
1479                          *      Over-ride an ACK with a NAK
1480                          */
1481                         request->reply->code = nak;
1482                         break;
1483                         
1484                 case RLM_MODULE_HANDLED:
1485                         return rcode;
1486                         
1487                 case RLM_MODULE_NOOP:
1488                 case RLM_MODULE_NOTFOUND:
1489                 case RLM_MODULE_OK:
1490                 case RLM_MODULE_UPDATED:
1491                         /*
1492                          *      Do NOT over-ride a previously set value.
1493                          *      Otherwise an "ok" here will re-write a
1494                          *      NAK to an ACK.
1495                          */
1496                         if (request->reply->code == 0) {
1497                                 request->reply->code = ack;
1498                         }
1499                         break;
1500
1501         }
1502
1503         return RLM_MODULE_OK;
1504 }
1505
1506
1507 /*
1508  *      Check if an incoming request is "ok"
1509  *
1510  *      It takes packets, not requests.  It sees if the packet looks
1511  *      OK.  If so, it does a number of sanity checks on it.
1512   */
1513 static int coa_socket_recv(rad_listen_t *listener,
1514                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1515 {
1516         ssize_t         rcode;
1517         int             code, src_port;
1518         RADIUS_PACKET   *packet;
1519         RAD_REQUEST_FUNP fun = NULL;
1520         RADCLIENT       *client;
1521         fr_ipaddr_t     src_ipaddr;
1522
1523         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1524         if (rcode < 0) return 0;
1525
1526         RAD_STATS_TYPE_INC(listener, total_requests);
1527
1528         if (rcode < 20) {       /* AUTH_HDR_LEN */
1529                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1530                 return 0;
1531         }
1532
1533         if ((client = client_listener_find(listener,
1534                                            &src_ipaddr, src_port)) == NULL) {
1535                 rad_recv_discard(listener->fd);
1536                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
1537                 return 0;
1538         }
1539
1540         /*
1541          *      Some sanity checks, based on the packet code.
1542          */
1543         switch(code) {
1544         case PW_COA_REQUEST:
1545         case PW_DISCONNECT_REQUEST:
1546                 fun = rad_coa_recv;
1547                 break;
1548
1549         default:
1550                 rad_recv_discard(listener->fd);
1551                 DEBUG("Invalid packet code %d sent to coa port from client %s port %d : IGNORED",
1552                       code, client->shortname, src_port);
1553                 return 0;
1554                 break;
1555         } /* switch over packet types */
1556
1557         /*
1558          *      Now that we've sanity checked everything, receive the
1559          *      packet.
1560          */
1561         packet = rad_recv(listener->fd, client->message_authenticator);
1562         if (!packet) {
1563                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1564                 DEBUG("%s", fr_strerror());
1565                 return 0;
1566         }
1567
1568         if (!received_request(listener, packet, prequest, client)) {
1569                 rad_free(&packet);
1570                 return 0;
1571         }
1572
1573         *pfun = fun;
1574         return 1;
1575 }
1576 #endif
1577
1578 #ifdef WITH_PROXY
1579 /*
1580  *      Recieve packets from a proxy socket.
1581  */
1582 static int proxy_socket_recv(rad_listen_t *listener,
1583                               RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1584 {
1585         REQUEST         *request;
1586         RADIUS_PACKET   *packet;
1587         RAD_REQUEST_FUNP fun = NULL;
1588         char            buffer[128];
1589
1590         packet = rad_recv(listener->fd, 0);
1591         if (!packet) {
1592                 radlog(L_ERR, "%s", fr_strerror());
1593                 return 0;
1594         }
1595
1596         /*
1597          *      FIXME: Client MIB updates?
1598          */
1599         switch(packet->code) {
1600         case PW_AUTHENTICATION_ACK:
1601         case PW_ACCESS_CHALLENGE:
1602         case PW_AUTHENTICATION_REJECT:
1603                 fun = rad_authenticate;
1604                 break;
1605
1606 #ifdef WITH_ACCOUNTING
1607         case PW_ACCOUNTING_RESPONSE:
1608                 fun = rad_accounting;
1609                 break;
1610 #endif
1611
1612 #ifdef WITH_COA
1613         case PW_DISCONNECT_ACK:
1614         case PW_DISCONNECT_NAK:
1615         case PW_COA_ACK:
1616         case PW_COA_NAK:
1617                 fun = rad_coa_reply;
1618                 break;
1619 #endif
1620
1621         default:
1622                 /*
1623                  *      FIXME: Update MIB for packet types?
1624                  */
1625                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
1626                        "from home server %s port %d - ID %d : IGNORED",
1627                        packet->code,
1628                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
1629                        packet->src_port, packet->id);
1630                 rad_free(&packet);
1631                 return 0;
1632         }
1633
1634         request = received_proxy_response(packet);
1635         if (!request) {
1636                 rad_free(&packet);
1637                 return 0;
1638         }
1639
1640 #ifdef WITH_COA
1641         /*
1642          *      Distinguish proxied CoA requests from ones we
1643          *      originate.
1644          */
1645         if ((fun == rad_coa_reply) &&
1646             (request->packet->code == request->proxy->code)) {
1647                 fun = rad_coa_recv;
1648         }
1649 #endif
1650
1651         rad_assert(fun != NULL);
1652         *pfun = fun;
1653         *prequest = request;
1654
1655         return 1;
1656 }
1657
1658 #ifdef WITH_TCP
1659 /*
1660  *      Recieve packets from a proxy socket.
1661  */
1662 static int proxy_socket_tcp_recv(rad_listen_t *listener,
1663                                  RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1664 {
1665         REQUEST         *request;
1666         RADIUS_PACKET   *packet;
1667         RAD_REQUEST_FUNP fun = NULL;
1668         listen_socket_t *sock = listener->data;
1669         char            buffer[128];
1670
1671         packet = fr_tcp_recv(listener->fd, 0);
1672         if (!packet) {
1673                 listener->status = RAD_LISTEN_STATUS_REMOVE_FD;
1674                 event_new_fd(listener);
1675                 return 0;
1676         }
1677
1678         /*
1679          *      FIXME: Client MIB updates?
1680          */
1681         switch(packet->code) {
1682         case PW_AUTHENTICATION_ACK:
1683         case PW_ACCESS_CHALLENGE:
1684         case PW_AUTHENTICATION_REJECT:
1685                 fun = rad_authenticate;
1686                 break;
1687
1688 #ifdef WITH_ACCOUNTING
1689         case PW_ACCOUNTING_RESPONSE:
1690                 fun = rad_accounting;
1691                 break;
1692 #endif
1693
1694         default:
1695                 /*
1696                  *      FIXME: Update MIB for packet types?
1697                  */
1698                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
1699                        "from home server %s port %d - ID %d : IGNORED",
1700                        packet->code,
1701                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
1702                        packet->src_port, packet->id);
1703                 rad_free(&packet);
1704                 return 0;
1705         }
1706
1707         packet->src_ipaddr = sock->other_ipaddr;
1708         packet->src_port = sock->other_port;
1709         packet->dst_ipaddr = sock->my_ipaddr;
1710         packet->dst_port = sock->my_port;
1711
1712         /*
1713          *      FIXME: Have it return an indication of packets that
1714          *      are OK to ignore (dups, too late), versus ones that
1715          *      aren't OK to ignore (unknown response, spoofed, etc.)
1716          *
1717          *      Close the socket on bad packets...
1718          */
1719         request = received_proxy_response(packet);
1720         if (!request) {
1721                 return 0;
1722         }
1723
1724         rad_assert(fun != NULL);
1725         sock->opened = sock->last_packet = request->timestamp;
1726
1727         *pfun = fun;
1728         *prequest = request;
1729
1730         return 1;
1731 }
1732 #endif
1733 #endif
1734
1735
1736 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1737 {
1738         if (!request->reply->code) return 0;
1739
1740         rad_encode(request->reply, request->packet,
1741                    request->client->secret);
1742         rad_sign(request->reply, request->packet,
1743                  request->client->secret);
1744
1745         return 0;
1746 }
1747
1748
1749 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1750 {
1751         if (rad_verify(request->packet, NULL,
1752                        request->client->secret) < 0) {
1753                 return -1;
1754         }
1755
1756         return rad_decode(request->packet, NULL,
1757                           request->client->secret);
1758 }
1759
1760 #ifdef WITH_PROXY
1761 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1762 {
1763         rad_encode(request->proxy, NULL, request->home_server->secret);
1764         rad_sign(request->proxy, NULL, request->home_server->secret);
1765
1766         return 0;
1767 }
1768
1769
1770 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1771 {
1772         /*
1773          *      rad_verify is run in event.c, received_proxy_response()
1774          */
1775
1776         return rad_decode(request->proxy_reply, request->proxy,
1777                            request->home_server->secret);
1778 }
1779 #endif
1780
1781 #include "dhcpd.c"
1782
1783 #include "command.c"
1784
1785 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
1786 #ifdef WITH_STATS
1787         { common_socket_parse, NULL,
1788           stats_socket_recv, auth_socket_send,
1789           socket_print, client_socket_encode, client_socket_decode },
1790 #else
1791         /*
1792          *      This always gets defined.
1793          */
1794         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_NONE */
1795 #endif
1796
1797 #ifdef WITH_PROXY
1798         /* proxying */
1799         { common_socket_parse, NULL,
1800           proxy_socket_recv, proxy_socket_send,
1801           socket_print, proxy_socket_encode, proxy_socket_decode },
1802 #endif
1803
1804         /* authentication */
1805         { common_socket_parse, NULL,
1806           auth_socket_recv, auth_socket_send,
1807           socket_print, client_socket_encode, client_socket_decode },
1808
1809 #ifdef WITH_ACCOUNTING
1810         /* accounting */
1811         { common_socket_parse, NULL,
1812           acct_socket_recv, acct_socket_send,
1813           socket_print, client_socket_encode, client_socket_decode},
1814 #endif
1815
1816 #ifdef WITH_DETAIL
1817         /* detail */
1818         { detail_parse, detail_free,
1819           detail_recv, detail_send,
1820           detail_print, detail_encode, detail_decode },
1821 #endif
1822
1823 #ifdef WITH_VMPS
1824         /* vlan query protocol */
1825         { common_socket_parse, NULL,
1826           vqp_socket_recv, vqp_socket_send,
1827           socket_print, vqp_socket_encode, vqp_socket_decode },
1828 #endif
1829
1830 #ifdef WITH_DHCP
1831         /* dhcp query protocol */
1832         { dhcp_socket_parse, NULL,
1833           dhcp_socket_recv, dhcp_socket_send,
1834           socket_print, dhcp_socket_encode, dhcp_socket_decode },
1835 #endif
1836
1837 #ifdef WITH_COMMAND_SOCKET
1838         /* TCP command socket */
1839         { command_socket_parse, command_socket_free,
1840           command_domain_accept, command_domain_send,
1841           command_socket_print, command_socket_encode, command_socket_decode },
1842 #endif
1843
1844 #ifdef WITH_COA
1845         /* Change of Authorization */
1846         { common_socket_parse, NULL,
1847           coa_socket_recv, auth_socket_send, /* CoA packets are same as auth */
1848           socket_print, client_socket_encode, client_socket_decode },
1849 #endif
1850
1851 };
1852
1853
1854
1855 /*
1856  *      Binds a listener to a socket.
1857  */
1858 static int listen_bind(rad_listen_t *this)
1859 {
1860         int rcode;
1861         struct sockaddr_storage salocal;
1862         socklen_t       salen;
1863         listen_socket_t *sock = this->data;
1864 #ifndef WITH_TCP
1865 #define proto_for_port "udp"
1866 #define sock_type SOCK_DGRAM
1867 #else
1868         const char *proto_for_port = "udp";
1869         int sock_type = SOCK_DGRAM;
1870         
1871         if (sock->proto == IPPROTO_TCP) {
1872 #ifdef WITH_VMPS
1873                 if (this->type == RAD_LISTEN_VQP) {
1874                         radlog(L_ERR, "VQP does not support TCP transport");
1875                         return -1;
1876                 }
1877 #endif
1878
1879                 proto_for_port = "tcp";
1880                 sock_type = SOCK_STREAM;        
1881         }
1882 #endif
1883
1884         /*
1885          *      If the port is zero, then it means the appropriate
1886          *      thing from /etc/services.
1887          */
1888         if (sock->my_port == 0) {
1889                 struct servent  *svp;
1890
1891                 switch (this->type) {
1892                 case RAD_LISTEN_AUTH:
1893                         svp = getservbyname ("radius", proto_for_port);
1894                         if (svp != NULL) {
1895                                 sock->my_port = ntohs(svp->s_port);
1896                         } else {
1897                                 sock->my_port = PW_AUTH_UDP_PORT;
1898                         }
1899                         break;
1900
1901 #ifdef WITH_ACCOUNTING
1902                 case RAD_LISTEN_ACCT:
1903                         svp = getservbyname ("radacct", proto_for_port);
1904                         if (svp != NULL) {
1905                                 sock->my_port = ntohs(svp->s_port);
1906                         } else {
1907                                 sock->my_port = PW_ACCT_UDP_PORT;
1908                         }
1909                         break;
1910 #endif
1911
1912 #ifdef WITH_PROXY
1913                 case RAD_LISTEN_PROXY:
1914                         /* leave it at zero */
1915                         break;
1916 #endif
1917
1918 #ifdef WITH_VMPS
1919                 case RAD_LISTEN_VQP:
1920                         sock->my_port = 1589;
1921                         break;
1922 #endif
1923
1924 #ifdef WITH_COA
1925                 case RAD_LISTEN_COA:
1926                         svp = getservbyname ("radius-dynauth", "udp");
1927                         if (svp != NULL) {
1928                                 sock->my_port = ntohs(svp->s_port);
1929                         } else {
1930                                 sock->my_port = PW_COA_UDP_PORT;
1931                         }
1932                         break;
1933 #endif
1934
1935                 default:
1936                         DEBUG("WARNING: Internal sanity check failed in binding to socket.  Ignoring problem.");
1937                         return -1;
1938                 }
1939         }
1940
1941         /*
1942          *      Copy fr_socket() here, as we may need to bind to a device.
1943          */
1944         this->fd = socket(sock->my_ipaddr.af, sock_type, 0);
1945         if (this->fd < 0) {
1946                 radlog(L_ERR, "Failed opening socket: %s", strerror(errno));
1947                 return -1;
1948         }
1949                 
1950         /*
1951          *      Bind to a device BEFORE touching IP addresses.
1952          */
1953         if (sock->interface) {
1954 #ifdef SO_BINDTODEVICE
1955                 struct ifreq ifreq;
1956                 strcpy(ifreq.ifr_name, sock->interface);
1957
1958                 fr_suid_up();
1959                 rcode = setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
1960                                    (char *)&ifreq, sizeof(ifreq));
1961                 fr_suid_down();
1962                 if (rcode < 0) {
1963                         close(this->fd);
1964                         radlog(L_ERR, "Failed binding to interface %s: %s",
1965                                sock->interface, strerror(errno));
1966                         return -1;
1967                 } /* else it worked. */
1968 #else
1969 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1970 #ifdef HAVE_NET_IF_H
1971                 /*
1972                  *      Odds are that any system supporting "bind to
1973                  *      device" also supports IPv6, so this next bit
1974                  *      isn't necessary.  But it's here for
1975                  *      completeness.
1976                  *
1977                  *      If we're doing IPv6, and the scope hasn't yet
1978                  *      been defined, set the scope to the scope of
1979                  *      the interface.
1980                  */
1981                 if (sock->my_ipaddr.af == AF_INET6) {
1982                         if (sock->my_ipaddr.scope == 0) {
1983                                 sock->my_ipaddr.scope = if_nametoindex(sock->interface);
1984                                 if (sock->my_ipaddr.scope == 0) {
1985                                         close(this->fd);
1986                                         radlog(L_ERR, "Failed finding interface %s: %s",
1987                                                sock->interface, strerror(errno));
1988                                         return -1;
1989                                 }
1990                         } /* else scope was defined: we're OK. */
1991                 } else
1992 #endif
1993 #endif
1994                                 /*
1995                                  *      IPv4: no link local addresses,
1996                                  *      and no bind to device.
1997                                  */
1998                 {
1999                         close(this->fd);
2000                         radlog(L_ERR, "Failed binding to interface %s: \"bind to device\" is unsupported", sock->interface);
2001                         return -1;
2002                 }
2003 #endif
2004         }
2005
2006 #ifdef WITH_TCP
2007         if (sock->proto == IPPROTO_TCP) {
2008                 int on = 1;
2009
2010                 if (setsockopt(this->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
2011                         close(this->fd);
2012                         radlog(L_ERR, "Failed to reuse address: %s", strerror(errno));
2013                         return -1;
2014                 }
2015         }
2016 #endif
2017
2018 #if defined(WITH_TCP) && defined(WITH_UDPFROMTO)
2019         else                    /* UDP sockets get UDPfromto */
2020 #endif
2021
2022 #ifdef WITH_UDPFROMTO
2023         /*
2024          *      Initialize udpfromto for all sockets.
2025          */
2026         if (udpfromto_init(this->fd) != 0) {
2027                 close(this->fd);
2028                 return -1;
2029         }
2030 #endif
2031
2032         /*
2033          *      Set up sockaddr stuff.
2034          */
2035         if (!fr_ipaddr2sockaddr(&sock->my_ipaddr, sock->my_port, &salocal, &salen)) {
2036                 close(this->fd);
2037                 return -1;
2038         }
2039                 
2040 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2041         if (sock->my_ipaddr.af == AF_INET6) {
2042                 /*
2043                  *      Listening on '::' does NOT get you IPv4 to
2044                  *      IPv6 mapping.  You've got to listen on an IPv4
2045                  *      address, too.  This makes the rest of the server
2046                  *      design a little simpler.
2047                  */
2048 #ifdef IPV6_V6ONLY
2049                 
2050                 if (IN6_IS_ADDR_UNSPECIFIED(&sock->my_ipaddr.ipaddr.ip6addr)) {
2051                         int on = 1;
2052                         
2053                         setsockopt(this->fd, IPPROTO_IPV6, IPV6_V6ONLY,
2054                                    (char *)&on, sizeof(on));
2055                 }
2056 #endif /* IPV6_V6ONLY */
2057         }
2058 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
2059
2060         if (sock->my_ipaddr.af == AF_INET) {
2061                 UNUSED int flag;
2062                 
2063 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2064                 /*
2065                  *      Disable PMTU discovery.  On Linux, this
2066                  *      also makes sure that the "don't fragment"
2067                  *      flag is zero.
2068                  */
2069                 flag = IP_PMTUDISC_DONT;
2070                 setsockopt(this->fd, IPPROTO_IP, IP_MTU_DISCOVER,
2071                            &flag, sizeof(flag));
2072 #endif
2073
2074 #if defined(IP_DONTFRAG)
2075                 /*
2076                  *      Ensure that the "don't fragment" flag is zero.
2077                  */
2078                 flag = 0;
2079                 setsockopt(this->fd, IPPROTO_IP, IP_DONTFRAG,
2080                            &flag, sizeof(flag));
2081 #endif
2082         }
2083
2084 #ifdef WITH_DHCP
2085 #ifdef SO_BROADCAST
2086         if (sock->broadcast) {
2087                 int on = 1;
2088                 
2089                 if (setsockopt(this->fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
2090                         radlog(L_ERR, "Can't set broadcast option: %s\n",
2091                                strerror(errno));
2092                         return -1;
2093                 }
2094         }
2095 #endif
2096 #endif
2097
2098         /*
2099          *      May be binding to priviledged ports.
2100          */
2101         if (sock->my_port != 0) {
2102 #ifdef SO_REUSEADDR
2103                 int on = 1;
2104
2105                 if (setsockopt(this->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
2106                         radlog(L_ERR, "Can't set re-use address option: %s\n",
2107                                strerror(errno));
2108                         return -1;
2109                 }
2110 #endif
2111
2112                 fr_suid_up();
2113                 rcode = bind(this->fd, (struct sockaddr *) &salocal, salen);
2114                 fr_suid_down();
2115                 if (rcode < 0) {
2116                         char buffer[256];
2117                         close(this->fd);
2118                         
2119                         this->print(this, buffer, sizeof(buffer));
2120                         radlog(L_ERR, "Failed binding to %s: %s\n",
2121                                buffer, strerror(errno));
2122                         return -1;
2123                 }
2124         
2125                 /*
2126                  *      FreeBSD jail issues.  We bind to 0.0.0.0, but the
2127                  *      kernel instead binds us to a 1.2.3.4.  If this
2128                  *      happens, notice, and remember our real IP.
2129                  */
2130                 {
2131                         struct sockaddr_storage src;
2132                         socklen_t               sizeof_src = sizeof(src);
2133                         
2134                         memset(&src, 0, sizeof_src);
2135                         if (getsockname(this->fd, (struct sockaddr *) &src,
2136                                         &sizeof_src) < 0) {
2137                                 radlog(L_ERR, "Failed getting socket name: %s",
2138                                        strerror(errno));
2139                                 return -1;
2140                         }
2141                         
2142                         if (!fr_sockaddr2ipaddr(&src, sizeof_src,
2143                                                 &sock->my_ipaddr, &sock->my_port)) {
2144                                 radlog(L_ERR, "Socket has unsupported address family");
2145                                 return -1;
2146                         }
2147                 }
2148         }
2149
2150 #ifdef WITH_TCP
2151         if (sock->proto == IPPROTO_TCP) {
2152                 if (listen(this->fd, 8) < 0) {
2153                         close(this->fd);
2154                         radlog(L_ERR, "Failed in listen(): %s", strerror(errno));
2155                         return -1;
2156                 }
2157         } else
2158 #endif
2159
2160           if (fr_nonblock(this->fd) < 0) {
2161                   close(this->fd);
2162                   radlog(L_ERR, "Failed setting non-blocking on socket: %s",
2163                          strerror(errno));
2164                   return -1;
2165           }
2166
2167         /*
2168          *      Mostly for proxy sockets.
2169          */
2170         sock->other_ipaddr.af = sock->my_ipaddr.af;
2171
2172 /*
2173  *      Don't screw up other people.
2174  */
2175 #undef proto_for_port
2176 #undef sock_type
2177
2178         return 0;
2179 }
2180
2181
2182 /*
2183  *      Allocate & initialize a new listener.
2184  */
2185 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
2186 {
2187         rad_listen_t *this;
2188
2189         this = rad_malloc(sizeof(*this));
2190         memset(this, 0, sizeof(*this));
2191
2192         this->type = type;
2193         this->recv = master_listen[this->type].recv;
2194         this->send = master_listen[this->type].send;
2195         this->print = master_listen[this->type].print;
2196         this->encode = master_listen[this->type].encode;
2197         this->decode = master_listen[this->type].decode;
2198
2199         switch (type) {
2200 #ifdef WITH_STATS
2201         case RAD_LISTEN_NONE:
2202 #endif
2203         case RAD_LISTEN_AUTH:
2204 #ifdef WITH_ACCOUNTING
2205         case RAD_LISTEN_ACCT:
2206 #endif
2207 #ifdef WITH_PROXY
2208         case RAD_LISTEN_PROXY:
2209 #endif
2210 #ifdef WITH_VMPS
2211         case RAD_LISTEN_VQP:
2212 #endif
2213 #ifdef WITH_COA
2214         case RAD_LISTEN_COA:
2215 #endif
2216                 this->data = rad_malloc(sizeof(listen_socket_t));
2217                 memset(this->data, 0, sizeof(listen_socket_t));
2218                 break;
2219
2220 #ifdef WITH_DHCP
2221         case RAD_LISTEN_DHCP:
2222                 this->data = rad_malloc(sizeof(dhcp_socket_t));
2223                 memset(this->data, 0, sizeof(dhcp_socket_t));
2224                 break;
2225 #endif
2226
2227 #ifdef WITH_DETAIL
2228         case RAD_LISTEN_DETAIL:
2229                 this->data = NULL;
2230                 break;
2231 #endif
2232
2233 #ifdef WITH_COMMAND_SOCKET
2234         case RAD_LISTEN_COMMAND:
2235                 this->data = rad_malloc(sizeof(fr_command_socket_t));
2236                 memset(this->data, 0, sizeof(fr_command_socket_t));
2237                 break;
2238 #endif
2239
2240         default:
2241                 rad_assert("Unsupported option!" == NULL);
2242                 break;
2243         }
2244
2245         return this;
2246 }
2247
2248 #ifdef WITH_PROXY
2249 /*
2250  *      Externally visible function for creating a new proxy LISTENER.
2251  *
2252  *      Not thread-safe, but all calls to it are protected by the
2253  *      proxy mutex in event.c
2254  */
2255 int proxy_new_listener(home_server *home, int src_port)
2256 {
2257         rad_listen_t *this;
2258         listen_socket_t *sock;
2259
2260         if (!home) return 0;
2261
2262         if ((home->max_connections > 0) &&
2263             (home->num_connections >= home->max_connections)) {
2264                 DEBUG("WARNING: Home server has too many open connections (%d)",
2265                       home->max_connections);
2266                 return 0;
2267         }
2268
2269         this = listen_alloc(RAD_LISTEN_PROXY);
2270
2271         sock = this->data;
2272         sock->other_ipaddr = home->ipaddr;
2273         sock->other_port = home->port;
2274         sock->home = home;
2275
2276         sock->my_ipaddr = home->src_ipaddr;
2277         sock->my_port = src_port;
2278         sock->proto = home->proto;
2279
2280 #ifdef WITH_TCP
2281         sock->last_packet = time(NULL);
2282
2283         if (home->proto == IPPROTO_TCP) {
2284                 this->recv = proxy_socket_tcp_recv;
2285
2286                 /*
2287                  *      FIXME: connect() is blocking!
2288                  *      We do this with the proxy mutex locked, which may
2289                  *      cause large delays!
2290                  *
2291                  *      http://www.developerweb.net/forum/showthread.php?p=13486
2292                  */
2293                 this->fd = fr_tcp_client_socket(&home->src_ipaddr,
2294                                                 &home->ipaddr, home->port);
2295         } else
2296 #endif
2297                 this->fd = fr_socket(&home->src_ipaddr, src_port);
2298
2299         if (this->fd < 0) {
2300                 DEBUG("Failed opening client socket: %s", fr_strerror());
2301                 listen_free(&this);
2302                 return 0;
2303         }
2304
2305         /*
2306          *      Figure out which port we were bound to.
2307          */
2308         if (sock->my_port == 0) {
2309                 struct sockaddr_storage src;
2310                 socklen_t               sizeof_src = sizeof(src);
2311                 
2312                 memset(&src, 0, sizeof_src);
2313                 if (getsockname(this->fd, (struct sockaddr *) &src,
2314                                 &sizeof_src) < 0) {
2315                         radlog(L_ERR, "Failed getting socket name: %s",
2316                                strerror(errno));
2317                         listen_free(&this);
2318                         return 0;
2319                 }
2320                 
2321                 if (!fr_sockaddr2ipaddr(&src, sizeof_src,
2322                                         &sock->my_ipaddr, &sock->my_port)) {
2323                         radlog(L_ERR, "Socket has unsupported address family");
2324                         listen_free(&this);
2325                         return 0;
2326                 }
2327         }
2328
2329         /*
2330          *      Tell the event loop that we have a new FD
2331          */
2332         if (!event_new_fd(this)) {
2333                 listen_free(&this);
2334                 return 0;
2335         }
2336         
2337         return 1;
2338 }
2339 #endif
2340
2341
2342 static const FR_NAME_NUMBER listen_compare[] = {
2343 #ifdef WITH_STATS
2344         { "status",     RAD_LISTEN_NONE },
2345 #endif
2346         { "auth",       RAD_LISTEN_AUTH },
2347 #ifdef WITH_ACCOUNTING
2348         { "acct",       RAD_LISTEN_ACCT },
2349 #endif
2350 #ifdef WITH_DETAIL
2351         { "detail",     RAD_LISTEN_DETAIL },
2352 #endif
2353 #ifdef WITH_PROXY
2354         { "proxy",      RAD_LISTEN_PROXY },
2355 #endif
2356 #ifdef WITH_VMPS
2357         { "vmps",       RAD_LISTEN_VQP },
2358 #endif
2359 #ifdef WITH_DHCP
2360         { "dhcp",       RAD_LISTEN_DHCP },
2361 #endif
2362 #ifdef WITH_COMMAND_SOCKET
2363         { "control",    RAD_LISTEN_COMMAND },
2364 #endif
2365 #ifdef WITH_COA
2366         { "coa",        RAD_LISTEN_COA },
2367 #endif
2368         { NULL, 0 },
2369 };
2370
2371
2372 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
2373 {
2374         int             type, rcode;
2375         char            *listen_type;
2376         rad_listen_t    *this;
2377
2378         listen_type = NULL;
2379         
2380         cf_log_info(cs, "listen {");
2381
2382         rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
2383                               &listen_type, "");
2384         if (rcode < 0) return NULL;
2385         if (rcode == 1) {
2386                 free(listen_type);
2387                 cf_log_err(cf_sectiontoitem(cs),
2388                            "No type specified in listen section");
2389                 return NULL;
2390         }
2391
2392         type = fr_str2int(listen_compare, listen_type, -1);
2393         if (type < 0) {
2394                 cf_log_err(cf_sectiontoitem(cs),
2395                            "Invalid type \"%s\" in listen section.",
2396                            listen_type);
2397                 free(listen_type);
2398                 return NULL;
2399         }
2400         free(listen_type);
2401
2402         /*
2403          *      Allow listen sections in the default config to
2404          *      refer to a server.
2405          */
2406         if (!server) {
2407                 rcode = cf_item_parse(cs, "virtual_server", PW_TYPE_STRING_PTR,
2408                                       &server, NULL);
2409                 if (rcode == 1) { /* compatiblity with 2.0-pre */
2410                         rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
2411                                               &server, NULL);
2412                 }
2413                 if (rcode < 0) return NULL;
2414         }
2415
2416 #ifdef WITH_PROXY
2417         /*
2418          *      We were passed a virtual server, so the caller is
2419          *      defining a proxy listener inside of a virtual server.
2420          *      This isn't allowed right now.
2421          */
2422         else if (type == RAD_LISTEN_PROXY) {
2423                 radlog(L_ERR, "Error: listen type \"proxy\" Cannot appear in a virtual server section");
2424                 return NULL;
2425         }
2426 #endif
2427
2428         /*
2429          *      Set up cross-type data.
2430          */
2431         this = listen_alloc(type);
2432         this->server = server;
2433         this->fd = -1;
2434
2435         /*
2436          *      Call per-type parser.
2437          */
2438         if (master_listen[type].parse(cs, this) < 0) {
2439                 listen_free(&this);
2440                 return NULL;
2441         }
2442
2443         cf_log_info(cs, "}");
2444
2445         return this;
2446 }
2447
2448 static int is_loopback(const fr_ipaddr_t *ipaddr)
2449 {
2450         /*
2451          *      We shouldn't proxy on loopback.
2452          */
2453         if ((ipaddr->af == AF_INET) &&
2454             (ipaddr->ipaddr.ip4addr.s_addr == htonl(INADDR_LOOPBACK))) {
2455                 return 1;
2456         }
2457         
2458 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2459         if ((ipaddr->af == AF_INET6) &&
2460             (IN6_IS_ADDR_LINKLOCAL(&ipaddr->ipaddr.ip6addr))) {
2461                 return 1;
2462         }
2463 #endif
2464
2465         return 0;
2466 }
2467
2468 /*
2469  *      Generate a list of listeners.  Takes an input list of
2470  *      listeners, too, so we don't close sockets with waiting packets.
2471  */
2472 int listen_init(CONF_SECTION *config, rad_listen_t **head)
2473 {
2474         int             override = FALSE;
2475         int             rcode;
2476         CONF_SECTION    *cs = NULL;
2477         rad_listen_t    **last;
2478         rad_listen_t    *this;
2479         fr_ipaddr_t     server_ipaddr;
2480         int             auth_port = 0;
2481 #ifdef WITH_PROXY
2482         int             defined_proxy = 0;
2483 #endif
2484
2485         /*
2486          *      We shouldn't be called with a pre-existing list.
2487          */
2488         rad_assert(head && (*head == NULL));
2489
2490         last = head;
2491         server_ipaddr.af = AF_UNSPEC;
2492
2493         /*
2494          *      If the port is specified on the command-line,
2495          *      it over-rides the configuration file.
2496          *
2497          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
2498          */
2499         if (mainconfig.port >= 0) auth_port = mainconfig.port;
2500
2501         /*
2502          *      If the IP address was configured on the command-line,
2503          *      use that as the "bind_address"
2504          */
2505         if (mainconfig.myip.af != AF_UNSPEC) {
2506                 memcpy(&server_ipaddr, &mainconfig.myip,
2507                        sizeof(server_ipaddr));
2508                 override = TRUE;
2509                 goto bind_it;
2510         }
2511
2512         /*
2513          *      Else look for bind_address and/or listen sections.
2514          */
2515         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
2516         rcode = cf_item_parse(config, "bind_address",
2517                               PW_TYPE_IPADDR,
2518                               &server_ipaddr.ipaddr.ip4addr, NULL);
2519         if (rcode < 0) return -1; /* error parsing it */
2520
2521         if (rcode == 0) { /* successfully parsed IPv4 */
2522                 listen_socket_t *sock;
2523                 server_ipaddr.af = AF_INET;
2524
2525                 radlog(L_INFO, "WARNING: The directive 'bind_address' is deprecated, and will be removed in future versions of FreeRADIUS. Please edit the configuration files to use the directive 'listen'.");
2526
2527         bind_it:
2528 #ifdef WITH_VMPS
2529                 if (strcmp(progname, "vmpsd") == 0) {
2530                         this = listen_alloc(RAD_LISTEN_VQP);
2531                         if (!auth_port) auth_port = 1589;
2532                 } else
2533 #endif
2534                         this = listen_alloc(RAD_LISTEN_AUTH);
2535
2536                 sock = this->data;
2537
2538                 sock->my_ipaddr = server_ipaddr;
2539                 sock->my_port = auth_port;
2540
2541                 sock->clients = clients_parse_section(config);
2542                 if (!sock->clients) {
2543                         cf_log_err(cf_sectiontoitem(config),
2544                                    "Failed to find any clients for this listen section");
2545                         listen_free(&this);
2546                         return -1;
2547                 }
2548
2549                 if (listen_bind(this) < 0) {
2550                         listen_free(head);
2551                         radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->my_port);
2552                         listen_free(&this);
2553                         return -1;
2554                 }
2555                 auth_port = sock->my_port;      /* may have been updated in listen_bind */
2556                 if (override) {
2557                         cs = cf_section_sub_find_name2(config, "server",
2558                                                        mainconfig.name);
2559                         if (cs) this->server = mainconfig.name;
2560                 }
2561
2562                 *last = this;
2563                 last = &(this->next);
2564
2565 #ifdef WITH_VMPS
2566                 /*
2567                  *      No acct for vmpsd
2568                  */
2569                 if (strcmp(progname, "vmpsd") == 0) goto add_sockets;
2570 #endif
2571
2572 #ifdef WITH_ACCOUNTING
2573                 /*
2574                  *      Open Accounting Socket.
2575                  *
2576                  *      If we haven't already gotten acct_port from
2577                  *      /etc/services, then make it auth_port + 1.
2578                  */
2579                 this = listen_alloc(RAD_LISTEN_ACCT);
2580                 sock = this->data;
2581
2582                 /*
2583                  *      Create the accounting socket.
2584                  *
2585                  *      The accounting port is always the
2586                  *      authentication port + 1
2587                  */
2588                 sock->my_ipaddr = server_ipaddr;
2589                 sock->my_port = auth_port + 1;
2590
2591                 sock->clients = clients_parse_section(config);
2592                 if (!sock->clients) {
2593                         cf_log_err(cf_sectiontoitem(config),
2594                                    "Failed to find any clients for this listen section");
2595                         return -1;
2596                 }
2597
2598                 if (listen_bind(this) < 0) {
2599                         listen_free(&this);
2600                         listen_free(head);
2601                         radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->my_port);
2602                         return -1;
2603                 }
2604
2605                 if (override) {
2606                         cs = cf_section_sub_find_name2(config, "server",
2607                                                        mainconfig.name);
2608                         if (cs) this->server = mainconfig.name;
2609                 }
2610
2611                 *last = this;
2612                 last = &(this->next);
2613 #endif
2614         } else if (mainconfig.port > 0) { /* no bind address, but a port */
2615                 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
2616                        mainconfig.port);
2617                 return -1;
2618         }
2619
2620         /*
2621          *      They specified an IP on the command-line, ignore
2622          *      all listen sections except the one in '-n'.
2623          */
2624         if (mainconfig.myip.af != AF_UNSPEC) {
2625                 CONF_SECTION *subcs;
2626                 const char *name2 = cf_section_name2(cs);
2627
2628                 cs = cf_section_sub_find_name2(config, "server",
2629                                                mainconfig.name);
2630                 if (!cs) goto add_sockets;
2631
2632                 /*
2633                  *      Should really abstract this code...
2634                  */
2635                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
2636                      subcs != NULL;
2637                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
2638                         this = listen_parse(subcs, name2);
2639                         if (!this) {
2640                                 listen_free(head);
2641                                 return -1;
2642                         }
2643
2644                         *last = this;
2645                         last = &(this->next);
2646                 } /* loop over "listen" directives in server <foo> */
2647
2648                 goto add_sockets;
2649         }
2650
2651         /*
2652          *      Walk through the "listen" sections, if they exist.
2653          */
2654         for (cs = cf_subsection_find_next(config, NULL, "listen");
2655              cs != NULL;
2656              cs = cf_subsection_find_next(config, cs, "listen")) {
2657                 this = listen_parse(cs, NULL);
2658                 if (!this) {
2659                         listen_free(head);
2660                         return -1;
2661                 }
2662
2663                 *last = this;
2664                 last = &(this->next);
2665         }
2666
2667         /*
2668          *      Check virtual servers for "listen" sections, too.
2669          *
2670          *      FIXME: Move to virtual server init?
2671          */
2672         for (cs = cf_subsection_find_next(config, NULL, "server");
2673              cs != NULL;
2674              cs = cf_subsection_find_next(config, cs, "server")) {
2675                 CONF_SECTION *subcs;
2676                 const char *name2 = cf_section_name2(cs);
2677                 
2678                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
2679                      subcs != NULL;
2680                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
2681                         this = listen_parse(subcs, name2);
2682                         if (!this) {
2683                                 listen_free(head);
2684                                 return -1;
2685                         }
2686                         
2687                         *last = this;
2688                         last = &(this->next);
2689                 } /* loop over "listen" directives in virtual servers */
2690         } /* loop over virtual servers */
2691
2692 add_sockets:
2693         /*
2694          *      No sockets to receive packets, this is an error.
2695          *      proxying is pointless.
2696          */
2697         if (!*head) {
2698                 radlog(L_ERR, "The server is not configured to listen on any ports.  Cannot start.");
2699                 return -1;
2700         }
2701
2702         /*
2703          *      Print out which sockets we're listening on, and
2704          *      add them to the event list.
2705          */
2706         for (this = *head; this != NULL; this = this->next) {
2707 #ifdef WITH_PROXY
2708                 if (this->type == RAD_LISTEN_PROXY) {
2709                         defined_proxy = 1;
2710                 }
2711
2712 #endif
2713                 event_new_fd(this);
2714         }
2715
2716         /*
2717          *      If we're proxying requests, open the proxy FD.
2718          *      Otherwise, don't do anything.
2719          */
2720 #ifdef WITH_PROXY
2721         if ((mainconfig.proxy_requests == TRUE) &&
2722             (*head != NULL) && !defined_proxy) {
2723                 listen_socket_t *sock = NULL;
2724                 int             port = 0;
2725                 home_server     home;
2726
2727                 memset(&home, 0, sizeof(home));
2728
2729                 /*
2730                  *      
2731                  */
2732                 home.proto = IPPROTO_UDP;
2733                 home.src_ipaddr = server_ipaddr;
2734
2735                 /*
2736                  *      Find the first authentication port,
2737                  *      and use it
2738                  */
2739                 for (this = *head; this != NULL; this = this->next) {
2740                         if (this->type == RAD_LISTEN_AUTH) {
2741                                 sock = this->data;
2742
2743                                 if (is_loopback(&sock->my_ipaddr)) continue;
2744
2745                                 if (home.src_ipaddr.af == AF_UNSPEC) {
2746                                         home.src_ipaddr = sock->my_ipaddr;
2747                                 }
2748                                 port = sock->my_port + 2;
2749                                 break;
2750                         }
2751 #ifdef WITH_ACCT
2752                         if (this->type == RAD_LISTEN_ACCT) {
2753                                 sock = this->data;
2754
2755                                 if (is_loopback(&sock->my_ipaddr)) continue;
2756
2757                                 if (home.src_ipaddr.af == AF_UNSPEC) {
2758                                         home.src_ipaddr = sock->my_ipaddr;
2759                                 }
2760                                 port = sock->my_port + 1;
2761                                 break;
2762                         }
2763 #endif
2764                 }
2765
2766                 /*
2767                  *      Address is still unspecified, use IPv4.
2768                  */
2769                 if (home.src_ipaddr.af == AF_UNSPEC) {
2770                         home.src_ipaddr.af = AF_INET;
2771                         /* everything else is already set to zero */
2772                 }
2773
2774                 home.ipaddr.af = home.src_ipaddr.af;
2775                 /* everything else is already set to zero */
2776
2777                 if (!proxy_new_listener(&home, port)) {
2778                         listen_free(head);
2779                         return -1;
2780                 }
2781         }
2782 #endif
2783
2784         /*
2785          *      Haven't defined any sockets.  Die.
2786          */
2787         if (!*head) return -1;
2788
2789
2790         return 0;
2791 }
2792
2793 /*
2794  *      Free a linked list of listeners;
2795  */
2796 void listen_free(rad_listen_t **head)
2797 {
2798         rad_listen_t *this;
2799
2800         if (!head || !*head) return;
2801
2802         this = *head;
2803         while (this) {
2804                 rad_listen_t *next = this->next;
2805
2806                 /*
2807                  *      Other code may have eaten the FD.
2808                  */
2809                 if (this->fd >= 0) close(this->fd);
2810
2811                 if (master_listen[this->type].free) {
2812                         master_listen[this->type].free(this);
2813                 }
2814
2815 #ifdef WITH_TCP
2816                 if ((this->type == RAD_LISTEN_AUTH)
2817 #ifdef WITH_ACCT
2818                     || (this->type == RAD_LISTEN_ACCT)
2819 #endif
2820 #ifdef WITH_PROXY
2821                     || (this->type == RAD_LISTEN_PROXY)
2822 #endif
2823                         ) {
2824                         listen_socket_t *sock = this->data;
2825                         rad_free(&sock->packet);
2826                 }
2827 #endif
2828
2829                 free(this->data);
2830                 free(this);
2831
2832                 this = next;
2833         }
2834
2835         *head = NULL;
2836 }
2837
2838 #ifdef WITH_STATS
2839 RADCLIENT_LIST *listener_find_client_list(const fr_ipaddr_t *ipaddr,
2840                                           int port)
2841 {
2842         rad_listen_t *this;
2843
2844         for (this = mainconfig.listen; this != NULL; this = this->next) {
2845                 listen_socket_t *sock;
2846
2847                 if ((this->type != RAD_LISTEN_AUTH)
2848 #ifdef WITH_ACCOUNTING
2849                     && (this->type != RAD_LISTEN_ACCT)
2850 #endif
2851                     ) continue;
2852                 
2853                 sock = this->data;
2854
2855                 if ((sock->my_port == port) &&
2856                     (fr_ipaddr_cmp(ipaddr, &sock->my_ipaddr) == 0)) {
2857                         return sock->clients;
2858                 }
2859         }
2860
2861         return NULL;
2862 }
2863 #endif
2864
2865 rad_listen_t *listener_find_byipaddr(const fr_ipaddr_t *ipaddr, int port)
2866 {
2867         rad_listen_t *this;
2868
2869         for (this = mainconfig.listen; this != NULL; this = this->next) {
2870                 listen_socket_t *sock;
2871
2872                 /*
2873                  *      FIXME: For TCP, ignore the *secondary*
2874                  *      listeners associated with the main socket.
2875                  */
2876                 if ((this->type != RAD_LISTEN_AUTH)
2877 #ifdef WITH_ACCOUNTING
2878                     && (this->type != RAD_LISTEN_ACCT)
2879 #endif
2880                     ) continue;
2881                 
2882                 sock = this->data;
2883
2884                 if ((sock->my_port == port) &&
2885                     (fr_ipaddr_cmp(ipaddr, &sock->my_ipaddr) == 0)) {
2886                         return this;
2887                 }
2888
2889                 if ((sock->my_port == port) &&
2890                     fr_inaddr_any(&sock->my_ipaddr)) {
2891                         return this;
2892                 }
2893         }
2894
2895         return NULL;
2896 }