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