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