c989532e26be0f14888e298354e0a88571cdb6fc
[tinc] / src / process.c
1 /*
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>
5
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.
10
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.
15
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.
19
20     $Id: process.c,v 1.1.2.65 2003/08/08 14:48:33 guus Exp $
21 */
22
23 #include "system.h"
24
25 #include "conf.h"
26 #include "connection.h"
27 #include "device.h"
28 #include "edge.h"
29 #include "logger.h"
30 #include "node.h"
31 #include "pidfile.h"
32 #include "process.h"
33 #include "subnet.h"
34 #include "utils.h"
35 #include "xalloc.h"
36
37 /* If zero, don't detach from the terminal. */
38 bool do_detach = true;
39 bool sighup = false;
40 bool sigalrm = false;
41
42 extern char *identname;
43 extern char *pidfilename;
44 extern char **g_argv;
45 extern bool use_logfile;
46 extern volatile bool running;
47
48 sigset_t emptysigset;
49
50 static int saved_debug_level = -1;
51
52 static void memory_full(int size)
53 {
54         logger(LOG_ERR, _("Memory exhausted (couldn't allocate %d bytes), exitting."), size);
55         cp_trace();
56         exit(1);
57 }
58
59 /* Some functions the less gifted operating systems might lack... */
60
61 #ifndef HAVE_FCLOSEALL
62 static int fcloseall(void)
63 {
64         fflush(stdin);
65         fflush(stdout);
66         fflush(stderr);
67         fclose(stdin);
68         fclose(stdout);
69         fclose(stderr);
70         return 0;
71 }
72 #endif
73
74 #ifdef HAVE_MINGW
75 extern char *identname;
76 extern char *program_name;
77 extern char **g_argv;
78
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;
83
84 bool install_service(void) {
85         char command[4096] = "";
86         char **argp;
87
88         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
89         if(!manager) {
90                 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
91                 return false;
92         }
93
94         if(!strchr(program_name, '\\')) {
95                 GetCurrentDirectory(sizeof(command), command);
96                 strncat(command, "\\", sizeof(command));
97         }
98
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));
103         }
104
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);
108         
109         if(!service) {
110                 logger(LOG_ERR, _("Could not create %s service: %s"), identname, winerror(GetLastError()));
111                 return false;
112         }
113
114         logger(LOG_INFO, _("%s service installed"), identname);
115
116         if(!StartService(service, 0, NULL))
117                 logger(LOG_WARNING, _("Could not start %s service: %s"), identname, winerror(GetLastError()));
118         else
119                 logger(LOG_INFO, _("%s service started"), identname);
120
121         return true;
122 }
123
124 bool remove_service(void) {
125         manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
126         if(!manager) {
127                 logger(LOG_ERR, _("Could not open service manager: %s"), winerror(GetLastError()));
128                 return false;
129         }
130
131         service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
132
133         if(!service) {
134                 logger(LOG_ERR, _("Could not open %s service: %s"), identname, winerror(GetLastError()));
135                 return false;
136         }
137
138         if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
139                 logger(LOG_ERR, _("Could not stop %s service: %s"), identname, winerror(GetLastError()));
140         else
141                 logger(LOG_INFO, _("%s service stopped"), identname);
142
143         if(!DeleteService(service)) {
144                 logger(LOG_ERR, _("Could not remove %s service: %s"), identname, winerror(GetLastError()));
145                 return false;
146         }
147
148         logger(LOG_INFO, _("%s service removed"), identname);
149
150         return true;
151 }
152
153 DWORD WINAPI controlhandler(DWORD request, DWORD type, LPVOID boe, LPVOID bah) {
154         switch(request) {
155                 case SERVICE_CONTROL_STOP:
156                         logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_STOP");
157                         running = false;
158                         break;
159                 case SERVICE_CONTROL_SHUTDOWN:
160                         logger(LOG_NOTICE, _("Got %s request"), "SERVICE_CONTROL_SHUTDOWN");
161                         running = false;
162                         break;
163                 default:
164                         logger(LOG_WARNING, _("Got unexpected request %d"), request);
165                         return ERROR_CALL_NOT_IMPLEMENTED;
166         }
167
168         if(!running) {
169                 status.dwWaitHint = 30000; 
170                 status.dwCurrentState = SERVICE_STOP_PENDING; 
171                 SetServiceStatus(statushandle, &status);
172         }
173
174         return NO_ERROR;
175 }
176
177 VOID WINAPI run_service(DWORD argc, LPTSTR* argv)
178 {
179         int err = 1;
180         extern int main2(int argc, char **argv);
181
182
183         status.dwServiceType = SERVICE_WIN32; 
184         status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
185         status.dwWin32ExitCode = 0; 
186         status.dwServiceSpecificExitCode = 0; 
187         status.dwCheckPoint = 0; 
188
189         statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 
190
191         if (!statushandle) {
192                 logger(LOG_ERR, _("System call `%s' failed: %s"), "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
193                 err = 1;
194         } else {
195                 status.dwWaitHint = 30000; 
196                 status.dwCurrentState = SERVICE_START_PENDING; 
197                 SetServiceStatus(statushandle, &status);
198
199                 status.dwWaitHint = 0; 
200                 status.dwCurrentState = SERVICE_RUNNING;
201                 SetServiceStatus(statushandle, &status);
202
203                 err = main2(argc, argv);
204
205                 status.dwWaitHint = 0;
206                 status.dwCurrentState = SERVICE_STOPPED; 
207                 //status.dwWin32ExitCode = err; 
208                 SetServiceStatus(statushandle, &status);
209         }
210
211         return;
212 }
213
214 bool init_service(void) {
215         SERVICE_TABLE_ENTRY services[] = {
216                 {identname, run_service},
217                 {NULL, NULL}
218         };
219
220         if(!StartServiceCtrlDispatcher(services)) {
221                 if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
222                         return false;
223                 }
224                 else
225                         logger(LOG_ERR, _("System call `%s' failed: %s"), "StartServiceCtrlDispatcher", winerror(GetLastError()));
226         }
227
228         return true;
229 }
230 #endif
231
232 #ifndef HAVE_MINGW
233 /*
234   check for an existing tinc for this net, and write pid to pidfile
235 */
236 static bool write_pidfile(void)
237 {
238         int pid;
239
240         cp();
241
242         pid = check_pid(pidfilename);
243
244         if(pid) {
245                 if(netname)
246                         fprintf(stderr, _("A tincd is already running for net `%s' with pid %d.\n"),
247                                         netname, pid);
248                 else
249                         fprintf(stderr, _("A tincd is already running with pid %d.\n"), pid);
250                 return false;
251         }
252
253         /* if it's locked, write-protected, or whatever */
254         if(!write_pid(pidfilename))
255                 return false;
256
257         return true;
258 }
259 #endif
260
261 /*
262   kill older tincd for this net
263 */
264 bool kill_other(int signal)
265 {
266 #ifndef HAVE_MINGW
267         int pid;
268
269         cp();
270
271         pid = read_pid(pidfilename);
272
273         if(!pid) {
274                 if(netname)
275                         fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
276                                         netname);
277                 else
278                         fprintf(stderr, _("No other tincd is running.\n"));
279                 return false;
280         }
281
282         errno = 0;                                      /* No error, sometimes errno is only changed on error */
283
284         /* ESRCH is returned when no process with that pid is found */
285         if(kill(pid, signal) && errno == ESRCH) {
286                 if(netname)
287                         fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
288                                         netname);
289                 else
290                         fprintf(stderr, _("The tincd is no longer running. "));
291
292                 fprintf(stderr, _("Removing stale lock file.\n"));
293                 remove_pid(pidfilename);
294         }
295
296         return true;
297 #else
298         return remove_service();
299 #endif
300 }
301
302 /*
303   Detach from current terminal, write pidfile, kill parent
304 */
305 bool detach(void)
306 {
307         cp();
308
309         setup_signals();
310
311         /* First check if we can open a fresh new pidfile */
312
313 #ifndef HAVE_MINGW
314         if(!write_pidfile())
315                 return false;
316
317         /* If we succeeded in doing that, detach */
318
319         closelogger();
320 #endif
321
322         if(do_detach) {
323 #ifndef HAVE_MINGW
324                 if(daemon(0, 0)) {
325                         fprintf(stderr, _("Couldn't detach from terminal: %s"),
326                                         strerror(errno));
327                         return false;
328                 }
329
330                 /* Now UPDATE the pid in the pidfile, because we changed it... */
331
332                 if(!write_pid(pidfilename))
333                         return false;
334 #else
335                 if(!statushandle)
336                         exit(install_service());
337 #endif
338         }
339
340         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
341
342         logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
343                            VERSION, __DATE__, __TIME__, debug_level);
344
345         xalloc_fail_func = memory_full;
346
347         return true;
348 }
349
350 bool execute_script(const char *name, char **envp)
351 {
352 #ifdef HAVE_SYSTEM
353         pid_t pid;
354         int status;
355         struct stat s;
356         char *scriptname;
357
358         cp();
359
360         asprintf(&scriptname, "%s/%s", confbase, name);
361
362         /* First check if there is a script */
363
364         if(stat(scriptname, &s))
365                 return true;
366
367         /* Set environment */
368         
369         while(*envp)
370                 putenv(*envp++);
371
372         ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
373
374         status = system(scriptname);
375
376         free(scriptname);
377
378         /* Unset environment? */
379
380         if(status != -1) {
381                 if(WIFEXITED(status)) { /* Child exited by itself */
382                         if(WEXITSTATUS(status)) {
383                                 logger(LOG_ERR, _("Process %d (%s) exited with non-zero status %d"),
384                                            pid, name, WEXITSTATUS(status));
385                                 return false;
386                         }
387                 } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
388                         logger(LOG_ERR, _("Process %d (%s) was killed by signal %d (%s)"), pid,
389                                    name, WTERMSIG(status), strsignal(WTERMSIG(status)));
390                         return false;
391                 } else {                        /* Something strange happened */
392                         logger(LOG_ERR, _("Process %d (%s) terminated abnormally"), pid,
393                                    name);
394                         return false;
395                 }
396         } else {
397                 logger(LOG_ERR, _("System call `%s' failed: %s"), "system",
398                            strerror(errno));
399                 return false;
400         }
401 #endif
402         return true;
403 }
404
405
406 /*
407   Signal handlers.
408 */
409
410 #ifndef HAVE_MINGW
411 static RETSIGTYPE sigterm_handler(int a)
412 {
413         logger(LOG_NOTICE, _("Got %s signal"), "TERM");
414         running = false;
415 }
416
417 static RETSIGTYPE sigquit_handler(int a)
418 {
419         logger(LOG_NOTICE, _("Got %s signal"), "QUIT");
420         running = false;
421 }
422
423 static RETSIGTYPE fatal_signal_square(int a)
424 {
425         logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
426                    strsignal(a));
427         cp_trace();
428         exit(1);
429 }
430
431 static RETSIGTYPE fatal_signal_handler(int a)
432 {
433         struct sigaction act;
434         logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
435         cp_trace();
436
437         if(do_detach) {
438                 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
439
440                 act.sa_handler = fatal_signal_square;
441                 act.sa_mask = emptysigset;
442                 act.sa_flags = 0;
443                 sigaction(SIGSEGV, &act, NULL);
444
445                 close_network_connections();
446                 sleep(5);
447                 remove_pid(pidfilename);
448                 execvp(g_argv[0], g_argv);
449         } else {
450                 logger(LOG_NOTICE, _("Not restarting."));
451                 exit(1);
452         }
453 }
454
455 static RETSIGTYPE sighup_handler(int a)
456 {
457         logger(LOG_NOTICE, _("Got %s signal"), "HUP");
458         sighup = true;
459 }
460
461 static RETSIGTYPE sigint_handler(int a)
462 {
463         logger(LOG_NOTICE, _("Got %s signal"), "INT");
464
465         if(saved_debug_level != -1) {
466                 logger(LOG_NOTICE, _("Reverting to old debug level (%d)"),
467                         saved_debug_level);
468                 debug_level = saved_debug_level;
469                 saved_debug_level = -1;
470         } else {
471                 logger(LOG_NOTICE,
472                         _("Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d."),
473                         debug_level);
474                 saved_debug_level = debug_level;
475                 debug_level = 5;
476         }
477 }
478
479 static RETSIGTYPE sigalrm_handler(int a)
480 {
481         logger(LOG_NOTICE, _("Got %s signal"), "ALRM");
482         sigalrm = true;
483 }
484
485 static RETSIGTYPE sigusr1_handler(int a)
486 {
487         dump_connections();
488 }
489
490 static RETSIGTYPE sigusr2_handler(int a)
491 {
492         dump_device_stats();
493         dump_nodes();
494         dump_edges();
495         dump_subnets();
496 }
497
498 static RETSIGTYPE sigwinch_handler(int a)
499 {
500         do_purge = true;
501 }
502
503 static RETSIGTYPE unexpected_signal_handler(int a)
504 {
505         logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
506         cp_trace();
507 }
508
509 static RETSIGTYPE ignore_signal_handler(int a)
510 {
511         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
512 }
513
514 static struct {
515         int signal;
516         void (*handler)(int);
517 } sighandlers[] = {
518         {SIGHUP, sighup_handler},
519         {SIGTERM, sigterm_handler},
520         {SIGQUIT, sigquit_handler},
521         {SIGSEGV, fatal_signal_handler},
522         {SIGBUS, fatal_signal_handler},
523         {SIGILL, fatal_signal_handler},
524         {SIGPIPE, ignore_signal_handler},
525         {SIGINT, sigint_handler},
526         {SIGUSR1, sigusr1_handler},
527         {SIGUSR2, sigusr2_handler},
528         {SIGCHLD, ignore_signal_handler},
529         {SIGALRM, sigalrm_handler},
530         {SIGWINCH, sigwinch_handler},
531         {0, NULL}
532 };
533 #endif
534
535 void setup_signals(void)
536 {
537 #ifndef HAVE_MINGW
538         int i;
539         struct sigaction act;
540
541         sigemptyset(&emptysigset);
542         act.sa_handler = NULL;
543         act.sa_mask = emptysigset;
544         act.sa_flags = 0;
545
546         /* Set a default signal handler for every signal, errors will be
547            ignored. */
548         for(i = 0; i < NSIG; i++) {
549                 if(!do_detach)
550                         act.sa_handler = SIG_DFL;
551                 else
552                         act.sa_handler = unexpected_signal_handler;
553                 sigaction(i, &act, NULL);
554         }
555
556         /* If we didn't detach, allow coredumps */
557         if(!do_detach)
558                 sighandlers[3].handler = SIG_DFL;
559
560         /* Then, for each known signal that we want to catch, assign a
561            handler to the signal, with error checking this time. */
562         for(i = 0; sighandlers[i].signal; i++) {
563                 act.sa_handler = sighandlers[i].handler;
564                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
565                         fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
566                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
567                                         strerror(errno));
568         }
569 #endif
570 }