tinc-gui: Reformat codebase according to PEP8
[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 #ifdef HAVE_LZO
37 #include LZO1X_H
38 #endif
39
40 #ifndef HAVE_MINGW
41 #include <pwd.h>
42 #include <grp.h>
43 #include <time.h>
44 #endif
45
46 #include <getopt.h>
47
48 #include "conf.h"
49 #include "control.h"
50 #include "crypto.h"
51 #include "device.h"
52 #include "event.h"
53 #include "logger.h"
54 #include "names.h"
55 #include "net.h"
56 #include "netutl.h"
57 #include "process.h"
58 #include "protocol.h"
59 #include "utils.h"
60 #include "xalloc.h"
61 #include "version.h"
62
63 /* If nonzero, display usage information and exit. */
64 static bool show_help = false;
65
66 /* If nonzero, print the version on standard output and exit.  */
67 static bool show_version = false;
68
69 /* If nonzero, use null ciphers and skip all key exchanges. */
70 bool bypass_security = false;
71
72 #ifdef HAVE_MLOCKALL
73 /* If nonzero, disable swapping for this process. */
74 static bool do_mlock = false;
75 #endif
76
77 #ifndef HAVE_MINGW
78 /* If nonzero, chroot to netdir after startup. */
79 static bool do_chroot = false;
80
81 /* If !NULL, do setuid to given user after startup */
82 static const char *switchuser = NULL;
83 #endif
84
85 /* If nonzero, write log entries to a separate file. */
86 bool use_logfile = false;
87
88 /* If nonzero, use syslog instead of stderr in no-detach mode. */
89 bool use_syslog = false;
90
91 char **g_argv;                  /* a copy of the cmdline arguments */
92
93 static int status = 1;
94
95 static struct option const long_options[] = {
96         {"config", required_argument, NULL, 'c'},
97         {"net", required_argument, NULL, 'n'},
98         {"help", no_argument, NULL, 1},
99         {"version", no_argument, NULL, 2},
100         {"no-detach", no_argument, NULL, 'D'},
101         {"debug", optional_argument, NULL, 'd'},
102         {"bypass-security", no_argument, NULL, 3},
103         {"mlock", no_argument, NULL, 'L'},
104         {"chroot", no_argument, NULL, 'R'},
105         {"user", required_argument, NULL, 'U'},
106         {"logfile", optional_argument, NULL, 4},
107         {"syslog", no_argument, NULL, 's'},
108         {"pidfile", required_argument, NULL, 5},
109         {"option", required_argument, NULL, 'o'},
110         {NULL, 0, NULL, 0}
111 };
112
113 #ifdef HAVE_MINGW
114 static struct WSAData wsa_state;
115 int main2(int argc, char **argv);
116 #endif
117
118 static void usage(bool status) {
119         if(status)
120                 fprintf(stderr, "Try `%s --help\' for more information.\n",
121                                 program_name);
122         else {
123                 printf("Usage: %s [option]...\n\n", program_name);
124                 printf( "  -c, --config=DIR              Read configuration options from DIR.\n"
125                                 "  -D, --no-detach               Don't fork and detach.\n"
126                                 "  -d, --debug[=LEVEL]           Increase debug level or set it to LEVEL.\n"
127                                 "  -n, --net=NETNAME             Connect to net NETNAME.\n"
128 #ifdef HAVE_MLOCKALL
129                                 "  -L, --mlock                   Lock tinc into main memory.\n"
130 #endif
131                                 "      --logfile[=FILENAME]      Write log entries to a logfile.\n"
132                                 "  -s  --syslog                  Use syslog instead of stderr with --no-detach.\n"
133                                 "      --pidfile=FILENAME        Write PID and control socket cookie to FILENAME.\n"
134                                 "      --bypass-security         Disables meta protocol security, for debugging.\n"
135                                 "  -o, --option[HOST.]KEY=VALUE  Set global/host configuration value.\n"
136 #ifndef HAVE_MINGW
137                                 "  -R, --chroot                  chroot to NET dir at startup.\n"
138                                 "  -U, --user=USER               setuid to given USER at startup.\n"
139 #endif
140                                 "      --help                    Display this help and exit.\n"
141                                 "      --version                 Output version information and exit.\n\n");
142                 printf("Report bugs to tinc@tinc-vpn.org.\n");
143         }
144 }
145
146 static bool parse_options(int argc, char **argv) {
147         config_t *cfg;
148         int r;
149         int option_index = 0;
150         int lineno = 0;
151
152         cmdline_conf = list_alloc((list_action_t)free_config);
153
154         while((r = getopt_long(argc, argv, "c:DLd::n:so:RU:", long_options, &option_index)) != EOF) {
155                 switch (r) {
156                         case 0:   /* long option */
157                                 break;
158
159                         case 'c': /* config file */
160                                 confbase = xstrdup(optarg);
161                                 break;
162
163                         case 'D': /* no detach */
164                                 do_detach = false;
165                                 break;
166
167                         case 'L': /* no detach */
168 #ifndef HAVE_MLOCKALL
169                                 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
170                                 return false;
171 #else
172                                 do_mlock = true;
173                                 break;
174 #endif
175
176                         case 'd': /* increase debug level */
177                                 if(!optarg && optind < argc && *argv[optind] != '-')
178                                         optarg = argv[optind++];
179                                 if(optarg)
180                                         debug_level = atoi(optarg);
181                                 else
182                                         debug_level++;
183                                 break;
184
185                         case 'n': /* net name given */
186                                 netname = xstrdup(optarg);
187                                 break;
188
189                         case 's': /* syslog */
190                                 use_logfile = false;
191                                 use_syslog = true;
192                                 break;
193
194                         case 'o': /* option */
195                                 cfg = parse_config_line(optarg, NULL, ++lineno);
196                                 if (!cfg)
197                                         return false;
198                                 list_insert_tail(cmdline_conf, cfg);
199                                 break;
200
201 #ifdef HAVE_MINGW
202                         case 'R':
203                         case 'U':
204                                 logger(DEBUG_ALWAYS, LOG_ERR, "The %s option is not supported on this platform.", argv[optind - 1]);
205                                 return false;
206 #else
207                         case 'R': /* chroot to NETNAME dir */
208                                 do_chroot = true;
209                                 break;
210
211                         case 'U': /* setuid to USER */
212                                 switchuser = optarg;
213                                 break;
214 #endif
215
216                         case 1:   /* show help */
217                                 show_help = true;
218                                 break;
219
220                         case 2:   /* show version */
221                                 show_version = true;
222                                 break;
223
224                         case 3:   /* bypass security */
225                                 bypass_security = true;
226                                 break;
227
228                         case 4:   /* write log entries to a file */
229                                 use_syslog = false;
230                                 use_logfile = true;
231                                 if(!optarg && optind < argc && *argv[optind] != '-')
232                                         optarg = argv[optind++];
233                                 if(optarg)
234                                         logfilename = xstrdup(optarg);
235                                 break;
236
237                         case 5:   /* open control socket here */
238                                 pidfilename = xstrdup(optarg);
239                                 break;
240
241                         case '?': /* wrong options */
242                                 usage(true);
243                                 return false;
244
245                         default:
246                                 break;
247                 }
248         }
249
250         if(optind < argc) {
251                 fprintf(stderr, "%s: unrecognized argument '%s'\n", argv[0], argv[optind]);
252                 usage(true);
253                 return false;
254         }
255
256         if(!netname && (netname = getenv("NETNAME")))
257                 netname = xstrdup(netname);
258
259         /* netname "." is special: a "top-level name" */
260
261         if(netname && (!*netname || !strcmp(netname, "."))) {
262                 free(netname);
263                 netname = NULL;
264         }
265
266         if(netname && (strpbrk(netname, "\\/") || *netname == '.')) {
267                 fprintf(stderr, "Invalid character in netname!\n");
268                 return false;
269         }
270
271         return true;
272 }
273
274 static bool drop_privs(void) {
275 #ifndef HAVE_MINGW
276         uid_t uid = 0;
277         if (switchuser) {
278                 struct passwd *pw = getpwnam(switchuser);
279                 if (!pw) {
280                         logger(DEBUG_ALWAYS, LOG_ERR, "unknown user `%s'", switchuser);
281                         return false;
282                 }
283                 uid = pw->pw_uid;
284                 if (initgroups(switchuser, pw->pw_gid) != 0 ||
285                     setgid(pw->pw_gid) != 0) {
286                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
287                                "initgroups", strerror(errno));
288                         return false;
289                 }
290 #ifndef __ANDROID__
291 // Not supported in android NDK
292                 endgrent();
293                 endpwent();
294 #endif
295         }
296         if (do_chroot) {
297                 tzset();        /* for proper timestamps in logs */
298                 if (chroot(confbase) != 0 || chdir("/") != 0) {
299                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
300                                "chroot", strerror(errno));
301                         return false;
302                 }
303                 free(confbase);
304                 confbase = xstrdup("");
305         }
306         if (switchuser)
307                 if (setuid(uid) != 0) {
308                         logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s",
309                                "setuid", strerror(errno));
310                         return false;
311                 }
312 #endif
313         return true;
314 }
315
316 #ifdef HAVE_MINGW
317 # define setpriority(level) !SetPriorityClass(GetCurrentProcess(), (level))
318
319 static void stop_handler(void *data, int flags) {
320         event_exit();
321 }
322
323 static BOOL WINAPI console_ctrl_handler(DWORD type) {
324         logger(DEBUG_ALWAYS, LOG_NOTICE, "Got console shutdown request");
325         if (WSASetEvent(stop_io.event) == FALSE)
326                 abort();
327         return TRUE;
328 }
329 #else
330 # define NORMAL_PRIORITY_CLASS 0
331 # define BELOW_NORMAL_PRIORITY_CLASS 10
332 # define HIGH_PRIORITY_CLASS -10
333 # define setpriority(level) (setpriority(PRIO_PROCESS, 0, (level)))
334 #endif
335
336 int main(int argc, char **argv) {
337         program_name = argv[0];
338
339         if(!parse_options(argc, argv))
340                 return 1;
341
342         make_names(true);
343
344         if(show_version) {
345                 printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
346                            BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
347                 printf("Copyright (C) 1998-2015 Ivo Timmermans, Guus Sliepen and others.\n"
348                                 "See the AUTHORS file for a complete list.\n\n"
349                                 "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
350                                 "and you are welcome to redistribute it under certain conditions;\n"
351                                 "see the file COPYING for details.\n");
352
353                 return 0;
354         }
355
356         if(show_help) {
357                 usage(false);
358                 return 0;
359         }
360
361 #ifdef HAVE_MINGW
362         if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
363                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
364                 return 1;
365         }
366 #else
367         // Check if we got an umbilical fd from the process that started us
368         char *umbstr = getenv("TINC_UMBILICAL");
369         if(umbstr) {
370                 umbilical = atoi(umbstr);
371                 if(fcntl(umbilical, F_GETFL) < 0)
372                         umbilical = 0;
373 #ifdef FD_CLOEXEC
374                 if(umbilical)
375                         fcntl(umbilical, F_SETFD, FD_CLOEXEC);
376 #endif
377         }
378 #endif
379
380         openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);
381
382         g_argv = argv;
383
384         if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid())
385                 do_detach = false;
386 #ifdef HAVE_UNSETENV
387         unsetenv("LISTEN_PID");
388 #endif
389
390         init_configuration(&config_tree);
391
392         /* Slllluuuuuuurrrrp! */
393
394         gettimeofday(&now, NULL);
395         srand(now.tv_sec + now.tv_usec);
396         crypto_init();
397
398         if(!read_server_config())
399                 return 1;
400
401 #ifdef HAVE_LZO
402         if(lzo_init() != LZO_E_OK) {
403                 logger(DEBUG_ALWAYS, LOG_ERR, "Error initializing LZO compressor!");
404                 return 1;
405         }
406 #endif
407
408 #ifdef HAVE_MINGW
409         io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
410         if (stop_io.event == FALSE)
411                 abort();
412
413         int result;
414         if(!do_detach || !init_service()) {
415                 SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
416                 result = main2(argc, argv);
417         } else
418                 result = 1;
419
420         if (WSACloseEvent(stop_io.event) == FALSE)
421                 abort();
422         io_del(&stop_io);
423         return result;
424 }
425
426 int main2(int argc, char **argv) {
427 #endif
428         char *priority = NULL;
429
430         if(!detach())
431                 return 1;
432
433 #ifdef HAVE_MLOCKALL
434         /* Lock all pages into memory if requested.
435          * This has to be done after daemon()/fork() so it works for child.
436          * No need to do that in parent as it's very short-lived. */
437         if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
438                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
439                    strerror(errno));
440                 return 1;
441         }
442 #endif
443
444         /* Setup sockets and open device. */
445
446         if(!setup_network())
447                 goto end;
448
449         /* Change process priority */
450
451         if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
452                 if(!strcasecmp(priority, "Normal")) {
453                         if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
454                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
455                                 goto end;
456                         }
457                 } else if(!strcasecmp(priority, "Low")) {
458                         if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
459                                        logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
460                                 goto end;
461                         }
462                 } else if(!strcasecmp(priority, "High")) {
463                         if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
464                                 logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
465                                 goto end;
466                         }
467                 } else {
468                         logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
469                         goto end;
470                 }
471         }
472
473         /* drop privileges */
474         if (!drop_privs())
475                 goto end;
476
477         /* Start main loop. It only exits when tinc is killed. */
478
479         logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");
480
481         if(umbilical) { // snip!
482                 write(umbilical, "", 1);
483                 close(umbilical);
484                 umbilical = 0;
485         }
486
487         try_outgoing_connections();
488
489         status = main_loop();
490
491         /* Shutdown properly. */
492
493 end:
494         close_network_connections();
495
496         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
497
498         free(priority);
499
500         crypto_exit();
501
502         exit_configuration(&config_tree);
503         free(cmdline_conf);
504         free_names();
505
506         return status;
507 }