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