No easy way to properly detect header files...
[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.59 2003/07/30 21:52:41 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
47 sigset_t emptysigset;
48
49 static int saved_debug_level = -1;
50
51 static void memory_full(int size)
52 {
53         logger(LOG_ERR, _("Memory exhausted (couldn't allocate %d bytes), exitting."), size);
54         cp_trace();
55         exit(1);
56 }
57
58 /* Some functions the less gifted operating systems might lack... */
59
60 #ifndef HAVE_FCLOSEALL
61 static int fcloseall(void)
62 {
63         fflush(stdin);
64         fflush(stdout);
65         fflush(stderr);
66         fclose(stdin);
67         fclose(stdout);
68         fclose(stderr);
69         return 0;
70 }
71 #endif
72
73 /*
74   Close network connections, and terminate neatly
75 */
76 void cleanup_and_exit(int c)
77 {
78         cp();
79
80         close_network_connections();
81
82         ifdebug(CONNECTIONS)
83                 dump_device_stats();
84
85         logger(LOG_NOTICE, _("Terminating"));
86
87         closelogger();
88         exit(c);
89 }
90
91 #ifndef HAVE_MINGW
92 /*
93   check for an existing tinc for this net, and write pid to pidfile
94 */
95 static bool write_pidfile(void)
96 {
97         int pid;
98
99         cp();
100
101         pid = check_pid(pidfilename);
102
103         if(pid) {
104                 if(netname)
105                         fprintf(stderr, _("A tincd is already running for net `%s' with pid %d.\n"),
106                                         netname, pid);
107                 else
108                         fprintf(stderr, _("A tincd is already running with pid %d.\n"), pid);
109                 return false;
110         }
111
112         /* if it's locked, write-protected, or whatever */
113         if(!write_pid(pidfilename))
114                 return false;
115
116         return true;
117 }
118 #endif
119
120 /*
121   kill older tincd for this net
122 */
123 bool kill_other(int signal)
124 {
125 #ifndef HAVE_MINGW
126         int pid;
127
128         cp();
129
130         pid = read_pid(pidfilename);
131
132         if(!pid) {
133                 if(netname)
134                         fprintf(stderr, _("No other tincd is running for net `%s'.\n"),
135                                         netname);
136                 else
137                         fprintf(stderr, _("No other tincd is running.\n"));
138                 return false;
139         }
140
141         errno = 0;                                      /* No error, sometimes errno is only changed on error */
142
143         /* ESRCH is returned when no process with that pid is found */
144         if(kill(pid, signal) && errno == ESRCH) {
145                 if(netname)
146                         fprintf(stderr, _("The tincd for net `%s' is no longer running. "),
147                                         netname);
148                 else
149                         fprintf(stderr, _("The tincd is no longer running. "));
150
151                 fprintf(stderr, _("Removing stale lock file.\n"));
152                 remove_pid(pidfilename);
153         }
154 #endif
155
156         return true;
157 }
158
159 /*
160   Detach from current terminal, write pidfile, kill parent
161 */
162 bool detach(void)
163 {
164         cp();
165
166         setup_signals();
167
168         /* First check if we can open a fresh new pidfile */
169
170 #ifndef HAVE_MINGW
171         if(!write_pidfile())
172                 return false;
173 #endif
174
175         /* If we succeeded in doing that, detach */
176
177         closelogger();
178
179 #ifdef HAVE_FORK
180         if(do_detach) {
181                 if(daemon(0, 0)) {
182                         fprintf(stderr, _("Couldn't detach from terminal: %s"),
183                                         strerror(errno));
184                         return false;
185                 }
186
187                 /* Now UPDATE the pid in the pidfile, because we changed it... */
188
189                 if(!write_pid(pidfilename))
190                         return false;
191         }
192 #endif
193
194         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
195
196         logger(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
197                            VERSION, __DATE__, __TIME__, debug_level);
198
199         xalloc_fail_func = memory_full;
200
201         return true;
202 }
203
204 #ifdef HAVE_FORK
205 /*
206   Execute the program name, with sane environment.
207 */
208 static void _execute_script(const char *scriptname, char **envp)
209         __attribute__ ((__noreturn__));
210 static void _execute_script(const char *scriptname, char **envp)
211 {
212         int save_errno;
213
214         cp();
215
216         while(*envp)
217                 putenv(*envp++);
218
219         chdir("/");
220
221         closelogger();
222
223         /* Close all file descriptors */
224         fcloseall();
225
226         execl(scriptname, NULL);
227         /* No return on success */
228
229         save_errno = errno;
230
231         openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR));
232         logger(LOG_ERR, _("Could not execute `%s': %s"), scriptname,
233                    strerror(save_errno));
234         exit(save_errno);
235 }
236 #endif
237
238 /*
239   Fork and execute the program pointed to by name.
240 */
241 bool execute_script(const char *name, char **envp)
242 {
243 #ifdef HAVE_FORK
244         pid_t pid;
245         int status;
246         struct stat s;
247         char *scriptname;
248
249         cp();
250
251         asprintf(&scriptname, "%s/%s", confbase, name);
252
253         /* First check if there is a script */
254
255         if(stat(scriptname, &s))
256                 return true;
257
258         pid = fork();
259
260         if(pid < 0) {
261                 logger(LOG_ERR, _("System call `%s' failed: %s"), "fork",
262                            strerror(errno));
263                 return false;
264         }
265
266         if(pid) {
267                 ifdebug(STATUS) logger(LOG_INFO, _("Executing script %s"), name);
268
269                 free(scriptname);
270
271                 if(waitpid(pid, &status, 0) == pid) {
272                         if(WIFEXITED(status)) { /* Child exited by itself */
273                                 if(WEXITSTATUS(status)) {
274                                         logger(LOG_ERR, _("Process %d (%s) exited with non-zero status %d"),
275                                                    pid, name, WEXITSTATUS(status));
276                                         return false;
277                                 } else
278                                         return true;
279                         } else if(WIFSIGNALED(status)) {        /* Child was killed by a signal */
280                                 logger(LOG_ERR, _("Process %d (%s) was killed by signal %d (%s)"), pid,
281                                            name, WTERMSIG(status), strsignal(WTERMSIG(status)));
282                                 return false;
283                         } else {                        /* Something strange happened */
284                                 logger(LOG_ERR, _("Process %d (%s) terminated abnormally"), pid,
285                                            name);
286                                 return false;
287                         }
288                 } else if (errno != EINTR) {
289                         logger(LOG_ERR, _("System call `%s' failed: %s"), "waitpid",
290                                    strerror(errno));
291                         return false;
292                 }
293
294                 /* Why do we get EINTR? */
295                 return true;
296         }
297
298         /* Child here */
299
300         _execute_script(scriptname, envp);
301 #else
302         return true;
303 #endif
304 }
305
306
307 /*
308   Signal handlers.
309 */
310
311 #ifndef HAVE_MINGW
312 static RETSIGTYPE sigterm_handler(int a)
313 {
314         logger(LOG_NOTICE, _("Got TERM signal"));
315
316         cleanup_and_exit(0);
317 }
318
319 static RETSIGTYPE sigquit_handler(int a)
320 {
321         logger(LOG_NOTICE, _("Got QUIT signal"));
322         cleanup_and_exit(0);
323 }
324
325 static RETSIGTYPE fatal_signal_square(int a)
326 {
327         logger(LOG_ERR, _("Got another fatal signal %d (%s): not restarting."), a,
328                    strsignal(a));
329         cp_trace();
330         exit(1);
331 }
332
333 static RETSIGTYPE fatal_signal_handler(int a)
334 {
335         struct sigaction act;
336         logger(LOG_ERR, _("Got fatal signal %d (%s)"), a, strsignal(a));
337         cp_trace();
338
339         if(do_detach) {
340                 logger(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
341
342                 act.sa_handler = fatal_signal_square;
343                 act.sa_mask = emptysigset;
344                 act.sa_flags = 0;
345                 sigaction(SIGSEGV, &act, NULL);
346
347                 close_network_connections();
348                 sleep(5);
349                 remove_pid(pidfilename);
350                 execvp(g_argv[0], g_argv);
351         } else {
352                 logger(LOG_NOTICE, _("Not restarting."));
353                 exit(1);
354         }
355 }
356
357 static RETSIGTYPE sighup_handler(int a)
358 {
359         logger(LOG_NOTICE, _("Got HUP signal"));
360         sighup = true;
361 }
362
363 static RETSIGTYPE sigint_handler(int a)
364 {
365         if(saved_debug_level != -1) {
366                 logger(LOG_NOTICE, _("Reverting to old debug level (%d)"),
367                         saved_debug_level);
368                 debug_level = saved_debug_level;
369                 saved_debug_level = -1;
370         } else {
371                 logger(LOG_NOTICE,
372                         _("Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d."),
373                         debug_level);
374                 saved_debug_level = debug_level;
375                 debug_level = 5;
376         }
377 }
378
379 static RETSIGTYPE sigalrm_handler(int a)
380 {
381         logger(LOG_NOTICE, _("Got ALRM signal"));
382         sigalrm = true;
383 }
384
385 static RETSIGTYPE sigusr1_handler(int a)
386 {
387         dump_connections();
388 }
389
390 static RETSIGTYPE sigusr2_handler(int a)
391 {
392         dump_device_stats();
393         dump_nodes();
394         dump_edges();
395         dump_subnets();
396 }
397
398 static RETSIGTYPE sigwinch_handler(int a)
399 {
400         do_purge = true;
401 }
402
403 static RETSIGTYPE unexpected_signal_handler(int a)
404 {
405         logger(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
406         cp_trace();
407 }
408
409 static RETSIGTYPE ignore_signal_handler(int a)
410 {
411         ifdebug(SCARY_THINGS) logger(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
412 }
413
414 static struct {
415         int signal;
416         void (*handler)(int);
417 } sighandlers[] = {
418         {SIGHUP, sighup_handler},
419         {SIGTERM, sigterm_handler},
420         {SIGQUIT, sigquit_handler},
421         {SIGSEGV, fatal_signal_handler},
422         {SIGBUS, fatal_signal_handler},
423         {SIGILL, fatal_signal_handler},
424         {SIGPIPE, ignore_signal_handler},
425         {SIGINT, sigint_handler},
426         {SIGUSR1, sigusr1_handler},
427         {SIGUSR2, sigusr2_handler},
428         {SIGCHLD, ignore_signal_handler},
429         {SIGALRM, sigalrm_handler},
430         {SIGWINCH, sigwinch_handler},
431         {0, NULL}
432 };
433 #endif
434
435 void setup_signals(void)
436 {
437 #ifndef HAVE_MINGW
438         int i;
439         struct sigaction act;
440
441         sigemptyset(&emptysigset);
442         act.sa_handler = NULL;
443         act.sa_mask = emptysigset;
444         act.sa_flags = 0;
445
446         /* Set a default signal handler for every signal, errors will be
447            ignored. */
448         for(i = 0; i < NSIG; i++) {
449                 if(!do_detach)
450                         act.sa_handler = SIG_DFL;
451                 else
452                         act.sa_handler = unexpected_signal_handler;
453                 sigaction(i, &act, NULL);
454         }
455
456         /* If we didn't detach, allow coredumps */
457         if(!do_detach)
458                 sighandlers[3].handler = SIG_DFL;
459
460         /* Then, for each known signal that we want to catch, assign a
461            handler to the signal, with error checking this time. */
462         for(i = 0; sighandlers[i].signal; i++) {
463                 act.sa_handler = sighandlers[i].handler;
464                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
465                         fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
466                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
467                                         strerror(errno));
468         }
469 #endif
470 }