Upon regeneration, free the old encryption key `securely\' by overwriting it.
[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   kill(ppid, SIGTERM);
185   
186   if(setsid() < 0)
187     return -1;
188   chdir("/"); /* avoid keeping a mointpoint busy */
189
190   openlog(identname, LOG_CONS | LOG_PID, LOG_DAEMON);
191
192   if(debug_lvl > 1)
193     syslog(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d.",
194            VERSION, __DATE__, __TIME__, debug_lvl);
195   else
196     syslog(LOG_NOTICE, "tincd %s starting, debug level %d.", VERSION, debug_lvl);
197
198   xalloc_fail_func = memory_full;
199
200   return 0;
201 }
202
203 /*
204   Close network connections, and terminate neatly
205 */
206 void cleanup_and_exit(int c)
207 {
208   close_network_connections();
209
210   if(debug_lvl > 0)
211     syslog(LOG_INFO, "Total bytes written: tap %d, socket %d; bytes read: tap %d, socket %d.",
212            total_tap_out, total_socket_out, total_tap_in, total_socket_in);
213
214   closelog();
215   kill(ppid, SIGTERM);
216   exit(c);
217 }
218
219 /*
220   check for an existing tinc for this net, and write pid to pidfile
221 */
222 int write_pidfile(void)
223 {
224   int pid;
225
226   if((pid = check_pid(pidfilename)))
227     {
228       if(netname)
229         fprintf(stderr, "A tincd is already running for net `%s' with pid %d.\n",
230                 netname, pid);
231       else
232         fprintf(stderr, "A tincd is already running with pid %d.\n", pid);
233       return 1;
234     }
235
236   /* if it's locked, write-protected, or whatever */
237   if(!write_pid(pidfilename))
238     return 1;
239
240   return 0;
241 }
242
243 /*
244   kill older tincd for this net
245 */
246 int kill_other(void)
247 {
248   int pid;
249
250   if(!(pid = read_pid(pidfilename)))
251     {
252       if(netname)
253         fprintf(stderr, "No other tincd is running for net `%s'.\n", netname);
254       else
255         fprintf(stderr, "No other tincd is running.\n");
256       return 1;
257     }
258
259   errno = 0;    /* No error, sometimes errno is only changed on error */
260   /* ESRCH is returned when no process with that pid is found */
261   if(kill(pid, SIGTERM) && errno == ESRCH)
262     fprintf(stderr, "Removing stale lock file.\n");
263   remove_pid(pidfilename);
264
265   return 0;
266 }
267
268 /*
269   Set all files and paths according to netname
270 */
271 void make_names(void)
272 {
273   if(!configfilename)
274     {
275       if(netname)
276         {
277           configfilename = xmalloc(strlen(netname)+18+strlen(CONFDIR));
278           sprintf(configfilename, "%s/tinc/%s/tincd.conf", CONFDIR, netname);
279         }
280       else
281         {
282           configfilename = xmalloc(17+strlen(CONFDIR));
283           sprintf(configfilename, "%s/tinc/tincd.conf", CONFDIR);
284         }
285     }
286   
287   if(netname)
288     {
289       pidfilename = xmalloc(strlen(netname)+20);
290       sprintf(pidfilename, "/var/run/tincd.%s.pid", netname);
291       confbase = xmalloc(strlen(netname)+8+strlen(CONFDIR));
292       sprintf(confbase, "%s/tinc/%s/", CONFDIR, netname);
293       identname = xmalloc(strlen(netname)+7);
294       sprintf(identname, "tincd.%s", netname);
295     }
296   else
297     {
298       pidfilename = "/var/run/tincd.pid";
299       confbase = xmalloc(7+strlen(CONFDIR));
300       sprintf(confbase, "%s/tinc/", CONFDIR);
301       identname = "tincd";
302     }
303 }
304
305 int
306 main(int argc, char **argv, char **envp)
307 {
308   program_name = argv[0];
309
310   parse_options(argc, argv, envp);
311
312   if(show_version)
313     {
314       printf("%s version %s\nCopyright (C) 1998,99 Ivo Timmermans and others,\n"
315              "see the AUTHORS file for a complete list.\n\n"
316              "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
317              "and you are welcome to redistribute it under certain conditions;\n"
318              "see the file COPYING for details.\n\n", PACKAGE, VERSION);
319       printf("This product includes software developed by Eric Young (eay@mincom.oz.au)\n");
320
321       return 0;
322     }
323
324   if(show_help)
325     usage(0);
326
327   if(geteuid())
328     {
329       fprintf(stderr, "You must be root to run this program. sorry.\n");
330       return 1;
331     }
332
333   g_argv = argv;
334
335   make_names();
336
337   if(kill_tincd)
338     exit(kill_other());
339
340   if(read_config_file(configfilename))
341     return 1;
342
343   setup_signals();
344
345   if(detach())
346     cleanup_and_exit(1);
347
348   if(security_init())
349     return 1;
350
351   if(setup_network_connections())
352     cleanup_and_exit(1);
353
354   main_loop();
355
356   cleanup_and_exit(1);
357   return 1;
358 }
359
360 RETSIGTYPE
361 sigterm_handler(int a)
362 {
363   if(debug_lvl > 0)
364     syslog(LOG_NOTICE, "Got TERM signal");
365   cleanup_and_exit(0);
366 }
367
368 RETSIGTYPE
369 sigquit_handler(int a)
370 {
371   if(debug_lvl > 0)
372     syslog(LOG_NOTICE, "Got QUIT signal");
373   cleanup_and_exit(0);
374 }
375
376 RETSIGTYPE
377 sigsegv_square(int a)
378 {
379   syslog(LOG_NOTICE, "Got another SEGV signal: not restarting");
380   exit(0);
381 }
382
383 RETSIGTYPE
384 sigsegv_handler(int a)
385 {
386   if(cp_file)
387     syslog(LOG_NOTICE, "Got SEGV signal after %s line %d. Trying to re-execute.",
388            cp_file, cp_line);
389   else
390     syslog(LOG_NOTICE, "Got SEGV signal; trying to re-execute.");
391
392   signal(SIGSEGV, sigsegv_square);
393
394   close_network_connections();
395   remove_pid(pidfilename);
396   execvp(g_argv[0], g_argv);
397 }
398
399 RETSIGTYPE
400 sighup_handler(int a)
401 {
402   if(debug_lvl > 0)
403     syslog(LOG_NOTICE, "Got HUP signal");
404   close_network_connections();
405   setup_network_connections();
406   /* FIXME: read config-file and re-establish network connections */
407 }
408
409 RETSIGTYPE
410 sigint_handler(int a)
411 {
412   if(debug_lvl > 0)
413     syslog(LOG_NOTICE, "Got INT signal");
414   cleanup_and_exit(0);
415 }
416
417 RETSIGTYPE
418 sigusr1_handler(int a)
419 {
420   dump_conn_list();
421 }
422
423 RETSIGTYPE
424 sigusr2_handler(int a)
425 {
426   if(debug_lvl > 1)
427     syslog(LOG_NOTICE, "Forcing new keys");
428   regenerate_keys();
429 }
430
431 RETSIGTYPE
432 sighuh(int a)
433 {
434   if(cp_file)
435     syslog(LOG_NOTICE, "Got unexpected signal after %s line %d.",
436            cp_file, cp_line);
437   else
438     syslog(LOG_NOTICE, "Got unexpected signal.");
439 }
440
441 void
442 setup_signals(void)
443 {
444   int i;
445
446   for(i=0;i<32;i++)
447     signal(i,sighuh);
448
449   if(signal(SIGTERM, SIG_IGN) != SIG_ERR)
450     signal(SIGTERM, sigterm_handler);
451   if(signal(SIGQUIT, SIG_IGN) != SIG_ERR)
452     signal(SIGQUIT, sigquit_handler);
453   if(signal(SIGSEGV, SIG_IGN) != SIG_ERR)
454     signal(SIGSEGV, sigsegv_handler);
455   if(signal(SIGHUP, SIG_IGN) != SIG_ERR)
456     signal(SIGHUP, sighup_handler);
457   signal(SIGPIPE, SIG_IGN);
458   if(signal(SIGINT, SIG_IGN) != SIG_ERR)
459     signal(SIGINT, sigint_handler);
460   signal(SIGUSR1, sigusr1_handler);
461   signal(SIGUSR2, sigusr2_handler);
462 }
463
464 RETSIGTYPE parent_exit(int a)
465 {
466   exit(0);
467 }
468