find: implement -quit
[oweals/busybox.git] / findutils / find.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini find implementation for busybox
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Reworked by David Douthitt <n9ubh@callsign.net> and
8  *  Matt Kraai <kraai@alumni.carnegiemellon.edu>.
9  *
10  * Licensed under GPLv2, see file LICENSE in this source tree.
11  */
12 /* findutils-4.1.20:
13  *
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' '{}  {}' ';'
23  * file.txt  file.txt
24  * (strace: execve("/bin/echo", ["echo", "file.txt  file.txt"], [ 30 vars ]))
25  * # find file.txt -exec 'echo' '{}  {}' ';' -print -exec pwd ';'
26  * file.txt  file.txt
27  * file.txt
28  * /tmp
29  * # find -name '*.c' -o -name '*.h'
30  * [shows files, *.c and *.h intermixed]
31  * # find file.txt -name '*f*' -o -name '*t*'
32  * file.txt
33  * # find file.txt -name '*z*' -o -name '*t*'
34  * file.txt
35  * # find file.txt -name '*f*' -o -name '*z*'
36  * file.txt
37  *
38  * # find t z -name '*t*' -print -o -name '*z*'
39  * t
40  * # find t z t z -name '*t*' -o -name '*z*' -print
41  * z
42  * z
43  * # find t z t z '(' -name '*t*' -o -name '*z*' ')' -o -print
44  * (no output)
45  */
46 /* Testing script
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
52  */
53 //config:config FIND
54 //config:       bool "find (14 kb)"
55 //config:       default y
56 //config:       help
57 //config:       find is used to search your system to find specified files.
58 //config:
59 //config:config FEATURE_FIND_PRINT0
60 //config:       bool "Enable -print0: NUL-terminated output"
61 //config:       default y
62 //config:       depends on FIND
63 //config:       help
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.
68 //config:
69 //config:config FEATURE_FIND_MTIME
70 //config:       bool "Enable -mtime: modified time matching"
71 //config:       default y
72 //config:       depends on FIND
73 //config:       help
74 //config:       Allow searching based on the modification time of
75 //config:       files, in days.
76 //config:
77 //config:config FEATURE_FIND_MMIN
78 //config:       bool "Enable -mmin: modified time matching by minutes"
79 //config:       default y
80 //config:       depends on FIND
81 //config:       help
82 //config:       Allow searching based on the modification time of
83 //config:       files, in minutes.
84 //config:
85 //config:config FEATURE_FIND_PERM
86 //config:       bool "Enable -perm: permissions matching"
87 //config:       default y
88 //config:       depends on FIND
89 //config:
90 //config:config FEATURE_FIND_TYPE
91 //config:       bool "Enable -type: file type matching (file/dir/link/...)"
92 //config:       default y
93 //config:       depends on FIND
94 //config:       help
95 //config:       Enable searching based on file type (file,
96 //config:       directory, socket, device, etc.).
97 //config:
98 //config:config FEATURE_FIND_XDEV
99 //config:       bool "Enable -xdev: 'stay in filesystem'"
100 //config:       default y
101 //config:       depends on FIND
102 //config:
103 //config:config FEATURE_FIND_MAXDEPTH
104 //config:       bool "Enable -mindepth N and -maxdepth N"
105 //config:       default y
106 //config:       depends on FIND
107 //config:
108 //config:config FEATURE_FIND_NEWER
109 //config:       bool "Enable -newer: compare file modification times"
110 //config:       default y
111 //config:       depends on FIND
112 //config:       help
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.
115 //config:
116 //config:config FEATURE_FIND_INUM
117 //config:       bool "Enable -inum: inode number matching"
118 //config:       default y
119 //config:       depends on FIND
120 //config:
121 //config:config FEATURE_FIND_EXEC
122 //config:       bool "Enable -exec: execute commands"
123 //config:       default y
124 //config:       depends on FIND
125 //config:       help
126 //config:       Support the 'find -exec' option for executing commands based upon
127 //config:       the files matched.
128 //config:
129 //config:config FEATURE_FIND_EXEC_PLUS
130 //config:       bool "Enable -exec ... {} +"
131 //config:       default y
132 //config:       depends on FEATURE_FIND_EXEC
133 //config:       help
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)
138 //config:
139 //config:config FEATURE_FIND_USER
140 //config:       bool "Enable -user: username/uid matching"
141 //config:       default y
142 //config:       depends on FIND
143 //config:
144 //config:config FEATURE_FIND_GROUP
145 //config:       bool "Enable -group: group/gid matching"
146 //config:       default y
147 //config:       depends on FIND
148 //config:
149 //config:config FEATURE_FIND_NOT
150 //config:       bool "Enable the 'not' (!) operator"
151 //config:       default y
152 //config:       depends on FIND
153 //config:       help
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'.
157 //config:
158 //config:config FEATURE_FIND_DEPTH
159 //config:       bool "Enable -depth"
160 //config:       default y
161 //config:       depends on FIND
162 //config:       help
163 //config:       Process each directory's contents before the directory itself.
164 //config:
165 //config:config FEATURE_FIND_PAREN
166 //config:       bool "Enable parens in options"
167 //config:       default y
168 //config:       depends on FIND
169 //config:       help
170 //config:       Enable usage of parens '(' to specify logical order of arguments.
171 //config:
172 //config:config FEATURE_FIND_SIZE
173 //config:       bool "Enable -size: file size matching"
174 //config:       default y
175 //config:       depends on FIND
176 //config:
177 //config:config FEATURE_FIND_PRUNE
178 //config:       bool "Enable -prune: exclude subdirectories"
179 //config:       default y
180 //config:       depends on FIND
181 //config:       help
182 //config:       If the file is a directory, don't descend into it. Useful for
183 //config:       exclusion .svn and CVS directories.
184 //config:
185 //config:config FEATURE_FIND_QUIT
186 //config:       bool "Enable -quit: exit"
187 //config:       default y
188 //config:       depends on FIND
189 //config:       help
190 //config:       If this action is reached, 'find' exits.
191 //config:
192 //config:config FEATURE_FIND_DELETE
193 //config:       bool "Enable -delete: delete files/dirs"
194 //config:       default y
195 //config:       depends on FIND && FEATURE_FIND_DEPTH
196 //config:       help
197 //config:       Support the 'find -delete' option for deleting files and directories.
198 //config:       WARNING: This option can do much harm if used wrong. Busybox will not
199 //config:       try to protect the user from doing stupid things. Use with care.
200 //config:
201 //config:config FEATURE_FIND_PATH
202 //config:       bool "Enable -path: match pathname with shell pattern"
203 //config:       default y
204 //config:       depends on FIND
205 //config:       help
206 //config:       The -path option matches whole pathname instead of just filename.
207 //config:
208 //config:config FEATURE_FIND_REGEX
209 //config:       bool "Enable -regex: match pathname with regex"
210 //config:       default y
211 //config:       depends on FIND
212 //config:       help
213 //config:       The -regex option matches whole pathname against regular expression.
214 //config:
215 //config:config FEATURE_FIND_CONTEXT
216 //config:       bool "Enable -context: security context matching"
217 //config:       default n
218 //config:       depends on FIND && SELINUX
219 //config:       help
220 //config:       Support the 'find -context' option for matching security context.
221 //config:
222 //config:config FEATURE_FIND_LINKS
223 //config:       bool "Enable -links: link count matching"
224 //config:       default y
225 //config:       depends on FIND
226 //config:       help
227 //config:       Support the 'find -links' option for matching number of links.
228
229 //applet:IF_FIND(APPLET_NOEXEC(find, find, BB_DIR_USR_BIN, BB_SUID_DROP, find))
230
231 //kbuild:lib-$(CONFIG_FIND) += find.o
232
233 //usage:#define find_trivial_usage
234 //usage:       "[-HL] [PATH]... [OPTIONS] [ACTIONS]"
235 //usage:#define find_full_usage "\n\n"
236 //usage:       "Search for files and perform actions on them.\n"
237 //usage:       "First failed action stops processing of current file.\n"
238 //usage:       "Defaults: PATH is current directory, action is '-print'\n"
239 //usage:     "\n        -L,-follow      Follow symlinks"
240 //usage:     "\n        -H              ...on command line only"
241 //usage:        IF_FEATURE_FIND_XDEV(
242 //usage:     "\n        -xdev           Don't descend directories on other filesystems"
243 //usage:        )
244 //usage:        IF_FEATURE_FIND_MAXDEPTH(
245 //usage:     "\n        -maxdepth N     Descend at most N levels. -maxdepth 0 applies"
246 //usage:     "\n                        actions to command line arguments only"
247 //usage:     "\n        -mindepth N     Don't act on first N levels"
248 //usage:        )
249 //usage:        IF_FEATURE_FIND_DEPTH(
250 //usage:     "\n        -depth          Act on directory *after* traversing it"
251 //usage:        )
252 //usage:     "\n"
253 //usage:     "\nActions:"
254 //usage:        IF_FEATURE_FIND_PAREN(
255 //usage:     "\n        ( ACTIONS )     Group actions for -o / -a"
256 //usage:        )
257 //usage:        IF_FEATURE_FIND_NOT(
258 //usage:     "\n        ! ACT           Invert ACT's success/failure"
259 //usage:        )
260 //usage:     "\n        ACT1 [-a] ACT2  If ACT1 fails, stop, else do ACT2"
261 //usage:     "\n        ACT1 -o ACT2    If ACT1 succeeds, stop, else do ACT2"
262 //usage:     "\n                        Note: -a has higher priority than -o"
263 //usage:     "\n        -name PATTERN   Match file name (w/o directory name) to PATTERN"
264 //usage:     "\n        -iname PATTERN  Case insensitive -name"
265 //usage:        IF_FEATURE_FIND_PATH(
266 //usage:     "\n        -path PATTERN   Match path to PATTERN"
267 //usage:     "\n        -ipath PATTERN  Case insensitive -path"
268 //usage:        )
269 //usage:        IF_FEATURE_FIND_REGEX(
270 //usage:     "\n        -regex PATTERN  Match path to regex PATTERN"
271 //usage:        )
272 //usage:        IF_FEATURE_FIND_TYPE(
273 //usage:     "\n        -type X         File type is X (one of: f,d,l,b,c,s,p)"
274 //usage:        )
275 //usage:        IF_FEATURE_FIND_PERM(
276 //usage:     "\n        -perm MASK      At least one mask bit (+MASK), all bits (-MASK),"
277 //usage:     "\n                        or exactly MASK bits are set in file's mode"
278 //usage:        )
279 //usage:        IF_FEATURE_FIND_MTIME(
280 //usage:     "\n        -mtime DAYS     mtime is greater than (+N), less than (-N),"
281 //usage:     "\n                        or exactly N days in the past"
282 //usage:        )
283 //usage:        IF_FEATURE_FIND_MMIN(
284 //usage:     "\n        -mmin MINS      mtime is greater than (+N), less than (-N),"
285 //usage:     "\n                        or exactly N minutes in the past"
286 //usage:        )
287 //usage:        IF_FEATURE_FIND_NEWER(
288 //usage:     "\n        -newer FILE     mtime is more recent than FILE's"
289 //usage:        )
290 //usage:        IF_FEATURE_FIND_INUM(
291 //usage:     "\n        -inum N         File has inode number N"
292 //usage:        )
293 //usage:        IF_FEATURE_FIND_USER(
294 //usage:     "\n        -user NAME/ID   File is owned by given user"
295 //usage:        )
296 //usage:        IF_FEATURE_FIND_GROUP(
297 //usage:     "\n        -group NAME/ID  File is owned by given group"
298 //usage:        )
299 //usage:        IF_FEATURE_FIND_SIZE(
300 //usage:     "\n        -size N[bck]    File size is N (c:bytes,k:kbytes,b:512 bytes(def.))"
301 //usage:     "\n                        +/-N: file size is bigger/smaller than N"
302 //usage:        )
303 //usage:        IF_FEATURE_FIND_LINKS(
304 //usage:     "\n        -links N        Number of links is greater than (+N), less than (-N),"
305 //usage:     "\n                        or exactly N"
306 //usage:        )
307 //usage:        IF_FEATURE_FIND_CONTEXT(
308 //usage:     "\n        -context CTX    File has specified security context"
309 //usage:        )
310 //usage:        IF_FEATURE_FIND_PRUNE(
311 //usage:     "\n        -prune          If current file is directory, don't descend into it"
312 //usage:        )
313 //usage:     "\nIf none of the following actions is specified, -print is assumed"
314 //usage:     "\n        -print          Print file name"
315 //usage:        IF_FEATURE_FIND_PRINT0(
316 //usage:     "\n        -print0         Print file name, NUL terminated"
317 //usage:        )
318 //usage:        IF_FEATURE_FIND_EXEC(
319 //usage:     "\n        -exec CMD ARG ; Run CMD with all instances of {} replaced by"
320 //usage:     "\n                        file name. Fails if CMD exits with nonzero"
321 //usage:        )
322 //usage:        IF_FEATURE_FIND_EXEC_PLUS(
323 //usage:     "\n        -exec CMD ARG + Run CMD with {} replaced by list of file names"
324 //usage:        )
325 //usage:        IF_FEATURE_FIND_DELETE(
326 //usage:     "\n        -delete         Delete current file/directory. Turns on -depth option"
327 //usage:        )
328 //usage:        IF_FEATURE_FIND_QUIT(
329 //usage:     "\n        -quit           Exit"
330 //usage:        )
331 //usage:
332 //usage:#define find_example_usage
333 //usage:       "$ find / -name passwd\n"
334 //usage:       "/etc/passwd\n"
335
336 #include <fnmatch.h>
337 #include "libbb.h"
338 #include "common_bufsiz.h"
339 #if ENABLE_FEATURE_FIND_REGEX
340 # include "xregex.h"
341 #endif
342 /* GNUism: */
343 #ifndef FNM_CASEFOLD
344 # define FNM_CASEFOLD 0
345 #endif
346
347 #if 1
348 # define dbg(...) ((void)0)
349 #else
350 # define dbg(...) bb_error_msg(__VA_ARGS__)
351 #endif
352
353
354 /* This is a NOEXEC applet. Be very careful! */
355
356
357 typedef int (*action_fp)(const char *fileName, const struct stat *statbuf, void *) FAST_FUNC;
358
359 typedef struct {
360         action_fp f;
361 #if ENABLE_FEATURE_FIND_NOT
362         bool invert;
363 #endif
364 } action;
365
366 #define ACTS(name, ...) typedef struct { action a; __VA_ARGS__ } action_##name;
367 #define ACTF(name) \
368         static int FAST_FUNC func_##name(const char *fileName UNUSED_PARAM, \
369                 const struct stat *statbuf UNUSED_PARAM, \
370                 action_##name* ap UNUSED_PARAM)
371
372                         ACTS(print)
373                         ACTS(name,  const char *pattern; bool iname;)
374 IF_FEATURE_FIND_PATH(   ACTS(path,  const char *pattern; bool ipath;))
375 IF_FEATURE_FIND_REGEX(  ACTS(regex, regex_t compiled_pattern;))
376 IF_FEATURE_FIND_PRINT0( ACTS(print0))
377 IF_FEATURE_FIND_TYPE(   ACTS(type,  int type_mask;))
378 IF_FEATURE_FIND_PERM(   ACTS(perm,  char perm_char; mode_t perm_mask;))
379 IF_FEATURE_FIND_MTIME(  ACTS(mtime, char mtime_char; unsigned mtime_days;))
380 IF_FEATURE_FIND_MMIN(   ACTS(mmin,  char mmin_char; unsigned mmin_mins;))
381 IF_FEATURE_FIND_NEWER(  ACTS(newer, time_t newer_mtime;))
382 IF_FEATURE_FIND_INUM(   ACTS(inum,  ino_t inode_num;))
383 IF_FEATURE_FIND_USER(   ACTS(user,  uid_t uid;))
384 IF_FEATURE_FIND_SIZE(   ACTS(size,  char size_char; off_t size;))
385 IF_FEATURE_FIND_CONTEXT(ACTS(context, security_context_t context;))
386 IF_FEATURE_FIND_PAREN(  ACTS(paren, action ***subexpr;))
387 IF_FEATURE_FIND_PRUNE(  ACTS(prune))
388 IF_FEATURE_FIND_QUIT(   ACTS(quit))
389 IF_FEATURE_FIND_DELETE( ACTS(delete))
390 IF_FEATURE_FIND_EXEC(   ACTS(exec,
391                                 char **exec_argv; /* -exec ARGS */
392                                 unsigned *subst_count;
393                                 int exec_argc; /* count of ARGS */
394                                 IF_FEATURE_FIND_EXEC_PLUS(
395                                         /*
396                                          * filelist is NULL if "exec ;"
397                                          * non-NULL if "exec +"
398                                          */
399                                         char **filelist;
400                                         int filelist_idx;
401                                         int file_len;
402                                 )
403                                 ))
404 IF_FEATURE_FIND_GROUP(  ACTS(group, gid_t gid;))
405 IF_FEATURE_FIND_LINKS(  ACTS(links, char links_char; int links_count;))
406
407 struct globals {
408         IF_FEATURE_FIND_XDEV(dev_t *xdev_dev;)
409         IF_FEATURE_FIND_XDEV(int xdev_count;)
410 #if ENABLE_FEATURE_FIND_MAXDEPTH
411         int minmaxdepth[2];
412 #endif
413         action ***actions;
414         smallint need_print;
415         smallint xdev_on;
416         smalluint exitstatus;
417         recurse_flags_t recurse_flags;
418         IF_FEATURE_FIND_EXEC_PLUS(unsigned max_argv_len;)
419 } FIX_ALIASING;
420 #define G (*(struct globals*)bb_common_bufsiz1)
421 #define INIT_G() do { \
422         setup_common_bufsiz(); \
423         BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
424         /* we have to zero it out because of NOEXEC */ \
425         memset(&G, 0, sizeof(G)); \
426         IF_FEATURE_FIND_MAXDEPTH(G.minmaxdepth[1] = INT_MAX;) \
427         IF_FEATURE_FIND_EXEC_PLUS(G.max_argv_len = bb_arg_max() - 2048;) \
428         G.need_print = 1; \
429         G.recurse_flags = ACTION_RECURSE; \
430 } while (0)
431
432 /* Return values of ACTFs ('action functions') are a bit mask:
433  * bit 1=1: prune (use SKIP constant for setting it)
434  * bit 0=1: matched successfully (TRUE)
435  */
436
437 static int exec_actions(action ***appp, const char *fileName, const struct stat *statbuf)
438 {
439         int cur_group;
440         int cur_action;
441         int rc = 0;
442         action **app, *ap;
443
444         /* "action group" is a set of actions ANDed together.
445          * groups are ORed together.
446          * We simply evaluate each group until we find one in which all actions
447          * succeed. */
448
449         /* -prune is special: if it is encountered, then we won't
450          * descend into current directory. It doesn't matter whether
451          * action group (in which -prune sits) will succeed or not:
452          * find * -prune -name 'f*' -o -name 'm*' -- prunes every dir
453          * find * -name 'f*' -o -prune -name 'm*' -- prunes all dirs
454          *     not starting with 'f' */
455
456         /* We invert TRUE bit (bit 0). Now 1 there means 'failure'.
457          * and bitwise OR in "rc |= TRUE ^ ap->f()" will:
458          * (1) make SKIP (-prune) bit stick; and (2) detect 'failure'.
459          * On return, bit is restored.  */
460
461         cur_group = -1;
462         while ((app = appp[++cur_group]) != NULL) {
463                 rc &= ~TRUE; /* 'success' so far, clear TRUE bit */
464                 cur_action = -1;
465                 while (1) {
466                         ap = app[++cur_action];
467                         if (!ap) /* all actions in group were successful */
468                                 return rc ^ TRUE; /* restore TRUE bit */
469                         rc |= TRUE ^ ap->f(fileName, statbuf, ap);
470 #if ENABLE_FEATURE_FIND_NOT
471                         if (ap->invert) rc ^= TRUE;
472 #endif
473                         dbg("grp %d action %d rc:0x%x", cur_group, cur_action, rc);
474                         if (rc & TRUE) /* current group failed, try next */
475                                 break;
476                 }
477         }
478         dbg("returning:0x%x", rc ^ TRUE);
479         return rc ^ TRUE; /* restore TRUE bit */
480 }
481
482 #if !FNM_CASEFOLD
483 static char *strcpy_upcase(char *dst, const char *src)
484 {
485         char *d = dst;
486         while (1) {
487                 unsigned char ch = *src++;
488                 if (ch >= 'a' && ch <= 'z')
489                         ch -= ('a' - 'A');
490                 *d++ = ch;
491                 if (ch == '\0')
492                         break;
493         }
494         return dst;
495 }
496 #endif
497
498 ACTF(name)
499 {
500         int r;
501         const char *tmp = bb_basename(fileName);
502         /* GNU findutils: find DIR/ -name DIR
503          * prints "DIR/" (DIR// prints "DIR//" etc).
504          * Need to strip trailing "/".
505          * Such names can come only from top-level names, but
506          * we can't do this before recursive_action() call,
507          * since then "find FILE/ -name FILE"
508          * would also work (on non-directories), which is wrong.
509          */
510         char *trunc_slash = NULL;
511
512         if (*tmp == '\0') {
513                 /* "foo/bar/[//...]" */
514                 while (tmp != fileName && tmp[-1] == '/')
515                         tmp--;
516                 if (tmp == fileName) { /* entire fileName is "//.."? */
517                         /* yes, convert "//..." to "/"
518                          * Testcases:
519                          * find / -maxdepth 1 -name /: prints /
520                          * find // -maxdepth 1 -name /: prints //
521                          * find / -maxdepth 1 -name //: prints nothing
522                          * find // -maxdepth 1 -name //: prints nothing
523                          */
524                         if (tmp[1])
525                                 trunc_slash = (char*)tmp + 1;
526                 } else {
527                         /* no, it's "foo/bar/[//...]", go back to 'b' */
528                         trunc_slash = (char*)tmp;
529                         while (tmp != fileName && tmp[-1] != '/')
530                                 tmp--;
531                 }
532         }
533
534         /* Was using FNM_PERIOD flag too,
535          * but somewhere between 4.1.20 and 4.4.0 GNU find stopped using it.
536          * find -name '*foo' should match .foo too:
537          */
538         if (trunc_slash) *trunc_slash = '\0';
539 #if FNM_CASEFOLD
540         r = fnmatch(ap->pattern, tmp, (ap->iname ? FNM_CASEFOLD : 0));
541 #else
542         if (ap->iname)
543                 tmp = strcpy_upcase(alloca(strlen(tmp) + 1), tmp);
544         r = fnmatch(ap->pattern, tmp, 0);
545 #endif
546         if (trunc_slash) *trunc_slash = '/';
547         return r == 0;
548 }
549
550 #if ENABLE_FEATURE_FIND_PATH
551 ACTF(path)
552 {
553 # if FNM_CASEFOLD
554         return fnmatch(ap->pattern, fileName, (ap->ipath ? FNM_CASEFOLD : 0)) == 0;
555 # else
556         if (ap->ipath)
557                 fileName = strcpy_upcase(alloca(strlen(fileName) + 1), fileName);
558         return fnmatch(ap->pattern, fileName, 0) == 0;
559 # endif
560 }
561 #endif
562 #if ENABLE_FEATURE_FIND_REGEX
563 ACTF(regex)
564 {
565         regmatch_t match;
566         if (regexec(&ap->compiled_pattern, fileName, 1, &match, 0 /*eflags*/))
567                 return 0; /* no match */
568         if (match.rm_so)
569                 return 0; /* match doesn't start at pos 0 */
570         if (fileName[match.rm_eo])
571                 return 0; /* match doesn't end exactly at end of pathname */
572         return 1;
573 }
574 #endif
575 #if ENABLE_FEATURE_FIND_TYPE
576 ACTF(type)
577 {
578         return ((statbuf->st_mode & S_IFMT) == ap->type_mask);
579 }
580 #endif
581 #if ENABLE_FEATURE_FIND_PERM
582 ACTF(perm)
583 {
584         /* -perm [+/]mode: at least one of perm_mask bits are set */
585         if (ap->perm_char == '+' || ap->perm_char == '/')
586                 return (statbuf->st_mode & ap->perm_mask) != 0;
587         /* -perm -mode: all of perm_mask are set */
588         if (ap->perm_char == '-')
589                 return (statbuf->st_mode & ap->perm_mask) == ap->perm_mask;
590         /* -perm mode: file mode must match perm_mask */
591         return (statbuf->st_mode & 07777) == ap->perm_mask;
592 }
593 #endif
594 #if ENABLE_FEATURE_FIND_MTIME
595 ACTF(mtime)
596 {
597         time_t file_age = time(NULL) - statbuf->st_mtime;
598         time_t mtime_secs = ap->mtime_days * 24*60*60;
599         if (ap->mtime_char == '+')
600                 return file_age >= mtime_secs + 24*60*60;
601         if (ap->mtime_char == '-')
602                 return file_age < mtime_secs;
603         /* just numeric mtime */
604         return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
605 }
606 #endif
607 #if ENABLE_FEATURE_FIND_MMIN
608 ACTF(mmin)
609 {
610         time_t file_age = time(NULL) - statbuf->st_mtime;
611         time_t mmin_secs = ap->mmin_mins * 60;
612         if (ap->mmin_char == '+')
613                 return file_age >= mmin_secs + 60;
614         if (ap->mmin_char == '-')
615                 return file_age < mmin_secs;
616         /* just numeric mmin */
617         return file_age >= mmin_secs && file_age < (mmin_secs + 60);
618 }
619 #endif
620 #if ENABLE_FEATURE_FIND_NEWER
621 ACTF(newer)
622 {
623         return (ap->newer_mtime < statbuf->st_mtime);
624 }
625 #endif
626 #if ENABLE_FEATURE_FIND_INUM
627 ACTF(inum)
628 {
629         return (statbuf->st_ino == ap->inode_num);
630 }
631 #endif
632 #if ENABLE_FEATURE_FIND_EXEC
633 static int do_exec(action_exec *ap, const char *fileName)
634 {
635         int i, rc;
636 # if ENABLE_FEATURE_FIND_EXEC_PLUS
637         int size = ap->exec_argc + ap->filelist_idx + 1;
638 # else
639         int size = ap->exec_argc + 1;
640 # endif
641 # if ENABLE_USE_PORTABLE_CODE
642         char **argv = alloca(sizeof(char*) * size);
643 # else /* gcc 4.3.1 generates smaller code: */
644         char *argv[size];
645 # endif
646         char **pp = argv;
647
648         for (i = 0; i < ap->exec_argc; i++) {
649                 const char *arg = ap->exec_argv[i];
650
651 # if ENABLE_FEATURE_FIND_EXEC_PLUS
652                 if (ap->filelist) {
653                         /* Handling "-exec +"
654                          * Only one exec_argv[i] has substitution in it.
655                          * Expand that one exec_argv[i] into file list.
656                          */
657                         if (ap->subst_count[i] == 0) {
658                                 *pp++ = xstrdup(arg);
659                         } else {
660                                 int j = 0;
661                                 while (ap->filelist[j]) {
662                                         /* 2nd arg here should be ap->subst_count[i], but it is always 1: */
663                                         *pp++ = xmalloc_substitute_string(arg, 1, "{}", ap->filelist[j]);
664                                         free(ap->filelist[j]);
665                                         j++;
666                                 }
667                         }
668                 } else
669 # endif
670                 {
671                         /* Handling "-exec ;" */
672                         *pp++ = xmalloc_substitute_string(arg, ap->subst_count[i], "{}", fileName);
673                 }
674         }
675         *pp = NULL; /* terminate the list */
676
677 # if ENABLE_FEATURE_FIND_EXEC_PLUS
678         if (ap->filelist) {
679                 ap->filelist[0] = NULL;
680                 ap->filelist_idx = 0;
681                 ap->file_len = 0;
682         }
683 # endif
684
685         rc = spawn_and_wait(argv);
686         if (rc < 0)
687                 bb_simple_perror_msg(argv[0]);
688
689         i = 0;
690         while (argv[i])
691                 free(argv[i++]);
692         return rc == 0; /* return 1 if exitcode 0 */
693 }
694 ACTF(exec)
695 {
696 # if ENABLE_FEATURE_FIND_EXEC_PLUS
697         if (ap->filelist) {
698                 int rc;
699
700                 ap->filelist = xrealloc_vector(ap->filelist, 8, ap->filelist_idx);
701                 ap->filelist[ap->filelist_idx++] = xstrdup(fileName);
702                 ap->file_len += strlen(fileName) + sizeof(char*) + 1;
703                 /* If we have lots of files already, exec the command */
704                 rc = 1;
705                 if (ap->file_len >= G.max_argv_len)
706                         rc = do_exec(ap, NULL);
707                 return rc;
708         }
709 # endif
710         return do_exec(ap, fileName);
711 }
712 # if ENABLE_FEATURE_FIND_EXEC_PLUS
713 static int flush_exec_plus(void)
714 {
715         action *ap;
716         action **app;
717         action ***appp = G.actions;
718         while ((app = *appp++) != NULL) {
719                 while ((ap = *app++) != NULL) {
720                         if (ap->f == (action_fp)func_exec) {
721                                 action_exec *ae = (void*)ap;
722                                 if (ae->filelist_idx != 0) {
723                                         int rc = do_exec(ae, NULL);
724 #  if ENABLE_FEATURE_FIND_NOT
725                                         if (ap->invert) rc = !rc;
726 #  endif
727                                         if (rc == 0)
728                                                 return 1;
729                                 }
730                         }
731                 }
732         }
733         return 0;
734 }
735 # endif
736 #endif
737 #if ENABLE_FEATURE_FIND_USER
738 ACTF(user)
739 {
740         return (statbuf->st_uid == ap->uid);
741 }
742 #endif
743 #if ENABLE_FEATURE_FIND_GROUP
744 ACTF(group)
745 {
746         return (statbuf->st_gid == ap->gid);
747 }
748 #endif
749 #if ENABLE_FEATURE_FIND_PRINT0
750 ACTF(print0)
751 {
752         printf("%s%c", fileName, '\0');
753         return TRUE;
754 }
755 #endif
756 ACTF(print)
757 {
758         puts(fileName);
759         return TRUE;
760 }
761 #if ENABLE_FEATURE_FIND_PAREN
762 ACTF(paren)
763 {
764         return exec_actions(ap->subexpr, fileName, statbuf);
765 }
766 #endif
767 #if ENABLE_FEATURE_FIND_SIZE
768 ACTF(size)
769 {
770         if (ap->size_char == '+')
771                 return statbuf->st_size > ap->size;
772         if (ap->size_char == '-')
773                 return statbuf->st_size < ap->size;
774         return statbuf->st_size == ap->size;
775 }
776 #endif
777 #if ENABLE_FEATURE_FIND_PRUNE
778 /*
779  * -prune: if -depth is not given, return true and do not descend
780  * current dir; if -depth is given, return false with no effect.
781  * Example:
782  * find dir -name 'asm-*' -prune -o -name '*.[chS]' -print
783  */
784 ACTF(prune)
785 {
786         return SKIP + TRUE;
787 }
788 #endif
789 #if ENABLE_FEATURE_FIND_QUIT
790 ACTF(quit)
791 {
792         exit(G.exitstatus);
793 }
794 #endif
795 #if ENABLE_FEATURE_FIND_DELETE
796 ACTF(delete)
797 {
798         int rc;
799         if (S_ISDIR(statbuf->st_mode)) {
800                 /* "find . -delete" skips rmdir(".") */
801                 rc = 0;
802                 if (NOT_LONE_CHAR(fileName, '.'))
803                         rc = rmdir(fileName);
804         } else {
805                 rc = unlink(fileName);
806         }
807         if (rc < 0)
808                 bb_simple_perror_msg(fileName);
809         return TRUE;
810 }
811 #endif
812 #if ENABLE_FEATURE_FIND_CONTEXT
813 ACTF(context)
814 {
815         security_context_t con;
816         int rc;
817
818         if (G.recurse_flags & ACTION_FOLLOWLINKS) {
819                 rc = getfilecon(fileName, &con);
820         } else {
821                 rc = lgetfilecon(fileName, &con);
822         }
823         if (rc < 0)
824                 return FALSE;
825         rc = strcmp(ap->context, con);
826         freecon(con);
827         return rc == 0;
828 }
829 #endif
830 #if ENABLE_FEATURE_FIND_LINKS
831 ACTF(links)
832 {
833         switch(ap->links_char) {
834         case '-' : return (statbuf->st_nlink <  ap->links_count);
835         case '+' : return (statbuf->st_nlink >  ap->links_count);
836         default:   return (statbuf->st_nlink == ap->links_count);
837         }
838 }
839 #endif
840
841 static int FAST_FUNC fileAction(const char *fileName,
842                 struct stat *statbuf,
843                 void *userData UNUSED_PARAM,
844                 int depth IF_NOT_FEATURE_FIND_MAXDEPTH(UNUSED_PARAM))
845 {
846         int r;
847         int same_fs = 1;
848
849 #if ENABLE_FEATURE_FIND_XDEV
850         if (S_ISDIR(statbuf->st_mode) && G.xdev_count) {
851                 int i;
852                 for (i = 0; i < G.xdev_count; i++) {
853                         if (G.xdev_dev[i] == statbuf->st_dev)
854                                 goto found;
855                 }
856                 //bb_error_msg("'%s': not same fs", fileName);
857                 same_fs = 0;
858  found: ;
859         }
860 #endif
861
862 #if ENABLE_FEATURE_FIND_MAXDEPTH
863         if (depth < G.minmaxdepth[0]) {
864                 if (same_fs)
865                         return TRUE; /* skip this, continue recursing */
866                 return SKIP; /* stop recursing */
867         }
868         if (depth > G.minmaxdepth[1])
869                 return SKIP; /* stop recursing */
870 #endif
871
872         r = exec_actions(G.actions, fileName, statbuf);
873         /* Had no explicit -print[0] or -exec? then print */
874         if ((r & TRUE) && G.need_print)
875                 puts(fileName);
876
877 #if ENABLE_FEATURE_FIND_MAXDEPTH
878         if (S_ISDIR(statbuf->st_mode)) {
879                 if (depth == G.minmaxdepth[1])
880                         return SKIP;
881         }
882 #endif
883         /* -xdev stops on mountpoints, but AFTER mountpoit itself
884          * is processed as usual */
885         if (!same_fs) {
886                 return SKIP;
887         }
888
889         /* Cannot return 0: our caller, recursive_action(),
890          * will perror() and skip dirs (if called on dir) */
891         return (r & SKIP) ? SKIP : TRUE;
892 }
893
894
895 #if ENABLE_FEATURE_FIND_TYPE
896 static int find_type(const char *type)
897 {
898         int mask = 0;
899
900         if (*type == 'b')
901                 mask = S_IFBLK;
902         else if (*type == 'c')
903                 mask = S_IFCHR;
904         else if (*type == 'd')
905                 mask = S_IFDIR;
906         else if (*type == 'p')
907                 mask = S_IFIFO;
908         else if (*type == 'f')
909                 mask = S_IFREG;
910         else if (*type == 'l')
911                 mask = S_IFLNK;
912         else if (*type == 's')
913                 mask = S_IFSOCK;
914
915         if (mask == 0 || type[1] != '\0')
916                 bb_error_msg_and_die(bb_msg_invalid_arg_to, type, "-type");
917
918         return mask;
919 }
920 #endif
921
922 #if ENABLE_FEATURE_FIND_PERM \
923  || ENABLE_FEATURE_FIND_MTIME || ENABLE_FEATURE_FIND_MMIN \
924  || ENABLE_FEATURE_FIND_SIZE  || ENABLE_FEATURE_FIND_LINKS
925 static const char* plus_minus_num(const char* str)
926 {
927         if (*str == '-' || *str == '+')
928                 str++;
929         return str;
930 }
931 #endif
932
933 /* Say no to GCCism */
934 #define USE_NESTED_FUNCTION 0
935
936 #if !USE_NESTED_FUNCTION
937 struct pp_locals {
938         action*** appp;
939         unsigned cur_group;
940         unsigned cur_action;
941         IF_FEATURE_FIND_NOT( bool invert_flag; )
942 };
943 static action* alloc_action(struct pp_locals *ppl, int sizeof_struct, action_fp f)
944 {
945         action *ap = xzalloc(sizeof_struct);
946         action **app;
947         action ***group = &ppl->appp[ppl->cur_group];
948         *group = app = xrealloc(*group, (ppl->cur_action+2) * sizeof(ppl->appp[0][0]));
949         app[ppl->cur_action++] = ap;
950         app[ppl->cur_action] = NULL;
951         ap->f = f;
952         IF_FEATURE_FIND_NOT( ap->invert = ppl->invert_flag; )
953         IF_FEATURE_FIND_NOT( ppl->invert_flag = 0; )
954         return ap;
955 }
956 #endif
957
958 static action*** parse_params(char **argv)
959 {
960         enum {
961                                 OPT_FOLLOW     ,
962         IF_FEATURE_FIND_XDEV(   OPT_XDEV       ,)
963         IF_FEATURE_FIND_DEPTH(  OPT_DEPTH      ,)
964                                 PARM_a         ,
965                                 PARM_o         ,
966         IF_FEATURE_FIND_NOT(    PARM_char_not  ,)
967 #if ENABLE_DESKTOP
968                                 PARM_and       ,
969                                 PARM_or        ,
970         IF_FEATURE_FIND_NOT(    PARM_not       ,)
971 #endif
972                                 PARM_print     ,
973         IF_FEATURE_FIND_PRINT0( PARM_print0    ,)
974         IF_FEATURE_FIND_PRUNE(  PARM_prune     ,)
975         IF_FEATURE_FIND_QUIT(   PARM_quit      ,)
976         IF_FEATURE_FIND_DELETE( PARM_delete    ,)
977         IF_FEATURE_FIND_EXEC(   PARM_exec      ,)
978         IF_FEATURE_FIND_PAREN(  PARM_char_brace,)
979         /* All options/actions starting from here require argument */
980                                 PARM_name      ,
981                                 PARM_iname     ,
982         IF_FEATURE_FIND_PATH(   PARM_path      ,)
983 #if ENABLE_DESKTOP
984         /* -wholename is a synonym for -path */
985         /* We support it because Linux kernel's "make tags" uses it */
986         IF_FEATURE_FIND_PATH(   PARM_wholename ,)
987 #endif
988         IF_FEATURE_FIND_PATH(   PARM_ipath     ,)
989         IF_FEATURE_FIND_REGEX(  PARM_regex     ,)
990         IF_FEATURE_FIND_TYPE(   PARM_type      ,)
991         IF_FEATURE_FIND_PERM(   PARM_perm      ,)
992         IF_FEATURE_FIND_MTIME(  PARM_mtime     ,)
993         IF_FEATURE_FIND_MMIN(   PARM_mmin      ,)
994         IF_FEATURE_FIND_NEWER(  PARM_newer     ,)
995         IF_FEATURE_FIND_INUM(   PARM_inum      ,)
996         IF_FEATURE_FIND_USER(   PARM_user      ,)
997         IF_FEATURE_FIND_GROUP(  PARM_group     ,)
998         IF_FEATURE_FIND_SIZE(   PARM_size      ,)
999         IF_FEATURE_FIND_CONTEXT(PARM_context   ,)
1000         IF_FEATURE_FIND_LINKS(  PARM_links     ,)
1001         IF_FEATURE_FIND_MAXDEPTH(OPT_MINDEPTH,OPT_MAXDEPTH,)
1002         };
1003
1004         static const char params[] ALIGN1 =
1005                                 "-follow\0"
1006         IF_FEATURE_FIND_XDEV(   "-xdev\0"                 )
1007         IF_FEATURE_FIND_DEPTH(  "-depth\0"                )
1008                                 "-a\0"
1009                                 "-o\0"
1010         IF_FEATURE_FIND_NOT(    "!\0"       )
1011 #if ENABLE_DESKTOP
1012                                 "-and\0"
1013                                 "-or\0"
1014         IF_FEATURE_FIND_NOT(    "-not\0"    )
1015 #endif
1016                                 "-print\0"
1017         IF_FEATURE_FIND_PRINT0( "-print0\0" )
1018         IF_FEATURE_FIND_PRUNE(  "-prune\0"  )
1019         IF_FEATURE_FIND_QUIT(   "-quit\0"  )
1020         IF_FEATURE_FIND_DELETE( "-delete\0" )
1021         IF_FEATURE_FIND_EXEC(   "-exec\0"   )
1022         IF_FEATURE_FIND_PAREN(  "(\0"       )
1023         /* All options/actions starting from here require argument */
1024                                 "-name\0"
1025                                 "-iname\0"
1026         IF_FEATURE_FIND_PATH(   "-path\0"   )
1027 #if ENABLE_DESKTOP
1028         IF_FEATURE_FIND_PATH(   "-wholename\0")
1029 #endif
1030         IF_FEATURE_FIND_PATH(   "-ipath\0"  )
1031         IF_FEATURE_FIND_REGEX(  "-regex\0"  )
1032         IF_FEATURE_FIND_TYPE(   "-type\0"   )
1033         IF_FEATURE_FIND_PERM(   "-perm\0"   )
1034         IF_FEATURE_FIND_MTIME(  "-mtime\0"  )
1035         IF_FEATURE_FIND_MMIN(   "-mmin\0"   )
1036         IF_FEATURE_FIND_NEWER(  "-newer\0"  )
1037         IF_FEATURE_FIND_INUM(   "-inum\0"   )
1038         IF_FEATURE_FIND_USER(   "-user\0"   )
1039         IF_FEATURE_FIND_GROUP(  "-group\0"  )
1040         IF_FEATURE_FIND_SIZE(   "-size\0"   )
1041         IF_FEATURE_FIND_CONTEXT("-context\0")
1042         IF_FEATURE_FIND_LINKS(  "-links\0"  )
1043         IF_FEATURE_FIND_MAXDEPTH("-mindepth\0""-maxdepth\0")
1044         ;
1045
1046 #if !USE_NESTED_FUNCTION
1047         struct pp_locals ppl;
1048 #define appp        (ppl.appp       )
1049 #define cur_group   (ppl.cur_group  )
1050 #define cur_action  (ppl.cur_action )
1051 #define invert_flag (ppl.invert_flag)
1052 #define ALLOC_ACTION(name) (action_##name*)alloc_action(&ppl, sizeof(action_##name), (action_fp) func_##name)
1053 #else
1054         action*** appp;
1055         unsigned cur_group;
1056         unsigned cur_action;
1057         IF_FEATURE_FIND_NOT( bool invert_flag; )
1058
1059         /* This is the only place in busybox where we use nested function.
1060          * So far more standard alternatives were bigger. */
1061         /* Auto decl suppresses "func without a prototype" warning: */
1062         auto action* alloc_action(int sizeof_struct, action_fp f);
1063         action* alloc_action(int sizeof_struct, action_fp f)
1064         {
1065                 action *ap;
1066                 appp[cur_group] = xrealloc(appp[cur_group], (cur_action+2) * sizeof(appp[0][0]));
1067                 appp[cur_group][cur_action++] = ap = xzalloc(sizeof_struct);
1068                 appp[cur_group][cur_action] = NULL;
1069                 ap->f = f;
1070                 IF_FEATURE_FIND_NOT( ap->invert = invert_flag; )
1071                 IF_FEATURE_FIND_NOT( invert_flag = 0; )
1072                 return ap;
1073         }
1074 #define ALLOC_ACTION(name) (action_##name*)alloc_action(sizeof(action_##name), (action_fp) func_##name)
1075 #endif
1076
1077         cur_group = 0;
1078         cur_action = 0;
1079         IF_FEATURE_FIND_NOT( invert_flag = 0; )
1080         appp = xzalloc(2 * sizeof(appp[0])); /* appp[0],[1] == NULL */
1081
1082         while (*argv) {
1083                 const char *arg = argv[0];
1084                 int parm = index_in_strings(params, arg);
1085                 const char *arg1 = argv[1];
1086
1087                 dbg("arg:'%s' arg1:'%s' parm:%d PARM_type:%d", arg, arg1, parm, PARM_type);
1088
1089                 if (parm >= PARM_name) {
1090                         /* All options/actions starting from -name require argument */
1091                         if (!arg1)
1092                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
1093                         argv++;
1094                 }
1095
1096                 /* We can use big switch() here, but on i386
1097                  * it doesn't give smaller code. Other arches? */
1098
1099 /* Options always return true. They always take effect
1100  * rather than being processed only when their place in the
1101  * expression is reached.
1102  */
1103                 /* Options */
1104                 if (parm == OPT_FOLLOW) {
1105                         dbg("follow enabled: %d", __LINE__);
1106                         G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
1107                 }
1108 #if ENABLE_FEATURE_FIND_XDEV
1109                 else if (parm == OPT_XDEV) {
1110                         dbg("%d", __LINE__);
1111                         G.xdev_on = 1;
1112                 }
1113 #endif
1114 #if ENABLE_FEATURE_FIND_MAXDEPTH
1115                 else if (parm == OPT_MINDEPTH || parm == OPT_MINDEPTH + 1) {
1116                         dbg("%d", __LINE__);
1117                         G.minmaxdepth[parm - OPT_MINDEPTH] = xatoi_positive(arg1);
1118                 }
1119 #endif
1120 #if ENABLE_FEATURE_FIND_DEPTH
1121                 else if (parm == OPT_DEPTH) {
1122                         dbg("%d", __LINE__);
1123                         G.recurse_flags |= ACTION_DEPTHFIRST;
1124                 }
1125 #endif
1126 /* Actions are grouped by operators
1127  * ( expr )              Force precedence
1128  * ! expr                True if expr is false
1129  * -not expr             Same as ! expr
1130  * expr1 [-a[nd]] expr2  And; expr2 is not evaluated if expr1 is false
1131  * expr1 -o[r] expr2     Or; expr2 is not evaluated if expr1 is true
1132  * expr1 , expr2         List; both expr1 and expr2 are always evaluated
1133  * We implement: (), -a, -o
1134  */
1135                 /* Operators */
1136                 else if (parm == PARM_a IF_DESKTOP(|| parm == PARM_and)) {
1137                         dbg("%d", __LINE__);
1138                         /* no further special handling required */
1139                 }
1140                 else if (parm == PARM_o IF_DESKTOP(|| parm == PARM_or)) {
1141                         dbg("%d", __LINE__);
1142                         /* start new OR group */
1143                         cur_group++;
1144                         appp = xrealloc(appp, (cur_group+2) * sizeof(appp[0]));
1145                         /*appp[cur_group] = NULL; - already NULL */
1146                         appp[cur_group+1] = NULL;
1147                         cur_action = 0;
1148                 }
1149 #if ENABLE_FEATURE_FIND_NOT
1150                 else if (parm == PARM_char_not IF_DESKTOP(|| parm == PARM_not)) {
1151                         /* also handles "find ! ! -name 'foo*'" */
1152                         invert_flag ^= 1;
1153                         dbg("invert_flag:%d", invert_flag);
1154                 }
1155 #endif
1156                 /* Actions */
1157                 else if (parm == PARM_print) {
1158                         dbg("%d", __LINE__);
1159                         G.need_print = 0;
1160                         (void) ALLOC_ACTION(print);
1161                 }
1162 #if ENABLE_FEATURE_FIND_PRINT0
1163                 else if (parm == PARM_print0) {
1164                         dbg("%d", __LINE__);
1165                         G.need_print = 0;
1166                         (void) ALLOC_ACTION(print0);
1167                 }
1168 #endif
1169 #if ENABLE_FEATURE_FIND_PRUNE
1170                 else if (parm == PARM_prune) {
1171                         dbg("%d", __LINE__);
1172                         (void) ALLOC_ACTION(prune);
1173                 }
1174 #endif
1175 #if ENABLE_FEATURE_FIND_QUIT
1176                 else if (parm == PARM_quit) {
1177                         dbg("%d", __LINE__);
1178                         (void) ALLOC_ACTION(quit);
1179                 }
1180 #endif
1181 #if ENABLE_FEATURE_FIND_DELETE
1182                 else if (parm == PARM_delete) {
1183                         dbg("%d", __LINE__);
1184                         G.need_print = 0;
1185                         G.recurse_flags |= ACTION_DEPTHFIRST;
1186                         (void) ALLOC_ACTION(delete);
1187                 }
1188 #endif
1189 #if ENABLE_FEATURE_FIND_EXEC
1190                 else if (parm == PARM_exec) {
1191                         int i;
1192                         action_exec *ap;
1193                         IF_FEATURE_FIND_EXEC_PLUS(int all_subst = 0;)
1194                         dbg("%d", __LINE__);
1195                         G.need_print = 0;
1196                         ap = ALLOC_ACTION(exec);
1197                         ap->exec_argv = ++argv; /* first arg after -exec */
1198                         /*ap->exec_argc = 0; - ALLOC_ACTION did it */
1199                         while (1) {
1200                                 if (!*argv) /* did not see ';' or '+' until end */
1201                                         bb_error_msg_and_die(bb_msg_requires_arg, "-exec");
1202                                 // find -exec echo Foo ">{}<" ";"
1203                                 // executes "echo Foo >FILENAME<",
1204                                 // find -exec echo Foo ">{}<" "+"
1205                                 // executes "echo Foo FILENAME1 FILENAME2 FILENAME3...".
1206                                 if ((argv[0][0] == ';' || argv[0][0] == '+')
1207                                  && argv[0][1] == '\0'
1208                                 ) {
1209 # if ENABLE_FEATURE_FIND_EXEC_PLUS
1210                                         if (argv[0][0] == '+')
1211                                                 ap->filelist = xzalloc(sizeof(ap->filelist[0]));
1212 # endif
1213                                         break;
1214                                 }
1215                                 argv++;
1216                                 ap->exec_argc++;
1217                         }
1218                         if (ap->exec_argc == 0)
1219                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
1220                         ap->subst_count = xmalloc(ap->exec_argc * sizeof(int));
1221                         i = ap->exec_argc;
1222                         while (i--) {
1223                                 ap->subst_count[i] = count_strstr(ap->exec_argv[i], "{}");
1224                                 IF_FEATURE_FIND_EXEC_PLUS(all_subst += ap->subst_count[i];)
1225                         }
1226 # if ENABLE_FEATURE_FIND_EXEC_PLUS
1227                         /*
1228                          * coreutils expects {} to appear only once in "-exec +"
1229                          */
1230                         if (all_subst != 1 && ap->filelist)
1231                                 bb_error_msg_and_die("only one '{}' allowed for -exec +");
1232 # endif
1233                 }
1234 #endif
1235 #if ENABLE_FEATURE_FIND_PAREN
1236                 else if (parm == PARM_char_brace) {
1237                         action_paren *ap;
1238                         char **endarg;
1239                         unsigned nested = 1;
1240
1241                         dbg("%d", __LINE__);
1242                         endarg = argv;
1243                         while (1) {
1244                                 if (!*++endarg)
1245                                         bb_error_msg_and_die("unpaired '('");
1246                                 if (LONE_CHAR(*endarg, '('))
1247                                         nested++;
1248                                 else if (LONE_CHAR(*endarg, ')') && !--nested) {
1249                                         *endarg = NULL;
1250                                         break;
1251                                 }
1252                         }
1253                         ap = ALLOC_ACTION(paren);
1254                         ap->subexpr = parse_params(argv + 1);
1255                         *endarg = (char*) ")"; /* restore NULLed parameter */
1256                         argv = endarg;
1257                 }
1258 #endif
1259                 else if (parm == PARM_name || parm == PARM_iname) {
1260                         action_name *ap;
1261                         dbg("%d", __LINE__);
1262                         ap = ALLOC_ACTION(name);
1263                         ap->pattern = arg1;
1264                         ap->iname = (parm == PARM_iname);
1265                 }
1266 #if ENABLE_FEATURE_FIND_PATH
1267                 else if (parm == PARM_path IF_DESKTOP(|| parm == PARM_wholename) || parm == PARM_ipath) {
1268                         action_path *ap;
1269                         dbg("%d", __LINE__);
1270                         ap = ALLOC_ACTION(path);
1271                         ap->pattern = arg1;
1272                         ap->ipath = (parm == PARM_ipath);
1273                 }
1274 #endif
1275 #if ENABLE_FEATURE_FIND_REGEX
1276                 else if (parm == PARM_regex) {
1277                         action_regex *ap;
1278                         dbg("%d", __LINE__);
1279                         ap = ALLOC_ACTION(regex);
1280                         xregcomp(&ap->compiled_pattern, arg1, 0 /*cflags*/);
1281                 }
1282 #endif
1283 #if ENABLE_FEATURE_FIND_TYPE
1284                 else if (parm == PARM_type) {
1285                         action_type *ap;
1286                         ap = ALLOC_ACTION(type);
1287                         ap->type_mask = find_type(arg1);
1288                         dbg("created:type mask:%x", ap->type_mask);
1289                 }
1290 #endif
1291 #if ENABLE_FEATURE_FIND_PERM
1292 /* -perm BITS   File's mode bits are exactly BITS (octal or symbolic).
1293  *              Symbolic modes use mode 0 as a point of departure.
1294  * -perm -BITS  All of the BITS are set in file's mode.
1295  * -perm [+/]BITS  At least one of the BITS is set in file's mode.
1296  */
1297                 else if (parm == PARM_perm) {
1298                         action_perm *ap;
1299                         dbg("%d", __LINE__);
1300                         ap = ALLOC_ACTION(perm);
1301                         ap->perm_char = arg1[0];
1302                         arg1 = (arg1[0] == '/' ? arg1+1 : plus_minus_num(arg1));
1303                         /*ap->perm_mask = 0; - ALLOC_ACTION did it */
1304                         ap->perm_mask = bb_parse_mode(arg1, ap->perm_mask);
1305                         if (ap->perm_mask == (mode_t)-1)
1306                                 bb_error_msg_and_die("invalid mode '%s'", arg1);
1307                 }
1308 #endif
1309 #if ENABLE_FEATURE_FIND_MTIME
1310                 else if (parm == PARM_mtime) {
1311                         action_mtime *ap;
1312                         dbg("%d", __LINE__);
1313                         ap = ALLOC_ACTION(mtime);
1314                         ap->mtime_char = arg1[0];
1315                         ap->mtime_days = xatoul(plus_minus_num(arg1));
1316                 }
1317 #endif
1318 #if ENABLE_FEATURE_FIND_MMIN
1319                 else if (parm == PARM_mmin) {
1320                         action_mmin *ap;
1321                         dbg("%d", __LINE__);
1322                         ap = ALLOC_ACTION(mmin);
1323                         ap->mmin_char = arg1[0];
1324                         ap->mmin_mins = xatoul(plus_minus_num(arg1));
1325                 }
1326 #endif
1327 #if ENABLE_FEATURE_FIND_NEWER
1328                 else if (parm == PARM_newer) {
1329                         struct stat stat_newer;
1330                         action_newer *ap;
1331                         dbg("%d", __LINE__);
1332                         ap = ALLOC_ACTION(newer);
1333                         xstat(arg1, &stat_newer);
1334                         ap->newer_mtime = stat_newer.st_mtime;
1335                 }
1336 #endif
1337 #if ENABLE_FEATURE_FIND_INUM
1338                 else if (parm == PARM_inum) {
1339                         action_inum *ap;
1340                         dbg("%d", __LINE__);
1341                         ap = ALLOC_ACTION(inum);
1342                         ap->inode_num = xatoul(arg1);
1343                 }
1344 #endif
1345 #if ENABLE_FEATURE_FIND_USER
1346                 else if (parm == PARM_user) {
1347                         action_user *ap;
1348                         dbg("%d", __LINE__);
1349                         ap = ALLOC_ACTION(user);
1350                         ap->uid = bb_strtou(arg1, NULL, 10);
1351                         if (errno)
1352                                 ap->uid = xuname2uid(arg1);
1353                 }
1354 #endif
1355 #if ENABLE_FEATURE_FIND_GROUP
1356                 else if (parm == PARM_group) {
1357                         action_group *ap;
1358                         dbg("%d", __LINE__);
1359                         ap = ALLOC_ACTION(group);
1360                         ap->gid = bb_strtou(arg1, NULL, 10);
1361                         if (errno)
1362                                 ap->gid = xgroup2gid(arg1);
1363                 }
1364 #endif
1365 #if ENABLE_FEATURE_FIND_SIZE
1366                 else if (parm == PARM_size) {
1367 /* -size n[bckw]: file uses n units of space
1368  * b (default): units are 512-byte blocks
1369  * c: 1 byte
1370  * k: kilobytes
1371  * w: 2-byte words
1372  */
1373 #if ENABLE_LFS
1374 #define XATOU_SFX xatoull_sfx
1375 #else
1376 #define XATOU_SFX xatoul_sfx
1377 #endif
1378                         static const struct suffix_mult find_suffixes[] = {
1379                                 { "c", 1 },
1380                                 { "w", 2 },
1381                                 { "", 512 },
1382                                 { "b", 512 },
1383                                 { "k", 1024 },
1384                                 { "", 0 }
1385                         };
1386                         action_size *ap;
1387                         dbg("%d", __LINE__);
1388                         ap = ALLOC_ACTION(size);
1389                         ap->size_char = arg1[0];
1390                         ap->size = XATOU_SFX(plus_minus_num(arg1), find_suffixes);
1391                 }
1392 #endif
1393 #if ENABLE_FEATURE_FIND_CONTEXT
1394                 else if (parm == PARM_context) {
1395                         action_context *ap;
1396                         dbg("%d", __LINE__);
1397                         ap = ALLOC_ACTION(context);
1398                         /*ap->context = NULL; - ALLOC_ACTION did it */
1399                         /* SELinux headers erroneously declare non-const parameter */
1400                         if (selinux_raw_to_trans_context((char*)arg1, &ap->context))
1401                                 bb_simple_perror_msg(arg1);
1402                 }
1403 #endif
1404 #if ENABLE_FEATURE_FIND_LINKS
1405                 else if (parm == PARM_links) {
1406                         action_links *ap;
1407                         dbg("%d", __LINE__);
1408                         ap = ALLOC_ACTION(links);
1409                         ap->links_char = arg1[0];
1410                         ap->links_count = xatoul(plus_minus_num(arg1));
1411                 }
1412 #endif
1413                 else {
1414                         bb_error_msg("unrecognized: %s", arg);
1415                         bb_show_usage();
1416                 }
1417                 argv++;
1418         }
1419         dbg("exiting %s", __func__);
1420         return appp;
1421 #undef ALLOC_ACTION
1422 #undef appp
1423 #undef cur_action
1424 #undef invert_flag
1425 }
1426
1427 int find_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1428 int find_main(int argc UNUSED_PARAM, char **argv)
1429 {
1430         int i, firstopt;
1431         char **past_HLP, *saved;
1432
1433         INIT_G();
1434
1435         /* "find -type f" + getopt("+HLP") => disaster.
1436          * Need to avoid getopt running into a non-HLP option.
1437          * Do this by temporarily storing NULL there:
1438          */
1439         past_HLP = argv;
1440         for (;;) {
1441                 saved = *++past_HLP;
1442                 if (!saved)
1443                         break;
1444                 if (saved[0] != '-')
1445                         break;
1446                 if (!saved[1])
1447                         break; /* it is "-" */
1448                 if ((saved+1)[strspn(saved+1, "HLP")] != '\0')
1449                         break;
1450         }
1451         *past_HLP = NULL;
1452         /* "+": stop on first non-option */
1453         i = getopt32(argv, "+HLP");
1454         if (i & (1<<0))
1455                 G.recurse_flags |= ACTION_FOLLOWLINKS_L0 | ACTION_DANGLING_OK;
1456         if (i & (1<<1))
1457                 G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
1458         /* -P is default and is ignored */
1459         argv = past_HLP; /* same result as "argv += optind;" */
1460         *past_HLP = saved;
1461
1462         for (firstopt = 0; argv[firstopt]; firstopt++) {
1463                 if (argv[firstopt][0] == '-')
1464                         break;
1465                 if (ENABLE_FEATURE_FIND_NOT && LONE_CHAR(argv[firstopt], '!'))
1466                         break;
1467                 if (ENABLE_FEATURE_FIND_PAREN && LONE_CHAR(argv[firstopt], '('))
1468                         break;
1469         }
1470         if (firstopt == 0) {
1471                 *--argv = (char*)".";
1472                 firstopt++;
1473         }
1474
1475         G.actions = parse_params(&argv[firstopt]);
1476         argv[firstopt] = NULL;
1477
1478 #if ENABLE_FEATURE_FIND_XDEV
1479         if (G.xdev_on) {
1480                 struct stat stbuf;
1481
1482                 G.xdev_count = firstopt;
1483                 G.xdev_dev = xzalloc(G.xdev_count * sizeof(G.xdev_dev[0]));
1484                 for (i = 0; argv[i]; i++) {
1485                         /* not xstat(): shouldn't bomb out on
1486                          * "find not_exist exist -xdev" */
1487                         if (stat(argv[i], &stbuf) == 0)
1488                                 G.xdev_dev[i] = stbuf.st_dev;
1489                         /* else G.xdev_dev[i] stays 0 and
1490                          * won't match any real device dev_t
1491                          */
1492                 }
1493         }
1494 #endif
1495
1496         for (i = 0; argv[i]; i++) {
1497                 if (!recursive_action(argv[i],
1498                                 G.recurse_flags,/* flags */
1499                                 fileAction,     /* file action */
1500                                 fileAction,     /* dir action */
1501                                 NULL,           /* user data */
1502                                 0)              /* depth */
1503                 ) {
1504                         G.exitstatus |= EXIT_FAILURE;
1505                 }
1506         }
1507
1508         IF_FEATURE_FIND_EXEC_PLUS(G.exitstatus |= flush_exec_plus();)
1509         return G.exitstatus;
1510 }