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