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