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