Clean up API for packet list stuff, and a minor bug.
[freeradius.git] / src / main / radclient.c
1 /*
2  * radclient.c  General radius packet debug tool.
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 2000  The FreeRADIUS server project
21  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  */
24 static const char rcsid[] = "$Id$";
25
26 #include <freeradius-devel/autoconf.h>
27
28 #include <stdio.h>
29 #include <stdlib.h>
30
31 #ifdef HAVE_UNISTD_H
32 #       include <unistd.h>
33 #endif
34
35 #include <string.h>
36 #include <ctype.h>
37 #include <netdb.h>
38
39 #ifdef HAVE_SYS_SELECT_H
40 #       include <sys/select.h>
41 #endif
42
43 #ifdef HAVE_GETOPT_H
44 #       include <getopt.h>
45 #endif
46
47 #include <assert.h>
48
49 #include <freeradius-devel/conf.h>
50 #include <freeradius-devel/radpaths.h>
51 #include <freeradius-devel/missing.h>
52 #include <freeradius-devel/libradius.h>
53
54 static int retries = 10;
55 static float timeout = 3;
56 static const char *secret = NULL;
57 static int do_output = 1;
58 static int totalapp = 0;
59 static int totaldeny = 0;
60 static int totallost = 0;
61
62 static int server_port = 0;
63 static int packet_code = 0;
64 static lrad_ipaddr_t server_ipaddr;
65 static int resend_count = 1;
66 static int done = 1;
67
68 static lrad_ipaddr_t client_ipaddr;
69 static int client_port = 0;
70
71 static int sockfd;
72 static int last_used_id = -1;
73
74 static rbtree_t *filename_tree = NULL;
75 static lrad_packet_list_t *pl = NULL;
76
77 static int sleep_time = -1;
78
79 typedef struct radclient_t {
80         struct          radclient_t *prev;
81         struct          radclient_t *next;
82
83         const char      *filename;
84         int             packet_number; /* in the file */
85         char            password[256];
86         time_t          timestamp;
87         RADIUS_PACKET   *request;
88         RADIUS_PACKET   *reply;
89         int             resend;
90         int             tries;
91         int             done;
92 } radclient_t;
93
94 static radclient_t *radclient_head = NULL;
95 static radclient_t *radclient_tail = NULL;
96
97
98 static void NEVER_RETURNS usage(void)
99 {
100         fprintf(stderr, "Usage: radclient [options] server[:port] <command> [<secret>]\n");
101
102         fprintf(stderr, "  <command>    One of auth, acct, status, coa, or disconnect.\n");
103         fprintf(stderr, "  -c count    Send each packet 'count' times.\n");
104         fprintf(stderr, "  -d raddb    Set dictionary directory.\n");
105         fprintf(stderr, "  -f file     Read packets from file, not stdin.\n");
106         fprintf(stderr, "  -i id       Set request id to 'id'.  Values may be 0..255\n");
107         fprintf(stderr, "  -n num      Send N requests/s\n");
108         fprintf(stderr, "  -p num      Send 'num' packets from a file in parallel.\n");
109         fprintf(stderr, "  -q          Do not print anything out.\n");
110         fprintf(stderr, "  -r retries  If timeout, retry sending the packet 'retries' times.\n");
111         fprintf(stderr, "  -s          Print out summary information of auth results.\n");
112         fprintf(stderr, "  -S file     read secret from file, not command line.\n");
113         fprintf(stderr, "  -t timeout  Wait 'timeout' seconds before retrying (may be a floating point number).\n");
114         fprintf(stderr, "  -v          Show program version information.\n");
115         fprintf(stderr, "  -x          Debugging mode.\n");
116         fprintf(stderr, "  -4          Use IPv4 address of server\n");
117         fprintf(stderr, "  -6          Use IPv6 address of server.\n");
118
119         exit(1);
120 }
121
122 /*
123  *      Free a radclient struct, which may (or may not)
124  *      already be in the list.
125  */
126 static void radclient_free(radclient_t *radclient)
127 {
128         radclient_t *prev, *next;
129
130         if (radclient->request) rad_free(&radclient->request);
131         if (radclient->reply) rad_free(&radclient->reply);
132
133         prev = radclient->prev;
134         next = radclient->next;
135
136         if (prev) {
137                 assert(radclient_head != radclient);
138                 prev->next = next;
139         } else if (radclient_head) {
140                 assert(radclient_head == radclient);
141                 radclient_head = next;
142         }
143
144         if (next) {
145                 assert(radclient_tail != radclient);
146                 next->prev = prev;
147         } else if (radclient_tail) {
148                 assert(radclient_tail == radclient);
149                 radclient_tail = prev;
150         }
151
152         free(radclient);
153 }
154
155 /*
156  *      Initialize a radclient data structure
157  */
158 static radclient_t *radclient_init(const char *filename)
159 {
160         FILE *fp;
161         VALUE_PAIR *vp;
162         radclient_t *start, *radclient, *prev = NULL;
163         int filedone = 0;
164         int packet_number = 1;
165
166         start = NULL;
167         assert(filename != NULL);
168
169         /*
170          *      Determine where to read the VP's from.
171          */
172         if (strcmp(filename, "-") != 0) {
173                 fp = fopen(filename, "r");
174                 if (!fp) {
175                         fprintf(stderr, "radclient: Error opening %s: %s\n",
176                                 filename, strerror(errno));
177                         return NULL;
178                 }
179         } else {
180                 fp = stdin;
181         }
182
183         /*
184          *      Loop until the file is done.
185          */
186         do {
187                 /*
188                  *      Allocate it.
189                  */
190                 radclient = malloc(sizeof(*radclient));
191                 if (!radclient) {
192                         perror("radclient: X");
193                         return NULL; /* memory leak "start" */
194                 }
195                 memset(radclient, 0, sizeof(*radclient));
196
197                 radclient->request = rad_alloc(1);
198                 if (!radclient->request) {
199                         librad_perror("radclient: Y");
200                         radclient_free(radclient);
201                         return NULL; /* memory leak "start" */
202                 }
203
204                 radclient->filename = filename;
205                 radclient->request->id = -1; /* allocate when sending */
206                 radclient->packet_number = packet_number++;
207
208                 /*
209                  *      Read the VP's.
210                  */
211                 radclient->request->vps = readvp2(fp, &filedone, "radclient:");
212                 if (!radclient->request->vps) {
213                         radclient_free(radclient);
214                         return start; /* done: return the list */
215                 }
216
217                 /*
218                  *      Keep a copy of the the User-Password attribute.
219                  */
220                 if ((vp = pairfind(radclient->request->vps, PW_PASSWORD)) != NULL) {
221                         strNcpy(radclient->password, vp->vp_strvalue,
222                                 sizeof(radclient->password));
223                         /*
224                          *      Otherwise keep a copy of the CHAP-Password attribute.
225                          */
226                 } else if ((vp = pairfind(radclient->request->vps, PW_CHAP_PASSWORD)) != NULL) {
227                         strNcpy(radclient->password, vp->vp_strvalue,
228                                 sizeof(radclient->password));
229                 } else {
230                         radclient->password[0] = '\0';
231                 }
232
233                 /*
234                  *  Fix up Digest-Attributes issues
235                  */
236                 for (vp = radclient->request->vps; vp != NULL; vp = vp->next) {
237                         switch (vp->attribute) {
238                         default:
239                                 break;
240
241                                 /*
242                                  *      Allow it to set the packet type in
243                                  *      the attributes read from the file.
244                                  */
245                         case PW_PACKET_TYPE:
246                                 radclient->request->code = vp->lvalue;
247                                 break;
248
249                         case PW_PACKET_DST_PORT:
250                                 radclient->request->dst_port = (vp->lvalue & 0xffff);
251                                 break;
252
253                         case PW_PACKET_DST_IP_ADDRESS:
254                                 radclient->request->dst_ipaddr.af = AF_INET;
255                                 radclient->request->dst_ipaddr.ipaddr.ip4addr.s_addr = vp->lvalue;
256                                 break;
257
258                         case PW_PACKET_DST_IPV6_ADDRESS:
259                                 radclient->request->dst_ipaddr.af = AF_INET6;
260                                 radclient->request->dst_ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
261                                 break;
262
263                         case PW_PACKET_SRC_PORT:
264                                 radclient->request->src_port = (vp->lvalue & 0xffff);
265                                 break;
266
267                         case PW_PACKET_SRC_IP_ADDRESS:
268                                 radclient->request->src_ipaddr.af = AF_INET;
269                                 radclient->request->src_ipaddr.ipaddr.ip4addr.s_addr = vp->lvalue;
270                                 break;
271
272                         case PW_PACKET_SRC_IPV6_ADDRESS:
273                                 radclient->request->src_ipaddr.af = AF_INET6;
274                                 radclient->request->src_ipaddr.ipaddr.ip6addr = vp->vp_ipv6addr;
275                                 break;
276
277                         case PW_DIGEST_REALM:
278                         case PW_DIGEST_NONCE:
279                         case PW_DIGEST_METHOD:
280                         case PW_DIGEST_URI:
281                         case PW_DIGEST_QOP:
282                         case PW_DIGEST_ALGORITHM:
283                         case PW_DIGEST_BODY_DIGEST:
284                         case PW_DIGEST_CNONCE:
285                         case PW_DIGEST_NONCE_COUNT:
286                         case PW_DIGEST_USER_NAME:
287                                 /* overlapping! */
288                                 memmove(&vp->vp_octets[2], &vp->vp_octets[0],
289                                         vp->length);
290                                 vp->vp_octets[0] = vp->attribute - PW_DIGEST_REALM + 1;
291                                 vp->length += 2;
292                                 vp->vp_octets[1] = vp->length;
293                                 vp->attribute = PW_DIGEST_ATTRIBUTES;
294                                 break;
295                         }
296                 } /* loop over the VP's we read in */
297
298                 if (!start) {
299                         start = radclient;
300                         prev = start;
301                 } else {
302                         prev->next = radclient;
303                         radclient->prev = prev;
304                         prev = radclient;
305                 }
306         } while (!filedone); /* loop until the file is done. */
307
308         if (fp != stdin) fclose(fp);
309
310         /*
311          *      And we're done.
312          */
313         return start;
314 }
315
316
317 /*
318  *      Sanity check each argument.
319  */
320 static int radclient_sane(radclient_t *radclient)
321 {
322         if (radclient->request->dst_port == 0) {
323                 radclient->request->dst_port = server_port;
324         }
325         if (radclient->request->dst_ipaddr.af == AF_UNSPEC) {
326                 if (server_ipaddr.af == AF_UNSPEC) {
327                         fprintf(stderr, "radclient: No server was given, but request %d in file %s did not contain Packet-Dst-IP-Address\n",
328                                 radclient->packet_number, radclient->filename);
329                         return -1;
330                 }
331                 radclient->request->dst_ipaddr = server_ipaddr;
332         }
333         if (radclient->request->code == 0) {
334                 if (packet_code == -1) {
335                         fprintf(stderr, "radclient: Request was \"auto\", but request %d in file %s did not contain Packet-Type\n",
336                                 radclient->packet_number, radclient->filename);
337                         return -1;
338                 }
339
340                 radclient->request->code = packet_code;
341         }
342         radclient->request->sockfd = -1;
343
344         return 0;
345 }
346
347
348 /*
349  *      For request handline.
350  */
351 static int filename_cmp(const void *one, const void *two)
352 {
353         return strcmp((const char *) one, (const char *) two);
354 }
355
356 static int filename_walk(void *context, void *data)
357 {
358         const char      *filename = data;
359         radclient_t     *radclient;
360
361         context = context;      /* -Wunused */
362
363         /*
364          *      Initialize the request we're about
365          *      to send.
366          */
367         radclient = radclient_init(filename);
368         if (!radclient) {
369                 exit(1);
370         }
371
372         if (!radclient_head) {
373                 assert(radclient_tail == NULL);
374                 radclient_head = radclient;
375         } else {
376                 assert(radclient_tail->next == NULL);
377                 radclient_tail->next = radclient;
378                 radclient->prev = radclient_tail;
379         }
380
381         /*
382          *      We may have had a list of "radclient" structures
383          *      returned to us.
384          */
385         while (radclient->next) radclient = radclient->next;
386         radclient_tail = radclient;
387
388         return 0;
389 }
390
391
392 /*
393  *      Deallocate packet ID, etc.
394  */
395 static void deallocate_id(radclient_t *radclient)
396 {
397         if (!radclient || !radclient->request ||
398             (radclient->request->id < 0)) {
399                 return;
400         }
401
402         /*
403          *      One more unused RADIUS ID.
404          */
405         lrad_packet_list_id_free(pl, radclient->request);
406         radclient->request->id = -1;
407
408         /*
409          *      If we've already sent a packet, free up the old one,
410          *      and ensure that the next packet has a unique
411          *      authentication vector.
412          */
413         if (radclient->request->data) {
414                 free(radclient->request->data);
415                 radclient->request->data = NULL;
416         }
417
418         if (radclient->reply) rad_free(&radclient->reply);
419 }
420
421
422 static void print_hex(RADIUS_PACKET *packet)
423 {
424         int i;
425
426         if (!packet->data) return;
427
428         printf("  Code:\t\t%u\n", packet->data[0]);
429         printf("  Id:\t\t%u\n", packet->data[1]);
430         printf("  Length:\t%u\n", ((packet->data[2] << 8) |
431                                    (packet->data[3])));
432         printf("  Vector:\t");
433         for (i = 4; i < 20; i++) {
434                 printf("%02x", packet->data[i]);
435         }
436         printf("\n");
437         
438         if (packet->data_len > 20) {
439                 int total;
440                 const uint8_t *ptr;
441                 printf("  Data:");
442
443                 total = packet->data_len - 20;
444                 ptr = packet->data + 20;
445
446                 while (total > 0) {
447                         int attrlen;
448
449                         printf("\t\t");
450                         if (total < 2) { /* too short */
451                                 printf("%02x\n", *ptr);
452                                 break;
453                         }
454
455                         if (ptr[1] > total) { /* too long */
456                                 for (i = 0; i < total; i++) {
457                                         printf("%02x ", ptr[i]);
458                                 }
459                                 break;
460                         }
461
462                         printf("%02x  %02x  ", ptr[0], ptr[1]);
463                         attrlen = ptr[1] - 2;
464                         ptr += 2;
465                         total -= 2;
466
467                         for (i = 0; i < attrlen; i++) {
468                                 if ((i > 0) && ((i & 0x0f) == 0x00))
469                                         printf("\t\t\t");
470                                 printf("%02x ", ptr[i]);
471                                 if ((i & 0x0f) == 0x0f) printf("\n");
472                         }
473
474                         if ((attrlen & 0x0f) != 0x00) printf("\n");
475
476                         ptr += attrlen;
477                         total -= attrlen;
478                 }
479         }
480         fflush(stdout);
481 }
482
483 /*
484  *      Send one packet.
485  */
486 static int send_one_packet(radclient_t *radclient)
487 {
488         assert(radclient->done == 0);
489
490         /*
491          *      Remember when we have to wake up, to re-send the
492          *      request, of we didn't receive a response.
493          */
494         if ((sleep_time == -1) ||
495             (sleep_time > (int) timeout)) {
496                 sleep_time = (int) timeout;
497         }
498
499         /*
500          *      Haven't sent the packet yet.  Initialize it.
501          */
502         if (radclient->request->id == -1) {
503                 int i, rcode;
504
505                 assert(radclient->reply == NULL);
506
507                 /*
508                  *      Didn't find a free packet ID, we're not done,
509                  *      we don't sleep, and we stop trying to process
510                  *      this packet.
511                  */
512         retry:
513                 rcode = lrad_packet_list_id_alloc(pl, radclient->request);
514                 if (rcode < 0) {
515                         int mysockfd;
516
517                         mysockfd = lrad_socket(&client_ipaddr, 0);
518                         if (!mysockfd) {
519                                 fprintf(stderr, "radclient: Can't open new socket\n");
520                                 exit(1);
521                         }
522                         if (!lrad_packet_list_socket_add(pl, mysockfd)) {
523                                 fprintf(stderr, "radclient: Can't add new socket\n");
524                                 exit(1);
525                         }
526                         goto retry;
527                 }
528
529                 if (rcode == 0) {
530                         done = 0;
531                         sleep_time = 0;
532                         return 0;
533                 }
534
535                 assert(radclient->request->id != -1);
536                 assert(radclient->request->data == NULL);
537
538                 for (i = 0; i < 4; i++) {
539                         *((uint32_t *) radclient->request->vector) = lrad_rand();
540                 }
541
542                 /*
543                  *      Update the password, so it can be encrypted with the
544                  *      new authentication vector.
545                  */
546                 if (radclient->password[0] != '\0') {
547                         VALUE_PAIR *vp;
548
549                         if ((vp = pairfind(radclient->request->vps, PW_PASSWORD)) != NULL) {
550                                 strNcpy(vp->vp_strvalue, radclient->password,
551                                         sizeof(vp->vp_strvalue));
552                                 vp->length = strlen(vp->vp_strvalue);
553
554                         } else if ((vp = pairfind(radclient->request->vps, PW_CHAP_PASSWORD)) != NULL) {
555                           /*
556                            *    FIXME: AND there's no CHAP-Challenge,
557                            *           AND vp->length != 17
558                            *           AND rad_chap_encode() != vp->vp_octets
559                            */
560                                 strNcpy(vp->vp_strvalue, radclient->password,
561                                         sizeof(vp->vp_strvalue));
562                                 vp->length = strlen(vp->vp_strvalue);
563
564                                 rad_chap_encode(radclient->request,
565                                                 vp->vp_octets,
566                                                 radclient->request->id, vp);
567                                 vp->length = 17;
568                         }
569                 }
570
571                 radclient->timestamp = time(NULL);
572                 radclient->tries = 1;
573                 radclient->resend++;
574
575                 /*
576                  *      Duplicate found.  Serious error!
577                  */
578                 if (!lrad_packet_list_insert(pl, &radclient->request)) {
579                         assert(0 == 1);
580                 }
581                 
582
583         } else {                /* radclient->request->id >= 0 */
584                 time_t now = time(NULL);
585
586                 /*
587                  *      FIXME: Accounting packets are never retried!
588                  *      The Acct-Delay-Time attribute is updated to
589                  *      reflect the delay, and the packet is re-sent
590                  *      from scratch!
591                  */
592
593                 /*
594                  *      Not time for a retry, do so.
595                  */
596                 if ((now - radclient->timestamp) < timeout) {
597                         /*
598                          *      When we walk over the tree sending
599                          *      packets, we update the minimum time
600                          *      required to sleep.
601                          */
602                         if ((sleep_time == -1) ||
603                             (sleep_time > (now - radclient->timestamp))) {
604                                 sleep_time = now - radclient->timestamp;
605                         }
606                         return 0;
607                 }
608
609                 /*
610                  *      We're not trying later, maybe the packet is done.
611                  */
612                 if (radclient->tries == retries) {
613                         assert(radclient->request->id >= 0);
614                         
615                         /*
616                          *      Delete the request from the tree of
617                          *      outstanding requests.
618                          */
619                         lrad_packet_list_yank(pl, radclient->request);
620
621                         fprintf(stderr, "radclient: no response from server for ID %d socket %d\n", radclient->request->id, radclient->request->sockfd);
622                         deallocate_id(radclient);
623                         
624                         /*
625                          *      Normally we mark it "done" when we've received
626                          *      the response, but this is a special case.
627                          */
628                         if (radclient->resend == resend_count) {
629                                 radclient->done = 1;
630                         }
631                         totallost++;
632                         return -1;
633                 }
634
635                 /*
636                  *      We are trying later.
637                  */
638                 radclient->timestamp = now;
639                 radclient->tries++;
640         }
641
642
643         /*
644          *      Send the packet.
645          */
646         if (rad_send(radclient->request, NULL, secret) < 0) {
647                 fprintf(stderr, "radclient: Failed to send packet for ID %d: %s\n",
648                         radclient->request->id, librad_errstr);
649         }
650
651         if (librad_debug > 2) print_hex(radclient->request);
652
653         return 0;
654 }
655
656 /*
657  *      Receive one packet, maybe.
658  */
659 static int recv_one_packet(int wait_time)
660 {
661         fd_set          set;
662         struct timeval  tv;
663         radclient_t     *radclient;
664         RADIUS_PACKET   *reply, **request_p;
665         volatile int max_fd;
666
667         /* And wait for reply, timing out as necessary */
668         FD_ZERO(&set);
669
670         max_fd = lrad_packet_list_fd_set(pl, &set);
671         if (max_fd < 0) exit(1); /* no sockets to listen on! */
672
673         if (wait_time <= 0) {
674                 tv.tv_sec = 0;
675         } else {
676                 tv.tv_sec = wait_time;
677         }
678         tv.tv_usec = 0;
679
680         /*
681          *      No packet was received.
682          */
683         if (select(max_fd, &set, NULL, NULL, &tv) <= 0) {
684                 return 0;
685         }
686
687         /*
688          *      Look for the packet.
689          */
690         reply = lrad_packet_list_recv(pl, &set);
691         if (!reply) {
692                 fprintf(stderr, "radclient: received bad packet: %s\n",
693                         librad_errstr);
694                 return -1;      /* bad packet */
695         }
696
697         if (librad_debug > 2) print_hex(reply);
698
699         request_p = lrad_packet_list_find_byreply(pl, reply);
700         if (!request_p) {
701                 fprintf(stderr, "radclient: received response to request we did not send. (id=%d socket %d)\n", reply->id, reply->sockfd);
702                 rad_free(&reply);
703                 return -1;      /* got reply to packet we didn't send */
704         }
705         radclient = lrad_packet2myptr(radclient_t, request, request_p);
706         lrad_packet_list_yank(pl, radclient->request);
707         deallocate_id(radclient);
708         radclient->reply = reply;
709
710         /*
711          *      Fails the signature validation: not a real reply.
712          *      FIXME: Silently drop it and listen for another packet.
713          */
714         if (rad_verify(reply, radclient->request, secret) < 0) {
715                 librad_perror("rad_verify");
716                 totallost++;
717                 goto packet_done; /* shared secret is incorrect */
718         }
719
720         /*
721          *      If this fails, we're out of memory.
722          */
723         if (rad_decode(reply, radclient->request, secret) != 0) {
724                 librad_perror("rad_decode");
725                 totallost++;
726                 goto packet_done;
727         }
728
729         /* libradius debug already prints out the value pairs for us */
730         if (!librad_debug && do_output) {
731                 printf("Received response ID %d, code %d, length = %d\n",
732                        reply->id, reply->code, reply->data_len);
733                 vp_printlist(stdout, reply->vps);
734         }
735         if (reply->code != PW_AUTHENTICATION_REJECT) {
736                 totalapp++;
737         } else {
738                 totaldeny++;
739         }
740
741 packet_done:
742         rad_free(&radclient->reply);
743
744         /*
745          *      Once we've sent the packet as many times as requested,
746          *      mark it done.
747          */
748         if (radclient->resend == resend_count) {
749                 assert(lrad_packet_list_find(pl, radclient->request) == NULL);
750                 radclient->done = 1;
751         }
752
753         return 0;
754 }
755
756
757 static int getport(const char *name)
758 {
759         struct  servent         *svp;
760
761         svp = getservbyname (name, "udp");
762         if (!svp) {
763                 return 0;
764         }
765
766         return ntohs(svp->s_port);
767 }
768
769 int main(int argc, char **argv)
770 {
771         char *p;
772         int c;
773         const char *radius_dir = RADDBDIR;
774         char filesecret[256];
775         FILE *fp;
776         int do_summary = 0;
777         int persec = 0;
778         int parallel = 1;
779         radclient_t     *this;
780         int force_af = AF_UNSPEC;
781
782         librad_debug = 0;
783
784         filename_tree = rbtree_create(filename_cmp, NULL, 0);
785         if (!filename_tree) {
786                 fprintf(stderr, "radclient: Out of memory\n");
787                 exit(1);
788         }
789
790         while ((c = getopt(argc, argv, "46c:d:f:hi:n:p:qr:sS:t:vx")) != EOF) switch(c) {
791                 case '4':
792                         force_af = AF_INET;
793                         break;
794                 case '6':
795                         force_af = AF_INET6;
796                         break;
797                 case 'c':
798                         if (!isdigit((int) *optarg))
799                                 usage();
800                         resend_count = atoi(optarg);
801                         break;
802                 case 'd':
803                         radius_dir = optarg;
804                         break;
805                 case 'f':
806                         rbtree_insert(filename_tree, optarg);
807                         break;
808                 case 'i':       /* currently broken */
809                         if (!isdigit((int) *optarg))
810                                 usage();
811                         last_used_id = atoi(optarg);
812                         if ((last_used_id < 0) || (last_used_id > 255)) {
813                                 usage();
814                         }
815                         break;
816
817                 case 'n':
818                         persec = atoi(optarg);
819                         if (persec <= 0) usage();
820                         break;
821
822                         /*
823                          *      Note that sending MANY requests in
824                          *      parallel can over-run the kernel
825                          *      queues, and Linux will happily discard
826                          *      packets.  So even if the server responds,
827                          *      the client may not see the response.
828                          */
829                 case 'p':
830                         parallel = atoi(optarg);
831                         if (parallel <= 0) usage();
832                         break;
833
834                 case 'q':
835                         do_output = 0;
836                         break;
837                 case 'r':
838                         if (!isdigit((int) *optarg))
839                                 usage();
840                         retries = atoi(optarg);
841                         if ((retries == 0) || (retries > 1000)) usage();
842                         break;
843                 case 's':
844                         do_summary = 1;
845                         break;
846                case 'S':
847                        fp = fopen(optarg, "r");
848                        if (!fp) {
849                                fprintf(stderr, "radclient: Error opening %s: %s\n",
850                                        optarg, strerror(errno));
851                                exit(1);
852                        }
853                        if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
854                                fprintf(stderr, "radclient: Error reading %s: %s\n",
855                                        optarg, strerror(errno));
856                                exit(1);
857                        }
858                        fclose(fp);
859
860                        /* truncate newline */
861                        p = filesecret + strlen(filesecret) - 1;
862                        while ((p >= filesecret) &&
863                               (*p < ' ')) {
864                                *p = '\0';
865                                --p;
866                        }
867
868                        if (strlen(filesecret) < 2) {
869                                fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
870                                exit(1);
871                        }
872                        secret = filesecret;
873                        break;
874                 case 't':
875                         if (!isdigit((int) *optarg))
876                                 usage();
877                         timeout = atof(optarg);
878                         break;
879                 case 'v':
880                         printf("radclient: $Id$ built on " __DATE__ " at " __TIME__ "\n");
881                         exit(0);
882                         break;
883                 case 'x':
884                         librad_debug++;
885                         break;
886                 case 'h':
887                 default:
888                         usage();
889                         break;
890         }
891         argc -= (optind - 1);
892         argv += (optind - 1);
893
894         if ((argc < 3)  ||
895             ((secret == NULL) && (argc < 4))) {
896                 usage();
897         }
898
899         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
900                 librad_perror("radclient");
901                 return 1;
902         }
903
904         /*
905          *      Resolve hostname.
906          */
907         server_ipaddr.af = force_af;
908         if (strcmp(argv[1], "-") != 0) {
909                 const char *hostname = argv[1];
910                 const char *portname = argv[1];
911                 char buffer[256];
912
913                 if (*argv[1] == '[') { /* IPv6 URL encoded */
914                         p = strchr(argv[1], ']');
915                         if ((p - argv[1]) >= sizeof(buffer)) {
916                                 usage();
917                         }
918                         
919                         memcpy(buffer, argv[1] + 1, p - argv[1] - 1);
920                         buffer[p - argv[1] - 1] = '\0';
921
922                         hostname = buffer;
923                         portname = p + 1;
924
925                 }
926                 p = strchr(portname, ':');
927                 if (p && (strchr(p + 1, ':') == NULL)) {
928                         *p = '\0';
929                         portname = p + 1;
930                 } else {
931                         portname = NULL;
932                 }
933
934                 if (ip_hton(hostname, force_af, &server_ipaddr) < 0) {
935                         fprintf(stderr, "radclient: Failed to find IP address for host %s: %s\n", hostname, strerror(errno));
936                         exit(1);
937                 }
938
939                 /*
940                  *      Strip port from hostname if needed.
941                  */
942                 if (portname) server_port = atoi(portname);
943         }
944
945         /*
946          *      See what kind of request we want to send.
947          */
948         if (strcmp(argv[2], "auth") == 0) {
949                 if (server_port == 0) server_port = getport("radius");
950                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
951                 packet_code = PW_AUTHENTICATION_REQUEST;
952
953         } else if (strcmp(argv[2], "challenge") == 0) {
954                 if (server_port == 0) server_port = getport("radius");
955                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
956                 packet_code = PW_ACCESS_CHALLENGE;
957
958         } else if (strcmp(argv[2], "acct") == 0) {
959                 if (server_port == 0) server_port = getport("radacct");
960                 if (server_port == 0) server_port = PW_ACCT_UDP_PORT;
961                 packet_code = PW_ACCOUNTING_REQUEST;
962                 do_summary = 0;
963
964         } else if (strcmp(argv[2], "status") == 0) {
965                 if (server_port == 0) server_port = getport("radius");
966                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
967                 packet_code = PW_STATUS_SERVER;
968
969         } else if (strcmp(argv[2], "disconnect") == 0) {
970                 if (server_port == 0) server_port = PW_POD_UDP_PORT;
971                 packet_code = PW_DISCONNECT_REQUEST;
972
973         } else if (strcmp(argv[2], "coa") == 0) {
974                 if (server_port == 0) server_port = PW_POD_UDP_PORT;
975                 packet_code = PW_COA_REQUEST;
976
977         } else if (strcmp(argv[2], "auto") == 0) {
978                 packet_code = -1;
979
980         } else if (isdigit((int) argv[2][0])) {
981                 if (server_port == 0) server_port = getport("radius");
982                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
983                 packet_code = atoi(argv[2]);
984         } else {
985                 usage();
986         }
987
988         /*
989          *      Add the secret.
990          */
991         if (argv[3]) secret = argv[3];
992
993         /*
994          *      If no '-f' is specified, we're reading from stdin.
995          */
996         if (rbtree_num_elements(filename_tree) == 0) {
997                 rbtree_insert(filename_tree, "-");
998         }
999
1000         /*
1001          *      Walk over the list of filenames, creating the requests.
1002          */
1003         if (rbtree_walk(filename_tree, InOrder, filename_walk, NULL) != 0) {
1004                 exit(1);
1005         }
1006
1007         /*
1008          *      No packets read.  Die.
1009          */
1010         if (!radclient_head) {
1011                 fprintf(stderr, "radclient: Nothing to send.\n");
1012                 exit(1);
1013         }
1014
1015         /*
1016          *      Bind to the first specified IP address and port.
1017          *      This means we ignore later ones.
1018          */
1019         if (radclient_head->request->src_ipaddr.af == AF_UNSPEC) {
1020                 memset(&client_ipaddr, 0, sizeof(client_ipaddr));
1021                 client_ipaddr.af = server_ipaddr.af;
1022                 client_port = 0;
1023         } else {
1024                 client_ipaddr = radclient_head->request->src_ipaddr;
1025                 client_port = radclient_head->request->src_port;
1026         }
1027         sockfd = lrad_socket(&client_ipaddr, client_port);
1028         if (sockfd < 0) {
1029                 fprintf(stderr, "radclient: socket: %s\n", librad_errstr);
1030                 exit(1);
1031         }
1032
1033         pl = lrad_packet_list_create(1);
1034         if (!pl) {
1035                 fprintf(stderr, "radclient: Out of memory\n");
1036                 exit(1);
1037         }
1038
1039         if (!lrad_packet_list_socket_add(pl, sockfd)) {
1040                 fprintf(stderr, "radclient: Out of memory\n");
1041                 exit(1);
1042         }
1043
1044         /*
1045          *      Walk over the list of packets, sanity checking
1046          *      everything.
1047          */
1048         for (this = radclient_head; this != NULL; this = this->next) {
1049                 this->request->src_ipaddr = client_ipaddr;
1050                 this->request->src_port = client_port;
1051                 if (radclient_sane(this) != 0) {
1052                         exit(1);
1053                 }
1054         }
1055
1056         /*
1057          *      Walk over the packets to send, until
1058          *      we're all done.
1059          *
1060          *      FIXME: This currently busy-loops until it receives
1061          *      all of the packets.  It should really have some sort of
1062          *      send packet, get time to wait, select for time, etc.
1063          *      loop.
1064          */
1065         do {
1066                 int n = parallel;
1067                 radclient_t *next;
1068                 const char *filename = NULL;
1069
1070                 done = 1;
1071                 sleep_time = -1;
1072
1073                 /*
1074                  *      Walk over the packets, sending them.
1075                  */
1076
1077                 for (this = radclient_head; this != NULL; this = next) {
1078                         next = this->next;
1079
1080                         /*
1081                          *      If there's a packet to receive,
1082                          *      receive it, but don't wait for a
1083                          *      packet.
1084                          */
1085                         recv_one_packet(0);
1086
1087                         /*
1088                          *      This packet is done.  Delete it.
1089                          */
1090                         if (this->done) {
1091                                 radclient_free(this);
1092                                 continue;
1093                         }
1094
1095                         /*
1096                          *      Packets from multiple '-f' are sent
1097                          *      in parallel.
1098                          *
1099                          *      Packets from one file are sent in
1100                          *      series, unless '-p' is specified, in
1101                          *      which case N packets from each file
1102                          *      are sent in parallel.
1103                          */
1104                         if (this->filename != filename) {
1105                                 filename = this->filename;
1106                                 n = parallel;
1107                         }
1108
1109                         if (n > 0) {
1110                                 n--;
1111
1112                                 /*
1113                                  *      Send the current packet.
1114                                  */
1115                                 send_one_packet(this);
1116
1117                                 /*
1118                                  *      Wait a little before sending
1119                                  *      the next packet, if told to.
1120                                  */
1121                                 if (persec) {
1122                                         struct timeval tv;
1123
1124                                         /*
1125                                          *      Don't sleep elsewhere.
1126                                          */
1127                                         sleep_time = 0;
1128
1129                                         if (persec == 1) {
1130                                                 tv.tv_sec = 1;
1131                                                 tv.tv_usec = 0;
1132                                         } else {
1133                                                 tv.tv_sec = 0;
1134                                                 tv.tv_usec = 1000000/persec;
1135                                         }
1136                                         
1137                                         /*
1138                                          *      Sleep for milliseconds,
1139                                          *      portably.
1140                                          *
1141                                          *      If we get an error or
1142                                          *      a signal, treat it like
1143                                          *      a normal timeout.
1144                                          */
1145                                         select(0, NULL, NULL, NULL, &tv);
1146                                 }
1147
1148                                 /*
1149                                  *      If we haven't sent this packet
1150                                  *      often enough, we're not done,
1151                                  *      and we shouldn't sleep.
1152                                  */
1153                                 if (this->resend < resend_count) {
1154                                         done = 0;
1155                                         sleep_time = 0;
1156                                 }
1157                         } else { /* haven't sent this packet, we're not done */
1158                                 assert(this->done == 0);
1159                                 assert(this->reply == NULL);
1160                                 done = 0;
1161                         }
1162                 }
1163
1164                 /*
1165                  *      Still have outstanding requests.
1166                  */
1167                 if (lrad_packet_list_num_elements(pl) > 0) {
1168                         done = 0;
1169                 } else {
1170                         sleep_time = 0;
1171                 }
1172
1173                 /*
1174                  *      Nothing to do until we receive a request, so
1175                  *      sleep until then.  Once we receive one packet,
1176                  *      we go back, and walk through the whole list again,
1177                  *      sending more packets (if necessary), and updating
1178                  *      the sleep time.
1179                  */
1180                 if (!done && (sleep_time > 0)) {
1181                         recv_one_packet(sleep_time);
1182                 }
1183         } while (!done);
1184
1185         rbtree_free(filename_tree);
1186         lrad_packet_list_free(pl);
1187
1188         if (do_summary) {
1189                 printf("\n\t   Total approved auths:  %d\n", totalapp);
1190                 printf("\t     Total denied auths:  %d\n", totaldeny);
1191                 printf("\t       Total lost auths:  %d\n", totallost);
1192         }
1193
1194         return 0;
1195 }