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
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, 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)
52 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 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
112 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
114 logger(LOG_INFO, _("%s service installed"), identname);
116 if(!StartService(service, 0, NULL))
117 logger(LOG_WARNING, _("Could not start %s service: %s"), identname, winerror(GetLastError()));
119 logger(LOG_INFO, _("%s service started"), identname);
124 bool remove_service(void) {
125 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
127 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
131 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
134 logger(LOG_ERR, _("Could not open %s service: %s"), identname, winerror(GetLastError()));
138 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
139 logger(LOG_ERR, _("Could not stop %s service: %s"), identname, winerror(GetLastError()));
141 logger(LOG_INFO, _("%s service stopped"), identname);
143 if(!DeleteService(service)) {
144 logger(LOG_ERR, _("Could not remove %s service: %s"), identname, winerror(GetLastError()));
148 logger(LOG_INFO, _("%s service removed"), identname);
153 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
155 case SERVICE_CONTROL_INTERROGATE:
156 SetServiceStatus(statushandle, &status);
158 case SERVICE_CONTROL_STOP:
159 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
161 case SERVICE_CONTROL_SHUTDOWN:
162 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
165 logger(LOG_WARNING, _("Got unexpected request %d"), request);
166 return ERROR_CALL_NOT_IMPLEMENTED;
171 status.dwWaitHint = 30000;
172 status.dwCurrentState = SERVICE_STOP_PENDING;
173 SetServiceStatus(statushandle, &status);
176 status.dwWaitHint = 0;
177 status.dwCurrentState = SERVICE_STOPPED;
178 SetServiceStatus(statushandle, &status);
184 VOID WINAPI run_service(DWORD argc, LPTSTR* argv)
187 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()));
202 status.dwWaitHint = 30000;
203 status.dwCurrentState = SERVICE_START_PENDING;
204 SetServiceStatus(statushandle, &status);
206 status.dwWaitHint = 0;
207 status.dwCurrentState = SERVICE_RUNNING;
208 SetServiceStatus(statushandle, &status);
210 err = main2(argc, argv);
212 status.dwWaitHint = 0;
213 status.dwCurrentState = SERVICE_STOPPED;
214 //status.dwWin32ExitCode = err;
215 SetServiceStatus(statushandle, &status);
221 bool init_service(void) {
222 SERVICE_TABLE_ENTRY services[] = {
223 {identname, run_service},
227 if(!StartServiceCtrlDispatcher(services)) {
228 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
232 logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
241 check for an existing tinc for this net, and write pid to pidfile
243 static bool write_pidfile(void)
249 pid = check_pid(pidfilename);
253 fprintf(stderr, _("A tincd is already running for net `%s' with pid %ld.\n"),
256 fprintf(stderr, _("A tincd is already running with pid %ld.\n"), (long)pid);
260 /* if it's locked, write-protected, or whatever */
261 if(!write_pid(pidfilename)) {
262 fprintf(stderr, _("Could write pid file %s: %s\n"), pidfilename, strerror(errno));
271 kill older tincd for this net
273 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"));
291 errno = 0; /* No error, sometimes errno is only changed on error */
293 /* ESRCH is returned when no process with that pid is found */
294 if(kill(pid, signal) && errno == ESRCH) {
296 fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
299 fprintf(stderr, _("The tincd is no longer running. "));
301 fprintf(stderr, _("Removing stale lock file.\n"));
302 remove_pid(pidfilename);
307 return remove_service();
312 Detach from current terminal, write pidfile, kill parent
320 /* First check if we can open a fresh new pidfile */
326 /* If we succeeded in doing that, detach */
334 fprintf(stderr, _("Couldn't detach from terminal: %s"),
339 /* Now UPDATE the pid in the pidfile, because we changed it... */
341 if(!write_pid(pidfilename)) {
342 fprintf(stderr, _("Could not write pid file %s: %s\n"), pidfilename, strerror(errno));
347 exit(install_service());
351 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
353 logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
354 VERSION, __DATE__, __TIME__, debug_level);
356 xalloc_fail_func = memory_full;
361 bool execute_script(const char *name, char **envp)
365 char *scriptname, *p;
371 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
373 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
378 scriptname[len - 1] = '\0';
381 /* First check if there is a script */
383 if(access(scriptname + 1, F_OK)) {
389 ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
392 /* Set environment */
394 for(i = 0; envp[i]; i++)
398 scriptname[len - 1] = '\"';
399 status = system(scriptname);
403 /* Unset environment */
405 for(i = 0; envp[i]; i++) {
406 char *e = strchr(envp[i], '=');
408 p = alloca(e - envp[i] + 1);
409 strncpy(p, envp[i], e - envp[i]);
410 p[e - envp[i]] = '\0';
417 if(WIFEXITED(status)) { /* Child exited by itself */
418 if(WEXITSTATUS(status)) {
419 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
420 name, WEXITSTATUS(status));
423 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
424 logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
425 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
427 } else { /* Something strange happened */
428 logger(LOG_ERR, _("Script %s terminated abnormally"), name);
432 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
446 static RETSIGTYPE sigterm_handler(int a)
448 logger(LOG_NOTICE, _("Got %s signal"), "TERM");
455 static RETSIGTYPE sigquit_handler(int a)
457 logger(LOG_NOTICE, _("Got %s signal"), "QUIT");
464 static RETSIGTYPE fatal_signal_square(int a)
466 logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
472 static RETSIGTYPE fatal_signal_handler(int a)
474 struct sigaction act;
475 logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
479 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
481 act.sa_handler = fatal_signal_square;
482 act.sa_mask = emptysigset;
484 sigaction(SIGSEGV, &act, NULL);
486 close_network_connections();
488 remove_pid(pidfilename);
489 execvp(g_argv[0], g_argv);
491 logger(LOG_NOTICE, _("Not restarting."));
496 static RETSIGTYPE sighup_handler(int a)
498 logger(LOG_NOTICE, _("Got %s signal"), "HUP");
502 static RETSIGTYPE sigint_handler(int a)
504 logger(LOG_NOTICE, _("Got %s signal"), "INT");
506 if(saved_debug_level != -1) {
507 logger(LOG_NOTICE, _("Reverting to old debug level (%d)"),
509 debug_level = saved_debug_level;
510 saved_debug_level = -1;
513 _("Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d."),
515 saved_debug_level = debug_level;
520 static RETSIGTYPE sigalrm_handler(int a)
522 logger(LOG_NOTICE, _("Got %s signal"), "ALRM");
526 static RETSIGTYPE sigusr1_handler(int a)
531 static RETSIGTYPE sigusr2_handler(int a)
539 static RETSIGTYPE sigwinch_handler(int a)
544 static RETSIGTYPE unexpected_signal_handler(int a)
546 logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
550 static RETSIGTYPE ignore_signal_handler(int a)
552 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
557 void (*handler)(int);
559 {SIGHUP, sighup_handler},
560 {SIGTERM, sigterm_handler},
561 {SIGQUIT, sigquit_handler},
562 {SIGSEGV, fatal_signal_handler},
563 {SIGBUS, fatal_signal_handler},
564 {SIGILL, fatal_signal_handler},
565 {SIGPIPE, ignore_signal_handler},
566 {SIGINT, sigint_handler},
567 {SIGUSR1, sigusr1_handler},
568 {SIGUSR2, sigusr2_handler},
569 {SIGCHLD, ignore_signal_handler},
570 {SIGALRM, sigalrm_handler},
571 {SIGWINCH, sigwinch_handler},
576 void setup_signals(void)
580 struct sigaction act;
582 sigemptyset(&emptysigset);
583 act.sa_handler = NULL;
584 act.sa_mask = emptysigset;
587 /* Set a default signal handler for every signal, errors will be
589 for(i = 1; i < NSIG; i++) {
591 act.sa_handler = SIG_DFL;
593 act.sa_handler = unexpected_signal_handler;
594 sigaction(i, &act, NULL);
597 /* If we didn't detach, allow coredumps */
599 sighandlers[3].handler = SIG_DFL;
601 /* Then, for each known signal that we want to catch, assign a
602 handler to the signal, with error checking this time. */
603 for(i = 0; sighandlers[i].signal; i++) {
604 act.sa_handler = sighandlers[i].handler;
605 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
606 fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
607 sighandlers[i].signal, strsignal(sighandlers[i].signal),