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