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