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