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