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;
47 static void memory_full(int size) {
48 logger(LOG_ERR, "Memory exhausted (couldn't allocate %d bytes), exitting.", size);
52 /* Some functions the less gifted operating systems might lack... */
55 extern char *identname;
56 extern char *program_name;
59 static SC_HANDLE manager = NULL;
60 static SC_HANDLE service = NULL;
61 static SERVICE_STATUS status = {0};
62 static SERVICE_STATUS_HANDLE statushandle = 0;
64 bool install_service(void) {
65 char command[4096] = "\"";
68 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
70 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
72 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
76 if(!strchr(program_name, '\\')) {
77 GetCurrentDirectory(sizeof command - 1, command + 1);
78 strncat(command, "\\", sizeof command - strlen(command));
81 strncat(command, program_name, sizeof command - strlen(command));
83 strncat(command, "\"", sizeof command - strlen(command));
85 for(argp = g_argv + 1; *argp; argp++) {
86 space = strchr(*argp, ' ');
87 strncat(command, " ", sizeof command - strlen(command));
90 strncat(command, "\"", sizeof command - strlen(command));
92 strncat(command, *argp, sizeof command - strlen(command));
95 strncat(command, "\"", sizeof command - strlen(command));
98 service = CreateService(manager, identname, identname,
99 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
100 command, NULL, NULL, NULL, NULL, NULL);
103 DWORD lasterror = GetLastError();
104 logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
105 if(lasterror != ERROR_SERVICE_EXISTS)
110 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
111 logger(LOG_INFO, "%s service installed", identname);
113 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
116 if(!StartService(service, 0, NULL))
117 logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
119 logger(LOG_INFO, "%s service started", identname);
124 bool remove_service(void) {
125 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
127 logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
131 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
134 logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
138 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
139 logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
141 logger(LOG_INFO, "%s service stopped", identname);
143 if(!DeleteService(service)) {
144 logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
148 logger(LOG_INFO, "%s service removed", identname);
153 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
155 case SERVICE_CONTROL_INTERROGATE:
156 SetServiceStatus(statushandle, &status);
158 case SERVICE_CONTROL_STOP:
159 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_STOP");
161 case SERVICE_CONTROL_SHUTDOWN:
162 logger(LOG_NOTICE, "Got %s request", "SERVICE_CONTROL_SHUTDOWN");
165 logger(LOG_WARNING, "Got unexpected request %d", request);
166 return ERROR_CALL_NOT_IMPLEMENTED;
169 event_loopexit(NULL);
170 status.dwWaitHint = 30000;
171 status.dwCurrentState = SERVICE_STOP_PENDING;
172 SetServiceStatus(statushandle, &status);
176 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
178 extern int main2(int argc, char **argv);
181 status.dwServiceType = SERVICE_WIN32;
182 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
183 status.dwWin32ExitCode = 0;
184 status.dwServiceSpecificExitCode = 0;
185 status.dwCheckPoint = 0;
187 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
190 logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
193 status.dwWaitHint = 30000;
194 status.dwCurrentState = SERVICE_START_PENDING;
195 SetServiceStatus(statushandle, &status);
197 status.dwWaitHint = 0;
198 status.dwCurrentState = SERVICE_RUNNING;
199 SetServiceStatus(statushandle, &status);
201 err = main2(argc, argv);
203 status.dwWaitHint = 0;
204 status.dwCurrentState = SERVICE_STOPPED;
205 //status.dwWin32ExitCode = err;
206 SetServiceStatus(statushandle, &status);
212 bool init_service(void) {
213 SERVICE_TABLE_ENTRY services[] = {
214 {identname, run_service},
218 if(!StartServiceCtrlDispatcher(services)) {
219 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
223 logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
231 Detach from current terminal
243 fprintf(stderr, "Couldn't detach from terminal: %s",
249 exit(install_service());
253 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
255 logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d",
256 VERSION, __DATE__, __TIME__, debug_level);
258 xalloc_fail_func = memory_full;
263 bool execute_script(const char *name, char **envp) {
270 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
272 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
277 scriptname[len - 1] = '\0';
280 /* First check if there is a script */
282 if(access(scriptname + 1, F_OK)) {
288 ifdebug(STATUS) logger(LOG_INFO, "Executing script %s", name);
291 /* Set environment */
293 for(i = 0; envp[i]; i++)
297 scriptname[len - 1] = '\"';
298 status = system(scriptname);
302 /* Unset environment */
304 for(i = 0; envp[i]; i++) {
305 char *e = strchr(envp[i], '=');
307 char p[e - envp[i] + 1];
308 strncpy(p, envp[i], e - envp[i]);
309 p[e - envp[i]] = '\0';
316 if(WIFEXITED(status)) { /* Child exited by itself */
317 if(WEXITSTATUS(status)) {
318 logger(LOG_ERR, "Script %s exited with non-zero status %d",
319 name, WEXITSTATUS(status));
322 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
323 logger(LOG_ERR, "Script %s was killed by signal %d (%s)",
324 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
326 } else { /* Something strange happened */
327 logger(LOG_ERR, "Script %s terminated abnormally", name);
331 logger(LOG_ERR, "System call `%s' failed: %s", "system", strerror(errno));
345 static RETSIGTYPE fatal_signal_square(int a) {
346 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));
356 logger(LOG_NOTICE, "Trying to re-execute in 5 seconds...");
358 act.sa_handler = fatal_signal_square;
359 act.sa_mask = emptysigset;
361 sigaction(SIGSEGV, &act, NULL);
363 close_network_connections();
366 execvp(g_argv[0], g_argv);
368 logger(LOG_NOTICE, "Not restarting.");
373 static RETSIGTYPE unexpected_signal_handler(int a) {
374 logger(LOG_WARNING, "Got unexpected signal %d (%s)", a, strsignal(a));
377 static RETSIGTYPE ignore_signal_handler(int a) {
378 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Ignored signal %d (%s)", a, strsignal(a));
383 void (*handler)(int);
385 {SIGSEGV, fatal_signal_handler},
386 {SIGBUS, fatal_signal_handler},
387 {SIGILL, fatal_signal_handler},
388 {SIGPIPE, ignore_signal_handler},
389 {SIGCHLD, ignore_signal_handler},
394 void setup_signals(void) {
397 struct sigaction act;
399 sigemptyset(&emptysigset);
400 act.sa_handler = NULL;
401 act.sa_mask = emptysigset;
404 /* Set a default signal handler for every signal, errors will be
406 for(i = 1; i < NSIG; i++) {
408 act.sa_handler = SIG_DFL;
410 act.sa_handler = unexpected_signal_handler;
411 sigaction(i, &act, NULL);
414 /* If we didn't detach, allow coredumps */
416 sighandlers[0].handler = SIG_DFL;
418 /* Then, for each known signal that we want to catch, assign a
419 handler to the signal, with error checking this time. */
420 for(i = 0; sighandlers[i].signal; i++) {
421 act.sa_handler = sighandlers[i].handler;
422 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
423 fprintf(stderr, "Installing signal handler for signal %d (%s) failed: %s\n",
424 sighandlers[i].signal, strsignal(sighandlers[i].signal),