2 process.c -- process management functions
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2011 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 int saved_debug_level = -1;
52 static void memory_full(int size) {
53 logger(LOG_ERR, "Memory exhausted (couldn't allocate %d bytes), exitting.", size);
57 /* Some functions the less gifted operating systems might lack... */
60 extern char *identname;
61 extern char *program_name;
64 static SC_HANDLE manager = NULL;
65 static SC_HANDLE service = NULL;
66 static SERVICE_STATUS status = {0};
67 static SERVICE_STATUS_HANDLE statushandle = 0;
69 bool install_service(void) {
70 char command[4096] = "\"";
73 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
75 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
77 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
81 if(!strchr(program_name, '\\')) {
82 GetCurrentDirectory(sizeof command - 1, command + 1);
83 strncat(command, "\\", sizeof command - strlen(command));
86 strncat(command, program_name, sizeof command - strlen(command));
88 strncat(command, "\"", sizeof command - strlen(command));
90 for(argp = g_argv + 1; *argp; argp++) {
91 space = strchr(*argp, ' ');
92 strncat(command, " ", sizeof command - strlen(command));
95 strncat(command, "\"", sizeof command - strlen(command));
97 strncat(command, *argp, sizeof command - strlen(command));
100 strncat(command, "\"", sizeof command - strlen(command));
103 service = CreateService(manager, identname, identname,
104 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
105 command, NULL, NULL, NULL, NULL, NULL);
108 DWORD lasterror = GetLastError();
109 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
110 if(lasterror != ERROR_SERVICE_EXISTS)
115 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
116 logger(LOG_INFO, "%s service installed", identname);
118 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
121 if(!StartService(service, 0, NULL))
122 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
124 logger(LOG_INFO, "%s service started", identname);
129 bool remove_service(void) {
130 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);
148 if(!DeleteService(service)) {
149 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
153 logger(LOG_INFO, "%s service removed", identname);
158 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
160 case SERVICE_CONTROL_INTERROGATE:
161 SetServiceStatus(statushandle, &status);
163 case SERVICE_CONTROL_STOP:
164 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
166 case SERVICE_CONTROL_SHUTDOWN:
167 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
170 logger(LOG_WARNING, "Got unexpected request %d", request);
171 return ERROR_CALL_NOT_IMPLEMENTED;
176 status.dwWaitHint = 30000;
177 status.dwCurrentState = SERVICE_STOP_PENDING;
178 SetServiceStatus(statushandle, &status);
181 status.dwWaitHint = 0;
182 status.dwCurrentState = SERVICE_STOPPED;
183 SetServiceStatus(statushandle, &status);
189 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
191 extern int main2(int argc, char **argv);
194 status.dwServiceType = SERVICE_WIN32;
195 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
196 status.dwWin32ExitCode = 0;
197 status.dwServiceSpecificExitCode = 0;
198 status.dwCheckPoint = 0;
200 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
203 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
206 status.dwWaitHint = 30000;
207 status.dwCurrentState = SERVICE_START_PENDING;
208 SetServiceStatus(statushandle, &status);
210 status.dwWaitHint = 0;
211 status.dwCurrentState = SERVICE_RUNNING;
212 SetServiceStatus(statushandle, &status);
214 err = main2(argc, argv);
216 status.dwWaitHint = 0;
217 status.dwCurrentState = SERVICE_STOPPED;
218 //status.dwWin32ExitCode = err;
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) {
236 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);
261 /* if it's locked, write-protected, or whatever */
262 if(!write_pid(pidfilename)) {
263 fprintf(stderr, "Could write pid file %s: %s\n", pidfilename, strerror(errno));
272 kill older tincd for this net
274 bool kill_other(int signal) {
278 pid = read_pid(pidfilename);
282 fprintf(stderr, "No other tincd is running for net `%s'.\n",
285 fprintf(stderr, "No other tincd is running.\n");
289 errno = 0; /* No error, sometimes errno is only changed on error */
291 /* ESRCH is returned when no process with that pid is found */
292 if(kill(pid, signal) && errno == ESRCH) {
294 fprintf(stderr, "The tincd for net `%s' is no longer running. ",
297 fprintf(stderr, "The tincd is no longer running. ");
299 fprintf(stderr, "Removing stale lock file.\n");
300 remove_pid(pidfilename);
305 return remove_service();
310 Detach from current terminal, write pidfile, kill parent
315 /* First check if we can open a fresh new pidfile */
321 /* If we succeeded in doing that, detach */
329 fprintf(stderr, "Couldn't detach from terminal: %s",
334 /* Now UPDATE the pid in the pidfile, because we changed it... */
336 if(!write_pid(pidfilename)) {
337 fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno));
342 exit(install_service());
346 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
348 logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
349 VERSION, __DATE__, __TIME__, debug_level);
351 xalloc_fail_func = memory_full;
356 bool execute_script(const char *name, char **envp) {
363 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
365 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
370 scriptname[len - 1] = '\0';
373 /* First check if there is a script */
375 if(access(scriptname + 1, F_OK)) {
381 ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
384 /* Set environment */
386 for(i = 0; envp[i]; i++)
390 scriptname[len - 1] = '\"';
391 status = system(scriptname);
395 /* Unset environment */
397 for(i = 0; envp[i]; i++) {
398 char *e = strchr(envp[i], '=');
400 char p[e - envp[i] + 1];
401 strncpy(p, envp[i], e - envp[i]);
402 p[e - envp[i]] = '\0';
409 if(WIFEXITED(status)) { /* Child exited by itself */
410 if(WEXITSTATUS(status)) {
411 logger(LOG_ERR, "Script %s exited with non-zero status %d",
412 name, WEXITSTATUS(status));
415 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
416 logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
417 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
419 } else { /* Something strange happened */
420 logger(LOG_ERR, "Script %s terminated abnormally", name);
424 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
438 static RETSIGTYPE sigterm_handler(int a) {
439 logger(LOG_NOTICE, "Got %s signal", "TERM");
446 static RETSIGTYPE sigquit_handler(int a) {
447 logger(LOG_NOTICE, "Got %s signal", "QUIT");
454 static RETSIGTYPE fatal_signal_square(int a) {
455 logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
460 static RETSIGTYPE fatal_signal_handler(int a) {
461 struct sigaction act;
462 logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
465 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
467 act.sa_handler = fatal_signal_square;
468 act.sa_mask = emptysigset;
470 sigaction(SIGSEGV, &act, NULL);
472 close_network_connections();
474 remove_pid(pidfilename);
475 execvp(g_argv[0], g_argv);
477 logger(LOG_NOTICE, "Not restarting.");
482 static RETSIGTYPE sighup_handler(int a) {
483 logger(LOG_NOTICE, "Got %s signal", "HUP");
487 static RETSIGTYPE sigint_handler(int a) {
488 logger(LOG_NOTICE, "Got %s signal", "INT");
490 if(saved_debug_level != -1) {
491 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
493 debug_level = saved_debug_level;
494 saved_debug_level = -1;
497 "Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d.",
499 saved_debug_level = debug_level;
504 static RETSIGTYPE sigalrm_handler(int a) {
505 logger(LOG_NOTICE, "Got %s signal", "ALRM");
509 static RETSIGTYPE sigusr1_handler(int a) {
513 static RETSIGTYPE sigusr2_handler(int a) {
520 static RETSIGTYPE sigwinch_handler(int a) {
524 static RETSIGTYPE unexpected_signal_handler(int a) {
525 logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
528 static RETSIGTYPE ignore_signal_handler(int a) {
529 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
534 void (*handler)(int);
536 {SIGHUP, sighup_handler},
537 {SIGTERM, sigterm_handler},
538 {SIGQUIT, sigquit_handler},
539 {SIGSEGV, fatal_signal_handler},
540 {SIGBUS, fatal_signal_handler},
541 {SIGILL, fatal_signal_handler},
542 {SIGPIPE, ignore_signal_handler},
543 {SIGINT, sigint_handler},
544 {SIGUSR1, sigusr1_handler},
545 {SIGUSR2, sigusr2_handler},
546 {SIGCHLD, ignore_signal_handler},
547 {SIGALRM, sigalrm_handler},
548 {SIGWINCH, sigwinch_handler},
554 void setup_signals(void) {
557 struct sigaction act;
559 sigemptyset(&emptysigset);
560 act.sa_handler = NULL;
561 act.sa_mask = emptysigset;
564 /* Set a default signal handler for every signal, errors will be
566 for(i = 1; i < NSIG; i++) {
568 act.sa_handler = SIG_DFL;
570 act.sa_handler = unexpected_signal_handler;
571 sigaction(i, &act, NULL);
574 /* If we didn't detach, allow coredumps */
576 sighandlers[3].handler = SIG_DFL;
578 /* Then, for each known signal that we want to catch, assign a
579 handler to the signal, with error checking this time. */
580 for(i = 0; sighandlers[i].signal; i++) {
581 act.sa_handler = sighandlers[i].handler;
582 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
583 fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
584 sighandlers[i].signal, strsignal(sighandlers[i].signal),