2d64357
/*
2d64357
 * Copyright 2006-2007 Free Software Foundation, Inc.
2d64357
 *
2d64357
 * This program is free software; you can redistribute it and/or modify
2d64357
 * it under the terms of the GNU General Public License as published by
2d64357
 * the Free Software Foundation; either version 2 of the License, or
2d64357
 * (at your option) any later version.
2d64357
 *
2d64357
 * This program is distributed in the hope that it will be useful,
2d64357
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
2d64357
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
2d64357
 * GNU General Public License for more details.
2d64357
 *
2d64357
 * You should have received a copy of the GNU General Public License
2d64357
 * along with this program; if not, write to the Free Software
2d64357
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
2d64357
 *
2d64357
 * Reap any leftover children possibly holding file descriptors.
2d64357
 * Children are identified by the stale file descriptor or PGID / SID.
2d64357
 * Both can be missed but only the stale file descriptors are important for us.
2d64357
 * PGID / SID may be set by the children on their own.
2d64357
 * If we fine a candidate we kill it will all its process tree (grandchildren).
2d64357
 * The child process is run with `2>&1' redirection (due to forkpty(3)).
2d64357
 * 2007-07-10  Jan Kratochvil  <jan.kratochvil@redhat.com>
2d64357
 */
2d64357
2d64357
/* For getpgid(2).  */
2d64357
#define _GNU_SOURCE 1
2d64357
2d64357
#include <stdio.h>
2d64357
#include <stdlib.h>
2d64357
#include <sys/types.h>
2d64357
#include <sys/wait.h>
2d64357
#include <dirent.h>
2d64357
#include <unistd.h>
2d64357
#include <errno.h>
2d64357
#include <ctype.h>
2d64357
#include <string.h>
2d64357
#include <limits.h>
2d64357
#include <fcntl.h>
2d64357
#include <assert.h>
2d64357
#include <pty.h>
2d64357
#include <poll.h>
8c4c91e
#include <sys/stat.h>
2d64357
2d64357
#define LENGTH(x) (sizeof (x) / sizeof (*(x)))
2d64357
2d64357
static const char *progname;
2d64357
Jan Kratochvil ab816ba
static volatile pid_t child;
2d64357
620a59a
static void signal_chld (int signo)
2d64357
{
620a59a
}
2d64357
620a59a
static volatile int signal_alrm_hit = 0;
2d64357
620a59a
static void signal_alrm (int signo)
620a59a
{
620a59a
  signal_alrm_hit = 1;
2d64357
}
2d64357
2d64357
static char childptyname[LINE_MAX];
2d64357
620a59a
static void print_child_error (const char *reason, char **argv)
620a59a
{
620a59a
  char **sp;
620a59a
620a59a
  fprintf (stderr, "%s: %d %s:", progname, (int) child, reason);
620a59a
  for (sp = argv; *sp != NULL; sp++)
620a59a
    {
620a59a
      fputc (' ', stderr);
620a59a
      fputs (*sp, stderr);
620a59a
    }
620a59a
  fputc ('\n', stderr);
620a59a
}
620a59a
620a59a
static int read_out (int amaster)
620a59a
{
620a59a
  char buf[LINE_MAX];
620a59a
  ssize_t buf_got;
620a59a
620a59a
  buf_got = read (amaster, buf, sizeof buf);
620a59a
  if (buf_got == 0)
620a59a
    return 0;
620a59a
  /* Weird but at least after POLLHUP we get EIO instead of just EOF.  */
620a59a
  if (buf_got == -1 && errno == EIO)
620a59a
    return 0;
8c4c91e
  if (buf_got == -1 && errno == EAGAIN)
8c4c91e
    return 0;
620a59a
  if (buf_got < 0)
620a59a
    {
620a59a
      perror ("read (amaster)");
620a59a
      exit (EXIT_FAILURE);
620a59a
    }
620a59a
  if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
620a59a
    {
620a59a
      perror ("write(2)");
620a59a
      exit (EXIT_FAILURE);
620a59a
    }
620a59a
  return 1;
620a59a
}
620a59a
Jan Kratochvil 43e595b
/* kill (child, 0) == 0 sometimes even when CHILD's state is already "Z".  */
Jan Kratochvil 43e595b
Jan Kratochvil 43e595b
static int child_exited (void)
Jan Kratochvil 43e595b
{
Jan Kratochvil 43e595b
  char buf[200];
Jan Kratochvil 43e595b
  int fd, i, retval;
Jan Kratochvil 43e595b
  ssize_t got;
Jan Kratochvil 01f3266
  char state[3];
Jan Kratochvil 43e595b
Jan Kratochvil 43e595b
  snprintf (buf, sizeof (buf), "/proc/%ld/stat", (long) child);
Jan Kratochvil 43e595b
  fd = open (buf, O_RDONLY);
Jan Kratochvil 43e595b
  if (fd == -1)
Jan Kratochvil 43e595b
    {
Jan Kratochvil 43e595b
      perror ("open (/proc/CHILD/stat)");
Jan Kratochvil 43e595b
      exit (EXIT_FAILURE);
Jan Kratochvil 43e595b
    }
Jan Kratochvil 43e595b
  got = read (fd, buf, sizeof(buf));
Jan Kratochvil 43e595b
  if (got <= 0)
Jan Kratochvil 43e595b
    {
Jan Kratochvil 43e595b
      perror ("read (/proc/CHILD/stat)");
Jan Kratochvil 43e595b
      exit (EXIT_FAILURE);
Jan Kratochvil 43e595b
    }
Jan Kratochvil 43e595b
  if (close (fd) != 0)
Jan Kratochvil 43e595b
    {
Jan Kratochvil 43e595b
      perror ("close (/proc/CHILD/stat)");
Jan Kratochvil 43e595b
      exit (EXIT_FAILURE);
Jan Kratochvil 43e595b
    }
Jan Kratochvil 01f3266
  /* RHEL-5 does not support %ms.  */
Jan Kratochvil 01f3266
  i = sscanf (buf, "%*d%*s%2s", state);
Jan Kratochvil 43e595b
  if (i != 1)
Jan Kratochvil 43e595b
    {
Jan Kratochvil 43e595b
      perror ("sscanf (/proc/CHILD/stat)");
Jan Kratochvil 43e595b
      exit (EXIT_FAILURE);
Jan Kratochvil 43e595b
    }
Jan Kratochvil 43e595b
  retval = strcmp (state, "Z") == 0;
Jan Kratochvil 43e595b
  return retval;
Jan Kratochvil 43e595b
}
Jan Kratochvil 43e595b
620a59a
static int spawn (char **argv, int timeout)
2d64357
{
2d64357
  pid_t child_got;
620a59a
  int status, amaster, i, rc;
2d64357
  struct sigaction act;
620a59a
  sigset_t set;
2d64357
  struct termios termios;
620a59a
  unsigned alarm_orig;
2d64357
620a59a
  /* We do not use signal(2) to be sure we do not have SA_RESTART.  */
2d64357
  memset (&act, 0, sizeof (act));
620a59a
  act.sa_handler = signal_chld;
2d64357
  i = sigemptyset (&act.sa_mask);
2d64357
  assert (i == 0);
620a59a
  act.sa_flags = 0;	/* !SA_RESTART */
2d64357
  i = sigaction (SIGCHLD, &act, NULL);
2d64357
  assert (i == 0);
2d64357
620a59a
  i = sigemptyset (&set);
620a59a
  assert (i == 0);
620a59a
  i = sigaddset (&set, SIGCHLD);
620a59a
  assert (i == 0);
620a59a
  i = sigprocmask (SIG_SETMASK, &set, NULL);
620a59a
  assert (i == 0);
620a59a
2d64357
  /* With TERMP passed as NULL we get "\n" -> "\r\n".  */
2d64357
  termios.c_iflag = IGNBRK | IGNPAR;
2d64357
  termios.c_oflag = 0;
2d64357
  termios.c_cflag = CS8 | CREAD | CLOCAL | HUPCL | B9600;
2d64357
  termios.c_lflag = IEXTEN | NOFLSH;
2d64357
  memset (termios.c_cc, _POSIX_VDISABLE, sizeof (termios.c_cc));
2d64357
  termios.c_cc[VTIME] = 0;
2d64357
  termios.c_cc[VMIN ] = 1;
2d64357
  cfmakeraw (&termios);
2d64357
#ifdef FLUSHO
2d64357
  /* Workaround a readline deadlock bug in _get_tty_settings().  */
2d64357
  termios.c_lflag &= ~FLUSHO;
2d64357
#endif
2d64357
  child = forkpty (&amaster, childptyname, &termios, NULL);
2d64357
  switch (child)
2d64357
    {
2d64357
      case -1:
2d64357
	perror ("forkpty(3)");
2d64357
	exit (EXIT_FAILURE);
2d64357
      case 0:
2d64357
	/* Do not replace STDIN as inferiors query its termios.  */
2d64357
#if 0
2d64357
	i = close (STDIN_FILENO);
2d64357
	assert (i == 0);
2d64357
	i = open ("/dev/null", O_RDONLY);
2d64357
	assert (i == STDIN_FILENO);
2d64357
#endif
2d64357
Jan Kratochvil 43e595b
	i = sigemptyset (&set);
Jan Kratochvil 43e595b
	assert (i == 0);
Jan Kratochvil 43e595b
	i = sigprocmask (SIG_SETMASK, &set, NULL);
Jan Kratochvil 43e595b
	assert (i == 0);
Jan Kratochvil 43e595b
2d64357
	/* Do not setpgrp(2) in the parent process as the process-group
2d64357
	   is shared for the whole sh(1) pipeline we could be a part
2d64357
	   of.  The process-group is set according to PID of the first
2d64357
	   command in the pipeline.
2d64357
	   We would rip even vi(1) in the case of:
2d64357
		./orphanripper sh -c 'sleep 1&' | vi -
2d64357
	   */
2d64357
	/* Do not setpgrp(2) as our pty would not be ours and we would
2d64357
	   get `SIGSTOP' later, particularly after spawning gdb(1).
2d64357
	   setsid(3) was already executed by forkpty(3) and it would fail if
2d64357
	   executed again.  */
2d64357
	if (getpid() != getpgrp ())
2d64357
	  {
2d64357
	    perror ("getpgrp(2)");
2d64357
	    exit (EXIT_FAILURE);
2d64357
	  }
620a59a
	execvp (argv[0], argv);
2d64357
	perror ("execvp(2)");
2d64357
	exit (EXIT_FAILURE);
2d64357
      default:
2d64357
	break;
2d64357
    }
2d64357
  i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
2d64357
  if (i != 0)
2d64357
    {
2d64357
      perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
620a59a
620a59a
  /* We do not use signal(2) to be sure we do not have SA_RESTART.  */
620a59a
  act.sa_handler = signal_alrm;
620a59a
  i = sigaction (SIGALRM, &act, NULL);
620a59a
  assert (i == 0);
620a59a
620a59a
  alarm_orig = alarm (timeout);
620a59a
  assert (alarm_orig == 0);
620a59a
620a59a
  i = sigemptyset (&set);
620a59a
  assert (i == 0);
620a59a
620a59a
  while (!signal_alrm_hit)
2d64357
    {
620a59a
      struct pollfd pollfd;
620a59a
620a59a
      pollfd.fd = amaster;
620a59a
      pollfd.events = POLLIN;
620a59a
      i = ppoll (&pollfd, 1, NULL, &set);
Jan Kratochvil ab816ba
      if (i == -1 && errno == EINTR)
Jan Kratochvil ab816ba
	{
Jan Kratochvil 43e595b
	  if (child_exited ())
Jan Kratochvil ab816ba
	    break;
Jan Kratochvil ab816ba
	  /* Non-CHILD child may have exited.  */
Jan Kratochvil ab816ba
	  continue;
Jan Kratochvil ab816ba
	}
620a59a
      assert (i == 1);
2d64357
      /* Data available?  Process it first.  */
620a59a
      if (pollfd.revents & POLLIN)
2d64357
	{
620a59a
	  if (!read_out (amaster))
2d64357
	    {
620a59a
	      fprintf (stderr, "%s: Unexpected EOF\n", progname);
2d64357
	      exit (EXIT_FAILURE);
2d64357
	    }
2d64357
	}
620a59a
      if (pollfd.revents & POLLHUP)
2d64357
        break;
620a59a
      if ((pollfd.revents &= ~POLLIN) != 0)
2d64357
	{
2d64357
	  fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
620a59a
		   (unsigned) pollfd.revents);
2d64357
	  exit (EXIT_FAILURE);
2d64357
	}
2d64357
      /* Child exited?  */
Jan Kratochvil 43e595b
      if (child_exited ())
2d64357
	break;
2d64357
    }
620a59a
620a59a
  if (signal_alrm_hit)
620a59a
    {
620a59a
      i = kill (child, SIGKILL);
620a59a
      assert (i == 0);
620a59a
    }
620a59a
  else
620a59a
    alarm (0);
620a59a
2d64357
  /* WNOHANG still could fail.  */
2d64357
  child_got = waitpid (child, &status, 0);
2d64357
  if (child != child_got)
2d64357
    {
2d64357
      fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
620a59a
  if (signal_alrm_hit)
620a59a
    {
620a59a
      char *buf;
620a59a
620a59a
      if (asprintf (&buf, "Timed out after %d seconds", timeout) != -1)
620a59a
	{
620a59a
	  print_child_error (buf, argv);
620a59a
	  free (buf);
620a59a
	}
620a59a
      rc = 128 + SIGALRM;
620a59a
    }
620a59a
  else if (WIFEXITED (status))
620a59a
    rc = WEXITSTATUS (status);
620a59a
  else if (WIFSIGNALED (status))
620a59a
    {
620a59a
      print_child_error (strsignal (WTERMSIG (status)), argv);
620a59a
      rc = 128 + WTERMSIG (status);
620a59a
    }
620a59a
  else if (WIFSTOPPED (status))
620a59a
    {
620a59a
      fprintf (stderr, "waitpid (%d): WIFSTOPPED - WSTOPSIG is %d\n",
620a59a
	       (int) child, WSTOPSIG (status));
620a59a
      exit (EXIT_FAILURE);
620a59a
    }
620a59a
  else
2d64357
    {
2d64357
      fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
Jan Kratochvil 43e595b
  /* Not used in fact.  */
620a59a
  i = sigprocmask (SIG_SETMASK, &set, NULL);
2d64357
  assert (i == 0);
2d64357
0911f37
  /* Do not unset O_NONBLOCK as a stale child (the whole purpose of this
0911f37
     program) having open its output pty would block us in read_out.  */
0911f37
#if 0
620a59a
  i = fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */);
620a59a
  if (i != 0)
620a59a
    {
620a59a
      perror ("fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */)");
620a59a
      exit (EXIT_FAILURE);
620a59a
    }
0911f37
#endif
620a59a
620a59a
  while (read_out (amaster));
620a59a
2d64357
  /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
2d64357
     entries which are not expected (and expecting ` (deleted)' would be
2d64357
     a race.  */
2d64357
#if 0
2d64357
  i = close (amaster);
2d64357
  if (i != 0)
2d64357
    {
2d64357
      perror ("close (forkpty ()'s amaster)");
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
#endif
2d64357
620a59a
  return rc;
2d64357
}
2d64357
2d64357
/* Detected commandline may look weird due to a race:
2d64357
   Original command:
2d64357
	./orphanripper sh -c 'sleep 1&' &
2d64357
   Correct output:
2d64357
	[1] 29610
2d64357
	./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
2d64357
   Raced output (sh(1) child still did not update its argv[]):
2d64357
	[1] 29613
2d64357
	./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
2d64357
   We could delay a bit before ripping the children.  */
2d64357
static const char *read_cmdline (pid_t pid)
2d64357
{
2d64357
  char cmdline_fname[32];
2d64357
  static char cmdline[LINE_MAX];
2d64357
  int fd;
2d64357
  ssize_t got;
2d64357
  char *s;
2d64357
2d64357
  if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
2d64357
      (int) pid) < 0)
2d64357
    return NULL;
2d64357
  fd = open (cmdline_fname, O_RDONLY);
2d64357
  if (fd == -1)
2d64357
    {
2d64357
      /* It may have already exited - ENOENT.  */
2d64357
#if 0
2d64357
      fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
2d64357
#endif
2d64357
      return NULL;
2d64357
    }
2d64357
  got = read (fd, cmdline, sizeof (cmdline) - 1);
2d64357
  if (got == -1)
2d64357
    fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
2d64357
       cmdline_fname);
2d64357
  if (close (fd) != 0)
2d64357
    fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
2d64357
       cmdline_fname);
2d64357
  if (got < 0)
2d64357
    return NULL;
2d64357
  /* Convert '\0' argument delimiters to spaces.  */
2d64357
  for (s = cmdline; s < cmdline + got; s++)
2d64357
    if (!*s)
2d64357
      *s = ' ';
2d64357
  /* Trim the trailing spaces (typically single '\0'->' ').  */
2d64357
  while (s > cmdline && isspace (s[-1]))
2d64357
    s--;
2d64357
  *s = 0;
2d64357
  return cmdline;
2d64357
}
2d64357
2d64357
static int dir_scan (const char *dirname,
2d64357
		  int (*callback) (struct dirent *dirent, const char *pathname))
2d64357
{
2d64357
  DIR *dir;
2d64357
  struct dirent *dirent;
2d64357
  int rc = 0;
2d64357
2d64357
  dir = opendir (dirname);
2d64357
  if (dir == NULL)
2d64357
    {
2d64357
      if (errno == EACCES || errno == ENOENT)
2d64357
	return rc;
2d64357
      fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
  while ((errno = 0, dirent = readdir (dir)))
2d64357
    {
2d64357
      char pathname[LINE_MAX];
2d64357
      int pathname_len;
2d64357
2d64357
      pathname_len = snprintf (pathname, sizeof pathname, "%s/%s",
2d64357
				 dirname, dirent->d_name);
620a59a
      if (pathname_len <= 0 || pathname_len >= (int) sizeof pathname)
2d64357
	{
2d64357
	  fprintf (stderr, "entry file name too long: `%s' / `%s'\n",
2d64357
		   dirname, dirent->d_name);
2d64357
	  continue;
2d64357
	}
2d64357
      /* RHEL-4.5 on s390x never fills in D_TYPE.  */
2d64357
      if (dirent->d_type == DT_UNKNOWN)
2d64357
        {
2d64357
	  struct stat statbuf;
2d64357
	  int i;
2d64357
2d64357
	  /* We are not interested in the /proc/PID/fd/ links targets.  */
2d64357
	  i = lstat (pathname, &statbuf);
2d64357
	  if (i == -1)
2d64357
	    {
2d64357
	      if (errno == EACCES || errno == ENOENT)
2d64357
	        continue;
2d64357
	      fprintf (stderr, "%s: stat (\"%s\"): %m\n", progname, pathname);
2d64357
	      exit (EXIT_FAILURE);
2d64357
	    }
2d64357
	  if (S_ISDIR (statbuf.st_mode))
2d64357
	    dirent->d_type = DT_DIR;
2d64357
	  if (S_ISLNK (statbuf.st_mode))
2d64357
	    dirent->d_type = DT_LNK;
2d64357
	  /* No other D_TYPE types used in this code.  */
2d64357
	}
2d64357
      rc = (*callback) (dirent, pathname);
2d64357
      if (rc != 0)
2d64357
	{
2d64357
	  errno = 0;
2d64357
	  break;
2d64357
	}
2d64357
    }
2d64357
  if (errno != 0)
2d64357
    {
2d64357
      fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
  if (closedir (dir) != 0)
2d64357
    {
2d64357
      fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
  return rc;
2d64357
}
2d64357
2d64357
static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
2d64357
{
2d64357
  char dirname[64];
2d64357
2d64357
  if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
2d64357
    {
2d64357
      perror ("snprintf(3)");
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
2d64357
  int callback (struct dirent *dirent, const char *pathname)
2d64357
  {
2d64357
    char buf[LINE_MAX];
2d64357
    ssize_t buf_len;
2d64357
2d64357
    if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
2d64357
	|| (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
2d64357
	    && strcmp (dirent->d_name, "..") != 0)
2d64357
	|| (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
2d64357
	    != strlen (dirent->d_name)))
2d64357
      {
2d64357
	fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
2d64357
			 " on readdir (\"%s\"): %m\n",
2d64357
		 dirent->d_name, (unsigned) dirent->d_type, dirname);
2d64357
	return 0;
2d64357
      }
2d64357
    if (dirent->d_type == DT_DIR)
2d64357
      return 0;
2d64357
    buf_len = readlink (pathname, buf, sizeof buf - 1);
620a59a
    if (buf_len <= 0 || buf_len >= (ssize_t) sizeof buf - 1)
2d64357
      {
2d64357
	if (errno != ENOENT && errno != EACCES)
2d64357
	  fprintf (stderr, "Error reading link \"%s\": %m\n", pathname);
2d64357
	return 0;
2d64357
      }
2d64357
    buf[buf_len] = 0;
2d64357
    return (*func) (pid, buf);
2d64357
  }
2d64357
2d64357
  return dir_scan (dirname, callback);
2d64357
}
2d64357
2d64357
static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
2d64357
{
2d64357
  int callback (struct dirent *dirent, const char *pathname)
2d64357
  {
2d64357
    if (dirent->d_type != DT_DIR
2d64357
	|| strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
2d64357
      return 0;
2d64357
    (*func) (atoi (dirent->d_name), data);
2d64357
    return 0;
2d64357
  }
2d64357
2d64357
  dir_scan ("/proc", callback);
2d64357
}
2d64357
2d64357
static int rip_check_ptyname (pid_t pid, const char *link)
2d64357
{
2d64357
  assert (pid != getpid ());
2d64357
2d64357
  return strcmp (link, childptyname) == 0;
2d64357
}
2d64357
2d64357
struct pid
2d64357
  {
2d64357
    struct pid *next;
2d64357
    pid_t pid;
2d64357
  };
2d64357
static struct pid *pid_list;
2d64357
2d64357
static int pid_found (pid_t pid)
2d64357
{
2d64357
  struct pid *entry;
2d64357
2d64357
  for (entry = pid_list; entry != NULL; entry = entry->next)
2d64357
    if (entry->pid == pid)
2d64357
      return 1;
2d64357
  return 0;
2d64357
}
2d64357
2d64357
/* Single pass is not enough, a (multithreaded) process was seen to survive.
2d64357
   Repeated killing of the same process is not enough, zombies can be killed.
2d64357
   */
2d64357
static int cleanup_acted;
2d64357
2d64357
static void pid_record (pid_t pid)
2d64357
{
2d64357
  struct pid *entry;
2d64357
2d64357
  if (pid_found (pid))
2d64357
    return;
2d64357
  cleanup_acted = 1;
2d64357
2d64357
  entry = malloc (sizeof (*entry));
2d64357
  if (entry == NULL)
2d64357
    {
2d64357
      fprintf (stderr, "%s: malloc: %m\n", progname);
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
  entry->pid = pid;
2d64357
  entry->next = pid_list;
2d64357
  pid_list = entry;
2d64357
}
2d64357
2d64357
static void pid_forall (void (*func) (pid_t pid))
2d64357
{
2d64357
  struct pid *entry;
2d64357
2d64357
  for (entry = pid_list; entry != NULL; entry = entry->next)
2d64357
    (*func) (entry->pid);
2d64357
}
2d64357
2d64357
/* Returns 0 on failure.  */
2d64357
static pid_t pid_get_parent (pid_t pid)
2d64357
{
2d64357
  char fname[64];
2d64357
  FILE *f;
2d64357
  char line[LINE_MAX];
2d64357
  pid_t retval = 0;
2d64357
2d64357
  if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
2d64357
    {
2d64357
      perror ("snprintf(3)");
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
  f = fopen (fname, "r");
2d64357
  if (f == NULL)
2d64357
    {
2d64357
      return 0;
2d64357
    }
2d64357
  while (errno = 0, fgets (line, sizeof line, f) == line)
2d64357
    {
2d64357
      if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
2d64357
	continue;
2d64357
      retval = atoi (line + sizeof "PPid:\t" - 1);
2d64357
      errno = 0;
2d64357
      break;
2d64357
    }
2d64357
  if (errno != 0)
2d64357
    {
2d64357
      fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
  if (fclose (f) != 0)
2d64357
    {
2d64357
      fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
2d64357
  return retval;
2d64357
}
2d64357
2d64357
static void killtree (pid_t pid);
2d64357
2d64357
static void killtree_pid_fs_scan (pid_t pid, void *data)
2d64357
{
2d64357
  pid_t parent_pid = *(pid_t *) data;
2d64357
2d64357
  /* Do not optimize it as we could miss some newly spawned processes.
2d64357
     Always traverse all the leaves.  */
2d64357
#if 0
2d64357
  /* Optimization.  */
2d64357
  if (pid_found (pid))
2d64357
    return;
2d64357
#endif
2d64357
2d64357
  if (pid_get_parent (pid) != parent_pid)
2d64357
    return;
2d64357
2d64357
  killtree (pid);
2d64357
}
2d64357
2d64357
static void killtree (pid_t pid)
2d64357
{
2d64357
  pid_record (pid);
2d64357
  pid_fs_scan (killtree_pid_fs_scan, &pid;;
2d64357
}
2d64357
2d64357
static void rip_pid_fs_scan (pid_t pid, void *data)
2d64357
{
2d64357
  pid_t pgid;
2d64357
2d64357
  /* Shouldn't happen.  */
2d64357
  if (pid == getpid ())
2d64357
    return;
2d64357
2d64357
  /* Check both PGID and the stale file descriptors.  */
2d64357
  pgid = getpgid (pid);
2d64357
  if (pgid == child
2d64357
      || fd_fs_scan (pid, rip_check_ptyname) != 0)
2d64357
    killtree (pid);
2d64357
}
2d64357
2d64357
static void killproc (pid_t pid)
2d64357
{
2d64357
  const char *cmdline;
2d64357
2d64357
  cmdline = read_cmdline (pid);
2d64357
  /* Avoid printing the message for already gone processes.  */
2d64357
  if (kill (pid, 0) != 0 && errno == ESRCH)
2d64357
    return;
2d64357
  if (cmdline == NULL)
2d64357
    cmdline = "<error>";
2d64357
  fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
2d64357
  if (kill (pid, SIGKILL) == 0)
2d64357
    cleanup_acted = 1;
2d64357
  else if (errno != ESRCH)
2d64357
    fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
2d64357
  /* RHEL-3 kernels cannot SIGKILL a `T (stopped)' process.  */
2d64357
  kill (pid, SIGCONT);
2d64357
  /* Do not waitpid(2) as it cannot be our direct descendant and it gets
2d64357
     cleaned up by init(8).  */
2d64357
#if 0
2d64357
  pid_t pid_got;
2d64357
  pid_got = waitpid (pid, NULL, 0);
2d64357
  if (pid != pid_got)
2d64357
    {
2d64357
      fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
2d64357
	 (int) pid, (int) pid_got);
2d64357
      return;
2d64357
    }
2d64357
#endif
2d64357
}
2d64357
2d64357
static void rip (void)
2d64357
{
2d64357
  cleanup_acted = 0;
2d64357
  do
2d64357
    {
2d64357
      if (cleanup_acted)
2d64357
        usleep (1000000 / 10);
2d64357
      cleanup_acted = 0;
2d64357
      pid_fs_scan (rip_pid_fs_scan, NULL);
2d64357
      pid_forall (killproc);
2d64357
    }
2d64357
  while (cleanup_acted);
2d64357
}
2d64357
2d64357
int main (int argc, char **argv)
2d64357
{
620a59a
  int timeout = 0;
2d64357
  int rc;
2d64357
620a59a
  progname = *argv++;
620a59a
  argc--;
620a59a
620a59a
  if (argc < 1 || strcmp (*argv, "-h") == 0
620a59a
      || strcmp (*argv, "--help") == 0)
2d64357
    {
620a59a
      puts ("Syntax: orphanripper [-t <seconds>] <execvp(3) commandline>");
2d64357
      exit (EXIT_FAILURE);
2d64357
    }
620a59a
  if ((*argv)[0] == '-' && (*argv)[1] == 't')
620a59a
    {
620a59a
      char *timeout_s = NULL;
620a59a
620a59a
      if ((*argv)[2] == 0)
620a59a
	timeout_s = *++argv;
620a59a
      else if (isdigit ((*argv)[2]))
620a59a
	timeout_s = (*argv) + 2;
620a59a
      if (timeout_s != NULL)
620a59a
	{
620a59a
	  long l;
620a59a
	  char *endptr;
620a59a
620a59a
	  argv++;
620a59a
	  l = strtol (timeout_s, &endptr, 0);
620a59a
	  timeout = l;
620a59a
	  if ((endptr != NULL && *endptr != 0) || timeout < 0 || timeout != l)
620a59a
	    {
620a59a
	      fprintf (stderr, "%s: Invalid timeout value: %s\n", progname,
620a59a
		       timeout_s);
620a59a
	      exit (EXIT_FAILURE);
620a59a
	    }
620a59a
	}
620a59a
    }
620a59a
620a59a
  rc = spawn (argv, timeout);
2d64357
  rip ();
2d64357
  return rc;
2d64357
}