Added help
[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 int command_show_client_config(rad_listen_t *listener, int argc, char *argv[])
733 {
734         RADCLIENT *client;
735         FILE *fp;
736         fr_ipaddr_t ipaddr;
737
738         if (argc == 0) {
739                 cprintf(listener, "ERROR: Must specify <ipaddr>\n");
740                 return 0;
741         }
742
743         if (ip_hton(argv[0], AF_UNSPEC, &ipaddr) < 0) {
744                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
745                         fr_strerror());
746                 return 0;
747         }
748
749         client = client_find(NULL, &ipaddr);
750         if (!client) {
751                 cprintf(listener, "ERROR: No such client\n");
752                 return 0;
753         }
754
755         if (!client->cs) return 1;
756
757         fp = fdopen(dup(listener->fd), "a");
758         if (!fp) {
759                 cprintf(listener, "ERROR: Can't dup %s\n", strerror(errno));
760                 return 0;
761         }
762
763         cf_section2file(fp, client->cs);
764         fclose(fp);
765
766         return 1;
767 }
768
769 static int command_show_home_server_config(rad_listen_t *listener, int argc, char *argv[])
770 {
771         home_server *home;
772         FILE *fp;
773         int port;
774         fr_ipaddr_t ipaddr;
775
776         if (argc < 1) {
777                 cprintf(listener, "ERROR: Must specify <ipaddr> <port>\n");
778                 return 0;
779         }
780
781         if (ip_hton(argv[0], AF_UNSPEC, &ipaddr) < 0) {
782                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
783                         fr_strerror());
784                 return 0;
785         }
786
787         port = atoi(argv[1]);
788
789         home = home_server_find(&ipaddr, port);
790         if (!home) {
791                 cprintf(listener, "ERROR: No such home server\n");
792                 return 0;
793         }
794
795         if (!home->cs) return 1;
796
797         fp = fdopen(dup(listener->fd), "a");
798         if (!fp) {
799                 cprintf(listener, "ERROR: Can't dup %s\n", strerror(errno));
800                 return 0;
801         }
802
803         cf_section2file(fp, home->cs);
804         fclose(fp);
805
806         return 1;
807 }
808
809
810
811 static fr_command_table_t command_table_debug[] = {
812         { "condition", FR_WRITE,
813           "debug condition <condition> - Enable debugging for requests matching <condition>",
814           command_debug_condition, NULL },
815
816         { "level", FR_WRITE,
817           "debug level <number> - Set debug level to <number>.  Higher is more debugging.",
818           command_debug_level, NULL },
819
820         { "file", FR_WRITE,
821           "debug file <filename> - Send all debuggin output to <filename>",
822           command_debug_file, NULL },
823
824         { NULL, 0, NULL, NULL, NULL }
825 };
826
827 static fr_command_table_t command_table_show_debug[] = {
828         { "condition", FR_READ,
829           "show debug condition - Shows current debugging condition.",
830           command_show_debug_condition, NULL },
831
832         { "level", FR_READ,
833           "show debug level - Shows current debugging level.",
834           command_show_debug_level, NULL },
835
836         { "file", FR_READ,
837           "show debug file - Shows current debugging file.",
838           command_show_debug_file, NULL },
839
840         { NULL, 0, NULL, NULL, NULL }
841 };
842
843 static fr_command_table_t command_table_show_module[] = {
844         { "config", FR_READ,
845           "show module config <module> - show configuration for given module",
846           command_show_module_config, NULL },
847         { "flags", FR_READ,
848           "show module flags <module> - show other module properties",
849           command_show_module_flags, NULL },
850         { "list", FR_READ,
851           "show module list - shows list of loaded modules",
852           command_show_modules, NULL },
853         { "methods", FR_READ,
854           "show module methods <module> - show sections where <module> may be used",
855           command_show_module_methods, NULL },
856
857         { NULL, 0, NULL, NULL, NULL }
858 };
859
860 static fr_command_table_t command_table_show_client[] = {
861         { "config", FR_READ,
862           "show client config <ipaddr> - show configuration for given client",
863           command_show_client_config, NULL },
864         { "list", FR_READ,
865           "show client list - shows list of global clients",
866           command_show_clients, NULL },
867
868         { NULL, 0, NULL, NULL, NULL }
869 };
870
871 static fr_command_table_t command_table_show_home[] = {
872         { "config", FR_READ,
873           "show home_server config <ipaddr> <port> - show configuration for given home server",
874           command_show_home_server_config, NULL },
875         { "list", FR_READ,
876           "show home_server list - shows list of home servers",
877           command_show_home_servers, NULL },
878
879         { NULL, 0, NULL, NULL, NULL }
880 };
881
882
883 static fr_command_table_t command_table_show[] = {
884         { "client", FR_READ,
885           "show client <command> - do sub-command of client",
886           NULL, command_table_show_client },
887         { "debug", FR_READ,
888           "show debug <command> - show debug properties",
889           NULL, command_table_show_debug },
890         { "home_server", FR_READ,
891           "show home_server <command> - do sub-command of home_server",
892           NULL, command_table_show_home },
893         { "module", FR_READ,
894           "show module <command> - do sub-command of module",
895           NULL, command_table_show_module },
896         { "uptime", FR_READ,
897           "show uptime - shows time at which server started",
898           command_uptime, NULL },
899         { "xml", FR_READ,
900           "show xml <reference> - Prints out configuration as XML",
901           command_show_xml, NULL },
902         { NULL, 0, NULL, NULL, NULL }
903 };
904
905
906 static int command_set_module_config(rad_listen_t *listener, int argc, char *argv[])
907 {
908         int i, rcode;
909         CONF_PAIR *cp;
910         CONF_SECTION *cs;
911         module_instance_t *mi;
912         const CONF_PARSER *variables;
913         void *data;
914
915         if (argc < 3) {
916                 cprintf(listener, "ERROR: No module name or variable was given\n");
917                 return 0;
918         }
919
920         cs = cf_section_find("modules");
921         if (!cs) return 0;
922
923         mi = find_module_instance(cs, argv[0], 0);
924         if (!mi) {
925                 cprintf(listener, "ERROR: No such module \"%s\"\n", argv[0]);
926                 return 0;
927         }
928
929         if ((mi->entry->module->type & RLM_TYPE_HUP_SAFE) == 0) {
930                 cprintf(listener, "ERROR: Cannot change configuration of module as it is cannot be HUP'd.\n");
931                 return 0;
932         }
933
934         variables = cf_section_parse_table(mi->cs);
935         if (!variables) {
936                 cprintf(listener, "ERROR: Cannot find configuration for module\n");
937                 return 0;
938         }
939
940         rcode = -1;
941         for (i = 0; variables[i].name != NULL; i++) {
942                 /*
943                  *      FIXME: Recurse into sub-types somehow...
944                  */
945                 if (variables[i].type == PW_TYPE_SUBSECTION) continue;
946
947                 if (strcmp(variables[i].name, argv[1]) == 0) {
948                         rcode = i;
949                         break;
950                 }
951         }
952
953         if (rcode < 0) {
954                 cprintf(listener, "ERROR: No such variable \"%s\"\n", argv[1]);
955                 return 0;
956         }
957
958         i = rcode;              /* just to be safe */
959
960         /*
961          *      It's not part of the dynamic configuration.  The module
962          *      needs to re-parse && validate things.
963          */
964         if (variables[i].data) {
965                 cprintf(listener, "ERROR: Variable cannot be dynamically updated\n");
966                 return 0;
967         }
968
969         data = ((char *) mi->insthandle) + variables[i].offset;
970
971         cp = cf_pair_find(mi->cs, argv[1]);
972         if (!cp) return 0;
973
974         /*
975          *      Replace the OLD value in the configuration file with
976          *      the NEW value.
977          *
978          *      FIXME: Parse argv[2] depending on it's data type!
979          *      If it's a string, look for leading single/double quotes,
980          *      end then call tokenize functions???
981          */
982         cf_pair_replace(mi->cs, cp, argv[2]);
983
984         rcode = cf_item_parse(mi->cs, argv[1], variables[i].type,
985                               data, argv[2]);
986         if (rcode < 0) {
987                 cprintf(listener, "ERROR: Failed to parse value\n");
988                 return 0;
989         }
990
991         return 1;               /* success */
992 }
993
994 static int command_print_stats(rad_listen_t *listener, fr_stats_t *stats,
995                                int auth)
996 {
997         cprintf(listener, "\trequests\t%d\n", stats->total_requests);
998         cprintf(listener, "\tresponses\t%d\n", stats->total_responses);
999         
1000         if (auth) {
1001                 cprintf(listener, "\taccepts\t\t%d\n",
1002                         stats->total_access_accepts);
1003                 cprintf(listener, "\trejects\t\t%d\n",
1004                         stats->total_access_rejects);
1005                 cprintf(listener, "\tchallenges\t%d\n",
1006                         stats->total_access_challenges);
1007         }
1008
1009         cprintf(listener, "\tdup\t\t%d\n", stats->total_dup_requests);
1010         cprintf(listener, "\tinvalid\t\t%d\n", stats->total_invalid_requests);
1011         cprintf(listener, "\tmalformed\t%d\n", stats->total_malformed_requests);
1012         cprintf(listener, "\tbad_signature\t%d\n", stats->total_bad_authenticators);
1013         cprintf(listener, "\tdropped\t\t%d\n", stats->total_packets_dropped);
1014         cprintf(listener, "\tunknown_types\t%d\n", stats->total_unknown_types);
1015         
1016         return 1;
1017 }
1018
1019
1020 static int command_stats_home_server(rad_listen_t *listener, int argc, char *argv[])
1021 {
1022         int port;
1023         home_server *home;
1024         fr_ipaddr_t ipaddr;
1025
1026         if (argc < 2) {
1027                 cprintf(listener, "ERROR: <ipaddr> and <port> are required.\n");
1028                 return 0;
1029         }
1030
1031         if (ip_hton(argv[0], AF_UNSPEC, &ipaddr) < 0) {
1032                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
1033                         fr_strerror());
1034                 return 0;
1035         }
1036
1037         port = atoi(argv[1]);
1038
1039         home = home_server_find(&ipaddr, port);
1040         if (!home) {
1041                 cprintf(listener, "ERROR: No such home server\n");
1042                 return 0;
1043         }
1044
1045         return command_print_stats(listener, &home->stats,
1046                                    (home->type == HOME_TYPE_AUTH));
1047 }
1048
1049
1050 static int command_stats_client(rad_listen_t *listener, int argc, char *argv[])
1051 {
1052         int auth = TRUE;
1053         RADCLIENT *client;
1054         fr_ipaddr_t ipaddr;
1055
1056         if (argc == 0) {
1057                 return command_print_stats(listener, &radius_auth_stats, 1);
1058         }
1059
1060         if (strcmp(argv[0], "auth") == 0) {
1061                 auth = TRUE;
1062
1063         } else if (strcmp(argv[0], "acct") == 0) {
1064 #ifdef WITH_ACCOUNTING
1065                 auth = FALSE;
1066 #else
1067                 cprintf(listener, "ERROR: This server was built without accounting support.\n");
1068                 return 0;
1069 #endif
1070
1071         } else {
1072                 cprintf(listener, "ERROR: Unknown statistics type\n");
1073                 return 0;
1074         }
1075
1076         if (argc == 1) {
1077 #ifdef WITH_ACCOUNTING
1078                 if (!auth) {
1079                         return command_print_stats(listener,
1080                                                    &radius_acct_stats, auth);
1081                 }
1082 #endif
1083                 return command_print_stats(listener, &radius_auth_stats, auth);
1084         }
1085
1086         if (ip_hton(argv[1], AF_UNSPEC, &ipaddr) < 0) {
1087                 cprintf(listener, "ERROR: Failed parsing IP address; %s\n",
1088                         fr_strerror());
1089                 return 0;
1090         }
1091
1092         client = client_find(NULL, &ipaddr);
1093         if (!client) {
1094                 cprintf(listener, "ERROR: No such client\n");
1095                 return 0;
1096         }
1097
1098 #ifdef WITH_ACCOUNTING
1099         if (!auth) {
1100                 return command_print_stats(listener, client->acct, auth);
1101         }
1102 #endif
1103
1104         return command_print_stats(listener, client->auth, auth);
1105 }
1106
1107
1108 static int command_add_client_file(rad_listen_t *listener, int argc, char *argv[])
1109 {
1110         RADCLIENT *c;
1111
1112         if (argc < 1) {
1113                 cprintf(listener, "ERROR: <file> is required\n");
1114                 return 0;
1115         }
1116
1117         /*
1118          *      Read the file and generate the client.
1119          */
1120         c = client_read(argv[0], FALSE, FALSE);
1121         if (!c) {
1122                 cprintf(listener, "ERROR: Unknown error reading client file.\n");
1123                 return 0;
1124         }
1125
1126         if (!client_add(NULL, c)) {
1127                 cprintf(listener, "ERROR: Unknown error inserting new client.\n");
1128                 client_free(c);
1129                 return 0;
1130         }
1131
1132         return 1;
1133 }
1134
1135
1136 static fr_command_table_t command_table_add_client[] = {
1137         { "file", FR_WRITE,
1138           "add client file <filename> - Add new client definition from <filename>",
1139           command_add_client_file, NULL },
1140
1141         { NULL, 0, NULL, NULL, NULL }
1142 };
1143
1144
1145 static fr_command_table_t command_table_add[] = {
1146         { "client", FR_WRITE,
1147           "add client <command> - Add client configuration commands",
1148           NULL, command_table_add_client },
1149
1150         { NULL, 0, NULL, NULL, NULL }
1151 };
1152
1153 static fr_command_table_t command_table_set_module[] = {
1154         { "config", FR_WRITE,
1155           "set module config <module> variable value - set configuration for <module>",
1156           command_set_module_config, NULL },
1157
1158         { NULL, 0, NULL, NULL, NULL }
1159 };
1160
1161
1162 static fr_command_table_t command_table_set[] = {
1163         { "module", FR_WRITE, NULL, NULL, command_table_set_module },
1164
1165         { NULL, 0, NULL, NULL, NULL }
1166 };
1167
1168
1169 static fr_command_table_t command_table_stats[] = {
1170         { "client", FR_READ,
1171           "stats client [auth/acct] <ipaddr> - show statistics for client",
1172           command_stats_client, NULL },
1173         { "home_server", FR_READ,
1174           "stats home_server <ipaddr> <port> - show statistics for home server",
1175           command_stats_home_server, NULL },
1176
1177         { NULL, 0, NULL, NULL, NULL }
1178 };
1179
1180 static fr_command_table_t command_table[] = {
1181         { "add", FR_WRITE,
1182           "add <command> - add configuration commands",
1183           NULL, command_table_add },
1184         { "debug", FR_WRITE,
1185           "debug <command> - debugging commands",
1186           NULL, command_table_debug },
1187         { "hup", FR_WRITE,
1188           "hup [module] - sends a HUP signal to the server, or optionally to one module",
1189           command_hup, NULL },
1190         { "reconnect", FR_READ,
1191           "reconnect - reconnect to a running server",
1192           NULL, NULL },         /* just here for "help" */
1193         { "terminate", FR_WRITE,
1194           "terminate - terminates the server, and causes it to exit",
1195           command_terminate, NULL },
1196         { "set", FR_WRITE, NULL, NULL, command_table_set },
1197         { "show",  FR_READ, NULL, NULL, command_table_show },
1198         { "stats",  FR_READ, NULL, NULL, command_table_stats },
1199
1200         { NULL, 0, NULL, NULL, NULL }
1201 };
1202
1203
1204 /*
1205  *      Parse the unix domain sockets.
1206  *
1207  *      FIXME: TCP + SSL, after RadSec is in.
1208  */
1209 static int command_socket_parse(CONF_SECTION *cs, rad_listen_t *this)
1210 {
1211         fr_command_socket_t *sock;
1212
1213         sock = this->data;
1214
1215         if (cf_section_parse(cs, sock, command_config) < 0) {
1216                 return -1;
1217         }
1218
1219 #if defined(HAVE_GETPEEREID) || defined (SO_PEERCRED)
1220         if (sock->uid_name) {
1221                 struct passwd *pw;
1222                 
1223                 pw = getpwnam(sock->uid_name);
1224                 if (!pw) {
1225                         radlog(L_ERR, "Failed getting uid for %s: %s",
1226                                sock->uid_name, strerror(errno));
1227                         return -1;
1228                 }
1229
1230                 sock->uid = pw->pw_uid;
1231         }
1232
1233         if (sock->gid_name) {
1234                 struct group *gr;
1235
1236                 gr = getgrnam(sock->gid_name);
1237                 if (!gr) {
1238                         radlog(L_ERR, "Failed getting gid for %s: %s",
1239                                sock->gid_name, strerror(errno));
1240                         return -1;
1241                 }
1242                 sock->gid = gr->gr_gid; 
1243         }
1244
1245 #else  /* can't get uid or gid of connecting user */
1246
1247         if (sock->uid_name || sock->gid_name) {
1248                 radlog(L_ERR, "System does not support uid or gid authentication for sockets");
1249                 return -1;
1250         }
1251
1252 #endif
1253
1254         if (!sock->mode_name) {
1255                 sock->mode = FR_READ;
1256         } else {
1257                 sock->mode = fr_str2int(mode_names, sock->mode_name, 0);
1258                 if (!sock->mode) {
1259                         radlog(L_ERR, "Invalid mode name \"%s\"",
1260                                sock->mode_name);
1261                         return -1;
1262                 }
1263         }
1264
1265         /*
1266          *      FIXME: check for absolute pathnames?
1267          *      check for uid/gid on the other end...    
1268          */
1269
1270         this->fd = fr_server_domain_socket(sock->path);
1271         if (this->fd < 0) {
1272                 return -1;
1273         }
1274
1275         return 0;
1276 }
1277
1278 static int command_socket_print(rad_listen_t *this, char *buffer, size_t bufsize)
1279 {
1280         fr_command_socket_t *sock = this->data;
1281
1282         snprintf(buffer, bufsize, "command file %s", sock->path);
1283         return 1;
1284 }
1285
1286
1287 /*
1288  *      String split routine.  Splits an input string IN PLACE
1289  *      into pieces, based on spaces.
1290  */
1291 static int str2argv(char *str, char **argv, int max_argc)
1292 {
1293         int argc = 0;
1294         size_t len;
1295         char buffer[1024];
1296
1297         while (*str) {
1298                 if (argc >= max_argc) return argc;
1299
1300                 /*
1301                  *      Chop out comments early.
1302                  */
1303                 if (*str == '#') {
1304                         *str = '\0';
1305                         break;
1306                 }
1307
1308                 while ((*str == ' ') ||
1309                        (*str == '\t') ||
1310                        (*str == '\r') ||
1311                        (*str == '\n')) *(str++) = '\0';
1312
1313                 if (!*str) return argc;
1314
1315                 if ((*str == '\'') || (*str == '"')) {
1316                         char *p = str;
1317                         FR_TOKEN token;
1318
1319                         token = gettoken((const char **) &p, buffer,
1320                                          sizeof(buffer));
1321                         if ((token != T_SINGLE_QUOTED_STRING) &&
1322                             (token != T_DOUBLE_QUOTED_STRING)) {
1323                                 return -1;
1324                         }
1325
1326                         len = strlen(buffer);
1327                         if (len >= (size_t) (p - str)) {
1328                                 return -1;
1329                         }
1330
1331                         memcpy(str, buffer, len + 1);
1332                         argv[argc] = str;
1333                         str = p;
1334
1335                 } else {
1336                         argv[argc] = str;
1337                 }
1338                 argc++;
1339
1340                 while (*str &&
1341                        (*str != ' ') &&
1342                        (*str != '\t') &&
1343                        (*str != '\r') &&
1344                        (*str != '\n')) str++;
1345         }
1346
1347         return argc;
1348 }
1349
1350 #define MAX_ARGV (16)
1351
1352 /*
1353  *      Check if an incoming request is "ok"
1354  *
1355  *      It takes packets, not requests.  It sees if the packet looks
1356  *      OK.  If so, it does a number of sanity checks on it.
1357  */
1358 static int command_domain_recv(rad_listen_t *listener,
1359                                UNUSED RAD_REQUEST_FUNP *pfun,
1360                                UNUSED REQUEST **prequest)
1361 {
1362         int i, rcode;
1363         ssize_t len;
1364         int argc;
1365         char *my_argv[MAX_ARGV], **argv;
1366         fr_command_table_t *table;
1367         fr_command_socket_t *co = listener->data;
1368
1369         *pfun = NULL;
1370         *prequest = NULL;
1371
1372         do {
1373                 ssize_t c;
1374                 char *p;
1375
1376                 len = recv(listener->fd, co->buffer + co->offset,
1377                            sizeof(co->buffer) - co->offset - 1, 0);
1378                 if (len == 0) goto close_socket; /* clean close */
1379
1380                 if (len < 0) {
1381                         if ((errno == EAGAIN) || (errno == EINTR)) {
1382                                 return 0;
1383                         }
1384                         goto close_socket;
1385                 }
1386
1387                 /*
1388                  *      CTRL-D
1389                  */
1390                 if ((co->offset == 0) && (co->buffer[0] == 0x04)) {
1391                 close_socket:
1392                         listener->status = RAD_LISTEN_STATUS_CLOSED;
1393                         event_new_fd(listener);
1394                         return 0;
1395                 }
1396
1397                 /*
1398                  *      See if there are multiple lines in the buffer.
1399                  */
1400                 p = co->buffer + co->offset;
1401                 rcode = 0;
1402                 p[len] = '\0';
1403                 for (c = 0; c < len; c++) {
1404                         if ((*p == '\r') || (*p == '\n')) {
1405                                 rcode = 1;
1406                                 *p = '\0';
1407
1408                                 /*
1409                                  *      FIXME: do real buffering...
1410                                  *      handling of CTRL-C, etc.
1411                                  */
1412
1413                         } else if (rcode) {
1414                                 /*
1415                                  *      \r \n followed by ASCII...
1416                                  */
1417                                 break;
1418                         }
1419
1420                         p++;
1421                 }
1422
1423                 co->offset += len;
1424
1425                 /*
1426                  *      Saw CR/LF.  Set next element, and exit.
1427                  */
1428                 if (rcode) {
1429                         co->next = p - co->buffer;
1430                         break;
1431                 }
1432
1433                 if (co->offset >= (ssize_t) (sizeof(co->buffer) - 1)) {
1434                         radlog(L_ERR, "Line too long!");
1435                         goto close_socket;
1436                 }
1437
1438                 co->offset++;
1439         } while (1);
1440
1441         argc = str2argv(co->buffer, my_argv, MAX_ARGV);
1442         if (argc == 0) goto do_next; /* empty strings are OK */
1443
1444         if (argc < 0) {
1445                 cprintf(listener, "ERROR: Failed parsing command.\n");
1446                 goto do_next;
1447         }
1448
1449         argv = my_argv;
1450
1451         for (len = 0; len <= co->offset; len++) {
1452                 if (co->buffer[len] < 0x20) {
1453                         co->buffer[len] = '\0';
1454                         break;
1455                 }
1456         }
1457
1458         /*
1459          *      Hard-code exit && quit.
1460          */
1461         if ((strcmp(argv[0], "exit") == 0) ||
1462             (strcmp(argv[0], "quit") == 0)) goto close_socket;
1463
1464 #if 0
1465         if (!co->user[0]) {
1466                 if (strcmp(argv[0], "login") != 0) {
1467                         cprintf(listener, "ERROR: Login required\n");
1468                         goto do_next;
1469                 }
1470
1471                 if (argc < 3) {
1472                         cprintf(listener, "ERROR: login <user> <password>\n");
1473                         goto do_next;
1474                 }
1475
1476                 /*
1477                  *      FIXME: Generate && process fake RADIUS request.
1478                  */
1479                 if ((strcmp(argv[1], "root") == 0) &&
1480                     (strcmp(argv[2], "password") == 0)) {
1481                         strlcpy(co->user, argv[1], sizeof(co->user));
1482                         goto do_next;
1483                 }
1484
1485                 cprintf(listener, "ERROR: Login incorrect\n");
1486                 goto do_next;
1487         }
1488 #endif
1489
1490         table = command_table;
1491  retry:
1492         len = 0;
1493         for (i = 0; table[i].command != NULL; i++) {
1494                 if (strcmp(table[i].command, argv[0]) == 0) {
1495                         /*
1496                          *      Check permissions.
1497                          */
1498                         if (((co->mode & FR_WRITE) == 0) &&
1499                             ((table[i].mode & FR_WRITE) != 0)) {
1500                                 cprintf(listener, "ERROR: You do not have write permission.\n");
1501                                 goto do_next;
1502                         }
1503
1504                         if (table[i].table) {
1505                                 /*
1506                                  *      This is the last argument, but
1507                                  *      there's a sub-table.  Print help.
1508                                  *      
1509                                  */
1510                                 if (argc == 1) {
1511                                         table = table[i].table;
1512                                         goto do_help;
1513                                 }
1514
1515                                 argc--;
1516                                 argv++;
1517                                 table = table[i].table;
1518                                 goto retry;
1519                         }
1520
1521                         if (!table[i].func) {
1522                                 cprintf(listener, "ERROR: Invalid command\n");
1523                                 goto do_next;
1524                         }
1525
1526                         len = 1;
1527                         rcode = table[i].func(listener,
1528                                               argc - 1, argv + 1);
1529                         break;
1530                 }
1531         }
1532
1533         /*
1534          *      No such command
1535          */
1536         if (!len) {
1537                 if ((strcmp(argv[0], "help") == 0) ||
1538                     (strcmp(argv[0], "?") == 0)) {
1539                 do_help:
1540                         for (i = 0; table[i].command != NULL; i++) {
1541                                 if (table[i].help) {
1542                                         cprintf(listener, "%s\n",
1543                                                 table[i].help);
1544                                 } else {
1545                                         cprintf(listener, "%s <command> - do sub-command of %s\n",
1546                                                 table[i].command, table[i].command);
1547                                 }
1548                         }
1549                         goto do_next;
1550                 }
1551
1552                 cprintf(listener, "ERROR: Unknown command \"%s\"\r\n",
1553                         argv[0]);
1554         }
1555
1556  do_next:
1557         cprintf(listener, "radmin> ");
1558
1559         if (co->next <= co->offset) {
1560                 co->offset = 0;
1561         } else {
1562                 memmove(co->buffer, co->buffer + co->next,
1563                         co->offset - co->next);
1564                 co->offset -= co->next;
1565         }
1566
1567         return 0;
1568 }
1569
1570
1571 static int command_domain_accept(rad_listen_t *listener,
1572                                  UNUSED RAD_REQUEST_FUNP *pfun,
1573                                  UNUSED REQUEST **prequest)
1574 {
1575         int newfd;
1576         uint32_t magic;
1577         rad_listen_t *this;
1578         socklen_t salen;
1579         struct sockaddr_storage src;
1580         fr_command_socket_t *sock = listener->data;
1581         
1582         salen = sizeof(src);
1583
1584         DEBUG2(" ... new connection request on command socket.");
1585         
1586         newfd = accept(listener->fd, (struct sockaddr *) &src, &salen);
1587         if (newfd < 0) {
1588                 /*
1589                  *      Non-blocking sockets must handle this.
1590                  */
1591                 if (errno == EWOULDBLOCK) {
1592                         return 0;
1593                 }
1594
1595                 DEBUG2(" ... failed to accept connection.");
1596                 return -1;
1597         }
1598
1599         /*
1600          *      Perform user authentication.
1601          */
1602         if (sock->uid_name || sock->gid_name) {
1603                 uid_t uid;
1604                 gid_t gid;
1605
1606                 if (getpeereid(listener->fd, &uid, &gid) < 0) {
1607                         radlog(L_ERR, "Failed getting peer credentials for %s: %s",
1608                                sock->path, strerror(errno));
1609                         close(newfd);
1610                         return -1;
1611                 }
1612
1613                 if (sock->uid_name && (sock->uid != uid)) {
1614                         radlog(L_ERR, "Unauthorized connection to %s from uid %ld",
1615                                sock->path, (long int) uid);
1616                         close(newfd);
1617                         return -1;
1618                 }
1619
1620                 if (sock->gid_name && (sock->gid != gid)) {
1621                         radlog(L_ERR, "Unauthorized connection to %s from gid %ld",
1622                                sock->path, (long int) gid);
1623                         close(newfd);
1624                         return -1;
1625                 }
1626         }
1627
1628         /*
1629          *      Write 32-bit magic number && version information.
1630          */
1631         magic = htonl(0xf7eead15);
1632         if (write(newfd, &magic, 4) < 0) {
1633                 radlog(L_ERR, "Failed writing initial data to socket: %s",
1634                        strerror(errno));
1635                 close(newfd);
1636                 return -1;
1637         }
1638         magic = htonl(1);       /* protocol version */
1639         if (write(newfd, &magic, 4) < 0) {
1640                 radlog(L_ERR, "Failed writing initial data to socket: %s",
1641                        strerror(errno));
1642                 close(newfd);
1643                 return -1;
1644         }
1645
1646
1647         /*
1648          *      Add the new listener.
1649          */
1650         this = listen_alloc(listener->type);
1651         if (!this) return -1;
1652
1653         /*
1654          *      Copy everything, including the pointer to the socket
1655          *      information.
1656          */
1657         sock = this->data;
1658         memcpy(this, listener, sizeof(*this));
1659         this->status = RAD_LISTEN_STATUS_INIT;
1660         this->next = NULL;
1661         this->data = sock;      /* fix it back */
1662
1663         sock->offset = 0;
1664         sock->user[0] = '\0';
1665         sock->path = ((fr_command_socket_t *) listener->data)->path;
1666         sock->mode = ((fr_command_socket_t *) listener->data)->mode;
1667
1668         this->fd = newfd;
1669         this->recv = command_domain_recv;
1670
1671         /*
1672          *      Tell the event loop that we have a new FD
1673          */
1674         event_new_fd(this);
1675
1676         return 0;
1677 }
1678
1679
1680 /*
1681  *      Send an authentication response packet
1682  */
1683 static int command_domain_send(UNUSED rad_listen_t *listener,
1684                                UNUSED REQUEST *request)
1685 {
1686         return 0;
1687 }
1688
1689
1690 static int command_socket_encode(UNUSED rad_listen_t *listener,
1691                                  UNUSED REQUEST *request)
1692 {
1693         return 0;
1694 }
1695
1696
1697 static int command_socket_decode(UNUSED rad_listen_t *listener,
1698                                  UNUSED REQUEST *request)
1699 {
1700         return 0;
1701 }
1702
1703 #endif /* WITH_COMMAND_SOCKET */