1319c0c0b90881f0aa6188f64705efaa58f4667e
[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.14 2000/11/24 23:13:05 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   if(write_pidfile())
154     return -1;
155
156   if(do_detach)
157     if(daemon(0, 0) < 0)
158       return -1;
159
160   openlog(identname, LOG_CONS | LOG_PID, LOG_DAEMON);
161
162   if(debug_lvl > DEBUG_NOTHING)
163     syslog(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
164            VERSION, __DATE__, __TIME__, debug_lvl);
165   else
166     syslog(LOG_NOTICE, _("tincd %s starting"), VERSION);
167
168   xalloc_fail_func = memory_full;
169 cp
170   return 0;
171 }
172
173 /*
174   Execute the program name, with sane environment.  All output will be
175   redirected to syslog.
176 */
177 void _execute_script(const char *name)  __attribute__ ((noreturn));
178 void _execute_script(const char *name)
179 {
180   int error = 0;
181   char *scriptname;
182   char *s;
183   int fd;
184   
185 cp
186   if(netname)
187     {
188       asprintf(&s, "NETNAME=%s", netname);
189       putenv(s);        /* Don't free s! see man 3 putenv */
190     }
191 #ifdef HAVE_UNSETENV
192   else
193     {
194       unsetenv("NETNAME");
195     }
196 #endif
197
198   chdir("/");
199   
200   asprintf(&scriptname, "%s/%s", confbase, name);
201
202   /* Close all file descriptors */
203   closelog();           /* <- this means we cannot use syslog() here anymore! */
204   fcloseall();
205
206   execl(scriptname, NULL);
207   /* No return on success */
208   
209   if(errno != ENOENT)   /* Ignore if the file does not exist */
210     exit(-1);           /* Some error while trying execl(). */
211   else
212     exit(0);
213 }
214
215 /*
216   Fork and execute the program pointed to by name.
217 */
218 int execute_script(const char *name)
219 {
220   pid_t pid;
221   int status;
222 cp
223   if((pid = fork()) < 0)
224     {
225       syslog(LOG_ERR, _("System call `%s' failed: %m"),
226              "fork");
227       return -1;
228     }
229
230   if(pid)
231     {
232       if(debug_lvl >= DEBUG_STATUS)
233         syslog(LOG_INFO, _("Executing script %s"), name);
234
235       if(waitpid(pid, &status, 0) == pid)
236         {
237           if(WIFEXITED(status))         /* Child exited by itself */
238             {
239               if(WEXITSTATUS(status))
240                 {
241                   syslog(LOG_ERR, _("Process %d (%s) exited with non-zero status %d"), pid, name, WEXITSTATUS(status));
242                   return -1;
243                 }
244               else
245                 return 0;
246             }
247           else if(WIFSIGNALED(status))  /* Child was killed by a signal */
248             {
249               syslog(LOG_ERR, _("Process %d (%s) was killed by signal %d (%s)"),
250                      pid, name, WTERMSIG(status), strsignal(WTERMSIG(status)));
251               return -1;
252             }
253           else                          /* Something strange happened */
254             {
255               syslog(LOG_ERR, _("Process %d (%s) terminated abnormaly"), pid, name);
256               return -1;
257             }
258         }
259       else
260         {
261           syslog(LOG_ERR, _("System call `%s' failed: %m"), "waitpid");
262           return -1;
263         }
264     }
265 cp
266   /* Child here */
267
268   _execute_script(name);
269 }
270
271 /*
272   Signal handlers.
273 */
274
275 RETSIGTYPE
276 sigterm_handler(int a)
277 {
278   if(debug_lvl > DEBUG_NOTHING)
279     syslog(LOG_NOTICE, _("Got TERM signal"));
280
281   cleanup_and_exit(0);
282 }
283
284 RETSIGTYPE
285 sigquit_handler(int a)
286 {
287   if(debug_lvl > DEBUG_NOTHING)
288     syslog(LOG_NOTICE, _("Got QUIT signal"));
289   cleanup_and_exit(0);
290 }
291
292 RETSIGTYPE
293 sigsegv_square(int a)
294 {
295   syslog(LOG_ERR, _("Got another SEGV signal: not restarting"));
296   cp_trace();
297   exit(0);
298 }
299
300 RETSIGTYPE
301 sigsegv_handler(int a)
302 {
303   syslog(LOG_ERR, _("Got SEGV signal"));
304   cp_trace();
305
306   if(do_detach)
307     {
308       syslog(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
309       signal(SIGSEGV, sigsegv_square);
310       close_network_connections();
311       sleep(5);
312       remove_pid(pidfilename);
313       execvp(g_argv[0], g_argv);
314     }
315   else
316     {
317       syslog(LOG_NOTICE, _("Not restarting."));
318       exit(0);
319     }
320 }
321
322 RETSIGTYPE
323 sighup_handler(int a)
324 {
325   if(debug_lvl > DEBUG_NOTHING)
326     syslog(LOG_NOTICE, _("Got HUP signal"));
327   sighup = 1;
328 }
329
330 RETSIGTYPE
331 sigint_handler(int a)
332 {
333   if(debug_lvl > DEBUG_NOTHING)
334     syslog(LOG_NOTICE, _("Got INT signal, exiting"));
335   cleanup_and_exit(0);
336 }
337
338 RETSIGTYPE
339 sigusr1_handler(int a)
340 {
341   dump_connection_list();
342 }
343
344 RETSIGTYPE
345 sigusr2_handler(int a)
346 {
347   dump_subnet_list();
348 }
349
350 RETSIGTYPE
351 sighuh(int a)
352 {
353   syslog(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
354   cp_trace();
355 }
356
357 void
358 setup_signals(void)
359 {
360   int i;
361
362   for(i=0;i<32;i++)
363     signal(i,sighuh);
364
365   if(signal(SIGTERM, SIG_IGN) != SIG_ERR)
366     signal(SIGTERM, sigterm_handler);
367   if(signal(SIGQUIT, SIG_IGN) != SIG_ERR)
368     signal(SIGQUIT, sigquit_handler);
369   if(signal(SIGSEGV, SIG_IGN) != SIG_ERR)
370     signal(SIGSEGV, sigsegv_handler);
371   if(signal(SIGHUP, SIG_IGN) != SIG_ERR)
372     signal(SIGHUP, sighup_handler);
373   signal(SIGPIPE, SIG_IGN);
374   if(signal(SIGINT, SIG_IGN) != SIG_ERR)
375     signal(SIGINT, sigint_handler);
376   signal(SIGUSR1, sigusr1_handler);
377   signal(SIGUSR2, sigusr2_handler);
378   signal(SIGCHLD, SIG_IGN);
379 }