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