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