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