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