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