2 process.c -- process management functions
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2015 Guus Sliepen <guus@tinc-vpn.org>
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.
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.
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.
24 #include "connection.h"
36 /* If zero, don't detach from the terminal. */
37 bool do_detach = true;
41 extern char *identname;
42 extern char *pidfilename;
44 extern bool use_logfile;
47 static sigset_t emptysigset;
50 /* Some functions the less gifted operating systems might lack... */
53 extern char *identname;
54 extern char *program_name;
57 static SC_HANDLE manager = NULL;
58 static SC_HANDLE service = NULL;
59 static SERVICE_STATUS status = {0};
60 static SERVICE_STATUS_HANDLE statushandle = 0;
62 bool install_service(void) {
63 char command[4096] = "\"";
66 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
68 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
71 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
75 if(!strchr(program_name, '\\')) {
76 GetCurrentDirectory(sizeof(command) - 1, command + 1);
77 strncat(command, "\\", sizeof(command) - strlen(command));
80 strncat(command, program_name, sizeof(command) - strlen(command));
82 strncat(command, "\"", sizeof(command) - strlen(command));
84 for(argp = g_argv + 1; *argp; argp++) {
85 space = strchr(*argp, ' ');
86 strncat(command, " ", sizeof(command) - strlen(command));
89 strncat(command, "\"", sizeof(command) - strlen(command));
92 strncat(command, *argp, sizeof(command) - strlen(command));
95 strncat(command, "\"", sizeof(command) - strlen(command));
99 service = CreateService(manager, identname, identname,
100 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
101 command, NULL, NULL, NULL, NULL, NULL);
104 DWORD lasterror = GetLastError();
105 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
107 if(lasterror != ERROR_SERVICE_EXISTS) {
113 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
114 logger(LOG_INFO, "%s service installed", identname);
116 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
119 if(!StartService(service, 0, NULL)) {
120 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
122 logger(LOG_INFO, "%s service started", identname);
128 bool remove_service(void) {
129 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
132 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
136 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
139 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
143 if(!ControlService(service, SERVICE_CONTROL_STOP, &status)) {
144 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
146 logger(LOG_INFO, "%s service stopped", identname);
149 if(!DeleteService(service)) {
150 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
154 logger(LOG_INFO, "%s service removed", identname);
159 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
161 case SERVICE_CONTROL_INTERROGATE:
162 SetServiceStatus(statushandle, &status);
165 case SERVICE_CONTROL_STOP:
166 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
169 case SERVICE_CONTROL_SHUTDOWN:
170 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
174 logger(LOG_WARNING, "Got unexpected request %d", (int)request);
175 return ERROR_CALL_NOT_IMPLEMENTED;
180 status.dwWaitHint = 30000;
181 status.dwCurrentState = SERVICE_STOP_PENDING;
182 SetServiceStatus(statushandle, &status);
185 status.dwWaitHint = 0;
186 status.dwCurrentState = SERVICE_STOPPED;
187 SetServiceStatus(statushandle, &status);
193 VOID WINAPI run_service(DWORD argc, LPTSTR *argv) {
194 extern int main2(int argc, char **argv);
196 status.dwServiceType = SERVICE_WIN32;
197 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
198 status.dwWin32ExitCode = 0;
199 status.dwServiceSpecificExitCode = 0;
200 status.dwCheckPoint = 0;
202 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
205 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
207 status.dwWaitHint = 30000;
208 status.dwCurrentState = SERVICE_START_PENDING;
209 SetServiceStatus(statushandle, &status);
211 status.dwWaitHint = 0;
212 status.dwCurrentState = SERVICE_RUNNING;
213 SetServiceStatus(statushandle, &status);
217 status.dwWaitHint = 0;
218 status.dwCurrentState = SERVICE_STOPPED;
219 SetServiceStatus(statushandle, &status);
225 bool init_service(void) {
226 SERVICE_TABLE_ENTRY services[] = {
227 {identname, run_service},
231 if(!StartServiceCtrlDispatcher(services)) {
232 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
235 logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
245 check for an existing tinc for this net, and write pid to pidfile
247 static bool write_pidfile(void) {
250 pid = check_pid(pidfilename);
254 fprintf(stderr, "A tincd is already running for net `%s' with pid %ld.\n",
257 fprintf(stderr, "A tincd is already running with pid %ld.\n", (long)pid);
263 /* if it's locked, write-protected, or whatever */
264 if(!write_pid(pidfilename)) {
265 fprintf(stderr, "Couldn't write pid file %s: %s\n", pidfilename, strerror(errno));
274 kill older tincd for this net
276 bool kill_other(int signal) {
280 pid = read_pid(pidfilename);
284 fprintf(stderr, "No other tincd is running for net `%s'.\n",
287 fprintf(stderr, "No other tincd is running.\n");
293 errno = 0; /* No error, sometimes errno is only changed on error */
295 /* ESRCH is returned when no process with that pid is found */
296 if(kill(pid, signal) && errno == ESRCH) {
298 fprintf(stderr, "The tincd for net `%s' is no longer running. ",
301 fprintf(stderr, "The tincd is no longer running. ");
304 fprintf(stderr, "Removing stale lock file.\n");
305 remove_pid(pidfilename);
310 return remove_service();
315 Detach from current terminal, write pidfile, kill parent
320 /* First check if we can open a fresh new pidfile */
324 if(!write_pidfile()) {
328 /* If we succeeded in doing that, detach */
337 fprintf(stderr, "Couldn't detach from terminal: %s",
342 /* Now UPDATE the pid in the pidfile, because we changed it... */
344 if(!write_pid(pidfilename)) {
345 fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno));
352 exit(install_service());
358 openlogger(identname, use_logfile ? LOGMODE_FILE : (do_detach ? LOGMODE_SYSLOG : LOGMODE_STDERR));
360 logger(LOG_NOTICE, "tincd %s starting, debug level %d",
361 VERSION, debug_level);
367 void unputenv(char *p) {
368 char *e = strchr(p, '=');
375 #ifndef HAVE_UNSETENV
377 // Windows requires putenv("FOO=") to unset %FOO%
387 // We must keep what we putenv() around in memory.
388 // To do this without memory leaks, keep things in a list and reuse if possible.
389 static list_t list = {};
391 for(list_node_t *node = list.head; node; node = node->next) {
392 char *data = node->data;
394 if(!strcmp(data, var)) {
400 char *data = xstrdup(var);
401 list_insert_tail(&list, data);
406 void putenv(const char *p) {}
407 void unputenv(const char *p) {}
410 bool execute_script(const char *name, char **envp) {
413 char *interpreter = NULL;
414 config_t *cfg_interpreter;
417 cfg_interpreter = lookup_config(config_tree, "ScriptsInterpreter");
419 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
422 if(cfg_interpreter) {
423 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
425 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
434 scriptname[len - 1] = '\0';
436 /* First check if there is a script */
437 if(access(scriptname + 1, F_OK)) {
442 // Custom scripts interpreter
443 if(get_config_string(cfg_interpreter, &interpreter)) {
444 // Force custom scripts interpreter allowing execution of scripts on android without execution flag (such as on /sdcard)
446 len = xasprintf(&scriptname, "%s \"%s/%s\"", interpreter, confbase, name);
454 ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
456 /* Set environment */
458 for(i = 0; envp[i]; i++) {
462 scriptname[len - 1] = '\"';
463 status = system(scriptname);
467 /* Unset environment */
469 for(i = 0; envp[i]; i++) {
476 if(WIFEXITED(status)) { /* Child exited by itself */
477 if(WEXITSTATUS(status)) {
478 logger(LOG_ERR, "Script %s exited with non-zero status %d",
479 name, WEXITSTATUS(status));
482 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
483 logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
484 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
486 } else { /* Something strange happened */
487 logger(LOG_ERR, "Script %s terminated abnormally", name);
493 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
507 static RETSIGTYPE sigterm_handler(int a) {
509 logger(LOG_NOTICE, "Got %s signal", "TERM");
518 static RETSIGTYPE sigquit_handler(int a) {
520 logger(LOG_NOTICE, "Got %s signal", "QUIT");
529 static RETSIGTYPE fatal_signal_square(int a) {
530 logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
535 static RETSIGTYPE fatal_signal_handler(int a) {
536 struct sigaction act;
537 logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
540 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
542 act.sa_handler = fatal_signal_square;
543 act.sa_mask = emptysigset;
545 sigaction(SIGSEGV, &act, NULL);
547 close_network_connections();
549 remove_pid(pidfilename);
550 execvp(g_argv[0], g_argv);
552 logger(LOG_NOTICE, "Not restarting.");
557 static RETSIGTYPE sighup_handler(int a) {
559 logger(LOG_NOTICE, "Got %s signal", "HUP");
563 static RETSIGTYPE sigint_handler(int a) {
565 static int saved_debug_level = -1;
567 logger(LOG_NOTICE, "Got %s signal", "INT");
569 if(saved_debug_level != -1) {
570 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
572 debug_level = saved_debug_level;
573 saved_debug_level = -1;
576 "Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d.",
578 saved_debug_level = debug_level;
583 static RETSIGTYPE sigalrm_handler(int a) {
585 logger(LOG_NOTICE, "Got %s signal", "ALRM");
589 static RETSIGTYPE sigusr1_handler(int a) {
594 static RETSIGTYPE sigusr2_handler(int a) {
602 static RETSIGTYPE sigwinch_handler(int a) {
607 static RETSIGTYPE unexpected_signal_handler(int a) {
609 logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
612 static RETSIGTYPE ignore_signal_handler(int a) {
614 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
619 void (*handler)(int);
621 {SIGHUP, sighup_handler},
622 {SIGTERM, sigterm_handler},
623 {SIGQUIT, sigquit_handler},
624 {SIGSEGV, fatal_signal_handler},
625 {SIGBUS, fatal_signal_handler},
626 {SIGILL, fatal_signal_handler},
627 {SIGPIPE, ignore_signal_handler},
628 {SIGINT, sigint_handler},
629 {SIGUSR1, sigusr1_handler},
630 {SIGUSR2, sigusr2_handler},
631 {SIGCHLD, ignore_signal_handler},
632 {SIGALRM, sigalrm_handler},
633 {SIGWINCH, sigwinch_handler},
639 void setup_signals(void) {
642 struct sigaction act;
644 sigemptyset(&emptysigset);
645 act.sa_handler = NULL;
646 act.sa_mask = emptysigset;
649 /* Set a default signal handler for every signal, errors will be
651 for(i = 1; i < NSIG; i++) {
653 act.sa_handler = SIG_DFL;
655 act.sa_handler = unexpected_signal_handler;
658 sigaction(i, &act, NULL);
661 /* If we didn't detach, allow coredumps */
663 sighandlers[3].handler = SIG_DFL;
666 /* Then, for each known signal that we want to catch, assign a
667 handler to the signal, with error checking this time. */
668 for(i = 0; sighandlers[i].signal; i++) {
669 act.sa_handler = sighandlers[i].handler;
671 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
672 fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
673 sighandlers[i].signal, strsignal(sighandlers[i].signal),