Simplified use of llvm checker
[freeradius.git] / src / lib / packet.c
1 /*
2  * packet.c     Generic packet manipulation functions.
3  *
4  * Version:     $Id$
5  *
6  *   This library is free software; you can redistribute it and/or
7  *   modify it under the terms of the GNU Lesser General Public
8  *   License as published by the Free Software Foundation; either
9  *   version 2.1 of the License, or (at your option) any later version.
10  *
11  *   This library 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 GNU
14  *   Lesser General Public License for more details.
15  *
16  *   You should have received a copy of the GNU Lesser General Public
17  *   License along with this library; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000-2006  The FreeRADIUS server project
21  */
22
23 #include        <freeradius-devel/ident.h>
24 RCSID("$Id$")
25
26 #include        <freeradius-devel/libradius.h>
27
28 #ifdef WITH_UDPFROMTO
29 #include        <freeradius-devel/udpfromto.h>
30 #endif
31
32 #include <fcntl.h>
33
34 /*
35  *      Take the key fields of a request packet, and convert it to a
36  *      hash.
37  */
38 uint32_t fr_request_packet_hash(const RADIUS_PACKET *packet)
39 {
40         uint32_t hash;
41
42         if (packet->hash) return packet->hash;
43
44         hash = fr_hash(&packet->sockfd, sizeof(packet->sockfd));
45         hash = fr_hash_update(&packet->src_port, sizeof(packet->src_port),
46                                 hash);
47         hash = fr_hash_update(&packet->dst_port,
48                                 sizeof(packet->dst_port), hash);
49         hash = fr_hash_update(&packet->src_ipaddr.af,
50                                 sizeof(packet->src_ipaddr.af), hash);
51
52         /*
53          *      The caller ensures that src & dst AF are the same.
54          */
55         switch (packet->src_ipaddr.af) {
56         case AF_INET:
57                 hash = fr_hash_update(&packet->src_ipaddr.ipaddr.ip4addr,
58                                         sizeof(packet->src_ipaddr.ipaddr.ip4addr),
59                                         hash);
60                 hash = fr_hash_update(&packet->dst_ipaddr.ipaddr.ip4addr,
61                                         sizeof(packet->dst_ipaddr.ipaddr.ip4addr),
62                                         hash);
63                 break;
64         case AF_INET6:
65                 hash = fr_hash_update(&packet->src_ipaddr.ipaddr.ip6addr,
66                                         sizeof(packet->src_ipaddr.ipaddr.ip6addr),
67                                         hash);
68                 hash = fr_hash_update(&packet->dst_ipaddr.ipaddr.ip6addr,
69                                         sizeof(packet->dst_ipaddr.ipaddr.ip6addr),
70                                         hash);
71                 break;
72         default:
73                 break;
74         }
75
76         return fr_hash_update(&packet->id, sizeof(packet->id), hash);
77 }
78
79
80 /*
81  *      Take the key fields of a reply packet, and convert it to a
82  *      hash.
83  *
84  *      i.e. take a reply packet, and find the hash of the request packet
85  *      that asked for the reply.  To do this, we hash the reverse fields
86  *      of the request.  e.g. where the request does (src, dst), we do
87  *      (dst, src)
88  */
89 uint32_t fr_reply_packet_hash(const RADIUS_PACKET *packet)
90 {
91         uint32_t hash;
92
93         hash = fr_hash(&packet->sockfd, sizeof(packet->sockfd));
94         hash = fr_hash_update(&packet->id, sizeof(packet->id), hash);
95         hash = fr_hash_update(&packet->src_port, sizeof(packet->src_port),
96                                 hash);
97         hash = fr_hash_update(&packet->dst_port,
98                                 sizeof(packet->dst_port), hash);
99         hash = fr_hash_update(&packet->src_ipaddr.af,
100                                 sizeof(packet->src_ipaddr.af), hash);
101
102         /*
103          *      The caller ensures that src & dst AF are the same.
104          */
105         switch (packet->src_ipaddr.af) {
106         case AF_INET:
107                 hash = fr_hash_update(&packet->dst_ipaddr.ipaddr.ip4addr,
108                                         sizeof(packet->dst_ipaddr.ipaddr.ip4addr),
109                                         hash);
110                 hash = fr_hash_update(&packet->src_ipaddr.ipaddr.ip4addr,
111                                         sizeof(packet->src_ipaddr.ipaddr.ip4addr),
112                                         hash);
113                 break;
114         case AF_INET6:
115                 hash = fr_hash_update(&packet->dst_ipaddr.ipaddr.ip6addr,
116                                         sizeof(packet->dst_ipaddr.ipaddr.ip6addr),
117                                         hash);
118                 hash = fr_hash_update(&packet->src_ipaddr.ipaddr.ip6addr,
119                                         sizeof(packet->src_ipaddr.ipaddr.ip6addr),
120                                         hash);
121                 break;
122         default:
123                 break;
124         }
125
126         return fr_hash_update(&packet->id, sizeof(packet->id), hash);
127 }
128
129
130 /*
131  *      See if two packets are identical.
132  *
133  *      Note that we do NOT compare the authentication vectors.
134  *      That's because if the authentication vector is different,
135  *      it means that the NAS has given up on the earlier request.
136  */
137 int fr_packet_cmp(const RADIUS_PACKET *a, const RADIUS_PACKET *b)
138 {
139         int rcode;
140
141         if (a->sockfd < b->sockfd) return -1;
142         if (a->sockfd > b->sockfd) return +1;
143
144         if (a->id < b->id) return -1;
145         if (a->id > b->id) return +1;
146
147         if (a->src_port < b->src_port) return -1;
148         if (a->src_port > b->src_port) return +1;
149
150         if (a->dst_port < b->dst_port) return -1;
151         if (a->dst_port > b->dst_port) return +1;
152
153         rcode = fr_ipaddr_cmp(&a->dst_ipaddr, &b->dst_ipaddr);
154         if (rcode != 0) return rcode;
155         return fr_ipaddr_cmp(&a->src_ipaddr, &b->src_ipaddr);
156 }
157
158 int fr_inaddr_any(fr_ipaddr_t *ipaddr)
159 {
160
161         if (ipaddr->af == AF_INET) {
162                 if (ipaddr->ipaddr.ip4addr.s_addr == INADDR_ANY) {
163                         return 1;
164                 }
165                 
166 #ifdef HAVE_STRUCT_SOCKADDR_IN6
167         } else if (ipaddr->af == AF_INET6) {
168                 if (IN6_IS_ADDR_UNSPECIFIED(&(ipaddr->ipaddr.ip6addr))) {
169                         return 1;
170                 }
171 #endif
172                 
173         } else {
174                 fr_strerror_printf("Unknown address family");
175                 return -1;
176         }
177
178         return 0;
179 }
180
181
182 /*
183  *      Create a fake "request" from a reply, for later lookup.
184  */
185 void fr_request_from_reply(RADIUS_PACKET *request,
186                              const RADIUS_PACKET *reply)
187 {
188         request->sockfd = reply->sockfd;
189         request->id = reply->id;
190         request->src_port = reply->dst_port;
191         request->dst_port = reply->src_port;
192         request->src_ipaddr = reply->dst_ipaddr;
193         request->dst_ipaddr = reply->src_ipaddr;
194 }
195
196
197 int fr_nonblock(UNUSED int fd)
198 {
199         int flags = 0;
200
201 #ifdef O_NONBLOCK
202
203         flags = fcntl(fd, F_GETFL, NULL);
204         if (flags >= 0) {
205                 flags |= O_NONBLOCK;
206                 return fcntl(fd, F_SETFL, flags);
207         }
208 #endif
209         return flags;
210 }
211
212 /*
213  *      Open a socket on the given IP and port.
214  */
215 int fr_socket(fr_ipaddr_t *ipaddr, int port)
216 {
217         int sockfd;
218         struct sockaddr_storage salocal;
219         socklen_t       salen;
220
221         if ((port < 0) || (port > 65535)) {
222                 fr_strerror_printf("Port %d is out of allowed bounds", port);
223                 return -1;
224         }
225
226         sockfd = socket(ipaddr->af, SOCK_DGRAM, 0);
227         if (sockfd < 0) {
228                 fr_strerror_printf("cannot open socket: %s", strerror(errno));
229                 return sockfd;
230         }
231
232 #ifdef WITH_UDPFROMTO
233         /*
234          *      Initialize udpfromto for all sockets.
235          */
236         if (udpfromto_init(sockfd) != 0) {
237                 close(sockfd);
238                 fr_strerror_printf("cannot initialize udpfromto: %s", strerror(errno));
239                 return -1;
240         }
241 #endif
242
243         if (fr_nonblock(sockfd) < 0) {
244                 close(sockfd);
245                 return -1;
246         }
247
248         if (!fr_ipaddr2sockaddr(ipaddr, port, &salocal, &salen)) {
249                 return sockfd;
250         }
251
252 #ifdef HAVE_STRUCT_SOCKADDR_IN6
253         if (ipaddr->af == AF_INET6) {
254                 /*
255                  *      Listening on '::' does NOT get you IPv4 to
256                  *      IPv6 mapping.  You've got to listen on an IPv4
257                  *      address, too.  This makes the rest of the server
258                  *      design a little simpler.
259                  */
260 #ifdef IPV6_V6ONLY
261
262                 if (IN6_IS_ADDR_UNSPECIFIED(&ipaddr->ipaddr.ip6addr)) {
263                         int on = 1;
264
265                         setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
266                                    (char *)&on, sizeof(on));
267                 }
268 #endif /* IPV6_V6ONLY */
269         }
270 #endif /* HAVE_STRUCT_SOCKADDR_IN6 */
271
272         if (ipaddr->af == AF_INET) {
273                 UNUSED int flag;
274                 
275 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
276                 /*
277                  *      Disable PMTU discovery.  On Linux, this
278                  *      also makes sure that the "don't fragment"
279                  *      flag is zero.
280                  */
281                 flag = IP_PMTUDISC_DONT;
282                 setsockopt(sockfd, IPPROTO_IP, IP_MTU_DISCOVER,
283                            &flag, sizeof(flag));
284 #endif
285
286 #if defined(IP_DONTFRAG)
287                 /*
288                  *      Ensure that the "don't fragment" flag is zero.
289                  */
290                 flag = 0;
291                 setsockopt(sockfd, IPPROTO_IP, IP_DONTFRAG,
292                            &flag, sizeof(flag));
293 #endif
294         }
295
296         if (bind(sockfd, (struct sockaddr *) &salocal, salen) < 0) {
297                 close(sockfd);
298                 fr_strerror_printf("cannot bind socket: %s", strerror(errno));
299                 return -1;
300         }
301
302         return sockfd;
303 }
304
305
306 /*
307  *      We need to keep track of the socket & it's IP/port.
308  */
309 typedef struct fr_packet_socket_t {
310         int             sockfd;
311         void            *ctx;
312
313         int             num_outgoing;
314
315         int             src_any;
316         fr_ipaddr_t     src_ipaddr;
317         int             src_port;
318
319         int             dst_any;
320         fr_ipaddr_t     dst_ipaddr;
321         int             dst_port;
322
323         int             dont_use;
324
325 #ifdef WITH_TCP
326         int             proto;
327 #endif
328
329         uint8_t         id[32];
330 } fr_packet_socket_t;
331
332
333 #define FNV_MAGIC_PRIME (0x01000193)
334 #define MAX_SOCKETS (256)
335 #define SOCKOFFSET_MASK (MAX_SOCKETS - 1)
336 #define SOCK2OFFSET(sockfd) ((sockfd * FNV_MAGIC_PRIME) & SOCKOFFSET_MASK)
337
338 #define MAX_QUEUES (8)
339
340 /*
341  *      Structure defining a list of packets (incoming or outgoing)
342  *      that should be managed.
343  */
344 struct fr_packet_list_t {
345         fr_hash_table_t *ht;
346
347         int             alloc_id;
348         int             num_outgoing;
349         int             last_recv;
350
351         fr_packet_socket_t sockets[MAX_SOCKETS];
352 };
353
354
355 /*
356  *      Ugh.  Doing this on every sent/received packet is not nice.
357  */
358 static fr_packet_socket_t *fr_socket_find(fr_packet_list_t *pl,
359                                           int sockfd)
360 {
361         int i, start;
362
363         i = start = SOCK2OFFSET(sockfd);
364
365         do {                    /* make this hack slightly more efficient */
366                 if (pl->sockets[i].sockfd == sockfd) return &pl->sockets[i];
367
368                 i = (i + 1) & SOCKOFFSET_MASK;
369         } while (i != start);
370
371         return NULL;
372 }
373
374 int fr_packet_list_socket_freeze(fr_packet_list_t *pl, int sockfd)
375 {
376         fr_packet_socket_t *ps;
377
378         if (!pl) return 0;
379
380         ps = fr_socket_find(pl, sockfd);
381         if (!ps) return 0;
382
383         ps->dont_use = 1;
384         return 1;
385 }
386
387 int fr_packet_list_socket_remove(fr_packet_list_t *pl, int sockfd,
388                                  void **pctx)
389 {
390         fr_packet_socket_t *ps;
391
392         if (!pl) return 0;
393
394         ps = fr_socket_find(pl, sockfd);
395         if (!ps) return 0;
396
397         /*
398          *      FIXME: Allow the caller forcibly discard these?
399          */
400         if (ps->num_outgoing != 0) return 0;
401
402         ps->sockfd = -1;
403         if (pctx) *pctx = ps->ctx;
404
405         return 1;
406 }
407
408 int fr_packet_list_socket_add(fr_packet_list_t *pl, int sockfd, int proto,
409                               fr_ipaddr_t *dst_ipaddr, int dst_port,
410                               void *ctx)
411 {
412         int i, start;
413         struct sockaddr_storage src;
414         socklen_t               sizeof_src;
415         fr_packet_socket_t      *ps;
416
417         if (!pl || !dst_ipaddr || (dst_ipaddr->af == AF_UNSPEC)) {
418                 fr_strerror_printf("Invalid argument");
419                 return 0;
420         }
421
422         ps = NULL;
423         i = start = SOCK2OFFSET(sockfd);
424
425         do {
426                 if (pl->sockets[i].sockfd == -1) {
427                         ps =  &pl->sockets[i];
428                         start = i;
429                         break;
430                 }
431
432                 i = (i + 1) & SOCKOFFSET_MASK;
433         } while (i != start);
434
435         if (!ps) {
436                 fr_strerror_printf("All socket entries are full");
437                 return 0;
438         }
439
440         memset(ps, 0, sizeof(*ps));
441         ps->ctx = ctx;
442         ps->proto = proto;
443
444         /*
445          *      Get address family, etc. first, so we know if we
446          *      need to do udpfromto.
447          *
448          *      FIXME: udpfromto also does this, but it's not
449          *      a critical problem.
450          */
451         sizeof_src = sizeof(src);
452         memset(&src, 0, sizeof_src);
453         if (getsockname(sockfd, (struct sockaddr *) &src,
454                         &sizeof_src) < 0) {
455                 fr_strerror_printf("%s", strerror(errno));
456                 return 0;
457         }
458
459         if (!fr_sockaddr2ipaddr(&src, sizeof_src, &ps->src_ipaddr,
460                                 &ps->src_port)) {
461                 fr_strerror_printf("Failed to get IP");
462                 return 0;
463         }
464
465         ps->dst_ipaddr = *dst_ipaddr;
466         ps->dst_port = dst_port;
467
468         ps->src_any = fr_inaddr_any(&ps->src_ipaddr);
469         if (ps->src_any < 0) return 0;
470
471         ps->dst_any = fr_inaddr_any(&ps->dst_ipaddr);
472         if (ps->dst_any < 0) return 0;
473
474         /*
475          *      As the last step before returning.
476          */
477         ps->sockfd = sockfd;
478
479         return 1;
480 }
481
482 static uint32_t packet_entry_hash(const void *data)
483 {
484         return fr_request_packet_hash(*(const RADIUS_PACKET * const *) data);
485 }
486
487 static int packet_entry_cmp(const void *one, const void *two)
488 {
489         const RADIUS_PACKET * const *a = one;
490         const RADIUS_PACKET * const *b = two;
491
492         return fr_packet_cmp(*a, *b);
493 }
494
495 void fr_packet_list_free(fr_packet_list_t *pl)
496 {
497         if (!pl) return;
498
499         fr_hash_table_free(pl->ht);
500         free(pl);
501 }
502
503
504 /*
505  *      Caller is responsible for managing the packet entries.
506  */
507 fr_packet_list_t *fr_packet_list_create(int alloc_id)
508 {
509         int i;
510         fr_packet_list_t        *pl;
511
512         pl = malloc(sizeof(*pl));
513         if (!pl) return NULL;
514         memset(pl, 0, sizeof(*pl));
515
516         pl->ht = fr_hash_table_create(packet_entry_hash,
517                                         packet_entry_cmp,
518                                         NULL);
519         if (!pl->ht) {
520                 fr_packet_list_free(pl);
521                 return NULL;
522         }
523
524         for (i = 0; i < MAX_SOCKETS; i++) {
525                 pl->sockets[i].sockfd = -1;
526         }
527
528         pl->alloc_id = alloc_id;
529
530         return pl;
531 }
532
533
534 /*
535  *      If pl->alloc_id is set, then fr_packet_list_id_alloc() MUST
536  *      be called before inserting the packet into the list!
537  */
538 int fr_packet_list_insert(fr_packet_list_t *pl,
539                             RADIUS_PACKET **request_p)
540 {
541         if (!pl || !request_p || !*request_p) return 0;
542
543         (*request_p)->hash = fr_request_packet_hash(*request_p);
544
545         return fr_hash_table_insert(pl->ht, request_p);
546 }
547
548 RADIUS_PACKET **fr_packet_list_find(fr_packet_list_t *pl,
549                                       RADIUS_PACKET *request)
550 {
551         if (!pl || !request) return 0;
552
553         return fr_hash_table_finddata(pl->ht, &request);
554 }
555
556
557 /*
558  *      This presumes that the reply has dst_ipaddr && dst_port set up
559  *      correctly (i.e. real IP, or "*").
560  */
561 RADIUS_PACKET **fr_packet_list_find_byreply(fr_packet_list_t *pl,
562                                               RADIUS_PACKET *reply)
563 {
564         RADIUS_PACKET my_request, *request;
565         fr_packet_socket_t *ps;
566
567         if (!pl || !reply) return NULL;
568
569         ps = fr_socket_find(pl, reply->sockfd);
570         if (!ps) return NULL;
571
572         /*
573          *      Initialize request from reply, AND from the source
574          *      IP & port of this socket.  The client may have bound
575          *      the socket to 0, in which case it's some random port,
576          *      that is NOT in the original request->src_port.
577          */
578         my_request.sockfd = reply->sockfd;
579         my_request.id = reply->id;
580
581         if (ps->src_any) {
582                 my_request.src_ipaddr = ps->src_ipaddr;
583         } else {
584                 my_request.src_ipaddr = reply->dst_ipaddr;
585         }
586         my_request.src_port = ps->src_port;
587
588         my_request.dst_ipaddr = reply->src_ipaddr;
589         my_request.dst_port = reply->src_port;
590         my_request.hash = 0;
591
592         request = &my_request;
593
594         return fr_hash_table_finddata(pl->ht, &request);
595 }
596
597
598 RADIUS_PACKET **fr_packet_list_yank(fr_packet_list_t *pl,
599                                       RADIUS_PACKET *request)
600 {
601         if (!pl || !request) return NULL;
602
603         return fr_hash_table_yank(pl->ht, &request);
604 }
605
606 int fr_packet_list_num_elements(fr_packet_list_t *pl)
607 {
608         if (!pl) return 0;
609
610         return fr_hash_table_num_elements(pl->ht);
611 }
612
613
614 /*
615  *      1 == ID was allocated & assigned
616  *      0 == error allocating memory
617  *      -1 == all ID's are used, caller should open a new socket.
618  *
619  *      Note that this ALSO assigns a socket to use, and updates
620  *      packet->request->src_ipaddr && packet->request->src_port
621  *
622  *      In multi-threaded systems, the calls to id_alloc && id_free
623  *      should be protected by a mutex.  This does NOT have to be
624  *      the same mutex as the one protecting the insert/find/yank
625  *      calls!
626  *
627  *      We assume that the packet has dst_ipaddr && dst_port
628  *      already initialized.  We will use those to find an
629  *      outgoing socket.  The request MAY also have src_ipaddr set.
630  *
631  *      We also assume that the sender doesn't care which protocol
632  *      should be used.
633  */
634 int fr_packet_list_id_alloc(fr_packet_list_t *pl, int proto,
635                             RADIUS_PACKET *request, void **pctx)
636 {
637         int i, j, k, fd, id, start_i, start_j, start_k;
638         int src_any = 0;
639         fr_packet_socket_t *ps;
640
641         if ((request->dst_ipaddr.af == AF_UNSPEC) ||
642             (request->dst_port == 0)) {
643                 fr_strerror_printf("No destination address/port specified");
644                 return 0;
645         }
646
647 #ifndef WITH_TCP
648         if ((proto != 0) && (proto != IPPROTO_UDP)) {
649                 fr_strerror_printf("Invalid destination protocol");
650                 return 0;
651         }
652 #endif
653
654         /*
655          *      Special case: unspec == "don't care"
656          */
657         if (request->src_ipaddr.af == AF_UNSPEC) {
658                 memset(&request->src_ipaddr, 0, sizeof(request->src_ipaddr));
659                 request->src_ipaddr.af = request->dst_ipaddr.af;
660         }
661
662         src_any = fr_inaddr_any(&request->src_ipaddr);
663         if (src_any < 0) return 0;
664
665         /*
666          *      MUST specify a destination address.
667          */
668         if (fr_inaddr_any(&request->dst_ipaddr) != 0) return 0;
669
670         /*
671          *      FIXME: Go to an LRU system.  This prevents ID re-use
672          *      for as long as possible.  The main problem with that
673          *      approach is that it requires us to populate the
674          *      LRU/FIFO when we add a new socket, or a new destination,
675          *      which can be expensive.
676          *
677          *      The LRU can be avoided if the caller takes care to free
678          *      Id's only when all responses have been received, OR after
679          *      a timeout.
680          *
681          *      Right now, the random approach is almost OK... it's
682          *      brute-force over all of the available ID's, BUT using
683          *      random numbers for everything spreads the load a bit.
684          *
685          *      The old method had a hash lookup on allocation AND
686          *      on free.  The new method has brute-force on allocation,
687          *      and near-zero cost on free.
688          */
689
690         id = fd = -1;
691         start_i = fr_rand() & SOCKOFFSET_MASK;
692
693 #define ID_i ((i + start_i) & SOCKOFFSET_MASK)
694         for (i = 0; i < MAX_SOCKETS; i++) {
695                 if (pl->sockets[ID_i].sockfd == -1) continue; /* paranoia */
696
697                 ps = &(pl->sockets[ID_i]);
698
699                 /*
700                  *      This socket is marked as "don't use for new
701                  *      packets".  But we can still receive packets
702                  *      that are outstanding.
703                  */
704                 if (ps->dont_use) continue;
705
706                 /*
707                  *      All IDs are allocated: ignore it.
708                  */
709                 if (ps->num_outgoing == 256) continue;
710
711 #ifdef WITH_TCP
712                 if (ps->proto != proto) continue;
713 #endif
714
715                 /*
716                  *      MUST match dst port, if we have one.
717                  */
718                 if ((ps->dst_port != 0) && 
719                     (ps->dst_port != request->dst_port)) continue;
720
721                 /*
722                  *      MUST match requested src port, if one has been given.
723                  */
724                 if ((request->src_port != 0) && 
725                     (ps->src_port != request->src_port)) continue;
726
727                 /*
728                  *      We're sourcing from *, and they asked for a
729                  *      specific source address: ignore it.
730                  */
731                 if (ps->src_any && !src_any) continue;
732
733                 /*
734                  *      We're sourcing from a specific IP, and they
735                  *      asked for a source IP that isn't us: ignore
736                  *      it.
737                  */
738                 if (!ps->src_any && !src_any &&
739                     (fr_ipaddr_cmp(&request->src_ipaddr,
740                                    &ps->src_ipaddr) != 0)) continue;
741
742                 /*
743                  *      UDP sockets are allowed to match
744                  *      destination IPs exactly, OR a socket
745                  *      with destination * is allowed to match
746                  *      any requested destination.
747                  *
748                  *      TCP sockets must match the destination
749                  *      exactly.  They *always* have dst_any=0,
750                  *      so the first check always matches.
751                  */
752                 if (!ps->dst_any &&
753                     (fr_ipaddr_cmp(&request->dst_ipaddr,
754                                    &ps->dst_ipaddr) != 0)) continue;
755                 
756                 /*
757                  *      Otherwise, this socket is OK to use.
758                  */
759
760                 /*
761                  *      Look for a free Id, starting from a random number.
762                  */
763                 start_j = fr_rand() & 0x1f;
764 #define ID_j ((j + start_j) & 0x1f)
765                 for (j = 0; j < 32; j++) {
766                         if (ps->id[ID_j] == 0xff) continue;
767
768
769                         start_k = fr_rand() & 0x07;
770 #define ID_k ((k + start_k) & 0x07)
771                         for (k = 0; k < 8; k++) {
772                                 if ((ps->id[ID_j] & (1 << ID_k)) != 0) continue;
773
774                                 ps->id[ID_j] |= (1 << ID_k);
775                                 id = (ID_j * 8) + ID_k;
776                                 fd = i;
777                                 break;
778                         }
779                         if (fd >= 0) break;
780                 }
781 #undef ID_i
782 #undef ID_j
783 #undef ID_k
784                 if (fd >= 0) break;
785                 break;
786         }
787
788         /*
789          *      Ask the caller to allocate a new ID.
790          */
791         if (fd < 0) return 0;
792
793         ps->num_outgoing++;
794         pl->num_outgoing++;
795
796         /*
797          *      Set the ID, source IP, and source port.
798          */
799         request->id = id;
800
801         request->sockfd = ps->sockfd;
802         request->src_ipaddr = ps->src_ipaddr;
803         request->src_port = ps->src_port;
804
805         if (pctx) *pctx = ps->ctx;
806
807         return 1;
808 }
809
810 /*
811  *      Should be called AFTER yanking it from the list, so that
812  *      any newly inserted entries don't collide with this one.
813  */
814 int fr_packet_list_id_free(fr_packet_list_t *pl,
815                              RADIUS_PACKET *request)
816 {
817         fr_packet_socket_t *ps;
818
819         if (!pl || !request) return 0;
820
821         ps = fr_socket_find(pl, request->sockfd);
822         if (!ps) return 0;
823
824 #if 0
825         if (!ps->id[(request->id >> 3) & 0x1f] & (1 << (request->id & 0x07))) {
826                 exit(1);
827         }
828 #endif
829
830         ps->id[(request->id >> 3) & 0x1f] &= ~(1 << (request->id & 0x07));
831         request->hash = 0;      /* invalidate the cached hash */
832
833         ps->num_outgoing--;
834         pl->num_outgoing--;
835
836         return 1;
837 }
838
839 int fr_packet_list_walk(fr_packet_list_t *pl, void *ctx,
840                           fr_hash_table_walk_t callback)
841 {
842         if (!pl || !callback) return 0;
843
844         return fr_hash_table_walk(pl->ht, callback, ctx);
845 }
846
847 int fr_packet_list_fd_set(fr_packet_list_t *pl, fd_set *set)
848 {
849         int i, maxfd;
850
851         if (!pl || !set) return 0;
852
853         maxfd = -1;
854
855         for (i = 0; i < MAX_SOCKETS; i++) {
856                 if (pl->sockets[i].sockfd == -1) continue;
857                 FD_SET(pl->sockets[i].sockfd, set);
858                 if (pl->sockets[i].sockfd > maxfd) {
859                         maxfd = pl->sockets[i].sockfd;
860                 }
861         }
862
863         if (maxfd < 0) return -1;
864
865         return maxfd + 1;
866 }
867
868 /*
869  *      Round-robins the receivers, without priority.
870  *
871  *      FIXME: Add sockfd, if -1, do round-robin, else do sockfd
872  *              IF in fdset.
873  */
874 RADIUS_PACKET *fr_packet_list_recv(fr_packet_list_t *pl, fd_set *set)
875 {
876         int start;
877         RADIUS_PACKET *packet;
878
879         if (!pl || !set) return NULL;
880
881         start = pl->last_recv;
882         do {
883                 start++;
884                 start &= SOCKOFFSET_MASK;
885
886                 if (pl->sockets[start].sockfd == -1) continue;
887
888                 if (!FD_ISSET(pl->sockets[start].sockfd, set)) continue;
889
890 #ifdef WITH_TCP
891                 if (pl->sockets[start].proto == IPPROTO_TCP) {
892                         packet = fr_tcp_recv(pl->sockets[start].sockfd, 0);
893                 } else
894 #endif
895                 packet = rad_recv(pl->sockets[start].sockfd, 0);
896                 if (!packet) continue;
897
898                 /*
899                  *      Call fr_packet_list_find_byreply().  If it
900                  *      doesn't find anything, discard the reply.
901                  */
902
903                 pl->last_recv = start;
904                 return packet;
905         } while (start != pl->last_recv);
906
907         return NULL;
908 }
909
910 int fr_packet_list_num_incoming(fr_packet_list_t *pl)
911 {
912         int num_elements;
913
914         if (!pl) return 0;
915
916         num_elements = fr_hash_table_num_elements(pl->ht);
917         if (num_elements < pl->num_outgoing) return 0; /* panic! */
918
919         return num_elements - pl->num_outgoing;
920 }
921
922 int fr_packet_list_num_outgoing(fr_packet_list_t *pl)
923 {
924         if (!pl) return 0;
925
926         return pl->num_outgoing;
927 }