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