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