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 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(GetLastError()));
105 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
107 logger(LOG_INFO, "%s service installed", identname);
109 if(!StartService(service, 0, NULL))
110 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
112 logger(LOG_INFO, "%s service started", identname);
117 bool remove_service(void) {
118 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
120 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
124 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
127 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
131 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
132 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
134 logger(LOG_INFO, "%s service stopped", identname);
136 if(!DeleteService(service)) {
137 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
141 logger(LOG_INFO, "%s service removed", identname);
146 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
148 case SERVICE_CONTROL_INTERROGATE:
149 SetServiceStatus(statushandle, &status);
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
236 fprintf(stderr, "Couldn't detach from terminal: %s",
242 exit(install_service());
246 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
248 logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
249 VERSION, __DATE__, __TIME__, debug_level);
251 xalloc_fail_func = memory_full;
256 bool execute_script(const char *name, char **envp) {
259 char *scriptname, *p;
263 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
265 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
270 scriptname[len - 1] = '\0';
273 /* First check if there is a script */
275 if(access(scriptname + 1, F_OK)) {
281 ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
284 /* Set environment */
286 for(i = 0; envp[i]; i++)
290 scriptname[len - 1] = '\"';
291 status = system(scriptname);
295 /* Unset environment */
297 for(i = 0; envp[i]; i++) {
298 char *e = strchr(envp[i], '=');
300 p = alloca(e - envp[i] + 1);
301 strncpy(p, envp[i], e - envp[i]);
302 p[e - envp[i]] = '\0';
309 if(WIFEXITED(status)) { /* Child exited by itself */
310 if(WEXITSTATUS(status)) {
311 logger(LOG_ERR, "Script %s exited with non-zero status %d",
312 name, WEXITSTATUS(status));
315 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
316 logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
317 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
319 } else { /* Something strange happened */
320 logger(LOG_ERR, "Script %s terminated abnormally", name);
324 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
338 static RETSIGTYPE fatal_signal_square(int a) {
339 logger(LOG_ERR, "Got another fatal signal %d (%s): not restarting.", a,
344 static RETSIGTYPE fatal_signal_handler(int a) {
345 struct sigaction act;
346 logger(LOG_ERR, "Got fatal signal %d (%s)", a, strsignal(a));
349 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
351 act.sa_handler = fatal_signal_square;
352 act.sa_mask = emptysigset;
354 sigaction(SIGSEGV, &act, NULL);
356 close_network_connections();
359 execvp(g_argv[0], g_argv);
361 logger(LOG_NOTICE, "Not restarting.");
366 static RETSIGTYPE unexpected_signal_handler(int a) {
367 logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
370 static RETSIGTYPE ignore_signal_handler(int a) {
371 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
376 void (*handler)(int);
378 {SIGSEGV, fatal_signal_handler},
379 {SIGBUS, fatal_signal_handler},
380 {SIGILL, fatal_signal_handler},
381 {SIGPIPE, ignore_signal_handler},
382 {SIGCHLD, ignore_signal_handler},
387 void setup_signals(void) {
390 struct sigaction act;
392 sigemptyset(&emptysigset);
393 act.sa_handler = NULL;
394 act.sa_mask = emptysigset;
397 /* Set a default signal handler for every signal, errors will be
399 for(i = 1; i < NSIG; i++) {
401 act.sa_handler = SIG_DFL;
403 act.sa_handler = unexpected_signal_handler;
404 sigaction(i, &act, NULL);
407 /* If we didn't detach, allow coredumps */
409 sighandlers[0].handler = SIG_DFL;
411 /* Then, for each known signal that we want to catch, assign a
412 handler to the signal, with error checking this time. */
413 for(i = 0; sighandlers[i].signal; i++) {
414 act.sa_handler = sighandlers[i].handler;
415 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
416 fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
417 sighandlers[i].signal, strsignal(sighandlers[i].signal),