New option -D, don't 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 /*
21  * $Log: tincd.c,v $
22  * Revision 1.4  2000/04/06 18:28:29  zarq
23  * New option -D, don't detach.
24  *
25  */
26
27 #include "config.h"
28
29 #include <errno.h>
30 #include <fcntl.h> 
31 #include <getopt.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <sys/types.h>
35 #include <syslog.h>
36 #include <unistd.h>
37
38 #ifdef HAVE_SYS_IOCTL_H
39 # include <sys/ioctl.h>
40 #endif
41
42 #include <pidfile.h>
43 #include <utils.h>
44 #include <xalloc.h>
45
46 #include "conf.h"
47 #include "encr.h"
48 #include "net.h"
49 #include "netutl.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 */
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 zarq@iname.com.\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(void)
160 {
161   syslog(LOG_ERR, "Memory exhausted; exiting.");
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 > 1)
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, debug level %d.", 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           configfilename = xmalloc(strlen(netname)+18+strlen(CONFDIR));
301           sprintf(configfilename, "%s/tinc/%s/tincd.conf", CONFDIR, netname);
302         }
303       else
304         {
305           configfilename = xmalloc(17+strlen(CONFDIR));
306           sprintf(configfilename, "%s/tinc/tincd.conf", CONFDIR);
307         }
308     }
309   
310   if(netname)
311     {
312       pidfilename = xmalloc(strlen(netname)+20);
313       sprintf(pidfilename, "/var/run/tincd.%s.pid", netname);
314       confbase = xmalloc(strlen(netname)+8+strlen(CONFDIR));
315       sprintf(confbase, "%s/tinc/%s/", CONFDIR, netname);
316       identname = xmalloc(strlen(netname)+7);
317       sprintf(identname, "tincd.%s", netname);
318     }
319   else
320     {
321       pidfilename = "/var/run/tincd.pid";
322       confbase = xmalloc(7+strlen(CONFDIR));
323       sprintf(confbase, "%s/tinc/", CONFDIR);
324       identname = "tincd";
325     }
326 }
327
328 int
329 main(int argc, char **argv, char **envp)
330 {
331   program_name = argv[0];
332
333   parse_options(argc, argv, envp);
334
335   if(show_version)
336     {
337       printf("%s version %s\nCopyright (C) 1998,99 Ivo Timmermans and others,\n"
338              "see the AUTHORS file for a complete list.\n\n"
339              "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
340              "and you are welcome to redistribute it under certain conditions;\n"
341              "see the file COPYING for details.\n\n", PACKAGE, VERSION);
342       printf("This product includes software developed by Eric Young (eay@mincom.oz.au)\n");
343
344       return 0;
345     }
346
347   if(show_help)
348     usage(0);
349
350   if(geteuid())
351     {
352       fprintf(stderr, "You must be root to run this program. sorry.\n");
353       return 1;
354     }
355
356   g_argv = argv;
357
358   make_names();
359
360   if(kill_tincd)
361     exit(kill_other());
362
363   if(read_config_file(configfilename))
364     return 1;
365
366   setup_signals();
367
368   if(detach())
369     exit(0);
370
371   if(security_init())
372     return 1;
373
374   if(setup_network_connections())
375     cleanup_and_exit(1);
376
377   main_loop();
378
379   cleanup_and_exit(1);
380   return 1;
381 }
382
383 RETSIGTYPE
384 sigterm_handler(int a)
385 {
386   if(debug_lvl > 0)
387     syslog(LOG_NOTICE, "Got TERM signal");
388   cleanup_and_exit(0);
389 }
390
391 RETSIGTYPE
392 sigquit_handler(int a)
393 {
394   if(debug_lvl > 0)
395     syslog(LOG_NOTICE, "Got QUIT signal");
396   cleanup_and_exit(0);
397 }
398
399 RETSIGTYPE
400 sigsegv_square(int a)
401 {
402   syslog(LOG_NOTICE, "Got another SEGV signal: not restarting");
403   exit(0);
404 }
405
406 RETSIGTYPE
407 sigsegv_handler(int a)
408 {
409   if(cp_file)
410     syslog(LOG_NOTICE, "Got SEGV signal after %s line %d. Trying to re-execute.",
411            cp_file, cp_line);
412   else
413     syslog(LOG_NOTICE, "Got SEGV signal; trying to re-execute.");
414
415   signal(SIGSEGV, sigsegv_square);
416
417   close_network_connections();
418   remove_pid(pidfilename);
419   execvp(g_argv[0], g_argv);
420 }
421
422 RETSIGTYPE
423 sighup_handler(int a)
424 {
425   if(debug_lvl > 0)
426     syslog(LOG_NOTICE, "Got HUP signal");
427   close_network_connections();
428   setup_network_connections();
429   /* FIXME: read config-file and re-establish network connections */
430 }
431
432 RETSIGTYPE
433 sigint_handler(int a)
434 {
435   if(debug_lvl > 0)
436     syslog(LOG_NOTICE, "Got INT signal");
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, "Forcing new keys");
451   regenerate_keys();
452 }
453
454 RETSIGTYPE
455 sighuh(int a)
456 {
457   if(cp_file)
458     syslog(LOG_NOTICE, "Got unexpected signal (%d) after %s line %d.",
459            a, cp_file, cp_line);
460   else
461     syslog(LOG_NOTICE, "Got unexpected signal (%d).", 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 }
492