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