1189df655716e949148c4bfa7844e1cb6b44a7cb
[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   i = fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */);
280   if (i != 0)
281     {
282       perror ("fcntl (amaster, F_SETFL, O_RDONLY /* !O_NONBLOCK */)");
283       exit (EXIT_FAILURE);
284     }
285
286   while (read_out (amaster));
287
288   /* Do not close the master FD as the child would have `/dev/pts/23 (deleted)'
289      entries which are not expected (and expecting ` (deleted)' would be
290      a race.  */
291 #if 0
292   i = close (amaster);
293   if (i != 0)
294     {
295       perror ("close (forkpty ()'s amaster)");
296       exit (EXIT_FAILURE);
297     }
298 #endif
299
300   return rc;
301 }
302
303 /* Detected commandline may look weird due to a race:
304    Original command:
305         ./orphanripper sh -c 'sleep 1&' &
306    Correct output:
307         [1] 29610
308         ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
309    Raced output (sh(1) child still did not update its argv[]):
310         [1] 29613
311         ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
312    We could delay a bit before ripping the children.  */
313 static const char *read_cmdline (pid_t pid)
314 {
315   char cmdline_fname[32];
316   static char cmdline[LINE_MAX];
317   int fd;
318   ssize_t got;
319   char *s;
320
321   if (snprintf (cmdline_fname, sizeof cmdline_fname, "/proc/%d/cmdline",
322       (int) pid) < 0)
323     return NULL;
324   fd = open (cmdline_fname, O_RDONLY);
325   if (fd == -1)
326     {
327       /* It may have already exited - ENOENT.  */
328 #if 0
329       fprintf (stderr, "%s: open (\"%s\"): %m\n", progname, cmdline_fname);
330 #endif
331       return NULL;
332     }
333   got = read (fd, cmdline, sizeof (cmdline) - 1);
334   if (got == -1)
335     fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
336        cmdline_fname);
337   if (close (fd) != 0)
338     fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
339        cmdline_fname);
340   if (got < 0)
341     return NULL;
342   /* Convert '\0' argument delimiters to spaces.  */
343   for (s = cmdline; s < cmdline + got; s++)
344     if (!*s)
345       *s = ' ';
346   /* Trim the trailing spaces (typically single '\0'->' ').  */
347   while (s > cmdline && isspace (s[-1]))
348     s--;
349   *s = 0;
350   return cmdline;
351 }
352
353 static int dir_scan (const char *dirname,
354                   int (*callback) (struct dirent *dirent, const char *pathname))
355 {
356   DIR *dir;
357   struct dirent *dirent;
358   int rc = 0;
359
360   dir = opendir (dirname);
361   if (dir == NULL)
362     {
363       if (errno == EACCES || errno == ENOENT)
364         return rc;
365       fprintf (stderr, "%s: opendir (\"%s\"): %m\n", progname, dirname);
366       exit (EXIT_FAILURE);
367     }
368   while ((errno = 0, dirent = readdir (dir)))
369     {
370       char pathname[LINE_MAX];
371       int pathname_len;
372
373       pathname_len = snprintf (pathname, sizeof pathname, "%s/%s",
374                                  dirname, dirent->d_name);
375       if (pathname_len <= 0 || pathname_len >= (int) sizeof pathname)
376         {
377           fprintf (stderr, "entry file name too long: `%s' / `%s'\n",
378                    dirname, dirent->d_name);
379           continue;
380         }
381       /* RHEL-4.5 on s390x never fills in D_TYPE.  */
382       if (dirent->d_type == DT_UNKNOWN)
383         {
384           struct stat statbuf;
385           int i;
386
387           /* We are not interested in the /proc/PID/fd/ links targets.  */
388           i = lstat (pathname, &statbuf);
389           if (i == -1)
390             {
391               if (errno == EACCES || errno == ENOENT)
392                 continue;
393               fprintf (stderr, "%s: stat (\"%s\"): %m\n", progname, pathname);
394               exit (EXIT_FAILURE);
395             }
396           if (S_ISDIR (statbuf.st_mode))
397             dirent->d_type = DT_DIR;
398           if (S_ISLNK (statbuf.st_mode))
399             dirent->d_type = DT_LNK;
400           /* No other D_TYPE types used in this code.  */
401         }
402       rc = (*callback) (dirent, pathname);
403       if (rc != 0)
404         {
405           errno = 0;
406           break;
407         }
408     }
409   if (errno != 0)
410     {
411       fprintf (stderr, "%s: readdir (\"%s\"): %m\n", progname, dirname);
412       exit (EXIT_FAILURE);
413     }
414   if (closedir (dir) != 0)
415     {
416       fprintf (stderr, "%s: closedir (\"%s\"): %m\n", progname, dirname);
417       exit (EXIT_FAILURE);
418     }
419   return rc;
420 }
421
422 static int fd_fs_scan (pid_t pid, int (*func) (pid_t pid, const char *link))
423 {
424   char dirname[64];
425
426   if (snprintf (dirname, sizeof dirname, "/proc/%d/fd", (int) pid) < 0)
427     {
428       perror ("snprintf(3)");
429       exit (EXIT_FAILURE);
430     }
431
432   int callback (struct dirent *dirent, const char *pathname)
433   {
434     char buf[LINE_MAX];
435     ssize_t buf_len;
436
437     if ((dirent->d_type != DT_DIR && dirent->d_type != DT_LNK)
438         || (dirent->d_type == DT_DIR && strcmp (dirent->d_name, ".") != 0
439             && strcmp (dirent->d_name, "..") != 0)
440         || (dirent->d_type == DT_LNK && strspn (dirent->d_name, "0123456789")
441             != strlen (dirent->d_name)))
442       {
443         fprintf (stderr, "Unexpected entry \"%s\" (d_type %u)"
444                          " on readdir (\"%s\"): %m\n",
445                  dirent->d_name, (unsigned) dirent->d_type, dirname);
446         return 0;
447       }
448     if (dirent->d_type == DT_DIR)
449       return 0;
450     buf_len = readlink (pathname, buf, sizeof buf - 1);
451     if (buf_len <= 0 || buf_len >= (ssize_t) sizeof buf - 1)
452       {
453         if (errno != ENOENT && errno != EACCES)
454           fprintf (stderr, "Error reading link \"%s\": %m\n", pathname);
455         return 0;
456       }
457     buf[buf_len] = 0;
458     return (*func) (pid, buf);
459   }
460
461   return dir_scan (dirname, callback);
462 }
463
464 static void pid_fs_scan (void (*func) (pid_t pid, void *data), void *data)
465 {
466   int callback (struct dirent *dirent, const char *pathname)
467   {
468     if (dirent->d_type != DT_DIR
469         || strspn (dirent->d_name, "0123456789") != strlen (dirent->d_name))
470       return 0;
471     (*func) (atoi (dirent->d_name), data);
472     return 0;
473   }
474
475   dir_scan ("/proc", callback);
476 }
477
478 static int rip_check_ptyname (pid_t pid, const char *link)
479 {
480   assert (pid != getpid ());
481
482   return strcmp (link, childptyname) == 0;
483 }
484
485 struct pid
486   {
487     struct pid *next;
488     pid_t pid;
489   };
490 static struct pid *pid_list;
491
492 static int pid_found (pid_t pid)
493 {
494   struct pid *entry;
495
496   for (entry = pid_list; entry != NULL; entry = entry->next)
497     if (entry->pid == pid)
498       return 1;
499   return 0;
500 }
501
502 /* Single pass is not enough, a (multithreaded) process was seen to survive.
503    Repeated killing of the same process is not enough, zombies can be killed.
504    */
505 static int cleanup_acted;
506
507 static void pid_record (pid_t pid)
508 {
509   struct pid *entry;
510
511   if (pid_found (pid))
512     return;
513   cleanup_acted = 1;
514
515   entry = malloc (sizeof (*entry));
516   if (entry == NULL)
517     {
518       fprintf (stderr, "%s: malloc: %m\n", progname);
519       exit (EXIT_FAILURE);
520     }
521   entry->pid = pid;
522   entry->next = pid_list;
523   pid_list = entry;
524 }
525
526 static void pid_forall (void (*func) (pid_t pid))
527 {
528   struct pid *entry;
529
530   for (entry = pid_list; entry != NULL; entry = entry->next)
531     (*func) (entry->pid);
532 }
533
534 /* Returns 0 on failure.  */
535 static pid_t pid_get_parent (pid_t pid)
536 {
537   char fname[64];
538   FILE *f;
539   char line[LINE_MAX];
540   pid_t retval = 0;
541
542   if (snprintf (fname, sizeof fname, "/proc/%d/status", (int) pid) < 0)
543     {
544       perror ("snprintf(3)");
545       exit (EXIT_FAILURE);
546     }
547   f = fopen (fname, "r");
548   if (f == NULL)
549     {
550       return 0;
551     }
552   while (errno = 0, fgets (line, sizeof line, f) == line)
553     {
554       if (strncmp (line, "PPid:\t", sizeof "PPid:\t" - 1) != 0)
555         continue;
556       retval = atoi (line + sizeof "PPid:\t" - 1);
557       errno = 0;
558       break;
559     }
560   if (errno != 0)
561     {
562       fprintf (stderr, "%s: fgets (\"%s\"): %m\n", progname, fname);
563       exit (EXIT_FAILURE);
564     }
565   if (fclose (f) != 0)
566     {
567       fprintf (stderr, "%s: fclose (\"%s\"): %m\n", progname, fname);
568       exit (EXIT_FAILURE);
569     }
570   return retval;
571 }
572
573 static void killtree (pid_t pid);
574
575 static void killtree_pid_fs_scan (pid_t pid, void *data)
576 {
577   pid_t parent_pid = *(pid_t *) data;
578
579   /* Do not optimize it as we could miss some newly spawned processes.
580      Always traverse all the leaves.  */
581 #if 0
582   /* Optimization.  */
583   if (pid_found (pid))
584     return;
585 #endif
586
587   if (pid_get_parent (pid) != parent_pid)
588     return;
589
590   killtree (pid);
591 }
592
593 static void killtree (pid_t pid)
594 {
595   pid_record (pid);
596   pid_fs_scan (killtree_pid_fs_scan, &pid);
597 }
598
599 static void rip_pid_fs_scan (pid_t pid, void *data)
600 {
601   pid_t pgid;
602
603   /* Shouldn't happen.  */
604   if (pid == getpid ())
605     return;
606
607   /* Check both PGID and the stale file descriptors.  */
608   pgid = getpgid (pid);
609   if (pgid == child
610       || fd_fs_scan (pid, rip_check_ptyname) != 0)
611     killtree (pid);
612 }
613
614 static void killproc (pid_t pid)
615 {
616   const char *cmdline;
617
618   cmdline = read_cmdline (pid);
619   /* Avoid printing the message for already gone processes.  */
620   if (kill (pid, 0) != 0 && errno == ESRCH)
621     return;
622   if (cmdline == NULL)
623     cmdline = "<error>";
624   fprintf (stderr, "%s: Killed -9 orphan PID %d: %s\n", progname, (int) pid, cmdline);
625   if (kill (pid, SIGKILL) == 0)
626     cleanup_acted = 1;
627   else if (errno != ESRCH)
628     fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname, (int) pid);
629   /* RHEL-3 kernels cannot SIGKILL a `T (stopped)' process.  */
630   kill (pid, SIGCONT);
631   /* Do not waitpid(2) as it cannot be our direct descendant and it gets
632      cleaned up by init(8).  */
633 #if 0
634   pid_t pid_got;
635   pid_got = waitpid (pid, NULL, 0);
636   if (pid != pid_got)
637     {
638       fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
639          (int) pid, (int) pid_got);
640       return;
641     }
642 #endif
643 }
644
645 static void rip (void)
646 {
647   cleanup_acted = 0;
648   do
649     {
650       if (cleanup_acted)
651         usleep (1000000 / 10);
652       cleanup_acted = 0;
653       pid_fs_scan (rip_pid_fs_scan, NULL);
654       pid_forall (killproc);
655     }
656   while (cleanup_acted);
657 }
658
659 int main (int argc, char **argv)
660 {
661   int timeout = 0;
662   int rc;
663
664   progname = *argv++;
665   argc--;
666
667   if (argc < 1 || strcmp (*argv, "-h") == 0
668       || strcmp (*argv, "--help") == 0)
669     {
670       puts ("Syntax: orphanripper [-t <seconds>] <execvp(3) commandline>");
671       exit (EXIT_FAILURE);
672     }
673   if ((*argv)[0] == '-' && (*argv)[1] == 't')
674     {
675       char *timeout_s = NULL;
676
677       if ((*argv)[2] == 0)
678         timeout_s = *++argv;
679       else if (isdigit ((*argv)[2]))
680         timeout_s = (*argv) + 2;
681       if (timeout_s != NULL)
682         {
683           long l;
684           char *endptr;
685
686           argv++;
687           l = strtol (timeout_s, &endptr, 0);
688           timeout = l;
689           if ((endptr != NULL && *endptr != 0) || timeout < 0 || timeout != l)
690             {
691               fprintf (stderr, "%s: Invalid timeout value: %s\n", progname,
692                        timeout_s);
693               exit (EXIT_FAILURE);
694             }
695         }
696     }
697
698   rc = spawn (argv, timeout);
699   rip ();
700   return rc;
701 }