2 process.c -- process management functions
3 Copyright (C) 1999-2004 Ivo Timmermans <ivo@tinc-vpn.org>,
4 2000-2004 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 "logger/logger.h"
28 static sigset_t emptysigset;
30 /* Some functions the less gifted operating systems might lack... */
33 static SC_HANDLE manager = NULL;
34 static SC_HANDLE service = NULL;
35 static SERVICE_STATUS status = {0};
36 static SERVICE_STATUS_HANDLE statushandle = 0;
38 bool install_service(void) {
39 char command[4096] = "\"";
42 SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};
44 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
46 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
50 if(!strchr(program_name, '\\')) {
51 GetCurrentDirectory(sizeof(command) - 1, command + 1);
52 strncat(command, "\\", sizeof(command));
55 strncat(command, program_name, sizeof(command));
57 strncat(command, "\"", sizeof(command));
59 for(argp = g_argv + 1; *argp; argp++) {
60 space = strchr(*argp, ' ');
61 strncat(command, " ", sizeof(command));
64 strncat(command, "\"", sizeof(command));
66 strncat(command, *argp, sizeof(command));
69 strncat(command, "\"", sizeof(command));
72 service = CreateService(manager, identname, identname,
73 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
74 command, "NDIS", NULL, NULL, NULL, NULL);
77 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
81 ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
83 logger(LOG_INFO, _("%s service installed"), identname);
85 if(!StartService(service, 0, NULL))
86 logger(LOG_WARNING, _("Could not start %s service: %s"), identname, winerror(GetLastError()));
88 logger(LOG_INFO, _("%s service started"), identname);
93 bool remove_service(void) {
94 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
96 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
100 service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
103 logger(LOG_ERR, _("Could not open %s service: %s"), identname, winerror(GetLastError()));
107 if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
108 logger(LOG_ERR, _("Could not stop %s service: %s"), identname, winerror(GetLastError()));
110 logger(LOG_INFO, _("%s service stopped"), identname);
112 if(!DeleteService(service)) {
113 logger(LOG_ERR, _("Could not remove %s service: %s"), identname, winerror(GetLastError()));
117 logger(LOG_INFO, _("%s service removed"), identname);
122 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
124 case SERVICE_CONTROL_STOP:
125 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
127 case SERVICE_CONTROL_SHUTDOWN:
128 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
131 logger(LOG_WARNING, _("Got unexpected request %d"), request);
132 return ERROR_CALL_NOT_IMPLEMENTED;
137 status.dwWaitHint = 30000;
138 status.dwCurrentState = SERVICE_STOP_PENDING;
139 SetServiceStatus(statushandle, &status);
142 status.dwWaitHint = 0;
143 status.dwCurrentState = SERVICE_STOPPED;
144 SetServiceStatus(statushandle, &status);
150 VOID WINAPI run_service(DWORD argc, LPTSTR* argv)
153 extern int main2(int argc, char **argv);
156 status.dwServiceType = SERVICE_WIN32;
157 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
158 status.dwWin32ExitCode = 0;
159 status.dwServiceSpecificExitCode = 0;
160 status.dwCheckPoint = 0;
162 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
165 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
168 status.dwWaitHint = 30000;
169 status.dwCurrentState = SERVICE_START_PENDING;
170 SetServiceStatus(statushandle, &status);
172 status.dwWaitHint = 0;
173 status.dwCurrentState = SERVICE_RUNNING;
174 SetServiceStatus(statushandle, &status);
176 err = main2(argc, argv);
178 status.dwWaitHint = 0;
179 status.dwCurrentState = SERVICE_STOPPED;
180 //status.dwWin32ExitCode = err;
181 SetServiceStatus(statushandle, &status);
187 bool init_service(void) {
188 SERVICE_TABLE_ENTRY services[] = {
189 {identname, run_service},
193 if(!StartServiceCtrlDispatcher(services)) {
194 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
198 logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
207 check for an existing tinc for this net, and write pid to pidfile
210 static pid_t read_pid(const char *pidfilename) {
214 pidfile = fopen(pidfilename, "r");
218 fscanf(pidfile, "%ld", &pid);
224 static pid_t check_pid(const char *pidfilename) {
227 pid = read_pid(pidfilename);
229 if (!pid || pid == getpid())
232 if(kill(pid, 0) && errno == ESRCH)
238 static pid_t write_pid(const char *pidfilename) {
243 pidfd = open(pidfilename, O_RDWR | O_CREAT);
249 if(flock(pidfd, LOCK_EX | LOCK_NB) == -1) {
255 pidfile = fdopen(pidfd, "r+");
263 fprintf(pidfile, "%ld\n", (long)pid);
267 flock(pidfd, LOCK_UN);
275 bool remove_pid(const char *pidfilename) {
276 return unlink(pidfilename) == 0;
279 static bool write_pidfile(void)
283 pid = check_pid(tinc_pidfilename);
287 fprintf(stderr, _("A tincd is already running for net `%s' with pid %ld.\n"),
288 tinc_netname, (long)pid);
290 fprintf(stderr, _("A tincd is already running with pid %ld.\n"), (long)pid);
294 /* if it's locked, write-protected, or whatever */
295 if(!write_pid(tinc_pidfilename)) {
296 fprintf(stderr, _("Could write pid file %s: %s\n"), tinc_pidfilename, strerror(errno));
305 kill older tincd for this net
307 bool kill_other(int signal)
312 pid = read_pid(tinc_pidfilename);
316 fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
319 fprintf(stderr, _("No other tincd is running.\n"));
323 errno = 0; /* No error, sometimes errno is only changed on error */
325 /* ESRCH is returned when no process with that pid is found */
326 if(kill(pid, signal) && errno == ESRCH) {
328 fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
331 fprintf(stderr, _("The tincd is no longer running. "));
333 fprintf(stderr, _("Removing stale lock file.\n"));
334 remove_pid(tinc_pidfilename);
339 return remove_service();
344 Detach from current terminal, write pidfile, kill parent
351 /* If we succeeded in doing that, detach */
356 fprintf(stderr, _("Couldn't detach from terminal: %s"),
361 /* Now UPDATE the pid in the pidfile, because we changed it... */
363 if(!write_pid(tinc_pidfilename)) {
364 fprintf(stderr, _("Could not write pid file %s: %s\n"), tinc_pidfilename, strerror(errno));
369 exit(install_service());
372 logger_init(tinc_identname, tinc_use_logfile ? LOGGER_MODE_FILE : LOGGER_MODE_SYSLOG);
377 bool execute_script(const char *name, char **envp)
385 len = asprintf(&scriptname, "\"%s/%s\"", tinc_confbase, name);
387 len = asprintf(&scriptname, "\"%s/%s.bat\"", tinc_confbase, name);
392 scriptname[len - 1] = '\0';
394 /* First check if there is a script */
396 if(stat(scriptname + 1, &s))
399 logger(LOG_INFO, _("Executing script %s"), name);
402 /* Set environment */
408 scriptname[len - 1] = '\"';
409 status = system(scriptname);
413 /* Unset environment? */
417 if(WIFEXITED(status)) { /* Child exited by itself */
418 if(WEXITSTATUS(status)) {
419 logger(LOG_ERR, _("Script %s exited with non-zero status %d"),
420 name, WEXITSTATUS(status));
423 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
424 logger(LOG_ERR, _("Script %s was killed by signal %d (%s)"),
425 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
427 } else { /* Something strange happened */
428 logger(LOG_ERR, _("Script %s terminated abnormally"), name);
432 logger(LOG_ERR, _("System call `%s' failed: %s"), "system", strerror(errno));
446 static RETSIGTYPE sigterm_handler(int a) {
447 logger(LOG_NOTICE, _("Got %s signal"), "TERM");
451 static RETSIGTYPE sigquit_handler(int a) {
452 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,
462 static RETSIGTYPE fatal_signal_handler(int a) {
463 struct sigaction act;
464 logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
465 logger(LOG_NOTICE, _("Not restarting."));
469 static RETSIGTYPE sighup_handler(int a) {
470 logger(LOG_NOTICE, _("Got %s signal"), "HUP");
474 static RETSIGTYPE sigint_handler(int a) {
475 static logger_level_t saved_logger_level = -1;
477 logger(LOG_NOTICE, _("Got %s signal"), "INT");
479 if(saved_logger_level != -1) {
480 logger(LOG_NOTICE, _("Reverting to old debug level (%d)"),
482 logger_level = saved_logger_level;
483 saved_logger_level = -1;
486 _("Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d."),
488 saved_logger_level = logger_level;
493 static RETSIGTYPE sigalrm_handler(int a) {
494 logger(LOG_NOTICE, _("Got %s signal"), "ALRM");
498 static RETSIGTYPE sigusr1_handler(int a) {
501 static RETSIGTYPE sigusr2_handler(int a) {
504 static RETSIGTYPE sigwinch_handler(int a) {
508 static RETSIGTYPE unexpected_signal_handler(int a) {
509 logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
512 static RETSIGTYPE ignore_signal_handler(int a) {
513 logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
518 void (*handler)(int);
520 {SIGHUP, sighup_handler},
521 {SIGTERM, sigterm_handler},
522 {SIGQUIT, sigquit_handler},
524 {SIGBUS, fatal_signal_handler},
525 {SIGILL, fatal_signal_handler},
526 {SIGPIPE, ignore_signal_handler},
527 {SIGINT, sigint_handler},
528 {SIGUSR1, sigusr1_handler},
529 {SIGUSR2, sigusr2_handler},
530 {SIGCHLD, ignore_signal_handler},
531 {SIGALRM, sigalrm_handler},
532 {SIGWINCH, sigwinch_handler},
537 void setup_signals(void)
541 struct sigaction act;
543 sigemptyset(&emptysigset);
544 act.sa_handler = NULL;
545 act.sa_mask = emptysigset;
548 /* Set a default signal handler for every signal, errors will be
550 for(i = 0; i < NSIG; i++) {
551 act.sa_handler = unexpected_signal_handler;
552 sigaction(i, &act, NULL);
555 /* Then, for each known signal that we want to catch, assign a
556 handler to the signal, with error checking this time. */
557 for(i = 0; sighandlers[i].signal; i++) {
558 act.sa_handler = sighandlers[i].handler;
559 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
560 fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
561 sighandlers[i].signal, strsignal(sighandlers[i].signal),