Absolutely horrible hacks to get radmin on a TCP socket.
[freeradius.git] / src / main / radmin.c
1 /*
2  * radmin.c     RADIUS Administration 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 2008   The FreeRADIUS server project
21  * Copyright 2008   Alan DeKok <aland@deployingradius.com>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/radpaths.h>
29
30 #ifdef HAVE_SYS_SOCKET_H
31 #include <sys/socket.h>
32 #endif
33
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
36 #endif
37
38 #ifdef HAVE_SYS_UN_H
39 #include <sys/un.h>
40 #ifndef SUN_LEN
41 #define SUN_LEN(su)  (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
42 #endif
43 #endif
44
45 #ifdef HAVE_GETOPT_H
46 #include <getopt.h>
47 #endif
48
49 #ifdef HAVE_SYS_STAT_H
50 #include <sys/stat.h>
51 #endif
52
53 #ifdef HAVE_LIBREADLINE
54
55 #if defined(HAVE_READLINE_READLINE_H)
56 #include <readline/readline.h>
57 #define USE_READLINE (1)
58 #elif defined(HAVE_READLINE_H)
59 #include <readline.h>
60 #define USE_READLINE (1)
61 #endif /* !defined(HAVE_READLINE_H) */
62
63 #endif /* HAVE_LIBREADLINE */
64
65 #ifdef HAVE_READLINE_HISTORY
66 #if defined(HAVE_READLINE_HISTORY_H)
67 #include <readline/history.h>
68 #define USE_READLINE_HISTORY (1)
69 #elif defined(HAVE_HISTORY_H)
70 #include <history.h>
71 #define USE_READLINE_HISTORY (1)
72 #endif /* defined(HAVE_READLINE_HISTORY_H) */
73
74 #endif /* HAVE_READLINE_HISTORY */
75
76 /*
77  *      For configuration file stuff.
78  */
79 char *radius_dir = RADDBDIR;
80 const char *progname = "radmin";
81
82 /*
83  *      The rest of this is because the conffile.c, etc. assume
84  *      they're running inside of the server.  And we don't (yet)
85  *      have a "libfreeradius-server", or "libfreeradius-util".
86  */
87 int debug_flag = 0;
88 struct main_config_t mainconfig;
89 char *request_log_file = NULL;
90 char *debug_log_file = NULL;
91 int radius_xlat(UNUSED char *out, UNUSED int outlen, UNUSED const char *fmt,
92                 UNUSED REQUEST *request, UNUSED RADIUS_ESCAPE_STRING func)
93 {
94         return -1;
95 }
96 int check_config = FALSE;
97
98 static FILE *outputfp = NULL;
99 static int echo = FALSE;
100 static const char *secret = "testing123";
101
102 static int fr_domain_socket(const char *path)
103 {
104         int sockfd = -1;
105 #ifdef HAVE_SYS_UN_H
106         size_t len;
107         socklen_t socklen;
108         struct sockaddr_un saremote;
109
110         len = strlen(path);
111         if (len >= sizeof(saremote.sun_path)) {
112                 fprintf(stderr, "%s: Path too long in filename\n", progname);
113                 return -1;
114         }
115
116         if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
117                 fprintf(stderr, "%s: Failed creating socket: %s\n",
118                         progname, strerror(errno));
119                 return -1;
120         }
121
122         saremote.sun_family = AF_UNIX;
123         memcpy(saremote.sun_path, path, len + 1); /* SUN_LEN does strlen */
124         
125         socklen = SUN_LEN(&saremote);
126
127         if (connect(sockfd, (struct sockaddr *)&saremote, socklen) < 0) {
128                 struct stat buf;
129
130                 close(sockfd);
131                 fprintf(stderr, "%s: Failed connecting to %s: %s\n",
132                         progname, path, strerror(errno));
133
134                 /*
135                  *      The file doesn't exist.  Tell the user how to
136                  *      fix it.
137                  */
138                 if ((stat(path, &buf) < 0) &&
139                     (errno == ENOENT)) {
140                         fprintf(stderr, "  Perhaps you need to run the commands:\n\tcd /etc/raddb\n\tln -s sites-available/control-socket sites-enabled/control-socket\n  and then re-start the server?\n");
141                 }
142
143                 return -1;
144         }
145
146 #ifdef O_NONBLOCK
147         {
148                 int flags;
149                 
150                 if ((flags = fcntl(sockfd, F_GETFL, NULL)) < 0)  {
151                         fprintf(stderr, "%s: Failure getting socket flags: %s",
152                                 progname, strerror(errno));
153                         close(sockfd);
154                         return -1;
155                 }
156                 
157                 flags |= O_NONBLOCK;
158                 if( fcntl(sockfd, F_SETFL, flags) < 0) {
159                         fprintf(stderr, "%s: Failure setting socket flags: %s",
160                                 progname, strerror(errno));
161                         close(sockfd);
162                         return -1;
163                 }
164         }
165 #endif
166 #endif
167         return sockfd;
168 }
169
170 static int client_socket(const char *server)
171 {
172         int sockfd, port;
173         fr_ipaddr_t ipaddr;
174         char *p, buffer[1024];
175
176         strlcpy(buffer, server, sizeof(buffer));
177
178         p = strchr(buffer, ':');
179         if (!p) {
180                 port = PW_RADMIN_PORT;
181         } else {
182                 port = atoi(p + 1);
183                 *p = '\0';
184         }
185
186         if (ip_hton(buffer, AF_INET, &ipaddr) < 0) {
187                 fprintf(stderr, "%s: Failed looking up host %s: %s\n",
188                         progname, buffer, strerror(errno));
189                 exit(1);
190         }
191
192         sockfd = fr_tcp_client_socket(NULL, &ipaddr, port);
193         if (sockfd < 0) {
194                 fprintf(stderr, "%s: Failed opening socket %s: %s\n",
195                         progname, server, strerror(errno));
196                 exit(1);
197         }
198         
199         return sockfd;
200 }
201
202 static void do_challenge(int sockfd)
203 {
204         ssize_t total, r;
205         uint8_t challenge[16];
206
207         for (total = 0; total < sizeof(challenge); ) {
208                 r = read(sockfd, challenge + total, sizeof(challenge) - total);
209                 if (r == 0) exit(1);
210                 
211                 if (r < 0) {
212 #ifdef ECONNRESET
213                         if (errno == ECONNRESET) {
214                                 fprintf(stderr, "%s: Connection reset",
215                                         progname);
216                                 exit(1);
217                         }
218 #endif
219                         if (errno == EINTR) continue;
220                         
221                         fprintf(stderr, "%s: Failed reading data: %s\n",
222                                 progname, strerror(errno));
223                         exit(1);
224                 }
225                 total += r;
226                 fflush(stdout);
227         }
228
229         fr_hmac_md5(secret, strlen(secret), challenge, sizeof(challenge),
230                     challenge);
231
232         write(sockfd, challenge, sizeof(challenge));
233 }
234
235
236 static int usage(void)
237 {
238         printf("Usage: %s [ args ]\n", progname);
239         printf("  -d raddb_dir    Configuration files are in \"raddbdir/*\".\n");
240         printf("  -e command      Execute 'command' and then exit.\n");
241         printf("  -E              Echo commands as they are being executed.\n");
242         printf("  -f socket_file  Open socket_file directly, without reading radius.conf\n");
243         printf("  -h              Print usage help information.\n");
244         printf("  -i input_file   Read commands from 'input_file'.\n");
245         printf("  -n name         Read raddb/name.conf instead of raddb/radiusd.conf\n");
246         printf("  -o output_file  Write commands to 'output_file'.\n");
247         printf("  -q              Quiet mode.\n");
248
249         exit(1);
250 }
251
252 static ssize_t run_command(int sockfd, const char *command,
253                            char *buffer, size_t bufsize)
254 {
255         char *p;
256         ssize_t size, len;
257
258         if (echo) {
259                 fprintf(outputfp, "%s\n", command);
260         }
261
262         /*
263          *      Write the text to the socket.
264          */
265         if (write(sockfd, command, strlen(command)) < 0) return -1;
266         if (write(sockfd, "\r\n", 2) < 0) return -1;
267
268         /*
269          *      Read the response
270          */
271         size = 0;
272         buffer[0] = '\0';
273
274         memset(buffer, 0, bufsize);
275
276         while (1) {
277                 int rcode;
278                 fd_set readfds;
279
280                 FD_ZERO(&readfds);
281                 FD_SET(sockfd, &readfds);
282
283                 rcode = select(sockfd + 1, &readfds, NULL, NULL, NULL);
284                 if (rcode < 0) {
285                         if (errno == EINTR) continue;
286
287                         fprintf(stderr, "%s: Failed selecting: %s\n",
288                                 progname, strerror(errno));
289                         exit(1);
290                 }
291
292                 if (rcode == 0) {
293                         fprintf(stderr, "%s: Server closed the connection.\n",
294                                 progname);
295                         exit(1);
296                 }
297
298 #ifdef MSG_DONTWAIT
299                 len = recv(sockfd, buffer + size,
300                            bufsize - size - 1, MSG_DONTWAIT);
301 #else
302                 /*
303                  *      Read one byte at a time (ugh)
304                  */
305                 len = recv(sockfd, buffer + size, 1, 0);
306 #endif
307                 if (len < 0) {
308                         /*
309                          *      No data: keep looping
310                          */
311                         if ((errno == EAGAIN) || (errno == EINTR)) {
312                                 continue;
313                         }
314
315                         fprintf(stderr, "%s: Error reading socket: %s\n",
316                                 progname, strerror(errno));
317                         exit(1);
318                 }
319                 if (len == 0) return 0; /* clean exit */
320
321                 size += len;
322                 buffer[size] = '\0';
323
324                 /*
325                  *      There really is a better way of doing this.
326                  */
327                 p = strstr(buffer, "radmin> ");
328                 if (p &&
329                     ((p == buffer) || 
330                      (p[-1] == '\n') ||
331                      (p[-1] == '\r'))) {
332                         *p = '\0';
333
334                         if (p[-1] == '\n') p[-1] = '\0';
335                         break;
336                 }
337         }
338
339         /*
340          *      Blank prompt.  Go get another command.
341          */
342         if (!buffer[0]) return 1;
343
344         buffer[size] = '\0'; /* this is at least right */
345
346         return 2;
347 }
348
349 #define MAX_COMMANDS (4)
350
351 int main(int argc, char **argv)
352 {
353         int argval, quiet = 0;
354         int done_license = 0;
355         int sockfd;
356         uint32_t magic, needed;
357         char *line = NULL;
358         ssize_t len, size;
359         const char *file = NULL;
360         const char *name = "radiusd";
361         char *p, buffer[65536];
362         const char *input_file = NULL;
363         FILE *inputfp = stdin;
364         const char *output_file = NULL;
365         const char *server = NULL;
366         
367         char *commands[MAX_COMMANDS];
368         int num_commands = -1;
369
370         outputfp = stdout;      /* stdout is not a constant value... */
371
372         if ((progname = strrchr(argv[0], FR_DIR_SEP)) == NULL)
373                 progname = argv[0];
374         else
375                 progname++;
376
377         while ((argval = getopt(argc, argv, "d:hi:e:Ef:n:o:qs:S")) != EOF) {
378                 switch(argval) {
379                 case 'd':
380                         if (file) {
381                                 fprintf(stderr, "%s: -d and -f cannot be used together.\n", progname);
382                                 exit(1);
383                         }
384                         if (server) {
385                                 fprintf(stderr, "%s: -d and -s cannot be used together.\n", progname);
386                                 exit(1);
387                         }
388                         radius_dir = optarg;
389                         break;
390
391                 case 'e':
392                         num_commands++; /* starts at -1 */
393                         if (num_commands >= MAX_COMMANDS) {
394                                 fprintf(stderr, "%s: Too many '-e'\n",
395                                         progname);
396                                 exit(1);
397                         }
398                         commands[num_commands] = optarg;
399                         break;
400
401                 case 'E':
402                         echo = TRUE;
403                         break;
404
405                 case 'f':
406                         radius_dir = NULL;
407                         file = optarg;
408                         break;
409
410                 default:
411                 case 'h':
412                         usage();
413                         break;
414
415                 case 'i':
416                         if (strcmp(optarg, "-") != 0) {
417                                 input_file = optarg;
418                         }
419                         quiet = 1;
420                         break;
421
422                 case 'n':
423                         name = optarg;
424                         break;
425
426                 case 'o':
427                         if (strcmp(optarg, "-") != 0) {
428                                 output_file = optarg;
429                         }
430                         quiet = 1;
431                         break;
432
433                 case 'q':
434                         quiet = 1;
435                         break;
436
437                 case 's':
438                         if (file) {
439                                 fprintf(stderr, "%s: -s and -f cannot be used together.\n", progname);
440                                 exit(1);
441                         }
442                         radius_dir = NULL;
443                         server = optarg;
444                         break;
445
446                 case 'S':
447                         secret = NULL;
448                         break;
449                 }
450         }
451
452         if (radius_dir) {
453                 int rcode;
454                 CONF_SECTION *cs, *subcs;
455
456                 file = NULL;    /* MUST read it from the conffile now */
457
458                 snprintf(buffer, sizeof(buffer), "%s/%s.conf",
459                          radius_dir, name);
460
461                 cs = cf_file_read(buffer);
462                 if (!cs) {
463                         fprintf(stderr, "%s: Errors reading %s\n",
464                                 progname, buffer);
465                         exit(1);
466                 }
467
468                 subcs = NULL;
469                 while ((subcs = cf_subsection_find_next(cs, subcs, "listen")) != NULL) {
470                         const char *value;
471                         CONF_PAIR *cp = cf_pair_find(subcs, "type");
472                         
473                         if (!cp) continue;
474
475                         value = cf_pair_value(cp);
476                         if (!value) continue;
477
478                         if (strcmp(value, "control") != 0) continue;
479
480                         /*
481                          *      Now find the socket name (sigh)
482                          */
483                         rcode = cf_item_parse(subcs, "socket",
484                                               PW_TYPE_STRING_PTR,
485                                               &file, NULL);
486                         if (rcode < 0) {
487                                 fprintf(stderr, "%s: Failed parsing listen section\n", progname);
488                                 exit(1);
489                         }
490
491                         if (!file) {
492                                 fprintf(stderr, "%s: No path given for socket\n",
493                                         progname);
494                                 exit(1);
495                         }
496                         break;
497                 }
498
499                 if (!file) {
500                         fprintf(stderr, "%s: Could not find control socket in %s\n",
501                                 progname, buffer);
502                         exit(1);
503                 }
504         }
505
506         if (input_file) {
507                 inputfp = fopen(input_file, "r");
508                 if (!inputfp) {
509                         fprintf(stderr, "%s: Failed opening %s: %s\n",
510                                 progname, input_file, strerror(errno));
511                         exit(1);
512                 }
513         }
514
515         if (output_file) {
516                 outputfp = fopen(output_file, "w");
517                 if (!outputfp) {
518                         fprintf(stderr, "%s: Failed creating %s: %s\n",
519                                 progname, output_file, strerror(errno));
520                         exit(1);
521                 }
522         }
523
524         /*
525          *      Check if stdin is a TTY only if input is from stdin
526          */
527         if (input_file && !quiet && !isatty(STDIN_FILENO)) quiet = 1;
528
529 #ifdef USE_READLINE
530         if (!quiet) {
531 #ifdef USE_READLINE_HISTORY
532                 using_history();
533 #endif
534                 rl_bind_key('\t', rl_insert);
535         }
536 #endif
537
538  reconnect:
539         if (file) {
540                 /*
541                  *      FIXME: Get destination from command line, if possible?
542                  */
543                 sockfd = fr_domain_socket(file);
544                 if (sockfd < 0) {
545                         exit(1);
546                 }
547         } else {
548                 sockfd = client_socket(server);
549         }
550
551         /*
552          *      Read initial magic && version information.
553          */
554         for (size = 0; size < 8; size += len) {
555                 len = read(sockfd, buffer + size, 8 - size);
556                 if (len < 0) {
557                         fprintf(stderr, "%s: Error reading initial data from socket: %s\n",
558                                 progname, strerror(errno));
559                         exit(1);
560                 }
561         }
562
563         memcpy(&magic, buffer, 4);
564         magic = ntohl(magic);
565         if (magic != 0xf7eead15) {
566                 fprintf(stderr, "%s: Socket %s is not FreeRADIUS administration socket\n", progname, file);
567                 exit(1);
568         }
569         
570         memcpy(&magic, buffer + 4, 4);
571         magic = ntohl(magic);
572
573         if (!server) {
574                 needed = 1;
575         } else {
576                 needed = 2;
577         }
578
579         if (magic != needed) {
580                 fprintf(stderr, "%s: Socket version mismatch: Need %d, got %d\n",
581                         progname, needed, magic);
582                 exit(1);
583         }
584
585         if (server && secret) do_challenge(sockfd);
586
587         /*
588          *      Run one command.
589          */
590         if (num_commands >= 0) {
591                 int i;
592
593                 for (i = 0; i <= num_commands; i++) {
594                         size = run_command(sockfd, commands[i],
595                                            buffer, sizeof(buffer));
596                         if (size < 0) exit(1);
597                         
598                         if (buffer[0]) {
599                                 fputs(buffer, outputfp);
600                                 fprintf(outputfp, "\n");
601                                 fflush(outputfp);
602                         }
603                 }
604                 exit(0);
605         }
606
607         if (!done_license && !quiet) {
608                 printf("radmin " RADIUSD_VERSION " - FreeRADIUS Server administration tool.\n");
609                 printf("Copyright (C) 2008-2011 The FreeRADIUS server project and contributors.\n");
610                 printf("There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n");
611                 printf("PARTICULAR PURPOSE.\n");
612                 printf("You may redistribute copies of FreeRADIUS under the terms of the\n");
613                 printf("GNU General Public License v2.\n");
614
615                 done_license = 1;
616         }
617
618         /*
619          *      FIXME: Do login?
620          */
621
622         while (1) {
623 #ifndef USE_READLINE
624                 if (!quiet) {
625                         printf("radmin> ");
626                         fflush(stdout);
627                 }
628 #else
629                 if (!quiet) {
630                         line = readline("radmin> ");
631                         
632                         if (!line) break;
633                         
634                         if (!*line) {
635                                 free(line);
636                                 continue;
637                         }
638                         
639 #ifdef USE_READLINE_HISTORY
640                         add_history(line);
641 #endif
642                 } else          /* quiet, or no readline */
643 #endif
644                 {
645                         line = fgets(buffer, sizeof(buffer), inputfp);
646                         if (!line) break;
647
648                         p = strchr(buffer, '\n');
649                         if (!p) {
650                                 fprintf(stderr, "%s: Input line too long\n",
651                                         progname);
652                                 exit(1);
653                         }
654                         
655                         *p = '\0';
656
657                         /*
658                          *      Strip off leading spaces.
659                          */
660                         for (p = line; *p != '\0'; p++) {
661                                 if ((p[0] == ' ') ||
662                                     (p[0] == '\t')) {
663                                         line = p + 1;
664                                         continue;
665                                 }
666
667                                 if (p[0] == '#') {
668                                         line = NULL;
669                                         break;
670                                 }
671
672                                 break;
673                         }
674
675                         /*
676                          *      Comments: keep going.
677                          */
678                         if (!line) continue;
679
680                         /*
681                          *      Strip off CR / LF
682                          */
683                         for (p = line; *p != '\0'; p++) {
684                                 if ((p[0] == '\r') ||
685                                     (p[0] == '\n')) {
686                                         p[0] = '\0';
687                                         break;
688                                 }
689                         }
690                 }
691
692                 if (strcmp(line, "reconnect") == 0) {
693                         close(sockfd);
694                         line = NULL;
695                         goto reconnect;
696                 }
697
698                 if (memcmp(line, "secret ", 7) == 0) {
699                         if (!secret) {
700                                 secret = line + 7;
701                                 do_challenge(sockfd);
702                         }
703                         line = NULL;
704                         continue;
705                 }
706
707                 /*
708                  *      Exit, done, etc.
709                  */
710                 if ((strcmp(line, "exit") == 0) ||
711                     (strcmp(line, "quit") == 0)) {
712                         break;
713                 }
714
715                 if (server && !secret) {
716                         fprintf(stderr, "ERROR: You must enter 'secret <SECRET>' before running any commands\n");
717                         line = NULL;
718                         continue;
719                 }
720
721                 size = run_command(sockfd, line, buffer, sizeof(buffer));
722                 if (size <= 0) break; /* error, or clean exit */
723
724                 if (size == 1) continue; /* no output. */
725
726                 fputs(buffer, outputfp);
727                 fflush(outputfp);
728                 fprintf(outputfp, "\n");
729         }
730
731         fprintf(outputfp, "\n");
732
733         return 0;
734 }
735