Only check for -fno-strict-overflow if -fwrapv does not work.
[tinc] / src / process.c
1 /*
2     process.c -- process management functions
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2015 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include "conf.h"
24 #include "connection.h"
25 #include "device.h"
26 #include "edge.h"
27 #include "logger.h"
28 #include "net.h"
29 #include "node.h"
30 #include "pidfile.h"
31 #include "process.h"
32 #include "subnet.h"
33 #include "utils.h"
34 #include "xalloc.h"
35
36 /* If zero, don't detach from the terminal. */
37 bool do_detach = true;
38 bool sighup = false;
39 bool sigalrm = false;
40
41 extern char *identname;
42 extern char *pidfilename;
43 extern char **g_argv;
44 extern bool use_logfile;
45
46 #ifndef HAVE_MINGW
47 static sigset_t emptysigset;
48 #endif
49
50 static void memory_full(int size) {
51         logger(LOG_ERR, "Memory exhausted (couldn't allocate %d bytes), exitting.", size);
52         exit(1);
53 }
54
55 /* Some functions the less gifted operating systems might lack... */
56
57 #ifdef HAVE_MINGW
58 extern char *identname;
59 extern char *program_name;
60 extern char **g_argv;
61
62 static SC_HANDLE manager = NULL;
63 static SC_HANDLE service = NULL;
64 static SERVICE_STATUS status = {0};
65 static SERVICE_STATUS_HANDLE statushandle = 0;
66
67 bool install_service(void) {
68         char command[4096] = "\"";
69         char **argp;
70         bool space;
71         SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
72
73         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
74         if(!manager) {
75                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
76                 return false;
77         }
78
79         if(!strchr(program_name, '\\')) {
80                 GetCurrentDirectory(sizeof command - 1, command + 1);
81                 strncat(command, "\\", sizeof command - strlen(command));
82         }
83
84         strncat(command, program_name, sizeof command - strlen(command));
85
86         strncat(command, "\"", sizeof command - strlen(command));
87
88         for(argp = g_argv + 1; *argp; argp++) {
89                 space = strchr(*argp, ' ');
90                 strncat(command, " ", sizeof command - strlen(command));
91                 
92                 if(space)
93                         strncat(command, "\"", sizeof command - strlen(command));
94                 
95                 strncat(command, *argp, sizeof command - strlen(command));
96
97                 if(space)
98                         strncat(command, "\"", sizeof command - strlen(command));
99         }
100
101         service = CreateService(manager, identname, identname,
102                         SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
103                         command, NULL, NULL, NULL, NULL, NULL);
104         
105         if(!service) {
106                 DWORD lasterror = GetLastError();
107                 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
108                 if(lasterror != ERROR_SERVICE_EXISTS)
109                         return false;
110         }
111
112         if(service) {
113                 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
114                 logger(LOG_INFO, "%s service installed", identname);
115         } else {
116                 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
117         }
118
119         if(!StartService(service, 0, NULL))
120                 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
121         else
122                 logger(LOG_INFO, "%s service started", identname);
123
124         return true;
125 }
126
127 bool remove_service(void) {
128         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
129         if(!manager) {
130                 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
131                 return false;
132         }
133
134         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
135
136         if(!service) {
137                 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
138                 return false;
139         }
140
141         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
142                 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
143         else
144                 logger(LOG_INFO, "%s service stopped", identname);
145
146         if(!DeleteService(service)) {
147                 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
148                 return false;
149         }
150
151         logger(LOG_INFO, "%s service removed", identname);
152
153         return true;
154 }
155
156 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
157         switch(request) {
158                 case SERVICE_CONTROL_INTERROGATE:
159                         SetServiceStatus(statushandle, &status);
160                         return NO_ERROR;
161                 case SERVICE_CONTROL_STOP:
162                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
163                         break;
164                 case SERVICE_CONTROL_SHUTDOWN:
165                         logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
166                         break;
167                 default:
168                         logger(LOG_WARNING, "Got unexpected request %d", (int)request);
169                         return ERROR_CALL_NOT_IMPLEMENTED;
170         }
171
172         if(running) {
173                 running = false;
174                 status.dwWaitHint = 30000; 
175                 status.dwCurrentState = SERVICE_STOP_PENDING; 
176                 SetServiceStatus(statushandle, &status);
177                 return NO_ERROR;
178         } else {
179                 status.dwWaitHint = 0; 
180                 status.dwCurrentState = SERVICE_STOPPED; 
181                 SetServiceStatus(statushandle, &status);
182                 exit(1);
183         }
184
185 }
186
187 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
188         extern int main2(int argc, char **argv);
189
190         status.dwServiceType = SERVICE_WIN32; 
191         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
192         status.dwWin32ExitCode = 0; 
193         status.dwServiceSpecificExitCode = 0; 
194         status.dwCheckPoint = 0; 
195
196         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 
197
198         if (!statushandle) {
199                 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
200         } else {
201                 status.dwWaitHint = 30000; 
202                 status.dwCurrentState = SERVICE_START_PENDING; 
203                 SetServiceStatus(statushandle, &status);
204
205                 status.dwWaitHint = 0; 
206                 status.dwCurrentState = SERVICE_RUNNING;
207                 SetServiceStatus(statushandle, &status);
208
209                 main2(argc, argv);
210
211                 status.dwWaitHint = 0;
212                 status.dwCurrentState = SERVICE_STOPPED; 
213                 SetServiceStatus(statushandle, &status);
214         }
215
216         return;
217 }
218
219 bool init_service(void) {
220         SERVICE_TABLE_ENTRY services[] = {
221                 {identname, run_service},
222                 {NULL, NULL}
223         };
224
225         if(!StartServiceCtrlDispatcher(services)) {
226                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
227                         return false;
228                 }
229                 else
230                         logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
231         }
232
233         return true;
234 }
235 #endif
236
237 #ifndef HAVE_MINGW
238 /*
239   check for an existing tinc for this net, and write pid to pidfile
240 */
241 static bool write_pidfile(void) {
242         pid_t pid;
243
244         pid = check_pid(pidfilename);
245
246         if(pid) {
247                 if(netname)
248                         fprintf(stderr, "A tincd is already running for net `%s' with pid %ld.\n",
249                                         netname, (long)pid);
250                 else
251                         fprintf(stderr, "A tincd is already running with pid %ld.\n", (long)pid);
252                 return false;
253         }
254
255         /* if it's locked, write-protected, or whatever */
256         if(!write_pid(pidfilename)) {
257                 fprintf(stderr, "Couldn't write pid file %s: %s\n", pidfilename, strerror(errno));
258                 return false;
259         }
260
261         return true;
262 }
263 #endif
264
265 /*
266   kill older tincd for this net
267 */
268 bool kill_other(int signal) {
269 #ifndef HAVE_MINGW
270         pid_t pid;
271
272         pid = read_pid(pidfilename);
273
274         if(!pid) {
275                 if(netname)
276                         fprintf(stderr, "No other tincd is running for net `%s'.\n",
277                                         netname);
278                 else
279                         fprintf(stderr, "No other tincd is running.\n");
280                 return false;
281         }
282
283         errno = 0;                                      /* No error, sometimes errno is only changed on error */
284
285         /* ESRCH is returned when no process with that pid is found */
286         if(kill(pid, signal) && errno == ESRCH) {
287                 if(netname)
288                         fprintf(stderr, "The tincd for net `%s' is no longer running. ",
289                                         netname);
290                 else
291                         fprintf(stderr, "The tincd is no longer running. ");
292
293                 fprintf(stderr, "Removing stale lock file.\n");
294                 remove_pid(pidfilename);
295         }
296
297         return true;
298 #else
299         return remove_service();
300 #endif
301 }
302
303 /*
304   Detach from current terminal, write pidfile, kill parent
305 */
306 bool detach(void) {
307         setup_signals();
308
309         /* First check if we can open a fresh new pidfile */
310
311 #ifndef HAVE_MINGW
312         if(!write_pidfile())
313                 return false;
314
315         /* If we succeeded in doing that, detach */
316
317         closelogger();
318 #endif
319
320         if(do_detach) {
321 #ifndef HAVE_MINGW
322                 if(daemon(0, 0)) {
323                         fprintf(stderr, "Couldn't detach from terminal: %s",
324                                         strerror(errno));
325                         return false;
326                 }
327
328                 /* Now UPDATE the pid in the pidfile, because we changed it... */
329
330                 if(!write_pid(pidfilename)) {
331                         fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno));
332                         return false;
333                 }
334 #else
335                 if(!statushandle)
336                         exit(install_service());
337 #endif
338         }
339
340         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
341
342         logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
343                            VERSION, __DATE__, __TIME__, debug_level);
344
345         xalloc_fail_func = memory_full;
346
347         return true;
348 }
349
350 #ifdef HAVE_PUTENV
351 void unputenv(char *p) {
352         char *e = strchr(p, '=');
353         if(!e)
354                 return;
355         int len = e - p;
356 #ifndef HAVE_UNSETENV
357 #ifdef HAVE_MINGW
358         // Windows requires putenv("FOO=") to unset %FOO%
359         len++;
360 #endif
361 #endif
362         char var[len];
363         strncpy(var, p, len);
364 #ifdef HAVE_UNSETENV
365         unsetenv(var);
366 #else
367         // We must keep what we putenv() around in memory.
368         // To do this without memory leaks, keep things in a list and reuse if possible.
369         static list_t list = {};
370         for(list_node_t *node = list->head; node; node++) {
371                 char *data = node->data;
372                 if(!strcmp(data, var)) {
373                         putenv(data);
374                         return;
375                 }
376         }
377         char *data = strcmp(var);
378         list_insert_tail(list, data);
379         putenv(data);
380 #endif
381 }
382 #else
383 void putenv(const char *p) {}
384 void unputenv(const char *p) {}
385 #endif
386
387 bool execute_script(const char *name, char **envp) {
388 #ifdef HAVE_SYSTEM
389         char *scriptname;
390         char *interpreter = NULL;
391         config_t *cfg_interpreter;
392         int status, len, i;
393
394         cfg_interpreter = lookup_config(config_tree, "ScriptsInterpreter");
395 #ifndef HAVE_MINGW
396         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
397 #else
398         if(cfg_interpreter)
399                 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
400         else
401                 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
402 #endif
403         if(len < 0)
404                 return false;
405
406         scriptname[len - 1] = '\0';
407
408         /* First check if there is a script */
409         if(access(scriptname + 1, F_OK)) {
410                 free(scriptname);
411                 return true;
412         }
413
414         // Custom scripts interpreter
415         if(get_config_string(cfg_interpreter, &interpreter)) {
416                 // Force custom scripts interpreter allowing execution of scripts on android without execution flag (such as on /sdcard)
417                 free(scriptname);
418                 len = xasprintf(&scriptname, "%s \"%s/%s\"", interpreter, confbase, name);
419                 free(interpreter);
420                 if(len < 0)
421                         return false;
422         }
423
424         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
425
426         /* Set environment */
427         
428         for(i = 0; envp[i]; i++)
429                 putenv(envp[i]);
430
431         scriptname[len - 1] = '\"';
432         status = system(scriptname);
433
434         free(scriptname);
435
436         /* Unset environment */
437
438         for(i = 0; envp[i]; i++)
439                 unputenv(envp[i]);
440
441         if(status != -1) {
442 #ifdef WEXITSTATUS
443                 if(WIFEXITED(status)) { /* Child exited by itself */
444                         if(WEXITSTATUS(status)) {
445                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
446                                            name, WEXITSTATUS(status));
447                                 return false;
448                         }
449                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
450                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
451                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
452                         return false;
453                 } else {                        /* Something strange happened */
454                         logger(LOG_ERR, "Script %s terminated abnormally", name);
455                         return false;
456                 }
457 #endif
458         } else {
459                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
460                 return false;
461         }
462 #endif
463         return true;
464 }
465
466
467 /*
468   Signal handlers.
469 */
470
471 #ifndef HAVE_MINGW
472 static RETSIGTYPE sigterm_handler(int a) {
473         logger(LOG_NOTICE, "Got %s signal", "TERM");
474         if(running)
475                 running = false;
476         else
477                 exit(1);
478 }
479
480 static RETSIGTYPE sigquit_handler(int a) {
481         logger(LOG_NOTICE, "Got %s signal", "QUIT");
482         if(running)
483                 running = false;
484         else
485                 exit(1);
486 }
487
488 static RETSIGTYPE fatal_signal_square(int a) {
489         logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
490                    strsignal(a));
491         exit(1);
492 }
493
494 static RETSIGTYPE fatal_signal_handler(int a) {
495         struct sigaction act;
496         logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
497
498         if(do_detach) {
499                 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
500
501                 act.sa_handler = fatal_signal_square;
502                 act.sa_mask = emptysigset;
503                 act.sa_flags = 0;
504                 sigaction(SIGSEGV, &act, NULL);
505
506                 close_network_connections();
507                 sleep(5);
508                 remove_pid(pidfilename);
509                 execvp(g_argv[0], g_argv);
510         } else {
511                 logger(LOG_NOTICE, "Not restarting.");
512                 exit(1);
513         }
514 }
515
516 static RETSIGTYPE sighup_handler(int a) {
517         logger(LOG_NOTICE, "Got %s signal", "HUP");
518         sighup = true;
519 }
520
521 static RETSIGTYPE sigint_handler(int a) {
522         static int saved_debug_level = -1;
523
524         logger(LOG_NOTICE, "Got %s signal", "INT");
525
526         if(saved_debug_level != -1) {
527                 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
528                         saved_debug_level);
529                 debug_level = saved_debug_level;
530                 saved_debug_level = -1;
531         } else {
532                 logger(LOG_NOTICE,
533                         "Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d.",
534                         debug_level);
535                 saved_debug_level = debug_level;
536                 debug_level = 5;
537         }
538 }
539
540 static RETSIGTYPE sigalrm_handler(int a) {
541         logger(LOG_NOTICE, "Got %s signal", "ALRM");
542         sigalrm = true;
543 }
544
545 static RETSIGTYPE sigusr1_handler(int a) {
546         dump_connections();
547 }
548
549 static RETSIGTYPE sigusr2_handler(int a) {
550         devops.dump_stats();
551         dump_nodes();
552         dump_edges();
553         dump_subnets();
554 }
555
556 static RETSIGTYPE sigwinch_handler(int a) {
557         do_purge = true;
558 }
559
560 static RETSIGTYPE unexpected_signal_handler(int a) {
561         logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
562 }
563
564 static RETSIGTYPE ignore_signal_handler(int a) {
565         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
566 }
567
568 static struct {
569         int signal;
570         void (*handler)(int);
571 } sighandlers[] = {
572         {SIGHUP, sighup_handler},
573         {SIGTERM, sigterm_handler},
574         {SIGQUIT, sigquit_handler},
575         {SIGSEGV, fatal_signal_handler},
576         {SIGBUS, fatal_signal_handler},
577         {SIGILL, fatal_signal_handler},
578         {SIGPIPE, ignore_signal_handler},
579         {SIGINT, sigint_handler},
580         {SIGUSR1, sigusr1_handler},
581         {SIGUSR2, sigusr2_handler},
582         {SIGCHLD, ignore_signal_handler},
583         {SIGALRM, sigalrm_handler},
584         {SIGWINCH, sigwinch_handler},
585         {SIGABRT, SIG_DFL},
586         {0, NULL}
587 };
588 #endif
589
590 void setup_signals(void) {
591 #ifndef HAVE_MINGW
592         int i;
593         struct sigaction act;
594
595         sigemptyset(&emptysigset);
596         act.sa_handler = NULL;
597         act.sa_mask = emptysigset;
598         act.sa_flags = 0;
599
600         /* Set a default signal handler for every signal, errors will be
601            ignored. */
602         for(i = 1; i < NSIG; i++) {
603                 if(!do_detach)
604                         act.sa_handler = SIG_DFL;
605                 else
606                         act.sa_handler = unexpected_signal_handler;
607                 sigaction(i, &act, NULL);
608         }
609
610         /* If we didn't detach, allow coredumps */
611         if(!do_detach)
612                 sighandlers[3].handler = SIG_DFL;
613
614         /* Then, for each known signal that we want to catch, assign a
615            handler to the signal, with error checking this time. */
616         for(i = 0; sighandlers[i].signal; i++) {
617                 act.sa_handler = sighandlers[i].handler;
618                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
619                         fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
620                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
621                                         strerror(errno));
622         }
623 #endif
624 }