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