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