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