Revert "Delete control socket when the server exits."
[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(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         /*
729          *      Maybe it's a socket that we opened to a home server.
730          */
731         if ((sock->proto == IPPROTO_TCP) &&
732             (this->type == RAD_LISTEN_PROXY)) {
733                 ADDSTRING(" (");
734                 ip_ntoh(&sock->my_ipaddr, buffer, bufsize);
735                 FORWARD;
736
737                 ADDSTRING(", ");
738                 snprintf(buffer, bufsize, "%d", sock->my_port);
739                 FORWARD;
740                 ADDSTRING(") -> home_server (");
741
742                 if ((sock->other_ipaddr.af == AF_INET) &&
743                     (sock->other_ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
744                         strlcpy(buffer, "*", bufsize);
745                 } else {
746                         ip_ntoh(&sock->other_ipaddr, buffer, bufsize);
747                 }
748                 FORWARD;
749                 
750                 ADDSTRING(", ");
751                 snprintf(buffer, bufsize, "%d", sock->other_port);
752                 FORWARD;
753
754                 ADDSTRING(")");
755
756                 return 1;
757         }
758 #endif
759
760         ADDSTRING(" address ");
761         
762         if ((sock->my_ipaddr.af == AF_INET) &&
763             (sock->my_ipaddr.ipaddr.ip4addr.s_addr == htonl(INADDR_ANY))) {
764                 strlcpy(buffer, "*", bufsize);
765         } else {
766                 ip_ntoh(&sock->my_ipaddr, buffer, bufsize);
767         }
768         FORWARD;
769
770         ADDSTRING(" port ");
771         snprintf(buffer, bufsize, "%d", sock->my_port);
772         FORWARD;
773
774         if (this->server) {
775                 ADDSTRING(" as server ");
776                 ADDSTRING(this->server);
777         }
778
779 #undef ADDSTRING
780 #undef FORWARD
781
782         return 1;
783 }
784
785
786 /*
787  *      Parse an authentication or accounting socket.
788  */
789 static int common_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
790 {
791         int             rcode;
792         int             listen_port;
793         fr_ipaddr_t     ipaddr;
794         listen_socket_t *sock = this->data;
795         char            *section_name = NULL;
796         CONF_SECTION    *client_cs, *parentcs;
797
798         /*
799          *      Try IPv4 first
800          */
801         ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
802         rcode = cf_item_parse(cs, "ipaddr", PW_TYPE_IPADDR,
803                               &ipaddr.ipaddr.ip4addr, NULL);
804         if (rcode < 0) return -1;
805
806         if (rcode == 0) { /* successfully parsed IPv4 */
807                 ipaddr.af = AF_INET;
808
809         } else {        /* maybe IPv6? */
810                 rcode = cf_item_parse(cs, "ipv6addr", PW_TYPE_IPV6ADDR,
811                                       &ipaddr.ipaddr.ip6addr, NULL);
812                 if (rcode < 0) return -1;
813
814                 if (rcode == 1) {
815                         cf_log_err(cf_sectiontoitem(cs),
816                                    "No address specified in listen section");
817                         return -1;
818                 }
819                 ipaddr.af = AF_INET6;
820         }
821
822         rcode = cf_item_parse(cs, "port", PW_TYPE_INTEGER,
823                               &listen_port, "0");
824         if (rcode < 0) return -1;
825
826         if ((listen_port < 0) || (listen_port > 65535)) {
827                         cf_log_err(cf_sectiontoitem(cs),
828                                    "Invalid value for \"port\"");
829                         return -1;
830         }
831
832         sock->proto = IPPROTO_UDP;
833
834         if (cf_pair_find(cs, "proto")) {
835 #ifndef WITH_TCP
836                 cf_log_err(cf_sectiontoitem(cs),
837                            "System does not support the TCP protocol.  Delete this line from the configuration file.");
838                 return -1;
839 #else
840                 char *proto = NULL;
841
842
843                 rcode = cf_item_parse(cs, "proto", PW_TYPE_STRING_PTR,
844                                       &proto, "udp");
845                 if (rcode < 0) return -1;
846
847                 if (strcmp(proto, "udp") == 0) {
848                         sock->proto = IPPROTO_UDP;
849
850                 } else if (strcmp(proto, "tcp") == 0) {
851                         sock->proto = IPPROTO_TCP;
852
853                         rcode = cf_item_parse(cs, "max_connections", PW_TYPE_INTEGER,
854                                               &sock->max_connections, "64");
855                         if (rcode < 0) return -1;
856
857                 } else {
858                         cf_log_err(cf_sectiontoitem(cs),
859                                    "Unknown proto name \"%s\"", proto);
860                         free(proto);
861                         return -1;
862                 }
863                 free(proto);
864
865                 /*
866                  *      TCP requires a destination IP for sockets.
867                  *      UDP doesn't, so it's allowed.
868                  */
869                 if ((this->type == RAD_LISTEN_PROXY) &&
870                     (sock->proto != IPPROTO_UDP)) {
871                         cf_log_err(cf_sectiontoitem(cs),
872                                    "Proxy listeners can only listen on proto = udp");
873                         return -1;
874                 }
875 #endif
876         }
877
878         sock->my_ipaddr = ipaddr;
879         sock->my_port = listen_port;
880
881         /*
882          *      If we can bind to interfaces, do so,
883          *      else don't.
884          */
885         if (cf_pair_find(cs, "interface")) {
886                 const char *value;
887                 CONF_PAIR *cp = cf_pair_find(cs, "interface");
888
889                 rad_assert(cp != NULL);
890                 value = cf_pair_value(cp);
891                 if (!value) {
892                         cf_log_err(cf_sectiontoitem(cs),
893                                    "No interface name given");
894                         return -1;
895                 }
896                 sock->interface = value;
897         }
898
899 #ifdef WITH_DHCP
900         /*
901          *      If we can do broadcasts..
902          */
903         if (cf_pair_find(cs, "broadcast")) {
904 #ifndef SO_BROADCAST
905                 cf_log_err(cf_sectiontoitem(cs),
906                            "System does not support broadcast sockets.  Delete this line from the configuration file.");
907                 return -1;
908 #else
909                 const char *value;
910                 CONF_PAIR *cp = cf_pair_find(cs, "broadcast");
911
912                 if (this->type != RAD_LISTEN_DHCP) {
913                         cf_log_err(cf_pairtoitem(cp),
914                                    "Broadcast can only be set for DHCP listeners.  Delete this line from the configuration file.");
915                         return -1;
916                 }
917                 
918                 rad_assert(cp != NULL);
919                 value = cf_pair_value(cp);
920                 if (!value) {
921                         cf_log_err(cf_sectiontoitem(cs),
922                                    "No broadcast value given");
923                         return -1;
924                 }
925
926                 /*
927                  *      Hack... whatever happened to cf_section_parse?
928                  */
929                 sock->broadcast = (strcmp(value, "yes") == 0);
930 #endif
931         }
932 #endif
933
934         /*
935          *      And bind it to the port.
936          */
937         if (listen_bind(this) < 0) {
938                 char buffer[128];
939                 cf_log_err(cf_sectiontoitem(cs),
940                            "Error binding to port for %s port %d",
941                            ip_ntoh(&sock->my_ipaddr, buffer, sizeof(buffer)),
942                            sock->my_port);
943                 return -1;
944         }
945
946 #ifdef WITH_PROXY
947         /*
948          *      Proxy sockets don't have clients.
949          */
950         if (this->type == RAD_LISTEN_PROXY) return 0;
951 #endif
952         
953         /*
954          *      The more specific configurations are preferred to more
955          *      generic ones.
956          */
957         client_cs = NULL;
958         parentcs = cf_top_section(cs);
959         rcode = cf_item_parse(cs, "clients", PW_TYPE_STRING_PTR,
960                               &section_name, NULL);
961         if (rcode < 0) return -1; /* bad string */
962         if (rcode == 0) {
963                 /*
964                  *      Explicit list given: use it.
965                  */
966                 client_cs = cf_section_sub_find_name2(parentcs,
967                                                       "clients",
968                                                       section_name);
969                 if (!client_cs) {
970                         client_cs = cf_section_find(section_name);
971                 }
972                 if (!client_cs) {
973                         cf_log_err(cf_sectiontoitem(cs),
974                                    "Failed to find clients %s {...}",
975                                    section_name);
976                         free(section_name);
977                         return -1;
978                 }
979                 free(section_name);
980         } /* else there was no "clients = " entry. */
981
982         if (!client_cs) {
983                 CONF_SECTION *server_cs;
984
985                 server_cs = cf_section_sub_find_name2(parentcs,
986                                                       "server",
987                                                       this->server);
988                 /*
989                  *      Found a "server foo" section.  If there are clients
990                  *      in it, use them.
991                  */
992                 if (server_cs &&
993                     (cf_section_sub_find(server_cs, "client") != NULL)) {
994                         client_cs = server_cs;
995                 }
996         }
997
998         /*
999          *      Still nothing.  Look for global clients.
1000          */
1001         if (!client_cs) client_cs = parentcs;
1002
1003         sock->clients = clients_parse_section(client_cs);
1004         if (!sock->clients) {
1005                 cf_log_err(cf_sectiontoitem(cs),
1006                            "Failed to load clients for this listen section");
1007                 return -1;
1008         }
1009
1010 #ifdef WITH_TCP
1011         if (sock->proto == IPPROTO_TCP) {
1012                 /*
1013                  *      Re-write the listener receive function to
1014                  *      allow us to accept the socket.
1015                  */
1016                 this->recv = auth_tcp_accept;
1017         }
1018 #endif
1019
1020         return 0;
1021 }
1022
1023 /*
1024  *      Send an authentication response packet
1025  */
1026 static int auth_socket_send(rad_listen_t *listener, REQUEST *request)
1027 {
1028         rad_assert(request->listener == listener);
1029         rad_assert(listener->send == auth_socket_send);
1030
1031         return rad_send(request->reply, request->packet,
1032                         request->client->secret);
1033 }
1034
1035
1036 #ifdef WITH_ACCOUNTING
1037 /*
1038  *      Send an accounting response packet (or not)
1039  */
1040 static int acct_socket_send(rad_listen_t *listener, REQUEST *request)
1041 {
1042         rad_assert(request->listener == listener);
1043         rad_assert(listener->send == acct_socket_send);
1044
1045         /*
1046          *      Accounting reject's are silently dropped.
1047          *
1048          *      We do it here to avoid polluting the rest of the
1049          *      code with this knowledge
1050          */
1051         if (request->reply->code == 0) return 0;
1052
1053         return rad_send(request->reply, request->packet,
1054                         request->client->secret);
1055 }
1056 #endif
1057
1058 #ifdef WITH_PROXY
1059 /*
1060  *      Send a packet to a home server.
1061  *
1062  *      FIXME: have different code for proxy auth & acct!
1063  */
1064 static int proxy_socket_send(rad_listen_t *listener, REQUEST *request)
1065 {
1066         rad_assert(request->proxy_listener == listener);
1067         rad_assert(listener->send == proxy_socket_send);
1068
1069         return rad_send(request->proxy, request->packet,
1070                         request->home_server->secret);
1071 }
1072 #endif
1073
1074 #ifdef WITH_STATS
1075 /*
1076  *      Check if an incoming request is "ok"
1077  *
1078  *      It takes packets, not requests.  It sees if the packet looks
1079  *      OK.  If so, it does a number of sanity checks on it.
1080   */
1081 static int stats_socket_recv(rad_listen_t *listener,
1082                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1083 {
1084         ssize_t         rcode;
1085         int             code, src_port;
1086         RADIUS_PACKET   *packet;
1087         RADCLIENT       *client;
1088         fr_ipaddr_t     src_ipaddr;
1089
1090         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1091         if (rcode < 0) return 0;
1092
1093         RAD_STATS_TYPE_INC(listener, total_requests);
1094
1095         if (rcode < 20) {       /* AUTH_HDR_LEN */
1096                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1097                 return 0;
1098         }
1099
1100         if ((client = client_listener_find(listener,
1101                                            &src_ipaddr, src_port)) == NULL) {
1102                 rad_recv_discard(listener->fd);
1103                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
1104                 return 0;
1105         }
1106
1107         /*
1108          *      We only understand Status-Server on this socket.
1109          */
1110         if (code != PW_STATUS_SERVER) {
1111                 DEBUG("Ignoring packet code %d sent to Status-Server port",
1112                       code);
1113                 rad_recv_discard(listener->fd);
1114                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
1115                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
1116                 return 0;
1117         }
1118
1119         /*
1120          *      Now that we've sanity checked everything, receive the
1121          *      packet.
1122          */
1123         packet = rad_recv(listener->fd, 1); /* require message authenticator */
1124         if (!packet) {
1125                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1126                 DEBUG("%s", fr_strerror());
1127                 return 0;
1128         }
1129
1130         if (!received_request(listener, packet, prequest, client)) {
1131                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1132                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
1133                 rad_free(&packet);
1134                 return 0;
1135         }
1136
1137         *pfun = rad_status_server;
1138         return 1;
1139 }
1140 #endif
1141
1142
1143 /*
1144  *      Check if an incoming request is "ok"
1145  *
1146  *      It takes packets, not requests.  It sees if the packet looks
1147  *      OK.  If so, it does a number of sanity checks on it.
1148   */
1149 static int auth_socket_recv(rad_listen_t *listener,
1150                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1151 {
1152         ssize_t         rcode;
1153         int             code, src_port;
1154         RADIUS_PACKET   *packet;
1155         RAD_REQUEST_FUNP fun = NULL;
1156         RADCLIENT       *client;
1157         fr_ipaddr_t     src_ipaddr;
1158
1159         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1160         if (rcode < 0) return 0;
1161
1162         RAD_STATS_TYPE_INC(listener, total_requests);
1163
1164         if (rcode < 20) {       /* AUTH_HDR_LEN */
1165                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1166                 return 0;
1167         }
1168
1169         if ((client = client_listener_find(listener,
1170                                            &src_ipaddr, src_port)) == NULL) {
1171                 rad_recv_discard(listener->fd);
1172                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
1173                 return 0;
1174         }
1175
1176         /*
1177          *      Some sanity checks, based on the packet code.
1178          */
1179         switch(code) {
1180         case PW_AUTHENTICATION_REQUEST:
1181                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
1182                 fun = rad_authenticate;
1183                 break;
1184
1185         case PW_STATUS_SERVER:
1186                 if (!mainconfig.status_server) {
1187                         rad_recv_discard(listener->fd);
1188                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1189                         RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
1190                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
1191                         return 0;
1192                 }
1193                 fun = rad_status_server;
1194                 break;
1195
1196         default:
1197                 rad_recv_discard(listener->fd);
1198                 RAD_STATS_INC(radius_auth_stats.total_unknown_types);
1199                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
1200
1201                 DEBUG("Invalid packet code %d sent to authentication port from client %s port %d : IGNORED",
1202                       code, client->shortname, src_port);
1203                 return 0;
1204                 break;
1205         } /* switch over packet types */
1206
1207         /*
1208          *      Now that we've sanity checked everything, receive the
1209          *      packet.
1210          */
1211         packet = rad_recv(listener->fd, client->message_authenticator);
1212         if (!packet) {
1213                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1214                 DEBUG("%s", fr_strerror());
1215                 return 0;
1216         }
1217
1218         if (!received_request(listener, packet, prequest, client)) {
1219                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1220                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
1221                 rad_free(&packet);
1222                 return 0;
1223         }
1224
1225         *pfun = fun;
1226         return 1;
1227 }
1228
1229
1230 #ifdef WITH_ACCOUNTING
1231 /*
1232  *      Receive packets from an accounting socket
1233  */
1234 static int acct_socket_recv(rad_listen_t *listener,
1235                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1236 {
1237         ssize_t         rcode;
1238         int             code, src_port;
1239         RADIUS_PACKET   *packet;
1240         RAD_REQUEST_FUNP fun = NULL;
1241         RADCLIENT       *client;
1242         fr_ipaddr_t     src_ipaddr;
1243
1244         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1245         if (rcode < 0) return 0;
1246
1247         RAD_STATS_TYPE_INC(listener, total_requests);
1248
1249         if (rcode < 20) {       /* AUTH_HDR_LEN */
1250                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1251                 return 0;
1252         }
1253
1254         if ((client = client_listener_find(listener,
1255                                            &src_ipaddr, src_port)) == NULL) {
1256                 rad_recv_discard(listener->fd);
1257                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
1258                 return 0;
1259         }
1260
1261         /*
1262          *      Some sanity checks, based on the packet code.
1263          */
1264         switch(code) {
1265         case PW_ACCOUNTING_REQUEST:
1266                 RAD_STATS_CLIENT_INC(listener, client, total_requests);
1267                 fun = rad_accounting;
1268                 break;
1269
1270         case PW_STATUS_SERVER:
1271                 if (!mainconfig.status_server) {
1272                         rad_recv_discard(listener->fd);
1273                         RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1274                         RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
1275
1276                         DEBUG("WARNING: Ignoring Status-Server request due to security configuration");
1277                         return 0;
1278                 }
1279                 fun = rad_status_server;
1280                 break;
1281
1282         default:
1283                 rad_recv_discard(listener->fd);
1284                 RAD_STATS_TYPE_INC(listener, total_unknown_types);
1285                 RAD_STATS_CLIENT_INC(listener, client, total_unknown_types);
1286
1287                 DEBUG("Invalid packet code %d sent to a accounting port from client %s port %d : IGNORED",
1288                       code, client->shortname, src_port);
1289                 return 0;
1290         } /* switch over packet types */
1291
1292         /*
1293          *      Now that we've sanity checked everything, receive the
1294          *      packet.
1295          */
1296         packet = rad_recv(listener->fd, 0);
1297         if (!packet) {
1298                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1299                 radlog(L_ERR, "%s", fr_strerror());
1300                 return 0;
1301         }
1302
1303         /*
1304          *      There can be no duplicate accounting packets.
1305          */
1306         if (!received_request(listener, packet, prequest, client)) {
1307                 RAD_STATS_TYPE_INC(listener, total_packets_dropped);
1308                 RAD_STATS_CLIENT_INC(listener, client, total_packets_dropped);
1309                 rad_free(&packet);
1310                 return 0;
1311         }
1312
1313         *pfun = fun;
1314         return 1;
1315 }
1316 #endif
1317
1318
1319 #ifdef WITH_COA
1320 /*
1321  *      For now, all CoA requests are *only* originated, and not
1322  *      proxied.  So all of the necessary work is done in the
1323  *      post-proxy section, which is automatically handled by event.c.
1324  *      As a result, we don't have to do anything here.
1325  */
1326 static int rad_coa_reply(REQUEST *request)
1327 {
1328         VALUE_PAIR *s1, *s2;
1329
1330         /*
1331          *      Inform the user about RFC requirements.
1332          */
1333         s1 = pairfind(request->proxy->vps, PW_STATE, 0);
1334         if (s1) {
1335                 s2 = pairfind(request->proxy_reply->vps, PW_STATE, 0);
1336
1337                 if (!s2) {
1338                         DEBUG("WARNING: Client was sent State in CoA, and did not respond with State.");
1339
1340                 } else if ((s1->length != s2->length) ||
1341                            (memcmp(s1->vp_octets, s2->vp_octets,
1342                                    s1->length) != 0)) {
1343                         DEBUG("WARNING: Client was sent State in CoA, and did not respond with the same State.");
1344                 }
1345         }
1346
1347         return RLM_MODULE_OK;
1348 }
1349
1350 /*
1351  *      Receive a CoA packet.
1352  */
1353 static int rad_coa_recv(REQUEST *request)
1354 {
1355         int rcode = RLM_MODULE_OK;
1356         int ack, nak;
1357         VALUE_PAIR *vp;
1358
1359         /*
1360          *      Get the correct response
1361          */
1362         switch (request->packet->code) {
1363         case PW_COA_REQUEST:
1364                 ack = PW_COA_ACK;
1365                 nak = PW_COA_NAK;
1366                 break;
1367
1368         case PW_DISCONNECT_REQUEST:
1369                 ack = PW_DISCONNECT_ACK;
1370                 nak = PW_DISCONNECT_NAK;
1371                 break;
1372
1373         default:                /* shouldn't happen */
1374                 return RLM_MODULE_FAIL;
1375         }
1376
1377 #ifdef WITH_PROXY
1378 #define WAS_PROXIED (request->proxy)
1379 #else
1380 #define WAS_PROXIED (0)
1381 #endif
1382
1383         if (!WAS_PROXIED) {
1384                 /*
1385                  *      RFC 5176 Section 3.3.  If we have a CoA-Request
1386                  *      with Service-Type = Authorize-Only, it MUST
1387                  *      have a State attribute in it.
1388                  */
1389                 vp = pairfind(request->packet->vps, PW_SERVICE_TYPE, 0);
1390                 if (request->packet->code == PW_COA_REQUEST) {
1391                         if (vp && (vp->vp_integer == 17)) {
1392                                 vp = pairfind(request->packet->vps, PW_STATE, 0);
1393                                 if (!vp || (vp->length == 0)) {
1394                                         RDEBUG("ERROR: CoA-Request with Service-Type = Authorize-Only MUST contain a State attribute");
1395                                         request->reply->code = PW_COA_NAK;
1396                                         return RLM_MODULE_FAIL;
1397                                 }
1398                         }
1399                 } else if (vp) {
1400                         /*
1401                          *      RFC 5176, Section 3.2.
1402                          */
1403                         RDEBUG("ERROR: Disconnect-Request MUST NOT contain a Service-Type attribute");
1404                         request->reply->code = PW_DISCONNECT_NAK;
1405                         return RLM_MODULE_FAIL;
1406                 }
1407
1408                 rcode = module_recv_coa(0, request);
1409                 switch (rcode) {
1410                 case RLM_MODULE_FAIL:
1411                 case RLM_MODULE_INVALID:
1412                 case RLM_MODULE_REJECT:
1413                 case RLM_MODULE_USERLOCK:
1414                 default:
1415                         request->reply->code = nak;
1416                         break;
1417                         
1418                 case RLM_MODULE_HANDLED:
1419                         return rcode;
1420                         
1421                 case RLM_MODULE_NOOP:
1422                 case RLM_MODULE_NOTFOUND:
1423                 case RLM_MODULE_OK:
1424                 case RLM_MODULE_UPDATED:
1425                         request->reply->code = ack;
1426                         break;
1427                 }
1428         } else {
1429                 /*
1430                  *      Start the reply code with the proxy reply
1431                  *      code.
1432                  */
1433                 request->reply->code = request->proxy_reply->code;
1434         }
1435
1436         /*
1437          *      Copy State from the request to the reply.
1438          *      See RFC 5176 Section 3.3.
1439          */
1440         vp = paircopy2(request->packet->vps, PW_STATE, 0);
1441         if (vp) pairadd(&request->reply->vps, vp);
1442
1443         /*
1444          *      We may want to over-ride the reply.
1445          */
1446         rcode = module_send_coa(0, request);
1447         switch (rcode) {
1448                 /*
1449                  *      We need to send CoA-NAK back if Service-Type
1450                  *      is Authorize-Only.  Rely on the user's policy
1451                  *      to do that.  We're not a real NAS, so this
1452                  *      restriction doesn't (ahem) apply to us.
1453                  */
1454                 case RLM_MODULE_FAIL:
1455                 case RLM_MODULE_INVALID:
1456                 case RLM_MODULE_REJECT:
1457                 case RLM_MODULE_USERLOCK:
1458                 default:
1459                         /*
1460                          *      Over-ride an ACK with a NAK
1461                          */
1462                         request->reply->code = nak;
1463                         break;
1464                         
1465                 case RLM_MODULE_HANDLED:
1466                         return rcode;
1467                         
1468                 case RLM_MODULE_NOOP:
1469                 case RLM_MODULE_NOTFOUND:
1470                 case RLM_MODULE_OK:
1471                 case RLM_MODULE_UPDATED:
1472                         /*
1473                          *      Do NOT over-ride a previously set value.
1474                          *      Otherwise an "ok" here will re-write a
1475                          *      NAK to an ACK.
1476                          */
1477                         if (request->reply->code == 0) {
1478                                 request->reply->code = ack;
1479                         }
1480                         break;
1481
1482         }
1483
1484         return RLM_MODULE_OK;
1485 }
1486
1487
1488 /*
1489  *      Check if an incoming request is "ok"
1490  *
1491  *      It takes packets, not requests.  It sees if the packet looks
1492  *      OK.  If so, it does a number of sanity checks on it.
1493   */
1494 static int coa_socket_recv(rad_listen_t *listener,
1495                             RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1496 {
1497         ssize_t         rcode;
1498         int             code, src_port;
1499         RADIUS_PACKET   *packet;
1500         RAD_REQUEST_FUNP fun = NULL;
1501         RADCLIENT       *client;
1502         fr_ipaddr_t     src_ipaddr;
1503
1504         rcode = rad_recv_header(listener->fd, &src_ipaddr, &src_port, &code);
1505         if (rcode < 0) return 0;
1506
1507         RAD_STATS_TYPE_INC(listener, total_requests);
1508
1509         if (rcode < 20) {       /* AUTH_HDR_LEN */
1510                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1511                 return 0;
1512         }
1513
1514         if ((client = client_listener_find(listener,
1515                                            &src_ipaddr, src_port)) == NULL) {
1516                 rad_recv_discard(listener->fd);
1517                 RAD_STATS_TYPE_INC(listener, total_invalid_requests);
1518                 return 0;
1519         }
1520
1521         /*
1522          *      Some sanity checks, based on the packet code.
1523          */
1524         switch(code) {
1525         case PW_COA_REQUEST:
1526         case PW_DISCONNECT_REQUEST:
1527                 fun = rad_coa_recv;
1528                 break;
1529
1530         default:
1531                 rad_recv_discard(listener->fd);
1532                 DEBUG("Invalid packet code %d sent to coa port from client %s port %d : IGNORED",
1533                       code, client->shortname, src_port);
1534                 return 0;
1535                 break;
1536         } /* switch over packet types */
1537
1538         /*
1539          *      Now that we've sanity checked everything, receive the
1540          *      packet.
1541          */
1542         packet = rad_recv(listener->fd, client->message_authenticator);
1543         if (!packet) {
1544                 RAD_STATS_TYPE_INC(listener, total_malformed_requests);
1545                 DEBUG("%s", fr_strerror());
1546                 return 0;
1547         }
1548
1549         if (!received_request(listener, packet, prequest, client)) {
1550                 rad_free(&packet);
1551                 return 0;
1552         }
1553
1554         *pfun = fun;
1555         return 1;
1556 }
1557 #endif
1558
1559 #ifdef WITH_PROXY
1560 /*
1561  *      Recieve packets from a proxy socket.
1562  */
1563 static int proxy_socket_recv(rad_listen_t *listener,
1564                               RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1565 {
1566         REQUEST         *request;
1567         RADIUS_PACKET   *packet;
1568         RAD_REQUEST_FUNP fun = NULL;
1569         char            buffer[128];
1570
1571         packet = rad_recv(listener->fd, 0);
1572         if (!packet) {
1573                 radlog(L_ERR, "%s", fr_strerror());
1574                 return 0;
1575         }
1576
1577         /*
1578          *      FIXME: Client MIB updates?
1579          */
1580         switch(packet->code) {
1581         case PW_AUTHENTICATION_ACK:
1582         case PW_ACCESS_CHALLENGE:
1583         case PW_AUTHENTICATION_REJECT:
1584                 fun = rad_authenticate;
1585                 break;
1586
1587 #ifdef WITH_ACCOUNTING
1588         case PW_ACCOUNTING_RESPONSE:
1589                 fun = rad_accounting;
1590                 break;
1591 #endif
1592
1593 #ifdef WITH_COA
1594         case PW_DISCONNECT_ACK:
1595         case PW_DISCONNECT_NAK:
1596         case PW_COA_ACK:
1597         case PW_COA_NAK:
1598                 fun = rad_coa_reply;
1599                 break;
1600 #endif
1601
1602         default:
1603                 /*
1604                  *      FIXME: Update MIB for packet types?
1605                  */
1606                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
1607                        "from home server %s port %d - ID %d : IGNORED",
1608                        packet->code,
1609                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
1610                        packet->src_port, packet->id);
1611                 rad_free(&packet);
1612                 return 0;
1613         }
1614
1615         request = received_proxy_response(packet);
1616         if (!request) {
1617                 rad_free(&packet);
1618                 return 0;
1619         }
1620
1621 #ifdef WITH_COA
1622         /*
1623          *      Distinguish proxied CoA requests from ones we
1624          *      originate.
1625          */
1626         if ((fun == rad_coa_reply) &&
1627             (request->packet->code == request->proxy->code)) {
1628                 fun = rad_coa_recv;
1629         }
1630 #endif
1631
1632         rad_assert(fun != NULL);
1633         *pfun = fun;
1634         *prequest = request;
1635
1636         return 1;
1637 }
1638
1639 #ifdef WITH_TCP
1640 /*
1641  *      Recieve packets from a proxy socket.
1642  */
1643 static int proxy_socket_tcp_recv(rad_listen_t *listener,
1644                                  RAD_REQUEST_FUNP *pfun, REQUEST **prequest)
1645 {
1646         REQUEST         *request;
1647         RADIUS_PACKET   *packet;
1648         RAD_REQUEST_FUNP fun = NULL;
1649         listen_socket_t *sock = listener->data;
1650         char            buffer[128];
1651
1652         packet = fr_tcp_recv(listener->fd, 0);
1653         if (!packet) {
1654                 listener->status = RAD_LISTEN_STATUS_REMOVE_FD;
1655                 event_new_fd(listener);
1656                 return 0;
1657         }
1658
1659         /*
1660          *      FIXME: Client MIB updates?
1661          */
1662         switch(packet->code) {
1663         case PW_AUTHENTICATION_ACK:
1664         case PW_ACCESS_CHALLENGE:
1665         case PW_AUTHENTICATION_REJECT:
1666                 fun = rad_authenticate;
1667                 break;
1668
1669 #ifdef WITH_ACCOUNTING
1670         case PW_ACCOUNTING_RESPONSE:
1671                 fun = rad_accounting;
1672                 break;
1673 #endif
1674
1675         default:
1676                 /*
1677                  *      FIXME: Update MIB for packet types?
1678                  */
1679                 radlog(L_ERR, "Invalid packet code %d sent to a proxy port "
1680                        "from home server %s port %d - ID %d : IGNORED",
1681                        packet->code,
1682                        ip_ntoh(&packet->src_ipaddr, buffer, sizeof(buffer)),
1683                        packet->src_port, packet->id);
1684                 rad_free(&packet);
1685                 return 0;
1686         }
1687
1688         packet->src_ipaddr = sock->other_ipaddr;
1689         packet->src_port = sock->other_port;
1690         packet->dst_ipaddr = sock->my_ipaddr;
1691         packet->dst_port = sock->my_port;
1692
1693         /*
1694          *      FIXME: Have it return an indication of packets that
1695          *      are OK to ignore (dups, too late), versus ones that
1696          *      aren't OK to ignore (unknown response, spoofed, etc.)
1697          *
1698          *      Close the socket on bad packets...
1699          */
1700         request = received_proxy_response(packet);
1701         if (!request) {
1702                 return 0;
1703         }
1704
1705         rad_assert(fun != NULL);
1706         sock->opened = sock->last_packet = request->timestamp;
1707
1708         *pfun = fun;
1709         *prequest = request;
1710
1711         return 1;
1712 }
1713 #endif
1714 #endif
1715
1716
1717 static int client_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1718 {
1719         if (!request->reply->code) return 0;
1720
1721         rad_encode(request->reply, request->packet,
1722                    request->client->secret);
1723         rad_sign(request->reply, request->packet,
1724                  request->client->secret);
1725
1726         return 0;
1727 }
1728
1729
1730 static int client_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1731 {
1732         if (rad_verify(request->packet, NULL,
1733                        request->client->secret) < 0) {
1734                 return -1;
1735         }
1736
1737         return rad_decode(request->packet, NULL,
1738                           request->client->secret);
1739 }
1740
1741 #ifdef WITH_PROXY
1742 static int proxy_socket_encode(UNUSED rad_listen_t *listener, REQUEST *request)
1743 {
1744         rad_encode(request->proxy, NULL, request->home_server->secret);
1745         rad_sign(request->proxy, NULL, request->home_server->secret);
1746
1747         return 0;
1748 }
1749
1750
1751 static int proxy_socket_decode(UNUSED rad_listen_t *listener, REQUEST *request)
1752 {
1753         /*
1754          *      rad_verify is run in event.c, received_proxy_response()
1755          */
1756
1757         return rad_decode(request->proxy_reply, request->proxy,
1758                            request->home_server->secret);
1759 }
1760 #endif
1761
1762 #include "dhcpd.c"
1763
1764 #include "command.c"
1765
1766 static const rad_listen_master_t master_listen[RAD_LISTEN_MAX] = {
1767 #ifdef WITH_STATS
1768         { common_socket_parse, NULL,
1769           stats_socket_recv, auth_socket_send,
1770           socket_print, client_socket_encode, client_socket_decode },
1771 #else
1772         /*
1773          *      This always gets defined.
1774          */
1775         { NULL, NULL, NULL, NULL, NULL, NULL, NULL},    /* RAD_LISTEN_NONE */
1776 #endif
1777
1778 #ifdef WITH_PROXY
1779         /* proxying */
1780         { common_socket_parse, NULL,
1781           proxy_socket_recv, proxy_socket_send,
1782           socket_print, proxy_socket_encode, proxy_socket_decode },
1783 #endif
1784
1785         /* authentication */
1786         { common_socket_parse, NULL,
1787           auth_socket_recv, auth_socket_send,
1788           socket_print, client_socket_encode, client_socket_decode },
1789
1790 #ifdef WITH_ACCOUNTING
1791         /* accounting */
1792         { common_socket_parse, NULL,
1793           acct_socket_recv, acct_socket_send,
1794           socket_print, client_socket_encode, client_socket_decode},
1795 #endif
1796
1797 #ifdef WITH_DETAIL
1798         /* detail */
1799         { detail_parse, detail_free,
1800           detail_recv, detail_send,
1801           detail_print, detail_encode, detail_decode },
1802 #endif
1803
1804 #ifdef WITH_VMPS
1805         /* vlan query protocol */
1806         { common_socket_parse, NULL,
1807           vqp_socket_recv, vqp_socket_send,
1808           socket_print, vqp_socket_encode, vqp_socket_decode },
1809 #endif
1810
1811 #ifdef WITH_DHCP
1812         /* dhcp query protocol */
1813         { dhcp_socket_parse, NULL,
1814           dhcp_socket_recv, dhcp_socket_send,
1815           socket_print, dhcp_socket_encode, dhcp_socket_decode },
1816 #endif
1817
1818 #ifdef WITH_COMMAND_SOCKET
1819         /* TCP command socket */
1820         { command_socket_parse, NULL,
1821           command_domain_accept, command_domain_send,
1822           command_socket_print, command_socket_encode, command_socket_decode },
1823 #endif
1824
1825 #ifdef WITH_COA
1826         /* Change of Authorization */
1827         { common_socket_parse, NULL,
1828           coa_socket_recv, auth_socket_send, /* CoA packets are same as auth */
1829           socket_print, client_socket_encode, client_socket_decode },
1830 #endif
1831
1832 };
1833
1834
1835
1836 /*
1837  *      Binds a listener to a socket.
1838  */
1839 static int listen_bind(rad_listen_t *this)
1840 {
1841         int rcode;
1842         struct sockaddr_storage salocal;
1843         socklen_t       salen;
1844         listen_socket_t *sock = this->data;
1845 #ifndef WITH_TCP
1846 #define proto_for_port "udp"
1847 #define sock_type SOCK_DGRAM
1848 #else
1849         const char *proto_for_port = "udp";
1850         int sock_type = SOCK_DGRAM;
1851         
1852         if (sock->proto == IPPROTO_TCP) {
1853 #ifdef WITH_VMPS
1854                 if (this->type == RAD_LISTEN_VQP) {
1855                         radlog(L_ERR, "VQP does not support TCP transport");
1856                         return -1;
1857                 }
1858 #endif
1859
1860                 proto_for_port = "tcp";
1861                 sock_type = SOCK_STREAM;        
1862         }
1863 #endif
1864
1865         /*
1866          *      If the port is zero, then it means the appropriate
1867          *      thing from /etc/services.
1868          */
1869         if (sock->my_port == 0) {
1870                 struct servent  *svp;
1871
1872                 switch (this->type) {
1873                 case RAD_LISTEN_AUTH:
1874                         svp = getservbyname ("radius", proto_for_port);
1875                         if (svp != NULL) {
1876                                 sock->my_port = ntohs(svp->s_port);
1877                         } else {
1878                                 sock->my_port = PW_AUTH_UDP_PORT;
1879                         }
1880                         break;
1881
1882 #ifdef WITH_ACCOUNTING
1883                 case RAD_LISTEN_ACCT:
1884                         svp = getservbyname ("radacct", proto_for_port);
1885                         if (svp != NULL) {
1886                                 sock->my_port = ntohs(svp->s_port);
1887                         } else {
1888                                 sock->my_port = PW_ACCT_UDP_PORT;
1889                         }
1890                         break;
1891 #endif
1892
1893 #ifdef WITH_PROXY
1894                 case RAD_LISTEN_PROXY:
1895                         /* leave it at zero */
1896                         break;
1897 #endif
1898
1899 #ifdef WITH_VMPS
1900                 case RAD_LISTEN_VQP:
1901                         sock->my_port = 1589;
1902                         break;
1903 #endif
1904
1905 #ifdef WITH_COA
1906                 case RAD_LISTEN_COA:
1907                         svp = getservbyname ("radius-dynauth", "udp");
1908                         if (svp != NULL) {
1909                                 sock->my_port = ntohs(svp->s_port);
1910                         } else {
1911                                 sock->my_port = PW_COA_UDP_PORT;
1912                         }
1913                         break;
1914 #endif
1915
1916                 default:
1917                         radlog(L_ERR, "ERROR: Non-fatal internal sanity check failed in bind.");
1918                         return -1;
1919                 }
1920         }
1921
1922         /*
1923          *      Copy fr_socket() here, as we may need to bind to a device.
1924          */
1925         this->fd = socket(sock->my_ipaddr.af, sock_type, 0);
1926         if (this->fd < 0) {
1927                 radlog(L_ERR, "Failed opening socket: %s", strerror(errno));
1928                 return -1;
1929         }
1930                 
1931         /*
1932          *      Bind to a device BEFORE touching IP addresses.
1933          */
1934         if (sock->interface) {
1935 #ifdef SO_BINDTODEVICE
1936                 struct ifreq ifreq;
1937                 strcpy(ifreq.ifr_name, sock->interface);
1938
1939                 fr_suid_up();
1940                 rcode = setsockopt(this->fd, SOL_SOCKET, SO_BINDTODEVICE,
1941                                    (char *)&ifreq, sizeof(ifreq));
1942                 fr_suid_down();
1943                 if (rcode < 0) {
1944                         close(this->fd);
1945                         radlog(L_ERR, "Failed binding to interface %s: %s",
1946                                sock->interface, strerror(errno));
1947                         return -1;
1948                 } /* else it worked. */
1949 #else
1950 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1951 #ifdef HAVE_NET_IF_H
1952                 /*
1953                  *      Odds are that any system supporting "bind to
1954                  *      device" also supports IPv6, so this next bit
1955                  *      isn't necessary.  But it's here for
1956                  *      completeness.
1957                  *
1958                  *      If we're doing IPv6, and the scope hasn't yet
1959                  *      been defined, set the scope to the scope of
1960                  *      the interface.
1961                  */
1962                 if (sock->my_ipaddr.af == AF_INET6) {
1963                         if (sock->my_ipaddr.scope == 0) {
1964                                 sock->my_ipaddr.scope = if_nametoindex(sock->interface);
1965                                 if (sock->my_ipaddr.scope == 0) {
1966                                         close(this->fd);
1967                                         radlog(L_ERR, "Failed finding interface %s: %s",
1968                                                sock->interface, strerror(errno));
1969                                         return -1;
1970                                 }
1971                         } /* else scope was defined: we're OK. */
1972                 } else
1973 #endif
1974 #endif
1975                                 /*
1976                                  *      IPv4: no link local addresses,
1977                                  *      and no bind to device.
1978                                  */
1979                 {
1980                         close(this->fd);
1981                         radlog(L_ERR, "Failed binding to interface %s: \"bind to device\" is unsupported", sock->interface);
1982                         return -1;
1983                 }
1984 #endif
1985         }
1986
1987 #ifdef WITH_TCP
1988         if (sock->proto == IPPROTO_TCP) {
1989                 int on = 1;
1990
1991                 if (setsockopt(this->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
1992                         close(this->fd);
1993                         radlog(L_ERR, "Failed to reuse address: %s", strerror(errno));
1994                         return -1;
1995                 }
1996         }
1997 #endif
1998
1999 #if defined(WITH_TCP) && defined(WITH_UDPFROMTO)
2000         else                    /* UDP sockets get UDPfromto */
2001 #endif
2002
2003 #ifdef WITH_UDPFROMTO
2004         /*
2005          *      Initialize udpfromto for all sockets.
2006          */
2007         if (udpfromto_init(this->fd) != 0) {
2008                 close(this->fd);
2009                 return -1;
2010         }
2011 #endif
2012
2013         /*
2014          *      Set up sockaddr stuff.
2015          */
2016         if (!fr_ipaddr2sockaddr(&sock->my_ipaddr, sock->my_port, &salocal, &salen)) {
2017                 close(this->fd);
2018                 return -1;
2019         }
2020                 
2021 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2022         if (sock->my_ipaddr.af == AF_INET6) {
2023                 /*
2024                  *      Listening on '::' does NOT get you IPv4 to
2025                  *      IPv6 mapping.  You've got to listen on an IPv4
2026                  *      address, too.  This makes the rest of the server
2027                  *      design a little simpler.
2028                  */
2029 #ifdef IPV6_V6ONLY
2030                 
2031                 if (IN6_IS_ADDR_UNSPECIFIED(&sock->my_ipaddr.ipaddr.ip6addr)) {
2032                         int on = 1;
2033                         
2034                         setsockopt(this->fd, IPPROTO_IPV6, IPV6_V6ONLY,
2035                                    (char *)&on, sizeof(on));
2036                 }
2037 #endif /* IPV6_V6ONLY */
2038         }
2039 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
2040
2041         if (sock->my_ipaddr.af == AF_INET) {
2042                 UNUSED int flag;
2043                 
2044 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
2045                 /*
2046                  *      Disable PMTU discovery.  On Linux, this
2047                  *      also makes sure that the "don't fragment"
2048                  *      flag is zero.
2049                  */
2050                 flag = IP_PMTUDISC_DONT;
2051                 setsockopt(this->fd, IPPROTO_IP, IP_MTU_DISCOVER,
2052                            &flag, sizeof(flag));
2053 #endif
2054
2055 #if defined(IP_DONTFRAG)
2056                 /*
2057                  *      Ensure that the "don't fragment" flag is zero.
2058                  */
2059                 flag = 0;
2060                 setsockopt(this->fd, IPPROTO_IP, IP_DONTFRAG,
2061                            &flag, sizeof(flag));
2062 #endif
2063         }
2064
2065 #ifdef WITH_DHCP
2066 #ifdef SO_BROADCAST
2067         if (sock->broadcast) {
2068                 int on = 1;
2069                 
2070                 if (setsockopt(this->fd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
2071                         radlog(L_ERR, "Can't set broadcast option: %s\n",
2072                                strerror(errno));
2073                         return -1;
2074                 }
2075         }
2076 #endif
2077 #endif
2078
2079         /*
2080          *      May be binding to priviledged ports.
2081          */
2082         if (sock->my_port != 0) {
2083 #ifdef SO_REUSEADDR
2084                 int on = 1;
2085
2086                 if (setsockopt(this->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
2087                         radlog(L_ERR, "Can't set re-use address option: %s\n",
2088                                strerror(errno));
2089                         return -1;
2090                 }
2091 #endif
2092
2093                 fr_suid_up();
2094                 rcode = bind(this->fd, (struct sockaddr *) &salocal, salen);
2095                 fr_suid_down();
2096                 if (rcode < 0) {
2097                         char buffer[256];
2098                         close(this->fd);
2099                         
2100                         this->print(this, buffer, sizeof(buffer));
2101                         radlog(L_ERR, "Failed binding to %s: %s\n",
2102                                buffer, strerror(errno));
2103                         return -1;
2104                 }
2105         
2106                 /*
2107                  *      FreeBSD jail issues.  We bind to 0.0.0.0, but the
2108                  *      kernel instead binds us to a 1.2.3.4.  If this
2109                  *      happens, notice, and remember our real IP.
2110                  */
2111                 {
2112                         struct sockaddr_storage src;
2113                         socklen_t               sizeof_src = sizeof(src);
2114                         
2115                         memset(&src, 0, sizeof_src);
2116                         if (getsockname(this->fd, (struct sockaddr *) &src,
2117                                         &sizeof_src) < 0) {
2118                                 radlog(L_ERR, "Failed getting socket name: %s",
2119                                        strerror(errno));
2120                                 return -1;
2121                         }
2122                         
2123                         if (!fr_sockaddr2ipaddr(&src, sizeof_src,
2124                                                 &sock->my_ipaddr, &sock->my_port)) {
2125                                 radlog(L_ERR, "Socket has unsupported address family");
2126                                 return -1;
2127                         }
2128                 }
2129         }
2130
2131 #ifdef WITH_TCP
2132         if (sock->proto == IPPROTO_TCP) {
2133                 if (listen(this->fd, 8) < 0) {
2134                         close(this->fd);
2135                         radlog(L_ERR, "Failed in listen(): %s", strerror(errno));
2136                         return -1;
2137                 }
2138         } else
2139 #endif
2140
2141           if (fr_nonblock(this->fd) < 0) {
2142                   close(this->fd);
2143                   radlog(L_ERR, "Failed setting non-blocking on socket: %s",
2144                          strerror(errno));
2145                   return -1;
2146           }
2147
2148         /*
2149          *      Mostly for proxy sockets.
2150          */
2151         sock->other_ipaddr.af = sock->my_ipaddr.af;
2152
2153 /*
2154  *      Don't screw up other people.
2155  */
2156 #undef proto_for_port
2157 #undef sock_type
2158
2159         return 0;
2160 }
2161
2162
2163 /*
2164  *      Allocate & initialize a new listener.
2165  */
2166 static rad_listen_t *listen_alloc(RAD_LISTEN_TYPE type)
2167 {
2168         rad_listen_t *this;
2169
2170         this = rad_malloc(sizeof(*this));
2171         memset(this, 0, sizeof(*this));
2172
2173         this->type = type;
2174         this->recv = master_listen[this->type].recv;
2175         this->send = master_listen[this->type].send;
2176         this->print = master_listen[this->type].print;
2177         this->encode = master_listen[this->type].encode;
2178         this->decode = master_listen[this->type].decode;
2179
2180         switch (type) {
2181 #ifdef WITH_STATS
2182         case RAD_LISTEN_NONE:
2183 #endif
2184         case RAD_LISTEN_AUTH:
2185 #ifdef WITH_ACCOUNTING
2186         case RAD_LISTEN_ACCT:
2187 #endif
2188 #ifdef WITH_PROXY
2189         case RAD_LISTEN_PROXY:
2190 #endif
2191 #ifdef WITH_VMPS
2192         case RAD_LISTEN_VQP:
2193 #endif
2194 #ifdef WITH_COA
2195         case RAD_LISTEN_COA:
2196 #endif
2197                 this->data = rad_malloc(sizeof(listen_socket_t));
2198                 memset(this->data, 0, sizeof(listen_socket_t));
2199                 break;
2200
2201 #ifdef WITH_DHCP
2202         case RAD_LISTEN_DHCP:
2203                 this->data = rad_malloc(sizeof(dhcp_socket_t));
2204                 memset(this->data, 0, sizeof(dhcp_socket_t));
2205                 break;
2206 #endif
2207
2208 #ifdef WITH_DETAIL
2209         case RAD_LISTEN_DETAIL:
2210                 this->data = NULL;
2211                 break;
2212 #endif
2213
2214 #ifdef WITH_COMMAND_SOCKET
2215         case RAD_LISTEN_COMMAND:
2216                 this->data = rad_malloc(sizeof(fr_command_socket_t));
2217                 memset(this->data, 0, sizeof(fr_command_socket_t));
2218                 break;
2219 #endif
2220
2221         default:
2222                 rad_assert("Unsupported option!" == NULL);
2223                 break;
2224         }
2225
2226         return this;
2227 }
2228
2229 #ifdef WITH_PROXY
2230 /*
2231  *      Externally visible function for creating a new proxy LISTENER.
2232  *
2233  *      Not thread-safe, but all calls to it are protected by the
2234  *      proxy mutex in event.c
2235  */
2236 int proxy_new_listener(home_server *home, int src_port)
2237 {
2238         rad_listen_t *this;
2239         listen_socket_t *sock;
2240
2241         if (!home) return 0;
2242
2243         if ((home->max_connections > 0) &&
2244             (home->num_connections >= home->max_connections)) {
2245                 DEBUG("WARNING: Home server has too many open connections (%d)",
2246                       home->max_connections);
2247                 return 0;
2248         }
2249
2250         this = listen_alloc(RAD_LISTEN_PROXY);
2251
2252         sock = this->data;
2253         sock->other_ipaddr = home->ipaddr;
2254         sock->other_port = home->port;
2255         sock->home = home;
2256
2257         sock->my_ipaddr = home->src_ipaddr;
2258         sock->my_port = src_port;
2259         sock->proto = home->proto;
2260
2261 #ifdef WITH_TCP
2262         sock->last_packet = time(NULL);
2263
2264         if (home->proto == IPPROTO_TCP) {
2265                 this->recv = proxy_socket_tcp_recv;
2266
2267                 /*
2268                  *      FIXME: connect() is blocking!
2269                  *      We do this with the proxy mutex locked, which may
2270                  *      cause large delays!
2271                  *
2272                  *      http://www.developerweb.net/forum/showthread.php?p=13486
2273                  */
2274                 this->fd = fr_tcp_client_socket(&home->src_ipaddr,
2275                                                 &home->ipaddr, home->port);
2276         } else
2277 #endif
2278                 this->fd = fr_socket(&home->src_ipaddr, src_port);
2279
2280         if (this->fd < 0) {
2281                 DEBUG("Failed opening client socket: %s", fr_strerror());
2282                 listen_free(&this);
2283                 return 0;
2284         }
2285
2286         /*
2287          *      Figure out which port we were bound to.
2288          */
2289         if (sock->my_port == 0) {
2290                 struct sockaddr_storage src;
2291                 socklen_t               sizeof_src = sizeof(src);
2292                 
2293                 memset(&src, 0, sizeof_src);
2294                 if (getsockname(this->fd, (struct sockaddr *) &src,
2295                                 &sizeof_src) < 0) {
2296                         radlog(L_ERR, "Failed getting socket name: %s",
2297                                strerror(errno));
2298                         listen_free(&this);
2299                         return 0;
2300                 }
2301                 
2302                 if (!fr_sockaddr2ipaddr(&src, sizeof_src,
2303                                         &sock->my_ipaddr, &sock->my_port)) {
2304                         radlog(L_ERR, "Socket has unsupported address family");
2305                         listen_free(&this);
2306                         return 0;
2307                 }
2308         }
2309
2310         /*
2311          *      Tell the event loop that we have a new FD
2312          */
2313         if (!event_new_fd(this)) {
2314                 listen_free(&this);
2315                 return 0;
2316         }
2317         
2318         return 1;
2319 }
2320 #endif
2321
2322
2323 static const FR_NAME_NUMBER listen_compare[] = {
2324 #ifdef WITH_STATS
2325         { "status",     RAD_LISTEN_NONE },
2326 #endif
2327         { "auth",       RAD_LISTEN_AUTH },
2328 #ifdef WITH_ACCOUNTING
2329         { "acct",       RAD_LISTEN_ACCT },
2330 #endif
2331 #ifdef WITH_DETAIL
2332         { "detail",     RAD_LISTEN_DETAIL },
2333 #endif
2334 #ifdef WITH_PROXY
2335         { "proxy",      RAD_LISTEN_PROXY },
2336 #endif
2337 #ifdef WITH_VMPS
2338         { "vmps",       RAD_LISTEN_VQP },
2339 #endif
2340 #ifdef WITH_DHCP
2341         { "dhcp",       RAD_LISTEN_DHCP },
2342 #endif
2343 #ifdef WITH_COMMAND_SOCKET
2344         { "control",    RAD_LISTEN_COMMAND },
2345 #endif
2346 #ifdef WITH_COA
2347         { "coa",        RAD_LISTEN_COA },
2348 #endif
2349         { NULL, 0 },
2350 };
2351
2352
2353 static rad_listen_t *listen_parse(CONF_SECTION *cs, const char *server)
2354 {
2355         int             type, rcode;
2356         char            *listen_type;
2357         rad_listen_t    *this;
2358
2359         listen_type = NULL;
2360         
2361         cf_log_info(cs, "listen {");
2362
2363         rcode = cf_item_parse(cs, "type", PW_TYPE_STRING_PTR,
2364                               &listen_type, "");
2365         if (rcode < 0) return NULL;
2366         if (rcode == 1) {
2367                 free(listen_type);
2368                 cf_log_err(cf_sectiontoitem(cs),
2369                            "No type specified in listen section");
2370                 return NULL;
2371         }
2372
2373         type = fr_str2int(listen_compare, listen_type, -1);
2374         if (type < 0) {
2375                 cf_log_err(cf_sectiontoitem(cs),
2376                            "Invalid type \"%s\" in listen section.",
2377                            listen_type);
2378                 free(listen_type);
2379                 return NULL;
2380         }
2381         free(listen_type);
2382
2383         /*
2384          *      Allow listen sections in the default config to
2385          *      refer to a server.
2386          */
2387         if (!server) {
2388                 rcode = cf_item_parse(cs, "virtual_server", PW_TYPE_STRING_PTR,
2389                                       &server, NULL);
2390                 if (rcode == 1) { /* compatiblity with 2.0-pre */
2391                         rcode = cf_item_parse(cs, "server", PW_TYPE_STRING_PTR,
2392                                               &server, NULL);
2393                 }
2394                 if (rcode < 0) return NULL;
2395         }
2396
2397 #ifdef WITH_PROXY
2398         /*
2399          *      We were passed a virtual server, so the caller is
2400          *      defining a proxy listener inside of a virtual server.
2401          *      This isn't allowed right now.
2402          */
2403         else if (type == RAD_LISTEN_PROXY) {
2404                 radlog(L_ERR, "Error: listen type \"proxy\" Cannot appear in a virtual server section");
2405                 return NULL;
2406         }
2407 #endif
2408
2409         /*
2410          *      Set up cross-type data.
2411          */
2412         this = listen_alloc(type);
2413         this->server = server;
2414         this->fd = -1;
2415
2416         /*
2417          *      Call per-type parser.
2418          */
2419         if (master_listen[type].parse(cs, this) < 0) {
2420                 listen_free(&this);
2421                 return NULL;
2422         }
2423
2424         cf_log_info(cs, "}");
2425
2426         return this;
2427 }
2428
2429 /*
2430  *      Generate a list of listeners.  Takes an input list of
2431  *      listeners, too, so we don't close sockets with waiting packets.
2432  */
2433 int listen_init(CONF_SECTION *config, rad_listen_t **head)
2434 {
2435         int             override = FALSE;
2436         int             rcode;
2437         CONF_SECTION    *cs = NULL;
2438         rad_listen_t    **last;
2439         rad_listen_t    *this;
2440         fr_ipaddr_t     server_ipaddr;
2441         int             auth_port = 0;
2442 #ifdef WITH_PROXY
2443         int             defined_proxy = 0;
2444 #endif
2445
2446         /*
2447          *      We shouldn't be called with a pre-existing list.
2448          */
2449         rad_assert(head && (*head == NULL));
2450
2451         last = head;
2452         server_ipaddr.af = AF_UNSPEC;
2453
2454         /*
2455          *      If the port is specified on the command-line,
2456          *      it over-rides the configuration file.
2457          *
2458          *      FIXME: If argv[0] == "vmpsd", then don't listen on auth/acct!
2459          */
2460         if (mainconfig.port >= 0) auth_port = mainconfig.port;
2461
2462         /*
2463          *      If the IP address was configured on the command-line,
2464          *      use that as the "bind_address"
2465          */
2466         if (mainconfig.myip.af != AF_UNSPEC) {
2467                 memcpy(&server_ipaddr, &mainconfig.myip,
2468                        sizeof(server_ipaddr));
2469                 override = TRUE;
2470                 goto bind_it;
2471         }
2472
2473         /*
2474          *      Else look for bind_address and/or listen sections.
2475          */
2476         server_ipaddr.ipaddr.ip4addr.s_addr = htonl(INADDR_NONE);
2477         rcode = cf_item_parse(config, "bind_address",
2478                               PW_TYPE_IPADDR,
2479                               &server_ipaddr.ipaddr.ip4addr, NULL);
2480         if (rcode < 0) return -1; /* error parsing it */
2481
2482         if (rcode == 0) { /* successfully parsed IPv4 */
2483                 listen_socket_t *sock;
2484                 server_ipaddr.af = AF_INET;
2485
2486                 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'.");
2487
2488         bind_it:
2489 #ifdef WITH_VMPS
2490                 if (strcmp(progname, "vmpsd") == 0) {
2491                         this = listen_alloc(RAD_LISTEN_VQP);
2492                         if (!auth_port) auth_port = 1589;
2493                 } else
2494 #endif
2495                         this = listen_alloc(RAD_LISTEN_AUTH);
2496
2497                 sock = this->data;
2498
2499                 sock->my_ipaddr = server_ipaddr;
2500                 sock->my_port = auth_port;
2501
2502                 sock->clients = clients_parse_section(config);
2503                 if (!sock->clients) {
2504                         cf_log_err(cf_sectiontoitem(config),
2505                                    "Failed to find any clients for this listen section");
2506                         listen_free(&this);
2507                         return -1;
2508                 }
2509
2510                 if (listen_bind(this) < 0) {
2511                         listen_free(head);
2512                         radlog(L_ERR, "There appears to be another RADIUS server running on the authentication port %d", sock->my_port);
2513                         listen_free(&this);
2514                         return -1;
2515                 }
2516                 auth_port = sock->my_port;      /* may have been updated in listen_bind */
2517                 if (override) {
2518                         cs = cf_section_sub_find_name2(config, "server",
2519                                                        mainconfig.name);
2520                         if (cs) this->server = mainconfig.name;
2521                 }
2522
2523                 *last = this;
2524                 last = &(this->next);
2525
2526 #ifdef WITH_VMPS
2527                 /*
2528                  *      No acct for vmpsd
2529                  */
2530                 if (strcmp(progname, "vmpsd") == 0) goto add_sockets;
2531 #endif
2532
2533 #ifdef WITH_ACCOUNTING
2534                 /*
2535                  *      Open Accounting Socket.
2536                  *
2537                  *      If we haven't already gotten acct_port from
2538                  *      /etc/services, then make it auth_port + 1.
2539                  */
2540                 this = listen_alloc(RAD_LISTEN_ACCT);
2541                 sock = this->data;
2542
2543                 /*
2544                  *      Create the accounting socket.
2545                  *
2546                  *      The accounting port is always the
2547                  *      authentication port + 1
2548                  */
2549                 sock->my_ipaddr = server_ipaddr;
2550                 sock->my_port = auth_port + 1;
2551
2552                 sock->clients = clients_parse_section(config);
2553                 if (!sock->clients) {
2554                         cf_log_err(cf_sectiontoitem(config),
2555                                    "Failed to find any clients for this listen section");
2556                         return -1;
2557                 }
2558
2559                 if (listen_bind(this) < 0) {
2560                         listen_free(&this);
2561                         listen_free(head);
2562                         radlog(L_ERR, "There appears to be another RADIUS server running on the accounting port %d", sock->my_port);
2563                         return -1;
2564                 }
2565
2566                 if (override) {
2567                         cs = cf_section_sub_find_name2(config, "server",
2568                                                        mainconfig.name);
2569                         if (cs) this->server = mainconfig.name;
2570                 }
2571
2572                 *last = this;
2573                 last = &(this->next);
2574 #endif
2575         } else if (mainconfig.port > 0) { /* no bind address, but a port */
2576                 radlog(L_ERR, "The command-line says \"-p %d\", but there is no associated IP address to use",
2577                        mainconfig.port);
2578                 return -1;
2579         }
2580
2581         /*
2582          *      They specified an IP on the command-line, ignore
2583          *      all listen sections except the one in '-n'.
2584          */
2585         if (mainconfig.myip.af != AF_UNSPEC) {
2586                 CONF_SECTION *subcs;
2587                 const char *name2 = cf_section_name2(cs);
2588
2589                 cs = cf_section_sub_find_name2(config, "server",
2590                                                mainconfig.name);
2591                 if (!cs) goto add_sockets;
2592
2593                 /*
2594                  *      Should really abstract this code...
2595                  */
2596                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
2597                      subcs != NULL;
2598                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
2599                         this = listen_parse(subcs, name2);
2600                         if (!this) {
2601                                 listen_free(head);
2602                                 return -1;
2603                         }
2604
2605                         *last = this;
2606                         last = &(this->next);
2607                 } /* loop over "listen" directives in server <foo> */
2608
2609                 goto add_sockets;
2610         }
2611
2612         /*
2613          *      Walk through the "listen" sections, if they exist.
2614          */
2615         for (cs = cf_subsection_find_next(config, NULL, "listen");
2616              cs != NULL;
2617              cs = cf_subsection_find_next(config, cs, "listen")) {
2618                 this = listen_parse(cs, NULL);
2619                 if (!this) {
2620                         listen_free(head);
2621                         return -1;
2622                 }
2623
2624                 *last = this;
2625                 last = &(this->next);
2626         }
2627
2628         /*
2629          *      Check virtual servers for "listen" sections, too.
2630          *
2631          *      FIXME: Move to virtual server init?
2632          */
2633         for (cs = cf_subsection_find_next(config, NULL, "server");
2634              cs != NULL;
2635              cs = cf_subsection_find_next(config, cs, "server")) {
2636                 CONF_SECTION *subcs;
2637                 const char *name2 = cf_section_name2(cs);
2638                 
2639                 for (subcs = cf_subsection_find_next(cs, NULL, "listen");
2640                      subcs != NULL;
2641                      subcs = cf_subsection_find_next(cs, subcs, "listen")) {
2642                         this = listen_parse(subcs, name2);
2643                         if (!this) {
2644                                 listen_free(head);
2645                                 return -1;
2646                         }
2647                         
2648                         *last = this;
2649                         last = &(this->next);
2650                 } /* loop over "listen" directives in virtual servers */
2651         } /* loop over virtual servers */
2652
2653 add_sockets:
2654         /*
2655          *      Print out which sockets we're listening on, and
2656          *      add them to the event list.
2657          */
2658         for (this = *head; this != NULL; this = this->next) {
2659 #ifdef WITH_PROXY
2660                 if (this->type == RAD_LISTEN_PROXY) {
2661                         defined_proxy = 1;
2662                 }
2663
2664 #endif
2665                 event_new_fd(this);
2666         }
2667
2668         /*
2669          *      If we're proxying requests, open the proxy FD.
2670          *      Otherwise, don't do anything.
2671          */
2672 #ifdef WITH_PROXY
2673         if ((mainconfig.proxy_requests == TRUE) &&
2674             (*head != NULL) && !defined_proxy) {
2675                 listen_socket_t *sock = NULL;
2676                 int             port = 0;
2677                 home_server     home;
2678
2679                 memset(&home, 0, sizeof(home));
2680
2681                 /*
2682                  *      
2683                  */
2684                 home.proto = IPPROTO_UDP;
2685                 home.src_ipaddr = server_ipaddr;
2686
2687                 /*
2688                  *      Find the first authentication port,
2689                  *      and use it
2690                  */
2691                 for (this = *head; this != NULL; this = this->next) {
2692                         if (this->type == RAD_LISTEN_AUTH) {
2693                                 sock = this->data;
2694                                 if (home.src_ipaddr.af == AF_UNSPEC) {
2695                                         home.src_ipaddr = sock->my_ipaddr;
2696                                 }
2697                                 port = sock->my_port + 2;
2698                                 break;
2699                         }
2700 #ifdef WITH_ACCT
2701                         if (this->type == RAD_LISTEN_ACCT) {
2702                                 sock = this->data;
2703                                 if (home.src_ipaddr.af == AF_UNSPEC) {
2704                                         home.src_ipaddr = sock->my_ipaddr;
2705                                 }
2706                                 port = sock->my_port + 1;
2707                                 break;
2708                         }
2709 #endif
2710                 }
2711
2712                 /*
2713                  *      Address is still unspecified, use IPv4.
2714                  */
2715                 if (home.src_ipaddr.af == AF_UNSPEC) {
2716                         home.src_ipaddr.af = AF_INET;
2717                         /* everything else is already set to zero */
2718                 }
2719
2720                 home.ipaddr.af = home.src_ipaddr.af;
2721                 /* everything else is already set to zero */
2722
2723                 if (!proxy_new_listener(&home, port)) {
2724                         listen_free(head);
2725                         return -1;
2726                 }
2727         }
2728 #endif
2729
2730         /*
2731          *      Haven't defined any sockets.  Die.
2732          */
2733         if (!*head) return -1;
2734
2735
2736         return 0;
2737 }
2738
2739 /*
2740  *      Free a linked list of listeners;
2741  */
2742 void listen_free(rad_listen_t **head)
2743 {
2744         rad_listen_t *this;
2745
2746         if (!head || !*head) return;
2747
2748         this = *head;
2749         while (this) {
2750                 rad_listen_t *next = this->next;
2751
2752                 /*
2753                  *      Other code may have eaten the FD.
2754                  */
2755                 if (this->fd >= 0) close(this->fd);
2756
2757                 if (master_listen[this->type].free) {
2758                         master_listen[this->type].free(this);
2759                 }
2760
2761 #ifdef WITH_TCP
2762                 if ((this->type == RAD_LISTEN_AUTH) ||
2763 #ifdef WITH_ACCT
2764                     (this->type == RAD_LISTEN_ACCT) ||
2765 #endif
2766 #ifdef WITH_PROXY
2767                     (this->type == RAD_LISTEN_PROXY)
2768 #endif
2769                         ) {
2770                         listen_socket_t *sock = this->data;
2771                         rad_free(&sock->packet);
2772                 }
2773 #endif
2774
2775                 free(this->data);
2776                 free(this);
2777
2778                 this = next;
2779         }
2780
2781         *head = NULL;
2782 }
2783
2784 #ifdef WITH_STATS
2785 RADCLIENT_LIST *listener_find_client_list(const fr_ipaddr_t *ipaddr,
2786                                           int port)
2787 {
2788         rad_listen_t *this;
2789
2790         for (this = mainconfig.listen; this != NULL; this = this->next) {
2791                 listen_socket_t *sock;
2792
2793                 if ((this->type != RAD_LISTEN_AUTH) &&
2794                     (this->type != RAD_LISTEN_ACCT)) continue;
2795                 
2796                 sock = this->data;
2797
2798                 if ((sock->my_port == port) &&
2799                     (fr_ipaddr_cmp(ipaddr, &sock->my_ipaddr) == 0)) {
2800                         return sock->clients;
2801                 }
2802         }
2803
2804         return NULL;
2805 }
2806 #endif
2807
2808 rad_listen_t *listener_find_byipaddr(const fr_ipaddr_t *ipaddr, int port)
2809 {
2810         rad_listen_t *this;
2811
2812         for (this = mainconfig.listen; this != NULL; this = this->next) {
2813                 listen_socket_t *sock;
2814
2815                 /*
2816                  *      FIXME: For TCP, ignore the *secondary*
2817                  *      listeners associated with the main socket.
2818                  */
2819                 if ((this->type != RAD_LISTEN_AUTH) &&
2820                     (this->type != RAD_LISTEN_ACCT)) continue;
2821                 
2822                 sock = this->data;
2823
2824                 if ((sock->my_port == port) &&
2825                     (fr_ipaddr_cmp(ipaddr, &sock->my_ipaddr) == 0)) {
2826                         return this;
2827                 }
2828
2829                 if ((sock->my_port == port) &&
2830                     ((sock->my_ipaddr.af == AF_INET) &&
2831                      (sock->my_ipaddr.ipaddr.ip4addr.s_addr == INADDR_ANY))) {
2832                         return this;
2833                 }
2834
2835 #ifdef HAVE_STRUCT_SOCKADDR_IN6
2836                 if ((sock->my_port == port) &&
2837                     (sock->my_ipaddr.af == AF_INET6) &&
2838                     (IN6_IS_ADDR_UNSPECIFIED(&sock->my_ipaddr.ipaddr.ip6addr))) {
2839                         return this;
2840                 }
2841 #endif
2842         }
2843
2844         return NULL;
2845 }