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