eea15dbddf5d44ffd39e29e91bd2980b63c832ca
[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.26 2000/11/08 00:20:06 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 (last is %s:%d) (couldn't allocate %d bytes), exiting."), cp_file, cp_line, size);
233   exit(1);
234 }
235
236 /*
237   Detach from current terminal, write pidfile, kill parent
238 */
239 int detach(void)
240 {
241   int fd;
242   pid_t pid;
243
244   if(do_detach)
245     {
246       ppid = getpid();
247
248       if((pid = fork()) < 0)
249         {
250           perror("fork");
251           return -1;
252         }
253       if(pid) /* parent process */
254         {
255           signal(SIGTERM, parent_exit);
256           sleep(600); /* wait 10 minutes */
257           exit(1);
258         }
259     }
260   
261   if(write_pidfile())
262     return -1;
263
264   if(do_detach)
265     {
266       if((fd = open("/dev/tty", O_RDWR)) >= 0)
267         {
268           if(ioctl(fd, TIOCNOTTY, NULL))
269             {
270               perror("ioctl");
271               return -1;
272             }
273           close(fd);
274         }
275
276       if(setsid() < 0)
277         return -1;
278
279       kill(ppid, SIGTERM);
280     }
281   
282   chdir("/"); /* avoid keeping a mointpoint busy */
283
284   openlog(identname, LOG_CONS | LOG_PID, LOG_DAEMON);
285
286   if(debug_lvl > DEBUG_NOTHING)
287     syslog(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
288            VERSION, __DATE__, __TIME__, debug_lvl);
289   else
290     syslog(LOG_NOTICE, _("tincd %s starting"), VERSION);
291
292   xalloc_fail_func = memory_full;
293
294   return 0;
295 }
296
297 /*
298   Close network connections, and terminate neatly
299 */
300 void cleanup_and_exit(int c)
301 {
302   close_network_connections();
303
304   if(debug_lvl > DEBUG_NOTHING)
305     syslog(LOG_INFO, _("Total bytes written: tap %d, socket %d; bytes read: tap %d, socket %d"),
306            total_tap_out, total_socket_out, total_tap_in, total_socket_in);
307
308   closelog();
309   kill(ppid, SIGTERM);
310   exit(c);
311 }
312
313 /*
314   check for an existing tinc for this net, and write pid to pidfile
315 */
316 int write_pidfile(void)
317 {
318   int pid;
319
320   if((pid = check_pid(pidfilename)))
321     {
322       if(netname)
323         fprintf(stderr, _("A tincd is already running for net `%s' with pid %d.\n"),
324                 netname, pid);
325       else
326         fprintf(stderr, _("A tincd is already running with pid %d.\n"), pid);
327       return 1;
328     }
329
330   /* if it's locked, write-protected, or whatever */
331   if(!write_pid(pidfilename))
332     return 1;
333
334   return 0;
335 }
336
337 /*
338   kill older tincd for this net
339 */
340 int kill_other(void)
341 {
342   int pid;
343
344   if(!(pid = read_pid(pidfilename)))
345     {
346       if(netname)
347         fprintf(stderr, _("No other tincd is running for net `%s'.\n"), netname);
348       else
349         fprintf(stderr, _("No other tincd is running.\n"));
350       return 1;
351     }
352
353   errno = 0;    /* No error, sometimes errno is only changed on error */
354   /* ESRCH is returned when no process with that pid is found */
355   if(kill(pid, SIGTERM) && errno == ESRCH)
356     fprintf(stderr, _("Removing stale lock file.\n"));
357   remove_pid(pidfilename);
358
359   return 0;
360 }
361
362 /*
363   Set all files and paths according to netname
364 */
365 void make_names(void)
366 {
367   if(netname)
368     {
369       if(!pidfilename)
370         asprintf(&pidfilename, "/var/run/tinc.%s.pid", netname);
371       if(!confbase)
372         asprintf(&confbase, "%s/tinc/%s", CONFDIR, netname);
373       else
374         fprintf(stderr, "Both netname and configuration directory given, using the latter...\n");
375       if(!identname)
376         asprintf(&identname, "tinc.%s", netname);
377     }
378   else
379     {
380       if(!pidfilename)
381         pidfilename = "/var/run/tinc.pid";
382       if(!confbase)
383         asprintf(&confbase, "%s/tinc", CONFDIR);
384       if(!identname)
385         identname = "tinc";
386     }
387 }
388
389 int
390 main(int argc, char **argv, char **envp)
391 {
392   program_name = argv[0];
393
394   setlocale (LC_ALL, "");
395   bindtextdomain (PACKAGE, LOCALEDIR);
396   textdomain (PACKAGE);
397
398   /* Do some intl stuff right now */
399   
400   unknown = _("unknown");
401
402   environment = envp;
403   parse_options(argc, argv, envp);
404
405   if(show_version)
406     {
407       printf(_("%s version %s (built %s %s, protocol %d)\n"), PACKAGE, VERSION, __DATE__, __TIME__, PROT_CURRENT);
408       printf(_("Copyright (C) 1998,1999,2000 Ivo Timmermans, Guus Sliepen and others.\n"
409                "See the AUTHORS file for a complete list.\n\n"
410                "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
411                "and you are welcome to redistribute it under certain conditions;\n"
412                "see the file COPYING for details.\n"));
413
414       return 0;
415     }
416
417   if(show_help)
418     usage(0);
419
420   if(geteuid())
421     {
422       fprintf(stderr, _("You must be root to run this program. Sorry.\n"));
423       return 1;
424     }
425
426   g_argv = argv;
427
428   make_names();
429
430   /* Slllluuuuuuurrrrp! */
431
432   RAND_load_file("/dev/urandom", 1024);
433
434   if(generate_keys)
435     exit(keygen(generate_keys));
436
437   if(kill_tincd)
438     exit(kill_other());
439
440   if(read_server_config())
441     return 1;
442
443   setup_signals();
444
445   if(detach())
446     exit(0);
447
448   if(debug_lvl >= DEBUG_ERROR)
449     ERR_load_crypto_strings();
450     
451   for(;;)
452     {
453       if(!setup_network_connections())
454         {
455           main_loop();
456           cleanup_and_exit(1);
457         }
458       
459       syslog(LOG_ERR, _("Unrecoverable error"));
460       cp_trace();
461
462       if(do_detach)
463         {
464           syslog(LOG_NOTICE, _("Restarting in %d seconds!"), MAXTIMEOUT);
465           sleep(MAXTIMEOUT);
466         }
467       else
468         {
469           syslog(LOG_ERR, _("Not restarting."));
470           exit(0);
471         }
472     }
473 }
474
475 RETSIGTYPE
476 sigterm_handler(int a)
477 {
478   if(debug_lvl > DEBUG_NOTHING)
479     syslog(LOG_NOTICE, _("Got TERM signal"));
480
481   cleanup_and_exit(0);
482 }
483
484 RETSIGTYPE
485 sigquit_handler(int a)
486 {
487   if(debug_lvl > DEBUG_NOTHING)
488     syslog(LOG_NOTICE, _("Got QUIT signal"));
489   cleanup_and_exit(0);
490 }
491
492 RETSIGTYPE
493 sigsegv_square(int a)
494 {
495   syslog(LOG_ERR, _("Got another SEGV signal: not restarting"));
496   exit(0);
497 }
498
499 RETSIGTYPE
500 sigsegv_handler(int a)
501 {
502   syslog(LOG_ERR, _("Got SEGV signal"));
503   cp_trace();
504
505   if(do_detach)
506     {
507       syslog(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
508       signal(SIGSEGV, sigsegv_square);
509       close_network_connections();
510       sleep(5);
511       remove_pid(pidfilename);
512       execvp(g_argv[0], g_argv);
513     }
514   else
515     {
516       syslog(LOG_NOTICE, _("Not restarting."));
517       exit(0);
518     }
519 }
520
521 RETSIGTYPE
522 sighup_handler(int a)
523 {
524   if(debug_lvl > DEBUG_NOTHING)
525     syslog(LOG_NOTICE, _("Got HUP signal"));
526   sighup = 1;
527 }
528
529 RETSIGTYPE
530 sigint_handler(int a)
531 {
532   if(debug_lvl > DEBUG_NOTHING)
533     syslog(LOG_NOTICE, _("Got INT signal, exiting"));
534   cleanup_and_exit(0);
535 }
536
537 RETSIGTYPE
538 sigusr1_handler(int a)
539 {
540   dump_conn_list();
541 }
542
543 RETSIGTYPE
544 sigusr2_handler(int a)
545 {
546   dump_subnet_list();
547 }
548
549 RETSIGTYPE
550 sighuh(int a)
551 {
552   syslog(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
553   cp_trace();
554 }
555
556 void
557 setup_signals(void)
558 {
559   int i;
560
561   for(i=0;i<32;i++)
562     signal(i,sighuh);
563
564   if(signal(SIGTERM, SIG_IGN) != SIG_ERR)
565     signal(SIGTERM, sigterm_handler);
566   if(signal(SIGQUIT, SIG_IGN) != SIG_ERR)
567     signal(SIGQUIT, sigquit_handler);
568   if(signal(SIGSEGV, SIG_IGN) != SIG_ERR)
569     signal(SIGSEGV, sigsegv_handler);
570   if(signal(SIGHUP, SIG_IGN) != SIG_ERR)
571     signal(SIGHUP, sighup_handler);
572   signal(SIGPIPE, SIG_IGN);
573   if(signal(SIGINT, SIG_IGN) != SIG_ERR)
574     signal(SIGINT, sigint_handler);
575   signal(SIGUSR1, sigusr1_handler);
576   signal(SIGUSR2, sigusr2_handler);
577   signal(SIGCHLD, SIG_IGN);
578 }
579
580 RETSIGTYPE parent_exit(int a)
581 {
582   exit(0);
583 }