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