fix warning in find.c
[oweals/busybox.git] / findutils / find.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini find implementation for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Reworked by David Douthitt <n9ubh@callsign.net> and
8  *  Matt Kraai <kraai@alumni.carnegiemellon.edu>.
9  *
10  * Licensed under the GPL version 2, see the file LICENSE in this tarball.
11  */
12
13 /* findutils-4.1.20:
14  *
15  * # find file.txt -exec 'echo {}' '{}  {}' ';'
16  * find: echo file.txt: No such file or directory
17  * # find file.txt -exec 'echo' '{}  {}' '; '
18  * find: missing argument to `-exec'
19  * # find file.txt -exec 'echo {}' '{}  {}' ';' junk
20  * find: paths must precede expression
21  * # find file.txt -exec 'echo {}' '{}  {}' ';' junk ';'
22  * find: paths must precede expression
23  * # find file.txt -exec 'echo' '{}  {}' ';'
24  * file.txt  file.txt
25  * (strace: execve("/bin/echo", ["echo", "file.txt  file.txt"], [ 30 vars ]))
26  * # find file.txt -exec 'echo' '{}  {}' ';' -print -exec pwd ';'
27  * file.txt  file.txt
28  * file.txt
29  * /tmp
30  * # find -name '*.c' -o -name '*.h'
31  * [shows files, *.c and *.h intermixed]
32  * # find file.txt -name '*f*' -o -name '*t*'
33  * file.txt
34  * # find file.txt -name '*z*' -o -name '*t*'
35  * file.txt
36  * # find file.txt -name '*f*' -o -name '*z*'
37  * file.txt
38  *
39  * # find t z -name '*t*' -print -o -name '*z*'
40  * t
41  * # find t z t z -name '*t*' -o -name '*z*' -print
42  * z
43  * z
44  * # find t z t z '(' -name '*t*' -o -name '*z*' ')' -o -print
45  * (no output)
46  */
47
48 #include <fnmatch.h>
49 #include "busybox.h"
50
51 USE_FEATURE_FIND_XDEV(static dev_t *xdev_dev;)
52 USE_FEATURE_FIND_XDEV(static int xdev_count;)
53
54 typedef int (*action_fp)(const char *fileName, struct stat *statbuf, void *);
55
56 typedef struct {
57         action_fp f;
58 } action;
59 #define ACTS(name, arg...) typedef struct { action a; arg; } action_##name;
60 #define ACTF(name)         static int func_##name(const char *fileName, struct stat *statbuf, action_##name* ap)
61                         ACTS(print)
62                         ACTS(name,  const char *pattern;)
63 USE_FEATURE_FIND_PRINT0(ACTS(print0))
64 USE_FEATURE_FIND_TYPE(  ACTS(type,  int type_mask;))
65 USE_FEATURE_FIND_PERM(  ACTS(perm,  char perm_char; mode_t perm_mask;))
66 USE_FEATURE_FIND_MTIME( ACTS(mtime, char mtime_char; unsigned mtime_days;))
67 USE_FEATURE_FIND_MMIN(  ACTS(mmin,  char mmin_char; unsigned mmin_mins;))
68 USE_FEATURE_FIND_NEWER( ACTS(newer, time_t newer_mtime;))
69 USE_FEATURE_FIND_INUM(  ACTS(inum,  ino_t inode_num;))
70 USE_FEATURE_FIND_EXEC(  ACTS(exec,  char **exec_argv; int *subst_count; int exec_argc;))
71 USE_DESKTOP(            ACTS(paren, action ***subexpr;))
72 USE_DESKTOP(            ACTS(size,  off_t size;))
73 USE_DESKTOP(            ACTS(prune))
74
75 static action ***actions;
76 static int need_print = 1;
77
78
79 #if ENABLE_FEATURE_FIND_EXEC
80 static int count_subst(const char *str)
81 {
82         int count = 0;
83         while ((str = strstr(str, "{}"))) {
84                 count++;
85                 str++;
86         }
87         return count;
88 }
89
90
91 static char* subst(const char *src, int count, const char* filename)
92 {
93         char *buf, *dst, *end;
94         int flen = strlen(filename);
95         /* we replace each '{}' with filename: growth by strlen-2 */
96         buf = dst = xmalloc(strlen(src) + count*(flen-2) + 1);
97         while ((end = strstr(src, "{}"))) {
98                 memcpy(dst, src, end - src);
99                 dst += end - src;
100                 src = end + 2;
101                 memcpy(dst, filename, flen);
102                 dst += flen;
103         }
104         strcpy(dst, src);
105         return buf;
106 }
107 #endif
108
109
110 static int exec_actions(action ***appp, const char *fileName, struct stat *statbuf)
111 {
112         int cur_group;
113         int cur_action;
114         int rc = TRUE;
115         action **app, *ap;
116
117         cur_group = -1;
118         while ((app = appp[++cur_group])) {
119                 cur_action = -1;
120                 do {
121                         ap = app[++cur_action];
122                 } while (ap && (rc = ap->f(fileName, statbuf, ap)));
123                 if (!ap) {
124                         /* all actions in group were successful */
125                         break;
126                 }
127         }
128         return rc;
129 }
130
131
132 ACTF(name)
133 {
134         const char *tmp = strrchr(fileName, '/');
135         if (tmp == NULL)
136                 tmp = fileName;
137         else
138                 tmp++;
139         return fnmatch(ap->pattern, tmp, FNM_PERIOD) == 0;
140 }
141 #if ENABLE_FEATURE_FIND_TYPE
142 ACTF(type)
143 {
144         return ((statbuf->st_mode & S_IFMT) == ap->type_mask);
145 }
146 #endif
147 #if ENABLE_FEATURE_FIND_PERM
148 ACTF(perm)
149 {
150         /* -perm +mode: at least one of perm_mask bits are set */
151         if (ap->perm_char == '+')
152                 return (statbuf->st_mode & ap->perm_mask) != 0;
153         /* -perm -mode: all of perm_mask are set */
154         if (ap->perm_char == '-')
155                 return (statbuf->st_mode & ap->perm_mask) == ap->perm_mask;
156         /* -perm mode: file mode must match perm_mask */
157         return (statbuf->st_mode & 07777) == ap->perm_mask;
158 }
159 #endif
160 #if ENABLE_FEATURE_FIND_MTIME
161 ACTF(mtime)
162 {
163         time_t file_age = time(NULL) - statbuf->st_mtime;
164         time_t mtime_secs = ap->mtime_days * 24*60*60;
165         if (ap->mtime_char == '+')
166                 return file_age >= mtime_secs + 24*60*60;
167         if (ap->mtime_char == '-')
168                 return file_age < mtime_secs;
169         /* just numeric mtime */
170         return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
171 }
172 #endif
173 #if ENABLE_FEATURE_FIND_MMIN
174 ACTF(mmin)
175 {
176         time_t file_age = time(NULL) - statbuf->st_mtime;
177         time_t mmin_secs = ap->mmin_mins * 60;
178         if (ap->mmin_char == '+')
179                 return file_age >= mmin_secs + 60;
180         if (ap->mmin_char == '-')
181                 return file_age < mmin_secs;
182         /* just numeric mmin */
183         return file_age >= mmin_secs && file_age < (mmin_secs + 60);
184 }
185 #endif
186 #if ENABLE_FEATURE_FIND_NEWER
187 ACTF(newer)
188 {
189         return (ap->newer_mtime < statbuf->st_mtime);
190 }
191 #endif
192 #if ENABLE_FEATURE_FIND_INUM
193 ACTF(inum)
194 {
195         return (statbuf->st_ino == ap->inode_num);
196 }
197 #endif
198 #if ENABLE_FEATURE_FIND_EXEC
199 ACTF(exec)
200 {
201         int i, rc;
202         char *argv[ap->exec_argc+1];
203         for (i = 0; i < ap->exec_argc; i++)
204                 argv[i] = subst(ap->exec_argv[i], ap->subst_count[i], fileName);
205         argv[i] = NULL; /* terminate the list */
206         rc = wait4pid(spawn(argv));
207         if (rc)
208                 bb_perror_msg("%s", argv[0]);
209         for (i = 0; i < ap->exec_argc; i++)
210                 free(argv[i]);
211         return rc == 0; /* return 1 if success */
212 }
213 #endif
214
215 #if ENABLE_FEATURE_FIND_PRINT0
216 ACTF(print0)
217 {
218         printf("%s%c", fileName, '\0');
219         return TRUE;
220 }
221 #endif
222
223 ACTF(print)
224 {
225         puts(fileName);
226         return TRUE;
227 }
228
229 #if ENABLE_DESKTOP
230 ACTF(paren)
231 {
232         return exec_actions(ap->subexpr, fileName, statbuf);
233 }
234
235 /*
236  * -prune: if -depth is not given, return true and do not descend
237  * current dir; if -depth is given, return false with no effect.
238  * Example:
239  * find dir -name 'asm-*' -prune -o -name '*.[chS]' -print
240  */
241 ACTF(prune)
242 {
243         return SKIP;
244 }
245
246 ACTF(size)
247 {
248         return statbuf->st_size == ap->size;
249 }
250 #endif
251
252
253 static int fileAction(const char *fileName, struct stat *statbuf, void* junk, int depth)
254 {
255         int rc;
256 #ifdef CONFIG_FEATURE_FIND_XDEV
257         if (S_ISDIR(statbuf->st_mode) && xdev_count) {
258                 int i;
259                 for (i = 0; i < xdev_count; i++) {
260                         if (xdev_dev[i] != statbuf->st_dev)
261                                 return SKIP;
262                 }
263         }
264 #endif
265         rc = exec_actions(actions, fileName, statbuf);
266         /* Had no explicit -print[0] or -exec? then print */
267         if (rc && need_print)
268                 puts(fileName);
269         /* Cannot return 0: our caller, recursive_action(),
270          * will perror() and skip dirs (if called on dir) */
271         return rc == 0 ? TRUE : rc;
272 }
273
274
275 #if ENABLE_FEATURE_FIND_TYPE
276 static int find_type(const char *type)
277 {
278         int mask = 0;
279
280         switch (type[0]) {
281         case 'b':
282                 mask = S_IFBLK;
283                 break;
284         case 'c':
285                 mask = S_IFCHR;
286                 break;
287         case 'd':
288                 mask = S_IFDIR;
289                 break;
290         case 'p':
291                 mask = S_IFIFO;
292                 break;
293         case 'f':
294                 mask = S_IFREG;
295                 break;
296         case 'l':
297                 mask = S_IFLNK;
298                 break;
299         case 's':
300                 mask = S_IFSOCK;
301                 break;
302         }
303
304         if (mask == 0 || type[1] != '\0')
305                 bb_error_msg_and_die(bb_msg_invalid_arg, type, "-type");
306
307         return mask;
308 }
309 #endif
310
311 static const char* plus_minus_num(const char* str)
312 {
313         if (*str == '-' || *str == '+')
314                 str++;
315         return str;
316 }
317
318 static action*** parse_params(char **argv)
319 {
320         action*** appp;
321         int cur_group = 0;
322         int cur_action = 0;
323
324         action* alloc_action(int sizeof_struct, action_fp f)
325         {
326                 action *ap;
327                 appp[cur_group] = xrealloc(appp[cur_group], (cur_action+2) * sizeof(*appp));
328                 appp[cur_group][cur_action++] = ap = xmalloc(sizeof_struct);
329                 appp[cur_group][cur_action] = NULL;
330                 ap->f = f;
331                 return ap;
332         }
333 #define ALLOC_ACTION(name) (action_##name*)alloc_action(sizeof(action_##name), (action_fp) func_##name)
334
335         appp = xzalloc(2 * sizeof(*appp)); /* appp[0],[1] == NULL */
336
337 // Actions have side effects and return a true or false value
338 // We implement: -print, -print0, -exec
339
340 // The rest are tests.
341
342 // Tests and actions are grouped by operators
343 // ( expr )              Force precedence
344 // ! expr                True if expr is false
345 // -not expr             Same as ! expr
346 // expr1 [-a[nd]] expr2  And; expr2 is not evaluated if expr1 is false
347 // expr1 -o[r] expr2     Or; expr2 is not evaluated if expr1 is true
348 // expr1 , expr2         List; both expr1 and expr2 are always evaluated
349 // We implement: (), -a, -o
350
351         while (*argv) {
352                 const char *arg = argv[0];
353                 const char *arg1 = argv[1];
354         /* --- Operators --- */
355                 if (strcmp(arg, "-a") == 0
356                     USE_DESKTOP(|| strcmp(arg, "-and") == 0)
357                 ) {
358                         /* no special handling required */
359                 }
360                 else if (strcmp(arg, "-o") == 0
361                          USE_DESKTOP(|| strcmp(arg, "-or") == 0)
362                 ) {
363                         /* start new OR group */
364                         cur_group++;
365                         appp = xrealloc(appp, (cur_group+2) * sizeof(*appp));
366                         appp[cur_group] = NULL;
367                         appp[cur_group+1] = NULL;
368                         cur_action = 0;
369                 }
370
371         /* --- Tests and actions --- */
372                 else if (strcmp(arg, "-print") == 0) {
373                         need_print = 0;
374                         (void) ALLOC_ACTION(print);
375                 }
376 #if ENABLE_FEATURE_FIND_PRINT0
377                 else if (strcmp(arg, "-print0") == 0) {
378                         need_print = 0;
379                         (void) ALLOC_ACTION(print0);
380                 }
381 #endif
382                 else if (strcmp(arg, "-name") == 0) {
383                         action_name *ap;
384                         if (!*++argv)
385                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
386                         ap = ALLOC_ACTION(name);
387                         ap->pattern = arg1;
388                 }
389 #if ENABLE_FEATURE_FIND_TYPE
390                 else if (strcmp(arg, "-type") == 0) {
391                         action_type *ap;
392                         if (!*++argv)
393                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
394                         ap = ALLOC_ACTION(type);
395                         ap->type_mask = find_type(arg1);
396                 }
397 #endif
398 #if ENABLE_FEATURE_FIND_PERM
399 /* TODO:
400  * -perm mode   File's permission bits are exactly mode (octal or symbolic).
401  *              Symbolic modes use mode 0 as a point of departure.
402  * -perm -mode  All of the permission bits mode are set for the file.
403  * -perm +mode  Any of the permission bits mode are set for the file.
404  */
405                 else if (strcmp(arg, "-perm") == 0) {
406                         action_perm *ap;
407                         if (!*++argv)
408                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
409                         ap = ALLOC_ACTION(perm);
410                         ap->perm_char = arg1[0];
411                         arg1 = plus_minus_num(arg1);
412                         ap->perm_mask = 0;
413                         if (!bb_parse_mode(arg1, &ap->perm_mask))
414                                 bb_error_msg_and_die("invalid mode: %s", arg1);
415                 }
416 #endif
417 #if ENABLE_FEATURE_FIND_MTIME
418                 else if (strcmp(arg, "-mtime") == 0) {
419                         action_mtime *ap;
420                         if (!*++argv)
421                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
422                         ap = ALLOC_ACTION(mtime);
423                         ap->mtime_char = arg1[0];
424                         ap->mtime_days = xatoul(plus_minus_num(arg1));
425                 }
426 #endif
427 #if ENABLE_FEATURE_FIND_MMIN
428                 else if (strcmp(arg, "-mmin") == 0) {
429                         action_mmin *ap;
430                         if (!*++argv)
431                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
432                         ap = ALLOC_ACTION(mmin);
433                         ap->mmin_char = arg1[0];
434                         ap->mmin_mins = xatoul(plus_minus_num(arg1));
435                 }
436 #endif
437 #if ENABLE_FEATURE_FIND_NEWER
438                 else if (strcmp(arg, "-newer") == 0) {
439                         action_newer *ap;
440                         struct stat stat_newer;
441                         if (!*++argv)
442                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
443                         xstat(arg1, &stat_newer);
444                         ap = ALLOC_ACTION(newer);
445                         ap->newer_mtime = stat_newer.st_mtime;
446                 }
447 #endif
448 #if ENABLE_FEATURE_FIND_INUM
449                 else if (strcmp(arg, "-inum") == 0) {
450                         action_inum *ap;
451                         if (!*++argv)
452                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
453                         ap = ALLOC_ACTION(inum);
454                         ap->inode_num = xatoul(arg1);
455                 }
456 #endif
457 #if ENABLE_FEATURE_FIND_EXEC
458                 else if (strcmp(arg, "-exec") == 0) {
459                         int i;
460                         action_exec *ap;
461                         need_print = 0;
462                         ap = ALLOC_ACTION(exec);
463                         ap->exec_argv = ++argv; /* first arg after -exec */
464                         ap->exec_argc = 0;
465                         while (1) {
466                                 if (!*argv) /* did not see ';' till end */
467                                         bb_error_msg_and_die(bb_msg_requires_arg, arg);
468                                 if (LONE_CHAR(argv[0], ';'))
469                                         break;
470                                 argv++;
471                                 ap->exec_argc++;
472                         }
473                         if (ap->exec_argc == 0)
474                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
475                         ap->subst_count = xmalloc(ap->exec_argc * sizeof(int));
476                         i = ap->exec_argc;
477                         while (i--)
478                                 ap->subst_count[i] = count_subst(ap->exec_argv[i]);
479                 }
480 #endif
481 #if ENABLE_DESKTOP
482                 else if (LONE_CHAR(arg, '(')) {
483                         action_paren *ap;
484                         char **endarg;
485                         int nested = 1;
486
487                         endarg = argv;
488                         while (1) {
489                                 if (!*++endarg)
490                                         bb_error_msg_and_die("unpaired '('");
491                                 if (LONE_CHAR(*endarg, '('))
492                                         nested++;
493                                 else if (LONE_CHAR(*endarg, ')') && !--nested) {
494                                         *endarg = NULL;
495                                         break;
496                                 }
497                         }
498                         ap = ALLOC_ACTION(paren);
499                         ap->subexpr = parse_params(argv + 1);
500                         *endarg = ")"; /* restore NULLed parameter */
501                         argv = endarg;
502                 }
503                 else if (strcmp(arg, "-prune") == 0) {
504                         (void) ALLOC_ACTION(prune);
505                 }
506                 else if (strcmp(arg, "-size") == 0) {
507                         action_size *ap;
508                         if (!*++argv)
509                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
510                         ap = ALLOC_ACTION(size);
511                         ap->size = XATOOFF(arg1);
512                 }
513 #endif
514                 else
515                         bb_show_usage();
516                 argv++;
517         }
518
519         return appp;
520 #undef ALLOC_ACTION
521 }
522
523
524 int find_main(int argc, char **argv)
525 {
526         int dereference = FALSE;
527         char *arg;
528         char **argp;
529         int i, firstopt, status = EXIT_SUCCESS;
530
531         for (firstopt = 1; firstopt < argc; firstopt++) {
532                 if (argv[firstopt][0] == '-')
533                         break;
534 #if ENABLE_DESKTOP
535                 if (LONE_CHAR(argv[firstopt], '('))
536                         break;
537 #endif
538         }
539         if (firstopt == 1) {
540                 argv[0] = ".";
541                 argv--;
542                 firstopt++;
543         }
544
545 // All options always return true. They always take effect,
546 // rather than being processed only when their place in the
547 // expression is reached
548 // We implement: -follow, -xdev
549
550         /* Process options, and replace then with -a */
551         /* (-a will be ignored by recursive parser later) */
552         argp = &argv[firstopt];
553         while ((arg = argp[0])) {
554                 if (strcmp(arg, "-follow") == 0) {
555                         dereference = TRUE;
556                         argp[0] = "-a";
557                 }
558 #if ENABLE_FEATURE_FIND_XDEV
559                 else if (strcmp(arg, "-xdev") == 0) {
560                         struct stat stbuf;
561                         if (!xdev_count) {
562                                 xdev_count = firstopt - 1;
563                                 xdev_dev = xmalloc(xdev_count * sizeof(dev_t));
564                                 for (i = 1; i < firstopt; i++) {
565                                         /* not xstat(): shouldn't bomb out on
566                                          * "find not_exist exist -xdev" */
567                                         if (stat(argv[i], &stbuf))
568                                                 stbuf.st_dev = -1L;
569                                         xdev_dev[i-1] = stbuf.st_dev;
570                                 }
571                         }
572                         argp[0] = "-a";
573                 }
574 #endif
575                 argp++;
576         }
577
578         actions = parse_params(&argv[firstopt]);
579
580         for (i = 1; i < firstopt; i++) {
581                 if (!recursive_action(argv[i],
582                                 TRUE,           // recurse
583                                 dereference,    // follow links
584                                 FALSE,          // depth first
585                                 fileAction,     // file action
586                                 fileAction,     // dir action
587                                 NULL,           // user data
588                                 0))             // depth
589                         status = EXIT_FAILURE;
590         }
591         return status;
592 }