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;
42 extern char *pidfilename;
44 extern bool use_logfile;
48 static int saved_debug_level = -1;
50 static void memory_full(int size) {
51 logger(LOG_ERR, _("Memory exhausted (couldn't allocate %d bytes), exitting."), size);
56 /* Some functions the less gifted operating systems might lack... */
59 extern char *identname;
60 extern char *program_name;
63 static SC_HANDLE manager = NULL;
64 static SC_HANDLE service = NULL;
65 static SERVICE_STATUS status = {0};
66 static SERVICE_STATUS_HANDLE statushandle = 0;
68 bool install_service(void) {
69 char command[4096] = "\"";
72 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
74 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
76 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
80 if(!strchr(program_name, '\\')) {
81 GetCurrentDirectory(sizeof command - 1, command + 1);
82 strncat(command, "\\", sizeof command - strlen(command));
85 strncat(command, program_name, sizeof command - strlen(command));
87 strncat(command, "\"", sizeof command - strlen(command));
89 for(argp = g_argv + 1; *argp; argp++) {
90 space = strchr(*argp, ' ');
91 strncat(command, " ", sizeof command - strlen(command));
94 strncat(command, "\"", sizeof command - strlen(command));
96 strncat(command, *argp, sizeof command - strlen(command));
99 strncat(command, "\"", sizeof command - strlen(command));
102 service = CreateService(manager, identname, identname,
103 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
104 command, NULL, NULL, NULL, NULL, NULL);
107 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
111 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
113 logger(LOG_INFO, _("%s service installed"), identname);
115 if(!StartService(service, 0, NULL))
116 logger(LOG_WARNING, _("Could not start %s service: %s"), identname, winerror(GetLastError()));
118 logger(LOG_INFO, _("%s service started"), identname);
123 bool remove_service(void) {
124 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
126 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
130 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
133 logger(LOG_ERR, _("Could not open %s service: %s"), identname, winerror(GetLastError()));
137 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
138 logger(LOG_ERR, _("Could not stop %s service: %s"), identname, winerror(GetLastError()));
140 logger(LOG_INFO, _("%s service stopped"), identname);
142 if(!DeleteService(service)) {
143 logger(LOG_ERR, _("Could not remove %s service: %s"), identname, winerror(GetLastError()));
147 logger(LOG_INFO, _("%s service removed"), identname);
152 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
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()));
228 check for an existing tinc for this net, and write pid to pidfile
230 static bool write_pidfile(void) {
235 pid = check_pid(pidfilename);
239 fprintf(stderr, _("A tincd is already running for net `%s' with pid %ld.\n"),
242 fprintf(stderr, _("A tincd is already running with pid %ld.\n"), (long)pid);
246 /* if it's locked, write-protected, or whatever */
247 if(!write_pid(pidfilename)) {
248 fprintf(stderr, _("Could write pid file %s: %s\n"), pidfilename, strerror(errno));
257 kill older tincd for this net
259 bool kill_other(int signal) {
265 pid = read_pid(pidfilename);
269 fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
272 fprintf(stderr, _("No other tincd is running.\n"));
276 errno = 0; /* No error, sometimes errno is only changed on error */
278 /* ESRCH is returned when no process with that pid is found */
279 if(kill(pid, signal) && errno == ESRCH) {
281 fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
284 fprintf(stderr, _("The tincd is no longer running. "));
286 fprintf(stderr, _("Removing stale lock file.\n"));
287 remove_pid(pidfilename);
292 return remove_service();
297 Detach from current terminal, write pidfile, kill parent
304 /* First check if we can open a fresh new pidfile */
310 /* If we succeeded in doing that, detach */
318 fprintf(stderr, _("Couldn't detach from terminal: %s"),
323 /* Now UPDATE the pid in the pidfile, because we changed it... */
325 if(!write_pid(pidfilename)) {
326 fprintf(stderr, _("Could not write pid file %s: %s\n"), pidfilename, strerror(errno));
331 exit(install_service());
335 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
337 logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
338 VERSION, __DATE__, __TIME__, debug_level);
340 xalloc_fail_func = memory_full;
345 bool execute_script(const char *name, char **envp) {
349 char *scriptname, *p;
355 len = asprintf(&scriptname, "\"%s/%s\"", confbase, name);
357 len = asprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
362 scriptname[len - 1] = '\0';
364 /* First check if there is a script */
366 if(stat(scriptname + 1, &s)) {
371 ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
374 /* Set environment */
376 for(i = 0; envp[i]; i++)
380 scriptname[len - 1] = '\"';
381 status = system(scriptname);
385 /* Unset environment */
387 for(i = 0; envp[i]; i++) {
388 char *e = strchr(envp[i], '=');
390 p = alloca(e - envp[i] + 1);
391 strncpy(p, envp[i], e - envp[i]);
392 p[e - envp[i]] = '\0';
399 if(WIFEXITED(status)) { /* Child exited by itself */
400 if(WEXITSTATUS(status)) {
401 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
402 name, WEXITSTATUS(status));
405 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
406 logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
407 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
409 } else { /* Something strange happened */
410 logger(LOG_ERR, _("Script %s terminated abnormally"), name);
414 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
428 static RETSIGTYPE fatal_signal_square(int a) {
429 logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
435 static RETSIGTYPE fatal_signal_handler(int a) {
436 struct sigaction act;
437 logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
441 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
443 act.sa_handler = fatal_signal_square;
444 act.sa_mask = emptysigset;
446 sigaction(SIGSEGV, &act, NULL);
448 close_network_connections();
450 remove_pid(pidfilename);
451 execvp(g_argv[0], g_argv);
453 logger(LOG_NOTICE, _("Not restarting."));
458 static RETSIGTYPE unexpected_signal_handler(int a) {
459 logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
463 static RETSIGTYPE ignore_signal_handler(int a) {
464 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
469 void (*handler)(int);
471 {SIGSEGV, fatal_signal_handler},
472 {SIGBUS, fatal_signal_handler},
473 {SIGILL, fatal_signal_handler},
474 {SIGPIPE, ignore_signal_handler},
475 {SIGCHLD, ignore_signal_handler},
480 void setup_signals(void) {
483 struct sigaction act;
485 sigemptyset(&emptysigset);
486 act.sa_handler = NULL;
487 act.sa_mask = emptysigset;
490 /* Set a default signal handler for every signal, errors will be
492 for(i = 0; i < NSIG; i++) {
494 act.sa_handler = SIG_DFL;
496 act.sa_handler = unexpected_signal_handler;
497 sigaction(i, &act, NULL);
500 /* If we didn't detach, allow coredumps */
502 sighandlers[0].handler = SIG_DFL;
504 /* Then, for each known signal that we want to catch, assign a
505 handler to the signal, with error checking this time. */
506 for(i = 0; sighandlers[i].signal; i++) {
507 act.sa_handler = sighandlers[i].handler;
508 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
509 fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
510 sighandlers[i].signal, strsignal(sighandlers[i].signal),