fuser: code shrink
[platform/upstream/busybox.git] / procps / fuser.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * tiny fuser implementation
4  *
5  * Copyright 2004 Tony J. White
6  *
7  * Licensed under GPLv2, see file LICENSE in this source tree.
8  */
9
10 //usage:#define fuser_trivial_usage
11 //usage:       "[OPTIONS] FILE or PORT/PROTO"
12 //usage:#define fuser_full_usage "\n\n"
13 //usage:       "Find processes which use FILEs or PORTs\n"
14 //usage:     "\nOptions:"
15 //usage:     "\n        -m      Find processes which use same fs as FILEs"
16 //usage:     "\n        -4,-6   Search only IPv4/IPv6 space"
17 //usage:     "\n        -s      Don't display PIDs"
18 //usage:     "\n        -k      Kill found processes"
19 //usage:     "\n        -SIGNAL Signal to send (default: KILL)"
20
21 #include "libbb.h"
22
23 #define MAX_LINE 255
24
25 #define OPTION_STRING "mks64"
26 enum {
27         OPT_MOUNT  = (1 << 0),
28         OPT_KILL   = (1 << 1),
29         OPT_SILENT = (1 << 2),
30         OPT_IP6    = (1 << 3),
31         OPT_IP4    = (1 << 4),
32 };
33
34 typedef struct inode_list {
35         struct inode_list *next;
36         ino_t inode;
37         dev_t dev;
38 } inode_list;
39
40 struct globals {
41         int recursion_depth;
42         pid_t mypid;
43         inode_list *inode_list_head;
44         smallint kill_failed;
45         int killsig;
46 } FIX_ALIASING;
47 #define G (*(struct globals*)&bb_common_bufsiz1)
48 #define INIT_G() do { \
49         G.mypid = getpid(); \
50         G.killsig = SIGKILL; \
51 } while (0)
52
53 static void add_inode(const struct stat *st)
54 {
55         inode_list **curr = &G.inode_list_head;
56
57         while (*curr) {
58                 if ((*curr)->dev == st->st_dev
59                  && (*curr)->inode == st->st_ino
60                 ) {
61                         return;
62                 }
63                 curr = &(*curr)->next;
64         }
65
66         *curr = xzalloc(sizeof(inode_list));
67         (*curr)->dev = st->st_dev;
68         (*curr)->inode = st->st_ino;
69 }
70
71 static smallint search_dev_inode(const struct stat *st)
72 {
73         inode_list *ilist = G.inode_list_head;
74
75         while (ilist) {
76                 if (ilist->dev == st->st_dev) {
77                         if (option_mask32 & OPT_MOUNT)
78                                 return 1;
79                         if (ilist->inode == st->st_ino)
80                                 return 1;
81                 }
82                 ilist = ilist->next;
83         }
84         return 0;
85 }
86
87 enum {
88         PROC_NET = 0,
89         PROC_DIR,
90         PROC_DIR_LINKS,
91         PROC_SUBDIR_LINKS,
92 };
93
94 static smallint scan_proc_net_or_maps(const char *path, unsigned port)
95 {
96         FILE *f;
97         char line[MAX_LINE + 1], addr[68];
98         int major, minor, r;
99         long long uint64_inode;
100         unsigned tmp_port;
101         smallint retval;
102         struct stat statbuf;
103         const char *fmt;
104         void *fag, *sag;
105
106         f = fopen_for_read(path);
107         if (!f)
108                 return 0;
109
110         if (G.recursion_depth == PROC_NET) {
111                 int fd;
112
113                 /* find socket dev */
114                 statbuf.st_dev = 0;
115                 fd = socket(AF_INET, SOCK_DGRAM, 0);
116                 if (fd >= 0) {
117                         fstat(fd, &statbuf);
118                         close(fd);
119                 }
120
121                 fmt = "%*d: %64[0-9A-Fa-f]:%x %*x:%*x %*x "
122                         "%*x:%*x %*x:%*x %*x %*d %*d %llu";
123                 fag = addr;
124                 sag = &tmp_port;
125         } else {
126                 fmt = "%*s %*s %*s %x:%x %llu";
127                 fag = &major;
128                 sag = &minor;
129         }
130
131         retval = 0;
132         while (fgets(line, MAX_LINE, f)) {
133                 r = sscanf(line, fmt, fag, sag, &uint64_inode);
134                 if (r != 3)
135                         continue;
136
137                 statbuf.st_ino = uint64_inode;
138                 if (G.recursion_depth == PROC_NET) {
139                         r = strlen(addr);
140                         if (r == 8 && (option_mask32 & OPT_IP6))
141                                 continue;
142                         if (r > 8 && (option_mask32 & OPT_IP4))
143                                 continue;
144                         if (tmp_port == port)
145                                 add_inode(&statbuf);
146                 } else {
147                         if (major != 0 && minor != 0 && statbuf.st_ino != 0) {
148                                 statbuf.st_dev = makedev(major, minor);
149                                 retval = search_dev_inode(&statbuf);
150                                 if (retval)
151                                         break;
152                         }
153                 }
154         }
155         fclose(f);
156
157         return retval;
158 }
159
160 static smallint scan_recursive(const char *path)
161 {
162         DIR *d;
163         struct dirent *d_ent;
164         smallint stop_scan;
165         smallint retval;
166
167         d = opendir(path);
168         if (d == NULL)
169                 return 0;
170
171         G.recursion_depth++;
172         retval = 0;
173         stop_scan = 0;
174         while (!stop_scan && (d_ent = readdir(d)) != NULL) {
175                 struct stat statbuf;
176                 pid_t pid;
177                 char *subpath;
178
179                 subpath = concat_subpath_file(path, d_ent->d_name);
180                 if (subpath == NULL)
181                         continue; /* . or .. */
182
183                 switch (G.recursion_depth) {
184                 case PROC_DIR:
185                         pid = (pid_t)bb_strtou(d_ent->d_name, NULL, 10);
186                         if (errno != 0
187                          || pid == G.mypid
188                         /* "this PID doesn't use specified FILEs or PORT/PROTO": */
189                          || scan_recursive(subpath) == 0
190                         ) {
191                                 break;
192                         }
193                         if (option_mask32 & OPT_KILL) {
194                                 if (kill(pid, G.killsig) != 0) {
195                                         bb_perror_msg("kill pid %s", d_ent->d_name);
196                                         G.kill_failed = 1;
197                                 }
198                         }
199                         if (!(option_mask32 & OPT_SILENT))
200                                 printf("%s ", d_ent->d_name);
201                         retval = 1;
202                         break;
203
204                 case PROC_DIR_LINKS:
205                         switch (
206                                 index_in_substrings(
207                                         "cwd"  "\0" "exe"  "\0"
208                                         "root" "\0" "fd"   "\0"
209                                         "lib"  "\0" "mmap" "\0"
210                                         "maps" "\0",
211                                         d_ent->d_name
212                                 )
213                         ) {
214                         enum {
215                                 CWD_LINK,
216                                 EXE_LINK,
217                                 ROOT_LINK,
218                                 FD_DIR_LINKS,
219                                 LIB_DIR_LINKS,
220                                 MMAP_DIR_LINKS,
221                                 MAPS,
222                         };
223                         case CWD_LINK:
224                         case EXE_LINK:
225                         case ROOT_LINK:
226                                 goto scan_link;
227                         case FD_DIR_LINKS:
228                         case LIB_DIR_LINKS:
229                         case MMAP_DIR_LINKS:
230                                 stop_scan = scan_recursive(subpath);
231                                 if (stop_scan)
232                                         retval = stop_scan;
233                                 break;
234                         case MAPS:
235                                 stop_scan = scan_proc_net_or_maps(subpath, 0);
236                                 if (stop_scan)
237                                         retval = stop_scan;
238                         default:
239                                 break;
240                         }
241                         break;
242                 case PROC_SUBDIR_LINKS:
243   scan_link:
244                         if (stat(subpath, &statbuf) < 0)
245                                 break;
246                         stop_scan = search_dev_inode(&statbuf);
247                         if (stop_scan)
248                                 retval = stop_scan;
249                 default:
250                         break;
251                 }
252                 free(subpath);
253         }
254         closedir(d);
255         G.recursion_depth--;
256         return retval;
257 }
258
259 int fuser_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
260 int fuser_main(int argc UNUSED_PARAM, char **argv)
261 {
262         char **pp;
263
264         INIT_G();
265
266         /* Handle -SIGNAL. Oh my... */
267         pp = argv;
268         while (*++pp) {
269                 int sig;
270                 char *arg = *pp;
271
272                 if (arg[0] != '-')
273                         continue;
274                 if (arg[1] == '-' && arg[2] == '\0') /* "--" */
275                         break;
276                 if ((arg[1] == '4' || arg[1] == '6') && arg[2] == '\0')
277                         continue; /* it's "-4" or "-6" */
278                 sig = get_signum(&arg[1]);
279                 if (sig < 0)
280                         continue;
281                 /* "-SIGNAL" option found. Remove it and bail out */
282                 G.killsig = sig;
283                 do {
284                         pp[0] = arg = pp[1];
285                         pp++;
286                 } while (arg);
287                 break;
288         }
289
290         opt_complementary = "-1"; /* at least one param */
291         getopt32(argv, OPTION_STRING);
292         argv += optind;
293
294         pp = argv;
295         while (*pp) {
296                 /* parse net arg */
297                 unsigned port;
298                 char path[sizeof("/proc/net/TCP6")];
299
300                 strcpy(path, "/proc/net/");
301                 if (sscanf(*pp, "%u/%4s", &port, path + sizeof("/proc/net/")-1) == 2
302                  && access(path, R_OK) != 0
303                 ) {
304                         /* PORT/PROTO */
305                         scan_proc_net_or_maps(path, port);
306                 } else {
307                         /* FILE */
308                         struct stat statbuf;
309                         xstat(*pp, &statbuf);
310                         add_inode(&statbuf);
311                 }
312                 pp++;
313         }
314
315         if (scan_recursive("/proc")) {
316                 if (!(option_mask32 & OPT_SILENT))
317                         bb_putchar('\n');
318                 return G.kill_failed;
319         }
320
321         return EXIT_FAILURE;
322 }