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