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