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