• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* find.c - Search directories for matching files.
2  *
3  * Copyright 2014 Rob Landley <rob@landley.net>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/find.c
6  *
7  * Our "unspecified" behavior for no paths is to use "."
8  * Parentheses can only stack 4096 deep
9  * Not treating two {} as an error, but only using last
10  * TODO: -context
11 
12 USE_FIND(NEWTOY(find, "?^HL[-HL]", TOYFLAG_USR|TOYFLAG_BIN))
13 
14 config FIND
15   bool "find"
16   default y
17   help
18     usage: find [-HL] [DIR...] [<options>]
19 
20     Search directories for matching files.
21     Default: search ".", match all, -print matches.
22 
23     -H  Follow command line symlinks         -L  Follow all symlinks
24 
25     Match filters:
26     -name  PATTERN   filename with wildcards  (-iname case insensitive)
27     -path  PATTERN   path name with wildcards (-ipath case insensitive)
28     -user  UNAME     belongs to user UNAME     -nouser     user ID not known
29     -group GROUP     belongs to group GROUP    -nogroup    group ID not known
30     -perm  [-/]MODE  permissions (-=min /=any) -prune      ignore dir contents
31     -size  N[c]      512 byte blocks (c=bytes) -xdev       only this filesystem
32     -links N         hardlink count            -atime N[u] accessed N units ago
33     -ctime N[u]      created N units ago       -mtime N[u] modified N units ago
34     -newer FILE      newer mtime than FILE     -mindepth N at least N dirs down
35     -depth           ignore contents of dir    -maxdepth N at most N dirs down
36     -inum N          inode number N            -empty      empty files and dirs
37     -type [bcdflps]  type is (block, char, dir, file, symlink, pipe, socket)
38     -true            always true               -false      always false
39     -context PATTERN security context          -executable access(X_OK) perm+ACL
40     -newerXY FILE    X=acm time > FILE's Y=acm time (Y=t: FILE is literal time)
41     -quit            exit immediately
42 
43     Numbers N may be prefixed by a - (less than) or + (greater than). Units for
44     -Xtime are d (days, default), h (hours), m (minutes), or s (seconds).
45 
46     Combine matches with:
47     !, -a, -o, ( )    not, and, or, group expressions
48 
49     Actions:
50     -print  Print match with newline  -print0        Print match with null
51     -exec   Run command with path     -execdir       Run command in file's dir
52     -ok     Ask before exec           -okdir         Ask before execdir
53     -delete Remove matching file/dir  -printf FORMAT Print using format string
54 
55     Commands substitute "{}" with matched file. End with ";" to run each file,
56     or "+" (next argument after "{}") to collect and run with multiple files.
57 
58     -printf FORMAT characters are \ escapes and:
59     %b  512 byte blocks used
60     %f  basename            %g  textual gid          %G  numeric gid
61     %i  decimal inode       %l  target of symlink    %m  octal mode
62     %M  ls format type/mode %p  path to file         %P  path to file minus DIR
63     %s  size in bytes       %T@ mod time as unixtime
64     %u  username            %U  numeric uid          %Z  security context
65 */
66 
67 #define FOR_find
68 #include "toys.h"
69 
70 GLOBALS(
71   char **filter;
72   struct double_list *argdata;
73   int topdir, xdev, depth;
74   time_t now;
75   long max_bytes;
76   char *start;
77 )
78 
79 struct execdir_data {
80   struct execdir_data *next;
81 
82   int namecount;
83   struct double_list *names;
84 };
85 
86 // None of this can go in TT because you can have more than one -exec
87 struct exec_range {
88   char *next, *prev;  // layout compatible with struct double_list
89 
90   int dir, plus, arglen, argsize, curly;
91   char **argstart;
92   struct execdir_data exec, *execdir;
93 };
94 
95 // Perform pending -exec (if any)
flush_exec(struct dirtree * new,struct exec_range * aa)96 static int flush_exec(struct dirtree *new, struct exec_range *aa)
97 {
98   struct execdir_data *bb = aa->execdir ? aa->execdir : &aa->exec;
99   char **newargs;
100   int rc, revert = 0;
101 
102   if (!bb->namecount) return 0;
103 
104   dlist_terminate(bb->names);
105 
106   // switch to directory for -execdir, or back to top if we have an -execdir
107   // _and_ a normal -exec, or are at top of tree in -execdir
108   if (TT.topdir != -1) {
109     if (aa->dir && new && new->parent) {
110       revert++;
111       rc = fchdir(new->parent->dirfd);
112     } else rc = fchdir(TT.topdir);
113     if (rc) {
114       perror_msg_raw(revert ? new->name : ".");
115 
116       return rc;
117     }
118   }
119 
120   // execdir: accumulated execs in this directory's children.
121   newargs = xmalloc(sizeof(char *)*(aa->arglen+bb->namecount+1));
122   if (aa->curly < 0) {
123     memcpy(newargs, aa->argstart, sizeof(char *)*aa->arglen);
124     newargs[aa->arglen] = 0;
125   } else {
126     int pos = aa->curly, rest = aa->arglen - aa->curly;
127     struct double_list *dl;
128 
129     // Collate argument list
130     memcpy(newargs, aa->argstart, sizeof(char *)*pos);
131     for (dl = bb->names; dl; dl = dl->next) newargs[pos++] = dl->data;
132     rest = aa->arglen - aa->curly - 1;
133     memcpy(newargs+pos, aa->argstart+aa->curly+1, sizeof(char *)*rest);
134     newargs[pos+rest] = 0;
135   }
136 
137   rc = xrun(newargs);
138 
139   llist_traverse(bb->names, llist_free_double);
140   bb->names = 0;
141   bb->namecount = 0;
142 
143   if (revert) revert = fchdir(TT.topdir);
144 
145   return rc;
146 }
147 
148 // Return numeric value with explicit sign
compare_numsign(long val,long units,char * str)149 static int compare_numsign(long val, long units, char *str)
150 {
151   char sign = 0;
152   long myval;
153 
154   if (*str == '+' || *str == '-') sign = *(str++);
155   else if (!isdigit(*str)) error_exit("%s not [+-]N", str);
156   myval = atolx(str);
157   if (units && isdigit(str[strlen(str)-1])) myval *= units;
158 
159   if (sign == '+') return val > myval;
160   if (sign == '-') return val < myval;
161   return val == myval;
162 }
163 
do_print(struct dirtree * new,char c)164 static void do_print(struct dirtree *new, char c)
165 {
166   char *s=dirtree_path(new, 0);
167 
168   xprintf("%s%c", s, c);
169   free(s);
170 }
171 
172 // Descend or ascend -execdir + directory level
execdir(struct dirtree * new,int flush)173 static void execdir(struct dirtree *new, int flush)
174 {
175   struct double_list *dl;
176   struct exec_range *aa;
177   struct execdir_data *bb;
178 
179   if (new && TT.topdir == -1) return;
180 
181   for (dl = TT.argdata; dl; dl = dl->next) {
182     if (dl->prev != (void *)1) continue;
183     aa = (void *)dl;
184     if (!aa->plus || (new && !aa->dir)) continue;
185 
186     if (flush) {
187 
188       // Flush pending "-execdir +" instances for this dir
189       // or flush everything for -exec at top
190       toys.exitval |= flush_exec(new, aa);
191 
192       // pop per-directory struct
193       if ((bb = aa->execdir)) {
194         aa->execdir = bb->next;
195         free(bb);
196       }
197     } else if (aa->dir) {
198 
199       // Push new per-directory struct for -execdir/okdir + codepath. (Can't
200       // use new->extra because command line may have multiple -execdir)
201       bb = xzalloc(sizeof(struct execdir_data));
202       bb->next = aa->execdir;
203       aa->execdir = bb;
204     }
205   }
206 }
207 
208 // Call this with 0 for first pass argument parsing and syntax checking (which
209 // populates argdata). Later commands traverse argdata (in order) when they
210 // need "do once" results.
do_find(struct dirtree * new)211 static int do_find(struct dirtree *new)
212 {
213   int pcount = 0, print = 0, not = 0, active = !!new, test = active, recurse;
214   struct double_list *argdata = TT.argdata;
215   char *s, **ss;
216 
217   recurse = DIRTREE_STATLESS|DIRTREE_COMEAGAIN|
218     (DIRTREE_SYMFOLLOW*!!(toys.optflags&FLAG_L));
219 
220   // skip . and .. below topdir, handle -xdev and -depth
221   if (new) {
222     // Handle stat failures first.
223     if (new->again&2) {
224       if (!new->parent || errno != ENOENT) {
225         perror_msg("'%s'", s = dirtree_path(new, 0));
226         free(s);
227       }
228       return 0;
229     }
230     if (new->parent) {
231       if (!dirtree_notdotdot(new)) return 0;
232       if (TT.xdev && new->st.st_dev != new->parent->st.st_dev) recurse = 0;
233     } else TT.start = new->name;
234 
235     if (S_ISDIR(new->st.st_mode)) {
236       // Descending into new directory
237       if (!new->again) {
238         struct dirtree *n;
239 
240         for (n = new->parent; n; n = n->parent) {
241           if (n->st.st_ino==new->st.st_ino && n->st.st_dev==new->st.st_dev) {
242             error_msg("'%s': loop detected", s = dirtree_path(new, 0));
243             free(s);
244 
245             return 0;
246           }
247         }
248 
249         if (TT.depth) {
250           execdir(new, 0);
251 
252           return recurse;
253         }
254       // Done with directory (COMEAGAIN call)
255       } else {
256         execdir(new, 1);
257         recurse = 0;
258         if (!TT.depth) return 0;
259       }
260     }
261   }
262 
263   // pcount: parentheses stack depth (using toybuf bytes, 4096 max depth)
264   // test: result of most recent test
265   // active: if 0 don't perform tests
266   // not: a pending ! applies to this test (only set if performing tests)
267   // print: saw one of print/ok/exec, no need for default -print
268 
269   if (TT.filter) for (ss = TT.filter; *ss; ss++) {
270     int check = active && test;
271 
272     s = *ss;
273 
274     // handle ! ( ) using toybuf as a stack
275     if (*s != '-') {
276       if (s[1]) goto error;
277 
278       if (*s == '!') {
279         // Don't invert if we're not making a decision
280         if (check) not = !not;
281 
282       // Save old "not" and "active" on toybuf stack.
283       // Deactivate this parenthetical if !test
284       // Note: test value should never change while !active
285       } else if (*s == '(') {
286         if (pcount == sizeof(toybuf)) goto error;
287         toybuf[pcount++] = not+(active<<1);
288         if (!check) active = 0;
289         not = 0;
290 
291       // Pop status, apply deferred not to test
292       } else if (*s == ')') {
293         if (--pcount < 0) goto error;
294         // Pop active state, apply deferred not (which was only set if checking)
295         active = (toybuf[pcount]>>1)&1;
296         if (active && (toybuf[pcount]&1)) test = !test;
297         not = 0;
298       } else goto error;
299 
300       continue;
301     } else s++;
302 
303     if (!strcmp(s, "xdev")) TT.xdev = 1;
304     else if (!strcmp(s, "delete")) {
305       // Delete forces depth first
306       TT.depth = 1;
307       if (new && check)
308         test = !unlinkat(dirtree_parentfd(new), new->name,
309           S_ISDIR(new->st.st_mode) ? AT_REMOVEDIR : 0);
310     } else if (!strcmp(s, "depth") || !strcmp(s, "d")) TT.depth = 1;
311     else if (!strcmp(s, "o") || !strcmp(s, "or")) {
312       if (not) goto error;
313       if (active) {
314         if (!test) test = 1;
315         else active = 0;     // decision has been made until next ")"
316       }
317     } else if (!strcmp(s, "not")) {
318       if (check) not = !not;
319       continue;
320     } else if (!strcmp(s, "true")) {
321       if (check) test = 1;
322     } else if (!strcmp(s, "false")) {
323       if (check) test = 0;
324 
325     // Mostly ignore NOP argument
326     } else if (!strcmp(s, "a") || !strcmp(s, "and") || !strcmp(s, "noleaf")) {
327       if (not) goto error;
328 
329     } else if (!strcmp(s, "print") || !strcmp("print0", s)) {
330       print++;
331       if (check) do_print(new, s[5] ? 0 : '\n');
332 
333     } else if (!strcmp(s, "empty")) {
334       if (check) {
335         // Alas neither st_size nor st_blocks reliably show an empty directory
336         if (S_ISDIR(new->st.st_mode)) {
337           int fd = openat(dirtree_parentfd(new), new->name, O_RDONLY);
338           DIR *dfd = fdopendir(fd);
339           struct dirent *de = (void *)1;
340           if (dfd) {
341             while ((de = readdir(dfd)) && isdotdot(de->d_name));
342             closedir(dfd);
343           }
344           if (de) test = 0;
345         } else if (S_ISREG(new->st.st_mode)) {
346           if (new->st.st_size) test = 0;
347         } else test = 0;
348       }
349     } else if (!strcmp(s, "nouser")) {
350       if (check && bufgetpwuid(new->st.st_uid)) test = 0;
351     } else if (!strcmp(s, "nogroup")) {
352       if (check && bufgetgrgid(new->st.st_gid)) test = 0;
353     } else if (!strcmp(s, "prune")) {
354       if (check && S_ISDIR(new->st.st_mode) && !TT.depth) recurse = 0;
355     } else if (!strcmp(s, "executable")) {
356       if (check && faccessat(dirtree_parentfd(new), new->name,X_OK,0)) test = 0;
357     } else if (!strcmp(s, "quit")) {
358       if (check) {
359         execdir(0, 1);
360         xexit();
361       }
362 
363     // Remaining filters take an argument
364     } else {
365       if (!strcmp(s, "name") || !strcmp(s, "iname")
366         || !strcmp(s, "wholename") || !strcmp(s, "iwholename")
367         || !strcmp(s, "path") || !strcmp(s, "ipath")
368         || !strcmp(s, "lname") || !strcmp(s, "ilname"))
369       {
370         int i = (*s == 'i'), is_path = (s[i] != 'n');
371         char *arg = ss[1], *path = 0, *name = new ? new->name : arg;
372 
373         // Handle path expansion and case flattening
374         if (new && s[i] == 'l')
375           name = path = xreadlinkat(dirtree_parentfd(new), new->name);
376         else if (new && is_path) name = path = dirtree_path(new, 0);
377         if (i) {
378           if ((check || !new) && name) name = strlower(name);
379           if (!new) dlist_add(&TT.argdata, name);
380           else arg = ((struct double_list *)llist_pop(&argdata))->data;
381         }
382 
383         if (check) {
384           test = !fnmatch(arg, path ? name : basename(name),
385             FNM_PATHNAME*(!is_path));
386           if (i) free(name);
387         }
388         free(path);
389       } else if (!CFG_TOYBOX_LSM_NONE && !strcmp(s, "context")) {
390         if (check) {
391           char *path = dirtree_path(new, 0), *context;
392 
393           if (lsm_get_context(path, &context) != -1) {
394             test = !fnmatch(ss[1], context, 0);
395             free(context);
396           } else test = 0;
397           free(path);
398         }
399       } else if (!strcmp(s, "perm")) {
400         if (check) {
401           char *m = ss[1];
402           int match_min = *m == '-',
403               match_any = *m == '/';
404           mode_t m1 = string_to_mode(m+(match_min || match_any), 0),
405                  m2 = new->st.st_mode & 07777;
406 
407           if (match_min || match_any) m2 &= m1;
408           test = match_any ? !m1 || m2 : m1 == m2;
409         }
410       } else if (!strcmp(s, "type")) {
411         if (check) {
412           int types[] = {S_IFBLK, S_IFCHR, S_IFDIR, S_IFLNK, S_IFIFO,
413                          S_IFREG, S_IFSOCK}, i;
414           char *t = ss[1];
415 
416           for (; *t; t++) {
417             if (*t == ',') continue;
418             i = stridx("bcdlpfs", *t);
419             if (i<0) error_exit("bad -type '%c'", *t);
420             if ((new->st.st_mode & S_IFMT) == types[i]) break;
421           }
422           test = *t;
423         }
424 
425       } else if (strchr("acm", *s)
426         && (!strcmp(s+1, "time") || !strcmp(s+1, "min")))
427       {
428         if (check) {
429           char *copy = ss[1];
430           time_t thyme = (int []){new->st.st_atime, new->st.st_ctime,
431                                   new->st.st_mtime}[stridx("acm", *s)];
432           int len = strlen(copy), uu, units = (s[1]=='m') ? 60 : 86400;
433 
434           if (len && -1!=(uu = stridx("dhms",tolower(copy[len-1])))) {
435             copy = xstrdup(copy);
436             copy[--len] = 0;
437             units = (int []){86400, 3600, 60, 1}[uu];
438           }
439           test = compare_numsign(TT.now - thyme, units, copy);
440           if (copy != ss[1]) free(copy);
441         }
442       } else if (!strcmp(s, "size")) {
443         if (check) test = compare_numsign(new->st.st_size, 512, ss[1]);
444       } else if (!strcmp(s, "links")) {
445         if (check) test = compare_numsign(new->st.st_nlink, 0, ss[1]);
446       } else if (!strcmp(s, "inum")) {
447         if (check) test = compare_numsign(new->st.st_ino, 0, ss[1]);
448       } else if (!strcmp(s, "mindepth") || !strcmp(s, "maxdepth")) {
449         if (check) {
450           struct dirtree *dt = new;
451           int i = 0, d = atolx(ss[1]);
452 
453           while ((dt = dt->parent)) i++;
454           if (s[1] == 'i') {
455             test = i >= d;
456             if (i == d && not) recurse = 0;
457           } else {
458             test = i <= d;
459             if (i == d && !not) recurse = 0;
460           }
461         }
462       } else if (!strcmp(s, "user") || !strcmp(s, "group")
463               || strstart(&s, "newer"))
464       {
465         int macoff[] = {offsetof(struct stat, st_mtim),
466           offsetof(struct stat, st_atim), offsetof(struct stat, st_ctim)};
467         struct {
468           void *next, *prev;
469           union {
470             uid_t uid;
471             gid_t gid;
472             struct timespec tm;
473           } u;
474         } *udl;
475 
476         if (!new) {
477           if (ss[1]) {
478             udl = xmalloc(sizeof(*udl));
479             dlist_add_nomalloc(&TT.argdata, (void *)udl);
480 
481             if (s != 1+*ss) {
482               if (*s && (s[2] || !strchr("Bmac", *s) || !strchr("tBmac", s[1])))
483                 goto error;
484               if (!*s || s[1]!='t') {
485                 struct stat st;
486 
487                 xstat(ss[1], &st);
488                 udl->u.tm = *(struct timespec *)(((char *)&st)
489                   + macoff[!*s ? 0 : stridx("ac", s[1])+1]);
490               } else if (s[1] == 't') {
491                 unsigned nano;
492 
493                 xparsedate(ss[1], &(udl->u.tm.tv_sec), &nano, 1);
494                 udl->u.tm.tv_nsec = nano;
495               }
496             } else if (*s == 'u') udl->u.uid = xgetuid(ss[1]);
497             else udl->u.gid = xgetgid(ss[1]);
498           }
499         } else {
500           udl = (void *)llist_pop(&argdata);
501           if (check) {
502             if (*s == 'u') test = new->st.st_uid == udl->u.uid;
503             else if (*s == 'g') test = new->st.st_gid == udl->u.gid;
504             else {
505               struct timespec *tm = (void *)(((char *)&new->st)
506                 + macoff[!s[5] ? 0 : stridx("ac", s[5])+1]);
507 
508               if (s[5] == 'B') test = 0;
509               else test = (tm->tv_sec == udl->u.tm.tv_sec)
510                 ? tm->tv_nsec > udl->u.tm.tv_nsec
511                 : tm->tv_sec > udl->u.tm.tv_sec;
512             }
513           }
514         }
515       } else if (!strcmp(s, "exec") || !strcmp("ok", s)
516               || !strcmp(s, "execdir") || !strcmp(s, "okdir"))
517       {
518         struct exec_range *aa;
519 
520         print++;
521 
522         // Initial argument parsing pass
523         if (!new) {
524           int len;
525 
526           // catch "-exec" with no args and "-exec \;"
527           if (!ss[1] || !strcmp(ss[1], ";")) error_exit("'%s' needs 1 arg", s);
528 
529           dlist_add_nomalloc(&TT.argdata, (void *)(aa = xzalloc(sizeof(*aa))));
530           aa->argstart = ++ss;
531           aa->curly = -1;
532 
533           // Record command line arguments to -exec
534           for (len = 0; ss[len]; len++) {
535             if (!strcmp(ss[len], ";")) break;
536             else if (!strcmp(ss[len], "{}")) {
537               aa->curly = len;
538               if (ss[len+1] && !strcmp(ss[len+1], "+")) {
539                 aa->plus++;
540                 len++;
541                 break;
542               }
543             } else aa->argsize += sizeof(char *) + strlen(ss[len]) + 1;
544           }
545           if (!ss[len]) error_exit("-exec without %s",
546             aa->curly!=-1 ? "\\;" : "{}");
547           ss += len;
548           aa->arglen = len;
549           aa->dir = !!strchr(s, 'd');
550           if (TT.topdir == -1) TT.topdir = xopenro(".");
551 
552         // collect names and execute commands
553         } else {
554           char *name, *ss1 = ss[1];
555           struct execdir_data *bb;
556 
557           // Grab command line exec argument list
558           aa = (void *)llist_pop(&argdata);
559           ss += aa->arglen + 1;
560 
561           if (!check) goto cont;
562           // name is always a new malloc, so we can always free it.
563           name = aa->dir ? xstrdup(new->name) : dirtree_path(new, 0);
564 
565           if (*s == 'o') {
566             fprintf(stderr, "[%s] %s", ss1, name);
567             if (!(test = yesno(0))) {
568               free(name);
569               goto cont;
570             }
571           }
572 
573           // Add next name to list (global list without -dir, local with)
574           bb = aa->execdir ? aa->execdir : &aa->exec;
575           dlist_add(&bb->names, name);
576           bb->namecount++;
577 
578           // -exec + collates and saves result in exitval
579           if (aa->plus) {
580             // Mark entry so COMEAGAIN can call flush_exec() in parent.
581             // This is never a valid pointer value for prev to have otherwise
582             // Done here vs argument parsing pass so it's after dlist_terminate
583             aa->prev = (void *)1;
584 
585             // Flush if the child's environment space gets too large.
586             // Linux caps individual arguments/variables at 131072 bytes,
587             // so this counter can't wrap.
588             if ((aa->plus += sizeof(char *)+strlen(name)+1) > TT.max_bytes) {
589               aa->plus = 1;
590               toys.exitval |= flush_exec(new, aa);
591             }
592           } else test = !flush_exec(new, aa);
593         }
594 
595         // Argument consumed, skip the check.
596         goto cont;
597       } else if (!strcmp(s, "printf")) {
598         char *fmt, *ff, next[32], buf[64], ch;
599         long ll;
600         int len;
601 
602         print++;
603         if (check) for (fmt = ss[1]; *fmt; fmt++) {
604           // Print the parts that aren't escapes
605           if (*fmt == '\\') {
606             unsigned u;
607 
608             if (fmt[1] == 'c') break;
609             if ((u = unescape2(&fmt, 0))<128) putchar(u);
610             else printf("%.*s", (int)wcrtomb(buf, u, 0), buf);
611             fmt--;
612           } else if (*fmt != '%') putchar(*fmt);
613           else if (*++fmt == '%') putchar('%');
614           else {
615             fmt = next_printf(ff = fmt-1, 0);
616             if ((len = fmt-ff)>28) error_exit("bad %.*s", len+1, ff);
617             memcpy(next, ff, len);
618             ff = 0;
619             ch = *fmt;
620 
621             // long long is its own stack size on LP64, so handle seperately
622             if (ch == 'i' || ch == 's') {
623               strcpy(next+len, "lld");
624               printf(next, (ch == 'i') ? (long long)new->st.st_ino
625                 : (long long)new->st.st_size);
626             } else {
627 
628               // LP64 says these are all a single "long" argument to printf
629               strcpy(next+len, "s");
630               if (ch == 'G') next[len] = 'd', ll = new->st.st_gid;
631               else if (ch == 'm') next[len] = 'o', ll = new->st.st_mode&~S_IFMT;
632               else if (ch == 'U') next[len] = 'd', ll = new->st.st_uid;
633               else if (ch == 'f') ll = (long)new->name;
634               else if (ch == 'g') ll = (long)getgroupname(new->st.st_gid);
635               else if (ch == 'u') ll = (long)getusername(new->st.st_uid);
636               else if (ch == 'l') {
637                 ll = (long)(ff = xreadlinkat(dirtree_parentfd(new), new->name));
638                 if (!ll) ll = (long)"";
639               } else if (ch == 'M') {
640                 mode_to_string(new->st.st_mode, buf);
641                 ll = (long)buf;
642               } else if (ch == 'P') {
643                 ch = *TT.start;
644                 *TT.start = 0;
645                 ll = (long)(ff = dirtree_path(new, 0));
646                 *TT.start = ch;
647               } else if (ch == 'p') ll = (long)(ff = dirtree_path(new, 0));
648               else if (ch == 'T') {
649                 if (*++fmt!='@') error_exit("bad -printf %%T: %%T%c", *fmt);
650                 sprintf(buf, "%lld.%ld", (long long)new->st.st_mtim.tv_sec,
651                              new->st.st_mtim.tv_nsec);
652                 ll = (long)buf;
653               } else if (ch == 'Z') {
654                 char *path = dirtree_path(new, 0);
655 
656                 ll = (lsm_get_context(path, &ff) != -1) ? (long)ff : (long)"?";
657                 free(path);
658               } else error_exit("bad -printf %%%c", ch);
659 
660               printf(next, ll);
661               free(ff);
662             }
663           }
664         }
665       } else goto error;
666 
667       // This test can go at the end because we do a syntax checking
668       // pass first. Putting it here gets the error message (-unknown
669       // vs -known noarg) right.
670       if (!*++ss) error_exit("'%s' needs 1 arg", --s);
671     }
672 cont:
673     // Apply pending "!" to result
674     if (active && not) test = !test;
675     not = 0;
676   }
677 
678   if (new) {
679     // If there was no action, print
680     if (!print && test) do_print(new, '\n');
681 
682     if (S_ISDIR(new->st.st_mode)) execdir(new, 0);
683 
684   } else dlist_terminate(TT.argdata);
685 
686   return recurse;
687 
688 error:
689   error_exit("bad arg '%s'", *ss);
690 }
691 
find_main(void)692 void find_main(void)
693 {
694   int i, len;
695   char **ss = (char *[]){"."};
696 
697   TT.topdir = -1;
698   TT.max_bytes = sysconf(_SC_ARG_MAX) - environ_bytes();
699 
700   // Distinguish paths from filters
701   for (len = 0; toys.optargs[len]; len++)
702     if (*toys.optargs[len] && strchr("-!(", *toys.optargs[len])) break;
703   TT.filter = toys.optargs+len;
704 
705   // use "." if no paths
706   if (len) ss = toys.optargs;
707   else len = 1;
708 
709   // first pass argument parsing, verify args match up, handle "evaluate once"
710   TT.now = time(0);
711   do_find(0);
712 
713   // Loop through paths
714   for (i = 0; i < len; i++)
715     dirtree_flagread(ss[i],
716       DIRTREE_STATLESS|(DIRTREE_SYMFOLLOW*!!(toys.optflags&(FLAG_H|FLAG_L))),
717       do_find);
718 
719   execdir(0, 1);
720 
721   if (CFG_TOYBOX_FREE) {
722     close(TT.topdir);
723     llist_traverse(TT.argdata, free);
724   }
725 }
726