a8ea62c682354d510fd5ec08706cadb2cb88de9d
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998,99 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.5  2000/04/17 16:23:29  zarq
23  * Pass the requested size from xmalloc() and xrealloc() on to xalloc_fail_func()
24  *
25  * Revision 1.4  2000/04/06 18:28:29  zarq
26  * New option -D, don't detach.
27  *
28  */
29
30 #include "config.h"
31
32 #include <errno.h>
33 #include <fcntl.h> 
34 #include <getopt.h>
35 #include <signal.h>
36 #include <stdio.h>
37 #include <sys/types.h>
38 #include <syslog.h>
39 #include <unistd.h>
40
41 #ifdef HAVE_SYS_IOCTL_H
42 # include <sys/ioctl.h>
43 #endif
44
45 #include <pidfile.h>
46 #include <utils.h>
47 #include <xalloc.h>
48
49 #include "conf.h"
50 #include "encr.h"
51 #include "net.h"
52 #include "netutl.h"
53
54 /* The name this program was run with. */
55 char *program_name;
56
57 /* If nonzero, display usage information and exit. */
58 static int show_help;
59
60 /* If nonzero, print the version on standard output and exit.  */
61 static int show_version;
62
63 /* If nonzero, it will attempt to kill a running tincd and exit. */
64 static int kill_tincd = 0;
65
66 /* If zero, don't detach from the terminal. */
67 static int do_detach = 1;
68
69 char *confbase = NULL;           /* directory in which all config files are */
70 char *configfilename = NULL;     /* configuration file name */
71 char *identname;                 /* program name for syslog */
72 char *netname = NULL;            /* name of the vpn network */
73 char *pidfilename;               /* pid file location */
74 static pid_t ppid;               /* pid of non-detached part */
75 char **g_argv;                   /* a copy of the cmdline arguments */
76
77 void cleanup_and_exit(int);
78 int detach(void);
79 int kill_other(void);
80 void make_names(void);
81 RETSIGTYPE parent_exit(int a);
82 void setup_signals(void);
83 int write_pidfile(void);
84
85 static struct option const long_options[] =
86 {
87   { "kill", no_argument, NULL, 'k' },
88   { "net", required_argument, NULL, 'n' },
89   { "timeout", required_argument, NULL, 'p' },
90   { "help", no_argument, &show_help, 1 },
91   { "version", no_argument, &show_version, 1 },
92   { "no-detach", no_argument, &do_detach, 0 },
93   { NULL, 0, NULL, 0 }
94 };
95
96 static void
97 usage(int status)
98 {
99   if(status != 0)
100     fprintf(stderr, "Try `%s --help\' for more information.\n", program_name);
101   else
102     {
103       printf("Usage: %s [option]...\n\n", program_name);
104       printf("  -c, --config=FILE     Read configuration options from FILE.\n"
105              "  -D, --no-detach       Don't fork and detach.\n"
106              "  -d                    Increase debug level.\n"
107              "  -k, --kill            Attempt to kill a running tincd and exit.\n"
108              "  -n, --net=NETNAME     Connect to net NETNAME.\n"
109              "  -t, --timeout=TIMEOUT Seconds to wait before giving a timeout.\n");
110       printf("      --help            Display this help and exit.\n"
111              "      --version         Output version information and exit.\n\n");
112       printf("Report bugs to zarq@iname.com.\n");
113     }
114   exit(status);
115 }
116
117 void
118 parse_options(int argc, char **argv, char **envp)
119 {
120   int r;
121   int option_index = 0;
122   config_t *p;
123
124   while((r = getopt_long(argc, argv, "c:Ddkn:t:", long_options, &option_index)) != EOF)
125     {
126       switch(r)
127         {
128         case 0: /* long option */
129           break;
130         case 'c': /* config file */
131           configfilename = xmalloc(strlen(optarg)+1);
132           strcpy(configfilename, optarg);
133           break;
134         case 'D': /* no detach */
135           do_detach = 0;
136           break;
137         case 'd': /* inc debug level */
138           debug_lvl++;
139           break;
140         case 'k': /* kill old tincds */
141           kill_tincd = 1;
142           break;
143         case 'n': /* net name given */
144           netname = xmalloc(strlen(optarg)+1);
145           strcpy(netname, optarg);
146           break;
147         case 't': /* timeout */
148           if(!(p = add_config_val(&config, TYPE_INT, optarg)))
149             {
150               printf("Invalid timeout value `%s'.\n", optarg);
151               usage(1);
152             }
153           break;
154         case '?':
155           usage(1);
156         default:
157           break;
158         }
159     }
160 }
161
162 void memory_full(int size)
163 {
164   syslog(LOG_ERR, "Memory exhausted (last is %s:%d) (couldn't allocate %d bytes); exiting.", cp_file, cp_line, size);
165   exit(1);
166 }
167
168 /*
169   Detach from current terminal, write pidfile, kill parent
170 */
171 int detach(void)
172 {
173   int fd;
174   pid_t pid;
175
176   if(do_detach)
177     {
178       ppid = getpid();
179
180       if((pid = fork()) < 0)
181         {
182           perror("fork");
183           return -1;
184         }
185       if(pid) /* parent process */
186         {
187           signal(SIGTERM, parent_exit);
188           sleep(600); /* wait 10 minutes */
189           exit(1);
190         }
191     }
192   
193   if(write_pidfile())
194     return -1;
195
196   if(do_detach)
197     {
198       if((fd = open("/dev/tty", O_RDWR)) >= 0)
199         {
200           if(ioctl(fd, TIOCNOTTY, NULL))
201             {
202               perror("ioctl");
203               return -1;
204             }
205           close(fd);
206         }
207
208       if(setsid() < 0)
209         return -1;
210
211       kill(ppid, SIGTERM);
212     }
213   
214   chdir("/"); /* avoid keeping a mointpoint busy */
215
216   openlog(identname, LOG_CONS | LOG_PID, LOG_DAEMON);
217
218   if(debug_lvl > 1)
219     syslog(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d.",
220            VERSION, __DATE__, __TIME__, debug_lvl);
221   else
222     syslog(LOG_NOTICE, "tincd %s starting, debug level %d.", VERSION, debug_lvl);
223
224   xalloc_fail_func = memory_full;
225
226   return 0;
227 }
228
229 /*
230   Close network connections, and terminate neatly
231 */
232 void cleanup_and_exit(int c)
233 {
234   close_network_connections();
235
236   if(debug_lvl > 0)
237     syslog(LOG_INFO, "Total bytes written: tap %d, socket %d; bytes read: tap %d, socket %d.",
238            total_tap_out, total_socket_out, total_tap_in, total_socket_in);
239
240   closelog();
241   kill(ppid, SIGTERM);
242   exit(c);
243 }
244
245 /*
246   check for an existing tinc for this net, and write pid to pidfile
247 */
248 int write_pidfile(void)
249 {
250   int pid;
251
252   if((pid = check_pid(pidfilename)))
253     {
254       if(netname)
255         fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n",
256                 netname, pid);
257       else
258         fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
259       return 1;
260     }
261
262   /* if it's locked, write-protected, or whatever */
263   if(!write_pid(pidfilename))
264     return 1;
265
266   return 0;
267 }
268
269 /*
270   kill older tincd for this net
271 */
272 int kill_other(void)
273 {
274   int pid;
275
276   if(!(pid = read_pid(pidfilename)))
277     {
278       if(netname)
279         fprintf(stderr, "No other tincd is running for net `%s'.\n", netname);
280       else
281         fprintf(stderr, "No other tincd is running.\n");
282       return 1;
283     }
284
285   errno = 0;    /* No error, sometimes errno is only changed on error */
286   /* ESRCH is returned when no process with that pid is found */
287   if(kill(pid, SIGTERM) && errno == ESRCH)
288     fprintf(stderr, "Removing stale lock file.\n");
289   remove_pid(pidfilename);
290
291   return 0;
292 }
293
294 /*
295   Set all files and paths according to netname
296 */
297 void make_names(void)
298 {
299   if(!configfilename)
300     {
301       if(netname)
302         {
303           configfilename = xmalloc(strlen(netname)+18+strlen(CONFDIR));
304           sprintf(configfilename, "%s/tinc/%s/tincd.conf", CONFDIR, netname);
305         }
306       else
307         {
308           configfilename = xmalloc(17+strlen(CONFDIR));
309           sprintf(configfilename, "%s/tinc/tincd.conf", CONFDIR);
310         }
311     }
312   
313   if(netname)
314     {
315       pidfilename = xmalloc(strlen(netname)+20);
316       sprintf(pidfilename, "/var/run/tincd.%s.pid", netname);
317       confbase = xmalloc(strlen(netname)+8+strlen(CONFDIR));
318       sprintf(confbase, "%s/tinc/%s/", CONFDIR, netname);
319       identname = xmalloc(strlen(netname)+7);
320       sprintf(identname, "tincd.%s", netname);
321     }
322   else
323     {
324       pidfilename = "/var/run/tincd.pid";
325       confbase = xmalloc(7+strlen(CONFDIR));
326       sprintf(confbase, "%s/tinc/", CONFDIR);
327       identname = "tincd";
328     }
329 }
330
331 int
332 main(int argc, char **argv, char **envp)
333 {
334   program_name = argv[0];
335
336   parse_options(argc, argv, envp);
337
338   if(show_version)
339     {
340       printf("%s version %s\nCopyright (C) 1998,99 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", PACKAGE, VERSION);
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 keys");
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   exit(0);
494 }
495