Move more functions from tincd.c into process.c.
[oweals/tinc.git] / 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.2 2000/11/16 22:12:23 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;
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(do_detach)
141     {
142       ppid = getpid();
143
144       if((pid = fork()) < 0)
145         {
146           perror("fork");
147           return -1;
148         }
149       if(pid) /* parent process */
150         {
151           signal(SIGTERM, parent_exit);
152           sleep(600); /* wait 10 minutes */
153           exit(1);
154         }
155     }
156   
157   if(write_pidfile())
158     return -1;
159
160   if(do_detach)
161     {
162       if((fd = open("/dev/tty", O_RDWR)) >= 0)
163         {
164           if(ioctl(fd, TIOCNOTTY, NULL))
165             {
166               perror("ioctl");
167               return -1;
168             }
169           close(fd);
170         }
171
172       if(setsid() < 0)
173         return -1;
174
175       kill(ppid, SIGTERM);
176     }
177   
178   chdir("/"); /* avoid keeping a mointpoint busy */
179
180   openlog(identname, LOG_CONS | LOG_PID, LOG_DAEMON);
181
182   if(debug_lvl > DEBUG_NOTHING)
183     syslog(LOG_NOTICE, _("tincd %s (%s %s) starting, debug level %d"),
184            VERSION, __DATE__, __TIME__, debug_lvl);
185   else
186     syslog(LOG_NOTICE, _("tincd %s starting"), VERSION);
187
188   xalloc_fail_func = memory_full;
189
190   return 0;
191 }
192
193 /*
194   Execute the program name, with sane environment.  All output will be
195   redirected to syslog.
196 */
197 void _execute_script(const char *name)  __attribute__ ((noreturn));
198 void _execute_script(const char *name)
199 {
200   int error = 0;
201   char *scriptname;
202   char *s;
203
204   if(netname)
205     {
206       asprintf(&s, "NETNAME=%s", netname);
207       putenv(s);        /* Don't free s! see man 3 putenv */
208     }
209 #ifdef HAVE_UNSETENV
210   else
211     {
212       unsetenv("NETNAME");
213     }
214 #endif
215
216   if(chdir(confbase) < 0)
217     /* This cannot fail since we already read config files from this
218        directory. - Guus */
219     /* Yes this can fail, somebody could have removed this directory
220        when we didn't pay attention. - Ivo */
221     {
222       if(chdir("/") < 0)
223         /* Now if THIS fails, something wicked is going on. - Ivo */
224         syslog(LOG_ERR, _("Couldn't chdir to `/': %m"));
225
226       /* Continue anyway. */
227     }
228   
229   asprintf(&scriptname, "%s/%s", confbase, name);
230
231   /* Close all file descriptors */
232   closelog();
233   fcloseall();
234
235   /* Open standard input */
236   if(open("/dev/null", O_RDONLY) < 0)
237     {
238       syslog(LOG_ERR, _("Opening `/dev/null' failed: %m"));
239       error = 1;
240     }
241
242   if(!error)
243     {
244       /* Standard output directly goes to syslog */
245       openlog(name, LOG_CONS | LOG_PID, LOG_DAEMON);
246       /* Standard error as well */
247       if(dup2(1, 2) < 0)
248         {
249           syslog(LOG_ERR, _("System call `%s' failed: %m"),
250                  "dup2");
251           error = 1;
252         }
253     }
254   
255   if(error && debug_lvl > 1)
256     syslog(LOG_INFO, _("This means that any output the script generates will not be shown in syslog."));
257   
258   execl(scriptname, NULL);
259   /* No return on success */
260   
261   if(errno != ENOENT)  /* Ignore if the file does not exist */
262     syslog(LOG_WARNING, _("Error executing `%s': %m"), scriptname);
263
264   /* No need to free things */
265   exit(0);
266 }
267
268 /*
269   Fork and execute the program pointed to by name.
270 */
271 int execute_script(const char *name)
272 {
273   pid_t pid;
274
275   if((pid = fork()) < 0)
276     {
277       syslog(LOG_ERR, _("System call `%s' failed: %m"),
278              "fork");
279       return -1;
280     }
281
282   if(pid)
283     {
284       list_append(child_pids, (void*)(int)pid);
285       return 0;
286     }
287
288   /* Child here */
289   _execute_script(name);
290 }
291
292 /*
293   Check a child (the pointer data is actually an integer, the PID of
294   that child.  A non-zero return value means that the child has exited
295   and can be removed from our list.
296 */
297 int check_child(void *data)
298 {
299   pid_t pid;
300   int status;
301
302   pid = (pid_t) data;
303   pid = waitpid(pid, &status, WNOHANG);
304   if(WIFEXITED(status))
305     {
306       if(WIFSIGNALED(status)) /* Child was killed by a signal */
307         {
308           syslog(LOG_ERR, _("Child with PID %d was killed by signal %d (%s)"),
309                  pid, WTERMSIG(status), strsignal(WTERMSIG(status)));
310           return -1;
311         }
312       if(WEXITSTATUS(status) != 0)
313         {
314           syslog(LOG_INFO, _("Child with PID %d exited with code %d"),
315                  WEXITSTATUS(status));
316         }
317       return -1;
318     }
319
320   /* Child is still running */
321   return 0;
322 }
323
324 /*
325   Check the status of all our children.
326 */
327 void check_children(void)
328 {
329   list_forall_nodes(child_pids, check_child);
330 }
331
332
333 /*
334   Signal handlers.
335 */
336
337 RETSIGTYPE
338 sigterm_handler(int a)
339 {
340   if(debug_lvl > DEBUG_NOTHING)
341     syslog(LOG_NOTICE, _("Got TERM signal"));
342
343   cleanup_and_exit(0);
344 }
345
346 RETSIGTYPE
347 sigquit_handler(int a)
348 {
349   if(debug_lvl > DEBUG_NOTHING)
350     syslog(LOG_NOTICE, _("Got QUIT signal"));
351   cleanup_and_exit(0);
352 }
353
354 RETSIGTYPE
355 sigsegv_square(int a)
356 {
357   syslog(LOG_ERR, _("Got another SEGV signal: not restarting"));
358   exit(0);
359 }
360
361 RETSIGTYPE
362 sigsegv_handler(int a)
363 {
364   syslog(LOG_ERR, _("Got SEGV signal"));
365   cp_trace();
366
367   if(do_detach)
368     {
369       syslog(LOG_NOTICE, _("Trying to re-execute in 5 seconds..."));
370       signal(SIGSEGV, sigsegv_square);
371       close_network_connections();
372       sleep(5);
373       remove_pid(pidfilename);
374       execvp(g_argv[0], g_argv);
375     }
376   else
377     {
378       syslog(LOG_NOTICE, _("Not restarting."));
379       exit(0);
380     }
381 }
382
383 RETSIGTYPE
384 sighup_handler(int a)
385 {
386   if(debug_lvl > DEBUG_NOTHING)
387     syslog(LOG_NOTICE, _("Got HUP signal"));
388   sighup = 1;
389 }
390
391 RETSIGTYPE
392 sigint_handler(int a)
393 {
394   if(debug_lvl > DEBUG_NOTHING)
395     syslog(LOG_NOTICE, _("Got INT signal, exiting"));
396   cleanup_and_exit(0);
397 }
398
399 RETSIGTYPE
400 sigusr1_handler(int a)
401 {
402   dump_conn_list();
403 }
404
405 RETSIGTYPE
406 sigusr2_handler(int a)
407 {
408   dump_subnet_list();
409 }
410
411 RETSIGTYPE
412 sighuh(int a)
413 {
414   syslog(LOG_WARNING, _("Got unexpected signal %d (%s)"), a, strsignal(a));
415   cp_trace();
416 }
417
418 void
419 setup_signals(void)
420 {
421   int i;
422
423   for(i=0;i<32;i++)
424     signal(i,sighuh);
425
426   if(signal(SIGTERM, SIG_IGN) != SIG_ERR)
427     signal(SIGTERM, sigterm_handler);
428   if(signal(SIGQUIT, SIG_IGN) != SIG_ERR)
429     signal(SIGQUIT, sigquit_handler);
430   if(signal(SIGSEGV, SIG_IGN) != SIG_ERR)
431     signal(SIGSEGV, sigsegv_handler);
432   if(signal(SIGHUP, SIG_IGN) != SIG_ERR)
433     signal(SIGHUP, sighup_handler);
434   signal(SIGPIPE, SIG_IGN);
435   if(signal(SIGINT, SIG_IGN) != SIG_ERR)
436     signal(SIGINT, sigint_handler);
437   signal(SIGUSR1, sigusr1_handler);
438   signal(SIGUSR2, sigusr2_handler);
439   signal(SIGCHLD, SIG_IGN);
440 }
441
442 RETSIGTYPE parent_exit(int a)
443 {
444   exit(0);
445 }