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