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