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