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