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