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;
43 extern bool use_logfile;
47 static void memory_full(int size) {
48 logger(LOG_ERR, _("Memory exhausted (couldn't allocate %d bytes), exitting."), size);
53 /* Some functions the less gifted operating systems might lack... */
56 extern char *identname;
57 extern char *program_name;
60 static SC_HANDLE manager = NULL;
61 static SC_HANDLE service = NULL;
62 static SERVICE_STATUS status = {0};
63 static SERVICE_STATUS_HANDLE statushandle = 0;
65 bool install_service(void) {
66 char command[4096] = "\"";
69 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
71 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
73 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
77 if(!strchr(program_name, '\\')) {
78 GetCurrentDirectory(sizeof command - 1, command + 1);
79 strncat(command, "\\", sizeof command - strlen(command));
82 strncat(command, program_name, sizeof command - strlen(command));
84 strncat(command, "\"", sizeof command - strlen(command));
86 for(argp = g_argv + 1; *argp; argp++) {
87 space = strchr(*argp, ' ');
88 strncat(command, " ", sizeof command - strlen(command));
91 strncat(command, "\"", sizeof command - strlen(command));
93 strncat(command, *argp, sizeof command - strlen(command));
96 strncat(command, "\"", sizeof command - strlen(command));
99 service = CreateService(manager, identname, identname,
100 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
101 command, NULL, NULL, NULL, NULL, NULL);
104 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
108 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
110 logger(LOG_INFO, _("%s service installed"), identname);
112 if(!StartService(service, 0, NULL))
113 logger(LOG_WARNING, _("Could not start %s service: %s"), identname, winerror(GetLastError()));
115 logger(LOG_INFO, _("%s service started"), identname);
120 bool remove_service(void) {
121 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
123 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
127 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
130 logger(LOG_ERR, _("Could not open %s service: %s"), identname, winerror(GetLastError()));
134 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
135 logger(LOG_ERR, _("Could not stop %s service: %s"), identname, winerror(GetLastError()));
137 logger(LOG_INFO, _("%s service stopped"), identname);
139 if(!DeleteService(service)) {
140 logger(LOG_ERR, _("Could not remove %s service: %s"), identname, winerror(GetLastError()));
144 logger(LOG_INFO, _("%s service removed"), identname);
149 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
151 case SERVICE_CONTROL_STOP:
152 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
154 case SERVICE_CONTROL_SHUTDOWN:
155 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
158 logger(LOG_WARNING, _("Got unexpected request %d"), request);
159 return ERROR_CALL_NOT_IMPLEMENTED;
162 event_loopexit(NULL);
163 status.dwWaitHint = 30000;
164 status.dwCurrentState = SERVICE_STOP_PENDING;
165 SetServiceStatus(statushandle, &status);
169 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
171 extern int main2(int argc, char **argv);
174 status.dwServiceType = SERVICE_WIN32;
175 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
176 status.dwWin32ExitCode = 0;
177 status.dwServiceSpecificExitCode = 0;
178 status.dwCheckPoint = 0;
180 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
183 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
186 status.dwWaitHint = 30000;
187 status.dwCurrentState = SERVICE_START_PENDING;
188 SetServiceStatus(statushandle, &status);
190 status.dwWaitHint = 0;
191 status.dwCurrentState = SERVICE_RUNNING;
192 SetServiceStatus(statushandle, &status);
194 err = main2(argc, argv);
196 status.dwWaitHint = 0;
197 status.dwCurrentState = SERVICE_STOPPED;
198 //status.dwWin32ExitCode = err;
199 SetServiceStatus(statushandle, &status);
205 bool init_service(void) {
206 SERVICE_TABLE_ENTRY services[] = {
207 {identname, run_service},
211 if(!StartServiceCtrlDispatcher(services)) {
212 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
216 logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
224 Detach from current terminal
238 fprintf(stderr, _("Couldn't detach from terminal: %s"),
244 exit(install_service());
248 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
250 logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
251 VERSION, __DATE__, __TIME__, debug_level);
253 xalloc_fail_func = memory_full;
258 bool execute_script(const char *name, char **envp) {
262 char *scriptname, *p;
268 len = asprintf(&scriptname, "\"%s/%s\"", confbase, name);
270 len = asprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
275 scriptname[len - 1] = '\0';
277 /* First check if there is a script */
279 if(stat(scriptname + 1, &s)) {
284 ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
287 /* Set environment */
289 for(i = 0; envp[i]; i++)
293 scriptname[len - 1] = '\"';
294 status = system(scriptname);
298 /* Unset environment */
300 for(i = 0; envp[i]; i++) {
301 char *e = strchr(envp[i], '=');
303 p = alloca(e - envp[i] + 1);
304 strncpy(p, envp[i], e - envp[i]);
305 p[e - envp[i]] = '\0';
312 if(WIFEXITED(status)) { /* Child exited by itself */
313 if(WEXITSTATUS(status)) {
314 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
315 name, WEXITSTATUS(status));
318 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
319 logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
320 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
322 } else { /* Something strange happened */
323 logger(LOG_ERR, _("Script %s terminated abnormally"), name);
327 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
341 static RETSIGTYPE fatal_signal_square(int a) {
342 logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
348 static RETSIGTYPE fatal_signal_handler(int a) {
349 struct sigaction act;
350 logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
354 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
356 act.sa_handler = fatal_signal_square;
357 act.sa_mask = emptysigset;
359 sigaction(SIGSEGV, &act, NULL);
361 close_network_connections();
364 execvp(g_argv[0], g_argv);
366 logger(LOG_NOTICE, _("Not restarting."));
371 static RETSIGTYPE unexpected_signal_handler(int a) {
372 logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
376 static RETSIGTYPE ignore_signal_handler(int a) {
377 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
382 void (*handler)(int);
384 {SIGSEGV, fatal_signal_handler},
385 {SIGBUS, fatal_signal_handler},
386 {SIGILL, fatal_signal_handler},
387 {SIGPIPE, ignore_signal_handler},
388 {SIGCHLD, ignore_signal_handler},
393 void setup_signals(void) {
396 struct sigaction act;
398 sigemptyset(&emptysigset);
399 act.sa_handler = NULL;
400 act.sa_mask = emptysigset;
403 /* Set a default signal handler for every signal, errors will be
405 for(i = 0; i < NSIG; i++) {
407 act.sa_handler = SIG_DFL;
409 act.sa_handler = unexpected_signal_handler;
410 sigaction(i, &act, NULL);
413 /* If we didn't detach, allow coredumps */
415 sighandlers[0].handler = SIG_DFL;
417 /* Then, for each known signal that we want to catch, assign a
418 handler to the signal, with error checking this time. */
419 for(i = 0; sighandlers[i].signal; i++) {
420 act.sa_handler = sighandlers[i].handler;
421 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
422 fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
423 sighandlers[i].signal, strsignal(sighandlers[i].signal),