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