- Finishing touch: encrypt the meta connections
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998,1999,2000 Ivo Timmermans <itimmermans@bigfoot.com>
4                             2000 Guus Sliepen <guus@sliepen.warande.net>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: tincd.c,v 1.10.4.21 2000/10/29 22:55:15 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h> 
27 #include <getopt.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <sys/types.h>
31 #include <syslog.h>
32 #include <unistd.h>
33 #include <signal.h>
34 #include <openssl/rand.h>
35 #include <openssl/rsa.h>
36 #include <openssl/err.h>
37 #include <string.h>
38
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
41 #endif
42
43 #include <pidfile.h>
44 #include <utils.h>
45 #include <xalloc.h>
46
47 #include "conf.h"
48 #include "net.h"
49 #include "netutl.h"
50 #include "protocol.h"
51 #include "subnet.h"
52
53 #include "system.h"
54
55 /* The name this program was run with. */
56 char *program_name;
57
58 /* If nonzero, display usage information and exit. */
59 static int show_help;
60
61 /* If nonzero, print the version on standard output and exit.  */
62 static int show_version;
63
64 /* If nonzero, it will attempt to kill a running tincd and exit. */
65 static int kill_tincd = 0;
66
67 /* If zero, don't detach from the terminal. */
68 static int do_detach = 1;
69
70 /* If nonzero, generate public/private keypair for this host/net. */
71 static int generate_keys = 0;
72
73 char *identname;                 /* program name for syslog */
74 char *pidfilename;               /* pid file location */
75 static pid_t ppid;               /* pid of non-detached part */
76 char **g_argv;                   /* a copy of the cmdline arguments */
77
78 void cleanup_and_exit(int);
79 int detach(void);
80 int kill_other(void);
81 void make_names(void);
82 RETSIGTYPE parent_exit(int a);
83 void setup_signals(void);
84 int write_pidfile(void);
85
86 static struct option const long_options[] =
87 {
88   { "kill", no_argument, NULL, 'k' },
89   { "net", required_argument, NULL, 'n' },
90   { "help", no_argument, &show_help, 1 },
91   { "version", no_argument, &show_version, 1 },
92   { "no-detach", no_argument, &do_detach, 0 },
93   { "keygen", optional_argument, NULL, 'K'},
94   { NULL, 0, NULL, 0 }
95 };
96
97 static void
98 usage(int status)
99 {
100   if(status != 0)
101     fprintf(stderr, _("Try `%s --help\' for more information.\n"), program_name);
102   else
103     {
104       printf(_("Usage: %s [option]...\n\n"), program_name);
105       printf(_("  -c, --config=DIR      Read configuration options from DIR.\n"
106                "  -D, --no-detach       Don't fork and detach.\n"
107                "  -d                    Increase debug level.\n"
108                "  -k, --kill            Attempt to kill a running tincd and exit.\n"
109                "  -n, --net=NETNAME     Connect to net NETNAME.\n"));
110       printf(_("  -K, --keygen[=BITS]   Generate public/private RSA keypair.\n"
111                "      --help            Display this help and exit.\n"
112                "      --version         Output version information and exit.\n\n"));
113       printf(_("Report bugs to tinc@nl.linux.org.\n"));
114     }
115   exit(status);
116 }
117
118 void
119 parse_options(int argc, char **argv, char **envp)
120 {
121   int r;
122   int option_index = 0;
123   
124   while((r = getopt_long(argc, argv, "c:Ddkn:K::", long_options, &option_index)) != EOF)
125     {
126       switch(r)
127         {
128         case 0: /* long option */
129           break;
130         case 'c': /* config file */
131           confbase = xmalloc(strlen(optarg)+1);
132           strcpy(confbase, optarg);
133           break;
134         case 'D': /* no detach */
135           do_detach = 0;
136           break;
137         case 'd': /* inc debug level */
138           debug_lvl++;
139           break;
140         case 'k': /* kill old tincds */
141           kill_tincd = 1;
142           break;
143         case 'n': /* net name given */
144           netname = xmalloc(strlen(optarg)+1);
145           strcpy(netname, optarg);
146           break;
147         case 'K': /* generate public/private keypair */
148           if(optarg)
149             {
150               generate_keys = atoi(optarg);
151               if(generate_keys < 512)
152                 {
153                   fprintf(stderr, _("Invalid argument! BITS must be a number equal to or greater than 512.\n"));
154                   usage(1);
155                 }
156               generate_keys &= ~7;      /* Round it to bytes */
157             }
158           else
159             generate_keys = 1024;
160           break;
161         case '?':
162           usage(1);
163         default:
164           break;
165         }
166     }
167 }
168
169 /* This function prettyprints the key generation process */
170
171 void indicator(int a, int b, void *p)
172 {
173   switch(a)
174   {
175     case 0:
176       fprintf(stderr, ".");
177       break;
178     case 1:
179       fprintf(stderr, "+");
180       break;
181     case 2:
182       fprintf(stderr, "-");
183       break;
184     case 3:
185       switch(b)
186         {
187           case 0:
188             fprintf(stderr, " p\n");      
189             break;
190           case 1:
191             fprintf(stderr, " q\n");
192             break;
193           default:
194             fprintf(stderr, "?");
195          }
196        break;
197     default:
198       fprintf(stderr, "?");
199   }
200 }
201
202 /* Generate a public/private RSA keypair, and possibly store it into the configuration file. */
203
204 int keygen(int bits)
205 {
206   RSA *rsa_key;
207
208   fprintf(stderr, _("Generating %d bits keys:\n"), bits);
209   rsa_key = RSA_generate_key(bits, 0xFFFF, indicator, NULL);
210   if(!rsa_key)
211     {
212       fprintf(stderr, _("Error during key generation!"));
213       return -1;
214      }
215   else
216     fprintf(stderr, _("Done.\n"));
217
218   fprintf(stderr, _("Please copy the private key to tinc.conf and the\npublic key to your host configuration file:\n\n"));
219   printf("PublicKey = %s\n", BN_bn2hex(rsa_key->n));
220   printf("PrivateKey = %s\n", BN_bn2hex(rsa_key->d));
221   
222   fflush(stdin);
223   return 0;
224 }
225
226 void memory_full(int size)
227 {
228   syslog(LOG_ERR, _("Memory exhausted (last is %s:%d) (couldn't allocate %d bytes), exiting."), cp_file, cp_line, size);
229   exit(1);
230 }
231
232 /*
233   Detach from current terminal, write pidfile, kill parent
234 */
235 int detach(void)
236 {
237   int fd;
238   pid_t pid;
239
240   if(do_detach)
241     {
242       ppid = getpid();
243
244       if((pid = fork()) < 0)
245         {
246           perror("fork");
247           return -1;
248         }
249       if(pid) /* parent process */
250         {
251           signal(SIGTERM, parent_exit);
252           sleep(600); /* wait 10 minutes */
253           exit(1);
254         }
255     }
256   
257   if(write_pidfile())
258     return -1;
259
260   if(do_detach)
261     {
262       if((fd = open("/dev/tty", O_RDWR)) >= 0)
263         {
264           if(ioctl(fd, TIOCNOTTY, NULL))
265             {
266               perror("ioctl");
267               return -1;
268             }
269           close(fd);
270         }
271
272       if(setsid() < 0)
273         return -1;
274
275       kill(ppid, SIGTERM);
276     }
277   
278   chdir("/"); /* avoid keeping a mointpoint busy */
279
280   openlog(identname, LOG_CONS | LOG_PID, LOG_DAEMON);
281
282   if(debug_lvl > DEBUG_NOTHING)
283     syslog(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
284            VERSION, __DATE__, __TIME__, debug_lvl);
285   else
286     syslog(LOG_NOTICE, _("tincd %s starting"), VERSION);
287
288   xalloc_fail_func = memory_full;
289
290   return 0;
291 }
292
293 /*
294   Close network connections, and terminate neatly
295 */
296 void cleanup_and_exit(int c)
297 {
298   close_network_connections();
299
300   if(debug_lvl > DEBUG_NOTHING)
301     syslog(LOG_INFO, _("Total bytes written: tap %d, socket %d; bytes read: tap %d, socket %d"),
302            total_tap_out, total_socket_out, total_tap_in, total_socket_in);
303
304   closelog();
305   kill(ppid, SIGTERM);
306   exit(c);
307 }
308
309 /*
310   check for an existing tinc for this net, and write pid to pidfile
311 */
312 int write_pidfile(void)
313 {
314   int pid;
315
316   if((pid = check_pid(pidfilename)))
317     {
318       if(netname)
319         fprintf(stderr, _("A tincd is already running for net `%s' with pid %d.\n"),
320                 netname, pid);
321       else
322         fprintf(stderr, _("A tincd is already running with pid %d.\n"), pid);
323       return 1;
324     }
325
326   /* if it's locked, write-protected, or whatever */
327   if(!write_pid(pidfilename))
328     return 1;
329
330   return 0;
331 }
332
333 /*
334   kill older tincd for this net
335 */
336 int kill_other(void)
337 {
338   int pid;
339
340   if(!(pid = read_pid(pidfilename)))
341     {
342       if(netname)
343         fprintf(stderr, _("No other tincd is running for net `%s'.\n"), netname);
344       else
345         fprintf(stderr, _("No other tincd is running.\n"));
346       return 1;
347     }
348
349   errno = 0;    /* No error, sometimes errno is only changed on error */
350   /* ESRCH is returned when no process with that pid is found */
351   if(kill(pid, SIGTERM) && errno == ESRCH)
352     fprintf(stderr, _("Removing stale lock file.\n"));
353   remove_pid(pidfilename);
354
355   return 0;
356 }
357
358 /*
359   Set all files and paths according to netname
360 */
361 void make_names(void)
362 {
363   if(netname)
364     {
365       if(!pidfilename)
366         asprintf(&pidfilename, "/var/run/tinc.%s.pid", netname);
367       if(!confbase)
368         asprintf(&confbase, "%s/tinc/%s", CONFDIR, netname);
369       if(!identname)
370         asprintf(&identname, "tinc.%s", netname);
371     }
372   else
373     {
374       if(!pidfilename)
375         pidfilename = "/var/run/tinc.pid";
376       if(!confbase)
377         asprintf(&confbase, "%s/tinc", CONFDIR);
378       if(!identname)
379         identname = "tinc";
380     }
381 }
382
383 int
384 main(int argc, char **argv, char **envp)
385 {
386   program_name = argv[0];
387
388   setlocale (LC_ALL, "");
389   bindtextdomain (PACKAGE, LOCALEDIR);
390   textdomain (PACKAGE);
391
392   /* Do some intl stuff right now */
393   
394   unknown = _("unknown");
395
396   parse_options(argc, argv, envp);
397
398   if(show_version)
399     {
400       printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE, VERSION, __DATE__, __TIME__, PROT_CURRENT);
401       printf(_("Copyright (C) 1998,1999,2000 Ivo Timmermans, Guus Sliepen and others.\n"
402                "See the AUTHORS file for a complete list.\n\n"
403                "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
404                "and you are welcome to redistribute it under certain conditions;\n"
405                "see the file COPYING for details.\n"));
406
407       return 0;
408     }
409
410   if(show_help)
411     usage(0);
412
413   if(geteuid())
414     {
415       fprintf(stderr, _("You must be root to run this program. Sorry.\n"));
416       return 1;
417     }
418
419   g_argv = argv;
420
421   make_names();
422
423   /* Slllluuuuuuurrrrp! */
424
425   RAND_load_file("/dev/urandom", 1024);
426
427   if(generate_keys)
428     exit(keygen(generate_keys));
429
430   if(kill_tincd)
431     exit(kill_other());
432
433   if(read_server_config())
434     return 1;
435
436   setup_signals();
437
438   if(detach())
439     exit(0);
440
441   if(debug_lvl >= DEBUG_ERROR)
442     ERR_load_crypto_strings();
443     
444   for(;;)
445     {
446       if(!setup_network_connections())
447         {
448           main_loop();
449           cleanup_and_exit(1);
450         }
451       
452       syslog(LOG_ERR, _("Unrecoverable error"));
453       cp_trace();
454
455       if(do_detach)
456         {
457           syslog(LOG_NOTICE, _("Restarting in %d seconds!"), MAXTIMEOUT);
458           sleep(MAXTIMEOUT);
459         }
460       else
461         {
462           syslog(LOG_ERR, _("Not restarting."));
463           exit(0);
464         }
465     }
466 }
467
468 RETSIGTYPE
469 sigterm_handler(int a)
470 {
471   if(debug_lvl > DEBUG_NOTHING)
472     syslog(LOG_NOTICE, _("Got TERM signal"));
473
474   cleanup_and_exit(0);
475 }
476
477 RETSIGTYPE
478 sigquit_handler(int a)
479 {
480   if(debug_lvl > DEBUG_NOTHING)
481     syslog(LOG_NOTICE, _("Got QUIT signal"));
482   cleanup_and_exit(0);
483 }
484
485 RETSIGTYPE
486 sigsegv_square(int a)
487 {
488   syslog(LOG_ERR, _("Got another SEGV signal: not restarting"));
489   exit(0);
490 }
491
492 RETSIGTYPE
493 sigsegv_handler(int a)
494 {
495   syslog(LOG_ERR, _("Got SEGV signal"));
496   cp_trace();
497
498   if(do_detach)
499     {
500       syslog(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
501       signal(SIGSEGV, sigsegv_square);
502       close_network_connections();
503       sleep(5);
504       remove_pid(pidfilename);
505       execvp(g_argv[0], g_argv);
506     }
507   else
508     {
509       syslog(LOG_NOTICE, _("Not restarting."));
510       exit(0);
511     }
512 }
513
514 RETSIGTYPE
515 sighup_handler(int a)
516 {
517   if(debug_lvl > DEBUG_NOTHING)
518     syslog(LOG_NOTICE, _("Got HUP signal"));
519   sighup = 1;
520 }
521
522 RETSIGTYPE
523 sigint_handler(int a)
524 {
525   if(debug_lvl > DEBUG_NOTHING)
526     syslog(LOG_NOTICE, _("Got INT signal, exiting"));
527   cleanup_and_exit(0);
528 }
529
530 RETSIGTYPE
531 sigusr1_handler(int a)
532 {
533   dump_conn_list();
534 }
535
536 RETSIGTYPE
537 sigusr2_handler(int a)
538 {
539   dump_subnet_list();
540 /* FIXME: reprogram this.
541   if(debug_lvl > DEBUG_NOTHING)
542    syslog(LOG_NOTICE, _("Got USR2 signal, forcing new key generation"));
543   regenerate_keys();
544 */
545 }
546
547 RETSIGTYPE
548 sighuh(int a)
549 {
550   syslog(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
551   cp_trace();
552 }
553
554 void
555 setup_signals(void)
556 {
557   int i;
558
559   for(i=0;i<32;i++)
560     signal(i,sighuh);
561
562   if(signal(SIGTERM, SIG_IGN) != SIG_ERR)
563     signal(SIGTERM, sigterm_handler);
564   if(signal(SIGQUIT, SIG_IGN) != SIG_ERR)
565     signal(SIGQUIT, sigquit_handler);
566   if(signal(SIGSEGV, SIG_IGN) != SIG_ERR)
567     signal(SIGSEGV, sigsegv_handler);
568   if(signal(SIGHUP, SIG_IGN) != SIG_ERR)
569     signal(SIGHUP, sighup_handler);
570   signal(SIGPIPE, SIG_IGN);
571   if(signal(SIGINT, SIG_IGN) != SIG_ERR)
572     signal(SIGINT, sigint_handler);
573   signal(SIGUSR1, sigusr1_handler);
574   signal(SIGUSR2, sigusr2_handler);
575   signal(SIGCHLD, SIG_IGN);
576 }
577
578 RETSIGTYPE parent_exit(int a)
579 {
580   exit(0);
581 }