Octets fixes.
[freeradius.git] / src / main / radclient.c
1 /*
2  * radclient.c  General radius packet debug tool.
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * Copyright 2000  The FreeRADIUS server project
21  * Copyright 2000  Miquel van Smoorenburg <miquels@cistron.nl>
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  */
24 static const char rcsid[] = "$Id$";
25
26 #include "autoconf.h"
27
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 "conf.h"
55 #include "radpaths.h"
56 #include "missing.h"
57 #include "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 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 /*
474  *      Send one packet.
475  */
476 static int send_one_packet(radclient_t *radclient)
477 {
478         int i;
479
480         assert(radclient->done == 0);
481
482         /*
483          *      Remember when we have to wake up, to re-send the
484          *      request, of we didn't receive a response.
485          */
486         if ((sleep_time == -1) ||
487             (sleep_time > (int) timeout)) {
488                 sleep_time = (int) timeout;
489         }
490
491         /*
492          *      Haven't sent the packet yet.  Initialize it.
493          */
494         if (radclient->request->id == -1) {
495                 int found = 0;
496
497                 assert(radclient->reply == NULL);
498
499                 /*
500                  *      Find a free packet Id
501                  */
502                 for (i = 0; i < 256; i++) {
503                         if (radius_id[(last_used_id + i) & 0xff] == 0) {
504                                 last_used_id = (last_used_id + i) & 0xff;
505                                 radius_id[last_used_id] = 1;
506                                 radclient->request->id = last_used_id++;
507                                 found = 1;
508                                 break;
509                         }
510                 }
511
512                 /*
513                  *      Didn't find a free packet ID, we're not done,
514                  *      we don't sleep, and we stop trying to process
515                  *      this packet.
516                  */
517                 if (!found) {
518                         done = 0;
519                         sleep_time = 0;
520                         return 0;
521                 }
522
523                 assert(radclient->request->id != -1);
524                 assert(radclient->request->data == NULL);
525
526                 librad_md5_calc(radclient->request->vector, radclient->request->vector,
527                                 sizeof(radclient->request->vector));
528
529                 /*
530                  *      Update the password, so it can be encrypted with the
531                  *      new authentication vector.
532                  */
533                 if (radclient->password[0] != '\0') {
534                         VALUE_PAIR *vp;
535
536                         if ((vp = pairfind(radclient->request->vps, PW_PASSWORD)) != NULL) {
537                                 strNcpy(vp->vp_strvalue, radclient->password,
538                                         sizeof(vp->vp_strvalue));
539                                 vp->length = strlen(vp->vp_strvalue);
540
541                         } else if ((vp = pairfind(radclient->request->vps, PW_CHAP_PASSWORD)) != NULL) {
542                                 strNcpy(vp->vp_strvalue, radclient->password,
543                                         sizeof(vp->vp_strvalue));
544                                 vp->length = strlen(vp->vp_strvalue);
545
546                                 rad_chap_encode(radclient->request,
547                                                 vp->vp_octets,
548                                                 radclient->request->id, vp);
549                                 vp->length = 17;
550                         }
551                 }
552
553                 radclient->timestamp = time(NULL);
554                 radclient->tries = 1;
555                 radclient->resend++;
556
557                 /*
558                  *      Duplicate found.  Serious error!
559                  */
560                 if (rbtree_insert(request_tree, radclient) == 0) {
561                         assert(0 == 1);
562                 }
563
564         } else {                /* radclient->request->id >= 0 */
565                 time_t now = time(NULL);
566
567                 /*
568                  *      FIXME: Accounting packets are never retried!
569                  *      The Acct-Delay-Time attribute is updated to
570                  *      reflect the delay, and the packet is re-sent
571                  *      from scratch!
572                  */
573
574                 /*
575                  *      Not time for a retry, do so.
576                  */
577                 if ((now - radclient->timestamp) < timeout) {
578                         /*
579                          *      When we walk over the tree sending
580                          *      packets, we update the minimum time
581                          *      required to sleep.
582                          */
583                         if ((sleep_time == -1) ||
584                             (sleep_time > (now - radclient->timestamp))) {
585                                 sleep_time = now - radclient->timestamp;
586                         }
587                         return 0;
588                 }
589
590                 /*
591                  *      We're not trying later, maybe the packet is done.
592                  */
593                 if (radclient->tries == retries) {
594                         rbnode_t *node;
595                         assert(radclient->request->id >= 0);
596                         
597                         /*
598                          *      Delete the request from the tree of
599                          *      outstanding requests.
600                          */
601                         node = rbtree_find(request_tree, radclient);
602                         assert(node != NULL);
603                         
604                         fprintf(stderr, "radclient: no response from server for ID %d\n", radclient->request->id);
605                         rbtree_delete(request_tree, node);
606                         
607                         /*
608                          *      Normally we mark it "done" when we've received
609                          *      the response, but this is a special case.
610                          */
611                         if (radclient->resend == resend_count) {
612                                 radclient->done = 1;
613                         }
614                         totallost++;
615                         return -1;
616                 }
617
618                 /*
619                  *      We are trying later.
620                  */
621                 radclient->timestamp = now;
622                 radclient->tries++;
623         }
624
625
626         /*
627          *      Send the packet.
628          */
629         if (rad_send(radclient->request, NULL, secret) < 0) {
630                 fprintf(stderr, "radclient: Failed to send packet for ID %d: %s\n",
631                         radclient->request->id, librad_errstr);
632         }
633
634         return 0;
635 }
636
637 /*
638  *      Receive one packet, maybe.
639  */
640 static int recv_one_packet(int wait_time)
641 {
642         fd_set          set;
643         struct timeval  tv;
644         radclient_t     myclient, *radclient;
645         RADIUS_PACKET   myrequest, *reply;
646         rbnode_t        *node;
647
648
649         /* And wait for reply, timing out as necessary */
650         FD_ZERO(&set);
651         FD_SET(sockfd, &set);
652
653         if (wait_time <= 0) {
654                 tv.tv_sec = 0;
655         } else {
656                 tv.tv_sec = wait_time;
657         }
658         tv.tv_usec = 0;
659
660         /*
661          *      No packet was received.
662          */
663         if (select(sockfd + 1, &set, NULL, NULL, &tv) != 1) {
664                 return 0;
665         }
666
667         /*
668          *      Look for the packet.
669          */
670         reply = rad_recv(sockfd);
671         if (!reply) {
672                 fprintf(stderr, "radclient: received bad packet: %s\n",
673                         librad_errstr);
674                 return -1;      /* bad packet */
675         }
676
677         myclient.request = &myrequest;
678         myrequest.id = reply->id;
679         myrequest.dst_ipaddr = reply->src_ipaddr;
680         myrequest.dst_port = reply->src_port;
681
682         node = rbtree_find(request_tree, &myclient);
683         if (!node) {
684                 fprintf(stderr, "radclient: received response to request we did not send.\n");
685                 rad_free(&reply);
686                 return -1;      /* got reply to packet we didn't send */
687         }
688
689         radclient = rbtree_node2data(request_tree, node);
690         assert(radclient != NULL);
691         rbtree_delete(request_tree, node);
692         assert(radclient->request->id == -1);
693         assert(radclient->request->data == NULL);
694
695         assert(radclient->reply == NULL);
696         radclient->reply = reply;
697
698         /*
699          *      FIXME: Do stuff to process the reply.
700          */
701         if (rad_decode(reply, radclient->request, secret) != 0) {
702                 librad_perror("rad_decode");
703                 rad_free(&radclient->reply);
704                 totallost++;
705                 return -1;
706         }
707
708         /* libradius debug already prints out the value pairs for us */
709         if (!librad_debug && do_output) {
710                 printf("Received response ID %d, code %d, length = %d\n",
711                        reply->id, reply->code, reply->data_len);
712                 vp_printlist(stdout, reply->vps);
713         }
714         if (reply->code != PW_AUTHENTICATION_REJECT) {
715                 totalapp++;
716         } else {
717                 totaldeny++;
718         }
719
720         if (radclient->reply) rad_free(&radclient->reply);
721
722         /*
723          *      Once we've sent the packet as many times as requested,
724          *      mark it done.
725          */
726         if (radclient->resend == resend_count) {
727                 assert((node = rbtree_find(request_tree, radclient)) == NULL);
728                 radclient->done = 1;
729         }
730
731         return 0;
732 }
733
734
735 static int getport(const char *name)
736 {
737         struct  servent         *svp;
738
739         svp = getservbyname (name, "udp");
740         if (!svp) {
741                 return 0;
742         }
743
744         return ntohs(svp->s_port);
745 }
746
747 int main(int argc, char **argv)
748 {
749         char *p;
750         int c;
751         const char *radius_dir = RADDBDIR;
752         char filesecret[256];
753         FILE *fp;
754         int do_summary = 0;
755         int persec = 0;
756         int parallel = 1;
757         radclient_t     *this;
758         int force_af = AF_UNSPEC;
759         int len = 0;
760         struct sockaddr_storage ss;
761         struct sockaddr_in *s4;
762
763         librad_debug = 0;
764
765         filename_tree = rbtree_create(filename_cmp, NULL, 0);
766         if (!filename_tree) {
767                 fprintf(stderr, "radclient: Out of memory\n");
768                 exit(1);
769         }
770
771         request_tree = rbtree_create(request_cmp, request_free, 0);
772         if (!request_tree) {
773                 fprintf(stderr, "radclient: Out of memory\n");
774                 exit(1);
775         }
776
777         while ((c = getopt(argc, argv, "46c:d:f:hi:n:p:qr:sS:t:vx")) != EOF) switch(c) {
778                 case '4':
779                         force_af = AF_INET;
780                         break;
781                 case '6':
782                         force_af = AF_INET6;
783                         break;
784                 case 'c':
785                         if (!isdigit((int) *optarg))
786                                 usage();
787                         resend_count = atoi(optarg);
788                         break;
789                 case 'd':
790                         radius_dir = optarg;
791                         break;
792                 case 'f':
793                         rbtree_insert(filename_tree, optarg);
794                         break;
795                 case 'i':
796                         if (!isdigit((int) *optarg))
797                                 usage();
798                         last_used_id = atoi(optarg);
799                         if ((last_used_id < 0) || (last_used_id > 255)) {
800                                 usage();
801                         }
802                         break;
803
804                 case 'n':
805                         persec = atoi(optarg);
806                         if (persec <= 0) usage();
807                         break;
808
809                 case 'p':
810                         parallel = atoi(optarg);
811                         if (parallel <= 0) usage();
812                         break;
813
814                 case 'q':
815                         do_output = 0;
816                         break;
817                 case 'r':
818                         if (!isdigit((int) *optarg))
819                                 usage();
820                         retries = atoi(optarg);
821                         if ((retries == 0) || (retries > 1000)) usage();
822                         break;
823                 case 's':
824                         do_summary = 1;
825                         break;
826                case 'S':
827                        fp = fopen(optarg, "r");
828                        if (!fp) {
829                                fprintf(stderr, "radclient: Error opening %s: %s\n",
830                                        optarg, strerror(errno));
831                                exit(1);
832                        }
833                        if (fgets(filesecret, sizeof(filesecret), fp) == NULL) {
834                                fprintf(stderr, "radclient: Error reading %s: %s\n",
835                                        optarg, strerror(errno));
836                                exit(1);
837                        }
838                        fclose(fp);
839
840                        /* truncate newline */
841                        p = filesecret + strlen(filesecret) - 1;
842                        while ((p >= filesecret) &&
843                               (*p < ' ')) {
844                                *p = '\0';
845                                --p;
846                        }
847
848                        if (strlen(filesecret) < 2) {
849                                fprintf(stderr, "radclient: Secret in %s is too short\n", optarg);
850                                exit(1);
851                        }
852                        secret = filesecret;
853                        break;
854                 case 't':
855                         if (!isdigit((int) *optarg))
856                                 usage();
857                         timeout = atof(optarg);
858                         break;
859                 case 'v':
860                         printf("radclient: $Id$ built on " __DATE__ " at " __TIME__ "\n");
861                         exit(0);
862                         break;
863                 case 'x':
864                         librad_debug++;
865                         break;
866                 case 'h':
867                 default:
868                         usage();
869                         break;
870         }
871         argc -= (optind - 1);
872         argv += (optind - 1);
873
874         if ((argc < 3)  ||
875             ((secret == NULL) && (argc < 4))) {
876                 usage();
877         }
878
879         if (dict_init(radius_dir, RADIUS_DICTIONARY) < 0) {
880                 librad_perror("radclient");
881                 return 1;
882         }
883
884         /*
885          *      Resolve hostname.
886          */
887         server_ipaddr.af = force_af;
888         if (strcmp(argv[1], "-") != 0) {
889                 const char *hostname = argv[1];
890                 const char *portname = argv[1];
891                 char buffer[256];
892
893                 if (*argv[1] == '[') { /* IPv6 URL encoded */
894                         p = strchr(argv[1], ']');
895                         if ((p - argv[1]) >= sizeof(buffer)) {
896                                 usage();
897                         }
898                         
899                         memcpy(buffer, argv[1] + 1, p - argv[1] - 1);
900                         buffer[p - argv[1] - 1] = '\0';
901
902                         hostname = buffer;
903                         portname = p + 1;
904
905                 }
906                 p = strchr(portname, ':');
907                 if (p && (strchr(p + 1, ':') == NULL)) {
908                         *p = '\0';
909                         portname = p + 1;
910                 } else {
911                         portname = NULL;
912                 }
913
914                 if (ip_hton(hostname, force_af, &server_ipaddr) < 0) {
915                         fprintf(stderr, "radclient: Failed to find IP address for host %s: %s\n", argv[1], strerror(errno));
916                         exit(1);
917                 }
918
919                 /*
920                  *      Strip port from hostname if needed.
921                  */
922                 if (portname) server_port = atoi(portname);
923         }
924
925         memset(radius_id, 0, sizeof(radius_id));
926
927         /*
928          *      See what kind of request we want to send.
929          */
930         if (strcmp(argv[2], "auth") == 0) {
931                 if (server_port == 0) server_port = getport("radius");
932                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
933                 packet_code = PW_AUTHENTICATION_REQUEST;
934
935         } else if (strcmp(argv[2], "challenge") == 0) {
936                 if (server_port == 0) server_port = getport("radius");
937                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
938                 packet_code = PW_ACCESS_CHALLENGE;
939
940         } else if (strcmp(argv[2], "acct") == 0) {
941                 if (server_port == 0) server_port = getport("radacct");
942                 if (server_port == 0) server_port = PW_ACCT_UDP_PORT;
943                 packet_code = PW_ACCOUNTING_REQUEST;
944                 do_summary = 0;
945
946         } else if (strcmp(argv[2], "status") == 0) {
947                 if (server_port == 0) server_port = getport("radius");
948                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
949                 packet_code = PW_STATUS_SERVER;
950
951         } else if (strcmp(argv[2], "disconnect") == 0) {
952                 if (server_port == 0) server_port = PW_POD_UDP_PORT;
953                 packet_code = PW_DISCONNECT_REQUEST;
954
955         } else if (strcmp(argv[2], "auto") == 0) {
956                 packet_code = -1;
957
958         } else if (isdigit((int) argv[2][0])) {
959                 if (server_port == 0) server_port = getport("radius");
960                 if (server_port == 0) server_port = PW_AUTH_UDP_PORT;
961                 packet_code = atoi(argv[2]);
962         } else {
963                 usage();
964         }
965
966         /*
967          *      Add the secret.
968          */
969         if (argv[3]) secret = argv[3];
970
971         /*
972          *      If no '-f' is specified, we're reading from stdin.
973          */
974         if (rbtree_num_elements(filename_tree) == 0) {
975                 rbtree_insert(filename_tree, "-");
976         }
977
978         /*
979          *      Walk over the list of filenames, creating the requests.
980          */
981         if (rbtree_walk(filename_tree, InOrder, filename_walk, NULL) != 0) {
982                 exit(1);
983         }
984
985         /*
986          *      No packets read.  Die.
987          */
988         if (!radclient_head) {
989                 fprintf(stderr, "radclient: Nothing to send.\n");
990                 exit(1);
991         }
992
993         /*
994          * Bind only if Packet-Src-IP(v6)Address Attribute is found
995          */
996         switch (radclient_head->request->src_ipaddr.af) {
997         case AF_UNSPEC:
998         default:
999                 /*
1000                  *      Grab the socket.
1001                  */
1002                 if ((sockfd = socket(server_ipaddr.af, SOCK_DGRAM, 0)) < 0) {
1003                         perror("radclient: socket: ");
1004                         exit(1);
1005                 }
1006                 break;
1007
1008 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1009         case AF_INET6:
1010                 {
1011                         struct sockaddr_in6 *s6;
1012                         s6 = (struct sockaddr_in6 *)&ss;
1013                         len = sizeof(struct sockaddr_in6);
1014                         s6->sin6_family = AF_INET6;
1015                         s6->sin6_flowinfo = 0;
1016                         s6->sin6_port = htons(radclient_head->request->src_port);
1017                         memcpy(&s6->sin6_addr, &radclient_head->request->src_ipaddr.ipaddr, 16);
1018                 }
1019                 goto sock_bind;
1020 #endif
1021
1022         case AF_INET:
1023                 s4 = (struct sockaddr_in *)&ss;
1024                 len = sizeof(struct sockaddr_in);
1025                 s4->sin_family = AF_INET;
1026                 s4->sin_port = htons(radclient_head->request->src_port);
1027                 memcpy(&s4->sin_addr, &radclient_head->request->src_ipaddr.ipaddr, 4);
1028                 goto sock_bind;
1029
1030         sock_bind:
1031                 if ((sockfd = socket(radclient_head->request->src_ipaddr.af,
1032                                  SOCK_DGRAM, 0)) < 0) {
1033
1034                         perror("radclient: socket: ");
1035                         exit(1);
1036                 }
1037                 if (bind(sockfd, (struct sockaddr *)&ss, len) < 0) {
1038                         perror("radclient: bind: ");
1039                         exit(1);
1040                 }
1041                 break;
1042         }
1043
1044         /*
1045          *      Walk over the list of packets, sanity checking
1046          *      everything.
1047          */
1048         for (this = radclient_head; this != NULL; this = this->next) {
1049                 if (radclient_sane(this) != 0) {
1050                         exit(1);
1051                 }
1052         }
1053
1054         if (last_used_id < 0) last_used_id = getpid() & 0xff;
1055
1056         /*
1057          *      Walk over the packets to send, until
1058          *      we're all done.
1059          *
1060          *      FIXME: This currently busy-loops until it receives
1061          *      all of the packets.  It should really have some sort of
1062          *      send packet, get time to wait, select for time, etc.
1063          *      loop.
1064          */
1065         do {
1066                 int n = parallel;
1067                 radclient_t *next;
1068                 const char *filename = NULL;
1069
1070                 done = 1;
1071                 sleep_time = -1;
1072
1073                 /*
1074                  *      Walk over the packets, sending them.
1075                  */
1076
1077                 for (this = radclient_head; this != NULL; this = next) {
1078                         next = this->next;
1079
1080                         /*
1081                          *      If there's a packet to receive,
1082                          *      receive it, but don't wait for a
1083                          *      packet.
1084                          */
1085                         recv_one_packet(0);
1086
1087                         /*
1088                          *      This packet is done.  Delete it.
1089                          */
1090                         if (this->done) {
1091                                 radclient_free(this);
1092                                 continue;
1093                         }
1094
1095                         /*
1096                          *      Packets from multiple '-f' are sent
1097                          *      in parallel.
1098                          *
1099                          *      Packets from one file are sent in
1100                          *      series, unless '-p' is specified, in
1101                          *      which case N packets from each file
1102                          *      are sent in parallel.
1103                          */
1104                         if (this->filename != filename) {
1105                                 filename = this->filename;
1106                                 n = parallel;
1107                         }
1108
1109                         if (n > 0) {
1110                                 n--;
1111
1112                                 /*
1113                                  *      Send the current packet.
1114                                  */
1115                                 send_one_packet(this);
1116
1117                                 /*
1118                                  *      Wait a little before sending
1119                                  *      the next packet, if told to.
1120                                  */
1121                                 if (persec) {
1122                                         struct timeval tv;
1123
1124                                         /*
1125                                          *      Don't sleep elsewhere.
1126                                          */
1127                                         sleep_time = 0;
1128
1129                                         if (persec == 1) {
1130                                                 tv.tv_sec = 1;
1131                                                 tv.tv_usec = 0;
1132                                         } else {
1133                                                 tv.tv_sec = 0;
1134                                                 tv.tv_usec = 1000000/persec;
1135                                         }
1136                                         
1137                                         /*
1138                                          *      Sleep for milliseconds,
1139                                          *      portably.
1140                                          *
1141                                          *      If we get an error or
1142                                          *      a signal, treat it like
1143                                          *      a normal timeout.
1144                                          */
1145                                         select(0, NULL, NULL, NULL, &tv);
1146                                 }
1147
1148                                 /*
1149                                  *      If we haven't sent this packet
1150                                  *      often enough, we're not done,
1151                                  *      and we shouldn't sleep.
1152                                  */
1153                                 if (this->resend < resend_count) {
1154                                         done = 0;
1155                                         sleep_time = 0;
1156                                 }
1157                         } else { /* haven't sent this packet, we're not done */
1158                                 assert(this->done == 0);
1159                                 assert(this->reply == NULL);
1160                                 done = 0;
1161                         }
1162                 }
1163
1164                 /*
1165                  *      Still have outstanding requests.
1166                  */
1167                 if (rbtree_num_elements(request_tree) > 0) {
1168                         done = 0;
1169                 } else {
1170                         sleep_time = 0;
1171                 }
1172
1173                 /*
1174                  *      Nothing to do until we receive a request, so
1175                  *      sleep until then.  Once we receive one packet,
1176                  *      we go back, and walk through the whole list again,
1177                  *      sending more packets (if necessary), and updating
1178                  *      the sleep time.
1179                  */
1180                 if (!done && (sleep_time > 0)) {
1181                         recv_one_packet(sleep_time);
1182                 }
1183         } while (!done);
1184
1185         rbtree_free(filename_tree);
1186         rbtree_free(request_tree);
1187
1188         if (do_summary) {
1189                 printf("\n\t   Total approved auths:  %d\n", totalapp);
1190                 printf("\t     Total denied auths:  %d\n", totaldeny);
1191                 printf("\t       Total lost auths:  %d\n", totallost);
1192         }
1193
1194         return 0;
1195 }