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