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;
40 extern char *identname;
41 extern char *pidfilename;
43 extern bool use_logfile;
44 extern volatile bool running;
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_INTERROGATE:
155 SetServiceStatus(statushandle, &status);
157 case SERVICE_CONTROL_STOP:
158 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
160 case SERVICE_CONTROL_SHUTDOWN:
161 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
164 logger(LOG_WARNING, _("Got unexpected request %d"), request);
165 return ERROR_CALL_NOT_IMPLEMENTED;
170 status.dwWaitHint = 30000;
171 status.dwCurrentState = SERVICE_STOP_PENDING;
172 SetServiceStatus(statushandle, &status);
175 status.dwWaitHint = 0;
176 status.dwCurrentState = SERVICE_STOPPED;
177 SetServiceStatus(statushandle, &status);
183 VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
185 extern int main2(int argc, char **argv);
188 status.dwServiceType = SERVICE_WIN32;
189 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
190 status.dwWin32ExitCode = 0;
191 status.dwServiceSpecificExitCode = 0;
192 status.dwCheckPoint = 0;
194 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
197 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
200 status.dwWaitHint = 30000;
201 status.dwCurrentState = SERVICE_START_PENDING;
202 SetServiceStatus(statushandle, &status);
204 status.dwWaitHint = 0;
205 status.dwCurrentState = SERVICE_RUNNING;
206 SetServiceStatus(statushandle, &status);
208 err = main2(argc, argv);
210 status.dwWaitHint = 0;
211 status.dwCurrentState = SERVICE_STOPPED;
212 //status.dwWin32ExitCode = err;
213 SetServiceStatus(statushandle, &status);
219 bool init_service(void) {
220 SERVICE_TABLE_ENTRY services[] = {
221 {identname, run_service},
225 if(!StartServiceCtrlDispatcher(services)) {
226 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
230 logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
239 check for an existing tinc for this net, and write pid to pidfile
241 static bool write_pidfile(void) {
246 pid = check_pid(pidfilename);
250 fprintf(stderr, _("A tincd is already running for net `%s' with pid %ld.\n"),
253 fprintf(stderr, _("A tincd is already running with pid %ld.\n"), (long)pid);
257 /* if it's locked, write-protected, or whatever */
258 if(!write_pid(pidfilename)) {
259 fprintf(stderr, _("Could write pid file %s: %s\n"), pidfilename, strerror(errno));
268 kill older tincd for this net
270 bool kill_other(int signal) {
276 pid = read_pid(pidfilename);
280 fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
283 fprintf(stderr, _("No other tincd is running.\n"));
287 errno = 0; /* No error, sometimes errno is only changed on error */
289 /* ESRCH is returned when no process with that pid is found */
290 if(kill(pid, signal) && errno == ESRCH) {
292 fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
295 fprintf(stderr, _("The tincd is no longer running. "));
297 fprintf(stderr, _("Removing stale lock file.\n"));
298 remove_pid(pidfilename);
303 return remove_service();
308 Detach from current terminal, write pidfile, kill parent
315 /* First check if we can open a fresh new pidfile */
321 /* If we succeeded in doing that, detach */
329 fprintf(stderr, _("Couldn't detach from terminal: %s"),
334 /* Now UPDATE the pid in the pidfile, because we changed it... */
336 if(!write_pid(pidfilename)) {
337 fprintf(stderr, _("Could not write pid file %s: %s\n"), pidfilename, strerror(errno));
342 exit(install_service());
346 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
348 logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
349 VERSION, __DATE__, __TIME__, debug_level);
351 xalloc_fail_func = memory_full;
356 bool execute_script(const char *name, char **envp) {
359 char *scriptname, *p;
365 len = xasprintf(&scriptname, "\"%s/%s\"", confbase, name);
367 len = xasprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
372 scriptname[len - 1] = '\0';
375 /* First check if there is a script */
377 if(access(scriptname + 1, F_OK)) {
383 ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
386 /* Set environment */
388 for(i = 0; envp[i]; i++)
392 scriptname[len - 1] = '\"';
393 status = system(scriptname);
397 /* Unset environment */
399 for(i = 0; envp[i]; i++) {
400 char *e = strchr(envp[i], '=');
402 p = alloca(e - envp[i] + 1);
403 strncpy(p, envp[i], e - envp[i]);
404 p[e - envp[i]] = '\0';
411 if(WIFEXITED(status)) { /* Child exited by itself */
412 if(WEXITSTATUS(status)) {
413 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
414 name, WEXITSTATUS(status));
417 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
418 logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
419 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
421 } else { /* Something strange happened */
422 logger(LOG_ERR, _("Script %s terminated abnormally"), name);
426 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
440 static RETSIGTYPE sigterm_handler(int a) {
441 logger(LOG_NOTICE, _("Got %s signal"), "TERM");
448 static RETSIGTYPE sigquit_handler(int a) {
449 logger(LOG_NOTICE, _("Got %s signal"), "QUIT");
456 static RETSIGTYPE fatal_signal_square(int a) {
457 logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
463 static RETSIGTYPE fatal_signal_handler(int a) {
464 struct sigaction act;
465 logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
469 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
471 act.sa_handler = fatal_signal_square;
472 act.sa_mask = emptysigset;
474 sigaction(SIGSEGV, &act, NULL);
476 close_network_connections();
478 remove_pid(pidfilename);
479 execvp(g_argv[0], g_argv);
481 logger(LOG_NOTICE, _("Not restarting."));
486 static RETSIGTYPE sighup_handler(int a) {
487 logger(LOG_NOTICE, _("Got %s signal"), "HUP");
491 static RETSIGTYPE sigint_handler(int a) {
492 logger(LOG_NOTICE, _("Got %s signal"), "INT");
494 if(saved_debug_level != -1) {
495 logger(LOG_NOTICE, _("Reverting to old debug level (%d)"),
497 debug_level = saved_debug_level;
498 saved_debug_level = -1;
501 _("Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d."),
503 saved_debug_level = debug_level;
508 static RETSIGTYPE sigalrm_handler(int a) {
509 logger(LOG_NOTICE, _("Got %s signal"), "ALRM");
513 static RETSIGTYPE sigusr1_handler(int a) {
517 static RETSIGTYPE sigusr2_handler(int a) {
524 static RETSIGTYPE sigwinch_handler(int a) {
528 static RETSIGTYPE unexpected_signal_handler(int a) {
529 logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
533 static RETSIGTYPE ignore_signal_handler(int a) {
534 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
539 void (*handler)(int);
541 {SIGHUP, sighup_handler},
542 {SIGTERM, sigterm_handler},
543 {SIGQUIT, sigquit_handler},
544 {SIGSEGV, fatal_signal_handler},
545 {SIGBUS, fatal_signal_handler},
546 {SIGILL, fatal_signal_handler},
547 {SIGPIPE, ignore_signal_handler},
548 {SIGINT, sigint_handler},
549 {SIGUSR1, sigusr1_handler},
550 {SIGUSR2, sigusr2_handler},
551 {SIGCHLD, ignore_signal_handler},
552 {SIGALRM, sigalrm_handler},
553 {SIGWINCH, sigwinch_handler},
558 void setup_signals(void) {
561 struct sigaction act;
563 sigemptyset(&emptysigset);
564 act.sa_handler = NULL;
565 act.sa_mask = emptysigset;
568 /* Set a default signal handler for every signal, errors will be
570 for(i = 1; i < NSIG; i++) {
572 act.sa_handler = SIG_DFL;
574 act.sa_handler = unexpected_signal_handler;
575 sigaction(i, &act, NULL);
578 /* If we didn't detach, allow coredumps */
580 sighandlers[3].handler = SIG_DFL;
582 /* Then, for each known signal that we want to catch, assign a
583 handler to the signal, with error checking this time. */
584 for(i = 0; sighandlers[i].signal; i++) {
585 act.sa_handler = sighandlers[i].handler;
586 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
587 fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
588 sighandlers[i].signal, strsignal(sighandlers[i].signal),