2 process.c -- process management functions
3 Copyright (C) 1999-2005 Ivo Timmermans,
4 2000-2006 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.
26 #include "connection.h"
37 /* If zero, don't detach from the terminal. */
38 bool do_detach = true;
41 extern char *identname;
42 extern char *pidfilename;
44 extern bool use_logfile;
48 static void memory_full(int size) {
49 logger(LOG_ERR, _("Memory exhausted (couldn't allocate %d bytes), exitting."), size);
54 /* Some functions the less gifted operating systems might lack... */
57 extern char *identname;
58 extern char *program_name;
61 static SC_HANDLE manager = NULL;
62 static SC_HANDLE service = NULL;
63 static SERVICE_STATUS status = {0};
64 static SERVICE_STATUS_HANDLE statushandle = 0;
66 bool install_service(void) {
67 char command[4096] = "\"";
70 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
72 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
74 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
78 if(!strchr(program_name, '\\')) {
79 GetCurrentDirectory(sizeof command - 1, command + 1);
80 strncat(command, "\\", sizeof command - strlen(command));
83 strncat(command, program_name, sizeof command - strlen(command));
85 strncat(command, "\"", sizeof command - strlen(command));
87 for(argp = g_argv + 1; *argp; argp++) {
88 space = strchr(*argp, ' ');
89 strncat(command, " ", sizeof command - strlen(command));
92 strncat(command, "\"", sizeof command - strlen(command));
94 strncat(command, *argp, sizeof command - strlen(command));
97 strncat(command, "\"", sizeof command - strlen(command));
100 service = CreateService(manager, identname, identname,
101 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
102 command, NULL, NULL, NULL, NULL, NULL);
105 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
109 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
111 logger(LOG_INFO, _("%s service installed"), identname);
113 if(!StartService(service, 0, NULL))
114 logger(LOG_WARNING, _("Could not start %s service: %s"), identname, winerror(GetLastError()));
116 logger(LOG_INFO, _("%s service started"), identname);
121 bool remove_service(void) {
122 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
124 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
128 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
131 logger(LOG_ERR, _("Could not open %s service: %s"), identname, winerror(GetLastError()));
135 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
136 logger(LOG_ERR, _("Could not stop %s service: %s"), identname, winerror(GetLastError()));
138 logger(LOG_INFO, _("%s service stopped"), identname);
140 if(!DeleteService(service)) {
141 logger(LOG_ERR, _("Could not remove %s service: %s"), identname, winerror(GetLastError()));
145 logger(LOG_INFO, _("%s service removed"), identname);
150 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
152 case SERVICE_CONTROL_STOP:
153 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
155 case SERVICE_CONTROL_SHUTDOWN:
156 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
159 logger(LOG_WARNING, _("Got unexpected request %d"), request);
160 return ERROR_CALL_NOT_IMPLEMENTED;
163 event_loopexit(NULL);
164 status.dwWaitHint = 30000;
165 status.dwCurrentState = SERVICE_STOP_PENDING;
166 SetServiceStatus(statushandle, &status);
170 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
172 extern int main2(int argc, char **argv);
175 status.dwServiceType = SERVICE_WIN32;
176 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
177 status.dwWin32ExitCode = 0;
178 status.dwServiceSpecificExitCode = 0;
179 status.dwCheckPoint = 0;
181 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
184 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
187 status.dwWaitHint = 30000;
188 status.dwCurrentState = SERVICE_START_PENDING;
189 SetServiceStatus(statushandle, &status);
191 status.dwWaitHint = 0;
192 status.dwCurrentState = SERVICE_RUNNING;
193 SetServiceStatus(statushandle, &status);
195 err = main2(argc, argv);
197 status.dwWaitHint = 0;
198 status.dwCurrentState = SERVICE_STOPPED;
199 //status.dwWin32ExitCode = err;
200 SetServiceStatus(statushandle, &status);
206 bool init_service(void) {
207 SERVICE_TABLE_ENTRY services[] = {
208 {identname, run_service},
212 if(!StartServiceCtrlDispatcher(services)) {
213 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
217 logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
226 check for an existing tinc for this net, and write pid to pidfile
228 static bool write_pidfile(void) {
233 pid = check_pid(pidfilename);
237 fprintf(stderr, _("A tincd is already running for net `%s' with pid %ld.\n"),
240 fprintf(stderr, _("A tincd is already running with pid %ld.\n"), (long)pid);
244 /* if it's locked, write-protected, or whatever */
245 if(!write_pid(pidfilename)) {
246 fprintf(stderr, _("Could write pid file %s: %s\n"), pidfilename, strerror(errno));
255 kill older tincd for this net
257 bool kill_other(int signal) {
263 pid = read_pid(pidfilename);
267 fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
270 fprintf(stderr, _("No other tincd is running.\n"));
274 errno = 0; /* No error, sometimes errno is only changed on error */
276 /* ESRCH is returned when no process with that pid is found */
277 if(kill(pid, signal) && errno == ESRCH) {
279 fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
282 fprintf(stderr, _("The tincd is no longer running. "));
284 fprintf(stderr, _("Removing stale lock file.\n"));
285 remove_pid(pidfilename);
290 return remove_service();
295 Detach from current terminal, write pidfile, kill parent
302 /* First check if we can open a fresh new pidfile */
308 /* If we succeeded in doing that, detach */
316 fprintf(stderr, _("Couldn't detach from terminal: %s"),
321 /* Now UPDATE the pid in the pidfile, because we changed it... */
323 if(!write_pid(pidfilename)) {
324 fprintf(stderr, _("Could not write pid file %s: %s\n"), pidfilename, strerror(errno));
329 exit(install_service());
333 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
335 logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
336 VERSION, __DATE__, __TIME__, debug_level);
338 xalloc_fail_func = memory_full;
343 bool execute_script(const char *name, char **envp) {
347 char *scriptname, *p;
353 len = asprintf(&scriptname, "\"%s/%s\"", confbase, name);
355 len = asprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
360 scriptname[len - 1] = '\0';
362 /* First check if there is a script */
364 if(stat(scriptname + 1, &s)) {
369 ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
372 /* Set environment */
374 for(i = 0; envp[i]; i++)
378 scriptname[len - 1] = '\"';
379 status = system(scriptname);
383 /* Unset environment */
385 for(i = 0; envp[i]; i++) {
386 char *e = strchr(envp[i], '=');
388 p = alloca(e - envp[i] + 1);
389 strncpy(p, envp[i], e - envp[i]);
390 p[e - envp[i]] = '\0';
397 if(WIFEXITED(status)) { /* Child exited by itself */
398 if(WEXITSTATUS(status)) {
399 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
400 name, WEXITSTATUS(status));
403 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
404 logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
405 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
407 } else { /* Something strange happened */
408 logger(LOG_ERR, _("Script %s terminated abnormally"), name);
412 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
426 static RETSIGTYPE fatal_signal_square(int a) {
427 logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
433 static RETSIGTYPE fatal_signal_handler(int a) {
434 struct sigaction act;
435 logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
439 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
441 act.sa_handler = fatal_signal_square;
442 act.sa_mask = emptysigset;
444 sigaction(SIGSEGV, &act, NULL);
446 close_network_connections();
448 remove_pid(pidfilename);
449 execvp(g_argv[0], g_argv);
451 logger(LOG_NOTICE, _("Not restarting."));
456 static RETSIGTYPE unexpected_signal_handler(int a) {
457 logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
461 static RETSIGTYPE ignore_signal_handler(int a) {
462 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
467 void (*handler)(int);
469 {SIGSEGV, fatal_signal_handler},
470 {SIGBUS, fatal_signal_handler},
471 {SIGILL, fatal_signal_handler},
472 {SIGPIPE, ignore_signal_handler},
473 {SIGCHLD, ignore_signal_handler},
478 void setup_signals(void) {
481 struct sigaction act;
483 sigemptyset(&emptysigset);
484 act.sa_handler = NULL;
485 act.sa_mask = emptysigset;
488 /* Set a default signal handler for every signal, errors will be
490 for(i = 0; i < NSIG; i++) {
492 act.sa_handler = SIG_DFL;
494 act.sa_handler = unexpected_signal_handler;
495 sigaction(i, &act, NULL);
498 /* If we didn't detach, allow coredumps */
500 sighandlers[0].handler = SIG_DFL;
502 /* Then, for each known signal that we want to catch, assign a
503 handler to the signal, with error checking this time. */
504 for(i = 0; sighandlers[i].signal; i++) {
505 act.sa_handler = sighandlers[i].handler;
506 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
507 fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
508 sighandlers[i].signal, strsignal(sighandlers[i].signal),