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_INTERROGATE:
152 SetServiceStatus(statushandle, &status);
154 case SERVICE_CONTROL_STOP:
155 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
157 case SERVICE_CONTROL_SHUTDOWN:
158 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
161 logger(LOG_WARNING, _("Got unexpected request %d"), request);
162 return ERROR_CALL_NOT_IMPLEMENTED;
165 event_loopexit(NULL);
166 status.dwWaitHint = 30000;
167 status.dwCurrentState = SERVICE_STOP_PENDING;
168 SetServiceStatus(statushandle, &status);
172 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
174 extern int main2(int argc, char **argv);
177 status.dwServiceType = SERVICE_WIN32;
178 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
179 status.dwWin32ExitCode = 0;
180 status.dwServiceSpecificExitCode = 0;
181 status.dwCheckPoint = 0;
183 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
186 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
189 status.dwWaitHint = 30000;
190 status.dwCurrentState = SERVICE_START_PENDING;
191 SetServiceStatus(statushandle, &status);
193 status.dwWaitHint = 0;
194 status.dwCurrentState = SERVICE_RUNNING;
195 SetServiceStatus(statushandle, &status);
197 err = main2(argc, argv);
199 status.dwWaitHint = 0;
200 status.dwCurrentState = SERVICE_STOPPED;
201 //status.dwWin32ExitCode = err;
202 SetServiceStatus(statushandle, &status);
208 bool init_service(void) {
209 SERVICE_TABLE_ENTRY services[] = {
210 {identname, run_service},
214 if(!StartServiceCtrlDispatcher(services)) {
215 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
219 logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
227 Detach from current terminal
241 fprintf(stderr, _("Couldn't detach from terminal: %s"),
247 exit(install_service());
251 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
253 logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
254 VERSION, __DATE__, __TIME__, debug_level);
256 xalloc_fail_func = memory_full;
261 bool execute_script(const char *name, char **envp) {
265 char *scriptname, *p;
271 len = asprintf(&scriptname, "\"%s/%s\"", confbase, name);
273 len = asprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
278 scriptname[len - 1] = '\0';
280 /* First check if there is a script */
282 if(stat(scriptname + 1, &s)) {
287 ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
290 /* Set environment */
292 for(i = 0; envp[i]; i++)
296 scriptname[len - 1] = '\"';
297 status = system(scriptname);
301 /* Unset environment */
303 for(i = 0; envp[i]; i++) {
304 char *e = strchr(envp[i], '=');
306 p = alloca(e - envp[i] + 1);
307 strncpy(p, envp[i], e - envp[i]);
308 p[e - envp[i]] = '\0';
315 if(WIFEXITED(status)) { /* Child exited by itself */
316 if(WEXITSTATUS(status)) {
317 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
318 name, WEXITSTATUS(status));
321 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
322 logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
323 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
325 } else { /* Something strange happened */
326 logger(LOG_ERR, _("Script %s terminated abnormally"), name);
330 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
344 static RETSIGTYPE fatal_signal_square(int a) {
345 logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
351 static RETSIGTYPE fatal_signal_handler(int a) {
352 struct sigaction act;
353 logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
357 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
359 act.sa_handler = fatal_signal_square;
360 act.sa_mask = emptysigset;
362 sigaction(SIGSEGV, &act, NULL);
364 close_network_connections();
367 execvp(g_argv[0], g_argv);
369 logger(LOG_NOTICE, _("Not restarting."));
374 static RETSIGTYPE unexpected_signal_handler(int a) {
375 logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
379 static RETSIGTYPE ignore_signal_handler(int a) {
380 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
385 void (*handler)(int);
387 {SIGSEGV, fatal_signal_handler},
388 {SIGBUS, fatal_signal_handler},
389 {SIGILL, fatal_signal_handler},
390 {SIGPIPE, ignore_signal_handler},
391 {SIGCHLD, ignore_signal_handler},
396 void setup_signals(void) {
399 struct sigaction act;
401 sigemptyset(&emptysigset);
402 act.sa_handler = NULL;
403 act.sa_mask = emptysigset;
406 /* Set a default signal handler for every signal, errors will be
408 for(i = 0; i < NSIG; i++) {
410 act.sa_handler = SIG_DFL;
412 act.sa_handler = unexpected_signal_handler;
413 sigaction(i, &act, NULL);
416 /* If we didn't detach, allow coredumps */
418 sighandlers[0].handler = SIG_DFL;
420 /* Then, for each known signal that we want to catch, assign a
421 handler to the signal, with error checking this time. */
422 for(i = 0; sighandlers[i].signal; i++) {
423 act.sa_handler = sighandlers[i].handler;
424 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
425 fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
426 sighandlers[i].signal, strsignal(sighandlers[i].signal),