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