Add ENV[PANIC_ACTION] support to all applications
[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, fr_syserror(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, fr_syserror(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, fr_syserror(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, fr_syserror(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, fr_syserror(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, fr_syserror(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, fr_syserror(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, fr_syserror(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, fr_syserror(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, fr_syserror(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 #ifndef NDEBUG
378         fr_fault_setup(getenv("PANIC_ACTION"), argv[0]);
379 #endif
380
381         talloc_set_log_stderr();
382
383         outputfp = stdout;      /* stdout is not a constant value... */
384
385         if ((progname = strrchr(argv[0], FR_DIR_SEP)) == NULL)
386                 progname = argv[0];
387         else
388                 progname++;
389
390         while ((argval = getopt(argc, argv, "d:hi:e:Ef:n:o:qs:S")) != EOF) {
391                 switch(argval) {
392                 case 'd':
393                         if (file) {
394                                 fprintf(stderr, "%s: -d and -f cannot be used together.\n", progname);
395                                 exit(1);
396                         }
397                         if (server) {
398                                 fprintf(stderr, "%s: -d and -s cannot be used together.\n", progname);
399                                 exit(1);
400                         }
401                         radius_dir = optarg;
402                         break;
403
404                 case 'e':
405                         num_commands++; /* starts at -1 */
406                         if (num_commands >= MAX_COMMANDS) {
407                                 fprintf(stderr, "%s: Too many '-e'\n",
408                                         progname);
409                                 exit(1);
410                         }
411                         commands[num_commands] = optarg;
412                         break;
413
414                 case 'E':
415                         echo = true;
416                         break;
417
418                 case 'f':
419                         radius_dir = NULL;
420                         file = optarg;
421                         break;
422
423                 default:
424                 case 'h':
425                         usage(0);
426                         break;
427
428                 case 'i':
429                         if (strcmp(optarg, "-") != 0) {
430                                 input_file = optarg;
431                         }
432                         quiet = 1;
433                         break;
434
435                 case 'n':
436                         name = optarg;
437                         break;
438
439                 case 'o':
440                         if (strcmp(optarg, "-") != 0) {
441                                 output_file = optarg;
442                         }
443                         quiet = 1;
444                         break;
445
446                 case 'q':
447                         quiet = 1;
448                         break;
449
450                 case 's':
451                         if (file) {
452                                 fprintf(stderr, "%s: -s and -f cannot be used together.\n", progname);
453                                 usage(1);
454                         }
455                         radius_dir = NULL;
456                         server = optarg;
457                         break;
458
459                 case 'S':
460                         secret = NULL;
461                         break;
462                 }
463         }
464
465         /*
466          *      Mismatch between the binary and the libraries it depends on
467          */
468         if (fr_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) {
469                 fr_perror("radmin");
470                 exit(1);
471         }
472
473         if (radius_dir) {
474                 int rcode;
475                 CONF_SECTION *cs, *subcs;
476
477                 file = NULL;    /* MUST read it from the conffile now */
478
479                 snprintf(buffer, sizeof(buffer), "%s/%s.conf",
480                          radius_dir, name);
481
482                 cs = cf_file_read(buffer);
483                 if (!cs) {
484                         fprintf(stderr, "%s: Errors reading or parsing %s\n", progname, buffer);
485                         usage(1);
486                 }
487
488                 subcs = NULL;
489                 while ((subcs = cf_subsection_find_next(cs, subcs, "listen")) != NULL) {
490                         char const *value;
491                         CONF_PAIR *cp = cf_pair_find(subcs, "type");
492
493                         if (!cp) continue;
494
495                         value = cf_pair_value(cp);
496                         if (!value) continue;
497
498                         if (strcmp(value, "control") != 0) continue;
499
500                         /*
501                          *      Now find the socket name (sigh)
502                          */
503                         rcode = cf_item_parse(subcs, "socket",
504                                               PW_TYPE_STRING_PTR,
505                                               &file, NULL);
506                         if (rcode < 0) {
507                                 fprintf(stderr, "%s: Failed parsing listen section\n", progname);
508                                 exit(1);
509                         }
510
511                         if (!file) {
512                                 fprintf(stderr, "%s: No path given for socket\n", progname);
513                                 usage(1);
514                         }
515                         break;
516                 }
517
518                 if (!file) {
519                         fprintf(stderr, "%s: Could not find control socket in %s\n", progname, buffer);
520                         exit(1);
521                 }
522         }
523
524         if (input_file) {
525                 inputfp = fopen(input_file, "r");
526                 if (!inputfp) {
527                         fprintf(stderr, "%s: Failed opening %s: %s\n", progname, input_file, fr_syserror(errno));
528                         exit(1);
529                 }
530         }
531
532         if (output_file) {
533                 outputfp = fopen(output_file, "w");
534                 if (!outputfp) {
535                         fprintf(stderr, "%s: Failed creating %s: %s\n", progname, output_file, fr_syserror(errno));
536                         exit(1);
537                 }
538         }
539
540         /*
541          *      Check if stdin is a TTY only if input is from stdin
542          */
543         if (input_file && !quiet && !isatty(STDIN_FILENO)) quiet = 1;
544
545 #ifdef USE_READLINE
546         if (!quiet) {
547 #ifdef USE_READLINE_HISTORY
548                 using_history();
549 #endif
550                 rl_bind_key('\t', rl_insert);
551         }
552 #endif
553
554  reconnect:
555         if (file) {
556                 /*
557                  *      FIXME: Get destination from command line, if possible?
558                  */
559                 sockfd = fr_domain_socket(file);
560                 if (sockfd < 0) {
561                         exit(1);
562                 }
563         } else {
564                 sockfd = client_socket(server);
565         }
566
567         /*
568          *      Read initial magic && version information.
569          */
570         for (size = 0; size < 8; size += len) {
571                 len = read(sockfd, buffer + size, 8 - size);
572                 if (len < 0) {
573                         fprintf(stderr, "%s: Error reading initial data from socket: %s\n",
574                                 progname, fr_syserror(errno));
575                         exit(1);
576                 }
577         }
578
579         memcpy(&magic, buffer, 4);
580         magic = ntohl(magic);
581         if (magic != 0xf7eead15) {
582                 fprintf(stderr, "%s: Socket %s is not FreeRADIUS administration socket\n", progname, file);
583                 exit(1);
584         }
585
586         memcpy(&magic, buffer + 4, 4);
587         magic = ntohl(magic);
588
589         if (!server) {
590                 needed = 1;
591         } else {
592                 needed = 2;
593         }
594
595         if (magic != needed) {
596                 fprintf(stderr, "%s: Socket version mismatch: Need %d, got %d\n",
597                         progname, needed, magic);
598                 exit(1);
599         }
600
601         if (server && secret) do_challenge(sockfd);
602
603         /*
604          *      Run one command.
605          */
606         if (num_commands >= 0) {
607                 int i;
608
609                 for (i = 0; i <= num_commands; i++) {
610                         size = run_command(sockfd, commands[i],
611                                            buffer, sizeof(buffer));
612                         if (size < 0) exit(1);
613
614                         if (buffer[0]) {
615                                 fputs(buffer, outputfp);
616                                 fprintf(outputfp, "\n");
617                                 fflush(outputfp);
618                         }
619                 }
620                 exit(0);
621         }
622
623         if (!done_license && !quiet) {
624                 printf("%s - FreeRADIUS Server administration tool.\n", radmin_version);
625                 printf("Copyright (C) 2008-2014 The FreeRADIUS server project and contributors.\n");
626                 printf("There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n");
627                 printf("PARTICULAR PURPOSE.\n");
628                 printf("You may redistribute copies of FreeRADIUS under the terms of the\n");
629                 printf("GNU General Public License v2.\n");
630
631                 done_license = 1;
632         }
633
634         /*
635          *      FIXME: Do login?
636          */
637
638         while (1) {
639 #ifndef USE_READLINE
640                 if (!quiet) {
641                         printf("radmin> ");
642                         fflush(stdout);
643                 }
644 #else
645                 if (!quiet) {
646                         line = readline("radmin> ");
647
648                         if (!line) break;
649
650                         if (!*line) {
651                                 free(line);
652                                 continue;
653                         }
654
655 #ifdef USE_READLINE_HISTORY
656                         add_history(line);
657 #endif
658                 } else          /* quiet, or no readline */
659 #endif
660                 {
661                         line = fgets(buffer, sizeof(buffer), inputfp);
662                         if (!line) break;
663
664                         p = strchr(buffer, '\n');
665                         if (!p) {
666                                 fprintf(stderr, "%s: Input line too long\n",
667                                         progname);
668                                 exit(1);
669                         }
670
671                         *p = '\0';
672
673                         /*
674                          *      Strip off leading spaces.
675                          */
676                         for (p = line; *p != '\0'; p++) {
677                                 if ((p[0] == ' ') ||
678                                     (p[0] == '\t')) {
679                                         line = p + 1;
680                                         continue;
681                                 }
682
683                                 if (p[0] == '#') {
684                                         line = NULL;
685                                         break;
686                                 }
687
688                                 break;
689                         }
690
691                         /*
692                          *      Comments: keep going.
693                          */
694                         if (!line) continue;
695
696                         /*
697                          *      Strip off CR / LF
698                          */
699                         for (p = line; *p != '\0'; p++) {
700                                 if ((p[0] == '\r') ||
701                                     (p[0] == '\n')) {
702                                         p[0] = '\0';
703                                         break;
704                                 }
705                         }
706                 }
707
708                 if (strcmp(line, "reconnect") == 0) {
709                         close(sockfd);
710                         line = NULL;
711                         goto reconnect;
712                 }
713
714                 if (memcmp(line, "secret ", 7) == 0) {
715                         if (!secret) {
716                                 secret = line + 7;
717                                 do_challenge(sockfd);
718                         }
719                         line = NULL;
720                         continue;
721                 }
722
723                 /*
724                  *      Exit, done, etc.
725                  */
726                 if ((strcmp(line, "exit") == 0) ||
727                     (strcmp(line, "quit") == 0)) {
728                         break;
729                 }
730
731                 if (server && !secret) {
732                         fprintf(stderr, "ERROR: You must enter 'secret <SECRET>' before running any commands\n");
733                         line = NULL;
734                         continue;
735                 }
736
737                 size = run_command(sockfd, line, buffer, sizeof(buffer));
738                 if (size <= 0) break; /* error, or clean exit */
739
740                 if (size == 1) continue; /* no output. */
741
742                 fputs(buffer, outputfp);
743                 fflush(outputfp);
744                 fprintf(outputfp, "\n");
745         }
746
747         fprintf(outputfp, "\n");
748
749         return 0;
750 }
751