9d5d8df69db474fb6d25a0eb9ffe8c9d50185f65
[nethome.git] / src / orphanripper.c
1 /*
2  * Copyright 2006-2007 Free Software Foundation, Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  * Reap any leftover children possibly holding file descriptors.
19  * Children are identified by the stale file descriptor or PGID / SID.
20  * Both can be missed but only the stale file descriptors are important for us.
21  * PGID / SID may be set by the children on their own.
22  * If we fine a candidate we kill it will all its process tree (grandchildren).
23  * The child process is run with `2>&1' redirection (due to forkpty(3)).
24  * 2007-07-10  Jan Kratochvil  <jan.kratochvil@redhat.com>
25  */
26
27 /* For getpgid(2).  */
28 #define _GNU_SOURCE 1
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 #include <dirent.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <ctype.h>
38 #include <string.h>
39 #include <limits.h>
40 #include <fcntl.h>
41 #include <assert.h>
42 #include <pty.h>
43 #include <poll.h>
44
45 #define LENGTH(x) (sizeof (x) / sizeof (*(x)))
46
47 static const char *progname;
48
49 static volatile int signal_child_hit = 0;
50
51 /* We use it to race-safely emulate ppoll(2) by poll(2).  */
52 static int pipefd[2];
53
54 static void signal_child (int signo)
55 {
56   int i;
57
58   signal_child_hit = 1;
59
60   assert (pipefd[1] != -1);
61   i = close (pipefd[1]);
62   assert (i == 0);
63   pipefd[1] = -1;
64 }
65
66 static volatile int signal_alarm_hit = 0;
67
68 static void signal_alarm (int signo)
69 {
70   signal_alarm_hit = 1;
71 }
72
73 static char childptyname[LINE_MAX];
74 static pid_t child;
75
76 static void print_child_error (const char *reason, char **argv)
77 {
78   char **sp;
79
80   fprintf (stderr, "%s: %d %s:", progname, (int) child, reason);
81   for (sp = argv; *sp != NULL; sp++)
82     {
83       fputc (' ', stderr);
84       fputs (*sp, stderr);
85     }
86   fputc ('\n', stderr);
87 }
88
89 static int spawn (char **argv, int timeout)
90 {
91   pid_t child_got;
92   int status, amaster, i, rc;
93   struct sigaction act;
94   struct termios termios;
95   unsigned alarm_orig;
96
97   i = pipe (pipefd);
98   assert (i == 0);
99
100   /* We do not use signal(2) to be sure we have SA_RESTART set.  */
101   memset (&act, 0, sizeof (act));
102   act.sa_handler = signal_child;
103   i = sigemptyset (&act.sa_mask);
104   assert (i == 0);
105   act.sa_flags = SA_RESTART;
106   i = sigaction (SIGCHLD, &act, NULL);
107   assert (i == 0);
108
109   /* With TERMP passed as NULL we get "\n" -> "\r\n".  */
110   termios.c_iflag = IGNBRK | IGNPAR;
111   termios.c_oflag = 0;
112   termios.c_cflag = CS8 | CREAD | CLOCAL | HUPCL | B9600;
113   termios.c_lflag = IEXTEN | NOFLSH;
114   memset (termios.c_cc, _POSIX_VDISABLE, sizeof (termios.c_cc));
115   termios.c_cc[VTIME] = 0;
116   termios.c_cc[VMIN ] = 1;
117   cfmakeraw (&termios);
118 #ifdef FLUSHO
119   /* Workaround a readline deadlock bug in _get_tty_settings().  */
120   termios.c_lflag &= ~FLUSHO;
121 #endif
122   child = forkpty (&amaster, childptyname, &termios, NULL);
123   switch (child)
124     {
125       case -1:
126         perror ("forkpty(3)");
127         exit (EXIT_FAILURE);
128       case 0:
129         i = close (pipefd[0]);
130         assert (i == 0);
131         i = close (pipefd[1]);
132         assert (i == 0);
133
134         /* Do not replace STDIN as inferiors query its termios.  */
135 #if 0
136         i = close (STDIN_FILENO);
137         assert (i == 0);
138         i = open ("/dev/null", O_RDONLY);
139         assert (i == STDIN_FILENO);
140 #endif
141
142         /* Do not setpgrp(2) in the parent process as the process-group
143            is shared for the whole sh(1) pipeline we could be a part
144            of.  The process-group is set according to PID of the first
145            command in the pipeline.
146            We would rip even vi(1) in the case of:
147                 ./orphanripper sh -c 'sleep 1&' | vi -
148            */
149         /* Do not setpgrp(2) as our pty would not be ours and we would
150            get `SIGSTOP' later, particularly after spawning gdb(1).
151            setsid(3) was already executed by forkpty(3) and it would fail if
152            executed again.  */
153         if (getpid() != getpgrp ())
154           {
155             perror ("getpgrp(2)");
156             exit (EXIT_FAILURE);
157           }
158         execvp (argv[0], argv);
159         perror ("execvp(2)");
160         exit (EXIT_FAILURE);
161       default:
162         break;
163     }
164   i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
165   if (i != 0)
166     {
167       perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
168       exit (EXIT_FAILURE);
169     }
170
171   /* We do not use signal(2) to be sure we have SA_RESTART set.  */
172   act.sa_handler = signal_alarm;
173   act.sa_flags &= ~SA_RESTART;
174   i = sigaction (SIGALRM, &act, NULL);
175   assert (i == 0);
176
177   alarm_orig = alarm (timeout);
178   assert (alarm_orig == 0);
179
180   while (!signal_alarm_hit)
181     {
182       struct pollfd pollfd[2];
183       char buf[LINE_MAX];
184       ssize_t buf_got;
185
186       pollfd[0].fd = amaster;
187       pollfd[0].events = POLLIN;
188       pollfd[1].fd = pipefd[0];
189       pollfd[1].events = POLLIN;
190       i = poll (pollfd, LENGTH (pollfd), -1);
191       if (i == -1 && errno == EINTR)
192         {
193           /* Weird but SA_RESTART sometimes does not work.  */
194           continue;
195         }
196       assert (i >= 1);
197       /* Data available?  Process it first.  */
198       if (pollfd[0].revents & POLLIN)
199         {
200           buf_got = read (amaster, buf, sizeof buf);
201           if (buf_got <= 0)
202             {
203               perror ("read (amaster)");
204               exit (EXIT_FAILURE);
205             }
206           if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
207             {
208               perror ("write(2)");
209               exit (EXIT_FAILURE);
210             }
211         }
212       if (pollfd[0].revents & POLLHUP)
213         break;
214       if ((pollfd[0].revents &= ~POLLIN) != 0)
215         {
216           fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
217                    (unsigned) pollfd[0].revents);
218           exit (EXIT_FAILURE);
219         }
220       /* Child exited?  */
221       if (pollfd[1].revents & POLLHUP)
222         break;
223       assert (pollfd[1].revents == 0);
224     }
225
226   if (signal_alarm_hit)
227     {
228       i = kill (child, SIGKILL);
229       assert (i == 0);
230     }
231   else
232     alarm (0);
233
234   /* WNOHANG still could fail.  */
235   child_got = waitpid (child, &status, 0);
236   if (child != child_got)
237     {
238       fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
239       exit (EXIT_FAILURE);
240     }
241   if (signal_alarm_hit)
242     {
243       char *buf;
244
245       if (asprintf (&buf, "Timed out after %d seconds", timeout) != -1)
246         {
247           print_child_error (buf, argv);
248           free (buf);
249         }
250       rc = 128 + SIGALRM;
251     }
252   else if (WIFEXITED (status))
253     rc = WEXITSTATUS (status);
254   else if (WIFSIGNALED (status))
255     {
256       print_child_error (strsignal (WTERMSIG (status)), argv);
257       rc = 128 + WTERMSIG (status);
258     }
259   else if (WIFSTOPPED (status))
260     {
261       fprintf (stderr, "waitpid (%d): WIFSTOPPED - WSTOPSIG is %d\n",
262                (int) child, WSTOPSIG (status));
263       exit (EXIT_FAILURE);
264     }
265   else
266     {
267       fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
268       exit (EXIT_FAILURE);
269     }
270
271   assert (signal_child_hit != 0);
272
273   assert (pipefd[1] == -1);
274   i = close (pipefd[0]);
275   assert (i == 0);
276
277   /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
278      entries which are not expected (and expecting ` (deleted)' would be
279      a race.  */
280 #if 0
281   i = close (amaster);
282   if (i != 0)
283     {
284       perror ("close (forkpty ()'s amaster)");
285       exit (EXIT_FAILURE);
286     }
287 #endif
288
289   return rc;
290 }
291
292 /* Detected commandline may look weird due to a race:
293    Original command:
294         ./orphanripper sh -c 'sleep 1&' &
295    Correct output:
296         [1] 29610
297         ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
298    Raced output (sh(1) child still did not update its argv[]):
299         [1] 29613
300         ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
301    We could delay a bit before ripping the children.  */
302 static const char *read_cmdline (pid_t pid)
303 {
304   char cmdline_fname[32];
305   static char cmdline[LINE_MAX];
306   int fd;
307   ssize_t got;
308   char *s;
309
310   if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
311       (int) pid) < 0)
312     return NULL;
313   fd = open (cmdline_fname, O_RDONLY);
314   if (fd == -1)
315     {
316       /* It may have already exited - ENOENT.  */
317 #if 0
318       fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
319 #endif
320       return NULL;
321     }
322   got = read (fd, cmdline, sizeof (cmdline) - 1);
323   if (got == -1)
324     fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
325        cmdline_fname);
326   if (close (fd) != 0)
327     fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
328        cmdline_fname);
329   if (got < 0)
330     return NULL;
331   /* Convert '\0' argument delimiters to spaces.  */
332   for (s = cmdline; s < cmdline + got; s++)
333     if (!*s)
334       *s = ' ';
335   /* Trim the trailing spaces (typically single '\0'->' ').  */
336   while (s > cmdline && isspace (s[-1]))
337     s--;
338   *s = 0;
339   return cmdline;
340 }
341
342 static int dir_scan (const char *dirname,
343                   int (*callback) (struct dirent *dirent, const char *pathname))
344 {
345   DIR *dir;
346   struct dirent *dirent;
347   int rc = 0;
348
349   dir = opendir (dirname);
350   if (dir == NULL)
351     {
352       if (errno == EACCES || errno == ENOENT)
353         return rc;
354       fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
355       exit (EXIT_FAILURE);
356     }
357   while ((errno = 0, dirent = readdir (dir)))
358     {
359       char pathname[LINE_MAX];
360       int pathname_len;
361
362       pathname_len = snprintf (pathname, sizeof pathname, "%s/%s",
363                                  dirname, dirent->d_name);
364       if (pathname_len <= 0 || pathname_len >= (int) sizeof pathname)
365         {
366           fprintf (stderr, "entry file name too long: `%s' / `%s'\n",
367                    dirname, dirent->d_name);
368           continue;
369         }
370       /* RHEL-4.5 on s390x never fills in D_TYPE.  */
371       if (dirent->d_type == DT_UNKNOWN)
372         {
373           struct stat statbuf;
374           int i;
375
376           /* We are not interested in the /proc/PID/fd/ links targets.  */
377           i = lstat (pathname, &statbuf);
378           if (i == -1)
379             {
380               if (errno == EACCES || errno == ENOENT)
381                 continue;
382               fprintf (stderr, "%s: stat (\"%s\"): %m\n", progname, pathname);
383               exit (EXIT_FAILURE);
384             }
385           if (S_ISDIR (statbuf.st_mode))
386             dirent->d_type = DT_DIR;
387           if (S_ISLNK (statbuf.st_mode))
388             dirent->d_type = DT_LNK;
389           /* No other D_TYPE types used in this code.  */
390         }
391       rc = (*callback) (dirent, pathname);
392       if (rc != 0)
393         {
394           errno = 0;
395           break;
396         }
397     }
398   if (errno != 0)
399     {
400       fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
401       exit (EXIT_FAILURE);
402     }
403   if (closedir (dir) != 0)
404     {
405       fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
406       exit (EXIT_FAILURE);
407     }
408   return rc;
409 }
410
411 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
412 {
413   char dirname[64];
414
415   if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
416     {
417       perror ("snprintf(3)");
418       exit (EXIT_FAILURE);
419     }
420
421   int callback (struct dirent *dirent, const char *pathname)
422   {
423     char buf[LINE_MAX];
424     ssize_t buf_len;
425
426     if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
427         || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
428             && strcmp (dirent->d_name, "..") != 0)
429         || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
430             != strlen (dirent->d_name)))
431       {
432         fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
433                          " on readdir (\"%s\"): %m\n",
434                  dirent->d_name, (unsigned) dirent->d_type, dirname);
435         return 0;
436       }
437     if (dirent->d_type == DT_DIR)
438       return 0;
439     buf_len = readlink (pathname, buf, sizeof buf - 1);
440     if (buf_len <= 0 || buf_len >= (ssize_t) sizeof buf - 1)
441       {
442         if (errno != ENOENT && errno != EACCES)
443           fprintf (stderr, "Error reading link \"%s\": %m\n", pathname);
444         return 0;
445       }
446     buf[buf_len] = 0;
447     return (*func) (pid, buf);
448   }
449
450   return dir_scan (dirname, callback);
451 }
452
453 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
454 {
455   int callback (struct dirent *dirent, const char *pathname)
456   {
457     if (dirent->d_type != DT_DIR
458         || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
459       return 0;
460     (*func) (atoi (dirent->d_name), data);
461     return 0;
462   }
463
464   dir_scan ("/proc", callback);
465 }
466
467 static int rip_check_ptyname (pid_t pid, const char *link)
468 {
469   assert (pid != getpid ());
470
471   return strcmp (link, childptyname) == 0;
472 }
473
474 struct pid
475   {
476     struct pid *next;
477     pid_t pid;
478   };
479 static struct pid *pid_list;
480
481 static int pid_found (pid_t pid)
482 {
483   struct pid *entry;
484
485   for (entry = pid_list; entry != NULL; entry = entry->next)
486     if (entry->pid == pid)
487       return 1;
488   return 0;
489 }
490
491 /* Single pass is not enough, a (multithreaded) process was seen to survive.
492    Repeated killing of the same process is not enough, zombies can be killed.
493    */
494 static int cleanup_acted;
495
496 static void pid_record (pid_t pid)
497 {
498   struct pid *entry;
499
500   if (pid_found (pid))
501     return;
502   cleanup_acted = 1;
503
504   entry = malloc (sizeof (*entry));
505   if (entry == NULL)
506     {
507       fprintf (stderr, "%s: malloc: %m\n", progname);
508       exit (EXIT_FAILURE);
509     }
510   entry->pid = pid;
511   entry->next = pid_list;
512   pid_list = entry;
513 }
514
515 static void pid_forall (void (*func) (pid_t pid))
516 {
517   struct pid *entry;
518
519   for (entry = pid_list; entry != NULL; entry = entry->next)
520     (*func) (entry->pid);
521 }
522
523 /* Returns 0 on failure.  */
524 static pid_t pid_get_parent (pid_t pid)
525 {
526   char fname[64];
527   FILE *f;
528   char line[LINE_MAX];
529   pid_t retval = 0;
530
531   if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
532     {
533       perror ("snprintf(3)");
534       exit (EXIT_FAILURE);
535     }
536   f = fopen (fname, "r");
537   if (f == NULL)
538     {
539       return 0;
540     }
541   while (errno = 0, fgets (line, sizeof line, f) == line)
542     {
543       if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
544         continue;
545       retval = atoi (line + sizeof "PPid:\t" - 1);
546       errno = 0;
547       break;
548     }
549   if (errno != 0)
550     {
551       fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
552       exit (EXIT_FAILURE);
553     }
554   if (fclose (f) != 0)
555     {
556       fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
557       exit (EXIT_FAILURE);
558     }
559   return retval;
560 }
561
562 static void killtree (pid_t pid);
563
564 static void killtree_pid_fs_scan (pid_t pid, void *data)
565 {
566   pid_t parent_pid = *(pid_t *) data;
567
568   /* Do not optimize it as we could miss some newly spawned processes.
569      Always traverse all the leaves.  */
570 #if 0
571   /* Optimization.  */
572   if (pid_found (pid))
573     return;
574 #endif
575
576   if (pid_get_parent (pid) != parent_pid)
577     return;
578
579   killtree (pid);
580 }
581
582 static void killtree (pid_t pid)
583 {
584   pid_record (pid);
585   pid_fs_scan (killtree_pid_fs_scan, &pid);
586 }
587
588 static void rip_pid_fs_scan (pid_t pid, void *data)
589 {
590   pid_t pgid;
591
592   /* Shouldn't happen.  */
593   if (pid == getpid ())
594     return;
595
596   /* Check both PGID and the stale file descriptors.  */
597   pgid = getpgid (pid);
598   if (pgid == child
599       || fd_fs_scan (pid, rip_check_ptyname) != 0)
600     killtree (pid);
601 }
602
603 static void killproc (pid_t pid)
604 {
605   const char *cmdline;
606
607   cmdline = read_cmdline (pid);
608   /* Avoid printing the message for already gone processes.  */
609   if (kill (pid, 0) != 0 && errno == ESRCH)
610     return;
611   if (cmdline == NULL)
612     cmdline = "<error>";
613   fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
614   if (kill (pid, SIGKILL) == 0)
615     cleanup_acted = 1;
616   else if (errno != ESRCH)
617     fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
618   /* RHEL-3 kernels cannot SIGKILL a `T (stopped)' process.  */
619   kill (pid, SIGCONT);
620   /* Do not waitpid(2) as it cannot be our direct descendant and it gets
621      cleaned up by init(8).  */
622 #if 0
623   pid_t pid_got;
624   pid_got = waitpid (pid, NULL, 0);
625   if (pid != pid_got)
626     {
627       fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
628          (int) pid, (int) pid_got);
629       return;
630     }
631 #endif
632 }
633
634 static void rip (void)
635 {
636   cleanup_acted = 0;
637   do
638     {
639       if (cleanup_acted)
640         usleep (1000000 / 10);
641       cleanup_acted = 0;
642       pid_fs_scan (rip_pid_fs_scan, NULL);
643       pid_forall (killproc);
644     }
645   while (cleanup_acted);
646 }
647
648 int main (int argc, char **argv)
649 {
650   int timeout = 0;
651   int rc;
652
653   progname = *argv++;
654   argc--;
655
656   if (argc < 1 || strcmp (*argv, "-h") == 0
657       || strcmp (*argv, "--help") == 0)
658     {
659       puts ("Syntax: orphanripper [-t <seconds>] <execvp(3) commandline>");
660       exit (EXIT_FAILURE);
661     }
662   if ((*argv)[0] == '-' && (*argv)[1] == 't')
663     {
664       char *timeout_s = NULL;
665
666       if ((*argv)[2] == 0)
667         timeout_s = *++argv;
668       else if (isdigit ((*argv)[2]))
669         timeout_s = (*argv) + 2;
670       if (timeout_s != NULL)
671         {
672           long l;
673           char *endptr;
674
675           argv++;
676           l = strtol (timeout_s, &endptr, 0);
677           timeout = l;
678           if ((endptr != NULL && *endptr != 0) || timeout < 0 || timeout != l)
679             {
680               fprintf (stderr, "%s: Invalid timeout value: %s\n", progname,
681                        timeout_s);
682               exit (EXIT_FAILURE);
683             }
684         }
685     }
686
687   rc = spawn (argv, timeout);
688   rip ();
689   return rc;
690 }