2006-11-30
[nethome.git] / src / orphanripper.c
1 /*
2  * Copyright 2006 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  * 2006-11-30  Jan Kratochvil  <jan.kratochvil@redhat.com>
20  */
21
22
23 #define _XOPEN_SOURCE 1
24 #define _XOPEN_SOURCE_EXTENDED 1
25 #define _BSD_SOURCE 1
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <dirent.h>
32 #include <unistd.h>
33 #include <errno.h>
34 #include <ctype.h>
35 #include <string.h>
36 #include <limits.h>
37 #include <fcntl.h>
38
39
40 static const char *progname;
41
42 static int spawn (char **argv, pid_t *child_pointer)
43 {
44         pid_t child, child_got;
45         int status;
46
47         switch (child = fork ()) {
48         case -1:
49                 perror ("fork(2)");
50                 exit (EXIT_FAILURE);
51         case 0:
52                 /* Do not setpgrp(2) in the parent process as the process-group
53                    is shared for the whole sh(1) pipeline we could be a part
54                    of.  The process-group is set according to PID of the first
55                    command in the pipeline.
56                    We would rip even vi(1) in the case of:
57                         ./orphanripper sh -c 'sleep 1&' | vi -
58                    */
59                 if (setpgrp ()) {
60                         perror ("setpgrp");
61                         exit (EXIT_FAILURE);
62                 }
63                 execvp (argv[1], argv + 1);
64                 perror ("execvp(2)");
65                 exit (EXIT_FAILURE);
66         default:
67                 break;
68         }
69         if (child != (child_got = waitpid (child, &status, 0))) {
70                 fprintf (stderr, "waitpid(%d)=%d: %m\n", (int) child,
71                          (int) child_got);
72                 exit (EXIT_FAILURE);
73         }
74         if (!WIFEXITED (status)) {
75                 fprintf (stderr, "waitpid(2): !WIFEXITED(%d)\n", status);
76                 exit (EXIT_FAILURE);
77         }
78
79         if (child_pointer)
80                 *child_pointer = child;
81         return WEXITSTATUS (status);
82 }
83
84 /* Detected commandline may look weird due to a race:
85    Original command:
86         ./orphanripper sh -c 'sleep 1&' &
87    Correct output:
88         [1] 29610
89         ./orphanripper: Killed -9 orphan PID 29612 (PGID 29611): sleep 1
90    Raced output (sh(1) child still did not update its argv[]):
91         [1] 29613
92         ./orphanripper: Killed -9 orphan PID 29615 (PGID 29614): sh -c sleep 1&
93    We could delay a bit before ripping the children.  */
94 static const char *read_cmdline (pid_t pid)
95 {
96         char cmdline_fname[32];
97         static char cmdline[LINE_MAX];
98         int fd;
99         ssize_t got;
100         char *s;
101
102         if (snprintf (cmdline_fname, sizeof (cmdline_fname), "/proc/%d/cmdline",
103                   (int) pid) < 0)
104                 return NULL;
105         fd = open (cmdline_fname, O_RDONLY);
106         if (fd == -1) {
107                 fprintf (stderr, "%s: open (\"%s\"): %m\n", progname,
108                          cmdline_fname);
109                 return NULL;
110         }
111         got = read (fd, cmdline, sizeof (cmdline) - 1);
112         if (got == -1)
113                 fprintf (stderr, "%s: read (\"%s\"): %m\n", progname,
114                          cmdline_fname);
115         if (close (fd))
116                 fprintf (stderr, "%s: close (\"%s\"): %m\n", progname,
117                          cmdline_fname);
118         if (got < 0)
119                 return NULL;
120         /* Convert '\0' argument delimiters to spaces.  */
121         for (s = cmdline; s < cmdline + got; s++)
122                 if (!*s)
123                         *s = ' ';
124         /* Trim the trailing spaces (typically single '\0'->' ').  */
125         while (s > cmdline && isspace (s[-1]))
126                 s--;
127         *s = 0;
128         return cmdline;
129 }
130
131 static void rip_pid (pid_t pid, pid_t pgid_child)
132 {
133         pid_t pgid_pids;
134         const char *cmdline;
135
136         /* Don't shoot ourselves.  */
137         if (pid == getpid())
138                 return;
139         pgid_pids = getpgid (pid);
140         /* Ignore errors (permissions? untested).  */
141         if (pgid_pids == -1)
142                 return;
143         /* Not a process of ours.  */
144         if (pgid_pids != pgid_child)
145                 return;
146
147         cmdline = read_cmdline (pid);
148         if (!cmdline)
149                 cmdline = "<error>";
150         fprintf (stderr, "%s: Killed -9 orphan PID %d (PGID %d): %s\n",
151                  progname, (int) pid, (int) pgid_pids, cmdline);
152         if (kill (pid, SIGKILL)) {
153                 fprintf (stderr, "%s: kill (%d, SIGKILL): %m\n", progname,
154                          (int) pid);
155                 return;
156         }
157         /* Do not waitpid(2) as it cannot be our direct descendant and it gets
158            cleaned up by init(8).  */
159 #if 0
160         pid_t pid_got;
161         if (pid != (pid_got = waitpid (pid, NULL, 0))) {
162                 fprintf (stderr, "%s: waitpid (%d) != %d: %m\n", progname,
163                          (int) pid, (int) pid_got);
164                 return;
165         }
166 #endif
167 }
168
169 static void rip (pid_t pgid_child)
170 {
171         DIR *dir;
172         struct dirent *dirent;
173
174         dir = opendir ("/proc");
175         if (!dir) {
176                 perror ("opendir (\"/proc\")");
177                 exit (EXIT_FAILURE);
178         }
179         while ((errno = 0, dirent = readdir (dir))) {
180                 const char *cs;
181
182                 /* FIXME: POSIX portability.  */
183                 if (dirent->d_type != DT_DIR)
184                         continue;
185                 /* Check /^\d+$/:  */
186                 for (cs = dirent->d_name; *cs; cs++)
187                         if (!isdigit (*cs))
188                                 break;
189                 if (cs == dirent->d_name || *cs)
190                         continue;
191                 rip_pid (atoi (dirent->d_name), pgid_child);
192         }
193         if (errno) {
194                 perror ("readdir (\"/proc\")");
195                 exit (EXIT_FAILURE);
196         }
197         if (closedir (dir)) {
198                 perror ("closedir (\"/proc\")");
199                 exit (EXIT_FAILURE);
200         }
201
202 }
203
204 int main (int argc, char **argv)
205 {
206         int rc;
207         pid_t child;
208
209         if (argc < 2
210             || !strcmp (argv[1], "-h")
211             || !strcmp (argv[1], "--help")) {
212                 fputs("Syntax: orphanripper <execvp(3) commandline>\n", stdout);
213                 exit (EXIT_FAILURE);
214         }
215         progname = argv[0];
216         rc = spawn (argv, &child);
217         rip (child);
218         return rc;
219 }