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