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.
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
49 * ./busybox find "$@" | tee /tmp/bb_find
50 * echo ==================
51 * /path/to/gnu/find "$@" | tee /tmp/std_find
52 * echo ==================
53 * diff -u /tmp/std_find /tmp/bb_find && echo Identical
60 //config: find is used to search your system to find specified files.
62 //config:config FEATURE_FIND_PRINT0
63 //config: bool "Enable -print0: NUL-terminated output"
65 //config: depends on FIND
67 //config: Causes output names to be separated by a NUL character
68 //config: rather than a newline. This allows names that contain
69 //config: newlines and other whitespace to be more easily
70 //config: interpreted by other programs.
72 //config:config FEATURE_FIND_MTIME
73 //config: bool "Enable -mtime: modified time matching"
75 //config: depends on FIND
77 //config: Allow searching based on the modification time of
78 //config: files, in days.
80 //config:config FEATURE_FIND_MMIN
81 //config: bool "Enable -mmin: modified time matching by minutes"
83 //config: depends on FIND
85 //config: Allow searching based on the modification time of
86 //config: files, in minutes.
88 //config:config FEATURE_FIND_PERM
89 //config: bool "Enable -perm: permissions matching"
91 //config: depends on FIND
93 //config:config FEATURE_FIND_TYPE
94 //config: bool "Enable -type: file type matching (file/dir/link/...)"
96 //config: depends on FIND
98 //config: Enable searching based on file type (file,
99 //config: directory, socket, device, etc.).
101 //config:config FEATURE_FIND_XDEV
102 //config: bool "Enable -xdev: 'stay in filesystem'"
104 //config: depends on FIND
106 //config:config FEATURE_FIND_MAXDEPTH
107 //config: bool "Enable -mindepth N and -maxdepth N"
109 //config: depends on FIND
111 //config:config FEATURE_FIND_NEWER
112 //config: bool "Enable -newer: compare file modification times"
114 //config: depends on FIND
116 //config: Support the 'find -newer' option for finding any files which have
117 //config: modification time that is more recent than the specified FILE.
119 //config:config FEATURE_FIND_INUM
120 //config: bool "Enable -inum: inode number matching"
122 //config: depends on FIND
124 //config:config FEATURE_FIND_EXEC
125 //config: bool "Enable -exec: execute commands"
127 //config: depends on FIND
129 //config: Support the 'find -exec' option for executing commands based upon
130 //config: the files matched.
132 //config:config FEATURE_FIND_EXEC_PLUS
133 //config: bool "Enable -exec ... {} +"
135 //config: depends on FEATURE_FIND_EXEC
137 //config: Support the 'find -exec ... {} +' option for executing commands
138 //config: for all matched files at once.
139 //config: Without this option, -exec + is a synonym for -exec ;
140 //config: (IOW: it works correctly, but without expected speedup)
142 //config:config FEATURE_FIND_USER
143 //config: bool "Enable -user: username/uid matching"
145 //config: depends on FIND
147 //config:config FEATURE_FIND_GROUP
148 //config: bool "Enable -group: group/gid matching"
150 //config: depends on FIND
152 //config:config FEATURE_FIND_NOT
153 //config: bool "Enable the 'not' (!) operator"
155 //config: depends on FIND
157 //config: Support the '!' operator to invert the test results.
158 //config: If 'Enable full-blown desktop' is enabled, then will also support
159 //config: the non-POSIX notation '-not'.
161 //config:config FEATURE_FIND_DEPTH
162 //config: bool "Enable -depth"
164 //config: depends on FIND
166 //config: Process each directory's contents before the directory itself.
168 //config:config FEATURE_FIND_PAREN
169 //config: bool "Enable parens in options"
171 //config: depends on FIND
173 //config: Enable usage of parens '(' to specify logical order of arguments.
175 //config:config FEATURE_FIND_SIZE
176 //config: bool "Enable -size: file size matching"
178 //config: depends on FIND
180 //config:config FEATURE_FIND_PRUNE
181 //config: bool "Enable -prune: exclude subdirectories"
183 //config: depends on FIND
185 //config: If the file is a directory, don't descend into it. Useful for
186 //config: exclusion .svn and CVS directories.
188 //config:config FEATURE_FIND_DELETE
189 //config: bool "Enable -delete: delete files/dirs"
191 //config: depends on FIND && FEATURE_FIND_DEPTH
193 //config: Support the 'find -delete' option for deleting files and directories.
194 //config: WARNING: This option can do much harm if used wrong. Busybox will not
195 //config: try to protect the user from doing stupid things. Use with care.
197 //config:config FEATURE_FIND_PATH
198 //config: bool "Enable -path: match pathname with shell pattern"
200 //config: depends on FIND
202 //config: The -path option matches whole pathname instead of just filename.
204 //config:config FEATURE_FIND_REGEX
205 //config: bool "Enable -regex: match pathname with regex"
207 //config: depends on FIND
209 //config: The -regex option matches whole pathname against regular expression.
211 //config:config FEATURE_FIND_CONTEXT
212 //config: bool "Enable -context: security context matching"
214 //config: depends on FIND && SELINUX
216 //config: Support the 'find -context' option for matching security context.
218 //config:config FEATURE_FIND_LINKS
219 //config: bool "Enable -links: link count matching"
221 //config: depends on FIND
223 //config: Support the 'find -links' option for matching number of links.
225 //applet:IF_FIND(APPLET_NOEXEC(find, find, BB_DIR_USR_BIN, BB_SUID_DROP, find))
227 //kbuild:lib-$(CONFIG_FIND) += find.o
229 //usage:#define find_trivial_usage
230 //usage: "[-HL] [PATH]... [OPTIONS] [ACTIONS]"
231 //usage:#define find_full_usage "\n\n"
232 //usage: "Search for files and perform actions on them.\n"
233 //usage: "First failed action stops processing of current file.\n"
234 //usage: "Defaults: PATH is current directory, action is '-print'\n"
235 //usage: "\n -L,-follow Follow symlinks"
236 //usage: "\n -H ...on command line only"
237 //usage: IF_FEATURE_FIND_XDEV(
238 //usage: "\n -xdev Don't descend directories on other filesystems"
240 //usage: IF_FEATURE_FIND_MAXDEPTH(
241 //usage: "\n -maxdepth N Descend at most N levels. -maxdepth 0 applies"
242 //usage: "\n actions to command line arguments only"
243 //usage: "\n -mindepth N Don't act on first N levels"
245 //usage: IF_FEATURE_FIND_DEPTH(
246 //usage: "\n -depth Act on directory *after* traversing it"
249 //usage: "\nActions:"
250 //usage: IF_FEATURE_FIND_PAREN(
251 //usage: "\n ( ACTIONS ) Group actions for -o / -a"
253 //usage: IF_FEATURE_FIND_NOT(
254 //usage: "\n ! ACT Invert ACT's success/failure"
256 //usage: "\n ACT1 [-a] ACT2 If ACT1 fails, stop, else do ACT2"
257 //usage: "\n ACT1 -o ACT2 If ACT1 succeeds, stop, else do ACT2"
258 //usage: "\n Note: -a has higher priority than -o"
259 //usage: "\n -name PATTERN Match file name (w/o directory name) to PATTERN"
260 //usage: "\n -iname PATTERN Case insensitive -name"
261 //usage: IF_FEATURE_FIND_PATH(
262 //usage: "\n -path PATTERN Match path to PATTERN"
263 //usage: "\n -ipath PATTERN Case insensitive -path"
265 //usage: IF_FEATURE_FIND_REGEX(
266 //usage: "\n -regex PATTERN Match path to regex PATTERN"
268 //usage: IF_FEATURE_FIND_TYPE(
269 //usage: "\n -type X File type is X (one of: f,d,l,b,c,...)"
271 //usage: IF_FEATURE_FIND_PERM(
272 //usage: "\n -perm MASK At least one mask bit (+MASK), all bits (-MASK),"
273 //usage: "\n or exactly MASK bits are set in file's mode"
275 //usage: IF_FEATURE_FIND_MTIME(
276 //usage: "\n -mtime DAYS mtime is greater than (+N), less than (-N),"
277 //usage: "\n or exactly N days in the past"
279 //usage: IF_FEATURE_FIND_MMIN(
280 //usage: "\n -mmin MINS mtime is greater than (+N), less than (-N),"
281 //usage: "\n or exactly N minutes in the past"
283 //usage: IF_FEATURE_FIND_NEWER(
284 //usage: "\n -newer FILE mtime is more recent than FILE's"
286 //usage: IF_FEATURE_FIND_INUM(
287 //usage: "\n -inum N File has inode number N"
289 //usage: IF_FEATURE_FIND_USER(
290 //usage: "\n -user NAME/ID File is owned by given user"
292 //usage: IF_FEATURE_FIND_GROUP(
293 //usage: "\n -group NAME/ID File is owned by given group"
295 //usage: IF_FEATURE_FIND_SIZE(
296 //usage: "\n -size N[bck] File size is N (c:bytes,k:kbytes,b:512 bytes(def.))"
297 //usage: "\n +/-N: file size is bigger/smaller than N"
299 //usage: IF_FEATURE_FIND_LINKS(
300 //usage: "\n -links N Number of links is greater than (+N), less than (-N),"
301 //usage: "\n or exactly N"
303 //usage: IF_FEATURE_FIND_CONTEXT(
304 //usage: "\n -context CTX File has specified security context"
306 //usage: IF_FEATURE_FIND_PRUNE(
307 //usage: "\n -prune If current file is directory, don't descend into it"
309 //usage: "\nIf none of the following actions is specified, -print is assumed"
310 //usage: "\n -print Print file name"
311 //usage: IF_FEATURE_FIND_PRINT0(
312 //usage: "\n -print0 Print file name, NUL terminated"
314 //usage: IF_FEATURE_FIND_EXEC(
315 //usage: "\n -exec CMD ARG ; Run CMD with all instances of {} replaced by"
316 //usage: "\n file name. Fails if CMD exits with nonzero"
318 //usage: IF_FEATURE_FIND_EXEC_PLUS(
319 //usage: "\n -exec CMD ARG + Run CMD with {} replaced by list of file names"
321 //usage: IF_FEATURE_FIND_DELETE(
322 //usage: "\n -delete Delete current file/directory. Turns on -depth option"
325 //usage:#define find_example_usage
326 //usage: "$ find / -name passwd\n"
327 //usage: "/etc/passwd\n"
331 #include "common_bufsiz.h"
332 #if ENABLE_FEATURE_FIND_REGEX
337 # define FNM_CASEFOLD 0
341 # define dbg(...) ((void)0)
343 # define dbg(...) bb_error_msg(__VA_ARGS__)
347 /* This is a NOEXEC applet. Be very careful! */
350 typedef int (*action_fp)(const char *fileName, const struct stat *statbuf, void *) FAST_FUNC;
354 #if ENABLE_FEATURE_FIND_NOT
359 #define ACTS(name, ...) typedef struct { action a; __VA_ARGS__ } action_##name;
361 static int FAST_FUNC func_##name(const char *fileName UNUSED_PARAM, \
362 const struct stat *statbuf UNUSED_PARAM, \
363 action_##name* ap UNUSED_PARAM)
366 ACTS(name, const char *pattern; bool iname;)
367 IF_FEATURE_FIND_PATH( ACTS(path, const char *pattern; bool ipath;))
368 IF_FEATURE_FIND_REGEX( ACTS(regex, regex_t compiled_pattern;))
369 IF_FEATURE_FIND_PRINT0( ACTS(print0))
370 IF_FEATURE_FIND_TYPE( ACTS(type, int type_mask;))
371 IF_FEATURE_FIND_PERM( ACTS(perm, char perm_char; mode_t perm_mask;))
372 IF_FEATURE_FIND_MTIME( ACTS(mtime, char mtime_char; unsigned mtime_days;))
373 IF_FEATURE_FIND_MMIN( ACTS(mmin, char mmin_char; unsigned mmin_mins;))
374 IF_FEATURE_FIND_NEWER( ACTS(newer, time_t newer_mtime;))
375 IF_FEATURE_FIND_INUM( ACTS(inum, ino_t inode_num;))
376 IF_FEATURE_FIND_USER( ACTS(user, uid_t uid;))
377 IF_FEATURE_FIND_SIZE( ACTS(size, char size_char; off_t size;))
378 IF_FEATURE_FIND_CONTEXT(ACTS(context, security_context_t context;))
379 IF_FEATURE_FIND_PAREN( ACTS(paren, action ***subexpr;))
380 IF_FEATURE_FIND_PRUNE( ACTS(prune))
381 IF_FEATURE_FIND_DELETE( ACTS(delete))
382 IF_FEATURE_FIND_EXEC( ACTS(exec,
383 char **exec_argv; /* -exec ARGS */
384 unsigned *subst_count;
385 int exec_argc; /* count of ARGS */
386 IF_FEATURE_FIND_EXEC_PLUS(
388 * filelist is NULL if "exec ;"
389 * non-NULL if "exec +"
396 IF_FEATURE_FIND_GROUP( ACTS(group, gid_t gid;))
397 IF_FEATURE_FIND_LINKS( ACTS(links, char links_char; int links_count;))
400 IF_FEATURE_FIND_XDEV(dev_t *xdev_dev;)
401 IF_FEATURE_FIND_XDEV(int xdev_count;)
402 #if ENABLE_FEATURE_FIND_MAXDEPTH
408 recurse_flags_t recurse_flags;
409 IF_FEATURE_FIND_EXEC_PLUS(unsigned max_argv_len;)
411 #define G (*(struct globals*)bb_common_bufsiz1)
412 #define INIT_G() do { \
413 setup_common_bufsiz(); \
414 BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
415 /* we have to zero it out because of NOEXEC */ \
416 memset(&G, 0, sizeof(G)); \
417 IF_FEATURE_FIND_MAXDEPTH(G.minmaxdepth[1] = INT_MAX;) \
418 IF_FEATURE_FIND_EXEC_PLUS(G.max_argv_len = bb_arg_max() - 2048;) \
420 G.recurse_flags = ACTION_RECURSE; \
423 /* Return values of ACTFs ('action functions') are a bit mask:
424 * bit 1=1: prune (use SKIP constant for setting it)
425 * bit 0=1: matched successfully (TRUE)
428 static int exec_actions(action ***appp, const char *fileName, const struct stat *statbuf)
435 /* "action group" is a set of actions ANDed together.
436 * groups are ORed together.
437 * We simply evaluate each group until we find one in which all actions
440 /* -prune is special: if it is encountered, then we won't
441 * descend into current directory. It doesn't matter whether
442 * action group (in which -prune sits) will succeed or not:
443 * find * -prune -name 'f*' -o -name 'm*' -- prunes every dir
444 * find * -name 'f*' -o -prune -name 'm*' -- prunes all dirs
445 * not starting with 'f' */
447 /* We invert TRUE bit (bit 0). Now 1 there means 'failure'.
448 * and bitwise OR in "rc |= TRUE ^ ap->f()" will:
449 * (1) make SKIP (-prune) bit stick; and (2) detect 'failure'.
450 * On return, bit is restored. */
453 while ((app = appp[++cur_group]) != NULL) {
454 rc &= ~TRUE; /* 'success' so far, clear TRUE bit */
457 ap = app[++cur_action];
458 if (!ap) /* all actions in group were successful */
459 return rc ^ TRUE; /* restore TRUE bit */
460 rc |= TRUE ^ ap->f(fileName, statbuf, ap);
461 #if ENABLE_FEATURE_FIND_NOT
462 if (ap->invert) rc ^= TRUE;
464 dbg("grp %d action %d rc:0x%x", cur_group, cur_action, rc);
465 if (rc & TRUE) /* current group failed, try next */
469 dbg("returning:0x%x", rc ^ TRUE);
470 return rc ^ TRUE; /* restore TRUE bit */
474 static char *strcpy_upcase(char *dst, const char *src)
478 unsigned char ch = *src++;
479 if (ch >= 'a' && ch <= 'z')
492 const char *tmp = bb_basename(fileName);
493 /* GNU findutils: find DIR/ -name DIR
494 * prints "DIR/" (DIR// prints "DIR//" etc).
495 * Need to strip trailing "/".
496 * Such names can come only from top-level names, but
497 * we can't do this before recursive_action() call,
498 * since then "find FILE/ -name FILE"
499 * would also work (on non-directories), which is wrong.
501 char *trunc_slash = NULL;
504 /* "foo/bar/[//...]" */
505 while (tmp != fileName && tmp[-1] == '/')
507 if (tmp == fileName) { /* entire fileName is "//.."? */
508 /* yes, convert "//..." to "/"
510 * find / -maxdepth 1 -name /: prints /
511 * find // -maxdepth 1 -name /: prints //
512 * find / -maxdepth 1 -name //: prints nothing
513 * find // -maxdepth 1 -name //: prints nothing
516 trunc_slash = (char*)tmp + 1;
518 /* no, it's "foo/bar/[//...]", go back to 'b' */
519 trunc_slash = (char*)tmp;
520 while (tmp != fileName && tmp[-1] != '/')
525 /* Was using FNM_PERIOD flag too,
526 * but somewhere between 4.1.20 and 4.4.0 GNU find stopped using it.
527 * find -name '*foo' should match .foo too:
529 if (trunc_slash) *trunc_slash = '\0';
531 r = fnmatch(ap->pattern, tmp, (ap->iname ? FNM_CASEFOLD : 0));
534 tmp = strcpy_upcase(alloca(strlen(tmp) + 1), tmp);
535 r = fnmatch(ap->pattern, tmp, 0);
537 if (trunc_slash) *trunc_slash = '/';
541 #if ENABLE_FEATURE_FIND_PATH
545 return fnmatch(ap->pattern, fileName, (ap->ipath ? FNM_CASEFOLD : 0)) == 0;
548 fileName = strcpy_upcase(alloca(strlen(fileName) + 1), fileName);
549 return fnmatch(ap->pattern, fileName, 0) == 0;
553 #if ENABLE_FEATURE_FIND_REGEX
557 if (regexec(&ap->compiled_pattern, fileName, 1, &match, 0 /*eflags*/))
558 return 0; /* no match */
560 return 0; /* match doesn't start at pos 0 */
561 if (fileName[match.rm_eo])
562 return 0; /* match doesn't end exactly at end of pathname */
566 #if ENABLE_FEATURE_FIND_TYPE
569 return ((statbuf->st_mode & S_IFMT) == ap->type_mask);
572 #if ENABLE_FEATURE_FIND_PERM
575 /* -perm [+/]mode: at least one of perm_mask bits are set */
576 if (ap->perm_char == '+' || ap->perm_char == '/')
577 return (statbuf->st_mode & ap->perm_mask) != 0;
578 /* -perm -mode: all of perm_mask are set */
579 if (ap->perm_char == '-')
580 return (statbuf->st_mode & ap->perm_mask) == ap->perm_mask;
581 /* -perm mode: file mode must match perm_mask */
582 return (statbuf->st_mode & 07777) == ap->perm_mask;
585 #if ENABLE_FEATURE_FIND_MTIME
588 time_t file_age = time(NULL) - statbuf->st_mtime;
589 time_t mtime_secs = ap->mtime_days * 24*60*60;
590 if (ap->mtime_char == '+')
591 return file_age >= mtime_secs + 24*60*60;
592 if (ap->mtime_char == '-')
593 return file_age < mtime_secs;
594 /* just numeric mtime */
595 return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
598 #if ENABLE_FEATURE_FIND_MMIN
601 time_t file_age = time(NULL) - statbuf->st_mtime;
602 time_t mmin_secs = ap->mmin_mins * 60;
603 if (ap->mmin_char == '+')
604 return file_age >= mmin_secs + 60;
605 if (ap->mmin_char == '-')
606 return file_age < mmin_secs;
607 /* just numeric mmin */
608 return file_age >= mmin_secs && file_age < (mmin_secs + 60);
611 #if ENABLE_FEATURE_FIND_NEWER
614 return (ap->newer_mtime < statbuf->st_mtime);
617 #if ENABLE_FEATURE_FIND_INUM
620 return (statbuf->st_ino == ap->inode_num);
623 #if ENABLE_FEATURE_FIND_EXEC
624 static int do_exec(action_exec *ap, const char *fileName)
627 # if ENABLE_FEATURE_FIND_EXEC_PLUS
628 int size = ap->exec_argc + ap->filelist_idx + 1;
630 int size = ap->exec_argc + 1;
632 # if ENABLE_USE_PORTABLE_CODE
633 char **argv = alloca(sizeof(char*) * size);
634 # else /* gcc 4.3.1 generates smaller code: */
639 for (i = 0; i < ap->exec_argc; i++) {
640 const char *arg = ap->exec_argv[i];
642 # if ENABLE_FEATURE_FIND_EXEC_PLUS
644 /* Handling "-exec +"
645 * Only one exec_argv[i] has substitution in it.
646 * Expand that one exec_argv[i] into file list.
648 if (ap->subst_count[i] == 0) {
649 *pp++ = xstrdup(arg);
652 while (ap->filelist[j]) {
653 /* 2nd arg here should be ap->subst_count[i], but it is always 1: */
654 *pp++ = xmalloc_substitute_string(arg, 1, "{}", ap->filelist[j]);
655 free(ap->filelist[j]);
662 /* Handling "-exec ;" */
663 *pp++ = xmalloc_substitute_string(arg, ap->subst_count[i], "{}", fileName);
666 *pp = NULL; /* terminate the list */
668 # if ENABLE_FEATURE_FIND_EXEC_PLUS
670 ap->filelist[0] = NULL;
671 ap->filelist_idx = 0;
676 rc = spawn_and_wait(argv);
678 bb_simple_perror_msg(argv[0]);
683 return rc == 0; /* return 1 if exitcode 0 */
687 # if ENABLE_FEATURE_FIND_EXEC_PLUS
691 ap->filelist = xrealloc_vector(ap->filelist, 8, ap->filelist_idx);
692 ap->filelist[ap->filelist_idx++] = xstrdup(fileName);
693 ap->file_len += strlen(fileName) + sizeof(char*) + 1;
694 /* If we have lots of files already, exec the command */
696 if (ap->file_len >= G.max_argv_len)
697 rc = do_exec(ap, NULL);
701 return do_exec(ap, fileName);
703 # if ENABLE_FEATURE_FIND_EXEC_PLUS
704 static int flush_exec_plus(void)
708 action ***appp = G.actions;
709 while ((app = *appp++) != NULL) {
710 while ((ap = *app++) != NULL) {
711 if (ap->f == (action_fp)func_exec) {
712 action_exec *ae = (void*)ap;
713 if (ae->filelist_idx != 0) {
714 int rc = do_exec(ae, NULL);
715 # if ENABLE_FEATURE_FIND_NOT
716 if (ap->invert) rc = !rc;
728 #if ENABLE_FEATURE_FIND_USER
731 return (statbuf->st_uid == ap->uid);
734 #if ENABLE_FEATURE_FIND_GROUP
737 return (statbuf->st_gid == ap->gid);
740 #if ENABLE_FEATURE_FIND_PRINT0
743 printf("%s%c", fileName, '\0');
752 #if ENABLE_FEATURE_FIND_PAREN
755 return exec_actions(ap->subexpr, fileName, statbuf);
758 #if ENABLE_FEATURE_FIND_SIZE
761 if (ap->size_char == '+')
762 return statbuf->st_size > ap->size;
763 if (ap->size_char == '-')
764 return statbuf->st_size < ap->size;
765 return statbuf->st_size == ap->size;
768 #if ENABLE_FEATURE_FIND_PRUNE
770 * -prune: if -depth is not given, return true and do not descend
771 * current dir; if -depth is given, return false with no effect.
773 * find dir -name 'asm-*' -prune -o -name '*.[chS]' -print
780 #if ENABLE_FEATURE_FIND_DELETE
784 if (S_ISDIR(statbuf->st_mode)) {
785 /* "find . -delete" skips rmdir(".") */
787 if (NOT_LONE_CHAR(fileName, '.'))
788 rc = rmdir(fileName);
790 rc = unlink(fileName);
793 bb_simple_perror_msg(fileName);
797 #if ENABLE_FEATURE_FIND_CONTEXT
800 security_context_t con;
803 if (G.recurse_flags & ACTION_FOLLOWLINKS) {
804 rc = getfilecon(fileName, &con);
806 rc = lgetfilecon(fileName, &con);
810 rc = strcmp(ap->context, con);
815 #if ENABLE_FEATURE_FIND_LINKS
818 switch(ap->links_char) {
819 case '-' : return (statbuf->st_nlink < ap->links_count);
820 case '+' : return (statbuf->st_nlink > ap->links_count);
821 default: return (statbuf->st_nlink == ap->links_count);
826 static int FAST_FUNC fileAction(const char *fileName,
827 struct stat *statbuf,
828 void *userData UNUSED_PARAM,
829 int depth IF_NOT_FEATURE_FIND_MAXDEPTH(UNUSED_PARAM))
834 #if ENABLE_FEATURE_FIND_XDEV
835 if (S_ISDIR(statbuf->st_mode) && G.xdev_count) {
837 for (i = 0; i < G.xdev_count; i++) {
838 if (G.xdev_dev[i] == statbuf->st_dev)
841 //bb_error_msg("'%s': not same fs", fileName);
847 #if ENABLE_FEATURE_FIND_MAXDEPTH
848 if (depth < G.minmaxdepth[0]) {
850 return TRUE; /* skip this, continue recursing */
851 return SKIP; /* stop recursing */
853 if (depth > G.minmaxdepth[1])
854 return SKIP; /* stop recursing */
857 r = exec_actions(G.actions, fileName, statbuf);
858 /* Had no explicit -print[0] or -exec? then print */
859 if ((r & TRUE) && G.need_print)
862 #if ENABLE_FEATURE_FIND_MAXDEPTH
863 if (S_ISDIR(statbuf->st_mode)) {
864 if (depth == G.minmaxdepth[1])
868 /* -xdev stops on mountpoints, but AFTER mountpoit itself
869 * is processed as usual */
874 /* Cannot return 0: our caller, recursive_action(),
875 * will perror() and skip dirs (if called on dir) */
876 return (r & SKIP) ? SKIP : TRUE;
880 #if ENABLE_FEATURE_FIND_TYPE
881 static int find_type(const char *type)
887 else if (*type == 'c')
889 else if (*type == 'd')
891 else if (*type == 'p')
893 else if (*type == 'f')
895 else if (*type == 'l')
897 else if (*type == 's')
900 if (mask == 0 || type[1] != '\0')
901 bb_error_msg_and_die(bb_msg_invalid_arg_to, type, "-type");
907 #if ENABLE_FEATURE_FIND_PERM \
908 || ENABLE_FEATURE_FIND_MTIME || ENABLE_FEATURE_FIND_MMIN \
909 || ENABLE_FEATURE_FIND_SIZE || ENABLE_FEATURE_FIND_LINKS
910 static const char* plus_minus_num(const char* str)
912 if (*str == '-' || *str == '+')
918 /* Say no to GCCism */
919 #define USE_NESTED_FUNCTION 0
921 #if !USE_NESTED_FUNCTION
926 IF_FEATURE_FIND_NOT( bool invert_flag; )
928 static action* alloc_action(struct pp_locals *ppl, int sizeof_struct, action_fp f)
930 action *ap = xzalloc(sizeof_struct);
932 action ***group = &ppl->appp[ppl->cur_group];
933 *group = app = xrealloc(*group, (ppl->cur_action+2) * sizeof(ppl->appp[0][0]));
934 app[ppl->cur_action++] = ap;
935 app[ppl->cur_action] = NULL;
937 IF_FEATURE_FIND_NOT( ap->invert = ppl->invert_flag; )
938 IF_FEATURE_FIND_NOT( ppl->invert_flag = 0; )
943 static action*** parse_params(char **argv)
947 IF_FEATURE_FIND_XDEV( OPT_XDEV ,)
948 IF_FEATURE_FIND_DEPTH( OPT_DEPTH ,)
951 IF_FEATURE_FIND_NOT( PARM_char_not ,)
955 IF_FEATURE_FIND_NOT( PARM_not ,)
958 IF_FEATURE_FIND_PRINT0( PARM_print0 ,)
959 IF_FEATURE_FIND_PRUNE( PARM_prune ,)
960 IF_FEATURE_FIND_DELETE( PARM_delete ,)
961 IF_FEATURE_FIND_EXEC( PARM_exec ,)
962 IF_FEATURE_FIND_PAREN( PARM_char_brace,)
963 /* All options/actions starting from here require argument */
966 IF_FEATURE_FIND_PATH( PARM_path ,)
968 /* -wholename is a synonym for -path */
969 /* We support it because Linux kernel's "make tags" uses it */
970 IF_FEATURE_FIND_PATH( PARM_wholename ,)
972 IF_FEATURE_FIND_PATH( PARM_ipath ,)
973 IF_FEATURE_FIND_REGEX( PARM_regex ,)
974 IF_FEATURE_FIND_TYPE( PARM_type ,)
975 IF_FEATURE_FIND_PERM( PARM_perm ,)
976 IF_FEATURE_FIND_MTIME( PARM_mtime ,)
977 IF_FEATURE_FIND_MMIN( PARM_mmin ,)
978 IF_FEATURE_FIND_NEWER( PARM_newer ,)
979 IF_FEATURE_FIND_INUM( PARM_inum ,)
980 IF_FEATURE_FIND_USER( PARM_user ,)
981 IF_FEATURE_FIND_GROUP( PARM_group ,)
982 IF_FEATURE_FIND_SIZE( PARM_size ,)
983 IF_FEATURE_FIND_CONTEXT(PARM_context ,)
984 IF_FEATURE_FIND_LINKS( PARM_links ,)
985 IF_FEATURE_FIND_MAXDEPTH(OPT_MINDEPTH,OPT_MAXDEPTH,)
988 static const char params[] ALIGN1 =
990 IF_FEATURE_FIND_XDEV( "-xdev\0" )
991 IF_FEATURE_FIND_DEPTH( "-depth\0" )
994 IF_FEATURE_FIND_NOT( "!\0" )
998 IF_FEATURE_FIND_NOT( "-not\0" )
1001 IF_FEATURE_FIND_PRINT0( "-print0\0" )
1002 IF_FEATURE_FIND_PRUNE( "-prune\0" )
1003 IF_FEATURE_FIND_DELETE( "-delete\0" )
1004 IF_FEATURE_FIND_EXEC( "-exec\0" )
1005 IF_FEATURE_FIND_PAREN( "(\0" )
1006 /* All options/actions starting from here require argument */
1009 IF_FEATURE_FIND_PATH( "-path\0" )
1011 IF_FEATURE_FIND_PATH( "-wholename\0")
1013 IF_FEATURE_FIND_PATH( "-ipath\0" )
1014 IF_FEATURE_FIND_REGEX( "-regex\0" )
1015 IF_FEATURE_FIND_TYPE( "-type\0" )
1016 IF_FEATURE_FIND_PERM( "-perm\0" )
1017 IF_FEATURE_FIND_MTIME( "-mtime\0" )
1018 IF_FEATURE_FIND_MMIN( "-mmin\0" )
1019 IF_FEATURE_FIND_NEWER( "-newer\0" )
1020 IF_FEATURE_FIND_INUM( "-inum\0" )
1021 IF_FEATURE_FIND_USER( "-user\0" )
1022 IF_FEATURE_FIND_GROUP( "-group\0" )
1023 IF_FEATURE_FIND_SIZE( "-size\0" )
1024 IF_FEATURE_FIND_CONTEXT("-context\0")
1025 IF_FEATURE_FIND_LINKS( "-links\0" )
1026 IF_FEATURE_FIND_MAXDEPTH("-mindepth\0""-maxdepth\0")
1029 #if !USE_NESTED_FUNCTION
1030 struct pp_locals ppl;
1031 #define appp (ppl.appp )
1032 #define cur_group (ppl.cur_group )
1033 #define cur_action (ppl.cur_action )
1034 #define invert_flag (ppl.invert_flag)
1035 #define ALLOC_ACTION(name) (action_##name*)alloc_action(&ppl, sizeof(action_##name), (action_fp) func_##name)
1039 unsigned cur_action;
1040 IF_FEATURE_FIND_NOT( bool invert_flag; )
1042 /* This is the only place in busybox where we use nested function.
1043 * So far more standard alternatives were bigger. */
1044 /* Auto decl suppresses "func without a prototype" warning: */
1045 auto action* alloc_action(int sizeof_struct, action_fp f);
1046 action* alloc_action(int sizeof_struct, action_fp f)
1049 appp[cur_group] = xrealloc(appp[cur_group], (cur_action+2) * sizeof(appp[0][0]));
1050 appp[cur_group][cur_action++] = ap = xzalloc(sizeof_struct);
1051 appp[cur_group][cur_action] = NULL;
1053 IF_FEATURE_FIND_NOT( ap->invert = invert_flag; )
1054 IF_FEATURE_FIND_NOT( invert_flag = 0; )
1057 #define ALLOC_ACTION(name) (action_##name*)alloc_action(sizeof(action_##name), (action_fp) func_##name)
1062 IF_FEATURE_FIND_NOT( invert_flag = 0; )
1063 appp = xzalloc(2 * sizeof(appp[0])); /* appp[0],[1] == NULL */
1066 const char *arg = argv[0];
1067 int parm = index_in_strings(params, arg);
1068 const char *arg1 = argv[1];
1070 dbg("arg:'%s' arg1:'%s' parm:%d PARM_type:%d", arg, arg1, parm, PARM_type);
1072 if (parm >= PARM_name) {
1073 /* All options/actions starting from -name require argument */
1075 bb_error_msg_and_die(bb_msg_requires_arg, arg);
1079 /* We can use big switch() here, but on i386
1080 * it doesn't give smaller code. Other arches? */
1082 /* Options always return true. They always take effect
1083 * rather than being processed only when their place in the
1084 * expression is reached.
1087 if (parm == OPT_FOLLOW) {
1088 dbg("follow enabled: %d", __LINE__);
1089 G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
1091 #if ENABLE_FEATURE_FIND_XDEV
1092 else if (parm == OPT_XDEV) {
1093 dbg("%d", __LINE__);
1097 #if ENABLE_FEATURE_FIND_MAXDEPTH
1098 else if (parm == OPT_MINDEPTH || parm == OPT_MINDEPTH + 1) {
1099 dbg("%d", __LINE__);
1100 G.minmaxdepth[parm - OPT_MINDEPTH] = xatoi_positive(arg1);
1103 #if ENABLE_FEATURE_FIND_DEPTH
1104 else if (parm == OPT_DEPTH) {
1105 dbg("%d", __LINE__);
1106 G.recurse_flags |= ACTION_DEPTHFIRST;
1109 /* Actions are grouped by operators
1110 * ( expr ) Force precedence
1111 * ! expr True if expr is false
1112 * -not expr Same as ! expr
1113 * expr1 [-a[nd]] expr2 And; expr2 is not evaluated if expr1 is false
1114 * expr1 -o[r] expr2 Or; expr2 is not evaluated if expr1 is true
1115 * expr1 , expr2 List; both expr1 and expr2 are always evaluated
1116 * We implement: (), -a, -o
1119 else if (parm == PARM_a IF_DESKTOP(|| parm == PARM_and)) {
1120 dbg("%d", __LINE__);
1121 /* no further special handling required */
1123 else if (parm == PARM_o IF_DESKTOP(|| parm == PARM_or)) {
1124 dbg("%d", __LINE__);
1125 /* start new OR group */
1127 appp = xrealloc(appp, (cur_group+2) * sizeof(appp[0]));
1128 /*appp[cur_group] = NULL; - already NULL */
1129 appp[cur_group+1] = NULL;
1132 #if ENABLE_FEATURE_FIND_NOT
1133 else if (parm == PARM_char_not IF_DESKTOP(|| parm == PARM_not)) {
1134 /* also handles "find ! ! -name 'foo*'" */
1136 dbg("invert_flag:%d", invert_flag);
1140 else if (parm == PARM_print) {
1141 dbg("%d", __LINE__);
1143 (void) ALLOC_ACTION(print);
1145 #if ENABLE_FEATURE_FIND_PRINT0
1146 else if (parm == PARM_print0) {
1147 dbg("%d", __LINE__);
1149 (void) ALLOC_ACTION(print0);
1152 #if ENABLE_FEATURE_FIND_PRUNE
1153 else if (parm == PARM_prune) {
1154 dbg("%d", __LINE__);
1155 (void) ALLOC_ACTION(prune);
1158 #if ENABLE_FEATURE_FIND_DELETE
1159 else if (parm == PARM_delete) {
1160 dbg("%d", __LINE__);
1162 G.recurse_flags |= ACTION_DEPTHFIRST;
1163 (void) ALLOC_ACTION(delete);
1166 #if ENABLE_FEATURE_FIND_EXEC
1167 else if (parm == PARM_exec) {
1170 IF_FEATURE_FIND_EXEC_PLUS(int all_subst = 0;)
1171 dbg("%d", __LINE__);
1173 ap = ALLOC_ACTION(exec);
1174 ap->exec_argv = ++argv; /* first arg after -exec */
1175 /*ap->exec_argc = 0; - ALLOC_ACTION did it */
1177 if (!*argv) /* did not see ';' or '+' until end */
1178 bb_error_msg_and_die(bb_msg_requires_arg, "-exec");
1179 // find -exec echo Foo ">{}<" ";"
1180 // executes "echo Foo >FILENAME<",
1181 // find -exec echo Foo ">{}<" "+"
1182 // executes "echo Foo FILENAME1 FILENAME2 FILENAME3...".
1183 if ((argv[0][0] == ';' || argv[0][0] == '+')
1184 && argv[0][1] == '\0'
1186 # if ENABLE_FEATURE_FIND_EXEC_PLUS
1187 if (argv[0][0] == '+')
1188 ap->filelist = xzalloc(sizeof(ap->filelist[0]));
1195 if (ap->exec_argc == 0)
1196 bb_error_msg_and_die(bb_msg_requires_arg, arg);
1197 ap->subst_count = xmalloc(ap->exec_argc * sizeof(int));
1200 ap->subst_count[i] = count_strstr(ap->exec_argv[i], "{}");
1201 IF_FEATURE_FIND_EXEC_PLUS(all_subst += ap->subst_count[i];)
1203 # if ENABLE_FEATURE_FIND_EXEC_PLUS
1205 * coreutils expects {} to appear only once in "-exec +"
1207 if (all_subst != 1 && ap->filelist)
1208 bb_error_msg_and_die("only one '{}' allowed for -exec +");
1212 #if ENABLE_FEATURE_FIND_PAREN
1213 else if (parm == PARM_char_brace) {
1216 unsigned nested = 1;
1218 dbg("%d", __LINE__);
1222 bb_error_msg_and_die("unpaired '('");
1223 if (LONE_CHAR(*endarg, '('))
1225 else if (LONE_CHAR(*endarg, ')') && !--nested) {
1230 ap = ALLOC_ACTION(paren);
1231 ap->subexpr = parse_params(argv + 1);
1232 *endarg = (char*) ")"; /* restore NULLed parameter */
1236 else if (parm == PARM_name || parm == PARM_iname) {
1238 dbg("%d", __LINE__);
1239 ap = ALLOC_ACTION(name);
1241 ap->iname = (parm == PARM_iname);
1243 #if ENABLE_FEATURE_FIND_PATH
1244 else if (parm == PARM_path IF_DESKTOP(|| parm == PARM_wholename) || parm == PARM_ipath) {
1246 dbg("%d", __LINE__);
1247 ap = ALLOC_ACTION(path);
1249 ap->ipath = (parm == PARM_ipath);
1252 #if ENABLE_FEATURE_FIND_REGEX
1253 else if (parm == PARM_regex) {
1255 dbg("%d", __LINE__);
1256 ap = ALLOC_ACTION(regex);
1257 xregcomp(&ap->compiled_pattern, arg1, 0 /*cflags*/);
1260 #if ENABLE_FEATURE_FIND_TYPE
1261 else if (parm == PARM_type) {
1263 ap = ALLOC_ACTION(type);
1264 ap->type_mask = find_type(arg1);
1265 dbg("created:type mask:%x", ap->type_mask);
1268 #if ENABLE_FEATURE_FIND_PERM
1269 /* -perm BITS File's mode bits are exactly BITS (octal or symbolic).
1270 * Symbolic modes use mode 0 as a point of departure.
1271 * -perm -BITS All of the BITS are set in file's mode.
1272 * -perm [+/]BITS At least one of the BITS is set in file's mode.
1274 else if (parm == PARM_perm) {
1276 dbg("%d", __LINE__);
1277 ap = ALLOC_ACTION(perm);
1278 ap->perm_char = arg1[0];
1279 arg1 = (arg1[0] == '/' ? arg1+1 : plus_minus_num(arg1));
1280 /*ap->perm_mask = 0; - ALLOC_ACTION did it */
1281 ap->perm_mask = bb_parse_mode(arg1, ap->perm_mask);
1282 if (ap->perm_mask == (mode_t)-1)
1283 bb_error_msg_and_die("invalid mode '%s'", arg1);
1286 #if ENABLE_FEATURE_FIND_MTIME
1287 else if (parm == PARM_mtime) {
1289 dbg("%d", __LINE__);
1290 ap = ALLOC_ACTION(mtime);
1291 ap->mtime_char = arg1[0];
1292 ap->mtime_days = xatoul(plus_minus_num(arg1));
1295 #if ENABLE_FEATURE_FIND_MMIN
1296 else if (parm == PARM_mmin) {
1298 dbg("%d", __LINE__);
1299 ap = ALLOC_ACTION(mmin);
1300 ap->mmin_char = arg1[0];
1301 ap->mmin_mins = xatoul(plus_minus_num(arg1));
1304 #if ENABLE_FEATURE_FIND_NEWER
1305 else if (parm == PARM_newer) {
1306 struct stat stat_newer;
1308 dbg("%d", __LINE__);
1309 ap = ALLOC_ACTION(newer);
1310 xstat(arg1, &stat_newer);
1311 ap->newer_mtime = stat_newer.st_mtime;
1314 #if ENABLE_FEATURE_FIND_INUM
1315 else if (parm == PARM_inum) {
1317 dbg("%d", __LINE__);
1318 ap = ALLOC_ACTION(inum);
1319 ap->inode_num = xatoul(arg1);
1322 #if ENABLE_FEATURE_FIND_USER
1323 else if (parm == PARM_user) {
1325 dbg("%d", __LINE__);
1326 ap = ALLOC_ACTION(user);
1327 ap->uid = bb_strtou(arg1, NULL, 10);
1329 ap->uid = xuname2uid(arg1);
1332 #if ENABLE_FEATURE_FIND_GROUP
1333 else if (parm == PARM_group) {
1335 dbg("%d", __LINE__);
1336 ap = ALLOC_ACTION(group);
1337 ap->gid = bb_strtou(arg1, NULL, 10);
1339 ap->gid = xgroup2gid(arg1);
1342 #if ENABLE_FEATURE_FIND_SIZE
1343 else if (parm == PARM_size) {
1344 /* -size n[bckw]: file uses n units of space
1345 * b (default): units are 512-byte blocks
1351 #define XATOU_SFX xatoull_sfx
1353 #define XATOU_SFX xatoul_sfx
1355 static const struct suffix_mult find_suffixes[] = {
1364 dbg("%d", __LINE__);
1365 ap = ALLOC_ACTION(size);
1366 ap->size_char = arg1[0];
1367 ap->size = XATOU_SFX(plus_minus_num(arg1), find_suffixes);
1370 #if ENABLE_FEATURE_FIND_CONTEXT
1371 else if (parm == PARM_context) {
1373 dbg("%d", __LINE__);
1374 ap = ALLOC_ACTION(context);
1375 /*ap->context = NULL; - ALLOC_ACTION did it */
1376 /* SELinux headers erroneously declare non-const parameter */
1377 if (selinux_raw_to_trans_context((char*)arg1, &ap->context))
1378 bb_simple_perror_msg(arg1);
1381 #if ENABLE_FEATURE_FIND_LINKS
1382 else if (parm == PARM_links) {
1384 dbg("%d", __LINE__);
1385 ap = ALLOC_ACTION(links);
1386 ap->links_char = arg1[0];
1387 ap->links_count = xatoul(plus_minus_num(arg1));
1391 bb_error_msg("unrecognized: %s", arg);
1396 dbg("exiting %s", __func__);
1404 int find_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1405 int find_main(int argc UNUSED_PARAM, char **argv)
1407 int i, firstopt, status = EXIT_SUCCESS;
1408 char **past_HLP, *saved;
1412 /* "find -type f" + getopt("+HLP") => disaster.
1413 * Need to avoid getopt running into a non-HLP option.
1414 * Do this by temporarily storing NULL there:
1418 saved = *++past_HLP;
1421 if (saved[0] != '-')
1424 break; /* it is "-" */
1425 if ((saved+1)[strspn(saved+1, "HLP")] != '\0')
1429 /* "+": stop on first non-option */
1430 i = getopt32(argv, "+HLP");
1432 G.recurse_flags |= ACTION_FOLLOWLINKS_L0 | ACTION_DANGLING_OK;
1434 G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
1435 /* -P is default and is ignored */
1436 argv = past_HLP; /* same result as "argv += optind;" */
1439 for (firstopt = 0; argv[firstopt]; firstopt++) {
1440 if (argv[firstopt][0] == '-')
1442 if (ENABLE_FEATURE_FIND_NOT && LONE_CHAR(argv[firstopt], '!'))
1444 if (ENABLE_FEATURE_FIND_PAREN && LONE_CHAR(argv[firstopt], '('))
1447 if (firstopt == 0) {
1448 *--argv = (char*)".";
1452 G.actions = parse_params(&argv[firstopt]);
1453 argv[firstopt] = NULL;
1455 #if ENABLE_FEATURE_FIND_XDEV
1459 G.xdev_count = firstopt;
1460 G.xdev_dev = xzalloc(G.xdev_count * sizeof(G.xdev_dev[0]));
1461 for (i = 0; argv[i]; i++) {
1462 /* not xstat(): shouldn't bomb out on
1463 * "find not_exist exist -xdev" */
1464 if (stat(argv[i], &stbuf) == 0)
1465 G.xdev_dev[i] = stbuf.st_dev;
1466 /* else G.xdev_dev[i] stays 0 and
1467 * won't match any real device dev_t
1473 for (i = 0; argv[i]; i++) {
1474 if (!recursive_action(argv[i],
1475 G.recurse_flags,/* flags */
1476 fileAction, /* file action */
1477 fileAction, /* dir action */
1478 NULL, /* user data */
1481 status |= EXIT_FAILURE;
1485 IF_FEATURE_FIND_EXEC_PLUS(status |= flush_exec_plus();)