6f7be4fc250563a82fd2f3c321e81693afa075c3
[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 the GPL version 2, see the file LICENSE in this tarball.
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 #include <fnmatch.h>
57 #include "libbb.h"
58 #if ENABLE_FEATURE_FIND_REGEX
59 #include "xregex.h"
60 #endif
61
62 /* This is a NOEXEC applet. Be very careful! */
63
64
65 typedef int (*action_fp)(const char *fileName, const struct stat *statbuf, void *) FAST_FUNC;
66
67 typedef struct {
68         action_fp f;
69 #if ENABLE_FEATURE_FIND_NOT
70         bool invert;
71 #endif
72 } action;
73
74 #define ACTS(name, ...) typedef struct { action a; __VA_ARGS__ } action_##name;
75 #define ACTF(name) \
76         static int FAST_FUNC func_##name(const char *fileName UNUSED_PARAM, \
77                 const struct stat *statbuf UNUSED_PARAM, \
78                 action_##name* ap UNUSED_PARAM)
79
80                         ACTS(print)
81                         ACTS(name,  const char *pattern; bool iname;)
82 IF_FEATURE_FIND_PATH(   ACTS(path,  const char *pattern;))
83 IF_FEATURE_FIND_REGEX(  ACTS(regex, regex_t compiled_pattern;))
84 IF_FEATURE_FIND_PRINT0( ACTS(print0))
85 IF_FEATURE_FIND_TYPE(   ACTS(type,  int type_mask;))
86 IF_FEATURE_FIND_PERM(   ACTS(perm,  char perm_char; mode_t perm_mask;))
87 IF_FEATURE_FIND_MTIME(  ACTS(mtime, char mtime_char; unsigned mtime_days;))
88 IF_FEATURE_FIND_MMIN(   ACTS(mmin,  char mmin_char; unsigned mmin_mins;))
89 IF_FEATURE_FIND_NEWER(  ACTS(newer, time_t newer_mtime;))
90 IF_FEATURE_FIND_INUM(   ACTS(inum,  ino_t inode_num;))
91 IF_FEATURE_FIND_USER(   ACTS(user,  uid_t uid;))
92 IF_FEATURE_FIND_SIZE(   ACTS(size,  char size_char; off_t size;))
93 IF_FEATURE_FIND_CONTEXT(ACTS(context, security_context_t context;))
94 IF_FEATURE_FIND_PAREN(  ACTS(paren, action ***subexpr;))
95 IF_FEATURE_FIND_PRUNE(  ACTS(prune))
96 IF_FEATURE_FIND_DELETE( ACTS(delete))
97 IF_FEATURE_FIND_EXEC(   ACTS(exec,  char **exec_argv; unsigned *subst_count; int exec_argc;))
98 IF_FEATURE_FIND_GROUP(  ACTS(group, gid_t gid;))
99
100 struct globals {
101         IF_FEATURE_FIND_XDEV(dev_t *xdev_dev;)
102         IF_FEATURE_FIND_XDEV(int xdev_count;)
103         action ***actions;
104         bool need_print;
105         recurse_flags_t recurse_flags;
106 };
107 #define G (*(struct globals*)&bb_common_bufsiz1)
108 #define INIT_G() do { \
109         struct G_sizecheck { \
110                 char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
111         }; \
112         G.need_print = 1; \
113         G.recurse_flags = ACTION_RECURSE; \
114 } while (0)
115
116 #if ENABLE_FEATURE_FIND_EXEC
117 static unsigned count_subst(const char *str)
118 {
119         unsigned count = 0;
120         while ((str = strstr(str, "{}")) != NULL) {
121                 count++;
122                 str++;
123         }
124         return count;
125 }
126
127
128 static char* subst(const char *src, unsigned count, const char* filename)
129 {
130         char *buf, *dst, *end;
131         size_t flen = strlen(filename);
132         /* we replace each '{}' with filename: growth by strlen-2 */
133         buf = dst = xmalloc(strlen(src) + count*(flen-2) + 1);
134         while ((end = strstr(src, "{}"))) {
135                 memcpy(dst, src, end - src);
136                 dst += end - src;
137                 src = end + 2;
138                 memcpy(dst, filename, flen);
139                 dst += flen;
140         }
141         strcpy(dst, src);
142         return buf;
143 }
144 #endif
145
146 /* Return values of ACTFs ('action functions') are a bit mask:
147  * bit 1=1: prune (use SKIP constant for setting it)
148  * bit 0=1: matched successfully (TRUE)
149  */
150
151 static int exec_actions(action ***appp, const char *fileName, const struct stat *statbuf)
152 {
153         int cur_group;
154         int cur_action;
155         int rc = 0;
156         action **app, *ap;
157
158         /* "action group" is a set of actions ANDed together.
159          * groups are ORed together.
160          * We simply evaluate each group until we find one in which all actions
161          * succeed. */
162
163         /* -prune is special: if it is encountered, then we won't
164          * descend into current directory. It doesn't matter whether
165          * action group (in which -prune sits) will succeed or not:
166          * find * -prune -name 'f*' -o -name 'm*' -- prunes every dir
167          * find * -name 'f*' -o -prune -name 'm*' -- prunes all dirs
168          *     not starting with 'f' */
169
170         /* We invert TRUE bit (bit 0). Now 1 there means 'failure'.
171          * and bitwise OR in "rc |= TRUE ^ ap->f()" will:
172          * (1) make SKIP (-prune) bit stick; and (2) detect 'failure'.
173          * On return, bit is restored.  */
174
175         cur_group = -1;
176         while ((app = appp[++cur_group])) {
177                 rc &= ~TRUE; /* 'success' so far, clear TRUE bit */
178                 cur_action = -1;
179                 while (1) {
180                         ap = app[++cur_action];
181                         if (!ap) /* all actions in group were successful */
182                                 return rc ^ TRUE; /* restore TRUE bit */
183                         rc |= TRUE ^ ap->f(fileName, statbuf, ap);
184 #if ENABLE_FEATURE_FIND_NOT
185                         if (ap->invert) rc ^= TRUE;
186 #endif
187                         if (rc & TRUE) /* current group failed, try next */
188                                 break;
189                 }
190         }
191         return rc ^ TRUE; /* restore TRUE bit */
192 }
193
194
195 ACTF(name)
196 {
197         const char *tmp = bb_basename(fileName);
198         if (tmp != fileName && !*tmp) { /* "foo/bar/". Oh no... go back to 'b' */
199                 tmp--;
200                 while (tmp != fileName && *--tmp != '/')
201                         continue;
202                 if (*tmp == '/')
203                         tmp++;
204         }
205         return fnmatch(ap->pattern, tmp, FNM_PERIOD | (ap->iname ? FNM_CASEFOLD : 0)) == 0;
206 }
207
208 #if ENABLE_FEATURE_FIND_PATH
209 ACTF(path)
210 {
211         return fnmatch(ap->pattern, fileName, 0) == 0;
212 }
213 #endif
214 #if ENABLE_FEATURE_FIND_REGEX
215 ACTF(regex)
216 {
217         regmatch_t match;
218         if (regexec(&ap->compiled_pattern, fileName, 1, &match, 0 /*eflags*/))
219                 return 0; /* no match */
220         if (match.rm_so)
221                 return 0; /* match doesn't start at pos 0 */
222         if (fileName[match.rm_eo])
223                 return 0; /* match doesn't end exactly at end of pathname */
224         return 1;
225 }
226 #endif
227 #if ENABLE_FEATURE_FIND_TYPE
228 ACTF(type)
229 {
230         return ((statbuf->st_mode & S_IFMT) == ap->type_mask);
231 }
232 #endif
233 #if ENABLE_FEATURE_FIND_PERM
234 ACTF(perm)
235 {
236         /* -perm +mode: at least one of perm_mask bits are set */
237         if (ap->perm_char == '+')
238                 return (statbuf->st_mode & ap->perm_mask) != 0;
239         /* -perm -mode: all of perm_mask are set */
240         if (ap->perm_char == '-')
241                 return (statbuf->st_mode & ap->perm_mask) == ap->perm_mask;
242         /* -perm mode: file mode must match perm_mask */
243         return (statbuf->st_mode & 07777) == ap->perm_mask;
244 }
245 #endif
246 #if ENABLE_FEATURE_FIND_MTIME
247 ACTF(mtime)
248 {
249         time_t file_age = time(NULL) - statbuf->st_mtime;
250         time_t mtime_secs = ap->mtime_days * 24*60*60;
251         if (ap->mtime_char == '+')
252                 return file_age >= mtime_secs + 24*60*60;
253         if (ap->mtime_char == '-')
254                 return file_age < mtime_secs;
255         /* just numeric mtime */
256         return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
257 }
258 #endif
259 #if ENABLE_FEATURE_FIND_MMIN
260 ACTF(mmin)
261 {
262         time_t file_age = time(NULL) - statbuf->st_mtime;
263         time_t mmin_secs = ap->mmin_mins * 60;
264         if (ap->mmin_char == '+')
265                 return file_age >= mmin_secs + 60;
266         if (ap->mmin_char == '-')
267                 return file_age < mmin_secs;
268         /* just numeric mmin */
269         return file_age >= mmin_secs && file_age < (mmin_secs + 60);
270 }
271 #endif
272 #if ENABLE_FEATURE_FIND_NEWER
273 ACTF(newer)
274 {
275         return (ap->newer_mtime < statbuf->st_mtime);
276 }
277 #endif
278 #if ENABLE_FEATURE_FIND_INUM
279 ACTF(inum)
280 {
281         return (statbuf->st_ino == ap->inode_num);
282 }
283 #endif
284 #if ENABLE_FEATURE_FIND_EXEC
285 ACTF(exec)
286 {
287         int i, rc;
288 #if ENABLE_USE_PORTABLE_CODE
289         char **argv = alloca(sizeof(char*) * (ap->exec_argc + 1));
290 #else /* gcc 4.3.1 generates smaller code: */
291         char *argv[ap->exec_argc + 1];
292 #endif
293         for (i = 0; i < ap->exec_argc; i++)
294                 argv[i] = subst(ap->exec_argv[i], ap->subst_count[i], fileName);
295         argv[i] = NULL; /* terminate the list */
296
297         rc = spawn_and_wait(argv);
298         if (rc < 0)
299                 bb_simple_perror_msg(argv[0]);
300
301         i = 0;
302         while (argv[i])
303                 free(argv[i++]);
304         return rc == 0; /* return 1 if exitcode 0 */
305 }
306 #endif
307 #if ENABLE_FEATURE_FIND_USER
308 ACTF(user)
309 {
310         return (statbuf->st_uid == ap->uid);
311 }
312 #endif
313 #if ENABLE_FEATURE_FIND_GROUP
314 ACTF(group)
315 {
316         return (statbuf->st_gid == ap->gid);
317 }
318 #endif
319 #if ENABLE_FEATURE_FIND_PRINT0
320 ACTF(print0)
321 {
322         printf("%s%c", fileName, '\0');
323         return TRUE;
324 }
325 #endif
326 ACTF(print)
327 {
328         puts(fileName);
329         return TRUE;
330 }
331 #if ENABLE_FEATURE_FIND_PAREN
332 ACTF(paren)
333 {
334         return exec_actions(ap->subexpr, fileName, statbuf);
335 }
336 #endif
337 #if ENABLE_FEATURE_FIND_SIZE
338 ACTF(size)
339 {
340         if (ap->size_char == '+')
341                 return statbuf->st_size > ap->size;
342         if (ap->size_char == '-')
343                 return statbuf->st_size < ap->size;
344         return statbuf->st_size == ap->size;
345 }
346 #endif
347 #if ENABLE_FEATURE_FIND_PRUNE
348 /*
349  * -prune: if -depth is not given, return true and do not descend
350  * current dir; if -depth is given, return false with no effect.
351  * Example:
352  * find dir -name 'asm-*' -prune -o -name '*.[chS]' -print
353  */
354 ACTF(prune)
355 {
356         return SKIP + TRUE;
357 }
358 #endif
359 #if ENABLE_FEATURE_FIND_DELETE
360 ACTF(delete)
361 {
362         int rc;
363         if (S_ISDIR(statbuf->st_mode)) {
364                 rc = rmdir(fileName);
365         } else {
366                 rc = unlink(fileName);
367         }
368         if (rc < 0)
369                 bb_simple_perror_msg(fileName);
370         return TRUE;
371 }
372 #endif
373 #if ENABLE_FEATURE_FIND_CONTEXT
374 ACTF(context)
375 {
376         security_context_t con;
377         int rc;
378
379         if (G.recurse_flags & ACTION_FOLLOWLINKS) {
380                 rc = getfilecon(fileName, &con);
381         } else {
382                 rc = lgetfilecon(fileName, &con);
383         }
384         if (rc < 0)
385                 return FALSE;
386         rc = strcmp(ap->context, con);
387         freecon(con);
388         return rc == 0;
389 }
390 #endif
391
392
393 static int FAST_FUNC fileAction(const char *fileName,
394                 struct stat *statbuf,
395                 void *userData IF_NOT_FEATURE_FIND_MAXDEPTH(UNUSED_PARAM),
396                 int depth IF_NOT_FEATURE_FIND_MAXDEPTH(UNUSED_PARAM))
397 {
398         int i;
399 #if ENABLE_FEATURE_FIND_MAXDEPTH
400 #define minmaxdepth ((int*)userData)
401
402         if (depth < minmaxdepth[0]) return TRUE;
403         if (depth > minmaxdepth[1]) return SKIP;
404 #endif
405
406 #if ENABLE_FEATURE_FIND_XDEV
407         if (S_ISDIR(statbuf->st_mode)) {
408                 if (G.xdev_count) {
409                         for (i = 0; i < G.xdev_count; i++) {
410                                 if (G.xdev_dev[i] == statbuf->st_dev)
411                                         goto found;
412                         }
413                         return SKIP;
414  found: ;
415                 }
416         }
417 #endif
418         i = exec_actions(G.actions, fileName, statbuf);
419         /* Had no explicit -print[0] or -exec? then print */
420         if ((i & TRUE) && G.need_print)
421                 puts(fileName);
422
423 #if ENABLE_FEATURE_FIND_MAXDEPTH
424         if (S_ISDIR(statbuf->st_mode))
425                 if (depth == minmaxdepth[1])
426                         return SKIP;
427 #endif
428         /* Cannot return 0: our caller, recursive_action(),
429          * will perror() and skip dirs (if called on dir) */
430         return (i & SKIP) ? SKIP : TRUE;
431 #undef minmaxdepth
432 }
433
434
435 #if ENABLE_FEATURE_FIND_TYPE
436 static int find_type(const char *type)
437 {
438         int mask = 0;
439
440         if (*type == 'b')
441                 mask = S_IFBLK;
442         else if (*type == 'c')
443                 mask = S_IFCHR;
444         else if (*type == 'd')
445                 mask = S_IFDIR;
446         else if (*type == 'p')
447                 mask = S_IFIFO;
448         else if (*type == 'f')
449                 mask = S_IFREG;
450         else if (*type == 'l')
451                 mask = S_IFLNK;
452         else if (*type == 's')
453                 mask = S_IFSOCK;
454
455         if (mask == 0 || type[1] != '\0')
456                 bb_error_msg_and_die(bb_msg_invalid_arg, type, "-type");
457
458         return mask;
459 }
460 #endif
461
462 #if ENABLE_FEATURE_FIND_PERM \
463  || ENABLE_FEATURE_FIND_MTIME || ENABLE_FEATURE_FIND_MMIN \
464  || ENABLE_FEATURE_FIND_SIZE
465 static const char* plus_minus_num(const char* str)
466 {
467         if (*str == '-' || *str == '+')
468                 str++;
469         return str;
470 }
471 #endif
472
473 static action*** parse_params(char **argv)
474 {
475         enum {
476                                 PARM_a         ,
477                                 PARM_o         ,
478         IF_FEATURE_FIND_NOT(    PARM_char_not  ,)
479 #if ENABLE_DESKTOP
480                                 PARM_and       ,
481                                 PARM_or        ,
482         IF_FEATURE_FIND_NOT(    PARM_not       ,)
483 #endif
484                                 PARM_print     ,
485         IF_FEATURE_FIND_PRINT0( PARM_print0    ,)
486         IF_FEATURE_FIND_DEPTH(  PARM_depth     ,)
487         IF_FEATURE_FIND_PRUNE(  PARM_prune     ,)
488         IF_FEATURE_FIND_DELETE( PARM_delete    ,)
489         IF_FEATURE_FIND_EXEC(   PARM_exec      ,)
490         IF_FEATURE_FIND_PAREN(  PARM_char_brace,)
491         /* All options starting from here require argument */
492                                 PARM_name      ,
493                                 PARM_iname     ,
494         IF_FEATURE_FIND_PATH(   PARM_path      ,)
495         IF_FEATURE_FIND_REGEX(  PARM_regex     ,)
496         IF_FEATURE_FIND_TYPE(   PARM_type      ,)
497         IF_FEATURE_FIND_PERM(   PARM_perm      ,)
498         IF_FEATURE_FIND_MTIME(  PARM_mtime     ,)
499         IF_FEATURE_FIND_MMIN(   PARM_mmin      ,)
500         IF_FEATURE_FIND_NEWER(  PARM_newer     ,)
501         IF_FEATURE_FIND_INUM(   PARM_inum      ,)
502         IF_FEATURE_FIND_USER(   PARM_user      ,)
503         IF_FEATURE_FIND_GROUP(  PARM_group     ,)
504         IF_FEATURE_FIND_SIZE(   PARM_size      ,)
505         IF_FEATURE_FIND_CONTEXT(PARM_context   ,)
506         };
507
508         static const char params[] ALIGN1 =
509                                  "-a\0"
510                                  "-o\0"
511         IF_FEATURE_FIND_NOT(    "!\0"       )
512 #if ENABLE_DESKTOP
513                                  "-and\0"
514                                  "-or\0"
515         IF_FEATURE_FIND_NOT(     "-not\0"    )
516 #endif
517                                  "-print\0"
518         IF_FEATURE_FIND_PRINT0( "-print0\0" )
519         IF_FEATURE_FIND_DEPTH(  "-depth\0"  )
520         IF_FEATURE_FIND_PRUNE(  "-prune\0"  )
521         IF_FEATURE_FIND_DELETE( "-delete\0" )
522         IF_FEATURE_FIND_EXEC(   "-exec\0"   )
523         IF_FEATURE_FIND_PAREN(  "(\0"       )
524         /* All options starting from here require argument */
525                                  "-name\0"
526                                  "-iname\0"
527         IF_FEATURE_FIND_PATH(   "-path\0"   )
528         IF_FEATURE_FIND_REGEX(  "-regex\0"  )
529         IF_FEATURE_FIND_TYPE(   "-type\0"   )
530         IF_FEATURE_FIND_PERM(   "-perm\0"   )
531         IF_FEATURE_FIND_MTIME(  "-mtime\0"  )
532         IF_FEATURE_FIND_MMIN(   "-mmin\0"   )
533         IF_FEATURE_FIND_NEWER(  "-newer\0"  )
534         IF_FEATURE_FIND_INUM(   "-inum\0"   )
535         IF_FEATURE_FIND_USER(   "-user\0"   )
536         IF_FEATURE_FIND_GROUP(  "-group\0"  )
537         IF_FEATURE_FIND_SIZE(   "-size\0"   )
538         IF_FEATURE_FIND_CONTEXT("-context\0")
539                                  ;
540
541         action*** appp;
542         unsigned cur_group = 0;
543         unsigned cur_action = 0;
544         IF_FEATURE_FIND_NOT( bool invert_flag = 0; )
545
546         /* This is the only place in busybox where we use nested function.
547          * So far more standard alternatives were bigger. */
548         /* Suppress a warning "func without a prototype" */
549         auto action* alloc_action(int sizeof_struct, action_fp f);
550         action* alloc_action(int sizeof_struct, action_fp f)
551         {
552                 action *ap;
553                 appp[cur_group] = xrealloc(appp[cur_group], (cur_action+2) * sizeof(*appp));
554                 appp[cur_group][cur_action++] = ap = xmalloc(sizeof_struct);
555                 appp[cur_group][cur_action] = NULL;
556                 ap->f = f;
557                 IF_FEATURE_FIND_NOT( ap->invert = invert_flag; )
558                 IF_FEATURE_FIND_NOT( invert_flag = 0; )
559                 return ap;
560         }
561
562 #define ALLOC_ACTION(name) (action_##name*)alloc_action(sizeof(action_##name), (action_fp) func_##name)
563
564         appp = xzalloc(2 * sizeof(appp[0])); /* appp[0],[1] == NULL */
565
566 /* Actions have side effects and return a true or false value
567  * We implement: -print, -print0, -exec
568  *
569  * The rest are tests.
570  *
571  * Tests and actions are grouped by operators
572  * ( expr )              Force precedence
573  * ! expr                True if expr is false
574  * -not expr             Same as ! expr
575  * expr1 [-a[nd]] expr2  And; expr2 is not evaluated if expr1 is false
576  * expr1 -o[r] expr2     Or; expr2 is not evaluated if expr1 is true
577  * expr1 , expr2         List; both expr1 and expr2 are always evaluated
578  * We implement: (), -a, -o
579  */
580         while (*argv) {
581                 const char *arg = argv[0];
582                 int parm = index_in_strings(params, arg);
583                 const char *arg1 = argv[1];
584
585                 if (parm >= PARM_name) {
586                         /* All options starting from -name require argument */
587                         if (!arg1)
588                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
589                         argv++;
590                 }
591
592                 /* We can use big switch() here, but on i386
593                  * it doesn't give smaller code. Other arches? */
594
595         /* --- Operators --- */
596                 if (parm == PARM_a IF_DESKTOP(|| parm == PARM_and)) {
597                         /* no further special handling required */
598                 }
599                 else if (parm == PARM_o IF_DESKTOP(|| parm == PARM_or)) {
600                         /* start new OR group */
601                         cur_group++;
602                         appp = xrealloc(appp, (cur_group+2) * sizeof(*appp));
603                         /*appp[cur_group] = NULL; - already NULL */
604                         appp[cur_group+1] = NULL;
605                         cur_action = 0;
606                 }
607 #if ENABLE_FEATURE_FIND_NOT
608                 else if (parm == PARM_char_not IF_DESKTOP(|| parm == PARM_not)) {
609                         /* also handles "find ! ! -name 'foo*'" */
610                         invert_flag ^= 1;
611                 }
612 #endif
613
614         /* --- Tests and actions --- */
615                 else if (parm == PARM_print) {
616                         G.need_print = 0;
617                         /* GNU find ignores '!' here: "find ! -print" */
618                         IF_FEATURE_FIND_NOT( invert_flag = 0; )
619                         (void) ALLOC_ACTION(print);
620                 }
621 #if ENABLE_FEATURE_FIND_PRINT0
622                 else if (parm == PARM_print0) {
623                         G.need_print = 0;
624                         IF_FEATURE_FIND_NOT( invert_flag = 0; )
625                         (void) ALLOC_ACTION(print0);
626                 }
627 #endif
628 #if ENABLE_FEATURE_FIND_DEPTH
629                 else if (parm == PARM_depth) {
630                         G.recurse_flags |= ACTION_DEPTHFIRST;
631                 }
632 #endif
633 #if ENABLE_FEATURE_FIND_PRUNE
634                 else if (parm == PARM_prune) {
635                         IF_FEATURE_FIND_NOT( invert_flag = 0; )
636                         (void) ALLOC_ACTION(prune);
637                 }
638 #endif
639 #if ENABLE_FEATURE_FIND_DELETE
640                 else if (parm == PARM_delete) {
641                         G.need_print = 0;
642                         G.recurse_flags |= ACTION_DEPTHFIRST;
643                         (void) ALLOC_ACTION(delete);
644                 }
645 #endif
646 #if ENABLE_FEATURE_FIND_EXEC
647                 else if (parm == PARM_exec) {
648                         int i;
649                         action_exec *ap;
650                         G.need_print = 0;
651                         IF_FEATURE_FIND_NOT( invert_flag = 0; )
652                         ap = ALLOC_ACTION(exec);
653                         ap->exec_argv = ++argv; /* first arg after -exec */
654                         ap->exec_argc = 0;
655                         while (1) {
656                                 if (!*argv) /* did not see ';' until end */
657                                         bb_error_msg_and_die("-exec CMD must end by ';'");
658                                 if (LONE_CHAR(argv[0], ';'))
659                                         break;
660                                 argv++;
661                                 ap->exec_argc++;
662                         }
663                         if (ap->exec_argc == 0)
664                                 bb_error_msg_and_die(bb_msg_requires_arg, arg);
665                         ap->subst_count = xmalloc(ap->exec_argc * sizeof(int));
666                         i = ap->exec_argc;
667                         while (i--)
668                                 ap->subst_count[i] = count_subst(ap->exec_argv[i]);
669                 }
670 #endif
671 #if ENABLE_FEATURE_FIND_PAREN
672                 else if (parm == PARM_char_brace) {
673                         action_paren *ap;
674                         char **endarg;
675                         unsigned nested = 1;
676
677                         endarg = argv;
678                         while (1) {
679                                 if (!*++endarg)
680                                         bb_error_msg_and_die("unpaired '('");
681                                 if (LONE_CHAR(*endarg, '('))
682                                         nested++;
683                                 else if (LONE_CHAR(*endarg, ')') && !--nested) {
684                                         *endarg = NULL;
685                                         break;
686                                 }
687                         }
688                         ap = ALLOC_ACTION(paren);
689                         ap->subexpr = parse_params(argv + 1);
690                         *endarg = (char*) ")"; /* restore NULLed parameter */
691                         argv = endarg;
692                 }
693 #endif
694                 else if (parm == PARM_name || parm == PARM_iname) {
695                         action_name *ap;
696                         ap = ALLOC_ACTION(name);
697                         ap->pattern = arg1;
698                         ap->iname = (parm == PARM_iname);
699                 }
700 #if ENABLE_FEATURE_FIND_PATH
701                 else if (parm == PARM_path) {
702                         action_path *ap;
703                         ap = ALLOC_ACTION(path);
704                         ap->pattern = arg1;
705                 }
706 #endif
707 #if ENABLE_FEATURE_FIND_REGEX
708                 else if (parm == PARM_regex) {
709                         action_regex *ap;
710                         ap = ALLOC_ACTION(regex);
711                         xregcomp(&ap->compiled_pattern, arg1, 0 /*cflags*/);
712                 }
713 #endif
714 #if ENABLE_FEATURE_FIND_TYPE
715                 else if (parm == PARM_type) {
716                         action_type *ap;
717                         ap = ALLOC_ACTION(type);
718                         ap->type_mask = find_type(arg1);
719                 }
720 #endif
721 #if ENABLE_FEATURE_FIND_PERM
722 /* -perm mode   File's permission bits are exactly mode (octal or symbolic).
723  *              Symbolic modes use mode 0 as a point of departure.
724  * -perm -mode  All of the permission bits mode are set for the file.
725  * -perm +mode  Any of the permission bits mode are set for the file.
726  */
727                 else if (parm == PARM_perm) {
728                         action_perm *ap;
729                         ap = ALLOC_ACTION(perm);
730                         ap->perm_char = arg1[0];
731                         arg1 = plus_minus_num(arg1);
732                         ap->perm_mask = 0;
733                         if (!bb_parse_mode(arg1, &ap->perm_mask))
734                                 bb_error_msg_and_die("invalid mode: %s", arg1);
735                 }
736 #endif
737 #if ENABLE_FEATURE_FIND_MTIME
738                 else if (parm == PARM_mtime) {
739                         action_mtime *ap;
740                         ap = ALLOC_ACTION(mtime);
741                         ap->mtime_char = arg1[0];
742                         ap->mtime_days = xatoul(plus_minus_num(arg1));
743                 }
744 #endif
745 #if ENABLE_FEATURE_FIND_MMIN
746                 else if (parm == PARM_mmin) {
747                         action_mmin *ap;
748                         ap = ALLOC_ACTION(mmin);
749                         ap->mmin_char = arg1[0];
750                         ap->mmin_mins = xatoul(plus_minus_num(arg1));
751                 }
752 #endif
753 #if ENABLE_FEATURE_FIND_NEWER
754                 else if (parm == PARM_newer) {
755                         struct stat stat_newer;
756                         action_newer *ap;
757                         ap = ALLOC_ACTION(newer);
758                         xstat(arg1, &stat_newer);
759                         ap->newer_mtime = stat_newer.st_mtime;
760                 }
761 #endif
762 #if ENABLE_FEATURE_FIND_INUM
763                 else if (parm == PARM_inum) {
764                         action_inum *ap;
765                         ap = ALLOC_ACTION(inum);
766                         ap->inode_num = xatoul(arg1);
767                 }
768 #endif
769 #if ENABLE_FEATURE_FIND_USER
770                 else if (parm == PARM_user) {
771                         action_user *ap;
772                         ap = ALLOC_ACTION(user);
773                         ap->uid = bb_strtou(arg1, NULL, 10);
774                         if (errno)
775                                 ap->uid = xuname2uid(arg1);
776                 }
777 #endif
778 #if ENABLE_FEATURE_FIND_GROUP
779                 else if (parm == PARM_group) {
780                         action_group *ap;
781                         ap = ALLOC_ACTION(group);
782                         ap->gid = bb_strtou(arg1, NULL, 10);
783                         if (errno)
784                                 ap->gid = xgroup2gid(arg1);
785                 }
786 #endif
787 #if ENABLE_FEATURE_FIND_SIZE
788                 else if (parm == PARM_size) {
789 /* -size n[bckw]: file uses n units of space
790  * b (default): units are 512-byte blocks
791  * c: 1 byte
792  * k: kilobytes
793  * w: 2-byte words
794  */
795 #if ENABLE_LFS
796 #define XATOU_SFX xatoull_sfx
797 #else
798 #define XATOU_SFX xatoul_sfx
799 #endif
800                         static const struct suffix_mult find_suffixes[] = {
801                                 { "c", 1 },
802                                 { "w", 2 },
803                                 { "", 512 },
804                                 { "b", 512 },
805                                 { "k", 1024 },
806                                 { "", 0 }
807                         };
808                         action_size *ap;
809                         ap = ALLOC_ACTION(size);
810                         ap->size_char = arg1[0];
811                         ap->size = XATOU_SFX(plus_minus_num(arg1), find_suffixes);
812                 }
813 #endif
814 #if ENABLE_FEATURE_FIND_CONTEXT
815                 else if (parm == PARM_context) {
816                         action_context *ap;
817                         ap = ALLOC_ACTION(context);
818                         ap->context = NULL;
819                         /* SELinux headers erroneously declare non-const parameter */
820                         if (selinux_raw_to_trans_context((char*)arg1, &ap->context))
821                                 bb_simple_perror_msg(arg1);
822                 }
823 #endif
824                 else {
825                         bb_error_msg("unrecognized: %s", arg);
826                         bb_show_usage();
827                 }
828                 argv++;
829         }
830         return appp;
831 #undef ALLOC_ACTION
832 }
833
834
835 int find_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
836 int find_main(int argc, char **argv)
837 {
838         static const char options[] ALIGN1 =
839                           "-follow\0"
840 IF_FEATURE_FIND_XDEV(    "-xdev\0"    )
841 IF_FEATURE_FIND_MAXDEPTH("-mindepth\0""-maxdepth\0")
842                           ;
843         enum {
844                           OPT_FOLLOW,
845 IF_FEATURE_FIND_XDEV(    OPT_XDEV    ,)
846 IF_FEATURE_FIND_MAXDEPTH(OPT_MINDEPTH,)
847         };
848
849         char *arg;
850         char **argp;
851         int i, firstopt, status = EXIT_SUCCESS;
852 #if ENABLE_FEATURE_FIND_MAXDEPTH
853         int minmaxdepth[2] = { 0, INT_MAX };
854 #else
855 #define minmaxdepth NULL
856 #endif
857
858         INIT_G();
859
860         for (firstopt = 1; firstopt < argc; firstopt++) {
861                 if (argv[firstopt][0] == '-')
862                         break;
863                 if (ENABLE_FEATURE_FIND_NOT && LONE_CHAR(argv[firstopt], '!'))
864                         break;
865 #if ENABLE_FEATURE_FIND_PAREN
866                 if (LONE_CHAR(argv[firstopt], '('))
867                         break;
868 #endif
869         }
870         if (firstopt == 1) {
871                 argv[0] = (char*)".";
872                 argv--;
873                 firstopt++;
874         }
875
876 /* All options always return true. They always take effect
877  * rather than being processed only when their place in the
878  * expression is reached.
879  * We implement: -follow, -xdev, -maxdepth
880  */
881         /* Process options, and replace then with -a */
882         /* (-a will be ignored by recursive parser later) */
883         argp = &argv[firstopt];
884         while ((arg = argp[0])) {
885                 int opt = index_in_strings(options, arg);
886                 if (opt == OPT_FOLLOW) {
887                         G.recurse_flags |= ACTION_FOLLOWLINKS | ACTION_DANGLING_OK;
888                         argp[0] = (char*)"-a";
889                 }
890 #if ENABLE_FEATURE_FIND_XDEV
891                 if (opt == OPT_XDEV) {
892                         struct stat stbuf;
893                         if (!G.xdev_count) {
894                                 G.xdev_count = firstopt - 1;
895                                 G.xdev_dev = xmalloc(G.xdev_count * sizeof(dev_t));
896                                 for (i = 1; i < firstopt; i++) {
897                                         /* not xstat(): shouldn't bomb out on
898                                          * "find not_exist exist -xdev" */
899                                         if (stat(argv[i], &stbuf))
900                                                 stbuf.st_dev = -1L;
901                                         G.xdev_dev[i-1] = stbuf.st_dev;
902                                 }
903                         }
904                         argp[0] = (char*)"-a";
905                 }
906 #endif
907 #if ENABLE_FEATURE_FIND_MAXDEPTH
908                 if (opt == OPT_MINDEPTH || opt == OPT_MINDEPTH + 1) {
909                         if (!argp[1])
910                                 bb_show_usage();
911                         minmaxdepth[opt - OPT_MINDEPTH] = xatoi_u(argp[1]);
912                         argp[0] = (char*)"-a";
913                         argp[1] = (char*)"-a";
914                         argp++;
915                 }
916 #endif
917                 argp++;
918         }
919
920         G.actions = parse_params(&argv[firstopt]);
921
922         for (i = 1; i < firstopt; i++) {
923                 if (!recursive_action(argv[i],
924                                 G.recurse_flags,/* flags */
925                                 fileAction,     /* file action */
926                                 fileAction,     /* dir action */
927 #if ENABLE_FEATURE_FIND_MAXDEPTH
928                                 minmaxdepth,    /* user data */
929 #else
930                                 NULL,           /* user data */
931 #endif
932                                 0))             /* depth */
933                         status = EXIT_FAILURE;
934         }
935         return status;
936 }