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 GPLv2, see file LICENSE in this source tree.
14 * # find file.txt -exec 'echo {}' '{} {}' ';'
15 * find: echo file.txt: No such file or directory
16 * # find file.txt -exec 'echo' '{} {}' '; '
17 * find: missing argument to '-exec'
18 * # find file.txt -exec 'echo {}' '{} {}' ';' junk
19 * find: paths must precede expression
20 * # find file.txt -exec 'echo {}' '{} {}' ';' junk ';'
21 * find: paths must precede expression
22 * # find file.txt -exec 'echo' '{} {}' ';'
24 * (strace: execve("/bin/echo", ["echo", "file.txt file.txt"], [ 30 vars ]))
25 * # find file.txt -exec 'echo' '{} {}' ';' -print -exec pwd ';'
29 * # find -name '*.c' -o -name '*.h'
30 * [shows files, *.c and *.h intermixed]
31 * # find file.txt -name '*f*' -o -name '*t*'
33 * # find file.txt -name '*z*' -o -name '*t*'
35 * # find file.txt -name '*f*' -o -name '*z*'
38 * # find t z -name '*t*' -print -o -name '*z*'
40 * # find t z t z -name '*t*' -o -name '*z*' -print
43 * # find t z t z '(' -name '*t*' -o -name '*z*' ')' -o -print
47 * ./busybox find "$@" | tee /tmp/bb_find
48 * echo ==================
49 * /path/to/gnu/find "$@" | tee /tmp/std_find
50 * echo ==================
51 * diff -u /tmp/std_find /tmp/bb_find && echo Identical
54 //config: bool "find (14 kb)"
57 //config: find is used to search your system to find specified files.
59 //config:config FEATURE_FIND_PRINT0
60 //config: bool "Enable -print0: NUL-terminated output"
62 //config: depends on FIND
64 //config: Causes output names to be separated by a NUL character
65 //config: rather than a newline. This allows names that contain
66 //config: newlines and other whitespace to be more easily
67 //config: interpreted by other programs.
69 //config:config FEATURE_FIND_MTIME
70 //config: bool "Enable -mtime: modified time matching"
72 //config: depends on FIND
74 //config: Allow searching based on the modification time of
75 //config: files, in days.
77 //config:config FEATURE_FIND_MMIN
78 //config: bool "Enable -mmin: modified time matching by minutes"
80 //config: depends on FIND
82 //config: Allow searching based on the modification time of
83 //config: files, in minutes.
85 //config:config FEATURE_FIND_PERM
86 //config: bool "Enable -perm: permissions matching"
88 //config: depends on FIND
90 //config:config FEATURE_FIND_TYPE
91 //config: bool "Enable -type: file type matching (file/dir/link/...)"
93 //config: depends on FIND
95 //config: Enable searching based on file type (file,
96 //config: directory, socket, device, etc.).
98 //config:config FEATURE_FIND_XDEV
99 //config: bool "Enable -xdev: 'stay in filesystem'"
101 //config: depends on FIND
103 //config:config FEATURE_FIND_MAXDEPTH
104 //config: bool "Enable -mindepth N and -maxdepth N"
106 //config: depends on FIND
108 //config:config FEATURE_FIND_NEWER
109 //config: bool "Enable -newer: compare file modification times"
111 //config: depends on FIND
113 //config: Support the 'find -newer' option for finding any files which have
114 //config: modification time that is more recent than the specified FILE.
116 //config:config FEATURE_FIND_INUM
117 //config: bool "Enable -inum: inode number matching"
119 //config: depends on FIND
121 //config:config FEATURE_FIND_EXEC
122 //config: bool "Enable -exec: execute commands"
124 //config: depends on FIND
126 //config: Support the 'find -exec' option for executing commands based upon
127 //config: the files matched.
129 //config:config FEATURE_FIND_EXEC_PLUS
130 //config: bool "Enable -exec ... {} +"
132 //config: depends on FEATURE_FIND_EXEC
134 //config: Support the 'find -exec ... {} +' option for executing commands
135 //config: for all matched files at once.
136 //config: Without this option, -exec + is a synonym for -exec ;
137 //config: (IOW: it works correctly, but without expected speedup)
139 //config:config FEATURE_FIND_USER
140 //config: bool "Enable -user: username/uid matching"
142 //config: depends on FIND
144 //config:config FEATURE_FIND_GROUP
145 //config: bool "Enable -group: group/gid matching"
147 //config: depends on FIND
149 //config:config FEATURE_FIND_NOT
150 //config: bool "Enable the 'not' (!) operator"
152 //config: depends on FIND
154 //config: Support the '!' operator to invert the test results.
155 //config: If 'Enable full-blown desktop' is enabled, then will also support
156 //config: the non-POSIX notation '-not'.
158 //config:config FEATURE_FIND_DEPTH
159 //config: bool "Enable -depth"
161 //config: depends on FIND
163 //config: Process each directory's contents before the directory itself.
165 //config:config FEATURE_FIND_PAREN
166 //config: bool "Enable parens in options"
168 //config: depends on FIND
170 //config: Enable usage of parens '(' to specify logical order of arguments.
172 //config:config FEATURE_FIND_SIZE
173 //config: bool "Enable -size: file size matching"
175 //config: depends on FIND
177 //config:config FEATURE_FIND_PRUNE
178 //config: bool "Enable -prune: exclude subdirectories"
180 //config: depends on FIND
182 //config: If the file is a directory, don't descend into it. Useful for
183 //config: exclusion .svn and CVS directories.
185 //config:config FEATURE_FIND_DELETE
186 //config: bool "Enable -delete: delete files/dirs"
188 //config: depends on FIND && FEATURE_FIND_DEPTH
190 //config: Support the 'find -delete' option for deleting files and directories.
191 //config: WARNING: This option can do much harm if used wrong. Busybox will not
192 //config: try to protect the user from doing stupid things. Use with care.
194 //config:config FEATURE_FIND_PATH
195 //config: bool "Enable -path: match pathname with shell pattern"
197 //config: depends on FIND
199 //config: The -path option matches whole pathname instead of just filename.
201 //config:config FEATURE_FIND_REGEX
202 //config: bool "Enable -regex: match pathname with regex"
204 //config: depends on FIND
206 //config: The -regex option matches whole pathname against regular expression.
208 //config:config FEATURE_FIND_CONTEXT
209 //config: bool "Enable -context: security context matching"
211 //config: depends on FIND && SELINUX
213 //config: Support the 'find -context' option for matching security context.
215 //config:config FEATURE_FIND_LINKS
216 //config: bool "Enable -links: link count matching"
218 //config: depends on FIND
220 //config: Support the 'find -links' option for matching number of links.
222 //applet:IF_FIND(APPLET_NOEXEC(find, find, BB_DIR_USR_BIN, BB_SUID_DROP, find))
224 //kbuild:lib-$(CONFIG_FIND) += find.o
226 //usage:#define find_trivial_usage
227 //usage: "[-HL] [PATH]... [OPTIONS] [ACTIONS]"
228 //usage:#define find_full_usage "\n\n"
229 //usage: "Search for files and perform actions on them.\n"
230 //usage: "First failed action stops processing of current file.\n"
231 //usage: "Defaults: PATH is current directory, action is '-print'\n"
232 //usage: "\n -L,-follow Follow symlinks"
233 //usage: "\n -H ...on command line only"
234 //usage: IF_FEATURE_FIND_XDEV(
235 //usage: "\n -xdev Don't descend directories on other filesystems"
237 //usage: IF_FEATURE_FIND_MAXDEPTH(
238 //usage: "\n -maxdepth N Descend at most N levels. -maxdepth 0 applies"
239 //usage: "\n actions to command line arguments only"
240 //usage: "\n -mindepth N Don't act on first N levels"
242 //usage: IF_FEATURE_FIND_DEPTH(
243 //usage: "\n -depth Act on directory *after* traversing it"
246 //usage: "\nActions:"
247 //usage: IF_FEATURE_FIND_PAREN(
248 //usage: "\n ( ACTIONS ) Group actions for -o / -a"
250 //usage: IF_FEATURE_FIND_NOT(
251 //usage: "\n ! ACT Invert ACT's success/failure"
253 //usage: "\n ACT1 [-a] ACT2 If ACT1 fails, stop, else do ACT2"
254 //usage: "\n ACT1 -o ACT2 If ACT1 succeeds, stop, else do ACT2"
255 //usage: "\n Note: -a has higher priority than -o"
256 //usage: "\n -name PATTERN Match file name (w/o directory name) to PATTERN"
257 //usage: "\n -iname PATTERN Case insensitive -name"
258 //usage: IF_FEATURE_FIND_PATH(
259 //usage: "\n -path PATTERN Match path to PATTERN"
260 //usage: "\n -ipath PATTERN Case insensitive -path"
262 //usage: IF_FEATURE_FIND_REGEX(
263 //usage: "\n -regex PATTERN Match path to regex PATTERN"
265 //usage: IF_FEATURE_FIND_TYPE(
266 //usage: "\n -type X File type is X (one of: f,d,l,b,c,s,p)"
268 //usage: IF_FEATURE_FIND_PERM(
269 //usage: "\n -perm MASK At least one mask bit (+MASK), all bits (-MASK),"
270 //usage: "\n or exactly MASK bits are set in file's mode"
272 //usage: IF_FEATURE_FIND_MTIME(
273 //usage: "\n -mtime DAYS mtime is greater than (+N), less than (-N),"
274 //usage: "\n or exactly N days in the past"
276 //usage: IF_FEATURE_FIND_MMIN(
277 //usage: "\n -mmin MINS mtime is greater than (+N), less than (-N),"
278 //usage: "\n or exactly N minutes in the past"
280 //usage: IF_FEATURE_FIND_NEWER(
281 //usage: "\n -newer FILE mtime is more recent than FILE's"
283 //usage: IF_FEATURE_FIND_INUM(
284 //usage: "\n -inum N File has inode number N"
286 //usage: IF_FEATURE_FIND_USER(
287 //usage: "\n -user NAME/ID File is owned by given user"
289 //usage: IF_FEATURE_FIND_GROUP(
290 //usage: "\n -group NAME/ID File is owned by given group"
292 //usage: IF_FEATURE_FIND_SIZE(
293 //usage: "\n -size N[bck] File size is N (c:bytes,k:kbytes,b:512 bytes(def.))"
294 //usage: "\n +/-N: file size is bigger/smaller than N"
296 //usage: IF_FEATURE_FIND_LINKS(
297 //usage: "\n -links N Number of links is greater than (+N), less than (-N),"
298 //usage: "\n or exactly N"
300 //usage: IF_FEATURE_FIND_CONTEXT(
301 //usage: "\n -context CTX File has specified security context"
303 //usage: IF_FEATURE_FIND_PRUNE(
304 //usage: "\n -prune If current file is directory, don't descend into it"
306 //usage: "\nIf none of the following actions is specified, -print is assumed"
307 //usage: "\n -print Print file name"
308 //usage: IF_FEATURE_FIND_PRINT0(
309 //usage: "\n -print0 Print file name, NUL terminated"
311 //usage: IF_FEATURE_FIND_EXEC(
312 //usage: "\n -exec CMD ARG ; Run CMD with all instances of {} replaced by"
313 //usage: "\n file name. Fails if CMD exits with nonzero"
315 //usage: IF_FEATURE_FIND_EXEC_PLUS(
316 //usage: "\n -exec CMD ARG + Run CMD with {} replaced by list of file names"
318 //usage: IF_FEATURE_FIND_DELETE(
319 //usage: "\n -delete Delete current file/directory. Turns on -depth option"
322 //usage:#define find_example_usage
323 //usage: "$ find / -name passwd\n"
324 //usage: "/etc/passwd\n"
328 #include "common_bufsiz.h"
329 #if ENABLE_FEATURE_FIND_REGEX
334 # define FNM_CASEFOLD 0
338 # define dbg(...) ((void)0)
340 # define dbg(...) bb_error_msg(__VA_ARGS__)
344 /* This is a NOEXEC applet. Be very careful! */
347 typedef int (*action_fp)(const char *fileName, const struct stat *statbuf, void *) FAST_FUNC;
351 #if ENABLE_FEATURE_FIND_NOT
356 #define ACTS(name, ...) typedef struct { action a; __VA_ARGS__ } action_##name;
358 static int FAST_FUNC func_##name(const char *fileName UNUSED_PARAM, \
359 const struct stat *statbuf UNUSED_PARAM, \
360 action_##name* ap UNUSED_PARAM)
363 ACTS(name, const char *pattern; bool iname;)
364 IF_FEATURE_FIND_PATH( ACTS(path, const char *pattern; bool ipath;))
365 IF_FEATURE_FIND_REGEX( ACTS(regex, regex_t compiled_pattern;))
366 IF_FEATURE_FIND_PRINT0( ACTS(print0))
367 IF_FEATURE_FIND_TYPE( ACTS(type, int type_mask;))
368 IF_FEATURE_FIND_PERM( ACTS(perm, char perm_char; mode_t perm_mask;))
369 IF_FEATURE_FIND_MTIME( ACTS(mtime, char mtime_char; unsigned mtime_days;))
370 IF_FEATURE_FIND_MMIN( ACTS(mmin, char mmin_char; unsigned mmin_mins;))
371 IF_FEATURE_FIND_NEWER( ACTS(newer, time_t newer_mtime;))
372 IF_FEATURE_FIND_INUM( ACTS(inum, ino_t inode_num;))
373 IF_FEATURE_FIND_USER( ACTS(user, uid_t uid;))
374 IF_FEATURE_FIND_SIZE( ACTS(size, char size_char; off_t size;))
375 IF_FEATURE_FIND_CONTEXT(ACTS(context, security_context_t context;))
376 IF_FEATURE_FIND_PAREN( ACTS(paren, action ***subexpr;))
377 IF_FEATURE_FIND_PRUNE( ACTS(prune))
378 IF_FEATURE_FIND_DELETE( ACTS(delete))
379 IF_FEATURE_FIND_EXEC( ACTS(exec,
380 char **exec_argv; /* -exec ARGS */
381 unsigned *subst_count;
382 int exec_argc; /* count of ARGS */
383 IF_FEATURE_FIND_EXEC_PLUS(
385 * filelist is NULL if "exec ;"
386 * non-NULL if "exec +"
393 IF_FEATURE_FIND_GROUP( ACTS(group, gid_t gid;))
394 IF_FEATURE_FIND_LINKS( ACTS(links, char links_char; int links_count;))
397 IF_FEATURE_FIND_XDEV(dev_t *xdev_dev;)
398 IF_FEATURE_FIND_XDEV(int xdev_count;)
399 #if ENABLE_FEATURE_FIND_MAXDEPTH
405 recurse_flags_t recurse_flags;
406 IF_FEATURE_FIND_EXEC_PLUS(unsigned max_argv_len;)
408 #define G (*(struct globals*)bb_common_bufsiz1)
409 #define INIT_G() do { \
410 setup_common_bufsiz(); \
411 BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
412 /* we have to zero it out because of NOEXEC */ \
413 memset(&G, 0, sizeof(G)); \
414 IF_FEATURE_FIND_MAXDEPTH(G.minmaxdepth[1] = INT_MAX;) \
415 IF_FEATURE_FIND_EXEC_PLUS(G.max_argv_len = bb_arg_max() - 2048;) \
417 G.recurse_flags = ACTION_RECURSE; \
420 /* Return values of ACTFs ('action functions') are a bit mask:
421 * bit 1=1: prune (use SKIP constant for setting it)
422 * bit 0=1: matched successfully (TRUE)
425 static int exec_actions(action ***appp, const char *fileName, const struct stat *statbuf)
432 /* "action group" is a set of actions ANDed together.
433 * groups are ORed together.
434 * We simply evaluate each group until we find one in which all actions
437 /* -prune is special: if it is encountered, then we won't
438 * descend into current directory. It doesn't matter whether
439 * action group (in which -prune sits) will succeed or not:
440 * find * -prune -name 'f*' -o -name 'm*' -- prunes every dir
441 * find * -name 'f*' -o -prune -name 'm*' -- prunes all dirs
442 * not starting with 'f' */
444 /* We invert TRUE bit (bit 0). Now 1 there means 'failure'.
445 * and bitwise OR in "rc |= TRUE ^ ap->f()" will:
446 * (1) make SKIP (-prune) bit stick; and (2) detect 'failure'.
447 * On return, bit is restored. */
450 while ((app = appp[++cur_group]) != NULL) {
451 rc &= ~TRUE; /* 'success' so far, clear TRUE bit */
454 ap = app[++cur_action];
455 if (!ap) /* all actions in group were successful */
456 return rc ^ TRUE; /* restore TRUE bit */
457 rc |= TRUE ^ ap->f(fileName, statbuf, ap);
458 #if ENABLE_FEATURE_FIND_NOT
459 if (ap->invert) rc ^= TRUE;
461 dbg("grp %d action %d rc:0x%x", cur_group, cur_action, rc);
462 if (rc & TRUE) /* current group failed, try next */
466 dbg("returning:0x%x", rc ^ TRUE);
467 return rc ^ TRUE; /* restore TRUE bit */
471 static char *strcpy_upcase(char *dst, const char *src)
475 unsigned char ch = *src++;
476 if (ch >= 'a' && ch <= 'z')
489 const char *tmp = bb_basename(fileName);
490 /* GNU findutils: find DIR/ -name DIR
491 * prints "DIR/" (DIR// prints "DIR//" etc).
492 * Need to strip trailing "/".
493 * Such names can come only from top-level names, but
494 * we can't do this before recursive_action() call,
495 * since then "find FILE/ -name FILE"
496 * would also work (on non-directories), which is wrong.
498 char *trunc_slash = NULL;
501 /* "foo/bar/[//...]" */
502 while (tmp != fileName && tmp[-1] == '/')
504 if (tmp == fileName) { /* entire fileName is "//.."? */
505 /* yes, convert "//..." to "/"
507 * find / -maxdepth 1 -name /: prints /
508 * find // -maxdepth 1 -name /: prints //
509 * find / -maxdepth 1 -name //: prints nothing
510 * find // -maxdepth 1 -name //: prints nothing
513 trunc_slash = (char*)tmp + 1;
515 /* no, it's "foo/bar/[//...]", go back to 'b' */
516 trunc_slash = (char*)tmp;
517 while (tmp != fileName && tmp[-1] != '/')
522 /* Was using FNM_PERIOD flag too,
523 * but somewhere between 4.1.20 and 4.4.0 GNU find stopped using it.
524 * find -name '*foo' should match .foo too:
526 if (trunc_slash) *trunc_slash = '\0';
528 r = fnmatch(ap->pattern, tmp, (ap->iname ? FNM_CASEFOLD : 0));
531 tmp = strcpy_upcase(alloca(strlen(tmp) + 1), tmp);
532 r = fnmatch(ap->pattern, tmp, 0);
534 if (trunc_slash) *trunc_slash = '/';
538 #if ENABLE_FEATURE_FIND_PATH
542 return fnmatch(ap->pattern, fileName, (ap->ipath ? FNM_CASEFOLD : 0)) == 0;
545 fileName = strcpy_upcase(alloca(strlen(fileName) + 1), fileName);
546 return fnmatch(ap->pattern, fileName, 0) == 0;
550 #if ENABLE_FEATURE_FIND_REGEX
554 if (regexec(&ap->compiled_pattern, fileName, 1, &match, 0 /*eflags*/))
555 return 0; /* no match */
557 return 0; /* match doesn't start at pos 0 */
558 if (fileName[match.rm_eo])
559 return 0; /* match doesn't end exactly at end of pathname */
563 #if ENABLE_FEATURE_FIND_TYPE
566 return ((statbuf->st_mode & S_IFMT) == ap->type_mask);
569 #if ENABLE_FEATURE_FIND_PERM
572 /* -perm [+/]mode: at least one of perm_mask bits are set */
573 if (ap->perm_char == '+' || ap->perm_char == '/')
574 return (statbuf->st_mode & ap->perm_mask) != 0;
575 /* -perm -mode: all of perm_mask are set */
576 if (ap->perm_char == '-')
577 return (statbuf->st_mode & ap->perm_mask) == ap->perm_mask;
578 /* -perm mode: file mode must match perm_mask */
579 return (statbuf->st_mode & 07777) == ap->perm_mask;
582 #if ENABLE_FEATURE_FIND_MTIME
585 time_t file_age = time(NULL) - statbuf->st_mtime;
586 time_t mtime_secs = ap->mtime_days * 24*60*60;
587 if (ap->mtime_char == '+')
588 return file_age >= mtime_secs + 24*60*60;
589 if (ap->mtime_char == '-')
590 return file_age < mtime_secs;
591 /* just numeric mtime */
592 return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
595 #if ENABLE_FEATURE_FIND_MMIN
598 time_t file_age = time(NULL) - statbuf->st_mtime;
599 time_t mmin_secs = ap->mmin_mins * 60;
600 if (ap->mmin_char == '+')
601 return file_age >= mmin_secs + 60;
602 if (ap->mmin_char == '-')
603 return file_age < mmin_secs;
604 /* just numeric mmin */
605 return file_age >= mmin_secs && file_age < (mmin_secs + 60);
608 #if ENABLE_FEATURE_FIND_NEWER
611 return (ap->newer_mtime < statbuf->st_mtime);
614 #if ENABLE_FEATURE_FIND_INUM
617 return (statbuf->st_ino == ap->inode_num);
620 #if ENABLE_FEATURE_FIND_EXEC
621 static int do_exec(action_exec *ap, const char *fileName)
624 # if ENABLE_FEATURE_FIND_EXEC_PLUS
625 int size = ap->exec_argc + ap->filelist_idx + 1;
627 int size = ap->exec_argc + 1;
629 # if ENABLE_USE_PORTABLE_CODE
630 char **argv = alloca(sizeof(char*) * size);
631 # else /* gcc 4.3.1 generates smaller code: */
636 for (i = 0; i < ap->exec_argc; i++) {
637 const char *arg = ap->exec_argv[i];
639 # if ENABLE_FEATURE_FIND_EXEC_PLUS
641 /* Handling "-exec +"
642 * Only one exec_argv[i] has substitution in it.
643 * Expand that one exec_argv[i] into file list.
645 if (ap->subst_count[i] == 0) {
646 *pp++ = xstrdup(arg);
649 while (ap->filelist[j]) {
650 /* 2nd arg here should be ap->subst_count[i], but it is always 1: */
651 *pp++ = xmalloc_substitute_string(arg, 1, "{}", ap->filelist[j]);
652 free(ap->filelist[j]);
659 /* Handling "-exec ;" */
660 *pp++ = xmalloc_substitute_string(arg, ap->subst_count[i], "{}", fileName);
663 *pp = NULL; /* terminate the list */
665 # if ENABLE_FEATURE_FIND_EXEC_PLUS
667 ap->filelist[0] = NULL;
668 ap->filelist_idx = 0;
673 rc = spawn_and_wait(argv);
675 bb_simple_perror_msg(argv[0]);
680 return rc == 0; /* return 1 if exitcode 0 */
684 # if ENABLE_FEATURE_FIND_EXEC_PLUS
688 ap->filelist = xrealloc_vector(ap->filelist, 8, ap->filelist_idx);
689 ap->filelist[ap->filelist_idx++] = xstrdup(fileName);
690 ap->file_len += strlen(fileName) + sizeof(char*) + 1;
691 /* If we have lots of files already, exec the command */
693 if (ap->file_len >= G.max_argv_len)
694 rc = do_exec(ap, NULL);
698 return do_exec(ap, fileName);
700 # if ENABLE_FEATURE_FIND_EXEC_PLUS
701 static int flush_exec_plus(void)
705 action ***appp = G.actions;
706 while ((app = *appp++) != NULL) {
707 while ((ap = *app++) != NULL) {
708 if (ap->f == (action_fp)func_exec) {
709 action_exec *ae = (void*)ap;
710 if (ae->filelist_idx != 0) {
711 int rc = do_exec(ae, NULL);
712 # if ENABLE_FEATURE_FIND_NOT
713 if (ap->invert) rc = !rc;
725 #if ENABLE_FEATURE_FIND_USER
728 return (statbuf->st_uid == ap->uid);
731 #if ENABLE_FEATURE_FIND_GROUP
734 return (statbuf->st_gid == ap->gid);
737 #if ENABLE_FEATURE_FIND_PRINT0
740 printf("%s%c", fileName, '\0');
749 #if ENABLE_FEATURE_FIND_PAREN
752 return exec_actions(ap->subexpr, fileName, statbuf);
755 #if ENABLE_FEATURE_FIND_SIZE
758 if (ap->size_char == '+')
759 return statbuf->st_size > ap->size;
760 if (ap->size_char == '-')
761 return statbuf->st_size < ap->size;
762 return statbuf->st_size == ap->size;
765 #if ENABLE_FEATURE_FIND_PRUNE
767 * -prune: if -depth is not given, return true and do not descend
768 * current dir; if -depth is given, return false with no effect.
770 * find dir -name 'asm-*' -prune -o -name '*.[chS]' -print
777 #if ENABLE_FEATURE_FIND_DELETE
781 if (S_ISDIR(statbuf->st_mode)) {
782 /* "find . -delete" skips rmdir(".") */
784 if (NOT_LONE_CHAR(fileName, '.'))
785 rc = rmdir(fileName);
787 rc = unlink(fileName);
790 bb_simple_perror_msg(fileName);
794 #if ENABLE_FEATURE_FIND_CONTEXT
797 security_context_t con;
800 if (G.recurse_flags & ACTION_FOLLOWLINKS) {
801 rc = getfilecon(fileName, &con);
803 rc = lgetfilecon(fileName, &con);
807 rc = strcmp(ap->context, con);
812 #if ENABLE_FEATURE_FIND_LINKS
815 switch(ap->links_char) {
816 case '-' : return (statbuf->st_nlink < ap->links_count);
817 case '+' : return (statbuf->st_nlink > ap->links_count);
818 default: return (statbuf->st_nlink == ap->links_count);
823 static int FAST_FUNC fileAction(const char *fileName,
824 struct stat *statbuf,
825 void *userData UNUSED_PARAM,
826 int depth IF_NOT_FEATURE_FIND_MAXDEPTH(UNUSED_PARAM))
831 #if ENABLE_FEATURE_FIND_XDEV
832 if (S_ISDIR(statbuf->st_mode) && G.xdev_count) {
834 for (i = 0; i < G.xdev_count; i++) {
835 if (G.xdev_dev[i] == statbuf->st_dev)
838 //bb_error_msg("'%s': not same fs", fileName);
844 #if ENABLE_FEATURE_FIND_MAXDEPTH
845 if (depth < G.minmaxdepth[0]) {
847 return TRUE; /* skip this, continue recursing */
848 return SKIP; /* stop recursing */
850 if (depth > G.minmaxdepth[1])
851 return SKIP; /* stop recursing */
854 r = exec_actions(G.actions, fileName, statbuf);
855 /* Had no explicit -print[0] or -exec? then print */
856 if ((r & TRUE) && G.need_print)
859 #if ENABLE_FEATURE_FIND_MAXDEPTH
860 if (S_ISDIR(statbuf->st_mode)) {
861 if (depth == G.minmaxdepth[1])
865 /* -xdev stops on mountpoints, but AFTER mountpoit itself
866 * is processed as usual */
871 /* Cannot return 0: our caller, recursive_action(),
872 * will perror() and skip dirs (if called on dir) */
873 return (r & SKIP) ? SKIP : TRUE;
877 #if ENABLE_FEATURE_FIND_TYPE
878 static int find_type(const char *type)
884 else if (*type == 'c')
886 else if (*type == 'd')
888 else if (*type == 'p')
890 else if (*type == 'f')
892 else if (*type == 'l')
894 else if (*type == 's')
897 if (mask == 0 || type[1] != '\0')
898 bb_error_msg_and_die(bb_msg_invalid_arg_to, type, "-type");
904 #if ENABLE_FEATURE_FIND_PERM \
905 || ENABLE_FEATURE_FIND_MTIME || ENABLE_FEATURE_FIND_MMIN \
906 || ENABLE_FEATURE_FIND_SIZE || ENABLE_FEATURE_FIND_LINKS
907 static const char* plus_minus_num(const char* str)
909 if (*str == '-' || *str == '+')
915 /* Say no to GCCism */
916 #define USE_NESTED_FUNCTION 0
918 #if !USE_NESTED_FUNCTION
923 IF_FEATURE_FIND_NOT( bool invert_flag; )
925 static action* alloc_action(struct pp_locals *ppl, int sizeof_struct, action_fp f)
927 action *ap = xzalloc(sizeof_struct);
929 action ***group = &ppl->appp[ppl->cur_group];
930 *group = app = xrealloc(*group, (ppl->cur_action+2) * sizeof(ppl->appp[0][0]));
931 app[ppl->cur_action++] = ap;
932 app[ppl->cur_action] = NULL;
934 IF_FEATURE_FIND_NOT( ap->invert = ppl->invert_flag; )
935 IF_FEATURE_FIND_NOT( ppl->invert_flag = 0; )
940 static action*** parse_params(char **argv)
944 IF_FEATURE_FIND_XDEV( OPT_XDEV ,)
945 IF_FEATURE_FIND_DEPTH( OPT_DEPTH ,)
948 IF_FEATURE_FIND_NOT( PARM_char_not ,)
952 IF_FEATURE_FIND_NOT( PARM_not ,)
955 IF_FEATURE_FIND_PRINT0( PARM_print0 ,)
956 IF_FEATURE_FIND_PRUNE( PARM_prune ,)
957 IF_FEATURE_FIND_DELETE( PARM_delete ,)
958 IF_FEATURE_FIND_EXEC( PARM_exec ,)
959 IF_FEATURE_FIND_PAREN( PARM_char_brace,)
960 /* All options/actions starting from here require argument */
963 IF_FEATURE_FIND_PATH( PARM_path ,)
965 /* -wholename is a synonym for -path */
966 /* We support it because Linux kernel's "make tags" uses it */
967 IF_FEATURE_FIND_PATH( PARM_wholename ,)
969 IF_FEATURE_FIND_PATH( PARM_ipath ,)
970 IF_FEATURE_FIND_REGEX( PARM_regex ,)
971 IF_FEATURE_FIND_TYPE( PARM_type ,)
972 IF_FEATURE_FIND_PERM( PARM_perm ,)
973 IF_FEATURE_FIND_MTIME( PARM_mtime ,)
974 IF_FEATURE_FIND_MMIN( PARM_mmin ,)
975 IF_FEATURE_FIND_NEWER( PARM_newer ,)
976 IF_FEATURE_FIND_INUM( PARM_inum ,)
977 IF_FEATURE_FIND_USER( PARM_user ,)
978 IF_FEATURE_FIND_GROUP( PARM_group ,)
979 IF_FEATURE_FIND_SIZE( PARM_size ,)
980 IF_FEATURE_FIND_CONTEXT(PARM_context ,)
981 IF_FEATURE_FIND_LINKS( PARM_links ,)
982 IF_FEATURE_FIND_MAXDEPTH(OPT_MINDEPTH,OPT_MAXDEPTH,)
985 static const char params[] ALIGN1 =
987 IF_FEATURE_FIND_XDEV( "-xdev\0" )
988 IF_FEATURE_FIND_DEPTH( "-depth\0" )
991 IF_FEATURE_FIND_NOT( "!\0" )
995 IF_FEATURE_FIND_NOT( "-not\0" )
998 IF_FEATURE_FIND_PRINT0( "-print0\0" )
999 IF_FEATURE_FIND_PRUNE( "-prune\0" )
1000 IF_FEATURE_FIND_DELETE( "-delete\0" )
1001 IF_FEATURE_FIND_EXEC( "-exec\0" )
1002 IF_FEATURE_FIND_PAREN( "(\0" )
1003 /* All options/actions starting from here require argument */
1006 IF_FEATURE_FIND_PATH( "-path\0" )
1008 IF_FEATURE_FIND_PATH( "-wholename\0")
1010 IF_FEATURE_FIND_PATH( "-ipath\0" )
1011 IF_FEATURE_FIND_REGEX( "-regex\0" )
1012 IF_FEATURE_FIND_TYPE( "-type\0" )
1013 IF_FEATURE_FIND_PERM( "-perm\0" )
1014 IF_FEATURE_FIND_MTIME( "-mtime\0" )
1015 IF_FEATURE_FIND_MMIN( "-mmin\0" )
1016 IF_FEATURE_FIND_NEWER( "-newer\0" )
1017 IF_FEATURE_FIND_INUM( "-inum\0" )
1018 IF_FEATURE_FIND_USER( "-user\0" )
1019 IF_FEATURE_FIND_GROUP( "-group\0" )
1020 IF_FEATURE_FIND_SIZE( "-size\0" )
1021 IF_FEATURE_FIND_CONTEXT("-context\0")
1022 IF_FEATURE_FIND_LINKS( "-links\0" )
1023 IF_FEATURE_FIND_MAXDEPTH("-mindepth\0""-maxdepth\0")
1026 #if !USE_NESTED_FUNCTION
1027 struct pp_locals ppl;
1028 #define appp (ppl.appp )
1029 #define cur_group (ppl.cur_group )
1030 #define cur_action (ppl.cur_action )
1031 #define invert_flag (ppl.invert_flag)
1032 #define ALLOC_ACTION(name) (action_##name*)alloc_action(&ppl, sizeof(action_##name), (action_fp) func_##name)
1036 unsigned cur_action;
1037 IF_FEATURE_FIND_NOT( bool invert_flag; )
1039 /* This is the only place in busybox where we use nested function.
1040 * So far more standard alternatives were bigger. */
1041 /* Auto decl suppresses "func without a prototype" warning: */
1042 auto action* alloc_action(int sizeof_struct, action_fp f);
1043 action* alloc_action(int sizeof_struct, action_fp f)
1046 appp[cur_group] = xrealloc(appp[cur_group], (cur_action+2) * sizeof(appp[0][0]));
1047 appp[cur_group][cur_action++] = ap = xzalloc(sizeof_struct);
1048 appp[cur_group][cur_action] = NULL;
1050 IF_FEATURE_FIND_NOT( ap->invert = invert_flag; )
1051 IF_FEATURE_FIND_NOT( invert_flag = 0; )
1054 #define ALLOC_ACTION(name) (action_##name*)alloc_action(sizeof(action_##name), (action_fp) func_##name)
1059 IF_FEATURE_FIND_NOT( invert_flag = 0; )
1060 appp = xzalloc(2 * sizeof(appp[0])); /* appp[0],[1] == NULL */
1063 const char *arg = argv[0];
1064 int parm = index_in_strings(params, arg);
1065 const char *arg1 = argv[1];
1067 dbg("arg:'%s' arg1:'%s' parm:%d PARM_type:%d", arg, arg1, parm, PARM_type);
1069 if (parm >= PARM_name) {
1070 /* All options/actions starting from -name require argument */
1072 bb_error_msg_and_die(bb_msg_requires_arg, arg);
1076 /* We can use big switch() here, but on i386
1077 * it doesn't give smaller code. Other arches? */
1079 /* Options always return true. They always take effect
1080 * rather than being processed only when their place in the
1081 * expression is reached.
1084 if (parm == OPT_FOLLOW) {
1085 dbg("follow enabled: %d", __LINE__);
1086 G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
1088 #if ENABLE_FEATURE_FIND_XDEV
1089 else if (parm == OPT_XDEV) {
1090 dbg("%d", __LINE__);
1094 #if ENABLE_FEATURE_FIND_MAXDEPTH
1095 else if (parm == OPT_MINDEPTH || parm == OPT_MINDEPTH + 1) {
1096 dbg("%d", __LINE__);
1097 G.minmaxdepth[parm - OPT_MINDEPTH] = xatoi_positive(arg1);
1100 #if ENABLE_FEATURE_FIND_DEPTH
1101 else if (parm == OPT_DEPTH) {
1102 dbg("%d", __LINE__);
1103 G.recurse_flags |= ACTION_DEPTHFIRST;
1106 /* Actions are grouped by operators
1107 * ( expr ) Force precedence
1108 * ! expr True if expr is false
1109 * -not expr Same as ! expr
1110 * expr1 [-a[nd]] expr2 And; expr2 is not evaluated if expr1 is false
1111 * expr1 -o[r] expr2 Or; expr2 is not evaluated if expr1 is true
1112 * expr1 , expr2 List; both expr1 and expr2 are always evaluated
1113 * We implement: (), -a, -o
1116 else if (parm == PARM_a IF_DESKTOP(|| parm == PARM_and)) {
1117 dbg("%d", __LINE__);
1118 /* no further special handling required */
1120 else if (parm == PARM_o IF_DESKTOP(|| parm == PARM_or)) {
1121 dbg("%d", __LINE__);
1122 /* start new OR group */
1124 appp = xrealloc(appp, (cur_group+2) * sizeof(appp[0]));
1125 /*appp[cur_group] = NULL; - already NULL */
1126 appp[cur_group+1] = NULL;
1129 #if ENABLE_FEATURE_FIND_NOT
1130 else if (parm == PARM_char_not IF_DESKTOP(|| parm == PARM_not)) {
1131 /* also handles "find ! ! -name 'foo*'" */
1133 dbg("invert_flag:%d", invert_flag);
1137 else if (parm == PARM_print) {
1138 dbg("%d", __LINE__);
1140 (void) ALLOC_ACTION(print);
1142 #if ENABLE_FEATURE_FIND_PRINT0
1143 else if (parm == PARM_print0) {
1144 dbg("%d", __LINE__);
1146 (void) ALLOC_ACTION(print0);
1149 #if ENABLE_FEATURE_FIND_PRUNE
1150 else if (parm == PARM_prune) {
1151 dbg("%d", __LINE__);
1152 (void) ALLOC_ACTION(prune);
1155 #if ENABLE_FEATURE_FIND_DELETE
1156 else if (parm == PARM_delete) {
1157 dbg("%d", __LINE__);
1159 G.recurse_flags |= ACTION_DEPTHFIRST;
1160 (void) ALLOC_ACTION(delete);
1163 #if ENABLE_FEATURE_FIND_EXEC
1164 else if (parm == PARM_exec) {
1167 IF_FEATURE_FIND_EXEC_PLUS(int all_subst = 0;)
1168 dbg("%d", __LINE__);
1170 ap = ALLOC_ACTION(exec);
1171 ap->exec_argv = ++argv; /* first arg after -exec */
1172 /*ap->exec_argc = 0; - ALLOC_ACTION did it */
1174 if (!*argv) /* did not see ';' or '+' until end */
1175 bb_error_msg_and_die(bb_msg_requires_arg, "-exec");
1176 // find -exec echo Foo ">{}<" ";"
1177 // executes "echo Foo >FILENAME<",
1178 // find -exec echo Foo ">{}<" "+"
1179 // executes "echo Foo FILENAME1 FILENAME2 FILENAME3...".
1180 if ((argv[0][0] == ';' || argv[0][0] == '+')
1181 && argv[0][1] == '\0'
1183 # if ENABLE_FEATURE_FIND_EXEC_PLUS
1184 if (argv[0][0] == '+')
1185 ap->filelist = xzalloc(sizeof(ap->filelist[0]));
1192 if (ap->exec_argc == 0)
1193 bb_error_msg_and_die(bb_msg_requires_arg, arg);
1194 ap->subst_count = xmalloc(ap->exec_argc * sizeof(int));
1197 ap->subst_count[i] = count_strstr(ap->exec_argv[i], "{}");
1198 IF_FEATURE_FIND_EXEC_PLUS(all_subst += ap->subst_count[i];)
1200 # if ENABLE_FEATURE_FIND_EXEC_PLUS
1202 * coreutils expects {} to appear only once in "-exec +"
1204 if (all_subst != 1 && ap->filelist)
1205 bb_error_msg_and_die("only one '{}' allowed for -exec +");
1209 #if ENABLE_FEATURE_FIND_PAREN
1210 else if (parm == PARM_char_brace) {
1213 unsigned nested = 1;
1215 dbg("%d", __LINE__);
1219 bb_error_msg_and_die("unpaired '('");
1220 if (LONE_CHAR(*endarg, '('))
1222 else if (LONE_CHAR(*endarg, ')') && !--nested) {
1227 ap = ALLOC_ACTION(paren);
1228 ap->subexpr = parse_params(argv + 1);
1229 *endarg = (char*) ")"; /* restore NULLed parameter */
1233 else if (parm == PARM_name || parm == PARM_iname) {
1235 dbg("%d", __LINE__);
1236 ap = ALLOC_ACTION(name);
1238 ap->iname = (parm == PARM_iname);
1240 #if ENABLE_FEATURE_FIND_PATH
1241 else if (parm == PARM_path IF_DESKTOP(|| parm == PARM_wholename) || parm == PARM_ipath) {
1243 dbg("%d", __LINE__);
1244 ap = ALLOC_ACTION(path);
1246 ap->ipath = (parm == PARM_ipath);
1249 #if ENABLE_FEATURE_FIND_REGEX
1250 else if (parm == PARM_regex) {
1252 dbg("%d", __LINE__);
1253 ap = ALLOC_ACTION(regex);
1254 xregcomp(&ap->compiled_pattern, arg1, 0 /*cflags*/);
1257 #if ENABLE_FEATURE_FIND_TYPE
1258 else if (parm == PARM_type) {
1260 ap = ALLOC_ACTION(type);
1261 ap->type_mask = find_type(arg1);
1262 dbg("created:type mask:%x", ap->type_mask);
1265 #if ENABLE_FEATURE_FIND_PERM
1266 /* -perm BITS File's mode bits are exactly BITS (octal or symbolic).
1267 * Symbolic modes use mode 0 as a point of departure.
1268 * -perm -BITS All of the BITS are set in file's mode.
1269 * -perm [+/]BITS At least one of the BITS is set in file's mode.
1271 else if (parm == PARM_perm) {
1273 dbg("%d", __LINE__);
1274 ap = ALLOC_ACTION(perm);
1275 ap->perm_char = arg1[0];
1276 arg1 = (arg1[0] == '/' ? arg1+1 : plus_minus_num(arg1));
1277 /*ap->perm_mask = 0; - ALLOC_ACTION did it */
1278 ap->perm_mask = bb_parse_mode(arg1, ap->perm_mask);
1279 if (ap->perm_mask == (mode_t)-1)
1280 bb_error_msg_and_die("invalid mode '%s'", arg1);
1283 #if ENABLE_FEATURE_FIND_MTIME
1284 else if (parm == PARM_mtime) {
1286 dbg("%d", __LINE__);
1287 ap = ALLOC_ACTION(mtime);
1288 ap->mtime_char = arg1[0];
1289 ap->mtime_days = xatoul(plus_minus_num(arg1));
1292 #if ENABLE_FEATURE_FIND_MMIN
1293 else if (parm == PARM_mmin) {
1295 dbg("%d", __LINE__);
1296 ap = ALLOC_ACTION(mmin);
1297 ap->mmin_char = arg1[0];
1298 ap->mmin_mins = xatoul(plus_minus_num(arg1));
1301 #if ENABLE_FEATURE_FIND_NEWER
1302 else if (parm == PARM_newer) {
1303 struct stat stat_newer;
1305 dbg("%d", __LINE__);
1306 ap = ALLOC_ACTION(newer);
1307 xstat(arg1, &stat_newer);
1308 ap->newer_mtime = stat_newer.st_mtime;
1311 #if ENABLE_FEATURE_FIND_INUM
1312 else if (parm == PARM_inum) {
1314 dbg("%d", __LINE__);
1315 ap = ALLOC_ACTION(inum);
1316 ap->inode_num = xatoul(arg1);
1319 #if ENABLE_FEATURE_FIND_USER
1320 else if (parm == PARM_user) {
1322 dbg("%d", __LINE__);
1323 ap = ALLOC_ACTION(user);
1324 ap->uid = bb_strtou(arg1, NULL, 10);
1326 ap->uid = xuname2uid(arg1);
1329 #if ENABLE_FEATURE_FIND_GROUP
1330 else if (parm == PARM_group) {
1332 dbg("%d", __LINE__);
1333 ap = ALLOC_ACTION(group);
1334 ap->gid = bb_strtou(arg1, NULL, 10);
1336 ap->gid = xgroup2gid(arg1);
1339 #if ENABLE_FEATURE_FIND_SIZE
1340 else if (parm == PARM_size) {
1341 /* -size n[bckw]: file uses n units of space
1342 * b (default): units are 512-byte blocks
1348 #define XATOU_SFX xatoull_sfx
1350 #define XATOU_SFX xatoul_sfx
1352 static const struct suffix_mult find_suffixes[] = {
1361 dbg("%d", __LINE__);
1362 ap = ALLOC_ACTION(size);
1363 ap->size_char = arg1[0];
1364 ap->size = XATOU_SFX(plus_minus_num(arg1), find_suffixes);
1367 #if ENABLE_FEATURE_FIND_CONTEXT
1368 else if (parm == PARM_context) {
1370 dbg("%d", __LINE__);
1371 ap = ALLOC_ACTION(context);
1372 /*ap->context = NULL; - ALLOC_ACTION did it */
1373 /* SELinux headers erroneously declare non-const parameter */
1374 if (selinux_raw_to_trans_context((char*)arg1, &ap->context))
1375 bb_simple_perror_msg(arg1);
1378 #if ENABLE_FEATURE_FIND_LINKS
1379 else if (parm == PARM_links) {
1381 dbg("%d", __LINE__);
1382 ap = ALLOC_ACTION(links);
1383 ap->links_char = arg1[0];
1384 ap->links_count = xatoul(plus_minus_num(arg1));
1388 bb_error_msg("unrecognized: %s", arg);
1393 dbg("exiting %s", __func__);
1401 int find_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1402 int find_main(int argc UNUSED_PARAM, char **argv)
1404 int i, firstopt, status = EXIT_SUCCESS;
1405 char **past_HLP, *saved;
1409 /* "find -type f" + getopt("+HLP") => disaster.
1410 * Need to avoid getopt running into a non-HLP option.
1411 * Do this by temporarily storing NULL there:
1415 saved = *++past_HLP;
1418 if (saved[0] != '-')
1421 break; /* it is "-" */
1422 if ((saved+1)[strspn(saved+1, "HLP")] != '\0')
1426 /* "+": stop on first non-option */
1427 i = getopt32(argv, "+HLP");
1429 G.recurse_flags |= ACTION_FOLLOWLINKS_L0 | ACTION_DANGLING_OK;
1431 G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
1432 /* -P is default and is ignored */
1433 argv = past_HLP; /* same result as "argv += optind;" */
1436 for (firstopt = 0; argv[firstopt]; firstopt++) {
1437 if (argv[firstopt][0] == '-')
1439 if (ENABLE_FEATURE_FIND_NOT && LONE_CHAR(argv[firstopt], '!'))
1441 if (ENABLE_FEATURE_FIND_PAREN && LONE_CHAR(argv[firstopt], '('))
1444 if (firstopt == 0) {
1445 *--argv = (char*)".";
1449 G.actions = parse_params(&argv[firstopt]);
1450 argv[firstopt] = NULL;
1452 #if ENABLE_FEATURE_FIND_XDEV
1456 G.xdev_count = firstopt;
1457 G.xdev_dev = xzalloc(G.xdev_count * sizeof(G.xdev_dev[0]));
1458 for (i = 0; argv[i]; i++) {
1459 /* not xstat(): shouldn't bomb out on
1460 * "find not_exist exist -xdev" */
1461 if (stat(argv[i], &stbuf) == 0)
1462 G.xdev_dev[i] = stbuf.st_dev;
1463 /* else G.xdev_dev[i] stays 0 and
1464 * won't match any real device dev_t
1470 for (i = 0; argv[i]; i++) {
1471 if (!recursive_action(argv[i],
1472 G.recurse_flags,/* flags */
1473 fileAction, /* file action */
1474 fileAction, /* dir action */
1475 NULL, /* user data */
1478 status |= EXIT_FAILURE;
1482 IF_FEATURE_FIND_EXEC_PLUS(status |= flush_exec_plus();)