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