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