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