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