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