f60651a7733393ec063cfee3a9416d8b7941db81
[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 char childptyname[LINE_MAX];
67 static pid_t child;
68
69 static int spawn (char **argv)
70 {
71   pid_t child_got;
72   int status, amaster, i;
73   struct sigaction act;
74   struct termios termios;
75
76   i = pipe (pipefd);
77   assert (i == 0);
78
79   /* We do not use signal(2) to be sure we have SA_RESTART set.  */
80   memset (&act, 0, sizeof (act));
81   act.sa_handler = signal_child;
82   i = sigemptyset (&act.sa_mask);
83   assert (i == 0);
84   act.sa_flags = SA_RESTART;
85   i = sigaction (SIGCHLD, &act, NULL);
86   assert (i == 0);
87
88   /* With TERMP passed as NULL we get "\n" -> "\r\n".  */
89   termios.c_iflag = IGNBRK | IGNPAR;
90   termios.c_oflag = 0;
91   termios.c_cflag = CS8 | CREAD | CLOCAL | HUPCL | B9600;
92   termios.c_lflag = IEXTEN | NOFLSH;
93   memset (termios.c_cc, _POSIX_VDISABLE, sizeof (termios.c_cc));
94   termios.c_cc[VTIME] = 0;
95   termios.c_cc[VMIN ] = 1;
96   cfmakeraw (&termios);
97 #ifdef FLUSHO
98   /* Workaround a readline deadlock bug in _get_tty_settings().  */
99   termios.c_lflag &= ~FLUSHO;
100 #endif
101   child = forkpty (&amaster, childptyname, &termios, NULL);
102   switch (child)
103     {
104       case -1:
105         perror ("forkpty(3)");
106         exit (EXIT_FAILURE);
107       case 0:
108         i = close (pipefd[0]);
109         assert (i == 0);
110         i = close (pipefd[1]);
111         assert (i == 0);
112
113         /* Do not replace STDIN as inferiors query its termios.  */
114 #if 0
115         i = close (STDIN_FILENO);
116         assert (i == 0);
117         i = open ("/dev/null", O_RDONLY);
118         assert (i == STDIN_FILENO);
119 #endif
120
121         /* Do not setpgrp(2) in the parent process as the process-group
122            is shared for the whole sh(1) pipeline we could be a part
123            of.  The process-group is set according to PID of the first
124            command in the pipeline.
125            We would rip even vi(1) in the case of:
126                 ./orphanripper sh -c 'sleep 1&' | vi -
127            */
128         /* Do not setpgrp(2) as our pty would not be ours and we would
129            get `SIGSTOP' later, particularly after spawning gdb(1).
130            setsid(3) was already executed by forkpty(3) and it would fail if
131            executed again.  */
132         if (getpid() != getpgrp ())
133           {
134             perror ("getpgrp(2)");
135             exit (EXIT_FAILURE);
136           }
137         execvp (argv[1], argv + 1);
138         perror ("execvp(2)");
139         exit (EXIT_FAILURE);
140       default:
141         break;
142     }
143   i = fcntl (amaster, F_SETFL, O_RDWR | O_NONBLOCK);
144   if (i != 0)
145     {
146       perror ("fcntl (amaster, F_SETFL, O_NONBLOCK)");
147       exit (EXIT_FAILURE);
148     }
149   for (;;)
150     {
151       struct pollfd pollfd[2];
152       char buf[LINE_MAX];
153       ssize_t buf_got;
154
155       pollfd[0].fd = amaster;
156       pollfd[0].events = POLLIN;
157       pollfd[1].fd = pipefd[0];
158       pollfd[1].events = POLLIN;
159       i = poll (pollfd, LENGTH (pollfd), -1);
160       if (i == -1 && errno == EINTR)
161         {
162           /* Weird but SA_RESTART sometimes does not work.  */
163           continue;
164         }
165       assert (i >= 1);
166       /* Data available?  Process it first.  */
167       if (pollfd[0].revents & POLLIN)
168         {
169           buf_got = read (amaster, buf, sizeof buf);
170           if (buf_got <= 0)
171             {
172               perror ("read (amaster)");
173               exit (EXIT_FAILURE);
174             }
175           if (write (STDOUT_FILENO, buf, buf_got) != buf_got)
176             {
177               perror ("write(2)");
178               exit (EXIT_FAILURE);
179             }
180         }
181       if (pollfd[0].revents & POLLHUP)
182         break;
183       if ((pollfd[0].revents &= ~POLLIN) != 0)
184         {
185           fprintf (stderr, "%s: ppoll(2): revents 0x%x\n", progname,
186                    (unsigned) pollfd[0].revents);
187           exit (EXIT_FAILURE);
188         }
189       /* Child exited?  */
190       if (pollfd[1].revents & POLLHUP)
191         break;
192       assert (pollfd[1].revents == 0);
193     }
194   /* WNOHANG still could fail.  */
195   child_got = waitpid (child, &status, 0);
196   if (child != child_got)
197     {
198       fprintf (stderr, "waitpid (%d) = %d: %m\n", (int) child, (int) child_got);
199       exit (EXIT_FAILURE);
200     }
201   if (!WIFEXITED (status))
202     {
203       fprintf (stderr, "waitpid (%d): !WIFEXITED (%d)\n", (int) child, status);
204       exit (EXIT_FAILURE);
205     }
206
207   assert (signal_child_hit != 0);
208   assert (pipefd[1] == -1);
209   i = close (pipefd[0]);
210   assert (i == 0);
211
212   /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
213      entries which are not expected (and expecting ` (deleted)' would be
214      a race.  */
215 #if 0
216   i = close (amaster);
217   if (i != 0)
218     {
219       perror ("close (forkpty ()'s amaster)");
220       exit (EXIT_FAILURE);
221     }
222 #endif
223
224   return WEXITSTATUS (status);
225 }
226
227 /* Detected commandline may look weird due to a race:
228    Original command:
229         ./orphanripper sh -c 'sleep 1&' &
230    Correct output:
231         [1] 29610
232         ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
233    Raced output (sh(1) child still did not update its argv[]):
234         [1] 29613
235         ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
236    We could delay a bit before ripping the children.  */
237 static const char *read_cmdline (pid_t pid)
238 {
239   char cmdline_fname[32];
240   static char cmdline[LINE_MAX];
241   int fd;
242   ssize_t got;
243   char *s;
244
245   if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
246       (int) pid) < 0)
247     return NULL;
248   fd = open (cmdline_fname, O_RDONLY);
249   if (fd == -1)
250     {
251       /* It may have already exited - ENOENT.  */
252 #if 0
253       fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
254 #endif
255       return NULL;
256     }
257   got = read (fd, cmdline, sizeof (cmdline) - 1);
258   if (got == -1)
259     fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
260        cmdline_fname);
261   if (close (fd) != 0)
262     fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
263        cmdline_fname);
264   if (got < 0)
265     return NULL;
266   /* Convert '\0' argument delimiters to spaces.  */
267   for (s = cmdline; s < cmdline + got; s++)
268     if (!*s)
269       *s = ' ';
270   /* Trim the trailing spaces (typically single '\0'->' ').  */
271   while (s > cmdline && isspace (s[-1]))
272     s--;
273   *s = 0;
274   return cmdline;
275 }
276
277 static int dir_scan (const char *dirname,
278                   int (*callback) (struct dirent *dirent, const char *pathname))
279 {
280   DIR *dir;
281   struct dirent *dirent;
282   int rc = 0;
283
284   dir = opendir (dirname);
285   if (dir == NULL)
286     {
287       if (errno == EACCES || errno == ENOENT)
288         return rc;
289       fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
290       exit (EXIT_FAILURE);
291     }
292   while ((errno = 0, dirent = readdir (dir)))
293     {
294       char pathname[LINE_MAX];
295       int pathname_len;
296
297       pathname_len = snprintf (pathname, sizeof pathname, "%s/%s",
298                                  dirname, dirent->d_name);
299       if (pathname_len <= 0 || pathname_len >= sizeof pathname)
300         {
301           fprintf (stderr, "entry file name too long: `%s' / `%s'\n",
302                    dirname, dirent->d_name);
303           continue;
304         }
305       /* RHEL-4.5 on s390x never fills in D_TYPE.  */
306       if (dirent->d_type == DT_UNKNOWN)
307         {
308           struct stat statbuf;
309           int i;
310
311           /* We are not interested in the /proc/PID/fd/ links targets.  */
312           i = lstat (pathname, &statbuf);
313           if (i == -1)
314             {
315               if (errno == EACCES || errno == ENOENT)
316                 continue;
317               fprintf (stderr, "%s: stat (\"%s\"): %m\n", progname, pathname);
318               exit (EXIT_FAILURE);
319             }
320           if (S_ISDIR (statbuf.st_mode))
321             dirent->d_type = DT_DIR;
322           if (S_ISLNK (statbuf.st_mode))
323             dirent->d_type = DT_LNK;
324           /* No other D_TYPE types used in this code.  */
325         }
326       rc = (*callback) (dirent, pathname);
327       if (rc != 0)
328         {
329           errno = 0;
330           break;
331         }
332     }
333   if (errno != 0)
334     {
335       fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
336       exit (EXIT_FAILURE);
337     }
338   if (closedir (dir) != 0)
339     {
340       fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
341       exit (EXIT_FAILURE);
342     }
343   return rc;
344 }
345
346 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
347 {
348   char dirname[64];
349
350   if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
351     {
352       perror ("snprintf(3)");
353       exit (EXIT_FAILURE);
354     }
355
356   int callback (struct dirent *dirent, const char *pathname)
357   {
358     char buf[LINE_MAX];
359     ssize_t buf_len;
360
361     if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
362         || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
363             && strcmp (dirent->d_name, "..") != 0)
364         || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
365             != strlen (dirent->d_name)))
366       {
367         fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
368                          " on readdir (\"%s\"): %m\n",
369                  dirent->d_name, (unsigned) dirent->d_type, dirname);
370         return 0;
371       }
372     if (dirent->d_type == DT_DIR)
373       return 0;
374     buf_len = readlink (pathname, buf, sizeof buf - 1);
375     if (buf_len <= 0 || buf_len >= sizeof buf - 1)
376       {
377         if (errno != ENOENT && errno != EACCES)
378           fprintf (stderr, "Error reading link \"%s\": %m\n", pathname);
379         return 0;
380       }
381     buf[buf_len] = 0;
382     return (*func) (pid, buf);
383   }
384
385   return dir_scan (dirname, callback);
386 }
387
388 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
389 {
390   int callback (struct dirent *dirent, const char *pathname)
391   {
392     if (dirent->d_type != DT_DIR
393         || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
394       return 0;
395     (*func) (atoi (dirent->d_name), data);
396     return 0;
397   }
398
399   dir_scan ("/proc", callback);
400 }
401
402 static int rip_check_ptyname (pid_t pid, const char *link)
403 {
404   assert (pid != getpid ());
405
406   return strcmp (link, childptyname) == 0;
407 }
408
409 struct pid
410   {
411     struct pid *next;
412     pid_t pid;
413   };
414 static struct pid *pid_list;
415
416 static int pid_found (pid_t pid)
417 {
418   struct pid *entry;
419
420   for (entry = pid_list; entry != NULL; entry = entry->next)
421     if (entry->pid == pid)
422       return 1;
423   return 0;
424 }
425
426 /* Single pass is not enough, a (multithreaded) process was seen to survive.
427    Repeated killing of the same process is not enough, zombies can be killed.
428    */
429 static int cleanup_acted;
430
431 static void pid_record (pid_t pid)
432 {
433   struct pid *entry;
434
435   if (pid_found (pid))
436     return;
437   cleanup_acted = 1;
438
439   entry = malloc (sizeof (*entry));
440   if (entry == NULL)
441     {
442       fprintf (stderr, "%s: malloc: %m\n", progname);
443       exit (EXIT_FAILURE);
444     }
445   entry->pid = pid;
446   entry->next = pid_list;
447   pid_list = entry;
448 }
449
450 static void pid_forall (void (*func) (pid_t pid))
451 {
452   struct pid *entry;
453
454   for (entry = pid_list; entry != NULL; entry = entry->next)
455     (*func) (entry->pid);
456 }
457
458 /* Returns 0 on failure.  */
459 static pid_t pid_get_parent (pid_t pid)
460 {
461   char fname[64];
462   FILE *f;
463   char line[LINE_MAX];
464   pid_t retval = 0;
465
466   if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
467     {
468       perror ("snprintf(3)");
469       exit (EXIT_FAILURE);
470     }
471   f = fopen (fname, "r");
472   if (f == NULL)
473     {
474       return 0;
475     }
476   while (errno = 0, fgets (line, sizeof line, f) == line)
477     {
478       if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
479         continue;
480       retval = atoi (line + sizeof "PPid:\t" - 1);
481       errno = 0;
482       break;
483     }
484   if (errno != 0)
485     {
486       fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
487       exit (EXIT_FAILURE);
488     }
489   if (fclose (f) != 0)
490     {
491       fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
492       exit (EXIT_FAILURE);
493     }
494   return retval;
495 }
496
497 static void killtree (pid_t pid);
498
499 static void killtree_pid_fs_scan (pid_t pid, void *data)
500 {
501   pid_t parent_pid = *(pid_t *) data;
502
503   /* Do not optimize it as we could miss some newly spawned processes.
504      Always traverse all the leaves.  */
505 #if 0
506   /* Optimization.  */
507   if (pid_found (pid))
508     return;
509 #endif
510
511   if (pid_get_parent (pid) != parent_pid)
512     return;
513
514   killtree (pid);
515 }
516
517 static void killtree (pid_t pid)
518 {
519   pid_record (pid);
520   pid_fs_scan (killtree_pid_fs_scan, &pid);
521 }
522
523 static void rip_pid_fs_scan (pid_t pid, void *data)
524 {
525   pid_t pgid;
526
527   /* Shouldn't happen.  */
528   if (pid == getpid ())
529     return;
530
531   /* Check both PGID and the stale file descriptors.  */
532   pgid = getpgid (pid);
533   if (pgid == child
534       || fd_fs_scan (pid, rip_check_ptyname) != 0)
535     killtree (pid);
536 }
537
538 static void killproc (pid_t pid)
539 {
540   const char *cmdline;
541
542   cmdline = read_cmdline (pid);
543   /* Avoid printing the message for already gone processes.  */
544   if (kill (pid, 0) != 0 && errno == ESRCH)
545     return;
546   if (cmdline == NULL)
547     cmdline = "<error>";
548   fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
549   if (kill (pid, SIGKILL) == 0)
550     cleanup_acted = 1;
551   else if (errno != ESRCH)
552     fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
553   /* RHEL-3 kernels cannot SIGKILL a `T (stopped)' process.  */
554   kill (pid, SIGCONT);
555   /* Do not waitpid(2) as it cannot be our direct descendant and it gets
556      cleaned up by init(8).  */
557 #if 0
558   pid_t pid_got;
559   pid_got = waitpid (pid, NULL, 0);
560   if (pid != pid_got)
561     {
562       fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
563          (int) pid, (int) pid_got);
564       return;
565     }
566 #endif
567 }
568
569 static void rip (void)
570 {
571   cleanup_acted = 0;
572   do
573     {
574       if (cleanup_acted)
575         usleep (1000000 / 10);
576       cleanup_acted = 0;
577       pid_fs_scan (rip_pid_fs_scan, NULL);
578       pid_forall (killproc);
579     }
580   while (cleanup_acted);
581 }
582
583 int main (int argc, char **argv)
584 {
585   int rc;
586
587   if (argc < 2 || strcmp (argv[1], "-h") == 0
588       || strcmp (argv[1], "--help") == 0)
589     {
590       fputs ("Syntax: orphanripper <execvp(3) commandline>\n", stdout);
591       exit (EXIT_FAILURE);
592     }
593   progname = argv[0];
594   rc = spawn (argv);
595   rip ();
596   return rc;
597 }