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