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