Set KillMode=mixed in the systemd service file.
[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 starting, debug level %d",
343                            VERSION, 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 + 1];
363         memcpy(var, p, len);
364         var[len] = 0;
365 #ifdef HAVE_UNSETENV
366         unsetenv(var);
367 #else
368         // We must keep what we putenv() around in memory.
369         // To do this without memory leaks, keep things in a list and reuse if possible.
370         static list_t list = {};
371         for(list_node_t *node = list.head; node; node = node->next) {
372                 char *data = node->data;
373                 if(!strcmp(data, var)) {
374                         putenv(data);
375                         return;
376                 }
377         }
378         char *data = xstrdup(var);
379         list_insert_tail(&list, data);
380         putenv(data);
381 #endif
382 }
383 #else
384 void putenv(const char *p) {}
385 void unputenv(const char *p) {}
386 #endif
387
388 bool execute_script(const char *name, char **envp) {
389 #ifdef HAVE_SYSTEM
390         char *scriptname;
391         char *interpreter = NULL;
392         config_t *cfg_interpreter;
393         int status, len, i;
394
395         cfg_interpreter = lookup_config(config_tree, "ScriptsInterpreter");
396 #ifndef HAVE_MINGW
397         len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
398 #else
399         if(cfg_interpreter)
400                 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
401         else
402                 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
403 #endif
404         if(len < 0)
405                 return false;
406
407         scriptname[len - 1] = '\0';
408
409         /* First check if there is a script */
410         if(access(scriptname + 1, F_OK)) {
411                 free(scriptname);
412                 return true;
413         }
414
415         // Custom scripts interpreter
416         if(get_config_string(cfg_interpreter, &interpreter)) {
417                 // Force custom scripts interpreter allowing execution of scripts on android without execution flag (such as on /sdcard)
418                 free(scriptname);
419                 len = xasprintf(&scriptname, "%s \"%s/%s\"", interpreter, confbase, name);
420                 free(interpreter);
421                 if(len < 0)
422                         return false;
423         }
424
425         ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
426
427         /* Set environment */
428         
429         for(i = 0; envp[i]; i++)
430                 putenv(envp[i]);
431
432         scriptname[len - 1] = '\"';
433         status = system(scriptname);
434
435         free(scriptname);
436
437         /* Unset environment */
438
439         for(i = 0; envp[i]; i++)
440                 unputenv(envp[i]);
441
442         if(status != -1) {
443 #ifdef WEXITSTATUS
444                 if(WIFEXITED(status)) { /* Child exited by itself */
445                         if(WEXITSTATUS(status)) {
446                                 logger(LOG_ERR, "Script %s exited with non-zero status %d",
447                                            name, WEXITSTATUS(status));
448                                 return false;
449                         }
450                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
451                         logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
452                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
453                         return false;
454                 } else {                        /* Something strange happened */
455                         logger(LOG_ERR, "Script %s terminated abnormally", name);
456                         return false;
457                 }
458 #endif
459         } else {
460                 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
461                 return false;
462         }
463 #endif
464         return true;
465 }
466
467
468 /*
469   Signal handlers.
470 */
471
472 #ifndef HAVE_MINGW
473 static RETSIGTYPE sigterm_handler(int a) {
474         logger(LOG_NOTICE, "Got %s signal", "TERM");
475         if(running)
476                 running = false;
477         else
478                 exit(1);
479 }
480
481 static RETSIGTYPE sigquit_handler(int a) {
482         logger(LOG_NOTICE, "Got %s signal", "QUIT");
483         if(running)
484                 running = false;
485         else
486                 exit(1);
487 }
488
489 static RETSIGTYPE fatal_signal_square(int a) {
490         logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
491                    strsignal(a));
492         exit(1);
493 }
494
495 static RETSIGTYPE fatal_signal_handler(int a) {
496         struct sigaction act;
497         logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
498
499         if(do_detach) {
500                 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
501
502                 act.sa_handler = fatal_signal_square;
503                 act.sa_mask = emptysigset;
504                 act.sa_flags = 0;
505                 sigaction(SIGSEGV, &act, NULL);
506
507                 close_network_connections();
508                 sleep(5);
509                 remove_pid(pidfilename);
510                 execvp(g_argv[0], g_argv);
511         } else {
512                 logger(LOG_NOTICE, "Not restarting.");
513                 exit(1);
514         }
515 }
516
517 static RETSIGTYPE sighup_handler(int a) {
518         logger(LOG_NOTICE, "Got %s signal", "HUP");
519         sighup = true;
520 }
521
522 static RETSIGTYPE sigint_handler(int a) {
523         static int saved_debug_level = -1;
524
525         logger(LOG_NOTICE, "Got %s signal", "INT");
526
527         if(saved_debug_level != -1) {
528                 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
529                         saved_debug_level);
530                 debug_level = saved_debug_level;
531                 saved_debug_level = -1;
532         } else {
533                 logger(LOG_NOTICE,
534                         "Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d.",
535                         debug_level);
536                 saved_debug_level = debug_level;
537                 debug_level = 5;
538         }
539 }
540
541 static RETSIGTYPE sigalrm_handler(int a) {
542         logger(LOG_NOTICE, "Got %s signal", "ALRM");
543         sigalrm = true;
544 }
545
546 static RETSIGTYPE sigusr1_handler(int a) {
547         dump_connections();
548 }
549
550 static RETSIGTYPE sigusr2_handler(int a) {
551         devops.dump_stats();
552         dump_nodes();
553         dump_edges();
554         dump_subnets();
555 }
556
557 static RETSIGTYPE sigwinch_handler(int a) {
558         do_purge = true;
559 }
560
561 static RETSIGTYPE unexpected_signal_handler(int a) {
562         logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
563 }
564
565 static RETSIGTYPE ignore_signal_handler(int a) {
566         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
567 }
568
569 static struct {
570         int signal;
571         void (*handler)(int);
572 } sighandlers[] = {
573         {SIGHUP, sighup_handler},
574         {SIGTERM, sigterm_handler},
575         {SIGQUIT, sigquit_handler},
576         {SIGSEGV, fatal_signal_handler},
577         {SIGBUS, fatal_signal_handler},
578         {SIGILL, fatal_signal_handler},
579         {SIGPIPE, ignore_signal_handler},
580         {SIGINT, sigint_handler},
581         {SIGUSR1, sigusr1_handler},
582         {SIGUSR2, sigusr2_handler},
583         {SIGCHLD, ignore_signal_handler},
584         {SIGALRM, sigalrm_handler},
585         {SIGWINCH, sigwinch_handler},
586         {SIGABRT, SIG_DFL},
587         {0, NULL}
588 };
589 #endif
590
591 void setup_signals(void) {
592 #ifndef HAVE_MINGW
593         int i;
594         struct sigaction act;
595
596         sigemptyset(&emptysigset);
597         act.sa_handler = NULL;
598         act.sa_mask = emptysigset;
599         act.sa_flags = 0;
600
601         /* Set a default signal handler for every signal, errors will be
602            ignored. */
603         for(i = 1; i < NSIG; i++) {
604                 if(!do_detach)
605                         act.sa_handler = SIG_DFL;
606                 else
607                         act.sa_handler = unexpected_signal_handler;
608                 sigaction(i, &act, NULL);
609         }
610
611         /* If we didn't detach, allow coredumps */
612         if(!do_detach)
613                 sighandlers[3].handler = SIG_DFL;
614
615         /* Then, for each known signal that we want to catch, assign a
616            handler to the signal, with error checking this time. */
617         for(i = 0; sighandlers[i].signal; i++) {
618                 act.sa_handler = sighandlers[i].handler;
619                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
620                         fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
621                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
622                                         strerror(errno));
623         }
624 #endif
625 }