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