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