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