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