1f0d960d364710ae05e23c6ef9b0fb62c53d9c7d
[freeradius.git] / src / main / command.c
1 /*
2  * command.c    Command socket processing.
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 #ifdef WITH_COMMAND_SOCKET
25
26 #include <freeradius-devel/modpriv.h>
27 #include <freeradius-devel/conffile.h>
28 #include <freeradius-devel/stats.h>
29 #include <freeradius-devel/realms.h>
30
31 #ifdef HAVE_SYS_UN_H
32 #include <sys/un.h>
33 #ifndef SUN_LEN
34 #define SUN_LEN(su)  (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
35 #endif
36 #endif
37
38 #ifdef HAVE_SYS_STAT_H
39 #include <sys/stat.h>
40 #endif
41
42 #ifdef HAVE_PWD_H
43 #include <pwd.h>
44 #endif
45
46 #ifdef HAVE_GRP_H
47 #include <grp.h>
48 #endif
49
50 typedef struct fr_command_table_t fr_command_table_t;
51
52 typedef int (*fr_command_func_t)(rad_listen_t *, int, char *argv[]);
53
54 #define FR_READ  (1)
55 #define FR_WRITE (2)
56
57 struct fr_command_table_t {
58         const char *command;
59         int mode;               /* read/write */
60         const char *help;
61         fr_command_func_t func;
62         fr_command_table_t *table;
63 };
64
65 #define COMMAND_BUFFER_SIZE (1024)
66
67 typedef struct fr_command_socket_t {
68         char    *path;
69         uid_t   uid;
70         gid_t   gid;
71         int     mode;
72         char    *uid_name;
73         char    *gid_name;
74         char    *mode_name;
75         char user[256];
76
77         /*
78          *      The next few entries handle fake packets injected by
79          *      the control socket.
80          */
81         fr_ipaddr_t     src_ipaddr; /* src_port is always 0 */
82         fr_ipaddr_t     dst_ipaddr;
83         int             dst_port;
84         rad_listen_t    *inject_listener;
85         RADCLIENT       *inject_client;
86
87         /*
88          *      The next few entries do buffer management.
89          */
90         ssize_t offset;
91         ssize_t next;
92         char buffer[COMMAND_BUFFER_SIZE];
93 } fr_command_socket_t;
94
95 static const CONF_PARSER command_config[] = {
96   { "socket",  PW_TYPE_STRING_PTR,
97     offsetof(fr_command_socket_t, path), NULL, "${run_dir}/radiusd.sock"},
98   { "uid",  PW_TYPE_STRING_PTR,
99     offsetof(fr_command_socket_t, uid_name), NULL, NULL},
100   { "gid",  PW_TYPE_STRING_PTR,
101     offsetof(fr_command_socket_t, gid_name), NULL, NULL},
102   { "mode",  PW_TYPE_STRING_PTR,
103     offsetof(fr_command_socket_t, mode_name), NULL, NULL},
104
105   { NULL, -1, 0, NULL, NULL }           /* end the list */
106 };
107
108 static FR_NAME_NUMBER mode_names[] = {
109         { "ro", FR_READ },
110         { "read-only", FR_READ },
111         { "read-write", FR_READ | FR_WRITE },
112         { "rw", FR_READ | FR_WRITE },
113         { NULL, 0 }
114 };
115
116
117 static ssize_t cprintf(rad_listen_t *listener, const char *fmt, ...)
118 #ifdef __GNUC__
119                 __attribute__ ((format (printf, 2, 3)))
120 #endif
121 ;
122
123 #ifndef HAVE_GETPEEREID
124 static int getpeereid(int s, uid_t *euid, gid_t *egid)
125 {
126 #ifndef SO_PEERCRED
127         return -1;
128 #else
129         struct ucred cr;
130         socklen_t cl = sizeof(cr);
131         
132         if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cl) < 0) {
133                 return -1;
134         }
135
136         *euid = cr.uid;
137         *egid = cr.gid;
138         return 0;
139 #endif /* SO_PEERCRED */
140 }
141 #endif /* HAVE_GETPEEREID */
142
143
144 static int fr_server_domain_socket(const char *path)
145 {
146         int sockfd;
147         size_t len;
148         socklen_t socklen;
149         struct sockaddr_un salocal;
150         struct stat buf;
151
152         len = strlen(path);
153         if (len >= sizeof(salocal.sun_path)) {
154                 radlog(L_ERR, "Path too long in socket filename.");
155                 return -1;
156         }
157
158         if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
159                 radlog(L_ERR, "Failed creating socket: %s",
160                         strerror(errno));
161                 return -1;
162         }
163
164         memset(&salocal, 0, sizeof(salocal));
165         salocal.sun_family = AF_UNIX;
166         memcpy(salocal.sun_path, path, len + 1); /* SUN_LEN does strlen */
167         
168         socklen = SUN_LEN(&salocal);
169
170         /*
171          *      Check the path.
172          */
173         if (stat(path, &buf) < 0) {
174                 if (errno != ENOENT) {
175                         radlog(L_ERR, "Failed to stat %s: %s",
176                                path, strerror(errno));
177                         return -1;
178                 }
179
180                 /*
181                  *      FIXME: Check the enclosing directory?
182                  */
183         } else {                /* it exists */
184                 if (!S_ISREG(buf.st_mode)
185 #ifdef S_ISSOCK
186                     && !S_ISSOCK(buf.st_mode)
187 #endif
188                         ) {
189                         radlog(L_ERR, "Cannot turn %s into socket", path);
190                         return -1;                     
191                 }
192
193                 /*
194                  *      Refuse to open sockets not owned by us.
195                  */
196                 if (buf.st_uid != geteuid()) {
197                         radlog(L_ERR, "We do not own %s", path);
198                         return -1;
199                 }
200
201                 if (unlink(path) < 0) {
202                         radlog(L_ERR, "Failed to delete %s: %s",
203                                path, strerror(errno));
204                         return -1;
205                 }
206         }
207
208         if (bind(sockfd, (struct sockaddr *)&salocal, socklen) < 0) {
209                 radlog(L_ERR, "Failed binding to %s: %s",
210                         path, strerror(errno));
211                 close(sockfd);
212                 return -1;
213         }
214
215         /*
216          *      FIXME: There's a race condition here.  But Linux
217          *      doesn't seem to permit fchmod on domain sockets.
218          */
219         if (chmod(path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0) {
220                 radlog(L_ERR, "Failed setting permissions on %s: %s",
221                        path, strerror(errno));
222                 close(sockfd);
223                 return -1;
224         }
225
226         if (listen(sockfd, 8) < 0) {
227                 radlog(L_ERR, "Failed listening to %s: %s",
228                         path, strerror(errno));
229                 close(sockfd);
230                 return -1;
231         }
232
233 #ifdef O_NONBLOCK
234         {
235                 int flags;
236                 
237                 if ((flags = fcntl(sockfd, F_GETFL, NULL)) < 0)  {
238                         radlog(L_ERR, "Failure getting socket flags: %s",
239                                 strerror(errno));
240                         close(sockfd);
241                         return -1;
242                 }
243                 
244                 flags |= O_NONBLOCK;
245                 if( fcntl(sockfd, F_SETFL, flags) < 0) {
246                         radlog(L_ERR, "Failure setting socket flags: %s",
247                                 strerror(errno));
248                         close(sockfd);
249                         return -1;
250                 }
251         }
252 #endif
253
254         return sockfd;
255 }
256
257 static void command_close_socket(rad_listen_t *this)
258 {
259         this->status = RAD_LISTEN_STATUS_CLOSED;
260
261         /*
262          *      This removes the socket from the event fd, so no one
263          *      will be calling us any more.
264          */
265         event_new_fd(this);
266
267         listen_free(&this);
268 }
269
270
271 static ssize_t cprintf(rad_listen_t *listener, const char *fmt, ...)
272 {
273         ssize_t len;
274         va_list ap;
275         char buffer[256];
276
277         va_start(ap, fmt);
278         len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
279         va_end(ap);
280
281         if (listener->status == RAD_LISTEN_STATUS_CLOSED) return 0;
282
283         len = write(listener->fd, buffer, len);
284         if (len <= 0) command_close_socket(listener);
285
286         /*
287          *      FIXME: Keep writing until done?
288          */
289         return len;
290 }
291
292 static int command_hup(rad_listen_t *listener, int argc, char *argv[])
293 {
294         CONF_SECTION *cs;
295         module_instance_t *mi;
296
297         if (argc == 0) {
298                 radius_signal_self(RADIUS_SIGNAL_SELF_HUP);
299                 return 1;
300         }
301
302         cs = cf_section_find("modules");
303         if (!cs) return 0;
304
305         mi = find_module_instance(cs, argv[0], 0);
306         if (!mi) {
307                 cprintf(listener, "ERROR: No such module \"%s\"\n", argv[0]);
308                 return 0;
309         }
310
311         if ((mi->entry->module->type & RLM_TYPE_HUP_SAFE) == 0) {
312                 cprintf(listener, "ERROR: Module %s cannot be hup'd\n",
313                         argv[0]);
314                 return 0;
315         }
316
317         if (!module_hup_module(mi->cs, mi, time(NULL))) {
318                 cprintf(listener, "ERROR: Failed to reload module\n");
319                 return 0;
320         }
321
322         return 1;               /* success */
323 }
324
325 static int command_terminate(UNUSED rad_listen_t *listener,
326                              UNUSED int argc, UNUSED char *argv[])
327 {
328         radius_signal_self(RADIUS_SIGNAL_SELF_TERM);
329
330         return 1;               /* success */
331 }
332
333 extern time_t fr_start_time;
334
335 static int command_uptime(rad_listen_t *listener,
336                           UNUSED int argc, UNUSED char *argv[])
337 {
338         char buffer[128];
339
340         CTIME_R(&fr_start_time, buffer, sizeof(buffer));
341         cprintf(listener, "Up since %s", buffer); /* no \r\n */
342
343         return 1;               /* success */
344 }
345
346 static const char *tabs = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
347
348 /*
349  *      FIXME: Recurse && indent?
350  */
351 static void cprint_conf_parser(rad_listen_t *listener, int indent, CONF_SECTION *cs,
352                                const void *base)
353                                
354 {
355         int i;
356         const void *data;
357         const char *name1 = cf_section_name1(cs);
358         const char *name2 = cf_section_name2(cs);
359         const CONF_PARSER *variables = cf_section_parse_table(cs);
360         char buffer[256];
361
362         if (name2) {
363                 cprintf(listener, "%.*s%s %s {\n", indent, tabs, name1, name2);
364         } else {
365                 cprintf(listener, "%.*s%s {\n", indent, tabs, name1);
366         }
367
368         indent++;
369         
370         /*
371          *      Print
372          */
373         if (variables) for (i = 0; variables[i].name != NULL; i++) {
374                 /*
375                  *      No base struct offset, data must be the pointer.
376                  *      If data doesn't exist, ignore the entry, there
377                  *      must be something wrong.
378                  */
379                 if (!base) {
380                         if (!variables[i].data) {
381                                 continue;
382                         }
383                         
384                         data = variables[i].data;;
385                         
386                 } else if (variables[i].data) {
387                         data = variables[i].data;;
388                         
389                 } else {
390                         data = (((char *)base) + variables[i].offset);
391                 }
392
393                 switch (variables[i].type) {
394                 default:
395                         cprintf(listener, "%.*s%s = ?\n", indent, tabs,
396                                 variables[i].name);
397                         break;
398                         
399                 case PW_TYPE_INTEGER:
400                         cprintf(listener, "%.*s%s = %u\n", indent, tabs,
401                                 variables[i].name, *(int *) data);
402                         break;
403                         
404                 case PW_TYPE_IPADDR:
405                         inet_ntop(AF_INET, data, buffer, sizeof(buffer));
406                         break;
407
408                 case PW_TYPE_IPV6ADDR:
409                         inet_ntop(AF_INET6, data, buffer, sizeof(buffer));
410                         break;
411
412                 case PW_TYPE_BOOLEAN:
413                         cprintf(listener, "%.*s%s = %s\n", indent, tabs,
414                                 variables[i].name, 
415                                 ((*(int *) data) == 0) ? "no" : "yes");
416                         break;
417                         
418                 case PW_TYPE_STRING_PTR:
419                 case PW_TYPE_FILENAME:
420                         /*
421                          *      FIXME: Escape things in the string!
422                          */
423                         if (*(char **) data) {
424                                 cprintf(listener, "%.*s%s = \"%s\"\n", indent, tabs,
425                                         variables[i].name, *(char **) data);
426                         } else {
427                                 cprintf(listener, "%.*s%s = \n", indent, tabs,
428                                         variables[i].name);
429                         }
430                                 
431                         break;
432                 }
433         }
434
435         indent--;
436
437         cprintf(listener, "%.*s}\n", indent, tabs);
438 }
439
440 static int command_show_module_config(rad_listen_t *listener, int argc, char *argv[])
441 {
442         CONF_SECTION *cs;
443         module_instance_t *mi;
444
445         if (argc != 1) {
446                 cprintf(listener, "ERROR: No module name was given\n");
447                 return 0;
448         }
449
450         cs = cf_section_find("modules");
451         if (!cs) return 0;
452
453         mi = find_module_instance(cs, argv[0], 0);
454         if (!mi) {
455                 cprintf(listener, "ERROR: No such module \"%s\"\n", argv[0]);
456                 return 0;
457         }
458
459         cprint_conf_parser(listener, 0, mi->cs, mi->insthandle);
460
461         return 1;               /* success */
462 }
463
464 static const char *method_names[RLM_COMPONENT_COUNT] = {
465         "authenticate",
466         "authorize",
467         "preacct",
468         "accounting",
469         "session",
470         "pre-proxy",
471         "post-proxy",
472         "post-auth"
473 };
474
475
476 static int command_show_module_methods(rad_listen_t *listener, int argc, char *argv[])
477 {
478         int i;
479         CONF_SECTION *cs;
480         const module_instance_t *mi;
481         const module_t *mod;
482
483         if (argc != 1) {
484                 cprintf(listener, "ERROR: No module name was given\n");
485                 return 0;
486         }
487
488         cs = cf_section_find("modules");
489         if (!cs) return 0;
490
491         mi = find_module_instance(cs, argv[0], 0);
492         if (!mi) {
493                 cprintf(listener, "ERROR: No such module \"%s\"\n", argv[0]);
494                 return 0;
495         }
496
497         mod = mi->entry->module;
498
499         for (i = 0; i < RLM_COMPONENT_COUNT; i++) {
500                 if (mod->methods[i]) cprintf(listener, "\t%s\n", method_names[i]);
501         }
502
503         return 1;               /* success */
504 }
505
506
507 static int command_show_module_flags(rad_listen_t *listener, int argc, char *argv[])
508 {
509         CONF_SECTION *cs;
510         const module_instance_t *mi;
511         const module_t *mod;
512
513         if (argc != 1) {
514                 cprintf(listener, "ERROR: No module name was given\n");
515                 return 0;
516         }
517
518         cs = cf_section_find("modules");
519         if (!cs) return 0;
520
521         mi = find_module_instance(cs, argv[0], 0);
522         if (!mi) {
523                 cprintf(listener, "ERROR: No such module \"%s\"\n", argv[0]);
524                 return 0;
525         }
526
527         mod = mi->entry->module;
528
529         if ((mod->type & RLM_TYPE_THREAD_SAFE) != 0)
530                 cprintf(listener, "\tthread-safe\n");
531
532
533         if ((mod->type & RLM_TYPE_CHECK_CONFIG_SAFE) != 0)
534                 cprintf(listener, "\twill-check-config\n");
535
536
537         if ((mod->type & RLM_TYPE_HUP_SAFE) != 0)
538                 cprintf(listener, "\treload-on-hup\n");
539
540         return 1;               /* success */
541 }
542
543
544 /*
545  *      Show all loaded modules
546  */
547 static int command_show_modules(rad_listen_t *listener, UNUSED int argc, UNUSED char *argv[])
548 {
549         CONF_SECTION *cs, *subcs;
550
551         cs = cf_section_find("modules");
552         if (!cs) return 0;
553
554         subcs = NULL;
555         while ((subcs = cf_subsection_find_next(cs, subcs, NULL)) != NULL) {
556                 const char *name1 = cf_section_name1(subcs);
557                 const char *name2 = cf_section_name2(subcs);
558
559                 module_instance_t *mi;
560
561                 if (name2) {
562                         mi = find_module_instance(cs, name2, 0);
563                         if (!mi) continue;
564
565                         cprintf(listener, "\t%s (%s)\n", name2, name1);
566                 } else {
567                         mi = find_module_instance(cs, name1, 0);
568                         if (!mi) continue;
569
570                         cprintf(listener, "\t%s\n", name1);
571                 }
572         }
573
574         return 1;               /* success */
575 }
576
577 #ifdef WITH_PROXY
578 static int command_show_home_servers(rad_listen_t *listener, UNUSED int argc, UNUSED char *argv[])
579 {
580         int i;
581         home_server *home;
582         const char *type, *state;
583
584         char buffer[256];
585
586         for (i = 0; i < 256; i++) {
587                 home = home_server_bynumber(i);
588                 if (!home) break;
589
590                 /*
591                  *      Internal "virtual" home server.
592                  */
593                 if (home->ipaddr.af == AF_UNSPEC) continue;
594
595                 if (home->type == HOME_TYPE_AUTH) {
596                         type = "auth";
597
598                 } else if (home->type == HOME_TYPE_ACCT) {
599                         type = "acct";
600
601                 } else continue;
602
603                 if (home->state == HOME_STATE_ALIVE) {
604                         state = "alive";
605
606                 } else if (home->state == HOME_STATE_ZOMBIE) {
607                         state = "zombie";
608
609                 } else if (home->state == HOME_STATE_IS_DEAD) {
610                         state = "dead";
611
612                 } else continue;
613
614                 cprintf(listener, "%s\t%d\t%s\t%s\t%d\n",
615                         ip_ntoh(&home->ipaddr, buffer, sizeof(buffer)),
616                         home->port, type, state,
617                         home->currently_outstanding);
618         }
619
620         return 0;
621 }
622 #endif
623
624 static int command_show_clients(rad_listen_t *listener, UNUSED int argc, UNUSED char *argv[])
625 {
626         int i;
627         RADCLIENT *client;
628         char buffer[256];
629
630         for (i = 0; i < 256; i++) {
631                 client = client_findbynumber(NULL, i);
632                 if (!client) break;
633
634                 ip_ntoh(&client->ipaddr, buffer, sizeof(buffer));
635
636                 if (((client->ipaddr.af == AF_INET) &&
637                      (client->prefix != 32)) ||
638                     ((client->ipaddr.af == AF_INET6) &&
639                      (client->prefix != 128))) {
640                         cprintf(listener, "\t%s/%d\n", buffer, client->prefix);
641                 } else {
642                         cprintf(listener, "\t%s\n", buffer);
643                 }
644         }
645
646         return 0;
647 }
648
649
650 static int command_show_xml(rad_listen_t *listener, UNUSED int argc, UNUSED char *argv[])
651 {
652         CONF_ITEM *ci;
653         FILE *fp = fdopen(dup(listener->fd), "a");
654
655         if (!fp) {
656                 cprintf(listener, "ERROR: Can't dup %s\n", strerror(errno));
657                 return 0;
658         }
659
660         if (argc == 0) {
661                 cprintf(listener, "ERROR: <reference> is required\n");
662                 return 0;
663         }
664         
665         ci = cf_reference_item(mainconfig.config, mainconfig.config, argv[0]);
666         if (!ci) {
667                 cprintf(listener, "ERROR: No such item <reference>\n");
668                 return 0;
669         }
670
671         if (cf_item_is_section(ci)) {
672                 cf_section2xml(fp, cf_itemtosection(ci));
673
674         } else if (cf_item_is_pair(ci)) {
675                 cf_pair2xml(fp, cf_itemtopair(ci));
676
677         } else {
678                 cprintf(listener, "ERROR: No such item <reference>\n");
679                 fclose(fp);
680                 return 0;
681         }
682
683         fclose(fp);
684
685         return 1;               /* success */
686 }
687
688 static int command_show_version(rad_listen_t *listener, UNUSED int argc, UNUSED char *argv[])
689 {
690         cprintf(listener, "%s\n", radiusd_version);
691         return 1;
692 }
693
694 static int command_debug_level(rad_listen_t *listener, int argc, char *argv[])
695 {
696         int number;
697
698         if (argc == 0) {
699                 cprintf(listener, "ERROR: Must specify <number>\n");
700                 return -1;
701         }
702
703         number = atoi(argv[0]);
704         if ((number < 0) || (number > 4)) {
705                 cprintf(listener, "ERROR: <number> must be between 0 and 4\n");
706                 return -1;
707         }
708
709         fr_debug_flag = debug_flag = number;
710
711         return 0;
712 }
713
714 char *debug_log_file = NULL;
715 static char debug_log_file_buffer[1024];
716
717 static int command_debug_file(rad_listen_t *listener, int argc, char *argv[])
718 {
719         if (debug_flag && mainconfig.radlog_dest == RADLOG_STDOUT) {
720                 cprintf(listener, "ERROR: Cannot redirect debug logs to a file when already in debugging mode.\n");
721                 return -1;
722         }
723
724         if ((argc > 0) && (strchr(argv[0], FR_DIR_SEP) != NULL)) {
725                 cprintf(listener, "ERROR: Cannot direct debug logs to absolute path.\n");
726         }
727
728         debug_log_file = NULL;
729
730         if (argc == 0) return 0;
731
732         /*
733          *      This looks weird, but it's here to avoid locking
734          *      a mutex for every log message.
735          */
736         memset(debug_log_file_buffer, 0, sizeof(debug_log_file_buffer));
737
738         /*
739          *      Debug files always go to the logging directory.
740          */
741         snprintf(debug_log_file_buffer, sizeof(debug_log_file_buffer),
742                  "%s/%s", radlog_dir, argv[0]);
743
744         debug_log_file = &debug_log_file_buffer[0];
745
746         return 0;
747 }
748
749 extern char *debug_condition;
750 static int command_debug_condition(UNUSED rad_listen_t *listener, int argc, char *argv[])
751 {
752         /*
753          *      Delete old condition.
754          *
755          *      This is thread-safe because the condition is evaluated
756          *      in the main server thread, as is this code.
757          */
758         free(debug_condition);
759         debug_condition = NULL;
760
761         /*
762          *      Disable it.
763          */
764         if (argc == 0) {
765                 return 0;
766         }
767
768         debug_condition = strdup(argv[0]);
769
770         return 0;
771 }
772
773 static int command_show_debug_condition(rad_listen_t *listener,
774                                         UNUSED int argc, UNUSED char *argv[])
775 {
776         if (!debug_condition) return 0;
777
778         cprintf(listener, "%s\n", debug_condition);
779         return 0;
780 }
781
782
783 static int command_show_debug_file(rad_listen_t *listener,
784                                         UNUSED int argc, UNUSED char *argv[])
785 {
786         if (!debug_log_file) return 0;
787
788         cprintf(listener, "%s\n", debug_log_file);
789         return 0;
790 }
791
792
793 static int command_show_debug_level(rad_listen_t *listener,
794                                         UNUSED int argc, UNUSED char *argv[])
795 {
796         cprintf(listener, "%d\n", debug_flag);
797         return 0;
798 }
799
800
801 static RADCLIENT *get_client(rad_listen_t *listener, int argc, char *argv[])
802 {
803         RADCLIENT *client;
804         fr_ipaddr_t ipaddr;
805
806         if (argc < 1) {
807                 cprintf(listener, "ERROR: Must specify <ipaddr>\n");
808                 return NULL;
809         }
810
811         if (ip_hton(argv[0], AF_UNSPEC, &ipaddr) < 0) {
812                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
813                         fr_strerror());
814                 return NULL;
815         }
816
817         client = client_find(NULL, &ipaddr);
818         if (!client) {
819                 cprintf(listener, "ERROR: No such client\n");
820                 return NULL;
821         }
822
823         return client;
824 }
825
826
827 static int command_show_client_config(rad_listen_t *listener, int argc, char *argv[])
828 {
829         RADCLIENT *client;
830         FILE *fp;
831
832         client = get_client(listener, argc, argv);
833         if (!client) {
834                 return 0;
835         }
836
837         if (!client->cs) return 1;
838
839         fp = fdopen(dup(listener->fd), "a");
840         if (!fp) {
841                 cprintf(listener, "ERROR: Can't dup %s\n", strerror(errno));
842                 return 0;
843         }
844
845         cf_section2file(fp, client->cs);
846         fclose(fp);
847
848         return 1;
849 }
850
851 #ifdef WITH_PROXY
852 static home_server *get_home_server(rad_listen_t *listener, int argc, char *argv[])
853 {
854         home_server *home;
855         int port;
856         fr_ipaddr_t ipaddr;
857
858         if (argc < 2) {
859                 cprintf(listener, "ERROR: Must specify <ipaddr> <port>\n");
860                 return NULL;
861         }
862
863         if (ip_hton(argv[0], AF_UNSPEC, &ipaddr) < 0) {
864                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
865                         fr_strerror());
866                 return NULL;
867         }
868
869         port = atoi(argv[1]);
870
871         home = home_server_find(&ipaddr, port);
872         if (!home) {
873                 cprintf(listener, "ERROR: No such home server\n");
874                 return NULL;
875         }
876
877         return home;
878 }
879
880 static int command_show_home_server_config(rad_listen_t *listener, int argc, char *argv[])
881 {
882         home_server *home;
883         FILE *fp;
884
885         home = get_home_server(listener, argc, argv);
886         if (!home) {
887                 return 0;
888         }
889
890         if (!home->cs) return 1;
891
892         fp = fdopen(dup(listener->fd), "a");
893         if (!fp) {
894                 cprintf(listener, "ERROR: Can't dup %s\n", strerror(errno));
895                 return 0;
896         }
897
898         cf_section2file(fp, home->cs);
899         fclose(fp);
900
901         return 1;
902 }
903
904 extern void revive_home_server(void *ctx);
905 extern void mark_home_server_dead(home_server *home, struct timeval *when);
906
907 static int command_set_home_server_state(rad_listen_t *listener, int argc, char *argv[])
908 {
909         home_server *home;
910
911         if (argc < 3) {
912                 cprintf(listener, "ERROR: Must specify <ipaddr> <port> <state>\n");
913                 return 0;
914         }
915
916         home = get_home_server(listener, argc, argv);
917         if (!home) {
918                 return 0;
919         }
920
921         if (strcmp(argv[2], "alive") == 0) {
922                 revive_home_server(home);
923
924         } else if (strcmp(argv[2], "dead") == 0) {
925                 struct timeval now;
926
927                 gettimeofday(&now, NULL); /* we do this WAY too ofetn */
928                 mark_home_server_dead(home, &now);
929
930         } else {
931                 cprintf(listener, "ERROR: Unknown state \"%s\"\n", argv[2]);
932                 return 0;
933         }
934
935         return 1;
936 }
937
938 static int command_show_home_server_state(rad_listen_t *listener, int argc, char *argv[])
939 {
940         home_server *home;
941
942         home = get_home_server(listener, argc, argv);
943         if (!home) {
944                 return 0;
945         }
946
947         switch (home->state) {
948         case HOME_STATE_ALIVE:
949                 cprintf(listener, "alive\n");
950                 break;
951
952         case HOME_STATE_IS_DEAD:
953                 cprintf(listener, "dead\n");
954                 break;
955
956         case HOME_STATE_ZOMBIE:
957                 cprintf(listener, "zombie\n");
958                 break;
959
960         default:
961                 cprintf(listener, "unknown\n");
962                 break;
963         }
964         
965         return 1;
966 }
967 #endif
968
969 /*
970  *      For encode/decode stuff
971  */
972 static int null_socket_dencode(UNUSED rad_listen_t *listener, UNUSED REQUEST *request)
973 {
974         return 0;
975 }
976
977 static int null_socket_send(UNUSED rad_listen_t *listener, REQUEST *request)
978 {
979         char *output_file;
980         FILE *fp;
981         VALUE_PAIR *vp;
982
983         output_file = request_data_reference(request, null_socket_send, 0);
984         if (!output_file) {
985                 radlog(L_ERR, "WARNING: No output file for injected packet %d",
986                        request->number);
987                 return 0;
988         }
989
990         fp = fopen(output_file, "w");
991         if (!fp) {
992                 radlog(L_ERR, "Failed to send injected file to %s: %s",
993                        output_file, strerror(errno));
994                 return 0;
995         }
996
997         if (request->reply->code != 0) {
998                 const char *what = "reply";
999                 char buffer[1024];
1000
1001                 if (request->reply->code < FR_MAX_PACKET_CODE) {
1002                         what = fr_packet_codes[request->reply->code];
1003                 }
1004
1005                 fprintf(fp, "%s\n", what);
1006
1007                 if (debug_flag) {
1008                         request->radlog(L_DBG, 0, request,
1009                                         "Injected %s packet to host %s port 0 code=%d, id=%d",
1010                                         what,
1011                                         inet_ntop(request->reply->src_ipaddr.af,
1012                                                   &request->reply->src_ipaddr.ipaddr,
1013                                                   buffer, sizeof(buffer)),
1014                                         request->reply->code, request->reply->id);
1015                 }
1016
1017                 for (vp = request->reply->vps; vp != NULL; vp = vp->next) {
1018                         vp_prints(buffer, sizeof(buffer), vp);
1019                         fprintf(fp, "%s\n", buffer);
1020                         if (debug_flag) {
1021                                 request->radlog(L_DBG, 0, request, "\t%s",
1022                                                 buffer);
1023                         }
1024                 }
1025         }
1026         fclose(fp);
1027
1028         return 0;
1029 }
1030
1031 static int command_inject_to(rad_listen_t *listener, int argc, char *argv[])
1032 {
1033         int port;
1034         RAD_LISTEN_TYPE type;
1035         fr_command_socket_t *sock = listener->data;
1036         fr_ipaddr_t ipaddr;
1037         rad_listen_t *found = NULL;
1038
1039         if (argc < 1) {
1040                 cprintf(listener, "ERROR: Must specify [auth/acct]\n");
1041                 return 0;
1042         }
1043
1044         if (strcmp(argv[0], "auth") == 0) {
1045                 type = RAD_LISTEN_AUTH;
1046
1047         } else if (strcmp(argv[0], "acct") == 0) {
1048 #ifdef WITH_ACCOUNTING
1049                 type = RAD_LISTEN_ACCT;
1050 #else
1051                 cprintf(listener, "ERROR: This server was built without accounting support.\n");
1052                 return 0;
1053 #endif
1054
1055         } else {
1056                 cprintf(listener, "ERROR: Unknown socket type\n");
1057                 return 0;
1058         }
1059
1060         if (argc < 3) {
1061                 cprintf(listener, "ERROR: No <ipaddr> <port> was given\n");
1062                 return 0;
1063         }
1064
1065         /*
1066          *      FIXME:  Look for optional arg 4, and bind interface.
1067          */
1068
1069         if (ip_hton(argv[1], AF_UNSPEC, &ipaddr) < 0) {
1070                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
1071                         fr_strerror());
1072                 return 0;
1073         }
1074         port = atoi(argv[2]);
1075
1076         found = listener_find_byipaddr(&ipaddr, port);
1077         if (!found) {
1078                 cprintf(listener, "ERROR: Could not find matching listener\n");
1079                 return 0;
1080         }
1081
1082         sock->inject_listener = found;
1083         sock->dst_ipaddr = ipaddr;
1084         sock->dst_port = port;
1085
1086         return 1;
1087 }
1088
1089 static int command_inject_from(rad_listen_t *listener, int argc, char *argv[])
1090 {
1091         RADCLIENT *client;
1092         fr_command_socket_t *sock = listener->data;
1093
1094         if (argc < 1) {
1095                 cprintf(listener, "ERROR: No <ipaddr> was given\n");
1096                 return 0;
1097         }
1098
1099         if (!sock->inject_listener) {
1100                 cprintf(listener, "ERROR: You must specify \"inject to\" before using \"inject from\"\n");
1101                 return 0;
1102         }
1103
1104         sock->src_ipaddr.af = AF_UNSPEC;
1105         if (ip_hton(argv[0], AF_UNSPEC, &sock->src_ipaddr) < 0) {
1106                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
1107                         fr_strerror());
1108                 return 0;
1109         }
1110
1111         client = client_listener_find(sock->inject_listener, &sock->src_ipaddr,
1112                                       0);
1113         if (!client) {
1114                 cprintf(listener, "ERROR: No such client %s\n", argv[0]);
1115                 return 0;
1116         }
1117         sock->inject_client = client;
1118
1119         return 1;
1120 }
1121
1122 static int command_inject_file(rad_listen_t *listener, int argc, char *argv[])
1123 {
1124         static int inject_id = 0;
1125         int filedone;
1126         fr_command_socket_t *sock = listener->data;
1127         rad_listen_t *fake;
1128         REQUEST *request = NULL;
1129         RADIUS_PACKET *packet;
1130         VALUE_PAIR *vp;
1131         FILE *fp;
1132         RAD_REQUEST_FUNP fun = NULL;
1133         char buffer[2048];
1134
1135         if (argc < 2) {
1136                 cprintf(listener, "ERROR: You must specify <input-file> <output-file>\n");
1137                 return 0;
1138         }
1139
1140         /*
1141          *      Output files always go to the logging directory.
1142          */
1143         snprintf(buffer, sizeof(buffer), "%s/%s", radlog_dir, argv[1]);
1144
1145         fp = fopen(argv[0], "r");
1146         if (!fp ) {
1147                 cprintf(listener, "ERROR: Failed opening %s: %s\n",
1148                         argv[0], strerror(errno));
1149                 return 0;
1150         }
1151
1152         vp = readvp2(fp, &filedone, "");
1153         fclose(fp);
1154         if (!vp) {
1155                 cprintf(listener, "ERROR: Failed reading attributes from %s: %s\n",
1156                         argv[0], fr_strerror());
1157                 return 0;
1158         }
1159
1160         fake = rad_malloc(sizeof(*fake));
1161         memcpy(fake, sock->inject_listener, sizeof(*fake));
1162
1163         /*
1164          *      Re-write the IO for the listener.
1165          */
1166         fake->encode = null_socket_dencode;
1167         fake->decode = null_socket_dencode;
1168         fake->send = null_socket_send;
1169
1170         packet = rad_alloc(0);
1171         packet->src_ipaddr = sock->src_ipaddr;
1172         packet->src_port = 0;
1173
1174         packet->dst_ipaddr = sock->dst_ipaddr;
1175         packet->dst_port = sock->dst_port;
1176         packet->vps = vp;
1177         packet->id = inject_id++;
1178
1179         if (fake->type == RAD_LISTEN_AUTH) {
1180                 packet->code = PW_AUTHENTICATION_REQUEST;
1181                 fun = rad_authenticate;
1182
1183         } else {
1184 #ifdef WITH_ACCOUNTING
1185                 packet->code = PW_ACCOUNTING_REQUEST;
1186                 fun = rad_accounting;
1187 #else
1188                 cprintf(listener, "ERROR: This server was built without accounting support.\n");
1189                 rad_free(&packet);
1190                 free(fake);
1191                 return 0;
1192 #endif
1193         }
1194
1195         if (!received_request(fake, packet, &request, sock->inject_client)) {
1196                 cprintf(listener, "ERROR: Failed to inject request.  See log file for details\n");
1197                 rad_free(&packet);
1198                 free(fake);
1199                 return 0;
1200         }
1201
1202         /*
1203          *      Remember what the output file is, and remember to
1204          *      delete the fake listener when done.
1205          */
1206         request_data_add(request, null_socket_send, 0, strdup(buffer), free);
1207         request_data_add(request, null_socket_send, 1, fake, free);
1208
1209         if (debug_flag) {
1210                 request->radlog(L_DBG, 0, request,
1211                                 "Injected %s packet from host %s port 0 code=%d, id=%d",
1212                                 fr_packet_codes[packet->code],
1213                                 inet_ntop(packet->src_ipaddr.af,
1214                                           &packet->src_ipaddr.ipaddr,
1215                                           buffer, sizeof(buffer)),
1216                                 packet->code, packet->id);
1217                 
1218                 for (vp = packet->vps; vp != NULL; vp = vp->next) {
1219                         vp_prints(buffer, sizeof(buffer), vp);
1220                         request->radlog(L_DBG, 0, request, "\t%s", buffer);
1221                 }
1222         }
1223
1224         /*
1225          *      And go process it.
1226          */
1227         thread_pool_addrequest(request, fun);
1228
1229         return 1;
1230 }
1231
1232
1233 static fr_command_table_t command_table_inject[] = {
1234         { "to", FR_WRITE,
1235           "inject to <ipaddr> <port> - Inject packets to the destination IP and port.",
1236           command_inject_to, NULL },
1237
1238         { "from", FR_WRITE,
1239           "inject from <ipaddr> - Inject packets as if they came from <ipaddr>",
1240           command_inject_from, NULL },
1241
1242         { "file", FR_WRITE,
1243           "inject file <input-file> <output-file> - Inject packet from input-file>, with results sent to <output-file>",
1244           command_inject_file, NULL },
1245
1246         { NULL, 0, NULL, NULL, NULL }
1247 };
1248
1249 static fr_command_table_t command_table_debug[] = {
1250         { "condition", FR_WRITE,
1251           "debug condition [condition] - Enable debugging for requests matching [condition]",
1252           command_debug_condition, NULL },
1253
1254         { "level", FR_WRITE,
1255           "debug level <number> - Set debug level to <number>.  Higher is more debugging.",
1256           command_debug_level, NULL },
1257
1258         { "file", FR_WRITE,
1259           "debug file [filename] - Send all debugging output to [filename]",
1260           command_debug_file, NULL },
1261
1262         { NULL, 0, NULL, NULL, NULL }
1263 };
1264
1265 static fr_command_table_t command_table_show_debug[] = {
1266         { "condition", FR_READ,
1267           "show debug condition - Shows current debugging condition.",
1268           command_show_debug_condition, NULL },
1269
1270         { "level", FR_READ,
1271           "show debug level - Shows current debugging level.",
1272           command_show_debug_level, NULL },
1273
1274         { "file", FR_READ,
1275           "show debug file - Shows current debugging file.",
1276           command_show_debug_file, NULL },
1277
1278         { NULL, 0, NULL, NULL, NULL }
1279 };
1280
1281 static fr_command_table_t command_table_show_module[] = {
1282         { "config", FR_READ,
1283           "show module config <module> - show configuration for given module",
1284           command_show_module_config, NULL },
1285         { "flags", FR_READ,
1286           "show module flags <module> - show other module properties",
1287           command_show_module_flags, NULL },
1288         { "list", FR_READ,
1289           "show module list - shows list of loaded modules",
1290           command_show_modules, NULL },
1291         { "methods", FR_READ,
1292           "show module methods <module> - show sections where <module> may be used",
1293           command_show_module_methods, NULL },
1294
1295         { NULL, 0, NULL, NULL, NULL }
1296 };
1297
1298 static fr_command_table_t command_table_show_client[] = {
1299         { "config", FR_READ,
1300           "show client config <ipaddr> - show configuration for given client",
1301           command_show_client_config, NULL },
1302         { "list", FR_READ,
1303           "show client list - shows list of global clients",
1304           command_show_clients, NULL },
1305
1306         { NULL, 0, NULL, NULL, NULL }
1307 };
1308
1309 #ifdef WITH_PROXY
1310 static fr_command_table_t command_table_show_home[] = {
1311         { "config", FR_READ,
1312           "show home_server config <ipaddr> <port> - show configuration for given home server",
1313           command_show_home_server_config, NULL },
1314         { "list", FR_READ,
1315           "show home_server list - shows list of home servers",
1316           command_show_home_servers, NULL },
1317         { "state", FR_READ,
1318           "show home_server state <ipaddr> <port> - shows state of given home server",
1319           command_show_home_server_state, NULL },
1320
1321         { NULL, 0, NULL, NULL, NULL }
1322 };
1323 #endif
1324
1325
1326 static fr_command_table_t command_table_show[] = {
1327         { "client", FR_READ,
1328           "show client <command> - do sub-command of client",
1329           NULL, command_table_show_client },
1330         { "debug", FR_READ,
1331           "show debug <command> - show debug properties",
1332           NULL, command_table_show_debug },
1333 #ifdef WITH_PROXY
1334         { "home_server", FR_READ,
1335           "show home_server <command> - do sub-command of home_server",
1336           NULL, command_table_show_home },
1337 #endif
1338         { "module", FR_READ,
1339           "show module <command> - do sub-command of module",
1340           NULL, command_table_show_module },
1341         { "uptime", FR_READ,
1342           "show uptime - shows time at which server started",
1343           command_uptime, NULL },
1344         { "version", FR_READ,
1345           "show version - Prints version of the running server",
1346           command_show_version, NULL },
1347         { "xml", FR_READ,
1348           "show xml <reference> - Prints out configuration as XML",
1349           command_show_xml, NULL },
1350         { NULL, 0, NULL, NULL, NULL }
1351 };
1352
1353
1354 static int command_set_module_config(rad_listen_t *listener, int argc, char *argv[])
1355 {
1356         int i, rcode;
1357         CONF_PAIR *cp;
1358         CONF_SECTION *cs;
1359         module_instance_t *mi;
1360         const CONF_PARSER *variables;
1361         void *data;
1362
1363         if (argc < 3) {
1364                 cprintf(listener, "ERROR: No module name or variable was given\n");
1365                 return 0;
1366         }
1367
1368         cs = cf_section_find("modules");
1369         if (!cs) return 0;
1370
1371         mi = find_module_instance(cs, argv[0], 0);
1372         if (!mi) {
1373                 cprintf(listener, "ERROR: No such module \"%s\"\n", argv[0]);
1374                 return 0;
1375         }
1376
1377         if ((mi->entry->module->type & RLM_TYPE_HUP_SAFE) == 0) {
1378                 cprintf(listener, "ERROR: Cannot change configuration of module as it is cannot be HUP'd.\n");
1379                 return 0;
1380         }
1381
1382         variables = cf_section_parse_table(mi->cs);
1383         if (!variables) {
1384                 cprintf(listener, "ERROR: Cannot find configuration for module\n");
1385                 return 0;
1386         }
1387
1388         rcode = -1;
1389         for (i = 0; variables[i].name != NULL; i++) {
1390                 /*
1391                  *      FIXME: Recurse into sub-types somehow...
1392                  */
1393                 if (variables[i].type == PW_TYPE_SUBSECTION) continue;
1394
1395                 if (strcmp(variables[i].name, argv[1]) == 0) {
1396                         rcode = i;
1397                         break;
1398                 }
1399         }
1400
1401         if (rcode < 0) {
1402                 cprintf(listener, "ERROR: No such variable \"%s\"\n", argv[1]);
1403                 return 0;
1404         }
1405
1406         i = rcode;              /* just to be safe */
1407
1408         /*
1409          *      It's not part of the dynamic configuration.  The module
1410          *      needs to re-parse && validate things.
1411          */
1412         if (variables[i].data) {
1413                 cprintf(listener, "ERROR: Variable cannot be dynamically updated\n");
1414                 return 0;
1415         }
1416
1417         data = ((char *) mi->insthandle) + variables[i].offset;
1418
1419         cp = cf_pair_find(mi->cs, argv[1]);
1420         if (!cp) return 0;
1421
1422         /*
1423          *      Replace the OLD value in the configuration file with
1424          *      the NEW value.
1425          *
1426          *      FIXME: Parse argv[2] depending on it's data type!
1427          *      If it's a string, look for leading single/double quotes,
1428          *      end then call tokenize functions???
1429          */
1430         cf_pair_replace(mi->cs, cp, argv[2]);
1431
1432         rcode = cf_item_parse(mi->cs, argv[1], variables[i].type,
1433                               data, argv[2]);
1434         if (rcode < 0) {
1435                 cprintf(listener, "ERROR: Failed to parse value\n");
1436                 return 0;
1437         }
1438
1439         return 1;               /* success */
1440 }
1441
1442 static int command_print_stats(rad_listen_t *listener, fr_stats_t *stats,
1443                                int auth)
1444 {
1445         cprintf(listener, "\trequests\t%d\n", stats->total_requests);
1446         cprintf(listener, "\tresponses\t%d\n", stats->total_responses);
1447         
1448         if (auth) {
1449                 cprintf(listener, "\taccepts\t\t%d\n",
1450                         stats->total_access_accepts);
1451                 cprintf(listener, "\trejects\t\t%d\n",
1452                         stats->total_access_rejects);
1453                 cprintf(listener, "\tchallenges\t%d\n",
1454                         stats->total_access_challenges);
1455         }
1456
1457         cprintf(listener, "\tdup\t\t%d\n", stats->total_dup_requests);
1458         cprintf(listener, "\tinvalid\t\t%d\n", stats->total_invalid_requests);
1459         cprintf(listener, "\tmalformed\t%d\n", stats->total_malformed_requests);
1460         cprintf(listener, "\tbad_signature\t%d\n", stats->total_bad_authenticators);
1461         cprintf(listener, "\tdropped\t\t%d\n", stats->total_packets_dropped);
1462         cprintf(listener, "\tunknown_types\t%d\n", stats->total_unknown_types);
1463         
1464         return 1;
1465 }
1466
1467
1468 #ifdef WITH_PROXY
1469 static int command_stats_home_server(rad_listen_t *listener, int argc, char *argv[])
1470 {
1471         home_server *home;
1472
1473         if (argc == 0) {
1474                 cprintf(listener, "ERROR: Must specify [auth/acct] OR <ipaddr> <port>\n");
1475                 return 0;
1476         }
1477
1478         if (argc == 1) {
1479 #ifdef WITH_ACCOUNTING
1480                 if (strcmp(argv[0], "acct") == 0) {
1481                         return command_print_stats(listener,
1482                                                    &proxy_acct_stats, 0);
1483                 }
1484 #endif
1485                 if (strcmp(argv[0], "auth") == 0) {
1486                         return command_print_stats(listener,
1487                                                    &proxy_auth_stats, 1);
1488                 }
1489
1490                 cprintf(listener, "ERROR: Should specify [auth/acct]\n");
1491                 return 0;
1492         }
1493
1494         home = get_home_server(listener, argc, argv);
1495         if (!home) {
1496                 return 0;
1497         }
1498
1499         command_print_stats(listener, &home->stats,
1500                             (home->type == HOME_TYPE_AUTH));
1501         cprintf(listener, "\toutstanding\t%d\n", home->currently_outstanding);
1502         return 1;
1503 }
1504 #endif
1505
1506 static int command_stats_client(rad_listen_t *listener, int argc, char *argv[])
1507 {
1508         int auth = TRUE;
1509         RADCLIENT *client;
1510
1511         if (argc < 1) {
1512                 cprintf(listener, "ERROR: Must specify [auth/acct]\n");
1513                 return 0;
1514         }
1515
1516         if (strcmp(argv[0], "auth") == 0) {
1517                 auth = TRUE;
1518
1519         } else if (strcmp(argv[0], "acct") == 0) {
1520 #ifdef WITH_ACCOUNTING
1521                 auth = FALSE;
1522 #else
1523                 cprintf(listener, "ERROR: This server was built without accounting support.\n");
1524                 return 0;
1525 #endif
1526
1527         } else {
1528                 cprintf(listener, "ERROR: Unknown statistics type\n");
1529                 return 0;
1530         }
1531
1532         /*
1533          *      Global results for all client.
1534          */
1535         if (argc == 1) {
1536 #ifdef WITH_ACCOUNTING
1537                 if (!auth) {
1538                         return command_print_stats(listener,
1539                                                    &radius_acct_stats, auth);
1540                 }
1541 #endif
1542                 return command_print_stats(listener, &radius_auth_stats, auth);
1543         }
1544
1545         client = get_client(listener, argc - 1, argv + 1);
1546         if (!client) {
1547                 return 0;
1548         }
1549
1550 #ifdef WITH_ACCOUNTING
1551         if (!auth) {
1552                 return command_print_stats(listener, client->acct, auth);
1553         }
1554 #endif
1555
1556         return command_print_stats(listener, client->auth, auth);
1557 }
1558
1559
1560 static int command_add_client_file(rad_listen_t *listener, int argc, char *argv[])
1561 {
1562         RADCLIENT *c;
1563
1564         if (argc < 1) {
1565                 cprintf(listener, "ERROR: <file> is required\n");
1566                 return 0;
1567         }
1568
1569         /*
1570          *      Read the file and generate the client.
1571          */
1572         c = client_read(argv[0], FALSE, FALSE);
1573         if (!c) {
1574                 cprintf(listener, "ERROR: Unknown error reading client file.\n");
1575                 return 0;
1576         }
1577
1578         if (!client_add(NULL, c)) {
1579                 cprintf(listener, "ERROR: Unknown error inserting new client.\n");
1580                 client_free(c);
1581                 return 0;
1582         }
1583
1584         return 1;
1585 }
1586
1587
1588 static fr_command_table_t command_table_add_client[] = {
1589         { "file", FR_WRITE,
1590           "add client file <filename> - Add new client definition from <filename>",
1591           command_add_client_file, NULL },
1592
1593         { NULL, 0, NULL, NULL, NULL }
1594 };
1595
1596
1597 static fr_command_table_t command_table_add[] = {
1598         { "client", FR_WRITE,
1599           "add client <command> - Add client configuration commands",
1600           NULL, command_table_add_client },
1601
1602         { NULL, 0, NULL, NULL, NULL }
1603 };
1604
1605
1606 #ifdef WITH_PROXY
1607 static fr_command_table_t command_table_set_home[] = {
1608         { "state", FR_WRITE,
1609           "set home_server state <ipaddr> <port> [alive|dead] - set state for given home server",
1610           command_set_home_server_state, NULL },
1611
1612         { NULL, 0, NULL, NULL, NULL }
1613 };
1614 #endif
1615
1616 static fr_command_table_t command_table_set_module[] = {
1617         { "config", FR_WRITE,
1618           "set module config <module> variable value - set configuration for <module>",
1619           command_set_module_config, NULL },
1620
1621         { NULL, 0, NULL, NULL, NULL }
1622 };
1623
1624
1625 static fr_command_table_t command_table_set[] = {
1626         { "module", FR_WRITE,
1627           "set module <command> - set module commands",
1628           NULL, command_table_set_module },
1629 #ifdef WITH_PROXY
1630         { "home_server", FR_WRITE, 
1631           "set home_server <command> - set home server commands",
1632           NULL, command_table_set_home },
1633 #endif
1634
1635         { NULL, 0, NULL, NULL, NULL }
1636 };
1637
1638
1639 static fr_command_table_t command_table_stats[] = {
1640         { "client", FR_READ,
1641           "stats client [auth/acct] <ipaddr> - show statistics for given client, or for all clients (auth or acct)",
1642           command_stats_client, NULL },
1643 #ifdef WITH_PROXY
1644         { "home_server", FR_READ,
1645           "stats home_server [<ipaddr>/auth/acct] <port> - show statistics for given home server (ipaddr and port), or for all home servers (auth or acct)",
1646           command_stats_home_server, NULL },
1647 #endif
1648
1649         { NULL, 0, NULL, NULL, NULL }
1650 };
1651
1652 static fr_command_table_t command_table[] = {
1653         { "add", FR_WRITE, NULL, NULL, command_table_add },
1654         { "debug", FR_WRITE,
1655           "debug <command> - debugging commands",
1656           NULL, command_table_debug },
1657         { "hup", FR_WRITE,
1658           "hup [module] - sends a HUP signal to the server, or optionally to one module",
1659           command_hup, NULL },
1660         { "inject", FR_WRITE,
1661           "inject <command> - commands to inject packets into a running server",
1662           NULL, command_table_inject },
1663         { "reconnect", FR_READ,
1664           "reconnect - reconnect to a running server",
1665           NULL, NULL },         /* just here for "help" */
1666         { "terminate", FR_WRITE,
1667           "terminate - terminates the server, and cause it to exit",
1668           command_terminate, NULL },
1669         { "set", FR_WRITE, NULL, NULL, command_table_set },
1670         { "show",  FR_READ, NULL, NULL, command_table_show },
1671         { "stats",  FR_READ, NULL, NULL, command_table_stats },
1672
1673         { NULL, 0, NULL, NULL, NULL }
1674 };
1675
1676
1677 /*
1678  *      Parse the unix domain sockets.
1679  *
1680  *      FIXME: TCP + SSL, after RadSec is in.
1681  */
1682 static int command_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
1683 {
1684         fr_command_socket_t *sock;
1685
1686         sock = this->data;
1687
1688         if (cf_section_parse(cs, sock, command_config) < 0) {
1689                 return -1;
1690         }
1691
1692 #if defined(HAVE_GETPEEREID) || defined (SO_PEERCRED)
1693         if (sock->uid_name) {
1694                 struct passwd *pw;
1695                 
1696                 pw = getpwnam(sock->uid_name);
1697                 if (!pw) {
1698                         radlog(L_ERR, "Failed getting uid for %s: %s",
1699                                sock->uid_name, strerror(errno));
1700                         return -1;
1701                 }
1702
1703                 sock->uid = pw->pw_uid;
1704         }
1705
1706         if (sock->gid_name) {
1707                 struct group *gr;
1708
1709                 gr = getgrnam(sock->gid_name);
1710                 if (!gr) {
1711                         radlog(L_ERR, "Failed getting gid for %s: %s",
1712                                sock->gid_name, strerror(errno));
1713                         return -1;
1714                 }
1715                 sock->gid = gr->gr_gid; 
1716         }
1717
1718 #else  /* can't get uid or gid of connecting user */
1719
1720         if (sock->uid_name || sock->gid_name) {
1721                 radlog(L_ERR, "System does not support uid or gid authentication for sockets");
1722                 return -1;
1723         }
1724
1725 #endif
1726
1727         if (!sock->mode_name) {
1728                 sock->mode = FR_READ;
1729         } else {
1730                 sock->mode = fr_str2int(mode_names, sock->mode_name, 0);
1731                 if (!sock->mode) {
1732                         radlog(L_ERR, "Invalid mode name \"%s\"",
1733                                sock->mode_name);
1734                         return -1;
1735                 }
1736         }
1737
1738         /*
1739          *      FIXME: check for absolute pathnames?
1740          *      check for uid/gid on the other end...    
1741          */
1742
1743         this->fd = fr_server_domain_socket(sock->path);
1744         if (this->fd < 0) {
1745                 return -1;
1746         }
1747
1748         return 0;
1749 }
1750
1751 static int command_socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
1752 {
1753         fr_command_socket_t *sock = this->data;
1754
1755         snprintf(buffer, bufsize, "command file %s", sock->path);
1756         return 1;
1757 }
1758
1759
1760 /*
1761  *      String split routine.  Splits an input string IN PLACE
1762  *      into pieces, based on spaces.
1763  */
1764 static int str2argv(char *str, char **argv, int max_argc)
1765 {
1766         int argc = 0;
1767         size_t len;
1768         char buffer[1024];
1769
1770         while (*str) {
1771                 if (argc >= max_argc) return argc;
1772
1773                 /*
1774                  *      Chop out comments early.
1775                  */
1776                 if (*str == '#') {
1777                         *str = '\0';
1778                         break;
1779                 }
1780
1781                 while ((*str == ' ') ||
1782                        (*str == '\t') ||
1783                        (*str == '\r') ||
1784                        (*str == '\n')) *(str++) = '\0';
1785
1786                 if (!*str) return argc;
1787
1788                 if ((*str == '\'') || (*str == '"')) {
1789                         char *p = str;
1790                         FR_TOKEN token;
1791
1792                         token = gettoken((const char **) &p, buffer,
1793                                          sizeof(buffer));
1794                         if ((token != T_SINGLE_QUOTED_STRING) &&
1795                             (token != T_DOUBLE_QUOTED_STRING)) {
1796                                 return -1;
1797                         }
1798
1799                         len = strlen(buffer);
1800                         if (len >= (size_t) (p - str)) {
1801                                 return -1;
1802                         }
1803
1804                         memcpy(str, buffer, len + 1);
1805                         argv[argc] = str;
1806                         str = p;
1807
1808                 } else {
1809                         argv[argc] = str;
1810                 }
1811                 argc++;
1812
1813                 while (*str &&
1814                        (*str != ' ') &&
1815                        (*str != '\t') &&
1816                        (*str != '\r') &&
1817                        (*str != '\n')) str++;
1818         }
1819
1820         return argc;
1821 }
1822
1823 static void print_help(rad_listen_t *listener,
1824                        fr_command_table_t *table, int recursive)
1825 {
1826         int i;
1827         
1828         for (i = 0; table[i].command != NULL; i++) {
1829                 if (table[i].help) {
1830                         cprintf(listener, "%s\n",
1831                                 table[i].help);
1832                 } else {
1833                         cprintf(listener, "%s <command> - do sub-command of %s\n",
1834                                 table[i].command, table[i].command);
1835                 }
1836
1837                 if (recursive && table[i].table) {
1838                         print_help(listener, table[i].table, recursive);
1839                 }
1840         }
1841 }
1842
1843 #define MAX_ARGV (16)
1844
1845 /*
1846  *      Check if an incoming request is "ok"
1847  *
1848  *      It takes packets, not requests.  It sees if the packet looks
1849  *      OK.  If so, it does a number of sanity checks on it.
1850  */
1851 static int command_domain_recv(rad_listen_t *listener,
1852                                UNUSED RAD_REQUEST_FUNP *pfun,
1853                                UNUSED REQUEST **prequest)
1854 {
1855         int i, rcode;
1856         ssize_t len;
1857         int argc;
1858         char *my_argv[MAX_ARGV], **argv;
1859         fr_command_table_t *table;
1860         fr_command_socket_t *co = listener->data;
1861
1862         *pfun = NULL;
1863         *prequest = NULL;
1864
1865         do {
1866                 ssize_t c;
1867                 char *p;
1868
1869                 len = recv(listener->fd, co->buffer + co->offset,
1870                            sizeof(co->buffer) - co->offset - 1, 0);
1871                 if (len == 0) goto close_socket; /* clean close */
1872
1873                 if (len < 0) {
1874                         if ((errno == EAGAIN) || (errno == EINTR)) {
1875                                 return 0;
1876                         }
1877                         goto close_socket;
1878                 }
1879
1880                 /*
1881                  *      CTRL-D
1882                  */
1883                 if ((co->offset == 0) && (co->buffer[0] == 0x04)) {
1884                 close_socket:
1885                         command_close_socket(listener);
1886                         return 0;
1887                 }
1888
1889                 /*
1890                  *      See if there are multiple lines in the buffer.
1891                  */
1892                 p = co->buffer + co->offset;
1893                 rcode = 0;
1894                 p[len] = '\0';
1895                 for (c = 0; c < len; c++) {
1896                         if ((*p == '\r') || (*p == '\n')) {
1897                                 rcode = 1;
1898                                 *p = '\0';
1899
1900                                 /*
1901                                  *      FIXME: do real buffering...
1902                                  *      handling of CTRL-C, etc.
1903                                  */
1904
1905                         } else if (rcode) {
1906                                 /*
1907                                  *      \r \n followed by ASCII...
1908                                  */
1909                                 break;
1910                         }
1911
1912                         p++;
1913                 }
1914
1915                 co->offset += len;
1916
1917                 /*
1918                  *      Saw CR/LF.  Set next element, and exit.
1919                  */
1920                 if (rcode) {
1921                         co->next = p - co->buffer;
1922                         break;
1923                 }
1924
1925                 if (co->offset >= (ssize_t) (sizeof(co->buffer) - 1)) {
1926                         radlog(L_ERR, "Line too long!");
1927                         goto close_socket;
1928                 }
1929
1930                 co->offset++;
1931         } while (1);
1932
1933         argc = str2argv(co->buffer, my_argv, MAX_ARGV);
1934         if (argc == 0) goto do_next; /* empty strings are OK */
1935
1936         if (argc < 0) {
1937                 cprintf(listener, "ERROR: Failed parsing command.\n");
1938                 goto do_next;
1939         }
1940
1941         argv = my_argv;
1942
1943         for (len = 0; len <= co->offset; len++) {
1944                 if (co->buffer[len] < 0x20) {
1945                         co->buffer[len] = '\0';
1946                         break;
1947                 }
1948         }
1949
1950         /*
1951          *      Hard-code exit && quit.
1952          */
1953         if ((strcmp(argv[0], "exit") == 0) ||
1954             (strcmp(argv[0], "quit") == 0)) goto close_socket;
1955
1956 #if 0
1957         if (!co->user[0]) {
1958                 if (strcmp(argv[0], "login") != 0) {
1959                         cprintf(listener, "ERROR: Login required\n");
1960                         goto do_next;
1961                 }
1962
1963                 if (argc < 3) {
1964                         cprintf(listener, "ERROR: login <user> <password>\n");
1965                         goto do_next;
1966                 }
1967
1968                 /*
1969                  *      FIXME: Generate && process fake RADIUS request.
1970                  */
1971                 if ((strcmp(argv[1], "root") == 0) &&
1972                     (strcmp(argv[2], "password") == 0)) {
1973                         strlcpy(co->user, argv[1], sizeof(co->user));
1974                         goto do_next;
1975                 }
1976
1977                 cprintf(listener, "ERROR: Login incorrect\n");
1978                 goto do_next;
1979         }
1980 #endif
1981
1982         table = command_table;
1983  retry:
1984         len = 0;
1985         for (i = 0; table[i].command != NULL; i++) {
1986                 if (strcmp(table[i].command, argv[0]) == 0) {
1987                         /*
1988                          *      Check permissions.
1989                          */
1990                         if (((co->mode & FR_WRITE) == 0) &&
1991                             ((table[i].mode & FR_WRITE) != 0)) {
1992                                 cprintf(listener, "ERROR: You do not have write permission.\n");
1993                                 goto do_next;
1994                         }
1995
1996                         if (table[i].table) {
1997                                 /*
1998                                  *      This is the last argument, but
1999                                  *      there's a sub-table.  Print help.
2000                                  *      
2001                                  */
2002                                 if (argc == 1) {
2003                                         table = table[i].table;
2004                                         goto do_help;
2005                                 }
2006
2007                                 argc--;
2008                                 argv++;
2009                                 table = table[i].table;
2010                                 goto retry;
2011                         }
2012
2013                         if (!table[i].func) {
2014                                 cprintf(listener, "ERROR: Invalid command\n");
2015                                 goto do_next;
2016                         }
2017
2018                         len = 1;
2019                         rcode = table[i].func(listener,
2020                                               argc - 1, argv + 1);
2021                         break;
2022                 }
2023         }
2024
2025         /*
2026          *      No such command
2027          */
2028         if (!len) {
2029                 if ((strcmp(argv[0], "help") == 0) ||
2030                     (strcmp(argv[0], "?") == 0)) {
2031                         int recursive = 0;
2032
2033                 do_help:
2034                         if ((argc > 1) && (strcmp(argv[1], "-r") == 0)) {
2035                                 recursive = TRUE;
2036                         }
2037
2038                         print_help(listener, table, recursive);
2039                         goto do_next;
2040                 }
2041
2042                 cprintf(listener, "ERROR: Unknown command \"%s\"\n",
2043                         argv[0]);
2044         }
2045
2046  do_next:
2047         cprintf(listener, "radmin> ");
2048
2049         if (co->next <= co->offset) {
2050                 co->offset = 0;
2051         } else {
2052                 memmove(co->buffer, co->buffer + co->next,
2053                         co->offset - co->next);
2054                 co->offset -= co->next;
2055         }
2056
2057         return 0;
2058 }
2059
2060
2061 static int command_domain_accept(rad_listen_t *listener,
2062                                  UNUSED RAD_REQUEST_FUNP *pfun,
2063                                  UNUSED REQUEST **prequest)
2064 {
2065         int newfd;
2066         uint32_t magic;
2067         rad_listen_t *this;
2068         socklen_t salen;
2069         struct sockaddr_storage src;
2070         fr_command_socket_t *sock = listener->data;
2071         
2072         salen = sizeof(src);
2073
2074         DEBUG2(" ... new connection request on command socket.");
2075         
2076         newfd = accept(listener->fd, (struct sockaddr *) &src, &salen);
2077         if (newfd < 0) {
2078                 /*
2079                  *      Non-blocking sockets must handle this.
2080                  */
2081                 if (errno == EWOULDBLOCK) {
2082                         return 0;
2083                 }
2084
2085                 DEBUG2(" ... failed to accept connection.");
2086                 return -1;
2087         }
2088
2089         /*
2090          *      Perform user authentication.
2091          */
2092         if (sock->uid_name || sock->gid_name) {
2093                 uid_t uid;
2094                 gid_t gid;
2095
2096                 if (getpeereid(listener->fd, &uid, &gid) < 0) {
2097                         radlog(L_ERR, "Failed getting peer credentials for %s: %s",
2098                                sock->path, strerror(errno));
2099                         close(newfd);
2100                         return -1;
2101                 }
2102
2103                 if (sock->uid_name && (sock->uid != uid)) {
2104                         radlog(L_ERR, "Unauthorized connection to %s from uid %ld",
2105                                sock->path, (long int) uid);
2106                         close(newfd);
2107                         return -1;
2108                 }
2109
2110                 if (sock->gid_name && (sock->gid != gid)) {
2111                         radlog(L_ERR, "Unauthorized connection to %s from gid %ld",
2112                                sock->path, (long int) gid);
2113                         close(newfd);
2114                         return -1;
2115                 }
2116         }
2117
2118         /*
2119          *      Write 32-bit magic number && version information.
2120          */
2121         magic = htonl(0xf7eead15);
2122         if (write(newfd, &magic, 4) < 0) {
2123                 radlog(L_ERR, "Failed writing initial data to socket: %s",
2124                        strerror(errno));
2125                 close(newfd);
2126                 return -1;
2127         }
2128         magic = htonl(1);       /* protocol version */
2129         if (write(newfd, &magic, 4) < 0) {
2130                 radlog(L_ERR, "Failed writing initial data to socket: %s",
2131                        strerror(errno));
2132                 close(newfd);
2133                 return -1;
2134         }
2135
2136
2137         /*
2138          *      Add the new listener.
2139          */
2140         this = listen_alloc(listener->type);
2141         if (!this) return -1;
2142
2143         /*
2144          *      Copy everything, including the pointer to the socket
2145          *      information.
2146          */
2147         sock = this->data;
2148         memcpy(this, listener, sizeof(*this));
2149         this->status = RAD_LISTEN_STATUS_INIT;
2150         this->next = NULL;
2151         this->data = sock;      /* fix it back */
2152
2153         sock->offset = 0;
2154         sock->user[0] = '\0';
2155         sock->path = ((fr_command_socket_t *) listener->data)->path;
2156         sock->mode = ((fr_command_socket_t *) listener->data)->mode;
2157
2158         this->fd = newfd;
2159         this->recv = command_domain_recv;
2160
2161         /*
2162          *      Tell the event loop that we have a new FD
2163          */
2164         event_new_fd(this);
2165
2166         return 0;
2167 }
2168
2169
2170 /*
2171  *      Send an authentication response packet
2172  */
2173 static int command_domain_send(UNUSED rad_listen_t *listener,
2174                                UNUSED REQUEST *request)
2175 {
2176         return 0;
2177 }
2178
2179
2180 static int command_socket_encode(UNUSED rad_listen_t *listener,
2181                                  UNUSED REQUEST *request)
2182 {
2183         return 0;
2184 }
2185
2186
2187 static int command_socket_decode(UNUSED rad_listen_t *listener,
2188                                  UNUSED REQUEST *request)
2189 {
2190         return 0;
2191 }
2192
2193 #endif /* WITH_COMMAND_SOCKET */