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