Set types correctly on talloced VALUE_PAIR buffers
[freeradius.git] / src / main / radiusd.c
1 /*
2  * radiusd.c    Main loop of the radius server.
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 2000-2012  The FreeRADIUS server project
21  * Copyright 1999,2000  Miquel van Smoorenburg <miquels@cistron.nl>
22  * Copyright 2000  Alan DeKok <aland@ox.org>
23  * Copyright 2000  Alan Curry <pacman-radius@cqc.com>
24  * Copyright 2000  Jeff Carneal <jeff@apex.net>
25  * Copyright 2000  Chad Miller <cmiller@surfsouth.com>
26  */
27
28 RCSID("$Id$")
29
30 #include <freeradius-devel/radiusd.h>
31 #include <freeradius-devel/modules.h>
32 #include <freeradius-devel/rad_assert.h>
33
34 #include <sys/file.h>
35
36 #include <fcntl.h>
37 #include <ctype.h>
38
39 #ifdef HAVE_GETOPT_H
40 #       include <getopt.h>
41 #endif
42
43 #ifdef HAVE_SYS_WAIT_H
44 #       include <sys/wait.h>
45 #endif
46 #ifndef WEXITSTATUS
47 #       define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8)
48 #endif
49 #ifndef WIFEXITED
50 #       define WIFEXITED(stat_val) (((stat_val) & 255) == 0)
51 #endif
52
53 /*
54  *  Global variables.
55  */
56 char const *progname = NULL;
57 char const *radius_dir = NULL;
58 char const *radacct_dir = NULL;
59 char const *radlog_dir = NULL;
60 char const *radlib_dir = NULL;
61 bool log_stripped_names;
62 log_debug_t debug_flag = 0;
63 bool check_config = false;
64
65 char const *radiusd_version = "FreeRADIUS Version " RADIUSD_VERSION_STRING
66 #ifdef RADIUSD_VERSION_COMMIT
67 " (git #" STRINGIFY(RADIUSD_VERSION_COMMIT) ")"
68 #endif
69 ", for host " HOSTINFO ", built on " __DATE__ " at " __TIME__;
70
71 pid_t radius_pid;
72
73 /*
74  *  Configuration items.
75  */
76
77 /*
78  *      Static functions.
79  */
80 static void usage(int);
81
82 static void sig_fatal (int);
83 #ifdef SIGHUP
84 static void sig_hup (int);
85 #endif
86
87 #ifdef WITH_VERIFY_PTR
88 static void die_horribly(char const *reason)
89 {
90         ERROR("talloc abort: %s\n", reason);
91         abort();
92 }
93 #endif
94
95 /*
96  *      The main guy.
97  */
98 int main(int argc, char *argv[])
99 {
100         int rcode = EXIT_SUCCESS;
101         int status;
102         int argval;
103         bool spawn_flag = true;
104         bool dont_fork = false;
105         bool write_pid = false;
106         int flag = 0;
107         int from_child[2] = {-1, -1};
108
109         int devnull;
110
111         /*
112          *      We probably don't want to free the talloc autofree context
113          *      directly, so we'll allocate a new context beneath it, and
114          *      free that before any leak reports.
115          */
116         TALLOC_CTX *autofree = talloc(talloc_autofree_context(), void *);
117
118         /*
119          *      If the server was built with debugging enabled always install
120          *      the basic fatal signal handlers.
121          */
122 #ifndef NDEBUG
123         fr_fault_setup(getenv("PANIC_ACTION"), argv[0]);
124 #endif
125
126 #ifdef OSFC2
127         set_auth_parameters(argc,argv);
128 #endif
129
130         if ((progname = strrchr(argv[0], FR_DIR_SEP)) == NULL)
131                 progname = argv[0];
132         else
133                 progname++;
134
135 #ifdef WIN32
136         {
137                 WSADATA wsaData;
138                 if (WSAStartup(MAKEWORD(2, 0), &wsaData)) {
139                         fprintf(stderr, "%s: Unable to initialize socket library.\n", progname);
140                         exit(EXIT_FAILURE);
141                 }
142         }
143 #endif
144
145         debug_flag = 0;
146         set_radius_dir(autofree, RADIUS_DIR);
147
148         /*
149          *      Ensure that the configuration is initialized.
150          */
151         memset(&mainconfig, 0, sizeof(mainconfig));
152         mainconfig.myip.af = AF_UNSPEC;
153         mainconfig.port = -1;
154         mainconfig.name = "radiusd";
155
156         /*
157          *      Don't put output anywhere until we get told a little
158          *      more.
159          */
160         default_log.dest = L_DST_NULL;
161         default_log.fd = -1;
162         mainconfig.log_file = NULL;
163
164         /*  Process the options.  */
165         while ((argval = getopt(argc, argv, "Cd:D:fhi:l:mMn:p:PstvxX")) != EOF) {
166
167                 switch(argval) {
168                         case 'C':
169                                 check_config = true;
170                                 spawn_flag = false;
171                                 dont_fork = true;
172                                 break;
173
174                         case 'd':
175                                 set_radius_dir(autofree, optarg);
176                                 break;
177
178                         case 'D':
179                                 mainconfig.dictionary_dir = talloc_typed_strdup(NULL, optarg);
180                                 break;
181
182                         case 'f':
183                                 dont_fork = true;
184                                 break;
185
186                         case 'h':
187                                 usage(0);
188                                 break;
189
190                         case 'l':
191                                 if (strcmp(optarg, "stdout") == 0) {
192                                         goto do_stdout;
193                                 }
194                                 mainconfig.log_file = strdup(optarg);
195                                 default_log.dest = L_DST_FILES;
196                                 default_log.fd = open(mainconfig.log_file,
197                                                             O_WRONLY | O_APPEND | O_CREAT, 0640);
198                                 if (default_log.fd < 0) {
199                                         fprintf(stderr, "radiusd: Failed to open log file %s: %s\n", mainconfig.log_file, fr_syserror(errno));
200                                         exit(EXIT_FAILURE);
201                                 }
202                                 fr_log_fp = fdopen(default_log.fd, "a");
203                                 break;
204
205                         case 'i':
206                                 if (ip_hton(optarg, AF_UNSPEC, &mainconfig.myip) < 0) {
207                                         fprintf(stderr, "radiusd: Invalid IP Address or hostname \"%s\"\n", optarg);
208                                         exit(EXIT_FAILURE);
209                                 }
210                                 flag |= 1;
211                                 break;
212
213                         case 'n':
214                                 mainconfig.name = optarg;
215                                 break;
216
217                         case 'm':
218                                 mainconfig.debug_memory = true;
219                                 break;
220
221                         case 'M':
222                                 mainconfig.memory_report = true;
223                                 mainconfig.debug_memory = true;
224                                 break;
225
226                         case 'p':
227                                 mainconfig.port = atoi(optarg);
228                                 if ((mainconfig.port <= 0) ||
229                                     (mainconfig.port >= 65536)) {
230                                         fprintf(stderr, "radiusd: Invalid port number %s\n", optarg);
231                                         exit(EXIT_FAILURE);
232                                 }
233                                 flag |= 2;
234                                 break;
235
236                         case 'P':
237                                 /* Force the PID to be written, even in -f mode */
238                                 write_pid = true;
239                                 break;
240
241                         case 's':       /* Single process mode */
242                                 spawn_flag = false;
243                                 dont_fork = true;
244                                 break;
245
246                         case 't':       /* no child threads */
247                                 spawn_flag = false;
248                                 break;
249
250                         case 'v':
251                                 /* Don't print timestamps */
252                                 debug_flag += 2;
253                                 fr_log_fp = stdout;
254                                 default_log.dest = L_DST_STDOUT;
255                                 default_log.fd = STDOUT_FILENO;
256
257                                 version();
258                                 exit(EXIT_SUCCESS);
259                         case 'X':
260                                 spawn_flag = false;
261                                 dont_fork = true;
262                                 debug_flag += 2;
263                                 mainconfig.log_auth = true;
264                                 mainconfig.log_auth_badpass = true;
265                                 mainconfig.log_auth_goodpass = true;
266                 do_stdout:
267                                 fr_log_fp = stdout;
268                                 default_log.dest = L_DST_STDOUT;
269                                 default_log.fd = STDOUT_FILENO;
270                                 break;
271
272                         case 'x':
273                                 debug_flag++;
274                                 break;
275
276                         default:
277                                 usage(1);
278                                 break;
279                 }
280         }
281
282         if (mainconfig.memory_report) {
283                 talloc_enable_null_tracking();
284 #ifdef WITH_VERIFY_PTR
285                 talloc_set_abort_fn(die_horribly);
286 #endif
287         }
288         talloc_set_log_fn(log_talloc);
289
290         /*
291          *      Mismatch between the binary and the libraries it depends on
292          */
293         if (fr_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) {
294                 fr_perror("radiusd");
295                 exit(EXIT_FAILURE);
296         }
297
298         if (rad_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) {
299                 exit(EXIT_FAILURE);
300         }
301
302         /*
303          *      Mismatch between build time OpenSSL and linked SSL,
304          *      better to die here than segfault later.
305          */
306 #ifdef HAVE_OPENSSL_CRYPTO_H
307         if (ssl_check_version() < 0) {
308                 exit(EXIT_FAILURE);
309         }
310
311         /*
312          *      Initialising OpenSSL once, here, is safer than having individual
313          *      modules do it.
314          */
315         tls_global_init();
316 #endif
317
318         if (flag && (flag != 0x03)) {
319                 fprintf(stderr, "radiusd: The options -i and -p cannot be used individually.\n");
320                 exit(EXIT_FAILURE);
321         }
322
323         if (debug_flag) {
324                 version();
325         }
326
327         /*
328          *  Initialize any event loops just enough so module instantiations
329          *  can add fd/event to them, but do not start them yet.
330          */
331         if (!radius_event_init(autofree)) {
332                 exit(EXIT_FAILURE);
333         }
334
335         /*  Read the configuration files, BEFORE doing anything else.  */
336         if (read_mainconfig(0) < 0) {
337                 exit(EXIT_FAILURE);
338         }
339
340         /* Set the panic action (if required) */
341         if (mainconfig.panic_action &&
342 #ifndef NDEBUG
343             !getenv("PANIC_ACTION") &&
344 #endif
345             (fr_fault_setup(mainconfig.panic_action, argv[0]) < 0)) {
346                 exit(EXIT_FAILURE);
347         }
348
349 #ifndef __MINGW32__
350
351         devnull = open("/dev/null", O_RDWR);
352         if (devnull < 0) {
353                 ERROR("Failed opening /dev/null: %s", fr_syserror(errno));
354                 exit(EXIT_FAILURE);
355         }
356
357         /*
358          *  Disconnect from session
359          */
360         if (dont_fork == false) {
361                 pid_t pid;
362
363                 /*
364                  *  Really weird things happen if we leave stdin open and call things like
365                  *  system() later.
366                  */
367                 if (dont_fork == false) {
368                         dup2(devnull, STDIN_FILENO);
369                 }
370
371                 if (pipe(from_child) != 0) {
372                         ERROR("Couldn't open pipe for child status: %s", fr_syserror(errno));
373                         exit(EXIT_FAILURE);
374                 }
375
376                 pid = fork();
377                 if (pid < 0) {
378                         ERROR("Couldn't fork: %s", fr_syserror(errno));
379                         exit(EXIT_FAILURE);
380                 }
381
382                 /*
383                  *  The parent exits, so the child can run in the background.
384                  *
385                  *  As the child can still encounter an error during initialisation
386                  *  we do a blocking read on a pipe between it and the parent.
387                  *
388                  *  Just before entering the event loop the child will send a success
389                  *  or failure message to the parent, via the pipe.
390                  */
391                 if (pid > 0) {
392                         uint8_t ret = 0;
393                         int stat_loc;
394
395                         /* So the pipe is correctly widowed if the child exits */
396                         close(from_child[1]);
397
398                         /*
399                          *      The child writes a 0x01 byte on
400                          *      success, and closes the pipe on error.
401                          */
402                         if ((read(from_child[0], &ret, 1) < 0)) {
403                                 ret = 0;
404                         }
405
406                         /* For cleanliness... */
407                         close(from_child[0]);
408
409                         /* Don't turn children into zombies */
410                         if (!ret) {
411                                 waitpid(pid, &stat_loc, WNOHANG);
412                                 exit(EXIT_FAILURE);
413                         }
414
415                         exit(EXIT_SUCCESS);
416                 }
417
418                 /* so the pipe is correctly widowed if the parent exits?! */
419                 close(from_child[0]);
420 #  ifdef HAVE_SETSID
421                 setsid();
422 #  endif
423         }
424 #endif
425
426         if (default_log.dest == L_DST_STDOUT) {
427                 setlinebuf(stdout);
428                 default_log.fd = STDOUT_FILENO;
429         } else if (debug_flag) {
430                 dup2(devnull, STDOUT_FILENO);
431         }
432
433         if (default_log.dest == L_DST_STDERR) {
434                 setlinebuf(stdout);
435                 default_log.fd = STDERR_FILENO;
436         } else {
437                 dup2(devnull, STDERR_FILENO);
438         }
439
440         /* Libraries may write messages to stderr or stdout */
441         if (debug_flag) {
442                 dup2(default_log.fd, STDOUT_FILENO);
443                 dup2(default_log.fd, STDERR_FILENO);
444         }
445
446         close(devnull);
447
448         /*
449          *  Ensure that we're using the CORRECT pid after forking,
450          *  NOT the one we started with.
451          */
452         radius_pid = getpid();
453
454         /*
455          *      Start the event loop(s) and threads.
456          */
457         radius_event_start(mainconfig.config, spawn_flag);
458
459         /*
460          *      Now that we've set everything up, we can install the signal
461          *      handlers.  Before this, if we get any signal, we don't know
462          *      what to do, so we might as well do the default, and die.
463          */
464 #ifdef SIGPIPE
465         signal(SIGPIPE, SIG_IGN);
466 #endif
467
468         if ((fr_set_signal(SIGHUP, sig_hup) < 0) ||
469             (fr_set_signal(SIGTERM, sig_fatal) < 0)) {
470                 ERROR("%s", fr_strerror());
471                 exit(EXIT_FAILURE);
472         }
473
474         /*
475          *      If we're debugging, then a CTRL-C will cause the
476          *      server to die immediately.  Use SIGTERM to shut down
477          *      the server cleanly in that case.
478          */
479         if (mainconfig.debug_memory || (debug_flag == 0)) {
480                 if ((fr_set_signal(SIGINT, sig_fatal) < 0)
481 #ifdef SIGQUIT
482                 || (fr_set_signal(SIGQUIT, sig_fatal) < 0)
483 #endif
484                 ) {
485                         ERROR("%s", fr_strerror());
486                         exit(EXIT_FAILURE);
487                 }
488         }
489
490         /*
491          *      Everything seems to have loaded OK, exit gracefully.
492          */
493         if (check_config) {
494                 DEBUG("Configuration appears to be OK.");
495
496                 /* for -C -m|-M */
497                 if (mainconfig.debug_memory) {
498                         goto cleanup;
499                 }
500
501                 exit(EXIT_SUCCESS);
502         }
503
504 #ifdef WITH_STATS
505         radius_stats_init(0);
506 #endif
507
508         /*
509          *      Write out the PID anyway if were in foreground mode.
510          */
511         if (!dont_fork) write_pid = true;
512
513         /*
514          *  Only write the PID file if we're running as a daemon.
515          *
516          *  And write it AFTER we've forked, so that we write the
517          *  correct PID.
518          */
519         if (write_pid) {
520                 FILE *fp;
521
522                 fp = fopen(mainconfig.pid_file, "w");
523                 if (fp != NULL) {
524                         /*
525                          *      FIXME: What about following symlinks,
526                          *      and having it over-write a normal file?
527                          */
528                         fprintf(fp, "%d\n", (int) radius_pid);
529                         fclose(fp);
530                 } else {
531                         ERROR("Failed creating PID file %s: %s\n",
532                                mainconfig.pid_file, fr_syserror(errno));
533                         exit(EXIT_FAILURE);
534                 }
535         }
536
537         exec_trigger(NULL, NULL, "server.start", false);
538
539         /*
540          *      Inform the parent (who should still be waiting) that
541          *      the rest of initialisation went OK, and that it should
542          *      exit with a 0 status.  If we don't get this far, then
543          *      we just close the pipe on exit, and the parent gets a
544          *      read failure.
545          */
546         if (!dont_fork) {
547                 if (write(from_child[1], "\001", 1) < 0) {
548                         WARN("Failed informing parent of successful start: %s",
549                              fr_syserror(errno));
550                 }
551                 close(from_child[1]);
552         }
553
554         /*
555          *      Process requests until HUP or exit.
556          */
557         while ((status = radius_event_process()) == 0x80) {
558 #ifdef WITH_STATS
559                 radius_stats_init(1);
560 #endif
561                 hup_mainconfig();
562         }
563         if (status < 0) {
564                 ERROR("Exiting due to internal error: %s", fr_strerror());
565                 rcode = EXIT_FAILURE;
566         } else {
567                 INFO("Exiting normally.");
568         }
569
570         exec_trigger(NULL, NULL, "server.stop", false);
571
572         /*
573          *      Ignore the TERM signal: we're
574          *      about to die.
575          */
576         signal(SIGTERM, SIG_IGN);
577
578         /*
579          *      Send a TERM signal to all
580          *      associated processes
581          *      (including us, which gets
582          *      ignored.)
583          */
584 #ifndef __MINGW32__
585         if (spawn_flag) kill(-radius_pid, SIGTERM);
586 #endif
587
588         /*
589          *      We're exiting, so we can delete the PID
590          *      file.  (If it doesn't exist, we can ignore
591          *      the error returned by unlink)
592          */
593         if (dont_fork == false) {
594                 unlink(mainconfig.pid_file);
595         }
596
597         radius_event_free();
598
599 cleanup:
600         /*
601          *      Detach any modules.
602          */
603         detach_modules();
604
605         xlat_free();            /* modules may have xlat's */
606
607         /*
608          *      Free the configuration items.
609          */
610         free_mainconfig();
611
612 #ifdef WIN32
613         WSACleanup();
614 #endif
615
616         /*
617          *      So we don't see autofreed memory in the talloc report
618          */
619         talloc_free(autofree);
620
621         if (mainconfig.memory_report) {
622                 INFO("Allocated memory at time of report:");
623                 log_talloc_report(NULL);
624         }
625
626         return rcode;
627 }
628
629
630 /*
631  *  Display the syntax for starting this program.
632  */
633 static void NEVER_RETURNS usage(int status)
634 {
635         FILE *output = status?stderr:stdout;
636
637         fprintf(output, "Usage: %s [options]\n", progname);
638         fprintf(output, "Options:\n");
639         fprintf(output, "  -C            Check configuration and exit.\n");
640         fprintf(stderr, "  -d <raddb>    Set configuration directory (defaults to " RADDBDIR ").\n");
641         fprintf(stderr, "  -D <dictdir>  Set main dictionary directory (defaults to " DICTDIR ").\n");
642         fprintf(output, "  -f            Run as a foreground process, not a daemon.\n");
643         fprintf(output, "  -h            Print this help message.\n");
644         fprintf(output, "  -i <ipaddr>   Listen on ipaddr ONLY.\n");
645         fprintf(output, "  -l <log_file> Logging output will be written to this file.\n");
646         fprintf(output, "  -m            On SIGINT or SIGQUIT exit cleanly instead of immediately.\n");
647         fprintf(output, "  -n <name>     Read raddb/name.conf instead of raddb/radiusd.conf.\n");
648         fprintf(output, "  -p <port>     Listen on port ONLY.\n");
649         fprintf(output, "  -P            Always write out PID, even with -f.\n");
650         fprintf(output, "  -s            Do not spawn child processes to handle requests.\n");
651         fprintf(output, "  -t            Disable threads.\n");
652         fprintf(output, "  -v            Print server version information.\n");
653         fprintf(output, "  -X            Turn on full debugging.\n");
654         fprintf(output, "  -x            Turn on additional debugging. (-xx gives more debugging).\n");
655         exit(status);
656 }
657
658
659 /*
660  *      We got a fatal signal.
661  */
662 static void sig_fatal(int sig)
663 {
664         if (getpid() != radius_pid) _exit(sig);
665
666         switch(sig) {
667         case SIGTERM:
668                 radius_signal_self(RADIUS_SIGNAL_SELF_TERM);
669                 break;
670
671         case SIGINT:
672 #ifdef SIGQUIT
673         case SIGQUIT:
674 #endif
675                 if (mainconfig.debug_memory || mainconfig.memory_report) {
676                         radius_signal_self(RADIUS_SIGNAL_SELF_TERM);
677                         break;
678                 }
679                 /* FALL-THROUGH */
680
681         default:
682                 _exit(sig);
683         }
684 }
685
686 #ifdef SIGHUP
687 /*
688  *  We got the hangup signal.
689  *  Re-read the configuration files.
690  */
691 static void sig_hup(UNUSED int sig)
692 {
693         reset_signal(SIGHUP, sig_hup);
694
695         radius_signal_self(RADIUS_SIGNAL_SELF_HUP);
696 }
697 #endif