2 process.c -- process management functions
3 Copyright (C) 1999-2003 Ivo Timmermans <ivo@o2w.nl>,
4 2000-2003 Guus Sliepen <guus@sliepen.eu.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.
20 $Id: process.c,v 1.1.2.63 2003/08/03 21:45:13 guus Exp $
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... */
61 #ifndef HAVE_FCLOSEALL
62 static int fcloseall(void)
75 extern char *identname;
76 extern char *program_name;
79 static SC_HANDLE manager = NULL;
80 static SC_HANDLE service = NULL;
81 static SERVICE_STATUS status = {0};
82 static SERVICE_STATUS_HANDLE statushandle = 0;
84 bool install_service(void) {
85 char command[4096] = "";
88 manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
90 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
94 if(!strchr(program_name, '\\')) {
95 GetCurrentDirectory(sizeof(command), command);
96 strncat(command, "\\", sizeof(command));
99 strncat(command, program_name, sizeof(command));
100 for(argp = g_argv + 1; *argp; argp++) {
101 strncat(command, " ", sizeof(command));
102 strncat(command, *argp, sizeof(command));
105 service = CreateService(manager, identname, identname,
106 SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
107 command, "NDIS", NULL, NULL, NULL, NULL);
110 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
114 logger(LOG_INFO, _("%s service installed"), identname);
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_STOP:
156 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
159 case SERVICE_CONTROL_SHUTDOWN:
160 logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
164 logger(LOG_WARNING, _("Got unexpected request %d"), request);
165 return ERROR_CALL_NOT_IMPLEMENTED;
169 status.dwCurrentState = SERVICE_STOP_PENDING;
170 SetServiceStatus(statushandle, &status);
176 VOID WINAPI run_service(DWORD argc, LPTSTR* argv)
179 extern int main2(int argc, char **argv);
182 status.dwServiceType = SERVICE_WIN32;
183 status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
184 status.dwWin32ExitCode = 0;
185 status.dwServiceSpecificExitCode = 0;
186 status.dwCheckPoint = 0;
187 status.dwWaitHint = 0;
189 statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL);
192 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
195 status.dwCurrentState = SERVICE_START_PENDING;
196 SetServiceStatus(statushandle, &status);
198 status.dwCurrentState = SERVICE_RUNNING;
199 SetServiceStatus(statushandle, &status);
201 err = main2(argc, argv);
203 status.dwCurrentState = SERVICE_STOPPED;
204 //status.dwWin32ExitCode = err;
205 SetServiceStatus(statushandle, &status);
211 bool init_service(void) {
212 SERVICE_TABLE_ENTRY services[] = {
213 {identname, run_service},
217 if(!StartServiceCtrlDispatcher(services)) {
218 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
222 logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
231 check for an existing tinc for this net, and write pid to pidfile
233 static bool write_pidfile(void)
239 pid = check_pid(pidfilename);
243 fprintf(stderr, _("A tincd is already running for net `%s' with pid %d.\n"),
246 fprintf(stderr, _("A tincd is already running with pid %d.\n"), pid);
250 /* if it's locked, write-protected, or whatever */
251 if(!write_pid(pidfilename))
259 kill older tincd for this net
261 bool kill_other(int signal)
268 pid = read_pid(pidfilename);
272 fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
275 fprintf(stderr, _("No other tincd is running.\n"));
279 errno = 0; /* No error, sometimes errno is only changed on error */
281 /* ESRCH is returned when no process with that pid is found */
282 if(kill(pid, signal) && errno == ESRCH) {
284 fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
287 fprintf(stderr, _("The tincd is no longer running. "));
289 fprintf(stderr, _("Removing stale lock file.\n"));
290 remove_pid(pidfilename);
295 return remove_service();
300 Detach from current terminal, write pidfile, kill parent
308 /* First check if we can open a fresh new pidfile */
314 /* If we succeeded in doing that, detach */
322 fprintf(stderr, _("Couldn't detach from terminal: %s"),
327 /* Now UPDATE the pid in the pidfile, because we changed it... */
329 if(!write_pid(pidfilename))
333 exit(install_service());
337 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
339 logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
340 VERSION, __DATE__, __TIME__, debug_level);
342 xalloc_fail_func = memory_full;
349 Execute the program name, with sane environment.
351 static void _execute_script(const char *scriptname, char **envp)
352 __attribute__ ((__noreturn__));
353 static void _execute_script(const char *scriptname, char **envp)
366 /* Close all file descriptors */
369 execl(scriptname, scriptname, NULL);
370 /* No return on success */
374 openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
375 logger(LOG_ERR, _("Could not execute `%s': %s"), scriptname,
376 strerror(save_errno));
382 Fork and execute the program pointed to by name.
384 bool execute_script(const char *name, char **envp)
394 asprintf(&scriptname, "%s/%s", confbase, name);
396 /* First check if there is a script */
398 if(stat(scriptname, &s))
404 logger(LOG_ERR, _("System call `%s' failed: %s"), "fork",
410 ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
414 if(waitpid(pid, &status, 0) == pid) {
415 if(WIFEXITED(status)) { /* Child exited by itself */
416 if(WEXITSTATUS(status)) {
417 logger(LOG_ERR, _("Process %d (%s) exited with non-zero status %d"),
418 pid, name, WEXITSTATUS(status));
422 } else if(WIFSIGNALED(status)) { /* Child was killed by a signal */
423 logger(LOG_ERR, _("Process %d (%s) was killed by signal %d (%s)"), pid,
424 name, WTERMSIG(status), strsignal(WTERMSIG(status)));
426 } else { /* Something strange happened */
427 logger(LOG_ERR, _("Process %d (%s) terminated abnormally"), pid,
431 } else if (errno != EINTR) {
432 logger(LOG_ERR, _("System call `%s' failed: %s"), "waitpid",
437 /* Why do we get EINTR? */
443 _execute_script(scriptname, envp);
455 static RETSIGTYPE sigterm_handler(int a)
457 logger(LOG_NOTICE, _("Got %s signal"), "TERM");
461 static RETSIGTYPE sigquit_handler(int a)
463 logger(LOG_NOTICE, _("Got %s signal"), "QUIT");
467 static RETSIGTYPE fatal_signal_square(int a)
469 logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
475 static RETSIGTYPE fatal_signal_handler(int a)
477 struct sigaction act;
478 logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
482 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
484 act.sa_handler = fatal_signal_square;
485 act.sa_mask = emptysigset;
487 sigaction(SIGSEGV, &act, NULL);
489 close_network_connections();
491 remove_pid(pidfilename);
492 execvp(g_argv[0], g_argv);
494 logger(LOG_NOTICE, _("Not restarting."));
499 static RETSIGTYPE sighup_handler(int a)
501 logger(LOG_NOTICE, _("Got %s signal"), "HUP");
505 static RETSIGTYPE sigint_handler(int a)
507 logger(LOG_NOTICE, _("Got %s signal"), "INT");
509 if(saved_debug_level != -1) {
510 logger(LOG_NOTICE, _("Reverting to old debug level (%d)"),
512 debug_level = saved_debug_level;
513 saved_debug_level = -1;
516 _("Temporarily setting debug level to 5. Kill me with SIGINT again to go back to level %d."),
518 saved_debug_level = debug_level;
523 static RETSIGTYPE sigalrm_handler(int a)
525 logger(LOG_NOTICE, _("Got %s signal"), "ALRM");
529 static RETSIGTYPE sigusr1_handler(int a)
534 static RETSIGTYPE sigusr2_handler(int a)
542 static RETSIGTYPE sigwinch_handler(int a)
547 static RETSIGTYPE unexpected_signal_handler(int a)
549 logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
553 static RETSIGTYPE ignore_signal_handler(int a)
555 ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
560 void (*handler)(int);
562 {SIGHUP, sighup_handler},
563 {SIGTERM, sigterm_handler},
564 {SIGQUIT, sigquit_handler},
565 {SIGSEGV, fatal_signal_handler},
566 {SIGBUS, fatal_signal_handler},
567 {SIGILL, fatal_signal_handler},
568 {SIGPIPE, ignore_signal_handler},
569 {SIGINT, sigint_handler},
570 {SIGUSR1, sigusr1_handler},
571 {SIGUSR2, sigusr2_handler},
572 {SIGCHLD, ignore_signal_handler},
573 {SIGALRM, sigalrm_handler},
574 {SIGWINCH, sigwinch_handler},
579 void setup_signals(void)
583 struct sigaction act;
585 sigemptyset(&emptysigset);
586 act.sa_handler = NULL;
587 act.sa_mask = emptysigset;
590 /* Set a default signal handler for every signal, errors will be
592 for(i = 0; i < NSIG; i++) {
594 act.sa_handler = SIG_DFL;
596 act.sa_handler = unexpected_signal_handler;
597 sigaction(i, &act, NULL);
600 /* If we didn't detach, allow coredumps */
602 sighandlers[3].handler = SIG_DFL;
604 /* Then, for each known signal that we want to catch, assign a
605 handler to the signal, with error checking this time. */
606 for(i = 0; sighandlers[i].signal; i++) {
607 act.sa_handler = sighandlers[i].handler;
608 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
609 fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
610 sighandlers[i].signal, strsignal(sighandlers[i].signal),