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