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