- Added log message when SIGCHLD is received ("thanks" to Ivo van Dong)
[oweals/tinc.git] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998,1999,2000 Ivo Timmermans <itimmermans@bigfoot.com>
4                             2000 Guus Sliepen <guus@sliepen.warande.net>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: tincd.c,v 1.10.4.3 2000/06/28 14:34:40 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h> 
27 #include <getopt.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <sys/types.h>
31 #include <syslog.h>
32 #include <unistd.h>
33
34 #ifdef HAVE_SYS_IOCTL_H
35 # include <sys/ioctl.h>
36 #endif
37
38 #include <pidfile.h>
39 #include <utils.h>
40 #include <xalloc.h>
41
42 #include "conf.h"
43 #include "encr.h"
44 #include "net.h"
45 #include "netutl.h"
46
47 #include "system.h"
48
49 /* The name this program was run with. */
50 char *program_name;
51
52 /* If nonzero, display usage information and exit. */
53 static int show_help;
54
55 /* If nonzero, print the version on standard output and exit.  */
56 static int show_version;
57
58 /* If nonzero, it will attempt to kill a running tincd and exit. */
59 static int kill_tincd = 0;
60
61 /* If zero, don't detach from the terminal. */
62 static int do_detach = 1;
63
64 char *confbase = NULL;           /* directory in which all config files are */
65 char *configfilename = NULL;     /* configuration file name */
66 char *identname;                 /* program name for syslog */
67 char *netname = NULL;            /* name of the vpn network */
68 char *pidfilename;               /* pid file location */
69 static pid_t ppid;               /* pid of non-detached part */
70 char **g_argv;                   /* a copy of the cmdline arguments */
71
72 void cleanup_and_exit(int);
73 int detach(void);
74 int kill_other(void);
75 void make_names(void);
76 RETSIGTYPE parent_exit(int a);
77 void setup_signals(void);
78 int write_pidfile(void);
79
80 static struct option const long_options[] =
81 {
82   { "kill", no_argument, NULL, 'k' },
83   { "net", required_argument, NULL, 'n' },
84   { "timeout", required_argument, NULL, 'p' },
85   { "help", no_argument, &show_help, 1 },
86   { "version", no_argument, &show_version, 1 },
87   { "no-detach", no_argument, &do_detach, 0 },
88   { NULL, 0, NULL, 0 }
89 };
90
91 static void
92 usage(int status)
93 {
94   if(status != 0)
95     fprintf(stderr, _("Try `%s --help\' for more information.\n"), program_name);
96   else
97     {
98       printf(_("Usage: %s [option]...\n\n"), program_name);
99       printf(_("  -c, --config=FILE     Read configuration options from FILE.\n"
100                "  -D, --no-detach       Don't fork and detach.\n"
101                "  -d                    Increase debug level.\n"
102                "  -k, --kill            Attempt to kill a running tincd and exit.\n"
103                "  -n, --net=NETNAME     Connect to net NETNAME.\n"
104                "  -t, --timeout=TIMEOUT Seconds to wait before giving a timeout.\n"));
105       printf(_("      --help            Display this help and exit.\n"
106                "      --version         Output version information and exit.\n\n"));
107       printf(_("Report bugs to tinc@nl.linux.org.\n"));
108     }
109   exit(status);
110 }
111
112 void
113 parse_options(int argc, char **argv, char **envp)
114 {
115   int r;
116   int option_index = 0;
117   config_t *p;
118
119   while((r = getopt_long(argc, argv, "c:Ddkn:t:", long_options, &option_index)) != EOF)
120     {
121       switch(r)
122         {
123         case 0: /* long option */
124           break;
125         case 'c': /* config file */
126           configfilename = xmalloc(strlen(optarg)+1);
127           strcpy(configfilename, optarg);
128           break;
129         case 'D': /* no detach */
130           do_detach = 0;
131           break;
132         case 'd': /* inc debug level */
133           debug_lvl++;
134           break;
135         case 'k': /* kill old tincds */
136           kill_tincd = 1;
137           break;
138         case 'n': /* net name given */
139           netname = xmalloc(strlen(optarg)+1);
140           strcpy(netname, optarg);
141           break;
142         case 't': /* timeout */
143           if(!(p = add_config_val(&config, TYPE_INT, optarg)))
144             {
145               printf(_("Invalid timeout value `%s'.\n"), optarg);
146               usage(1);
147             }
148           break;
149         case '?':
150           usage(1);
151         default:
152           break;
153         }
154     }
155 }
156
157 void memory_full(int size)
158 {
159   syslog(LOG_ERR, _("Memory exhausted (last is %s:%d) (couldn't allocate %d bytes), exiting."), cp_file, cp_line, size);
160   exit(1);
161 }
162
163 /*
164   Detach from current terminal, write pidfile, kill parent
165 */
166 int detach(void)
167 {
168   int fd;
169   pid_t pid;
170
171   if(do_detach)
172     {
173       ppid = getpid();
174
175       if((pid = fork()) < 0)
176         {
177           perror("fork");
178           return -1;
179         }
180       if(pid) /* parent process */
181         {
182           signal(SIGTERM, parent_exit);
183           sleep(600); /* wait 10 minutes */
184           exit(1);
185         }
186     }
187   
188   if(write_pidfile())
189     return -1;
190
191   if(do_detach)
192     {
193       if((fd = open("/dev/tty", O_RDWR)) >= 0)
194         {
195           if(ioctl(fd, TIOCNOTTY, NULL))
196             {
197               perror("ioctl");
198               return -1;
199             }
200           close(fd);
201         }
202
203       if(setsid() < 0)
204         return -1;
205
206       kill(ppid, SIGTERM);
207     }
208   
209   chdir("/"); /* avoid keeping a mointpoint busy */
210
211   openlog(identname, LOG_CONS | LOG_PID, LOG_DAEMON);
212
213   if(debug_lvl > 0)
214     syslog(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
215            VERSION, __DATE__, __TIME__, debug_lvl);
216   else
217     syslog(LOG_NOTICE, _("tincd %s starting"), VERSION, debug_lvl);
218
219   xalloc_fail_func = memory_full;
220
221   return 0;
222 }
223
224 /*
225   Close network connections, and terminate neatly
226 */
227 void cleanup_and_exit(int c)
228 {
229   close_network_connections();
230
231   if(debug_lvl > 0)
232     syslog(LOG_INFO, _("Total bytes written: tap %d, socket %d; bytes read: tap %d, socket %d"),
233            total_tap_out, total_socket_out, total_tap_in, total_socket_in);
234
235   closelog();
236   kill(ppid, SIGTERM);
237   exit(c);
238 }
239
240 /*
241   check for an existing tinc for this net, and write pid to pidfile
242 */
243 int write_pidfile(void)
244 {
245   int pid;
246
247   if((pid = check_pid(pidfilename)))
248     {
249       if(netname)
250         fprintf(stderr, _("A tincd is already running for net `%s' with pid %d.\n"),
251                 netname, pid);
252       else
253         fprintf(stderr, _("A tincd is already running with pid %d.\n"), pid);
254       return 1;
255     }
256
257   /* if it's locked, write-protected, or whatever */
258   if(!write_pid(pidfilename))
259     return 1;
260
261   return 0;
262 }
263
264 /*
265   kill older tincd for this net
266 */
267 int kill_other(void)
268 {
269   int pid;
270
271   if(!(pid = read_pid(pidfilename)))
272     {
273       if(netname)
274         fprintf(stderr, _("No other tincd is running for net `%s'.\n"), netname);
275       else
276         fprintf(stderr, _("No other tincd is running.\n"));
277       return 1;
278     }
279
280   errno = 0;    /* No error, sometimes errno is only changed on error */
281   /* ESRCH is returned when no process with that pid is found */
282   if(kill(pid, SIGTERM) && errno == ESRCH)
283     fprintf(stderr, _("Removing stale lock file.\n"));
284   remove_pid(pidfilename);
285
286   return 0;
287 }
288
289 /*
290   Set all files and paths according to netname
291 */
292 void make_names(void)
293 {
294   if(!configfilename)
295     {
296       if(netname)
297         {
298           configfilename = xmalloc(strlen(netname)+18+strlen(CONFDIR));
299           sprintf(configfilename, "%s/tinc/%s/tinc.conf", CONFDIR, netname);
300         }
301       else
302         {
303           configfilename = xmalloc(17+strlen(CONFDIR));
304           sprintf(configfilename, "%s/tinc/tinc.conf", CONFDIR);
305         }
306     }
307   
308   if(netname)
309     {
310       pidfilename = xmalloc(strlen(netname)+20);
311       sprintf(pidfilename, "/var/run/tinc.%s.pid", netname);
312       confbase = xmalloc(strlen(netname)+8+strlen(CONFDIR));
313       sprintf(confbase, "%s/tinc/%s/", CONFDIR, netname);
314       identname = xmalloc(strlen(netname)+7);
315       sprintf(identname, "tinc.%s", netname);
316     }
317   else
318     {
319       pidfilename = "/var/run/tinc.pid";
320       confbase = xmalloc(7+strlen(CONFDIR));
321       sprintf(confbase, "%s/tinc/", CONFDIR);
322       identname = "tinc";
323     }
324 }
325
326 int
327 main(int argc, char **argv, char **envp)
328 {
329   program_name = argv[0];
330
331   setlocale (LC_ALL, "");
332   bindtextdomain (PACKAGE, LOCALEDIR);
333   textdomain (PACKAGE);
334
335   parse_options(argc, argv, envp);
336
337   if(show_version)
338     {
339       printf(_("%s version %s\n"), PACKAGE, VERSION);
340       printf(_("Copyright (C) 1998,1999,2000 Ivo Timmermans and others,\n"
341                "see the AUTHORS file for a complete list.\n\n"
342                "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
343                "and you are welcome to redistribute it under certain conditions;\n"
344                "see the file COPYING for details.\n\n"));
345       printf(_("This product includes software developed by Eric Young (eay@mincom.oz.au)\n"));
346
347       return 0;
348     }
349
350   if(show_help)
351     usage(0);
352
353   if(geteuid())
354     {
355       fprintf(stderr, _("You must be root to run this program. Sorry.\n"));
356       return 1;
357     }
358
359   g_argv = argv;
360
361   make_names();
362
363   if(kill_tincd)
364     exit(kill_other());
365
366   if(read_config_file(configfilename))
367     return 1;
368
369   setup_signals();
370
371   if(detach())
372     exit(0);
373
374   if(security_init())
375     return 1;
376
377   if(setup_network_connections())
378     cleanup_and_exit(1);
379
380   main_loop();
381
382   cleanup_and_exit(1);
383   return 1;
384 }
385
386 RETSIGTYPE
387 sigterm_handler(int a)
388 {
389   if(debug_lvl > 0)
390     syslog(LOG_NOTICE, _("Got TERM signal"));
391   cleanup_and_exit(0);
392 }
393
394 RETSIGTYPE
395 sigquit_handler(int a)
396 {
397   if(debug_lvl > 0)
398     syslog(LOG_NOTICE, _("Got QUIT signal"));
399   cleanup_and_exit(0);
400 }
401
402 RETSIGTYPE
403 sigsegv_square(int a)
404 {
405   syslog(LOG_NOTICE, _("Got another SEGV signal: not restarting"));
406   exit(0);
407 }
408
409 RETSIGTYPE
410 sigsegv_handler(int a)
411 {
412   if(cp_file)
413     syslog(LOG_NOTICE, _("Got SEGV signal after %s line %d, trying to re-execute"),
414            cp_file, cp_line);
415   else
416     syslog(LOG_NOTICE, _("Got SEGV signal, trying to re-execute"));
417
418   signal(SIGSEGV, sigsegv_square);
419
420   close_network_connections();
421   remove_pid(pidfilename);
422   execvp(g_argv[0], g_argv);
423 }
424
425 RETSIGTYPE
426 sighup_handler(int a)
427 {
428   if(debug_lvl > 0)
429     syslog(LOG_NOTICE, _("Got HUP signal"));
430   close_network_connections();
431   setup_network_connections();
432   /* FIXME: read config-file and re-establish network connections */
433 }
434
435 RETSIGTYPE
436 sigint_handler(int a)
437 {
438   if(debug_lvl > 0)
439     syslog(LOG_NOTICE, _("Got INT signal"));
440   cleanup_and_exit(0);
441 }
442
443 RETSIGTYPE
444 sigusr1_handler(int a)
445 {
446   dump_conn_list();
447 }
448
449 RETSIGTYPE
450 sigusr2_handler(int a)
451 {
452   if(debug_lvl > 1)
453     syslog(LOG_NOTICE, _("Forcing new key generation"));
454   regenerate_keys();
455 }
456
457 RETSIGTYPE
458 sighuh(int a)
459 {
460   if(cp_file)
461     syslog(LOG_NOTICE, _("Got unexpected signal %d after %s line %d"),
462            a, cp_file, cp_line);
463   else
464     syslog(LOG_NOTICE, _("Got unexpected signal %d"), a);
465 }
466
467 void
468 setup_signals(void)
469 {
470   int i;
471
472   for(i=0;i<32;i++)
473     signal(i,sighuh);
474
475   if(signal(SIGTERM, SIG_IGN) != SIG_ERR)
476     signal(SIGTERM, sigterm_handler);
477   if(signal(SIGQUIT, SIG_IGN) != SIG_ERR)
478     signal(SIGQUIT, sigquit_handler);
479   if(signal(SIGSEGV, SIG_IGN) != SIG_ERR)
480     signal(SIGSEGV, sigsegv_handler);
481   if(signal(SIGHUP, SIG_IGN) != SIG_ERR)
482     signal(SIGHUP, sighup_handler);
483   signal(SIGPIPE, SIG_IGN);
484   if(signal(SIGINT, SIG_IGN) != SIG_ERR)
485     signal(SIGINT, sigint_handler);
486   signal(SIGUSR1, sigusr1_handler);
487   signal(SIGUSR2, sigusr2_handler);
488   signal(SIGCHLD, parent_exit);
489 }
490
491 RETSIGTYPE parent_exit(int a)
492 {
493   syslog(LOG_NOTICE, _("Got SIGCHLD: exitting immediately"));
494   exit(0);
495 }