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