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