- Cleaned up and checked for some more NULL pointers in rbl.c
[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.9 2000/11/22 17:49:16 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 <syslog.h>
31 #include <sys/ioctl.h>
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 #include <unistd.h>
35
36 #include <list.h>
37 #include <pidfile.h>
38 #include <utils.h>
39 #include <xalloc.h>
40
41 #include "conf.h"
42 #include "process.h"
43
44 #include "system.h"
45
46 /* A list containing all our children */
47 list_t *child_pids = NULL;
48
49 /* If zero, don't detach from the terminal. */
50 int do_detach = 1;
51
52 static pid_t ppid;
53
54 extern char *identname;
55 extern char *pidfilename;
56 extern char **g_argv;
57
58 void init_processes(void)
59 {
60 cp
61   child_pids = list_new();
62 cp
63 }
64
65 void memory_full(int size)
66 {
67   syslog(LOG_ERR, _("Memory exhausted (couldn't allocate %d bytes), exiting."), size);
68   cp_trace();
69   exit(1);
70 }
71
72 /*
73   Close network connections, and terminate neatly
74 */
75 void cleanup_and_exit(int c)
76 {
77 cp
78   close_network_connections();
79
80   if(debug_lvl > DEBUG_NOTHING)
81     syslog(LOG_INFO, _("Total bytes written: tap %d, socket %d; bytes read: tap %d, socket %d"),
82            total_tap_out, total_socket_out, total_tap_in, total_socket_in);
83
84   closelog();
85   kill(ppid, SIGTERM);
86   exit(c);
87 }
88
89 /*
90   check for an existing tinc for this net, and write pid to pidfile
91 */
92 int write_pidfile(void)
93 {
94   int pid;
95 cp
96   if((pid = check_pid(pidfilename)))
97     {
98       if(netname)
99         fprintf(stderr, _("A tincd is already running for net `%s' with pid %d.\n"),
100                 netname, pid);
101       else
102         fprintf(stderr, _("A tincd is already running with pid %d.\n"), pid);
103       return 1;
104     }
105
106   /* if it's locked, write-protected, or whatever */
107   if(!write_pid(pidfilename))
108     return 1;
109 cp
110   return 0;
111 }
112
113 /*
114   kill older tincd for this net
115 */
116 int kill_other(void)
117 {
118   int pid;
119 cp
120   if(!(pid = read_pid(pidfilename)))
121     {
122       if(netname)
123         fprintf(stderr, _("No other tincd is running for net `%s'.\n"), netname);
124       else
125         fprintf(stderr, _("No other tincd is running.\n"));
126       return 1;
127     }
128
129   errno = 0;    /* No error, sometimes errno is only changed on error */
130   /* ESRCH is returned when no process with that pid is found */
131   if(kill(pid, SIGTERM) && errno == ESRCH)
132     fprintf(stderr, _("Removing stale lock file.\n"));
133   remove_pid(pidfilename);
134 cp
135   return 0;
136 }
137
138 /*
139   Detach from current terminal, write pidfile, kill parent
140 */
141 int detach(void)
142 {
143   int fd;
144   pid_t pid;
145 cp
146   setup_signals();
147
148   if(write_pidfile())
149     return -1;
150
151   if(do_detach)
152     daemon(0, 0);
153
154   openlog(identname, LOG_CONS | LOG_PID, LOG_DAEMON);
155
156   if(debug_lvl > DEBUG_NOTHING)
157     syslog(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
158            VERSION, __DATE__, __TIME__, debug_lvl);
159   else
160     syslog(LOG_NOTICE, _("tincd %s starting"), VERSION);
161
162   xalloc_fail_func = memory_full;
163 cp
164   return 0;
165 }
166
167 /*
168   Execute the program name, with sane environment.  All output will be
169   redirected to syslog.
170 */
171 void _execute_script(const char *name)  __attribute__ ((noreturn));
172 void _execute_script(const char *name)
173 {
174   int error = 0;
175   char *scriptname;
176   char *s;
177   int fd;
178   
179 cp
180   if(netname)
181     {
182       asprintf(&s, "NETNAME=%s", netname);
183       putenv(s);        /* Don't free s! see man 3 putenv */
184     }
185 #ifdef HAVE_UNSETENV
186   else
187     {
188       unsetenv("NETNAME");
189     }
190 #endif
191
192   if(chdir(confbase) < 0)
193     /* This cannot fail since we already read config files from this
194        directory. - Guus */
195     /* Yes this can fail, somebody could have removed this directory
196        when we didn't pay attention. - Ivo */
197     {
198       if(chdir("/") < 0)
199         /* Now if THIS fails, something wicked is going on. - Ivo */
200         syslog(LOG_ERR, _("Couldn't chdir to `/': %m"));
201
202       /* Continue anyway. */
203     }
204   
205   asprintf(&scriptname, "%s/%s", confbase, name);
206
207   /* Close all file descriptors */
208   closelog();
209   fcloseall();
210
211   /* Open standard input */
212   if((fd = open("/dev/null", O_RDONLY)) < 0)
213     {
214       syslog(LOG_ERR, _("Opening `/dev/null' failed: %m"));
215       error = 1;
216     }
217   if(dup2(fd, 0) != 0)
218     {
219       syslog(LOG_ERR, _("Couldn't assign /dev/null to standard input: %m"));
220       error = 1;
221     }
222
223   if(!error)
224     {
225       close(1);  /* fd #1 should be the first available filedescriptor now. */
226       /* Standard output directly goes to syslog */
227       openlog(name, LOG_CONS | LOG_PID, LOG_DAEMON);
228       /* Standard error as well */
229       if(dup2(1, 2) < 0)
230         {
231           syslog(LOG_ERR, _("System call `%s' failed: %m"),
232                  "dup2");
233           error = 1;
234         }
235     }
236   
237   if(error && debug_lvl > 1)
238     syslog(LOG_INFO, _("This means that any output the script generates will not be shown in syslog."));
239   
240   execl(scriptname, NULL);
241   /* No return on success */
242   
243   if(errno != ENOENT)  /* Ignore if the file does not exist */
244     syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
245
246   /* No need to free things */
247   exit(0);
248 }
249
250 /*
251   Fork and execute the program pointed to by name.
252 */
253 int execute_script(const char *name)
254 {
255   pid_t pid;
256 cp
257   if((pid = fork()) < 0)
258     {
259       syslog(LOG_ERR, _("System call `%s' failed: %m"),
260              "fork");
261       return -1;
262     }
263
264   if(pid)
265     {
266       list_append(child_pids, &pid);
267       return 0;
268     }
269 cp
270   /* Child here */
271   _execute_script(name);
272 }
273
274 /*
275   Check a child (the pointer data is actually an integer, the PID of
276   that child.  A non-zero return value means that the child has exited
277   and can be removed from our list.
278 */
279 int check_child(void *data)
280 {
281   pid_t pid;
282   int status;
283 cp
284   pid = (pid_t) data;
285   pid = waitpid(pid, &status, WNOHANG);
286   if(WIFEXITED(status))
287     {
288       if(WIFSIGNALED(status)) /* Child was killed by a signal */
289         {
290           syslog(LOG_ERR, _("Child with PID %d was killed by signal %d (%s)"),
291                  pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
292           return -1;
293         }
294       if(WEXITSTATUS(status) != 0)
295         {
296           syslog(LOG_INFO, _("Child with PID %d exited with code %d"),
297                  WEXITSTATUS(status));
298         }
299       return -1;
300     }
301 cp
302   /* Child is still running */
303   return 0;
304 }
305
306 /*
307   Check the status of all our children.
308 */
309 void check_children(void)
310 {
311   list_forall_nodes(child_pids, check_child);
312 }
313
314
315 /*
316   Signal handlers.
317 */
318
319 RETSIGTYPE
320 sigterm_handler(int a)
321 {
322   if(debug_lvl > DEBUG_NOTHING)
323     syslog(LOG_NOTICE, _("Got TERM signal"));
324
325   cleanup_and_exit(0);
326 }
327
328 RETSIGTYPE
329 sigquit_handler(int a)
330 {
331   if(debug_lvl > DEBUG_NOTHING)
332     syslog(LOG_NOTICE, _("Got QUIT signal"));
333   cleanup_and_exit(0);
334 }
335
336 RETSIGTYPE
337 sigsegv_square(int a)
338 {
339   syslog(LOG_ERR, _("Got another SEGV signal: not restarting"));
340   exit(0);
341 }
342
343 RETSIGTYPE
344 sigsegv_handler(int a)
345 {
346   syslog(LOG_ERR, _("Got SEGV signal"));
347   cp_trace();
348
349   if(do_detach)
350     {
351       syslog(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
352       signal(SIGSEGV, sigsegv_square);
353       close_network_connections();
354       sleep(5);
355       remove_pid(pidfilename);
356       execvp(g_argv[0], g_argv);
357     }
358   else
359     {
360       syslog(LOG_NOTICE, _("Not restarting."));
361       exit(0);
362     }
363 }
364
365 RETSIGTYPE
366 sighup_handler(int a)
367 {
368   if(debug_lvl > DEBUG_NOTHING)
369     syslog(LOG_NOTICE, _("Got HUP signal"));
370   sighup = 1;
371 }
372
373 RETSIGTYPE
374 sigint_handler(int a)
375 {
376   if(debug_lvl > DEBUG_NOTHING)
377     syslog(LOG_NOTICE, _("Got INT signal, exiting"));
378   cleanup_and_exit(0);
379 }
380
381 RETSIGTYPE
382 sigusr1_handler(int a)
383 {
384   dump_connection_list();
385 }
386
387 RETSIGTYPE
388 sigusr2_handler(int a)
389 {
390   dump_subnet_list();
391 }
392
393 RETSIGTYPE
394 sighuh(int a)
395 {
396   syslog(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
397   cp_trace();
398 }
399
400 void
401 setup_signals(void)
402 {
403   int i;
404
405   for(i=0;i<32;i++)
406     signal(i,sighuh);
407
408   if(signal(SIGTERM, SIG_IGN) != SIG_ERR)
409     signal(SIGTERM, sigterm_handler);
410   if(signal(SIGQUIT, SIG_IGN) != SIG_ERR)
411     signal(SIGQUIT, sigquit_handler);
412   if(signal(SIGSEGV, SIG_IGN) != SIG_ERR)
413     signal(SIGSEGV, sigsegv_handler);
414   if(signal(SIGHUP, SIG_IGN) != SIG_ERR)
415     signal(SIGHUP, sighup_handler);
416   signal(SIGPIPE, SIG_IGN);
417   if(signal(SIGINT, SIG_IGN) != SIG_ERR)
418     signal(SIGINT, sigint_handler);
419   signal(SIGUSR1, sigusr1_handler);
420   signal(SIGUSR2, sigusr2_handler);
421   signal(SIGCHLD, SIG_IGN);
422 }
423
424 RETSIGTYPE parent_exit(int a)
425 {
426   exit(0);
427 }