Update copyright notices.
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2005 Ivo Timmermans
4                   2000-2012 Guus Sliepen <guus@tinc-vpn.org>
5                   2008      Max Rijevski <maksuf@gmail.com>
6                   2009      Michael Tokarev <mjt@tls.msk.ru>
7                   2010      Julien Muchembled <jm@jmuchemb.eu>
8                   2010      Timothy Redaelli <timothy@redaelli.eu>
9
10     This program is free software; you can redistribute it and/or modify
11     it under the terms of the GNU General Public License as published by
12     the Free Software Foundation; either version 2 of the License, or
13     (at your option) any later version.
14
15     This program is distributed in the hope that it will be useful,
16     but WITHOUT ANY WARRANTY; without even the implied warranty of
17     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18     GNU General Public License for more details.
19
20     You should have received a copy of the GNU General Public License along
21     with this program; if not, write to the Free Software Foundation, Inc.,
22     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 */
24
25 #include "system.h"
26
27 /* Darwin (MacOS/X) needs the following definition... */
28 #ifndef _P1003_1B_VISIBLE
29 #define _P1003_1B_VISIBLE
30 #endif
31
32 #ifdef HAVE_SYS_MMAN_H
33 #include <sys/mman.h>
34 #endif
35
36 #include <openssl/rand.h>
37 #include <openssl/rsa.h>
38 #include <openssl/pem.h>
39 #include <openssl/evp.h>
40 #include <openssl/engine.h>
41
42 #ifdef HAVE_LZO
43 #include LZO1X_H
44 #endif
45
46 #ifndef HAVE_MINGW
47 #include <pwd.h>
48 #include <grp.h>
49 #include <time.h>
50 #endif
51
52 #include <getopt.h>
53 #include "pidfile.h"
54
55 #include "conf.h"
56 #include "device.h"
57 #include "logger.h"
58 #include "net.h"
59 #include "netutl.h"
60 #include "process.h"
61 #include "protocol.h"
62 #include "utils.h"
63 #include "xalloc.h"
64
65 /* The name this program was run with. */
66 char *program_name = NULL;
67
68 /* If nonzero, display usage information and exit. */
69 bool show_help = false;
70
71 /* If nonzero, print the version on standard output and exit.  */
72 bool show_version = false;
73
74 /* If nonzero, it will attempt to kill a running tincd and exit. */
75 int kill_tincd = 0;
76
77 /* If nonzero, generate public/private keypair for this host/net. */
78 int generate_keys = 0;
79
80 /* If nonzero, use null ciphers and skip all key exchanges. */
81 bool bypass_security = false;
82
83 /* If nonzero, disable swapping for this process. */
84 bool do_mlock = false;
85
86 /* If nonzero, chroot to netdir after startup. */
87 static bool do_chroot = false;
88
89 /* If !NULL, do setuid to given user after startup */
90 static const char *switchuser = NULL;
91
92 /* If nonzero, write log entries to a separate file. */
93 bool use_logfile = false;
94
95 char *identname = NULL;                         /* program name for syslog */
96 char *pidfilename = NULL;                       /* pid file location */
97 char *logfilename = NULL;                       /* log file location */
98 char **g_argv;                                  /* a copy of the cmdline arguments */
99
100 static int status;
101
102 static struct option const long_options[] = {
103         {"config", required_argument, NULL, 'c'},
104         {"kill", optional_argument, NULL, 'k'},
105         {"net", required_argument, NULL, 'n'},
106         {"help", no_argument, NULL, 1},
107         {"version", no_argument, NULL, 2},
108         {"no-detach", no_argument, NULL, 'D'},
109         {"generate-keys", optional_argument, NULL, 'K'},
110         {"debug", optional_argument, NULL, 'd'},
111         {"bypass-security", no_argument, NULL, 3},
112         {"mlock", no_argument, NULL, 'L'},
113         {"chroot", no_argument, NULL, 'R'},
114         {"user", required_argument, NULL, 'U'},
115         {"logfile", optional_argument, NULL, 4},
116         {"pidfile", required_argument, NULL, 5},
117         {"option", required_argument, NULL, 'o'},
118         {NULL, 0, NULL, 0}
119 };
120
121 #ifdef HAVE_MINGW
122 static struct WSAData wsa_state;
123 CRITICAL_SECTION mutex;
124 int main2(int argc, char **argv);
125 #endif
126
127 static void usage(bool status) {
128         if(status)
129                 fprintf(stderr, "Try `%s --help\' for more information.\n",
130                                 program_name);
131         else {
132                 printf("Usage: %s [option]...\n\n", program_name);
133                 printf("  -c, --config=DIR               Read configuration options from DIR.\n"
134                                 "  -D, --no-detach                Don't fork and detach.\n"
135                                 "  -d, --debug[=LEVEL]            Increase debug level or set it to LEVEL.\n"
136                                 "  -k, --kill[=SIGNAL]            Attempt to kill a running tincd and exit.\n"
137                                 "  -n, --net=NETNAME              Connect to net NETNAME.\n"
138                                 "  -K, --generate-keys[=BITS]     Generate public/private RSA keypair.\n"
139                                 "  -L, --mlock                    Lock tinc into main memory.\n"
140                                 "      --logfile[=FILENAME]       Write log entries to a logfile.\n"
141                                 "      --pidfile=FILENAME         Write PID to FILENAME.\n"
142                                 "  -o, --option=[HOST.]KEY=VALUE  Set global/host configuration value.\n"
143                                 "  -R, --chroot                   chroot to NET dir at startup.\n"
144                                 "  -U, --user=USER                setuid to given USER at startup.\n"
145                                 "      --help                     Display this help and exit.\n"
146                                 "      --version                  Output version information and exit.\n\n");
147                 printf("Report bugs to tinc@tinc-vpn.org.\n");
148         }
149 }
150
151 static bool parse_options(int argc, char **argv) {
152         config_t *cfg;
153         int r;
154         int option_index = 0;
155         int lineno = 0;
156
157         cmdline_conf = list_alloc((list_action_t)free_config);
158
159         while((r = getopt_long(argc, argv, "c:DLd::k::n:o:K::RU:", long_options, &option_index)) != EOF) {
160                 switch (r) {
161                         case 0:                         /* long option */
162                                 break;
163
164                         case 'c':                               /* config file */
165                                 confbase = xstrdup(optarg);
166                                 break;
167
168                         case 'D':                               /* no detach */
169                                 do_detach = false;
170                                 break;
171
172                         case 'L':                               /* no detach */
173 #ifndef HAVE_MLOCKALL
174                                 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
175                                 return false;
176 #else
177                                 do_mlock = true;
178                                 break;
179 #endif
180
181                         case 'd':                               /* inc debug level */
182                                 if(optarg)
183                                         debug_level = atoi(optarg);
184                                 else
185                                         debug_level++;
186                                 break;
187
188                         case 'k':                               /* kill old tincds */
189 #ifndef HAVE_MINGW
190                                 if(optarg) {
191                                         if(!strcasecmp(optarg, "HUP"))
192                                                 kill_tincd = SIGHUP;
193                                         else if(!strcasecmp(optarg, "TERM"))
194                                                 kill_tincd = SIGTERM;
195                                         else if(!strcasecmp(optarg, "KILL"))
196                                                 kill_tincd = SIGKILL;
197                                         else if(!strcasecmp(optarg, "USR1"))
198                                                 kill_tincd = SIGUSR1;
199                                         else if(!strcasecmp(optarg, "USR2"))
200                                                 kill_tincd = SIGUSR2;
201                                         else if(!strcasecmp(optarg, "WINCH"))
202                                                 kill_tincd = SIGWINCH;
203                                         else if(!strcasecmp(optarg, "INT"))
204                                                 kill_tincd = SIGINT;
205                                         else if(!strcasecmp(optarg, "ALRM"))
206                                                 kill_tincd = SIGALRM;
207                                         else if(!strcasecmp(optarg, "ABRT"))
208                                                 kill_tincd = SIGABRT;
209                                         else {
210                                                 kill_tincd = atoi(optarg);
211
212                                                 if(!kill_tincd) {
213                                                         fprintf(stderr, "Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n",
214                                                                         optarg);
215                                                         usage(true);
216                                                         return false;
217                                                 }
218                                         }
219                                 } else
220                                         kill_tincd = SIGTERM;
221 #else
222                                         kill_tincd = 1;
223 #endif
224                                 break;
225
226                         case 'n':                               /* net name given */
227                                 /* netname "." is special: a "top-level name" */
228                                 netname = strcmp(optarg, ".") != 0 ?
229                                                 xstrdup(optarg) : NULL;
230                                 break;
231
232                         case 'o':                               /* option */
233                                 cfg = parse_config_line(optarg, NULL, ++lineno);
234                                 if (!cfg)
235                                         return false;
236                                 list_insert_tail(cmdline_conf, cfg);
237                                 break;
238
239                         case 'K':                               /* generate public/private keypair */
240                                 if(optarg) {
241                                         generate_keys = atoi(optarg);
242
243                                         if(generate_keys < 512) {
244                                                 fprintf(stderr, "Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n",
245                                                                 optarg);
246                                                 usage(true);
247                                                 return false;
248                                         }
249
250                                         generate_keys &= ~7;    /* Round it to bytes */
251                                 } else
252                                         generate_keys = 2048;
253                                 break;
254
255                         case 'R':                               /* chroot to NETNAME dir */
256                                 do_chroot = true;
257                                 break;
258
259                         case 'U':                               /* setuid to USER */
260                                 switchuser = optarg;
261                                 break;
262
263                         case 1:                                 /* show help */
264                                 show_help = true;
265                                 break;
266
267                         case 2:                                 /* show version */
268                                 show_version = true;
269                                 break;
270
271                         case 3:                                 /* bypass security */
272                                 bypass_security = true;
273                                 break;
274
275                         case 4:                                 /* write log entries to a file */
276                                 use_logfile = true;
277                                 if(optarg)
278                                         logfilename = xstrdup(optarg);
279                                 break;
280
281                         case 5:                                 /* write PID to a file */
282                                 pidfilename = xstrdup(optarg);
283                                 break;
284
285                         case '?':
286                                 usage(true);
287                                 return false;
288
289                         default:
290                                 break;
291                 }
292         }
293
294         return true;
295 }
296
297 /* This function prettyprints the key generation process */
298
299 static void indicator(int a, int b, void *p) {
300         switch (a) {
301                 case 0:
302                         fprintf(stderr, ".");
303                         break;
304
305                 case 1:
306                         fprintf(stderr, "+");
307                         break;
308
309                 case 2:
310                         fprintf(stderr, "-");
311                         break;
312
313                 case 3:
314                         switch (b) {
315                                 case 0:
316                                         fprintf(stderr, " p\n");
317                                         break;
318
319                                 case 1:
320                                         fprintf(stderr, " q\n");
321                                         break;
322
323                                 default:
324                                         fprintf(stderr, "?");
325                         }
326                         break;
327
328                 default:
329                         fprintf(stderr, "?");
330         }
331 }
332
333 /*
334   Generate a public/private RSA keypair, and ask for a file to store
335   them in.
336 */
337 static bool keygen(int bits) {
338         RSA *rsa_key;
339         FILE *f;
340         char *name = NULL;
341         char *filename;
342
343         get_config_string(lookup_config(config_tree, "Name"), &name);
344
345         if(name && !check_id(name)) {
346                 fprintf(stderr, "Invalid name for myself!\n");
347                 return false;
348         }
349
350         fprintf(stderr, "Generating %d bits keys:\n", bits);
351         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
352
353         if(!rsa_key) {
354                 fprintf(stderr, "Error during key generation!\n");
355                 return false;
356         } else
357                 fprintf(stderr, "Done.\n");
358
359         xasprintf(&filename, "%s/rsa_key.priv", confbase);
360         f = ask_and_open(filename, "private RSA key");
361
362         if(!f)
363                 return false;
364
365 #ifdef HAVE_FCHMOD
366         /* Make it unreadable for others. */
367         fchmod(fileno(f), 0600);
368 #endif
369                 
370         fputc('\n', f);
371         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
372         fclose(f);
373         free(filename);
374
375         if(name)
376                 xasprintf(&filename, "%s/hosts/%s", confbase, name);
377         else
378                 xasprintf(&filename, "%s/rsa_key.pub", confbase);
379
380         f = ask_and_open(filename, "public RSA key");
381
382         if(!f)
383                 return false;
384
385         fputc('\n', f);
386         PEM_write_RSAPublicKey(f, rsa_key);
387         fclose(f);
388         free(filename);
389         if(name)
390                 free(name);
391
392         return true;
393 }
394
395 /*
396   Set all files and paths according to netname
397 */
398 static void make_names(void) {
399 #ifdef HAVE_MINGW
400         HKEY key;
401         char installdir[1024] = "";
402         long len = sizeof(installdir);
403 #endif
404
405         if(netname)
406                 xasprintf(&identname, "tinc.%s", netname);
407         else
408                 identname = xstrdup("tinc");
409
410 #ifdef HAVE_MINGW
411         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
412                 if(!RegQueryValueEx(key, NULL, 0, 0, installdir, &len)) {
413                         if(!logfilename)
414                                 xasprintf(&logfilename, "%s/log/%s.log", identname);
415                         if(!confbase) {
416                                 if(netname)
417                                         xasprintf(&confbase, "%s/%s", installdir, netname);
418                                 else
419                                         xasprintf(&confbase, "%s", installdir);
420                         }
421                 }
422                 RegCloseKey(key);
423                 if(*installdir)
424                         return;
425         }
426 #endif
427
428         if(!pidfilename)
429                 xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
430
431         if(!logfilename)
432                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
433
434         if(netname) {
435                 if(!confbase)
436                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
437                 else
438                         logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
439         } else {
440                 if(!confbase)
441                         xasprintf(&confbase, CONFDIR "/tinc");
442         }
443 }
444
445 static void free_names() {
446         if (identname) free(identname);
447         if (netname) free(netname);
448         if (pidfilename) free(pidfilename);
449         if (logfilename) free(logfilename);
450         if (confbase) free(confbase);
451 }
452
453 static bool drop_privs() {
454 #ifdef HAVE_MINGW
455         if (switchuser) {
456                 logger(LOG_ERR, "%s not supported on this platform", "-U");
457                 return false;
458         }
459         if (do_chroot) {
460                 logger(LOG_ERR, "%s not supported on this platform", "-R");
461                 return false;
462         }
463 #else
464         uid_t uid = 0;
465         if (switchuser) {
466                 struct passwd *pw = getpwnam(switchuser);
467                 if (!pw) {
468                         logger(LOG_ERR, "unknown user `%s'", switchuser);
469                         return false;
470                 }
471                 uid = pw->pw_uid;
472                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
473                     setgid(pw->pw_gid) != 0) {
474                         logger(LOG_ERR, "System call `%s' failed: %s",
475                                "initgroups", strerror(errno));
476                         return false;
477                 }
478                 endgrent();
479                 endpwent();
480         }
481         if (do_chroot) {
482                 tzset();        /* for proper timestamps in logs */
483                 if (chroot(confbase) != 0 || chdir("/") != 0) {
484                         logger(LOG_ERR, "System call `%s' failed: %s",
485                                "chroot", strerror(errno));
486                         return false;
487                 }
488                 free(confbase);
489                 confbase = xstrdup("");
490         }
491         if (switchuser)
492                 if (setuid(uid) != 0) {
493                         logger(LOG_ERR, "System call `%s' failed: %s",
494                                "setuid", strerror(errno));
495                         return false;
496                 }
497 #endif
498         return true;
499 }
500
501 #ifdef HAVE_MINGW
502 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
503 #else
504 # define NORMAL_PRIORITY_CLASS 0
505 # define BELOW_NORMAL_PRIORITY_CLASS 10
506 # define HIGH_PRIORITY_CLASS -10
507 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
508 #endif
509
510 int main(int argc, char **argv) {
511         program_name = argv[0];
512
513         if(!parse_options(argc, argv))
514                 return 1;
515         
516         make_names();
517
518         if(show_version) {
519                 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
520                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
521                 printf("Copyright (C) 1998-2012 Ivo Timmermans, Guus Sliepen and others.\n"
522                                 "See the AUTHORS file for a complete list.\n\n"
523                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
524                                 "and you are welcome to redistribute it under certain conditions;\n"
525                                 "see the file COPYING for details.\n");
526
527                 return 0;
528         }
529
530         if(show_help) {
531                 usage(false);
532                 return 0;
533         }
534
535         if(kill_tincd)
536                 return !kill_other(kill_tincd);
537
538         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
539
540         g_argv = argv;
541
542         init_configuration(&config_tree);
543
544         /* Slllluuuuuuurrrrp! */
545
546         RAND_load_file("/dev/urandom", 1024);
547
548         ENGINE_load_builtin_engines();
549         ENGINE_register_all_complete();
550
551         OpenSSL_add_all_algorithms();
552
553         if(generate_keys) {
554                 read_server_config();
555                 return !keygen(generate_keys);
556         }
557
558         if(!read_server_config())
559                 return 1;
560
561 #ifdef HAVE_LZO
562         if(lzo_init() != LZO_E_OK) {
563                 logger(LOG_ERR, "Error initializing LZO compressor!");
564                 return 1;
565         }
566 #endif
567
568 #ifdef HAVE_MINGW
569         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
570                 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
571                 return 1;
572         }
573
574         if(!do_detach || !init_service())
575                 return main2(argc, argv);
576         else
577                 return 1;
578 }
579
580 int main2(int argc, char **argv) {
581         InitializeCriticalSection(&mutex);
582         EnterCriticalSection(&mutex);
583 #endif
584         char *priority = NULL;
585
586         if(!detach())
587                 return 1;
588
589 #ifdef HAVE_MLOCKALL
590         /* Lock all pages into memory if requested.
591          * This has to be done after daemon()/fork() so it works for child.
592          * No need to do that in parent as it's very short-lived. */
593         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
594                 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
595                    strerror(errno));
596                 return 1;
597         }
598 #endif
599
600         /* Setup sockets and open device. */
601
602         if(!setup_network())
603                 goto end;
604
605         /* Initiate all outgoing connections. */
606
607         try_outgoing_connections();
608
609         /* Change process priority */
610
611         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
612                 if(!strcasecmp(priority, "Normal")) {
613                         if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
614                                 logger(LOG_ERR, "System call `%s' failed: %s",
615                                        "setpriority", strerror(errno));
616                                 goto end;
617                         }
618                 } else if(!strcasecmp(priority, "Low")) {
619                         if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
620                                        logger(LOG_ERR, "System call `%s' failed: %s",
621                                        "setpriority", strerror(errno));
622                                 goto end;
623                         }
624                 } else if(!strcasecmp(priority, "High")) {
625                         if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
626                                 logger(LOG_ERR, "System call `%s' failed: %s",
627                                        "setpriority", strerror(errno));
628                                 goto end;
629                         }
630                 } else {
631                         logger(LOG_ERR, "Invalid priority `%s`!", priority);
632                         goto end;
633                 }
634         }
635
636         /* drop privileges */
637         if (!drop_privs())
638                 goto end;
639
640         /* Start main loop. It only exits when tinc is killed. */
641
642         status = main_loop();
643
644         /* Shutdown properly. */
645
646         ifdebug(CONNECTIONS)
647                 devops.dump_stats();
648
649         close_network_connections();
650
651 end:
652         logger(LOG_NOTICE, "Terminating");
653
654 #ifndef HAVE_MINGW
655         remove_pid(pidfilename);
656 #endif
657
658         free(priority);
659
660         EVP_cleanup();
661         ENGINE_cleanup();
662         CRYPTO_cleanup_all_ex_data();
663         ERR_remove_state(0);
664         ERR_free_strings();
665
666         exit_configuration(&config_tree);
667         list_free(cmdline_conf);
668         free_names();
669
670         return status;
671 }