2 process.c -- process management functions
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2009 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"
35 /* If zero, don't detach from the terminal. */
36 bool do_detach = true;
40 extern char *identname;
41 extern char *pidfilename;
43 extern bool use_logfile;
44 extern volatile bool running;
48 static int saved_debug_level = -1;
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 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(GetLastError()));
110 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
112 logger(LOG_INFO, "%s service installed", identname);
114 if(!StartService(service, 0, NULL))
115 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
117 logger(LOG_INFO, "%s service started", identname);
122 bool remove_service(void) {
123 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
125 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
129 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
132 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
136 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
137 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
139 logger(LOG_INFO, "%s service stopped", identname);
141 if(!DeleteService(service)) {
142 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
146 logger(LOG_INFO, "%s service removed", identname);
151 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
153 case SERVICE_CONTROL_INTERROGATE:
154 SetServiceStatus(statushandle, &status);
156 case SERVICE_CONTROL_STOP:
157 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
159 case SERVICE_CONTROL_SHUTDOWN:
160 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
163 logger(LOG_WARNING, "Got unexpected request %d", request);
164 return ERROR_CALL_NOT_IMPLEMENTED;
169 status.dwWaitHint = 30000;
170 status.dwCurrentState = SERVICE_STOP_PENDING;
171 SetServiceStatus(statushandle, &status);
174 status.dwWaitHint = 0;
175 status.dwCurrentState = SERVICE_STOPPED;
176 SetServiceStatus(statushandle, &status);
182 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
184 extern int main2(int argc, char **argv);
187 status.dwServiceType = SERVICE_WIN32;
188 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
189 status.dwWin32ExitCode = 0;
190 status.dwServiceSpecificExitCode = 0;
191 status.dwCheckPoint = 0;
193 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
196 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
199 status.dwWaitHint = 30000;
200 status.dwCurrentState = SERVICE_START_PENDING;
201 SetServiceStatus(statushandle, &status);
203 status.dwWaitHint = 0;
204 status.dwCurrentState = SERVICE_RUNNING;
205 SetServiceStatus(statushandle, &status);
207 err = main2(argc, argv);
209 status.dwWaitHint = 0;
210 status.dwCurrentState = SERVICE_STOPPED;
211 //status.dwWin32ExitCode = err;
212 SetServiceStatus(statushandle, &status);
218 bool init_service(void) {
219 SERVICE_TABLE_ENTRY services[] = {
220 {identname, run_service},
224 if(!StartServiceCtrlDispatcher(services)) {
225 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
229 logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
238 check for an existing tinc for this net, and write pid to pidfile
240 static bool write_pidfile(void) {
243 pid = check_pid(pidfilename);
247 fprintf(stderr, "A tincd is already running for net `%s' with pid %ld.\n",
250 fprintf(stderr, "A tincd is already running with pid %ld.\n", (long)pid);
254 /* if it's locked, write-protected, or whatever */
255 if(!write_pid(pidfilename)) {
256 fprintf(stderr, "Could write pid file %s: %s\n", pidfilename, strerror(errno));
265 kill older tincd for this net
267 bool kill_other(int signal) {
271 pid = read_pid(pidfilename);
275 fprintf(stderr, "No other tincd is running for net `%s'.\n",
278 fprintf(stderr, "No other tincd is running.\n");
282 errno = 0; /* No error, sometimes errno is only changed on error */
284 /* ESRCH is returned when no process with that pid is found */
285 if(kill(pid, signal) && errno == ESRCH) {
287 fprintf(stderr, "The tincd for net `%s' is no longer running. ",
290 fprintf(stderr, "The tincd is no longer running. ");
292 fprintf(stderr, "Removing stale lock file.\n");
293 remove_pid(pidfilename);
298 return remove_service();
303 Detach from current terminal, write pidfile, kill parent
308 /* First check if we can open a fresh new pidfile */
314 /* If we succeeded in doing that, detach */
322 fprintf(stderr, "Couldn't detach from terminal: %s",
327 /* Now UPDATE the pid in the pidfile, because we changed it... */
329 if(!write_pid(pidfilename)) {
330 fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno));
335 exit(install_service());
339 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
341 logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
342 VERSION, __DATE__, __TIME__, debug_level);
344 xalloc_fail_func = memory_full;
349 bool execute_script(const char *name, char **envp) {
352 char *scriptname, *p;
356 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
358 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
363 scriptname[len - 1] = '\0';
366 /* First check if there is a script */
368 if(access(scriptname + 1, F_OK)) {
374 ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
377 /* Set environment */
379 for(i = 0; envp[i]; i++)
383 scriptname[len - 1] = '\"';
384 status = system(scriptname);
388 /* Unset environment */
390 for(i = 0; envp[i]; i++) {
391 char *e = strchr(envp[i], '=');
393 p = alloca(e - envp[i] + 1);
394 strncpy(p, envp[i], e - envp[i]);
395 p[e - envp[i]] = '\0';
402 if(WIFEXITED(status)) { /* Child exited by itself */
403 if(WEXITSTATUS(status)) {
404 logger(LOG_ERR, "Script %s exited with non-zero status %d",
405 name, WEXITSTATUS(status));
408 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
409 logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
410 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
412 } else { /* Something strange happened */
413 logger(LOG_ERR, "Script %s terminated abnormally", name);
417 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
431 static RETSIGTYPE sigterm_handler(int a) {
432 logger(LOG_NOTICE, "Got %s signal", "TERM");
439 static RETSIGTYPE sigquit_handler(int a) {
440 logger(LOG_NOTICE, "Got %s signal", "QUIT");
447 static RETSIGTYPE fatal_signal_square(int a) {
448 logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
453 static RETSIGTYPE fatal_signal_handler(int a) {
454 struct sigaction act;
455 logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
458 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
460 act.sa_handler = fatal_signal_square;
461 act.sa_mask = emptysigset;
463 sigaction(SIGSEGV, &act, NULL);
465 close_network_connections();
467 remove_pid(pidfilename);
468 execvp(g_argv[0], g_argv);
470 logger(LOG_NOTICE, "Not restarting.");
475 static RETSIGTYPE sighup_handler(int a) {
476 logger(LOG_NOTICE, "Got %s signal", "HUP");
480 static RETSIGTYPE sigint_handler(int a) {
481 logger(LOG_NOTICE, "Got %s signal", "INT");
483 if(saved_debug_level != -1) {
484 logger(LOG_NOTICE, "Reverting to old debug level (%d)",
486 debug_level = saved_debug_level;
487 saved_debug_level = -1;
490 "Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d.",
492 saved_debug_level = debug_level;
497 static RETSIGTYPE sigalrm_handler(int a) {
498 logger(LOG_NOTICE, "Got %s signal", "ALRM");
502 static RETSIGTYPE sigusr1_handler(int a) {
506 static RETSIGTYPE sigusr2_handler(int a) {
513 static RETSIGTYPE sigwinch_handler(int a) {
517 static RETSIGTYPE unexpected_signal_handler(int a) {
518 logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
521 static RETSIGTYPE ignore_signal_handler(int a) {
522 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
527 void (*handler)(int);
529 {SIGHUP, sighup_handler},
530 {SIGTERM, sigterm_handler},
531 {SIGQUIT, sigquit_handler},
532 {SIGSEGV, fatal_signal_handler},
533 {SIGBUS, fatal_signal_handler},
534 {SIGILL, fatal_signal_handler},
535 {SIGPIPE, ignore_signal_handler},
536 {SIGINT, sigint_handler},
537 {SIGUSR1, sigusr1_handler},
538 {SIGUSR2, sigusr2_handler},
539 {SIGCHLD, ignore_signal_handler},
540 {SIGALRM, sigalrm_handler},
541 {SIGWINCH, sigwinch_handler},
546 void setup_signals(void) {
549 struct sigaction act;
551 sigemptyset(&emptysigset);
552 act.sa_handler = NULL;
553 act.sa_mask = emptysigset;
556 /* Set a default signal handler for every signal, errors will be
558 for(i = 1; i < NSIG; i++) {
560 act.sa_handler = SIG_DFL;
562 act.sa_handler = unexpected_signal_handler;
563 sigaction(i, &act, NULL);
566 /* If we didn't detach, allow coredumps */
568 sighandlers[3].handler = SIG_DFL;
570 /* Then, for each known signal that we want to catch, assign a
571 handler to the signal, with error checking this time. */
572 for(i = 0; sighandlers[i].signal; i++) {
573 act.sa_handler = sighandlers[i].handler;
574 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
575 fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
576 sighandlers[i].signal, strsignal(sighandlers[i].signal),