Signed / unsigned fixes and function prototypes
[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         char    *copy;          /* <sigh> */
70         uid_t   uid;
71         gid_t   gid;
72         int     mode;
73         char    *uid_name;
74         char    *gid_name;
75         char    *mode_name;
76         char user[256];
77
78         /*
79          *      The next few entries handle fake packets injected by
80          *      the control socket.
81          */
82         fr_ipaddr_t     src_ipaddr; /* src_port is always 0 */
83         fr_ipaddr_t     dst_ipaddr;
84         int             dst_port;
85         rad_listen_t    *inject_listener;
86         RADCLIENT       *inject_client;
87
88         /*
89          *      The next few entries do buffer management.
90          */
91         ssize_t offset;
92         ssize_t next;
93         char buffer[COMMAND_BUFFER_SIZE];
94 } fr_command_socket_t;
95
96 static const CONF_PARSER command_config[] = {
97   { "socket",  PW_TYPE_STRING_PTR,
98     offsetof(fr_command_socket_t, path), NULL, "${run_dir}/radiusd.sock"},
99   { "uid",  PW_TYPE_STRING_PTR,
100     offsetof(fr_command_socket_t, uid_name), NULL, NULL},
101   { "gid",  PW_TYPE_STRING_PTR,
102     offsetof(fr_command_socket_t, gid_name), NULL, NULL},
103   { "mode",  PW_TYPE_STRING_PTR,
104     offsetof(fr_command_socket_t, mode_name), NULL, NULL},
105
106   { NULL, -1, 0, NULL, NULL }           /* end the list */
107 };
108
109 static FR_NAME_NUMBER mode_names[] = {
110         { "ro", FR_READ },
111         { "read-only", FR_READ },
112         { "read-write", FR_READ | FR_WRITE },
113         { "rw", FR_READ | FR_WRITE },
114         { NULL, 0 }
115 };
116
117
118 static ssize_t cprintf(rad_listen_t *listener, const char *fmt, ...)
119 #ifdef __GNUC__
120                 __attribute__ ((format (printf, 2, 3)))
121 #endif
122 ;
123
124 #ifndef HAVE_GETPEEREID
125 static int getpeereid(int s, uid_t *euid, gid_t *egid)
126 {
127 #ifndef SO_PEERCRED
128         return -1;
129 #else
130         struct ucred cr;
131         socklen_t cl = sizeof(cr);
132         
133         if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cl) < 0) {
134                 return -1;
135         }
136
137         *euid = cr.uid;
138         *egid = cr.gid;
139         return 0;
140 #endif /* SO_PEERCRED */
141 }
142 #endif /* HAVE_GETPEEREID */
143
144
145 static int fr_server_domain_socket(const char *path)
146 {
147         int sockfd;
148         size_t len;
149         socklen_t socklen;
150         struct sockaddr_un salocal;
151         struct stat buf;
152
153         len = strlen(path);
154         if (len >= sizeof(salocal.sun_path)) {
155                 radlog(L_ERR, "Path too long in socket filename.");
156                 return -1;
157         }
158
159         if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
160                 radlog(L_ERR, "Failed creating socket: %s",
161                         strerror(errno));
162                 return -1;
163         }
164
165         memset(&salocal, 0, sizeof(salocal));
166         salocal.sun_family = AF_UNIX;
167         memcpy(salocal.sun_path, path, len + 1); /* SUN_LEN does strlen */
168         
169         socklen = SUN_LEN(&salocal);
170
171         /*
172          *      Check the path.
173          */
174         if (stat(path, &buf) < 0) {
175                 if (errno != ENOENT) {
176                         radlog(L_ERR, "Failed to stat %s: %s",
177                                path, strerror(errno));
178                         return -1;
179                 }
180
181                 /*
182                  *      FIXME: Check the enclosing directory?
183                  */
184         } else {                /* it exists */
185                 if (!S_ISREG(buf.st_mode)
186 #ifdef S_ISSOCK
187                     && !S_ISSOCK(buf.st_mode)
188 #endif
189                         ) {
190                         radlog(L_ERR, "Cannot turn %s into socket", path);
191                         return -1;                     
192                 }
193
194                 /*
195                  *      Refuse to open sockets not owned by us.
196                  */
197                 if (buf.st_uid != geteuid()) {
198                         radlog(L_ERR, "We do not own %s", path);
199                         return -1;
200                 }
201
202                 if (unlink(path) < 0) {
203                         radlog(L_ERR, "Failed to delete %s: %s",
204                                path, strerror(errno));
205                         return -1;
206                 }
207         }
208
209         if (bind(sockfd, (struct sockaddr *)&salocal, socklen) < 0) {
210                 radlog(L_ERR, "Failed binding to %s: %s",
211                         path, strerror(errno));
212                 close(sockfd);
213                 return -1;
214         }
215
216         /*
217          *      FIXME: There's a race condition here.  But Linux
218          *      doesn't seem to permit fchmod on domain sockets.
219          */
220         if (chmod(path, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0) {
221                 radlog(L_ERR, "Failed setting permissions on %s: %s",
222                        path, strerror(errno));
223                 close(sockfd);
224                 return -1;
225         }
226
227         if (listen(sockfd, 8) < 0) {
228                 radlog(L_ERR, "Failed listening to %s: %s",
229                         path, strerror(errno));
230                 close(sockfd);
231                 return -1;
232         }
233
234 #ifdef O_NONBLOCK
235         {
236                 int flags;
237                 
238                 if ((flags = fcntl(sockfd, F_GETFL, NULL)) < 0)  {
239                         radlog(L_ERR, "Failure getting socket flags: %s",
240                                 strerror(errno));
241                         close(sockfd);
242                         return -1;
243                 }
244                 
245                 flags |= O_NONBLOCK;
246                 if( fcntl(sockfd, F_SETFL, flags) < 0) {
247                         radlog(L_ERR, "Failure setting socket flags: %s",
248                                 strerror(errno));
249                         close(sockfd);
250                         return -1;
251                 }
252         }
253 #endif
254
255         return sockfd;
256 }
257
258
259 static void command_close_socket(rad_listen_t *this)
260 {
261         this->status = RAD_LISTEN_STATUS_CLOSED;
262
263         /*
264          *      This removes the socket from the event fd, so no one
265          *      will be calling us any more.
266          */
267         event_new_fd(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 = (((const 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, *(const 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                                 ((*(const 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 (*(const char * const *) data) {
424                                 cprintf(listener, "%.*s%s = \"%s\"\n", indent, tabs,
425                                         variables[i].name, *(const char * const *) 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, *proto;
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->proto == IPPROTO_UDP) {
604                         proto = "udp";
605                 }
606 #ifdef WITH_TCP
607                 else if (home->proto == IPPROTO_TCP) {
608                         proto = "tcp";
609                 }
610 #endif
611                 else proto = "??";
612
613                 if (home->state == HOME_STATE_ALIVE) {
614                         state = "alive";
615
616                 } else if (home->state == HOME_STATE_ZOMBIE) {
617                         state = "zombie";
618
619                 } else if (home->state == HOME_STATE_IS_DEAD) {
620                         state = "dead";
621
622                 } else continue;
623
624                 cprintf(listener, "%s\t%d\t%s\t%s\t%s\t%d\n",
625                         ip_ntoh(&home->ipaddr, buffer, sizeof(buffer)),
626                         home->port, proto, type, state,
627                         home->currently_outstanding);
628         }
629
630         return 0;
631 }
632 #endif
633
634 static int command_show_clients(rad_listen_t *listener, UNUSED int argc, UNUSED char *argv[])
635 {
636         int i;
637         RADCLIENT *client;
638         char buffer[256];
639
640         for (i = 0; i < 256; i++) {
641                 client = client_findbynumber(NULL, i);
642                 if (!client) break;
643
644                 ip_ntoh(&client->ipaddr, buffer, sizeof(buffer));
645
646                 if (((client->ipaddr.af == AF_INET) &&
647                      (client->prefix != 32)) ||
648                     ((client->ipaddr.af == AF_INET6) &&
649                      (client->prefix != 128))) {
650                         cprintf(listener, "\t%s/%d\n", buffer, client->prefix);
651                 } else {
652                         cprintf(listener, "\t%s\n", buffer);
653                 }
654         }
655
656         return 0;
657 }
658
659
660 static int command_show_xml(rad_listen_t *listener, UNUSED int argc, UNUSED char *argv[])
661 {
662         CONF_ITEM *ci;
663         FILE *fp = fdopen(dup(listener->fd), "a");
664
665         if (!fp) {
666                 cprintf(listener, "ERROR: Can't dup %s\n", strerror(errno));
667                 return 0;
668         }
669
670         if (argc == 0) {
671                 cprintf(listener, "ERROR: <reference> is required\n");
672                 return 0;
673         }
674         
675         ci = cf_reference_item(mainconfig.config, mainconfig.config, argv[0]);
676         if (!ci) {
677                 cprintf(listener, "ERROR: No such item <reference>\n");
678                 return 0;
679         }
680
681         if (cf_item_is_section(ci)) {
682                 cf_section2xml(fp, cf_itemtosection(ci));
683
684         } else if (cf_item_is_pair(ci)) {
685                 cf_pair2xml(fp, cf_itemtopair(ci));
686
687         } else {
688                 cprintf(listener, "ERROR: No such item <reference>\n");
689                 fclose(fp);
690                 return 0;
691         }
692
693         fclose(fp);
694
695         return 1;               /* success */
696 }
697
698 static int command_show_version(rad_listen_t *listener, UNUSED int argc, UNUSED char *argv[])
699 {
700         cprintf(listener, "%s\n", radiusd_version);
701         return 1;
702 }
703
704 static int command_debug_level(rad_listen_t *listener, int argc, char *argv[])
705 {
706         int number;
707
708         if (argc == 0) {
709                 cprintf(listener, "ERROR: Must specify <number>\n");
710                 return -1;
711         }
712
713         number = atoi(argv[0]);
714         if ((number < 0) || (number > 4)) {
715                 cprintf(listener, "ERROR: <number> must be between 0 and 4\n");
716                 return -1;
717         }
718
719         fr_debug_flag = debug_flag = number;
720
721         return 0;
722 }
723
724 char *debug_log_file = NULL;
725 static char debug_log_file_buffer[1024];
726
727 static int command_debug_file(rad_listen_t *listener, int argc, char *argv[])
728 {
729         if (debug_flag && mainconfig.radlog_dest == RADLOG_STDOUT) {
730                 cprintf(listener, "ERROR: Cannot redirect debug logs to a file when already in debugging mode.\n");
731                 return -1;
732         }
733
734         if ((argc > 0) && (strchr(argv[0], FR_DIR_SEP) != NULL)) {
735                 cprintf(listener, "ERROR: Cannot direct debug logs to absolute path.\n");
736         }
737
738         debug_log_file = NULL;
739
740         if (argc == 0) return 0;
741
742         /*
743          *      This looks weird, but it's here to avoid locking
744          *      a mutex for every log message.
745          */
746         memset(debug_log_file_buffer, 0, sizeof(debug_log_file_buffer));
747
748         /*
749          *      Debug files always go to the logging directory.
750          */
751         snprintf(debug_log_file_buffer, sizeof(debug_log_file_buffer),
752                  "%s/%s", radlog_dir, argv[0]);
753
754         debug_log_file = &debug_log_file_buffer[0];
755
756         return 0;
757 }
758
759 extern char *debug_condition;
760 static int command_debug_condition(UNUSED rad_listen_t *listener, int argc, char *argv[])
761 {
762         /*
763          *      Delete old condition.
764          *
765          *      This is thread-safe because the condition is evaluated
766          *      in the main server thread, as is this code.
767          */
768         free(debug_condition);
769         debug_condition = NULL;
770
771         /*
772          *      Disable it.
773          */
774         if (argc == 0) {
775                 return 0;
776         }
777
778         debug_condition = strdup(argv[0]);
779
780         return 0;
781 }
782
783 static int command_show_debug_condition(rad_listen_t *listener,
784                                         UNUSED int argc, UNUSED char *argv[])
785 {
786         if (!debug_condition) return 0;
787
788         cprintf(listener, "%s\n", debug_condition);
789         return 0;
790 }
791
792
793 static int command_show_debug_file(rad_listen_t *listener,
794                                         UNUSED int argc, UNUSED char *argv[])
795 {
796         if (!debug_log_file) return 0;
797
798         cprintf(listener, "%s\n", debug_log_file);
799         return 0;
800 }
801
802
803 static int command_show_debug_level(rad_listen_t *listener,
804                                         UNUSED int argc, UNUSED char *argv[])
805 {
806         cprintf(listener, "%d\n", debug_flag);
807         return 0;
808 }
809
810
811 static RADCLIENT *get_client(rad_listen_t *listener, int argc, char *argv[])
812 {
813         RADCLIENT *client;
814         fr_ipaddr_t ipaddr;
815         int proto = IPPROTO_UDP;
816
817         if (argc < 1) {
818                 cprintf(listener, "ERROR: Must specify <ipaddr>\n");
819                 return NULL;
820         }
821
822         if (ip_hton(argv[0], AF_UNSPEC, &ipaddr) < 0) {
823                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
824                         fr_strerror());
825                 return NULL;
826         }
827
828 #ifdef WITH_TCP
829         if (argc >= 2) {
830                 if (strcmp(argv[1], "tcp") == 0) {
831                         proto = IPPROTO_TCP;
832
833                 } else if (strcmp(argv[1], "udp") == 0) {
834                         proto = IPPROTO_UDP;
835
836                 } else {
837                         cprintf(listener, "ERROR: Unknown protocol %s.  Please use \"udp\" or \"tcp\"\n",
838                                 argv[1]);
839                         return NULL;
840                 }
841         }
842 #endif
843
844         client = client_find(NULL, &ipaddr, proto);
845         if (!client) {
846                 cprintf(listener, "ERROR: No such client\n");
847                 return NULL;
848         }
849
850         return client;
851 }
852
853
854 static int command_show_client_config(rad_listen_t *listener, int argc, char *argv[])
855 {
856         RADCLIENT *client;
857         FILE *fp;
858
859         client = get_client(listener, argc, argv);
860         if (!client) {
861                 return 0;
862         }
863
864         if (!client->cs) return 1;
865
866         fp = fdopen(dup(listener->fd), "a");
867         if (!fp) {
868                 cprintf(listener, "ERROR: Can't dup %s\n", strerror(errno));
869                 return 0;
870         }
871
872         cf_section2file(fp, client->cs);
873         fclose(fp);
874
875         return 1;
876 }
877
878 #ifdef WITH_PROXY
879 static home_server *get_home_server(rad_listen_t *listener, int argc,
880                                     char *argv[], int *last)
881 {
882         home_server *home;
883         int port;
884         int proto = IPPROTO_UDP;
885         fr_ipaddr_t ipaddr;
886
887         if (argc < 2) {
888                 cprintf(listener, "ERROR: Must specify <ipaddr> <port> [proto]\n");
889                 return NULL;
890         }
891
892         if (ip_hton(argv[0], AF_UNSPEC, &ipaddr) < 0) {
893                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
894                         fr_strerror());
895                 return NULL;
896         }
897
898         port = atoi(argv[1]);
899
900         if (last) *last = 2;
901         if (argc > 2) {
902                 if (strcmp(argv[2], "udp") == 0) {
903                         proto = IPPROTO_UDP;
904                         if (last) *last = 3;
905                 }
906 #ifdef WITH_TCP
907                 if (strcmp(argv[2], "tcp") == 0) {
908                         proto = IPPROTO_TCP;
909                         if (last) *last = 3;
910                 }
911 #endif
912         }
913
914         home = home_server_find(&ipaddr, port, proto);
915         if (!home) {
916                 cprintf(listener, "ERROR: No such home server\n");
917                 return NULL;
918         }
919
920         return home;
921 }
922
923 static int command_show_home_server_config(rad_listen_t *listener, int argc, char *argv[])
924 {
925         home_server *home;
926         FILE *fp;
927
928         home = get_home_server(listener, argc, argv, NULL);
929         if (!home) {
930                 return 0;
931         }
932
933         if (!home->cs) return 1;
934
935         fp = fdopen(dup(listener->fd), "a");
936         if (!fp) {
937                 cprintf(listener, "ERROR: Can't dup %s\n", strerror(errno));
938                 return 0;
939         }
940
941         cf_section2file(fp, home->cs);
942         fclose(fp);
943
944         return 1;
945 }
946
947 static int command_set_home_server_state(rad_listen_t *listener, int argc, char *argv[])
948 {
949         int last;
950         home_server *home;
951
952         if (argc < 3) {
953                 cprintf(listener, "ERROR: Must specify <ipaddr> <port> [proto] <state>\n");
954                 return 0;
955         }
956
957         home = get_home_server(listener, argc, argv, &last);
958         if (!home) {
959                 return 0;
960         }
961
962         if (strcmp(argv[last], "alive") == 0) {
963                 revive_home_server(home);
964
965         } else if (strcmp(argv[last], "dead") == 0) {
966                 struct timeval now;
967
968                 gettimeofday(&now, NULL); /* we do this WAY too ofetn */
969                 mark_home_server_dead(home, &now);
970
971         } else {
972                 cprintf(listener, "ERROR: Unknown state \"%s\"\n", argv[last]);
973                 return 0;
974         }
975
976         return 1;
977 }
978
979 static int command_show_home_server_state(rad_listen_t *listener, int argc, char *argv[])
980 {
981         home_server *home;
982
983         home = get_home_server(listener, argc, argv, NULL);
984         if (!home) {
985                 return 0;
986         }
987
988         switch (home->state) {
989         case HOME_STATE_ALIVE:
990                 cprintf(listener, "alive\n");
991                 break;
992
993         case HOME_STATE_IS_DEAD:
994                 cprintf(listener, "dead\n");
995                 break;
996
997         case HOME_STATE_ZOMBIE:
998                 cprintf(listener, "zombie\n");
999                 break;
1000
1001         default:
1002                 cprintf(listener, "unknown\n");
1003                 break;
1004         }
1005         
1006         return 1;
1007 }
1008 #endif
1009
1010 /*
1011  *      For encode/decode stuff
1012  */
1013 static int null_socket_dencode(UNUSED rad_listen_t *listener, UNUSED REQUEST *request)
1014 {
1015         return 0;
1016 }
1017
1018 static int null_socket_send(UNUSED rad_listen_t *listener, REQUEST *request)
1019 {
1020         char *output_file;
1021         FILE *fp;
1022         VALUE_PAIR *vp;
1023
1024         output_file = request_data_reference(request, null_socket_send, 0);
1025         if (!output_file) {
1026                 radlog(L_ERR, "WARNING: No output file for injected packet %d",
1027                        request->number);
1028                 return 0;
1029         }
1030
1031         fp = fopen(output_file, "w");
1032         if (!fp) {
1033                 radlog(L_ERR, "Failed to send injected file to %s: %s",
1034                        output_file, strerror(errno));
1035                 return 0;
1036         }
1037
1038         if (request->reply->code != 0) {
1039                 const char *what = "reply";
1040                 char buffer[1024];
1041
1042                 if (request->reply->code < FR_MAX_PACKET_CODE) {
1043                         what = fr_packet_codes[request->reply->code];
1044                 }
1045
1046                 fprintf(fp, "%s\n", what);
1047
1048                 if (debug_flag) {
1049                         request->radlog(L_DBG, 0, request,
1050                                         "Injected %s packet to host %s port 0 code=%d, id=%d",
1051                                         what,
1052                                         inet_ntop(request->reply->src_ipaddr.af,
1053                                                   &request->reply->src_ipaddr.ipaddr,
1054                                                   buffer, sizeof(buffer)),
1055                                         request->reply->code, request->reply->id);
1056                 }
1057
1058                 for (vp = request->reply->vps; vp != NULL; vp = vp->next) {
1059                         vp_prints(buffer, sizeof(buffer), vp);
1060                         fprintf(fp, "%s\n", buffer);
1061                         if (debug_flag) {
1062                                 request->radlog(L_DBG, 0, request, "\t%s",
1063                                                 buffer);
1064                         }
1065                 }
1066         }
1067         fclose(fp);
1068
1069         return 0;
1070 }
1071
1072 static int command_inject_to(rad_listen_t *listener, int argc, char *argv[])
1073 {
1074         int port;
1075         RAD_LISTEN_TYPE type;
1076         fr_command_socket_t *sock = listener->data;
1077         fr_ipaddr_t ipaddr;
1078         rad_listen_t *found = NULL;
1079
1080         if (argc < 1) {
1081                 cprintf(listener, "ERROR: Must specify [auth/acct]\n");
1082                 return 0;
1083         }
1084
1085         if (strcmp(argv[0], "auth") == 0) {
1086                 type = RAD_LISTEN_AUTH;
1087
1088         } else if (strcmp(argv[0], "acct") == 0) {
1089 #ifdef WITH_ACCOUNTING
1090                 type = RAD_LISTEN_ACCT;
1091 #else
1092                 cprintf(listener, "ERROR: This server was built without accounting support.\n");
1093                 return 0;
1094 #endif
1095
1096         } else {
1097                 cprintf(listener, "ERROR: Unknown socket type\n");
1098                 return 0;
1099         }
1100
1101         if (argc < 3) {
1102                 cprintf(listener, "ERROR: No <ipaddr> <port> was given\n");
1103                 return 0;
1104         }
1105
1106         /*
1107          *      FIXME:  Look for optional arg 4, and bind interface.
1108          */
1109
1110         if (ip_hton(argv[1], AF_UNSPEC, &ipaddr) < 0) {
1111                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
1112                         fr_strerror());
1113                 return 0;
1114         }
1115         port = atoi(argv[2]);
1116
1117         found = listener_find_byipaddr(&ipaddr, port);
1118         if (!found) {
1119                 cprintf(listener, "ERROR: Could not find matching listener\n");
1120                 return 0;
1121         }
1122
1123         sock->inject_listener = found;
1124         sock->dst_ipaddr = ipaddr;
1125         sock->dst_port = port;
1126
1127         return 1;
1128 }
1129
1130 static int command_inject_from(rad_listen_t *listener, int argc, char *argv[])
1131 {
1132         RADCLIENT *client;
1133         fr_command_socket_t *sock = listener->data;
1134
1135         if (argc < 1) {
1136                 cprintf(listener, "ERROR: No <ipaddr> was given\n");
1137                 return 0;
1138         }
1139
1140         if (!sock->inject_listener) {
1141                 cprintf(listener, "ERROR: You must specify \"inject to\" before using \"inject from\"\n");
1142                 return 0;
1143         }
1144
1145         sock->src_ipaddr.af = AF_UNSPEC;
1146         if (ip_hton(argv[0], AF_UNSPEC, &sock->src_ipaddr) < 0) {
1147                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
1148                         fr_strerror());
1149                 return 0;
1150         }
1151
1152         client = client_listener_find(sock->inject_listener, &sock->src_ipaddr,
1153                                       0);
1154         if (!client) {
1155                 cprintf(listener, "ERROR: No such client %s\n", argv[0]);
1156                 return 0;
1157         }
1158         sock->inject_client = client;
1159
1160         return 1;
1161 }
1162
1163 static int command_inject_file(rad_listen_t *listener, int argc, char *argv[])
1164 {
1165         static int inject_id = 0;
1166         int filedone;
1167         fr_command_socket_t *sock = listener->data;
1168         rad_listen_t *fake;
1169         REQUEST *request = NULL;
1170         RADIUS_PACKET *packet;
1171         VALUE_PAIR *vp;
1172         FILE *fp;
1173         RAD_REQUEST_FUNP fun = NULL;
1174         char buffer[2048];
1175
1176         if (argc < 2) {
1177                 cprintf(listener, "ERROR: You must specify <input-file> <output-file>\n");
1178                 return 0;
1179         }
1180
1181         /*
1182          *      Output files always go to the logging directory.
1183          */
1184         snprintf(buffer, sizeof(buffer), "%s/%s", radlog_dir, argv[1]);
1185
1186         fp = fopen(argv[0], "r");
1187         if (!fp ) {
1188                 cprintf(listener, "ERROR: Failed opening %s: %s\n",
1189                         argv[0], strerror(errno));
1190                 return 0;
1191         }
1192
1193         vp = readvp2(fp, &filedone, "");
1194         fclose(fp);
1195         if (!vp) {
1196                 cprintf(listener, "ERROR: Failed reading attributes from %s: %s\n",
1197                         argv[0], fr_strerror());
1198                 return 0;
1199         }
1200
1201         fake = rad_malloc(sizeof(*fake));
1202         memcpy(fake, sock->inject_listener, sizeof(*fake));
1203
1204         /*
1205          *      Re-write the IO for the listener.
1206          */
1207         fake->encode = null_socket_dencode;
1208         fake->decode = null_socket_dencode;
1209         fake->send = null_socket_send;
1210
1211         packet = rad_alloc(0);
1212         packet->src_ipaddr = sock->src_ipaddr;
1213         packet->src_port = 0;
1214
1215         packet->dst_ipaddr = sock->dst_ipaddr;
1216         packet->dst_port = sock->dst_port;
1217         packet->vps = vp;
1218         packet->id = inject_id++;
1219
1220         if (fake->type == RAD_LISTEN_AUTH) {
1221                 packet->code = PW_AUTHENTICATION_REQUEST;
1222                 fun = rad_authenticate;
1223
1224         } else {
1225 #ifdef WITH_ACCOUNTING
1226                 packet->code = PW_ACCOUNTING_REQUEST;
1227                 fun = rad_accounting;
1228 #else
1229                 cprintf(listener, "ERROR: This server was built without accounting support.\n");
1230                 rad_free(&packet);
1231                 free(fake);
1232                 return 0;
1233 #endif
1234         }
1235
1236         if (!received_request(fake, packet, &request, sock->inject_client)) {
1237                 cprintf(listener, "ERROR: Failed to inject request.  See log file for details\n");
1238                 rad_free(&packet);
1239                 free(fake);
1240                 return 0;
1241         }
1242
1243         /*
1244          *      Remember what the output file is, and remember to
1245          *      delete the fake listener when done.
1246          */
1247         request_data_add(request, null_socket_send, 0, strdup(buffer), free);
1248         request_data_add(request, null_socket_send, 1, fake, free);
1249
1250         if (debug_flag) {
1251                 request->radlog(L_DBG, 0, request,
1252                                 "Injected %s packet from host %s port 0 code=%d, id=%d",
1253                                 fr_packet_codes[packet->code],
1254                                 inet_ntop(packet->src_ipaddr.af,
1255                                           &packet->src_ipaddr.ipaddr,
1256                                           buffer, sizeof(buffer)),
1257                                 packet->code, packet->id);
1258                 
1259                 for (vp = packet->vps; vp != NULL; vp = vp->next) {
1260                         vp_prints(buffer, sizeof(buffer), vp);
1261                         request->radlog(L_DBG, 0, request, "\t%s", buffer);
1262                 }
1263         }
1264
1265         /*
1266          *      And go process it.
1267          */
1268         thread_pool_addrequest(request, fun);
1269
1270         return 1;
1271 }
1272
1273
1274 static fr_command_table_t command_table_inject[] = {
1275         { "to", FR_WRITE,
1276           "inject to <ipaddr> <port> - Inject packets to the destination IP and port.",
1277           command_inject_to, NULL },
1278
1279         { "from", FR_WRITE,
1280           "inject from <ipaddr> - Inject packets as if they came from <ipaddr>",
1281           command_inject_from, NULL },
1282
1283         { "file", FR_WRITE,
1284           "inject file <input-file> <output-file> - Inject packet from input-file>, with results sent to <output-file>",
1285           command_inject_file, NULL },
1286
1287         { NULL, 0, NULL, NULL, NULL }
1288 };
1289
1290 static fr_command_table_t command_table_debug[] = {
1291         { "condition", FR_WRITE,
1292           "debug condition [condition] - Enable debugging for requests matching [condition]",
1293           command_debug_condition, NULL },
1294
1295         { "level", FR_WRITE,
1296           "debug level <number> - Set debug level to <number>.  Higher is more debugging.",
1297           command_debug_level, NULL },
1298
1299         { "file", FR_WRITE,
1300           "debug file [filename] - Send all debugging output to [filename]",
1301           command_debug_file, NULL },
1302
1303         { NULL, 0, NULL, NULL, NULL }
1304 };
1305
1306 static fr_command_table_t command_table_show_debug[] = {
1307         { "condition", FR_READ,
1308           "show debug condition - Shows current debugging condition.",
1309           command_show_debug_condition, NULL },
1310
1311         { "level", FR_READ,
1312           "show debug level - Shows current debugging level.",
1313           command_show_debug_level, NULL },
1314
1315         { "file", FR_READ,
1316           "show debug file - Shows current debugging file.",
1317           command_show_debug_file, NULL },
1318
1319         { NULL, 0, NULL, NULL, NULL }
1320 };
1321
1322 static fr_command_table_t command_table_show_module[] = {
1323         { "config", FR_READ,
1324           "show module config <module> - show configuration for given module",
1325           command_show_module_config, NULL },
1326         { "flags", FR_READ,
1327           "show module flags <module> - show other module properties",
1328           command_show_module_flags, NULL },
1329         { "list", FR_READ,
1330           "show module list - shows list of loaded modules",
1331           command_show_modules, NULL },
1332         { "methods", FR_READ,
1333           "show module methods <module> - show sections where <module> may be used",
1334           command_show_module_methods, NULL },
1335
1336         { NULL, 0, NULL, NULL, NULL }
1337 };
1338
1339 static fr_command_table_t command_table_show_client[] = {
1340         { "config", FR_READ,
1341           "show client config <ipaddr> "
1342 #ifdef WITH_TCP
1343           "[proto] "
1344 #endif
1345           "- show configuration for given client",
1346           command_show_client_config, NULL },
1347         { "list", FR_READ,
1348           "show client list - shows list of global clients",
1349           command_show_clients, NULL },
1350
1351         { NULL, 0, NULL, NULL, NULL }
1352 };
1353
1354 #ifdef WITH_PROXY
1355 static fr_command_table_t command_table_show_home[] = {
1356         { "config", FR_READ,
1357           "show home_server config <ipaddr> <port> [proto] - show configuration for given home server",
1358           command_show_home_server_config, NULL },
1359         { "list", FR_READ,
1360           "show home_server list - shows list of home servers",
1361           command_show_home_servers, NULL },
1362         { "state", FR_READ,
1363           "show home_server state <ipaddr> <port> [proto] - shows state of given home server",
1364           command_show_home_server_state, NULL },
1365
1366         { NULL, 0, NULL, NULL, NULL }
1367 };
1368 #endif
1369
1370
1371 static fr_command_table_t command_table_show[] = {
1372         { "client", FR_READ,
1373           "show client <command> - do sub-command of client",
1374           NULL, command_table_show_client },
1375         { "debug", FR_READ,
1376           "show debug <command> - show debug properties",
1377           NULL, command_table_show_debug },
1378 #ifdef WITH_PROXY
1379         { "home_server", FR_READ,
1380           "show home_server <command> - do sub-command of home_server",
1381           NULL, command_table_show_home },
1382 #endif
1383         { "module", FR_READ,
1384           "show module <command> - do sub-command of module",
1385           NULL, command_table_show_module },
1386         { "uptime", FR_READ,
1387           "show uptime - shows time at which server started",
1388           command_uptime, NULL },
1389         { "version", FR_READ,
1390           "show version - Prints version of the running server",
1391           command_show_version, NULL },
1392         { "xml", FR_READ,
1393           "show xml <reference> - Prints out configuration as XML",
1394           command_show_xml, NULL },
1395         { NULL, 0, NULL, NULL, NULL }
1396 };
1397
1398
1399 static int command_set_module_config(rad_listen_t *listener, int argc, char *argv[])
1400 {
1401         int i, rcode;
1402         CONF_PAIR *cp;
1403         CONF_SECTION *cs;
1404         module_instance_t *mi;
1405         const CONF_PARSER *variables;
1406         void *data;
1407
1408         if (argc < 3) {
1409                 cprintf(listener, "ERROR: No module name or variable was given\n");
1410                 return 0;
1411         }
1412
1413         cs = cf_section_find("modules");
1414         if (!cs) return 0;
1415
1416         mi = find_module_instance(cs, argv[0], 0);
1417         if (!mi) {
1418                 cprintf(listener, "ERROR: No such module \"%s\"\n", argv[0]);
1419                 return 0;
1420         }
1421
1422         if ((mi->entry->module->type & RLM_TYPE_HUP_SAFE) == 0) {
1423                 cprintf(listener, "ERROR: Cannot change configuration of module as it is cannot be HUP'd.\n");
1424                 return 0;
1425         }
1426
1427         variables = cf_section_parse_table(mi->cs);
1428         if (!variables) {
1429                 cprintf(listener, "ERROR: Cannot find configuration for module\n");
1430                 return 0;
1431         }
1432
1433         rcode = -1;
1434         for (i = 0; variables[i].name != NULL; i++) {
1435                 /*
1436                  *      FIXME: Recurse into sub-types somehow...
1437                  */
1438                 if (variables[i].type == PW_TYPE_SUBSECTION) continue;
1439
1440                 if (strcmp(variables[i].name, argv[1]) == 0) {
1441                         rcode = i;
1442                         break;
1443                 }
1444         }
1445
1446         if (rcode < 0) {
1447                 cprintf(listener, "ERROR: No such variable \"%s\"\n", argv[1]);
1448                 return 0;
1449         }
1450
1451         i = rcode;              /* just to be safe */
1452
1453         /*
1454          *      It's not part of the dynamic configuration.  The module
1455          *      needs to re-parse && validate things.
1456          */
1457         if (variables[i].data) {
1458                 cprintf(listener, "ERROR: Variable cannot be dynamically updated\n");
1459                 return 0;
1460         }
1461
1462         data = ((char *) mi->insthandle) + variables[i].offset;
1463
1464         cp = cf_pair_find(mi->cs, argv[1]);
1465         if (!cp) return 0;
1466
1467         /*
1468          *      Replace the OLD value in the configuration file with
1469          *      the NEW value.
1470          *
1471          *      FIXME: Parse argv[2] depending on it's data type!
1472          *      If it's a string, look for leading single/double quotes,
1473          *      end then call tokenize functions???
1474          */
1475         cf_pair_replace(mi->cs, cp, argv[2]);
1476
1477         rcode = cf_item_parse(mi->cs, argv[1], variables[i].type,
1478                               data, argv[2]);
1479         if (rcode < 0) {
1480                 cprintf(listener, "ERROR: Failed to parse value\n");
1481                 return 0;
1482         }
1483
1484         return 1;               /* success */
1485 }
1486
1487 static int command_set_module_status(rad_listen_t *listener, int argc, char *argv[])
1488 {
1489         CONF_SECTION *cs;
1490         module_instance_t *mi;
1491
1492         if (argc < 2) {
1493                 cprintf(listener, "ERROR: No module name or status was given\n");
1494                 return 0;
1495         }
1496
1497         cs = cf_section_find("modules");
1498         if (!cs) return 0;
1499
1500         mi = find_module_instance(cs, argv[0], 0);
1501         if (!mi) {
1502                 cprintf(listener, "ERROR: No such module \"%s\"\n", argv[0]);
1503                 return 0;
1504         }
1505
1506
1507         if (strcmp(argv[1], "alive") == 0) {
1508                 mi->dead = FALSE;
1509
1510         } else if (strcmp(argv[1], "dead") == 0) {
1511                 mi->dead = TRUE;
1512
1513         } else {
1514                 cprintf(listener, "ERROR: Unknown status \"%s\"\n", argv[2]);
1515                 return 0;
1516         }
1517
1518         return 1;               /* success */
1519 }
1520
1521 #ifdef WITH_STATS
1522 static int command_print_stats(rad_listen_t *listener, fr_stats_t *stats,
1523                                int auth)
1524 {
1525         cprintf(listener, "\trequests\t%u\n", stats->total_requests);
1526         cprintf(listener, "\tresponses\t%u\n", stats->total_responses);
1527         
1528         if (auth) {
1529                 cprintf(listener, "\taccepts\t\t%u\n",
1530                         stats->total_access_accepts);
1531                 cprintf(listener, "\trejects\t\t%u\n",
1532                         stats->total_access_rejects);
1533                 cprintf(listener, "\tchallenges\t%u\n",
1534                         stats->total_access_challenges);
1535         }
1536
1537         cprintf(listener, "\tdup\t\t%u\n", stats->total_dup_requests);
1538         cprintf(listener, "\tinvalid\t\t%u\n", stats->total_invalid_requests);
1539         cprintf(listener, "\tmalformed\t%u\n", stats->total_malformed_requests);
1540         cprintf(listener, "\tbad_signature\t%u\n", stats->total_bad_authenticators);
1541         cprintf(listener, "\tdropped\t\t%u\n", stats->total_packets_dropped);
1542         cprintf(listener, "\tunknown_types\t%u\n", stats->total_unknown_types);
1543         
1544         return 1;
1545 }
1546
1547 #ifdef WITH_DETAIL
1548 static FR_NAME_NUMBER state_names[] = {
1549         { "unopened", STATE_UNOPENED },
1550         { "unlocked", STATE_UNLOCKED },
1551         { "header", STATE_HEADER },
1552         { "reading", STATE_READING },
1553         { "queued", STATE_QUEUED },
1554         { "running", STATE_RUNNING },
1555         { "no-reply", STATE_NO_REPLY },
1556         { "replied", STATE_REPLIED },
1557
1558         { NULL, 0 }
1559 };
1560
1561 static int command_stats_detail(rad_listen_t *listener, int argc, char *argv[])
1562 {
1563         rad_listen_t *this;
1564         listen_detail_t *data;
1565         struct stat buf;
1566
1567         if (argc == 0) {
1568                 cprintf(listener, "ERROR: Must specify <filename>\n");
1569                 return 0;
1570         }
1571
1572         data = NULL;
1573         for (this = mainconfig.listen; this != NULL; this = this->next) {
1574                 if (this->type != RAD_LISTEN_DETAIL) continue;
1575
1576                 data = this->data;
1577                 if (strcmp(argv[1], data->filename) != 0) continue;
1578
1579                 break;
1580         }
1581
1582         cprintf(listener, "\tstate\t%s\n",
1583                 fr_int2str(state_names, data->state, "?"));
1584
1585         if ((data->state == STATE_UNOPENED) ||
1586             (data->state == STATE_UNLOCKED)) {
1587                 return 1;
1588         }
1589
1590         /*
1591          *      Race conditions: file might not exist.
1592          */
1593         if (stat(data->filename_work, &buf) < 0) {
1594                 cprintf(listener, "packets\t0\n");
1595                 cprintf(listener, "tries\t0\n");
1596                 cprintf(listener, "offset\t0\n");
1597                 cprintf(listener, "size\t0\n");
1598                 return 1;
1599         }
1600
1601         cprintf(listener, "packets\t%d\n", data->packets);
1602         cprintf(listener, "tries\t%d\n", data->tries);
1603         cprintf(listener, "offset\t%u\n", (unsigned int) data->offset);
1604         cprintf(listener, "size\t%u\n", (unsigned int) buf.st_size);
1605
1606         return 1;
1607 }
1608 #endif
1609
1610 #ifdef WITH_PROXY
1611 static int command_stats_home_server(rad_listen_t *listener, int argc, char *argv[])
1612 {
1613         home_server *home;
1614
1615         if (argc == 0) {
1616                 cprintf(listener, "ERROR: Must specify [auth/acct] OR <ipaddr> <port>\n");
1617                 return 0;
1618         }
1619
1620         if (argc == 1) {
1621 #ifdef WITH_ACCOUNTING
1622                 if (strcmp(argv[0], "acct") == 0) {
1623                         return command_print_stats(listener,
1624                                                    &proxy_acct_stats, 0);
1625                 }
1626 #endif
1627                 if (strcmp(argv[0], "auth") == 0) {
1628                         return command_print_stats(listener,
1629                                                    &proxy_auth_stats, 1);
1630                 }
1631
1632                 cprintf(listener, "ERROR: Should specify [auth/acct]\n");
1633                 return 0;
1634         }
1635
1636         home = get_home_server(listener, argc, argv, NULL);
1637         if (!home) {
1638                 return 0;
1639         }
1640
1641         command_print_stats(listener, &home->stats,
1642                             (home->type == HOME_TYPE_AUTH));
1643         cprintf(listener, "\toutstanding\t%d\n", home->currently_outstanding);
1644         return 1;
1645 }
1646 #endif
1647
1648 static int command_stats_client(rad_listen_t *listener, int argc, char *argv[])
1649 {
1650         int auth = TRUE;
1651         RADCLIENT *client;
1652
1653         if (argc < 1) {
1654                 cprintf(listener, "ERROR: Must specify [auth/acct]\n");
1655                 return 0;
1656         }
1657
1658         if (strcmp(argv[0], "auth") == 0) {
1659                 auth = TRUE;
1660
1661         } else if (strcmp(argv[0], "acct") == 0) {
1662 #ifdef WITH_ACCOUNTING
1663                 auth = FALSE;
1664 #else
1665                 cprintf(listener, "ERROR: This server was built without accounting support.\n");
1666                 return 0;
1667 #endif
1668
1669         } else {
1670                 cprintf(listener, "ERROR: Unknown statistics type\n");
1671                 return 0;
1672         }
1673
1674         /*
1675          *      Global results for all client.
1676          */
1677         if (argc == 1) {
1678 #ifdef WITH_ACCOUNTING
1679                 if (!auth) {
1680                         return command_print_stats(listener,
1681                                                    &radius_acct_stats, auth);
1682                 }
1683 #endif
1684                 return command_print_stats(listener, &radius_auth_stats, auth);
1685         }
1686
1687         client = get_client(listener, argc - 1, argv + 1);
1688         if (!client) {
1689                 return 0;
1690         }
1691
1692 #ifdef WITH_ACCOUNTING
1693         if (!auth) {
1694                 return command_print_stats(listener, client->acct, auth);
1695         }
1696 #endif
1697
1698         return command_print_stats(listener, client->auth, auth);
1699 }
1700 #endif  /* WITH_STATS */
1701
1702
1703 static int command_add_client_file(rad_listen_t *listener, int argc, char *argv[])
1704 {
1705         RADCLIENT *c;
1706
1707         if (argc < 1) {
1708                 cprintf(listener, "ERROR: <file> is required\n");
1709                 return 0;
1710         }
1711
1712         /*
1713          *      Read the file and generate the client.
1714          */
1715         c = client_read(argv[0], FALSE, FALSE);
1716         if (!c) {
1717                 cprintf(listener, "ERROR: Unknown error reading client file.\n");
1718                 return 0;
1719         }
1720
1721         if (!client_add(NULL, c)) {
1722                 cprintf(listener, "ERROR: Unknown error inserting new client.\n");
1723                 client_free(c);
1724                 return 0;
1725         }
1726
1727         return 1;
1728 }
1729
1730
1731 static int command_del_client(rad_listen_t *listener, int argc, char *argv[])
1732 {
1733 #ifdef WITH_DYNAMIC_CLIENTS
1734         RADCLIENT *client;
1735
1736         client = get_client(listener, argc - 1, argv + 1);
1737         if (!client) return 0;
1738
1739         if (!client->dynamic) {
1740                 cprintf(listener, "ERROR: Client %s was not dynamically defined.\n", argv[1]);
1741                 return 0;
1742         }
1743
1744         /*
1745          *      DON'T delete it.  Instead, mark it as "dead now".  The
1746          *      next time we receive a packet for the client, it will
1747          *      be deleted.
1748          *
1749          *      If we don't receive a packet from it, the client
1750          *      structure will stick around for a while.  Oh well...
1751          */
1752         client->lifetime = 1;
1753 #else
1754         cprintf(listener, "ERROR: Dynamic clients are not supported.\n");
1755 #endif
1756
1757         return 1;
1758 }
1759
1760
1761 static fr_command_table_t command_table_del_client[] = {
1762         { "ipaddr", FR_WRITE,
1763           "del client ipaddr <ipaddr> - Delete a dynamically created client",
1764           command_del_client, NULL },
1765
1766         { NULL, 0, NULL, NULL, NULL }
1767 };
1768
1769
1770 static fr_command_table_t command_table_del[] = {
1771         { "client", FR_WRITE,
1772           "del client <command> - Delete client configuration commands",
1773           NULL, command_table_del_client },
1774
1775         { NULL, 0, NULL, NULL, NULL }
1776 };
1777
1778
1779 static fr_command_table_t command_table_add_client[] = {
1780         { "file", FR_WRITE,
1781           "add client file <filename> - Add new client definition from <filename>",
1782           command_add_client_file, NULL },
1783
1784         { NULL, 0, NULL, NULL, NULL }
1785 };
1786
1787
1788 static fr_command_table_t command_table_add[] = {
1789         { "client", FR_WRITE,
1790           "add client <command> - Add client configuration commands",
1791           NULL, command_table_add_client },
1792
1793         { NULL, 0, NULL, NULL, NULL }
1794 };
1795
1796
1797 #ifdef WITH_PROXY
1798 static fr_command_table_t command_table_set_home[] = {
1799         { "state", FR_WRITE,
1800           "set home_server state <ipaddr> <port> [proto] [alive|dead] - set state for given home server",
1801           command_set_home_server_state, NULL },
1802
1803         { NULL, 0, NULL, NULL, NULL }
1804 };
1805 #endif
1806
1807 static fr_command_table_t command_table_set_module[] = {
1808         { "config", FR_WRITE,
1809           "set module config <module> variable value - set configuration for <module>",
1810           command_set_module_config, NULL },
1811
1812         { "status", FR_WRITE,
1813           "set module status [alive|dead] - set the module to be alive or dead (always return \"fail\")",
1814           command_set_module_status, NULL },
1815
1816         { NULL, 0, NULL, NULL, NULL }
1817 };
1818
1819
1820 static fr_command_table_t command_table_set[] = {
1821         { "module", FR_WRITE,
1822           "set module <command> - set module commands",
1823           NULL, command_table_set_module },
1824 #ifdef WITH_PROXY
1825         { "home_server", FR_WRITE, 
1826           "set home_server <command> - set home server commands",
1827           NULL, command_table_set_home },
1828 #endif
1829
1830         { NULL, 0, NULL, NULL, NULL }
1831 };
1832
1833
1834 #ifdef WITH_STATS
1835 static fr_command_table_t command_table_stats[] = {
1836         { "client", FR_READ,
1837           "stats client [auth/acct] <ipaddr> "
1838 #ifdef WITH_TCP
1839           "[proto] "
1840 #endif
1841           "- show statistics for given client, or for all clients (auth or acct)",
1842           command_stats_client, NULL },
1843 #ifdef WITH_PROXY
1844         { "home_server", FR_READ,
1845           "stats home_server [<ipaddr>/auth/acct] <port> - show statistics for given home server (ipaddr and port), or for all home servers (auth or acct)",
1846           command_stats_home_server, NULL },
1847 #endif
1848
1849 #ifdef WITH_DETAIL
1850         { "detail", FR_READ,
1851           "stats detail <filename> - show statistics for the given detail file",
1852           command_stats_detail, NULL },
1853 #endif
1854
1855         { NULL, 0, NULL, NULL, NULL }
1856 };
1857 #endif
1858
1859 static fr_command_table_t command_table[] = {
1860         { "add", FR_WRITE, NULL, NULL, command_table_add },
1861         { "debug", FR_WRITE,
1862           "debug <command> - debugging commands",
1863           NULL, command_table_debug },
1864         { "del", FR_WRITE, NULL, NULL, command_table_del },
1865         { "hup", FR_WRITE,
1866           "hup [module] - sends a HUP signal to the server, or optionally to one module",
1867           command_hup, NULL },
1868         { "inject", FR_WRITE,
1869           "inject <command> - commands to inject packets into a running server",
1870           NULL, command_table_inject },
1871         { "reconnect", FR_READ,
1872           "reconnect - reconnect to a running server",
1873           NULL, NULL },         /* just here for "help" */
1874         { "terminate", FR_WRITE,
1875           "terminate - terminates the server, and cause it to exit",
1876           command_terminate, NULL },
1877         { "set", FR_WRITE, NULL, NULL, command_table_set },
1878         { "show",  FR_READ, NULL, NULL, command_table_show },
1879 #ifdef WITH_STATS
1880         { "stats",  FR_READ, NULL, NULL, command_table_stats },
1881 #endif
1882
1883         { NULL, 0, NULL, NULL, NULL }
1884 };
1885
1886
1887 static void command_socket_free(rad_listen_t *this)
1888 {
1889         fr_command_socket_t *sock = this->data;
1890
1891         unlink(sock->copy);
1892         free(sock->copy);
1893         sock->copy = NULL;
1894 }
1895
1896
1897 /*
1898  *      Parse the unix domain sockets.
1899  *
1900  *      FIXME: TCP + SSL, after RadSec is in.
1901  */
1902 static int command_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
1903 {
1904         fr_command_socket_t *sock;
1905
1906         if (check_config) return 0;
1907
1908         sock = this->data;
1909
1910         if (cf_section_parse(cs, sock, command_config) < 0) {
1911                 return -1;
1912         }
1913
1914         sock->copy = NULL;
1915         if (sock->path) sock->copy = strdup(sock->path);
1916
1917 #if defined(HAVE_GETPEEREID) || defined (SO_PEERCRED)
1918         if (sock->uid_name) {
1919                 struct passwd *pw;
1920                 
1921                 pw = getpwnam(sock->uid_name);
1922                 if (!pw) {
1923                         radlog(L_ERR, "Failed getting uid for %s: %s",
1924                                sock->uid_name, strerror(errno));
1925                         return -1;
1926                 }
1927
1928                 sock->uid = pw->pw_uid;
1929         }
1930
1931         if (sock->gid_name) {
1932                 struct group *gr;
1933
1934                 gr = getgrnam(sock->gid_name);
1935                 if (!gr) {
1936                         radlog(L_ERR, "Failed getting gid for %s: %s",
1937                                sock->gid_name, strerror(errno));
1938                         return -1;
1939                 }
1940                 sock->gid = gr->gr_gid; 
1941         }
1942
1943 #else  /* can't get uid or gid of connecting user */
1944
1945         if (sock->uid_name || sock->gid_name) {
1946                 radlog(L_ERR, "System does not support uid or gid authentication for sockets");
1947                 return -1;
1948         }
1949
1950 #endif
1951
1952         if (!sock->mode_name) {
1953                 sock->mode = FR_READ;
1954         } else {
1955                 sock->mode = fr_str2int(mode_names, sock->mode_name, 0);
1956                 if (!sock->mode) {
1957                         radlog(L_ERR, "Invalid mode name \"%s\"",
1958                                sock->mode_name);
1959                         return -1;
1960                 }
1961         }
1962
1963         /*
1964          *      FIXME: check for absolute pathnames?
1965          *      check for uid/gid on the other end...    
1966          */
1967
1968         this->fd = fr_server_domain_socket(sock->path);
1969         if (this->fd < 0) {
1970                 return -1;
1971         }
1972
1973         return 0;
1974 }
1975
1976 static int command_socket_print(const rad_listen_t *this, char *buffer, size_t bufsize)
1977 {
1978         fr_command_socket_t *sock = this->data;
1979
1980         snprintf(buffer, bufsize, "command file %s", sock->path);
1981         return 1;
1982 }
1983
1984
1985 /*
1986  *      String split routine.  Splits an input string IN PLACE
1987  *      into pieces, based on spaces.
1988  */
1989 static int str2argv(char *str, char **argv, int max_argc)
1990 {
1991         int argc = 0;
1992         size_t len;
1993         char buffer[1024];
1994
1995         while (*str) {
1996                 if (argc >= max_argc) return argc;
1997
1998                 /*
1999                  *      Chop out comments early.
2000                  */
2001                 if (*str == '#') {
2002                         *str = '\0';
2003                         break;
2004                 }
2005
2006                 while ((*str == ' ') ||
2007                        (*str == '\t') ||
2008                        (*str == '\r') ||
2009                        (*str == '\n')) *(str++) = '\0';
2010
2011                 if (!*str) return argc;
2012
2013                 if ((*str == '\'') || (*str == '"')) {
2014                         char *p = str;
2015                         FR_TOKEN token;
2016
2017                         token = gettoken((const char **) &p, buffer,
2018                                          sizeof(buffer));
2019                         if ((token != T_SINGLE_QUOTED_STRING) &&
2020                             (token != T_DOUBLE_QUOTED_STRING)) {
2021                                 return -1;
2022                         }
2023
2024                         len = strlen(buffer);
2025                         if (len >= (size_t) (p - str)) {
2026                                 return -1;
2027                         }
2028
2029                         memcpy(str, buffer, len + 1);
2030                         argv[argc] = str;
2031                         str = p;
2032
2033                 } else {
2034                         argv[argc] = str;
2035                 }
2036                 argc++;
2037
2038                 while (*str &&
2039                        (*str != ' ') &&
2040                        (*str != '\t') &&
2041                        (*str != '\r') &&
2042                        (*str != '\n')) str++;
2043         }
2044
2045         return argc;
2046 }
2047
2048 static void print_help(rad_listen_t *listener,
2049                        fr_command_table_t *table, int recursive)
2050 {
2051         int i;
2052         
2053         for (i = 0; table[i].command != NULL; i++) {
2054                 if (table[i].help) {
2055                         cprintf(listener, "%s\n",
2056                                 table[i].help);
2057                 } else {
2058                         cprintf(listener, "%s <command> - do sub-command of %s\n",
2059                                 table[i].command, table[i].command);
2060                 }
2061
2062                 if (recursive && table[i].table) {
2063                         print_help(listener, table[i].table, recursive);
2064                 }
2065         }
2066 }
2067
2068 #define MAX_ARGV (16)
2069
2070 /*
2071  *      Check if an incoming request is "ok"
2072  *
2073  *      It takes packets, not requests.  It sees if the packet looks
2074  *      OK.  If so, it does a number of sanity checks on it.
2075  */
2076 static int command_domain_recv(rad_listen_t *listener,
2077                                UNUSED RAD_REQUEST_FUNP *pfun,
2078                                UNUSED REQUEST **prequest)
2079 {
2080         int i, rcode;
2081         ssize_t len;
2082         int argc;
2083         char *my_argv[MAX_ARGV], **argv;
2084         fr_command_table_t *table;
2085         fr_command_socket_t *co = listener->data;
2086
2087         *pfun = NULL;
2088         *prequest = NULL;
2089
2090         do {
2091                 ssize_t c;
2092                 char *p;
2093
2094                 len = recv(listener->fd, co->buffer + co->offset,
2095                            sizeof(co->buffer) - co->offset - 1, 0);
2096                 if (len == 0) goto close_socket; /* clean close */
2097
2098                 if (len < 0) {
2099                         if ((errno == EAGAIN) || (errno == EINTR)) {
2100                                 return 0;
2101                         }
2102                         goto close_socket;
2103                 }
2104
2105                 /*
2106                  *      CTRL-D
2107                  */
2108                 if ((co->offset == 0) && (co->buffer[0] == 0x04)) {
2109                 close_socket:
2110                         command_close_socket(listener);
2111                         return 0;
2112                 }
2113
2114                 /*
2115                  *      See if there are multiple lines in the buffer.
2116                  */
2117                 p = co->buffer + co->offset;
2118                 rcode = 0;
2119                 p[len] = '\0';
2120                 for (c = 0; c < len; c++) {
2121                         if ((*p == '\r') || (*p == '\n')) {
2122                                 rcode = 1;
2123                                 *p = '\0';
2124
2125                                 /*
2126                                  *      FIXME: do real buffering...
2127                                  *      handling of CTRL-C, etc.
2128                                  */
2129
2130                         } else if (rcode) {
2131                                 /*
2132                                  *      \r \n followed by ASCII...
2133                                  */
2134                                 break;
2135                         }
2136
2137                         p++;
2138                 }
2139
2140                 co->offset += len;
2141
2142                 /*
2143                  *      Saw CR/LF.  Set next element, and exit.
2144                  */
2145                 if (rcode) {
2146                         co->next = p - co->buffer;
2147                         break;
2148                 }
2149
2150                 if (co->offset >= (ssize_t) (sizeof(co->buffer) - 1)) {
2151                         radlog(L_ERR, "Line too long!");
2152                         goto close_socket;
2153                 }
2154
2155                 co->offset++;
2156         } while (1);
2157
2158         DEBUG("radmin> %s", co->buffer);
2159
2160         argc = str2argv(co->buffer, my_argv, MAX_ARGV);
2161         if (argc == 0) goto do_next; /* empty strings are OK */
2162
2163         if (argc < 0) {
2164                 cprintf(listener, "ERROR: Failed parsing command.\n");
2165                 goto do_next;
2166         }
2167
2168         argv = my_argv;
2169
2170         for (len = 0; len <= co->offset; len++) {
2171                 if (co->buffer[len] < 0x20) {
2172                         co->buffer[len] = '\0';
2173                         break;
2174                 }
2175         }
2176
2177         /*
2178          *      Hard-code exit && quit.
2179          */
2180         if ((strcmp(argv[0], "exit") == 0) ||
2181             (strcmp(argv[0], "quit") == 0)) goto close_socket;
2182
2183 #if 0
2184         if (!co->user[0]) {
2185                 if (strcmp(argv[0], "login") != 0) {
2186                         cprintf(listener, "ERROR: Login required\n");
2187                         goto do_next;
2188                 }
2189
2190                 if (argc < 3) {
2191                         cprintf(listener, "ERROR: login <user> <password>\n");
2192                         goto do_next;
2193                 }
2194
2195                 /*
2196                  *      FIXME: Generate && process fake RADIUS request.
2197                  */
2198                 if ((strcmp(argv[1], "root") == 0) &&
2199                     (strcmp(argv[2], "password") == 0)) {
2200                         strlcpy(co->user, argv[1], sizeof(co->user));
2201                         goto do_next;
2202                 }
2203
2204                 cprintf(listener, "ERROR: Login incorrect\n");
2205                 goto do_next;
2206         }
2207 #endif
2208
2209         table = command_table;
2210  retry:
2211         len = 0;
2212         for (i = 0; table[i].command != NULL; i++) {
2213                 if (strcmp(table[i].command, argv[0]) == 0) {
2214                         /*
2215                          *      Check permissions.
2216                          */
2217                         if (((co->mode & FR_WRITE) == 0) &&
2218                             ((table[i].mode & FR_WRITE) != 0)) {
2219                                 cprintf(listener, "ERROR: You do not have write permission.  See \"mode = rw\" in the \"listen\" section for this socket.\n");
2220                                 goto do_next;
2221                         }
2222
2223                         if (table[i].table) {
2224                                 /*
2225                                  *      This is the last argument, but
2226                                  *      there's a sub-table.  Print help.
2227                                  *      
2228                                  */
2229                                 if (argc == 1) {
2230                                         table = table[i].table;
2231                                         goto do_help;
2232                                 }
2233
2234                                 argc--;
2235                                 argv++;
2236                                 table = table[i].table;
2237                                 goto retry;
2238                         }
2239
2240                         if ((argc == 2) && (strcmp(argv[1], "?") == 0)) goto do_help;
2241
2242                         if (!table[i].func) {
2243                                 cprintf(listener, "ERROR: Invalid command\n");
2244                                 goto do_next;
2245                         }
2246
2247                         len = 1;
2248                         rcode = table[i].func(listener,
2249                                               argc - 1, argv + 1);
2250                         break;
2251                 }
2252         }
2253
2254         /*
2255          *      No such command
2256          */
2257         if (!len) {
2258                 if ((strcmp(argv[0], "help") == 0) ||
2259                     (strcmp(argv[0], "?") == 0)) {
2260                         int recursive;
2261
2262                 do_help:
2263                         if ((argc > 1) && (strcmp(argv[1], "-r") == 0)) {
2264                                 recursive = TRUE;
2265                         } else {
2266                                 recursive = FALSE;
2267                         }
2268
2269                         print_help(listener, table, recursive);
2270                         goto do_next;
2271                 }
2272
2273                 cprintf(listener, "ERROR: Unknown command \"%s\"\n",
2274                         argv[0]);
2275         }
2276
2277  do_next:
2278         cprintf(listener, "radmin> ");
2279
2280         if (co->next <= co->offset) {
2281                 co->offset = 0;
2282         } else {
2283                 memmove(co->buffer, co->buffer + co->next,
2284                         co->offset - co->next);
2285                 co->offset -= co->next;
2286         }
2287
2288         return 0;
2289 }
2290
2291
2292 static int command_domain_accept(rad_listen_t *listener,
2293                                  UNUSED RAD_REQUEST_FUNP *pfun,
2294                                  UNUSED REQUEST **prequest)
2295 {
2296         int newfd;
2297         uint32_t magic;
2298         rad_listen_t *this;
2299         socklen_t salen;
2300         struct sockaddr_storage src;
2301         fr_command_socket_t *sock = listener->data;
2302         
2303         salen = sizeof(src);
2304
2305         DEBUG2(" ... new connection request on command socket.");
2306
2307         *pfun = NULL;
2308         *prequest = NULL;
2309         
2310         newfd = accept(listener->fd, (struct sockaddr *) &src, &salen);
2311         if (newfd < 0) {
2312                 /*
2313                  *      Non-blocking sockets must handle this.
2314                  */
2315                 if (errno == EWOULDBLOCK) {
2316                         return 0;
2317                 }
2318
2319                 DEBUG2(" ... failed to accept connection.");
2320                 return 0;
2321         }
2322
2323         /*
2324          *      Perform user authentication.
2325          */
2326         if (sock->uid_name || sock->gid_name) {
2327                 uid_t uid;
2328                 gid_t gid;
2329
2330                 if (getpeereid(listener->fd, &uid, &gid) < 0) {
2331                         radlog(L_ERR, "Failed getting peer credentials for %s: %s",
2332                                sock->path, strerror(errno));
2333                         close(newfd);
2334                         return 0;
2335                 }
2336
2337                 if (sock->uid_name && (sock->uid != uid)) {
2338                         radlog(L_ERR, "Unauthorized connection to %s from uid %ld",
2339                                sock->path, (long int) uid);
2340                         close(newfd);
2341                         return 0;
2342                 }
2343
2344                 if (sock->gid_name && (sock->gid != gid)) {
2345                         radlog(L_ERR, "Unauthorized connection to %s from gid %ld",
2346                                sock->path, (long int) gid);
2347                         close(newfd);
2348                         return 0;
2349                 }
2350         }
2351
2352         /*
2353          *      Write 32-bit magic number && version information.
2354          */
2355         magic = htonl(0xf7eead15);
2356         if (write(newfd, &magic, 4) < 0) {
2357                 radlog(L_ERR, "Failed writing initial data to socket: %s",
2358                        strerror(errno));
2359                 close(newfd);
2360                 return 0;
2361         }
2362         magic = htonl(1);       /* protocol version */
2363         if (write(newfd, &magic, 4) < 0) {
2364                 radlog(L_ERR, "Failed writing initial data to socket: %s",
2365                        strerror(errno));
2366                 close(newfd);
2367                 return 0;
2368         }
2369
2370
2371         /*
2372          *      Add the new listener.
2373          */
2374         this = listen_alloc(listener->type);
2375         if (!this) return 0;
2376
2377         /*
2378          *      Copy everything, including the pointer to the socket
2379          *      information.
2380          */
2381         sock = this->data;
2382         memcpy(this, listener, sizeof(*this));
2383         this->status = RAD_LISTEN_STATUS_INIT;
2384         this->next = NULL;
2385         this->data = sock;      /* fix it back */
2386
2387         sock->offset = 0;
2388         sock->user[0] = '\0';
2389         sock->path = ((fr_command_socket_t *) listener->data)->path;
2390         sock->mode = ((fr_command_socket_t *) listener->data)->mode;
2391
2392         this->fd = newfd;
2393         this->recv = command_domain_recv;
2394
2395         /*
2396          *      Tell the event loop that we have a new FD
2397          */
2398         event_new_fd(this);
2399
2400         return 0;
2401 }
2402
2403
2404 /*
2405  *      Send an authentication response packet
2406  */
2407 static int command_domain_send(UNUSED rad_listen_t *listener,
2408                                UNUSED REQUEST *request)
2409 {
2410         return 0;
2411 }
2412
2413
2414 static int command_socket_encode(UNUSED rad_listen_t *listener,
2415                                  UNUSED REQUEST *request)
2416 {
2417         return 0;
2418 }
2419
2420
2421 static int command_socket_decode(UNUSED rad_listen_t *listener,
2422                                  UNUSED REQUEST *request)
2423 {
2424         return 0;
2425 }
2426
2427 #endif /* WITH_COMMAND_SOCKET */