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 static void memory_full(int size) {
51 logger(LOG_ERR, "Memory exhausted (couldn't allocate %d bytes), exitting.", size);
55 /* Some functions the less gifted operating systems might lack... */
58 extern char *identname;
59 extern char *program_name;
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;
67 bool install_service(void) {
68 char command[4096] = "\"";
71 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
73 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
75 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
79 if(!strchr(program_name, '\\')) {
80 GetCurrentDirectory(sizeof command - 1, command + 1);
81 strncat(command, "\\", sizeof command - strlen(command));
84 strncat(command, program_name, sizeof command - strlen(command));
86 strncat(command, "\"", sizeof command - strlen(command));
88 for(argp = g_argv + 1; *argp; argp++) {
89 space = strchr(*argp, ' ');
90 strncat(command, " ", sizeof command - strlen(command));
93 strncat(command, "\"", sizeof command - strlen(command));
95 strncat(command, *argp, sizeof command - strlen(command));
98 strncat(command, "\"", sizeof command - strlen(command));
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);
106 DWORD lasterror = GetLastError();
107 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
108 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);
127 bool remove_service(void) {
128 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
130 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
134 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
137 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
141 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
142 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
144 logger(LOG_INFO, "%s service stopped", identname);
146 if(!DeleteService(service)) {
147 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
151 logger(LOG_INFO, "%s service removed", identname);
156 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
158 case SERVICE_CONTROL_INTERROGATE:
159 SetServiceStatus(statushandle, &status);
161 case SERVICE_CONTROL_STOP:
162 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
164 case SERVICE_CONTROL_SHUTDOWN:
165 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
168 logger(LOG_WARNING, "Got unexpected request %d", (int)request);
169 return ERROR_CALL_NOT_IMPLEMENTED;
174 status.dwWaitHint = 30000;
175 status.dwCurrentState = SERVICE_STOP_PENDING;
176 SetServiceStatus(statushandle, &status);
179 status.dwWaitHint = 0;
180 status.dwCurrentState = SERVICE_STOPPED;
181 SetServiceStatus(statushandle, &status);
187 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
188 extern int main2(int argc, char **argv);
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;
196 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
199 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
201 status.dwWaitHint = 30000;
202 status.dwCurrentState = SERVICE_START_PENDING;
203 SetServiceStatus(statushandle, &status);
205 status.dwWaitHint = 0;
206 status.dwCurrentState = SERVICE_RUNNING;
207 SetServiceStatus(statushandle, &status);
211 status.dwWaitHint = 0;
212 status.dwCurrentState = SERVICE_STOPPED;
213 SetServiceStatus(statushandle, &status);
219 bool init_service(void) {
220 SERVICE_TABLE_ENTRY services[] = {
221 {identname, run_service},
225 if(!StartServiceCtrlDispatcher(services)) {
226 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
230 logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
239 check for an existing tinc for this net, and write pid to pidfile
241 static bool write_pidfile(void) {
244 pid = check_pid(pidfilename);
248 fprintf(stderr, "A tincd is already running for net `%s' with pid %ld.\n",
251 fprintf(stderr, "A tincd is already running with pid %ld.\n", (long)pid);
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));
266 kill older tincd for this net
268 bool kill_other(int signal) {
272 pid = read_pid(pidfilename);
276 fprintf(stderr, "No other tincd is running for net `%s'.\n",
279 fprintf(stderr, "No other tincd is running.\n");
283 errno = 0; /* No error, sometimes errno is only changed on error */
285 /* ESRCH is returned when no process with that pid is found */
286 if(kill(pid, signal) && errno == ESRCH) {
288 fprintf(stderr, "The tincd for net `%s' is no longer running. ",
291 fprintf(stderr, "The tincd is no longer running. ");
293 fprintf(stderr, "Removing stale lock file.\n");
294 remove_pid(pidfilename);
299 return remove_service();
304 Detach from current terminal, write pidfile, kill parent
309 /* First check if we can open a fresh new pidfile */
315 /* If we succeeded in doing that, detach */
323 fprintf(stderr, "Couldn't detach from terminal: %s",
328 /* Now UPDATE the pid in the pidfile, because we changed it... */
330 if(!write_pid(pidfilename)) {
331 fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno));
336 exit(install_service());
340 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
342 logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
343 VERSION, __DATE__, __TIME__, debug_level);
345 xalloc_fail_func = memory_full;
351 void unputenv(char *p) {
352 char *e = strchr(p, '=');
356 #ifndef HAVE_UNSETENV
358 // Windows requires putenv("FOO=") to unset %FOO%
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)) {
378 char *data = xstrdup(var);
379 list_insert_tail(&list, data);
384 void putenv(const char *p) {}
385 void unputenv(const char *p) {}
388 bool execute_script(const char *name, char **envp) {
391 char *interpreter = NULL;
392 config_t *cfg_interpreter;
395 cfg_interpreter = lookup_config(config_tree, "ScriptsInterpreter");
397 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
400 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
402 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
407 scriptname[len - 1] = '\0';
409 /* First check if there is a script */
410 if(access(scriptname + 1, F_OK)) {
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)
419 len = xasprintf(&scriptname, "%s \"%s/%s\"", interpreter, confbase, name);
425 ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
427 /* Set environment */
429 for(i = 0; envp[i]; i++)
432 scriptname[len - 1] = '\"';
433 status = system(scriptname);
437 /* Unset environment */
439 for(i = 0; envp[i]; i++)
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));
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)));
454 } else { /* Something strange happened */
455 logger(LOG_ERR, "Script %s terminated abnormally", name);
460 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
473 static RETSIGTYPE sigterm_handler(int a) {
474 logger(LOG_NOTICE, "Got %s signal", "TERM");
481 static RETSIGTYPE sigquit_handler(int a) {
482 logger(LOG_NOTICE, "Got %s signal", "QUIT");
489 static RETSIGTYPE fatal_signal_square(int a) {
490 logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
495 static RETSIGTYPE fatal_signal_handler(int a) {
496 struct sigaction act;
497 logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
500 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
502 act.sa_handler = fatal_signal_square;
503 act.sa_mask = emptysigset;
505 sigaction(SIGSEGV, &act, NULL);
507 close_network_connections();
509 remove_pid(pidfilename);
510 execvp(g_argv[0], g_argv);
512 logger(LOG_NOTICE, "Not restarting.");
517 static RETSIGTYPE sighup_handler(int a) {
518 logger(LOG_NOTICE, "Got %s signal", "HUP");
522 static RETSIGTYPE sigint_handler(int a) {
523 static int saved_debug_level = -1;
525 logger(LOG_NOTICE, "Got %s signal", "INT");
527 if(saved_debug_level != -1) {
528 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
530 debug_level = saved_debug_level;
531 saved_debug_level = -1;
534 "Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d.",
536 saved_debug_level = debug_level;
541 static RETSIGTYPE sigalrm_handler(int a) {
542 logger(LOG_NOTICE, "Got %s signal", "ALRM");
546 static RETSIGTYPE sigusr1_handler(int a) {
550 static RETSIGTYPE sigusr2_handler(int a) {
557 static RETSIGTYPE sigwinch_handler(int a) {
561 static RETSIGTYPE unexpected_signal_handler(int a) {
562 logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
565 static RETSIGTYPE ignore_signal_handler(int a) {
566 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
571 void (*handler)(int);
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},
591 void setup_signals(void) {
594 struct sigaction act;
596 sigemptyset(&emptysigset);
597 act.sa_handler = NULL;
598 act.sa_mask = emptysigset;
601 /* Set a default signal handler for every signal, errors will be
603 for(i = 1; i < NSIG; i++) {
605 act.sa_handler = SIG_DFL;
607 act.sa_handler = unexpected_signal_handler;
608 sigaction(i, &act, NULL);
611 /* If we didn't detach, allow coredumps */
613 sighandlers[3].handler = SIG_DFL;
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),