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