1 /* vi: set sw=4 ts=4: */
3 * Mini find implementation for busybox
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Reworked by David Douthitt <n9ubh@callsign.net> and
8 * Matt Kraai <kraai@alumni.carnegiemellon.edu>.
10 * Licensed under the GPL version 2, see the file LICENSE in this tarball.
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' '{} {}' ';'
25 * (strace: execve("/bin/echo", ["echo", "file.txt file.txt"], [ 30 vars ]))
26 * # find file.txt -exec 'echo' '{} {}' ';' -print -exec pwd ';'
30 * # find -name '*.c' -o -name '*.h'
31 * [shows files, *.c and *.h intermixed]
32 * # find file.txt -name '*f*' -o -name '*t*'
34 * # find file.txt -name '*z*' -o -name '*t*'
36 * # find file.txt -name '*f*' -o -name '*z*'
39 * # find t z -name '*t*' -print -o -name '*z*'
41 * # find t z t z -name '*t*' -o -name '*z*' -print
44 * # find t z t z '(' -name '*t*' -o -name '*z*' ')' -o -print
51 /* This is a NOEXEC applet. Be very careful! */
54 USE_FEATURE_FIND_XDEV(static dev_t *xdev_dev;)
55 USE_FEATURE_FIND_XDEV(static int xdev_count;)
57 typedef int (*action_fp)(const char *fileName, struct stat *statbuf, void *);
61 #if ENABLE_FEATURE_FIND_NOT
65 #define ACTS(name, arg...) typedef struct { action a; arg; } action_##name;
66 #define ACTF(name) static int func_##name(const char *fileName, struct stat *statbuf, action_##name* ap)
68 ACTS(name, const char *pattern;)
69 USE_FEATURE_FIND_PRINT0(ACTS(print0))
70 USE_FEATURE_FIND_TYPE( ACTS(type, int type_mask;))
71 USE_FEATURE_FIND_PERM( ACTS(perm, char perm_char; mode_t perm_mask;))
72 USE_FEATURE_FIND_MTIME( ACTS(mtime, char mtime_char; unsigned mtime_days;))
73 USE_FEATURE_FIND_MMIN( ACTS(mmin, char mmin_char; unsigned mmin_mins;))
74 USE_FEATURE_FIND_NEWER( ACTS(newer, time_t newer_mtime;))
75 USE_FEATURE_FIND_INUM( ACTS(inum, ino_t inode_num;))
76 USE_FEATURE_FIND_EXEC( ACTS(exec, char **exec_argv; unsigned *subst_count; int exec_argc;))
77 USE_FEATURE_FIND_USER( ACTS(user, uid_t uid;))
78 USE_FEATURE_FIND_GROUP( ACTS(group, gid_t gid;))
79 USE_FEATURE_FIND_PAREN( ACTS(paren, action ***subexpr;))
80 USE_FEATURE_FIND_SIZE( ACTS(size, off_t size;))
81 USE_FEATURE_FIND_PRUNE( ACTS(prune))
82 USE_FEATURE_FIND_DELETE(ACTS(delete))
83 USE_FEATURE_FIND_PATH( ACTS(path, const char *pattern;))
85 static action ***actions;
86 static bool need_print = 1;
87 static int recurse_flags = ACTION_RECURSE;
89 #if ENABLE_FEATURE_FIND_EXEC
90 static unsigned count_subst(const char *str)
93 while ((str = strstr(str, "{}"))) {
101 static char* subst(const char *src, unsigned count, const char* filename)
103 char *buf, *dst, *end;
104 size_t flen = strlen(filename);
105 /* we replace each '{}' with filename: growth by strlen-2 */
106 buf = dst = xmalloc(strlen(src) + count*(flen-2) + 1);
107 while ((end = strstr(src, "{}"))) {
108 memcpy(dst, src, end - src);
111 memcpy(dst, filename, flen);
119 /* Return values of ACTFs ('action functions') are a bit mask:
120 * bit 1=1: prune (use SKIP constant for setting it)
121 * bit 0=1: matched successfully (TRUE)
124 static int exec_actions(action ***appp, const char *fileName, struct stat *statbuf)
131 /* "action group" is a set of actions ANDed together.
132 * groups are ORed together.
133 * We simply evaluate each group until we find one in which all actions
136 /* -prune is special: if it is encountered, then we won't
137 * descend into current directory. It doesn't matter whether
138 * action group (in which -prune sits) will succeed or not:
139 * find * -prune -name 'f*' -o -name 'm*' -- prunes every dir
140 * find * -name 'f*' -o -prune -name 'm*' -- prunes all dirs
141 * not starting with 'f' */
143 /* We invert TRUE bit (bit 0). Now 1 there means 'failure'.
144 * and bitwise OR in "rc |= TRUE ^ ap->f()" will:
145 * (1) make SKIP (-prune) bit stick; and (2) detect 'failure'.
146 * On return, bit is restored. */
149 while ((app = appp[++cur_group])) {
150 rc &= ~TRUE; /* 'success' so far, clear TRUE bit */
153 ap = app[++cur_action];
154 if (!ap) /* all actions in group were successful */
155 return rc ^ TRUE; /* restore TRUE bit */
156 rc |= TRUE ^ ap->f(fileName, statbuf, ap);
157 #if ENABLE_FEATURE_FIND_NOT
158 if (ap->invert) rc ^= TRUE;
160 if (rc & TRUE) /* current group failed, try next */
164 return rc ^ TRUE; /* restore TRUE bit */
170 const char *tmp = strrchr(fileName, '/');
175 if (!*tmp) { /* "foo/bar/". Oh no... go back to 'b' */
177 while (tmp != fileName && *--tmp != '/')
183 return fnmatch(ap->pattern, tmp, FNM_PERIOD) == 0;
185 #if ENABLE_FEATURE_FIND_TYPE
188 return ((statbuf->st_mode & S_IFMT) == ap->type_mask);
191 #if ENABLE_FEATURE_FIND_PERM
194 /* -perm +mode: at least one of perm_mask bits are set */
195 if (ap->perm_char == '+')
196 return (statbuf->st_mode & ap->perm_mask) != 0;
197 /* -perm -mode: all of perm_mask are set */
198 if (ap->perm_char == '-')
199 return (statbuf->st_mode & ap->perm_mask) == ap->perm_mask;
200 /* -perm mode: file mode must match perm_mask */
201 return (statbuf->st_mode & 07777) == ap->perm_mask;
204 #if ENABLE_FEATURE_FIND_MTIME
207 time_t file_age = time(NULL) - statbuf->st_mtime;
208 time_t mtime_secs = ap->mtime_days * 24*60*60;
209 if (ap->mtime_char == '+')
210 return file_age >= mtime_secs + 24*60*60;
211 if (ap->mtime_char == '-')
212 return file_age < mtime_secs;
213 /* just numeric mtime */
214 return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
217 #if ENABLE_FEATURE_FIND_MMIN
220 time_t file_age = time(NULL) - statbuf->st_mtime;
221 time_t mmin_secs = ap->mmin_mins * 60;
222 if (ap->mmin_char == '+')
223 return file_age >= mmin_secs + 60;
224 if (ap->mmin_char == '-')
225 return file_age < mmin_secs;
226 /* just numeric mmin */
227 return file_age >= mmin_secs && file_age < (mmin_secs + 60);
230 #if ENABLE_FEATURE_FIND_NEWER
233 return (ap->newer_mtime < statbuf->st_mtime);
236 #if ENABLE_FEATURE_FIND_INUM
239 return (statbuf->st_ino == ap->inode_num);
242 #if ENABLE_FEATURE_FIND_EXEC
246 char *argv[ap->exec_argc + 1];
247 for (i = 0; i < ap->exec_argc; i++)
248 argv[i] = subst(ap->exec_argv[i], ap->subst_count[i], fileName);
249 argv[i] = NULL; /* terminate the list */
251 rc = spawn_and_wait(argv);
253 bb_perror_msg("%s", argv[0]);
258 return rc == 0; /* return 1 if exitcode 0 */
262 #if ENABLE_FEATURE_FIND_USER
265 return (statbuf->st_uid == ap->uid);
269 #if ENABLE_FEATURE_FIND_GROUP
272 return (statbuf->st_gid == ap->gid);
276 #if ENABLE_FEATURE_FIND_PRINT0
279 printf("%s%c", fileName, '\0');
290 #if ENABLE_FEATURE_FIND_PAREN
293 return exec_actions(ap->subexpr, fileName, statbuf);
297 #if ENABLE_FEATURE_FIND_PRUNE
299 * -prune: if -depth is not given, return true and do not descend
300 * current dir; if -depth is given, return false with no effect.
302 * find dir -name 'asm-*' -prune -o -name '*.[chS]' -print
310 #if ENABLE_FEATURE_FIND_DELETE
314 if (S_ISDIR(statbuf->st_mode)) {
315 rc = rmdir(fileName);
317 rc = unlink(fileName);
320 bb_perror_msg("%s", fileName);
325 #if ENABLE_FEATURE_FIND_PATH
328 return fnmatch(ap->pattern, fileName, 0) == 0;
332 #if ENABLE_FEATURE_FIND_SIZE
335 return statbuf->st_size == ap->size;
340 static int fileAction(const char *fileName, struct stat *statbuf, void* junk, int depth)
343 #if ENABLE_FEATURE_FIND_XDEV
344 if (S_ISDIR(statbuf->st_mode) && xdev_count) {
345 for (i = 0; i < xdev_count; i++) {
346 if (xdev_dev[i] != statbuf->st_dev)
351 i = exec_actions(actions, fileName, statbuf);
352 /* Had no explicit -print[0] or -exec? then print */
353 if ((i & TRUE) && need_print)
355 /* Cannot return 0: our caller, recursive_action(),
356 * will perror() and skip dirs (if called on dir) */
357 return (i & SKIP) ? SKIP : TRUE;
361 #if ENABLE_FEATURE_FIND_TYPE
362 static int find_type(const char *type)
368 else if (*type == 'c')
370 else if (*type == 'd')
372 else if (*type == 'p')
374 else if (*type == 'f')
376 else if (*type == 'l')
378 else if (*type == 's')
381 if (mask == 0 || *(type + 1) != '\0')
382 bb_error_msg_and_die(bb_msg_invalid_arg, type, "-type");
388 #if ENABLE_FEATURE_FIND_PERM || ENABLE_FEATURE_FIND_MTIME \
389 || ENABLE_FEATURE_FIND_MMIN
390 static const char* plus_minus_num(const char* str)
392 if (*str == '-' || *str == '+')
398 static action*** parse_params(char **argv)
403 USE_FEATURE_FIND_NOT( PARM_char_not ,)
405 USE_FEATURE_FIND_PRINT0(PARM_print0 ,)
407 USE_FEATURE_FIND_TYPE( PARM_type ,)
408 USE_FEATURE_FIND_PERM( PARM_perm ,)
409 USE_FEATURE_FIND_MTIME( PARM_mtime ,)
410 USE_FEATURE_FIND_MMIN( PARM_mmin ,)
411 USE_FEATURE_FIND_NEWER( PARM_newer ,)
412 USE_FEATURE_FIND_INUM( PARM_inum ,)
413 USE_FEATURE_FIND_EXEC( PARM_exec ,)
414 USE_FEATURE_FIND_USER( PARM_user ,)
415 USE_FEATURE_FIND_GROUP( PARM_group ,)
416 USE_FEATURE_FIND_DEPTH( PARM_depth ,)
417 USE_FEATURE_FIND_PAREN( PARM_char_brace,)
418 USE_FEATURE_FIND_SIZE( PARM_size ,)
419 USE_FEATURE_FIND_PRUNE( PARM_prune ,)
420 USE_FEATURE_FIND_DELETE(PARM_delete ,)
421 USE_FEATURE_FIND_PATH( PARM_path ,)
425 USE_FEATURE_FIND_NOT( PARM_not ,)
429 static const char *const params[] = {
432 USE_FEATURE_FIND_NOT( "!" ,)
434 USE_FEATURE_FIND_PRINT0("-print0",)
436 USE_FEATURE_FIND_TYPE( "-type" ,)
437 USE_FEATURE_FIND_PERM( "-perm" ,)
438 USE_FEATURE_FIND_MTIME( "-mtime" ,)
439 USE_FEATURE_FIND_MMIN( "-mmin" ,)
440 USE_FEATURE_FIND_NEWER( "-newer" ,)
441 USE_FEATURE_FIND_INUM( "-inum" ,)
442 USE_FEATURE_FIND_EXEC( "-exec" ,)
443 USE_FEATURE_FIND_USER( "-user" ,)
444 USE_FEATURE_FIND_GROUP( "-group" ,)
445 USE_FEATURE_FIND_DEPTH( "-depth" ,)
446 USE_FEATURE_FIND_PAREN( "(" ,)
447 USE_FEATURE_FIND_SIZE( "-size" ,)
448 USE_FEATURE_FIND_PRUNE( "-prune" ,)
449 USE_FEATURE_FIND_DELETE("-delete",)
450 USE_FEATURE_FIND_PATH( "-path" ,)
454 USE_FEATURE_FIND_NOT( "-not" ,)
460 unsigned cur_group = 0;
461 unsigned cur_action = 0;
462 USE_FEATURE_FIND_NOT( bool invert_flag = 0; )
464 /* 'static' doesn't work here! (gcc 4.1.2) */
465 action* alloc_action(int sizeof_struct, action_fp f)
468 appp[cur_group] = xrealloc(appp[cur_group], (cur_action+2) * sizeof(*appp));
469 appp[cur_group][cur_action++] = ap = xmalloc(sizeof_struct);
470 appp[cur_group][cur_action] = NULL;
472 USE_FEATURE_FIND_NOT( ap->invert = invert_flag; )
473 USE_FEATURE_FIND_NOT( invert_flag = 0; )
477 #define ALLOC_ACTION(name) (action_##name*)alloc_action(sizeof(action_##name), (action_fp) func_##name)
479 appp = xzalloc(2 * sizeof(appp[0])); /* appp[0],[1] == NULL */
481 /* Actions have side effects and return a true or false value
482 * We implement: -print, -print0, -exec
484 * The rest are tests.
486 * Tests and actions are grouped by operators
487 * ( expr ) Force precedence
488 * ! expr True if expr is false
489 * -not expr Same as ! expr
490 * expr1 [-a[nd]] expr2 And; expr2 is not evaluated if expr1 is false
491 * expr1 -o[r] expr2 Or; expr2 is not evaluated if expr1 is true
492 * expr1 , expr2 List; both expr1 and expr2 are always evaluated
493 * We implement: (), -a, -o
496 const char *arg = argv[0];
497 const char *arg1 = argv[1];
498 int parm = index_in_str_array(params, arg);
499 /* --- Operators --- */
500 if (parm == PARM_a USE_DESKTOP(|| parm == PARM_and)) {
501 /* no further special handling required */
503 else if (parm == PARM_o USE_DESKTOP(|| parm == PARM_or)) {
504 /* start new OR group */
506 appp = xrealloc(appp, (cur_group+2) * sizeof(*appp));
507 /*appp[cur_group] = NULL; - already NULL */
508 appp[cur_group+1] = NULL;
511 #if ENABLE_FEATURE_FIND_NOT
512 else if (parm == PARM_char_not USE_DESKTOP(|| parm == PARM_not)) {
513 /* also handles "find ! ! -name 'foo*'" */
518 /* --- Tests and actions --- */
519 else if (parm == PARM_print) {
521 /* GNU find ignores '!' here: "find ! -print" */
522 USE_FEATURE_FIND_NOT( invert_flag = 0; )
523 (void) ALLOC_ACTION(print);
525 #if ENABLE_FEATURE_FIND_PRINT0
526 else if (parm == PARM_print0) {
528 USE_FEATURE_FIND_NOT( invert_flag = 0; )
529 (void) ALLOC_ACTION(print0);
532 else if (parm == PARM_name) {
535 bb_error_msg_and_die(bb_msg_requires_arg, arg);
536 ap = ALLOC_ACTION(name);
539 #if ENABLE_FEATURE_FIND_TYPE
540 else if (parm == PARM_type) {
543 bb_error_msg_and_die(bb_msg_requires_arg, arg);
544 ap = ALLOC_ACTION(type);
545 ap->type_mask = find_type(arg1);
548 #if ENABLE_FEATURE_FIND_PERM
549 /* -perm mode File's permission bits are exactly mode (octal or symbolic).
550 * Symbolic modes use mode 0 as a point of departure.
551 * -perm -mode All of the permission bits mode are set for the file.
552 * -perm +mode Any of the permission bits mode are set for the file.
554 else if (parm == PARM_perm) {
557 bb_error_msg_and_die(bb_msg_requires_arg, arg);
558 ap = ALLOC_ACTION(perm);
559 ap->perm_char = arg1[0];
560 arg1 = plus_minus_num(arg1);
562 if (!bb_parse_mode(arg1, &ap->perm_mask))
563 bb_error_msg_and_die("invalid mode: %s", arg1);
566 #if ENABLE_FEATURE_FIND_MTIME
567 else if (parm == PARM_mtime) {
570 bb_error_msg_and_die(bb_msg_requires_arg, arg);
571 ap = ALLOC_ACTION(mtime);
572 ap->mtime_char = arg1[0];
573 ap->mtime_days = xatoul(plus_minus_num(arg1));
576 #if ENABLE_FEATURE_FIND_MMIN
577 else if (parm == PARM_mmin) {
580 bb_error_msg_and_die(bb_msg_requires_arg, arg);
581 ap = ALLOC_ACTION(mmin);
582 ap->mmin_char = arg1[0];
583 ap->mmin_mins = xatoul(plus_minus_num(arg1));
586 #if ENABLE_FEATURE_FIND_NEWER
587 else if (parm == PARM_newer) {
589 struct stat stat_newer;
591 bb_error_msg_and_die(bb_msg_requires_arg, arg);
592 xstat(arg1, &stat_newer);
593 ap = ALLOC_ACTION(newer);
594 ap->newer_mtime = stat_newer.st_mtime;
597 #if ENABLE_FEATURE_FIND_INUM
598 else if (parm == PARM_inum) {
601 bb_error_msg_and_die(bb_msg_requires_arg, arg);
602 ap = ALLOC_ACTION(inum);
603 ap->inode_num = xatoul(arg1);
606 #if ENABLE_FEATURE_FIND_EXEC
607 else if (parm == PARM_exec) {
611 USE_FEATURE_FIND_NOT( invert_flag = 0; )
612 ap = ALLOC_ACTION(exec);
613 ap->exec_argv = ++argv; /* first arg after -exec */
616 if (!*argv) /* did not see ';' until end */
617 bb_error_msg_and_die(bb_msg_requires_arg, arg);
618 if (LONE_CHAR(argv[0], ';'))
623 if (ap->exec_argc == 0)
624 bb_error_msg_and_die(bb_msg_requires_arg, arg);
625 ap->subst_count = xmalloc(ap->exec_argc * sizeof(int));
628 ap->subst_count[i] = count_subst(ap->exec_argv[i]);
631 #if ENABLE_FEATURE_FIND_USER
632 else if (parm == PARM_user) {
635 bb_error_msg_and_die(bb_msg_requires_arg, arg);
636 ap = ALLOC_ACTION(user);
637 ap->uid = bb_strtou(arg1, NULL, 10);
639 ap->uid = xuname2uid(arg1);
642 #if ENABLE_FEATURE_FIND_GROUP
643 else if (parm == PARM_group) {
646 bb_error_msg_and_die(bb_msg_requires_arg, arg);
647 ap = ALLOC_ACTION(group);
648 ap->gid = bb_strtou(arg1, NULL, 10);
650 ap->gid = xgroup2gid(arg1);
653 #if ENABLE_FEATURE_FIND_DEPTH
654 else if (parm == PARM_depth) {
655 recurse_flags |= ACTION_DEPTHFIRST;
658 #if ENABLE_FEATURE_FIND_PAREN
659 else if (parm == PARM_char_brace) {
667 bb_error_msg_and_die("unpaired '('");
668 if (LONE_CHAR(*endarg, '('))
670 else if (LONE_CHAR(*endarg, ')') && !--nested) {
675 ap = ALLOC_ACTION(paren);
676 ap->subexpr = parse_params(argv + 1);
677 *endarg = (char*) ")"; /* restore NULLed parameter */
681 #if ENABLE_FEATURE_FIND_PRUNE
682 else if (parm == PARM_prune) {
683 USE_FEATURE_FIND_NOT( invert_flag = 0; )
684 (void) ALLOC_ACTION(prune);
687 #if ENABLE_FEATURE_FIND_DELETE
688 else if (parm == PARM_delete) {
690 recurse_flags |= ACTION_DEPTHFIRST;
691 (void) ALLOC_ACTION(delete);
694 #if ENABLE_FEATURE_FIND_PATH
695 else if (parm == PARM_path) {
698 bb_error_msg_and_die(bb_msg_requires_arg, arg);
699 ap = ALLOC_ACTION(path);
703 #if ENABLE_FEATURE_FIND_SIZE
704 else if (parm == PARM_size) {
707 bb_error_msg_and_die(bb_msg_requires_arg, arg);
708 ap = ALLOC_ACTION(size);
709 ap->size = XATOOFF(arg1);
721 int find_main(int argc, char **argv);
722 int find_main(int argc, char **argv)
724 static const char * const options[] = {
726 USE_FEATURE_FIND_XDEV( "-xdev", )
732 int i, firstopt, status = EXIT_SUCCESS;
734 for (firstopt = 1; firstopt < argc; firstopt++) {
735 if (argv[firstopt][0] == '-')
737 if (ENABLE_FEATURE_FIND_NOT && LONE_CHAR(argv[firstopt], '!'))
739 #if ENABLE_FEATURE_FIND_PAREN
740 if (LONE_CHAR(argv[firstopt], '('))
745 argv[0] = (char*)".";
750 /* All options always return true. They always take effect
751 * rather than being processed only when their place in the
752 * expression is reached.
753 * We implement: -follow, -xdev
755 /* Process options, and replace then with -a */
756 /* (-a will be ignored by recursive parser later) */
757 argp = &argv[firstopt];
758 while ((arg = argp[0])) {
759 i = index_in_str_array(options, arg);
760 if (i == 0) { /* -follow */
761 recurse_flags |= ACTION_FOLLOWLINKS;
762 argp[0] = (char*)"-a";
764 #if ENABLE_FEATURE_FIND_XDEV
765 else if (i == 1) { /* -xdev */
768 xdev_count = firstopt - 1;
769 xdev_dev = xmalloc(xdev_count * sizeof(dev_t));
770 for (i = 1; i < firstopt; i++) {
771 /* not xstat(): shouldn't bomb out on
772 * "find not_exist exist -xdev" */
773 if (stat(argv[i], &stbuf))
775 xdev_dev[i-1] = stbuf.st_dev;
778 argp[0] = (char*)"-a";
784 actions = parse_params(&argv[firstopt]);
786 for (i = 1; i < firstopt; i++) {
787 if (!recursive_action(argv[i],
788 recurse_flags, /* flags */
789 fileAction, /* file action */
790 fileAction, /* dir action */
791 NULL, /* user data */
793 status = EXIT_FAILURE;