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