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;
39 extern char *identname;
41 extern bool use_logfile;
45 static void memory_full(int size) {
46 logger(LOG_ERR, "Memory exhausted (couldn't allocate %d bytes), exitting.", size);
50 /* Some functions the less gifted operating systems might lack... */
53 extern char *identname;
54 extern char *program_name;
57 static SC_HANDLE manager = NULL;
58 static SC_HANDLE service = NULL;
59 static SERVICE_STATUS status = {0};
60 static SERVICE_STATUS_HANDLE statushandle = 0;
62 bool install_service(void) {
63 char command[4096] = "\"";
66 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
68 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
70 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
74 if(!strchr(program_name, '\\')) {
75 GetCurrentDirectory(sizeof command - 1, command + 1);
76 strncat(command, "\\", sizeof command - strlen(command));
79 strncat(command, program_name, sizeof command - strlen(command));
81 strncat(command, "\"", sizeof command - strlen(command));
83 for(argp = g_argv + 1; *argp; argp++) {
84 space = strchr(*argp, ' ');
85 strncat(command, " ", sizeof command - strlen(command));
88 strncat(command, "\"", sizeof command - strlen(command));
90 strncat(command, *argp, sizeof command - strlen(command));
93 strncat(command, "\"", sizeof command - strlen(command));
96 service = CreateService(manager, identname, identname,
97 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
98 command, NULL, NULL, NULL, NULL, NULL);
101 DWORD lasterror = GetLastError();
102 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
103 if(lasterror != ERROR_SERVICE_EXISTS)
108 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
109 logger(LOG_INFO, "%s service installed", identname);
111 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
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;
167 event_loopexit(NULL);
168 status.dwWaitHint = 30000;
169 status.dwCurrentState = SERVICE_STOP_PENDING;
170 SetServiceStatus(statushandle, &status);
174 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
176 extern int main2(int argc, char **argv);
179 status.dwServiceType = SERVICE_WIN32;
180 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
181 status.dwWin32ExitCode = 0;
182 status.dwServiceSpecificExitCode = 0;
183 status.dwCheckPoint = 0;
185 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
188 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
191 status.dwWaitHint = 30000;
192 status.dwCurrentState = SERVICE_START_PENDING;
193 SetServiceStatus(statushandle, &status);
195 status.dwWaitHint = 0;
196 status.dwCurrentState = SERVICE_RUNNING;
197 SetServiceStatus(statushandle, &status);
199 err = main2(argc, argv);
201 status.dwWaitHint = 0;
202 status.dwCurrentState = SERVICE_STOPPED;
203 //status.dwWin32ExitCode = err;
204 SetServiceStatus(statushandle, &status);
210 bool init_service(void) {
211 SERVICE_TABLE_ENTRY services[] = {
212 {identname, run_service},
216 if(!StartServiceCtrlDispatcher(services)) {
217 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
221 logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
229 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) {
264 char *scriptname, *p;
268 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
270 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
275 scriptname[len - 1] = '\0';
278 /* First check if there is a script */
280 if(access(scriptname + 1, F_OK)) {
286 ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
289 /* Set environment */
291 for(i = 0; envp[i]; i++)
295 scriptname[len - 1] = '\"';
296 status = system(scriptname);
300 /* Unset environment */
302 for(i = 0; envp[i]; i++) {
303 char *e = strchr(envp[i], '=');
305 p = alloca(e - envp[i] + 1);
306 strncpy(p, envp[i], e - envp[i]);
307 p[e - envp[i]] = '\0';
314 if(WIFEXITED(status)) { /* Child exited by itself */
315 if(WEXITSTATUS(status)) {
316 logger(LOG_ERR, "Script %s exited with non-zero status %d",
317 name, WEXITSTATUS(status));
320 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
321 logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
322 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
324 } else { /* Something strange happened */
325 logger(LOG_ERR, "Script %s terminated abnormally", name);
329 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
343 static RETSIGTYPE fatal_signal_square(int a) {
344 logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
349 static RETSIGTYPE fatal_signal_handler(int a) {
350 struct sigaction act;
351 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));
375 static RETSIGTYPE ignore_signal_handler(int a) {
376 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
381 void (*handler)(int);
383 {SIGSEGV, fatal_signal_handler},
384 {SIGBUS, fatal_signal_handler},
385 {SIGILL, fatal_signal_handler},
386 {SIGPIPE, ignore_signal_handler},
387 {SIGCHLD, ignore_signal_handler},
392 void setup_signals(void) {
395 struct sigaction act;
397 sigemptyset(&emptysigset);
398 act.sa_handler = NULL;
399 act.sa_mask = emptysigset;
402 /* Set a default signal handler for every signal, errors will be
404 for(i = 1; i < NSIG; i++) {
406 act.sa_handler = SIG_DFL;
408 act.sa_handler = unexpected_signal_handler;
409 sigaction(i, &act, NULL);
412 /* If we didn't detach, allow coredumps */
414 sighandlers[0].handler = SIG_DFL;
416 /* Then, for each known signal that we want to catch, assign a
417 handler to the signal, with error checking this time. */
418 for(i = 0; sighandlers[i].signal; i++) {
419 act.sa_handler = sighandlers[i].handler;
420 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
421 fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
422 sighandlers[i].signal, strsignal(sighandlers[i].signal),