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