Small fixes to make LZO compression work.
[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.50 2002/09/30 19:04:37 zarq 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 = -1;
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 != -1) {
368                 syslog(LOG_NOTICE, _("Reverting to old debug level (%d)"),
369                            saved_debug_lvl);
370                 debug_lvl = saved_debug_lvl;
371                 saved_debug_lvl = -1;
372         } else {
373                 syslog(LOG_NOTICE, _("Temporarily setting debug level to 5.  Kill me with SIGINT again to go back to level %d."),
374                            debug_lvl);
375                 saved_debug_lvl = debug_lvl;
376                 debug_lvl = 5;
377         }
378 }
379
380 RETSIGTYPE sigalrm_handler(int a)
381 {
382         if(debug_lvl > DEBUG_NOTHING)
383                 syslog(LOG_NOTICE, _("Got ALRM signal"));
384         sigalrm = 1;
385 }
386
387 RETSIGTYPE sigusr1_handler(int a)
388 {
389         dump_connections();
390 }
391
392 RETSIGTYPE sigusr2_handler(int a)
393 {
394         dump_device_stats();
395         dump_nodes();
396         dump_edges();
397         dump_subnets();
398 }
399
400 RETSIGTYPE sigwinch_handler(int a)
401 {
402         extern int do_purge;
403         do_purge = 1;
404 }
405
406 RETSIGTYPE unexpected_signal_handler(int a)
407 {
408         syslog(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
409         cp_trace();
410 }
411
412 RETSIGTYPE ignore_signal_handler(int a)
413 {
414         if(debug_lvl >= DEBUG_SCARY_THINGS) {
415                 syslog(LOG_DEBUG, _("Ignored signal %d (%s)"), a, strsignal(a));
416                 cp_trace();
417         }
418 }
419
420 struct {
421         int signal;
422         void (*handler)(int);
423 } sighandlers[] = {
424         {
425         SIGHUP, sighup_handler}, {
426         SIGTERM, sigterm_handler}, {
427         SIGQUIT, sigquit_handler}, {
428         SIGSEGV, fatal_signal_handler}, {
429         SIGBUS, fatal_signal_handler}, {
430         SIGILL, fatal_signal_handler}, {
431         SIGPIPE, ignore_signal_handler}, {
432         SIGINT, sigint_handler}, {
433         SIGUSR1, sigusr1_handler}, {
434         SIGUSR2, sigusr2_handler}, {
435         SIGCHLD, ignore_signal_handler}, {
436         SIGALRM, sigalrm_handler}, {
437         SIGWINCH, sigwinch_handler}, {
438         0, NULL}
439 };
440
441 void setup_signals(void)
442 {
443         int i;
444         struct sigaction act;
445
446         sigemptyset(&emptysigset);
447         act.sa_handler = NULL;
448         act.sa_mask = emptysigset;
449         act.sa_flags = 0;
450
451         /* Set a default signal handler for every signal, errors will be
452            ignored. */
453         for(i = 0; i < NSIG; i++) {
454                 if(!do_detach)
455                         act.sa_handler = SIG_DFL;
456                 else
457                         act.sa_handler = unexpected_signal_handler;
458                 sigaction(i, &act, NULL);
459         }
460
461         /* If we didn't detach, allow coredumps */
462         if(!do_detach)
463                 sighandlers[3].handler = SIG_DFL;
464
465         /* Then, for each known signal that we want to catch, assign a
466            handler to the signal, with error checking this time. */
467         for(i = 0; sighandlers[i].signal; i++) {
468                 act.sa_handler = sighandlers[i].handler;
469                 if(sigaction(sighandlers[i].signal, &act, NULL) < 0)
470                         fprintf(stderr, _("Installing signal handler for signal %d (%s) failed: %s\n"),
471                                         sighandlers[i].signal, strsignal(sighandlers[i].signal),
472                                         strerror(errno));
473         }
474 }