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