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