Fix warnings from the Clang Static Analyzer.
[tinc] / src / tincd.c
1 /*
2     tincd.c -- the main file for tincd
3     Copyright (C) 1998-2005 Ivo Timmermans
4                   2000-2015 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 = 1;
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                                 if(confbase) {
166                                         fprintf(stderr, "Only one configuration directory can be given.\n");
167                                         usage(true);
168                                         return false;
169                                 }
170                                 confbase = xstrdup(optarg);
171                                 break;
172
173                         case 'D':                               /* no detach */
174                                 do_detach = false;
175                                 break;
176
177                         case 'L':                               /* no detach */
178 #ifndef HAVE_MLOCKALL
179                                 logger(LOG_ERR, "%s not supported on this platform", "mlockall()");
180                                 return false;
181 #else
182                                 do_mlock = true;
183                                 break;
184 #endif
185
186                         case 'd':                               /* increase debug level */
187                                 if(!optarg && optind < argc && *argv[optind] != '-')
188                                         optarg = argv[optind++];
189                                 if(optarg)
190                                         debug_level = atoi(optarg);
191                                 else
192                                         debug_level++;
193                                 break;
194
195                         case 'k':                               /* kill old tincds */
196 #ifndef HAVE_MINGW
197                                 if(!optarg && optind < argc && *argv[optind] != '-')
198                                         optarg = argv[optind++];
199                                 if(optarg) {
200                                         if(!strcasecmp(optarg, "HUP"))
201                                                 kill_tincd = SIGHUP;
202                                         else if(!strcasecmp(optarg, "TERM"))
203                                                 kill_tincd = SIGTERM;
204                                         else if(!strcasecmp(optarg, "KILL"))
205                                                 kill_tincd = SIGKILL;
206                                         else if(!strcasecmp(optarg, "USR1"))
207                                                 kill_tincd = SIGUSR1;
208                                         else if(!strcasecmp(optarg, "USR2"))
209                                                 kill_tincd = SIGUSR2;
210                                         else if(!strcasecmp(optarg, "WINCH"))
211                                                 kill_tincd = SIGWINCH;
212                                         else if(!strcasecmp(optarg, "INT"))
213                                                 kill_tincd = SIGINT;
214                                         else if(!strcasecmp(optarg, "ALRM"))
215                                                 kill_tincd = SIGALRM;
216                                         else if(!strcasecmp(optarg, "ABRT"))
217                                                 kill_tincd = SIGABRT;
218                                         else {
219                                                 kill_tincd = atoi(optarg);
220
221                                                 if(!kill_tincd) {
222                                                         fprintf(stderr, "Invalid argument `%s'; SIGNAL must be a number or one of HUP, TERM, KILL, USR1, USR2, WINCH, INT or ALRM.\n",
223                                                                         optarg);
224                                                         usage(true);
225                                                         return false;
226                                                 }
227                                         }
228                                 } else
229                                         kill_tincd = SIGTERM;
230 #else
231                                         kill_tincd = 1;
232 #endif
233                                 break;
234
235                         case 'n':                               /* net name given */
236                                 /* netname "." is special: a "top-level name" */
237                                 if(netname) {
238                                         fprintf(stderr, "Only one netname can be given.\n");
239                                         usage(true);
240                                         return false;
241                                 }
242                                 if(optarg && strcmp(optarg, "."))
243                                         netname = xstrdup(optarg);
244                                 break;
245
246                         case 'o':                               /* option */
247                                 cfg = parse_config_line(optarg, NULL, ++lineno);
248                                 if (!cfg)
249                                         return false;
250                                 list_insert_tail(cmdline_conf, cfg);
251                                 break;
252
253                         case 'K':                               /* generate public/private keypair */
254                                 if(!optarg && optind < argc && *argv[optind] != '-')
255                                         optarg = argv[optind++];
256                                 if(optarg) {
257                                         generate_keys = atoi(optarg);
258
259                                         if(generate_keys < 512) {
260                                                 fprintf(stderr, "Invalid argument `%s'; BITS must be a number equal to or greater than 512.\n",
261                                                                 optarg);
262                                                 usage(true);
263                                                 return false;
264                                         }
265
266                                         generate_keys &= ~7;    /* Round it to bytes */
267                                 } else
268                                         generate_keys = 2048;
269                                 break;
270
271                         case 'R':                               /* chroot to NETNAME dir */
272                                 do_chroot = true;
273                                 break;
274
275                         case 'U':                               /* setuid to USER */
276                                 switchuser = optarg;
277                                 break;
278
279                         case 1:                                 /* show help */
280                                 show_help = true;
281                                 break;
282
283                         case 2:                                 /* show version */
284                                 show_version = true;
285                                 break;
286
287                         case 3:                                 /* bypass security */
288                                 bypass_security = true;
289                                 break;
290
291                         case 4:                                 /* write log entries to a file */
292                                 use_logfile = true;
293                                 if(!optarg && optind < argc && *argv[optind] != '-')
294                                         optarg = argv[optind++];
295                                 if(optarg) {
296                                         if(logfilename) {
297                                                 fprintf(stderr, "Only one logfile can be given.\n");
298                                                 usage(true);
299                                                 return false;
300                                         }
301                                         logfilename = xstrdup(optarg);
302                                 }
303                                 break;
304
305                         case 5:                                 /* write PID to a file */
306                                 if(pidfilename) {
307                                         fprintf(stderr, "Only one pidfile can be given.\n");
308                                         usage(true);
309                                         return false;
310                                 }
311                                 pidfilename = xstrdup(optarg);
312                                 break;
313
314                         case '?':
315                                 usage(true);
316                                 return false;
317
318                         default:
319                                 break;
320                 }
321         }
322
323         if(optind < argc) {
324                 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
325                 usage(true);
326                 return false;
327         }
328
329         return true;
330 }
331
332 /* This function prettyprints the key generation process */
333
334 static void indicator(int a, int b, void *p) {
335         switch (a) {
336                 case 0:
337                         fprintf(stderr, ".");
338                         break;
339
340                 case 1:
341                         fprintf(stderr, "+");
342                         break;
343
344                 case 2:
345                         fprintf(stderr, "-");
346                         break;
347
348                 case 3:
349                         switch (b) {
350                                 case 0:
351                                         fprintf(stderr, " p\n");
352                                         break;
353
354                                 case 1:
355                                         fprintf(stderr, " q\n");
356                                         break;
357
358                                 default:
359                                         fprintf(stderr, "?");
360                         }
361                         break;
362
363                 default:
364                         fprintf(stderr, "?");
365         }
366 }
367
368 /*
369   Generate a public/private RSA keypair, and ask for a file to store
370   them in.
371 */
372 static bool keygen(int bits) {
373         RSA *rsa_key;
374         FILE *f;
375         char *pubname, *privname;
376
377         fprintf(stderr, "Generating %d bits keys:\n", bits);
378         rsa_key = RSA_generate_key(bits, 0x10001, indicator, NULL);
379
380         if(!rsa_key) {
381                 fprintf(stderr, "Error during key generation!\n");
382                 return false;
383         } else
384                 fprintf(stderr, "Done.\n");
385
386         xasprintf(&privname, "%s/rsa_key.priv", confbase);
387         f = ask_and_open(privname, "private RSA key");
388         free(privname);
389
390         if(!f)
391                 return false;
392
393 #ifdef HAVE_FCHMOD
394         /* Make it unreadable for others. */
395         fchmod(fileno(f), 0600);
396 #endif
397                 
398         fputc('\n', f);
399         PEM_write_RSAPrivateKey(f, rsa_key, NULL, NULL, 0, NULL, NULL);
400         fclose(f);
401
402         char *name = get_name();
403
404         if(name) {
405                 xasprintf(&pubname, "%s/hosts/%s", confbase, name);
406                 free(name);
407         } else {
408                 xasprintf(&pubname, "%s/rsa_key.pub", confbase);
409         }
410
411         f = ask_and_open(pubname, "public RSA key");
412         free(pubname);
413
414         if(!f)
415                 return false;
416
417         fputc('\n', f);
418         PEM_write_RSAPublicKey(f, rsa_key);
419         fclose(f);
420
421         return true;
422 }
423
424 /*
425   Set all files and paths according to netname
426 */
427 static void make_names(void) {
428 #ifdef HAVE_MINGW
429         HKEY key;
430         char installdir[1024] = "";
431         DWORD len = sizeof(installdir);
432 #endif
433
434         if(netname)
435                 xasprintf(&identname, "tinc.%s", netname);
436         else
437                 identname = xstrdup("tinc");
438
439 #ifdef HAVE_MINGW
440         if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\tinc", 0, KEY_READ, &key)) {
441                 if(!RegQueryValueEx(key, NULL, 0, 0, (LPBYTE)installdir, &len)) {
442                         if(!confbase) {
443                                 if(netname)
444                                         xasprintf(&confbase, "%s/%s", installdir, netname);
445                                 else
446                                         xasprintf(&confbase, "%s", installdir);
447                         }
448                         if(!logfilename)
449                                 xasprintf(&logfilename, "%s/tinc.log", confbase);
450                 }
451                 RegCloseKey(key);
452                 if(*installdir)
453                         return;
454         }
455 #endif
456
457         if(!pidfilename)
458                 xasprintf(&pidfilename, LOCALSTATEDIR "/run/%s.pid", identname);
459
460         if(!logfilename)
461                 xasprintf(&logfilename, LOCALSTATEDIR "/log/%s.log", identname);
462
463         if(netname) {
464                 if(!confbase)
465                         xasprintf(&confbase, CONFDIR "/tinc/%s", netname);
466                 else
467                         logger(LOG_INFO, "Both netname and configuration directory given, using the latter...");
468         } else {
469                 if(!confbase)
470                         xasprintf(&confbase, CONFDIR "/tinc");
471         }
472 }
473
474 static void free_names() {
475         if (identname) free(identname);
476         if (netname) free(netname);
477         if (pidfilename) free(pidfilename);
478         if (logfilename) free(logfilename);
479         if (confbase) free(confbase);
480 }
481
482 static bool drop_privs() {
483 #ifdef HAVE_MINGW
484         if (switchuser) {
485                 logger(LOG_ERR, "%s not supported on this platform", "-U");
486                 return false;
487         }
488         if (do_chroot) {
489                 logger(LOG_ERR, "%s not supported on this platform", "-R");
490                 return false;
491         }
492 #else
493         uid_t uid = 0;
494         if (switchuser) {
495                 struct passwd *pw = getpwnam(switchuser);
496                 if (!pw) {
497                         logger(LOG_ERR, "unknown user `%s'", switchuser);
498                         return false;
499                 }
500                 uid = pw->pw_uid;
501                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
502                     setgid(pw->pw_gid) != 0) {
503                         logger(LOG_ERR, "System call `%s' failed: %s",
504                                "initgroups", strerror(errno));
505                         return false;
506                 }
507 #ifndef __ANDROID__
508 // Not supported in android NDK
509                 endgrent();
510                 endpwent();
511 #endif
512         }
513         if (do_chroot) {
514                 tzset();        /* for proper timestamps in logs */
515                 if (chroot(confbase) != 0 || chdir("/") != 0) {
516                         logger(LOG_ERR, "System call `%s' failed: %s",
517                                "chroot", strerror(errno));
518                         return false;
519                 }
520                 free(confbase);
521                 confbase = xstrdup("");
522         }
523         if (switchuser)
524                 if (setuid(uid) != 0) {
525                         logger(LOG_ERR, "System call `%s' failed: %s",
526                                "setuid", strerror(errno));
527                         return false;
528                 }
529 #endif
530         return true;
531 }
532
533 #ifdef HAVE_MINGW
534 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
535 #else
536 # define NORMAL_PRIORITY_CLASS 0
537 # define BELOW_NORMAL_PRIORITY_CLASS 10
538 # define HIGH_PRIORITY_CLASS -10
539 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
540 #endif
541
542 int main(int argc, char **argv) {
543         program_name = argv[0];
544
545         if(!parse_options(argc, argv))
546                 return 1;
547         
548         make_names();
549
550         if(show_version) {
551                 printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
552                            VERSION, __DATE__, __TIME__, PROT_CURRENT);
553                 printf("Copyright (C) 1998-2015 Ivo Timmermans, Guus Sliepen and others.\n"
554                                 "See the AUTHORS file for a complete list.\n\n"
555                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
556                                 "and you are welcome to redistribute it under certain conditions;\n"
557                                 "see the file COPYING for details.\n");
558
559                 return 0;
560         }
561
562         if(show_help) {
563                 usage(false);
564                 return 0;
565         }
566
567         if(kill_tincd)
568                 return !kill_other(kill_tincd);
569
570         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
571
572         g_argv = argv;
573
574         if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid())
575                 do_detach = false;
576 #ifdef HAVE_UNSETENV
577         unsetenv("LISTEN_PID");
578 #endif
579
580         init_configuration(&config_tree);
581
582         /* Slllluuuuuuurrrrp! */
583
584         RAND_load_file("/dev/urandom", 1024);
585
586         ENGINE_load_builtin_engines();
587         ENGINE_register_all_complete();
588
589         OpenSSL_add_all_algorithms();
590
591         if(generate_keys) {
592                 read_server_config();
593                 return !keygen(generate_keys);
594         }
595
596         if(!read_server_config())
597                 return 1;
598
599 #ifdef HAVE_LZO
600         if(lzo_init() != LZO_E_OK) {
601                 logger(LOG_ERR, "Error initializing LZO compressor!");
602                 return 1;
603         }
604 #endif
605
606 #ifdef HAVE_MINGW
607         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
608                 logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
609                 return 1;
610         }
611
612         if(!do_detach || !init_service())
613                 return main2(argc, argv);
614         else
615                 return 1;
616 }
617
618 int main2(int argc, char **argv) {
619         InitializeCriticalSection(&mutex);
620         EnterCriticalSection(&mutex);
621 #endif
622         char *priority = NULL;
623
624         if(!detach())
625                 return 1;
626
627 #ifdef HAVE_MLOCKALL
628         /* Lock all pages into memory if requested.
629          * This has to be done after daemon()/fork() so it works for child.
630          * No need to do that in parent as it's very short-lived. */
631         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
632                 logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
633                    strerror(errno));
634                 return 1;
635         }
636 #endif
637
638         /* Setup sockets and open device. */
639
640         if(!setup_network())
641                 goto end;
642
643         /* Initiate all outgoing connections. */
644
645         try_outgoing_connections();
646
647         /* Change process priority */
648
649         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
650                 if(!strcasecmp(priority, "Normal")) {
651                         if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
652                                 logger(LOG_ERR, "System call `%s' failed: %s",
653                                        "setpriority", strerror(errno));
654                                 goto end;
655                         }
656                 } else if(!strcasecmp(priority, "Low")) {
657                         if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
658                                        logger(LOG_ERR, "System call `%s' failed: %s",
659                                        "setpriority", strerror(errno));
660                                 goto end;
661                         }
662                 } else if(!strcasecmp(priority, "High")) {
663                         if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
664                                 logger(LOG_ERR, "System call `%s' failed: %s",
665                                        "setpriority", strerror(errno));
666                                 goto end;
667                         }
668                 } else {
669                         logger(LOG_ERR, "Invalid priority `%s`!", priority);
670                         goto end;
671                 }
672         }
673
674         /* drop privileges */
675         if (!drop_privs())
676                 goto end;
677
678         /* Start main loop. It only exits when tinc is killed. */
679
680         status = main_loop();
681
682         /* Shutdown properly. */
683
684         ifdebug(CONNECTIONS)
685                 devops.dump_stats();
686
687         close_network_connections();
688
689 end:
690         logger(LOG_NOTICE, "Terminating");
691
692 #ifndef HAVE_MINGW
693         remove_pid(pidfilename);
694 #endif
695
696         free(priority);
697
698         EVP_cleanup();
699         ENGINE_cleanup();
700         CRYPTO_cleanup_all_ex_data();
701         ERR_remove_state(0);
702         ERR_free_strings();
703
704         exit_configuration(&config_tree);
705         list_free(cmdline_conf);
706         free_names();
707
708         return status;
709 }