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;
42 extern char *identname;
43 extern char *pidfilename;
45 extern bool use_logfile;
46 extern volatile bool running;
50 static int saved_debug_level = -1;
52 static void memory_full(int size)
54 logger(LOG_ERR, _("Memory exhausted (couldn't allocate %d bytes), exitting."), size);
59 /* Some functions the less gifted operating systems might lack... */
62 extern char *identname;
63 extern char *program_name;
66 static SC_HANDLE manager = NULL;
67 static SC_HANDLE service = NULL;
68 static SERVICE_STATUS status = {0};
69 static SERVICE_STATUS_HANDLE statushandle = 0;
71 bool install_service(void) {
72 char command[4096] = "\"";
75 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
77 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
79 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
83 if(!strchr(program_name, '\\')) {
84 GetCurrentDirectory(sizeof command - 1, command + 1);
85 strncat(command, "\\", sizeof command - strlen(command));
88 strncat(command, program_name, sizeof command - strlen(command));
90 strncat(command, "\"", sizeof command - strlen(command));
92 for(argp = g_argv + 1; *argp; argp++) {
93 space = strchr(*argp, ' ');
94 strncat(command, " ", sizeof command - strlen(command));
97 strncat(command, "\"", sizeof command - strlen(command));
99 strncat(command, *argp, sizeof command - strlen(command));
102 strncat(command, "\"", sizeof command - strlen(command));
105 service = CreateService(manager, identname, identname,
106 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
107 command, NULL, NULL, NULL, NULL, NULL);
110 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
114 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
116 logger(LOG_INFO, _("%s service installed"), identname);
118 if(!StartService(service, 0, NULL))
119 logger(LOG_WARNING, _("Could not start %s service: %s"), identname, winerror(GetLastError()));
121 logger(LOG_INFO, _("%s service started"), identname);
126 bool remove_service(void) {
127 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
129 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
133 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
136 logger(LOG_ERR, _("Could not open %s service: %s"), identname, winerror(GetLastError()));
140 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
141 logger(LOG_ERR, _("Could not stop %s service: %s"), identname, winerror(GetLastError()));
143 logger(LOG_INFO, _("%s service stopped"), identname);
145 if(!DeleteService(service)) {
146 logger(LOG_ERR, _("Could not remove %s service: %s"), identname, winerror(GetLastError()));
150 logger(LOG_INFO, _("%s service removed"), identname);
155 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
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)
186 extern int main2(int argc, char **argv);
189 status.dwServiceType = SERVICE_WIN32;
190 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
191 status.dwWin32ExitCode = 0;
192 status.dwServiceSpecificExitCode = 0;
193 status.dwCheckPoint = 0;
195 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
198 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
201 status.dwWaitHint = 30000;
202 status.dwCurrentState = SERVICE_START_PENDING;
203 SetServiceStatus(statushandle, &status);
205 status.dwWaitHint = 0;
206 status.dwCurrentState = SERVICE_RUNNING;
207 SetServiceStatus(statushandle, &status);
209 err = main2(argc, argv);
211 status.dwWaitHint = 0;
212 status.dwCurrentState = SERVICE_STOPPED;
213 //status.dwWin32ExitCode = err;
214 SetServiceStatus(statushandle, &status);
220 bool init_service(void) {
221 SERVICE_TABLE_ENTRY services[] = {
222 {identname, run_service},
226 if(!StartServiceCtrlDispatcher(services)) {
227 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
231 logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
240 check for an existing tinc for this net, and write pid to pidfile
242 static bool write_pidfile(void)
248 pid = check_pid(pidfilename);
252 fprintf(stderr, _("A tincd is already running for net `%s' with pid %ld.\n"),
255 fprintf(stderr, _("A tincd is already running with pid %ld.\n"), (long)pid);
259 /* if it's locked, write-protected, or whatever */
260 if(!write_pid(pidfilename)) {
261 fprintf(stderr, _("Could write pid file %s: %s\n"), pidfilename, strerror(errno));
270 kill older tincd for this net
272 bool kill_other(int signal)
279 pid = read_pid(pidfilename);
283 fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
286 fprintf(stderr, _("No other tincd is running.\n"));
290 errno = 0; /* No error, sometimes errno is only changed on error */
292 /* ESRCH is returned when no process with that pid is found */
293 if(kill(pid, signal) && errno == ESRCH) {
295 fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
298 fprintf(stderr, _("The tincd is no longer running. "));
300 fprintf(stderr, _("Removing stale lock file.\n"));
301 remove_pid(pidfilename);
306 return remove_service();
311 Detach from current terminal, write pidfile, kill parent
319 /* First check if we can open a fresh new pidfile */
325 /* If we succeeded in doing that, detach */
333 fprintf(stderr, _("Couldn't detach from terminal: %s"),
338 /* Now UPDATE the pid in the pidfile, because we changed it... */
340 if(!write_pid(pidfilename)) {
341 fprintf(stderr, _("Could not write pid file %s: %s\n"), pidfilename, strerror(errno));
346 exit(install_service());
350 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
352 logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
353 VERSION, __DATE__, __TIME__, debug_level);
355 xalloc_fail_func = memory_full;
360 bool execute_script(const char *name, char **envp)
365 char *scriptname, *p;
371 len = asprintf(&scriptname, "\"%s/%s\"", confbase, name);
373 len = asprintf(&scriptname, "\"%s/%s.bat\"", confbase, name);
378 scriptname[len - 1] = '\0';
380 /* First check if there is a script */
382 if(stat(scriptname + 1, &s)) {
387 ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
390 /* Set environment */
392 for(i = 0; envp[i]; i++)
396 scriptname[len - 1] = '\"';
397 status = system(scriptname);
401 /* Unset environment */
403 for(i = 0; envp[i]; i++) {
404 char *e = strchr(envp[i], '=');
406 p = alloca(e - envp[i] + 1);
407 strncpy(p, envp[i], e - envp[i]);
408 p[e - envp[i]] = '\0';
415 if(WIFEXITED(status)) { /* Child exited by itself */
416 if(WEXITSTATUS(status)) {
417 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
418 name, WEXITSTATUS(status));
421 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
422 logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
423 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
425 } else { /* Something strange happened */
426 logger(LOG_ERR, _("Script %s terminated abnormally"), name);
430 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
444 static RETSIGTYPE sigterm_handler(int a)
446 logger(LOG_NOTICE, _("Got %s signal"), "TERM");
453 static RETSIGTYPE sigquit_handler(int a)
455 logger(LOG_NOTICE, _("Got %s signal"), "QUIT");
462 static RETSIGTYPE fatal_signal_square(int a)
464 logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
470 static RETSIGTYPE fatal_signal_handler(int a)
472 struct sigaction act;
473 logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
477 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
479 act.sa_handler = fatal_signal_square;
480 act.sa_mask = emptysigset;
482 sigaction(SIGSEGV, &act, NULL);
484 close_network_connections();
486 remove_pid(pidfilename);
487 execvp(g_argv[0], g_argv);
489 logger(LOG_NOTICE, _("Not restarting."));
494 static RETSIGTYPE sighup_handler(int a)
496 logger(LOG_NOTICE, _("Got %s signal"), "HUP");
500 static RETSIGTYPE sigint_handler(int a)
502 logger(LOG_NOTICE, _("Got %s signal"), "INT");
504 if(saved_debug_level != -1) {
505 logger(LOG_NOTICE, _("Reverting to old debug level (%d)"),
507 debug_level = saved_debug_level;
508 saved_debug_level = -1;
511 _("Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d."),
513 saved_debug_level = debug_level;
518 static RETSIGTYPE sigalrm_handler(int a)
520 logger(LOG_NOTICE, _("Got %s signal"), "ALRM");
524 static RETSIGTYPE sigusr1_handler(int a)
529 static RETSIGTYPE sigusr2_handler(int a)
537 static RETSIGTYPE sigwinch_handler(int a)
542 static RETSIGTYPE unexpected_signal_handler(int a)
544 logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
548 static RETSIGTYPE ignore_signal_handler(int a)
550 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
555 void (*handler)(int);
557 {SIGHUP, sighup_handler},
558 {SIGTERM, sigterm_handler},
559 {SIGQUIT, sigquit_handler},
560 {SIGSEGV, fatal_signal_handler},
561 {SIGBUS, fatal_signal_handler},
562 {SIGILL, fatal_signal_handler},
563 {SIGPIPE, ignore_signal_handler},
564 {SIGINT, sigint_handler},
565 {SIGUSR1, sigusr1_handler},
566 {SIGUSR2, sigusr2_handler},
567 {SIGCHLD, ignore_signal_handler},
568 {SIGALRM, sigalrm_handler},
569 {SIGWINCH, sigwinch_handler},
574 void setup_signals(void)
578 struct sigaction act;
580 sigemptyset(&emptysigset);
581 act.sa_handler = NULL;
582 act.sa_mask = emptysigset;
585 /* Set a default signal handler for every signal, errors will be
587 for(i = 0; i < NSIG; i++) {
589 act.sa_handler = SIG_DFL;
591 act.sa_handler = unexpected_signal_handler;
592 sigaction(i, &act, NULL);
595 /* If we didn't detach, allow coredumps */
597 sighandlers[3].handler = SIG_DFL;
599 /* Then, for each known signal that we want to catch, assign a
600 handler to the signal, with error checking this time. */
601 for(i = 0; sighandlers[i].signal; i++) {
602 act.sa_handler = sighandlers[i].handler;
603 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
604 fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
605 sighandlers[i].signal, strsignal(sighandlers[i].signal),