xref: /aosp_15_r20/external/toybox/toys/posix/find.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* find.c - Search directories for matching files.
2  *
3  * Copyright 2014 Rob Landley <[email protected]>
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      ignore case -name
27     -path  PATTERN   path name with wildcards  -ipath      ignore case -path
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            -empty      empty files and dirs
33     -atime N[u]      accessed N units ago      -true       always true
34     -ctime N[u]      created N units ago       -false      always false
35     -mtime N[u]      modified N units ago      -executable access(X_OK) perm+ACL
36     -inum  N         inode number N            -readable   access(R_OK) perm+ACL
37     -context PATTERN security context          -depth      contents before dir
38     -samefile FILE   hardlink to FILE          -maxdepth N at most N dirs down
39     -newer    FILE   newer mtime than FILE     -mindepth N at least N dirs down
40     -newerXY  FILE   X=acm time > FILE's Y=acm time (Y=t: FILE is literal time)
41     -type [bcdflps]  type is (block, char, dir, file, symlink, pipe, socket)
42 
43     Numbers N may be prefixed by - (less than) or + (greater than). Units for
44     -[acm]time 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     -quit   Exit immediately
55 
56     Commands substitute "{}" with matched file. End with ";" to run each file,
57     or "+" (next argument after "{}") to collect and run with multiple files.
58 
59     -printf FORMAT characters are \ escapes and:
60     %b  512 byte blocks used
61     %f  basename            %g  textual gid          %G  numeric gid
62     %i  decimal inode       %l  target of symlink    %m  octal mode
63     %M  ls format type/mode %p  path to file         %P  path to file minus DIR
64     %s  size in bytes       %T@ mod time as unixtime
65     %u  username            %U  numeric uid          %Z  security context
66 */
67 
68 #define FOR_find
69 #include "toys.h"
70 
71 GLOBALS(
72   char **filter;
73   struct double_list *argdata;
74   int topdir, xdev, depth;
75   time_t now;
76   long max_bytes;
77   char *start;
78 )
79 
80 struct execdir_data {
81   struct execdir_data *next;
82 
83   int namecount;
84   struct double_list *names;
85 };
86 
87 // None of this can go in TT because you can have more than one -exec
88 struct exec_range {
89   char *next, *prev;  // layout compatible with struct double_list
90 
91   int dir, plus, arglen, argsize, curly;
92   char **argstart;
93   struct execdir_data exec, *execdir;
94 };
95 
96 // Perform pending -exec (if any)
flush_exec(struct dirtree * new,struct exec_range * aa)97 static int flush_exec(struct dirtree *new, struct exec_range *aa)
98 {
99   struct execdir_data *bb = aa->execdir ? aa->execdir : &aa->exec;
100   char **newargs;
101   int rc, revert = 0;
102 
103   if (!bb->namecount) return 0;
104 
105   dlist_terminate(bb->names);
106 
107   // switch to directory for -execdir, or back to top if we have an -execdir
108   // _and_ a normal -exec, or are at top of tree in -execdir
109   if (TT.topdir != -1) {
110     if (aa->dir && new && new->parent) {
111       revert++;
112       rc = fchdir(new->parent->dirfd);
113     } else rc = fchdir(TT.topdir);
114     if (rc) {
115       perror_msg_raw(revert ? new->name : ".");
116 
117       return rc;
118     }
119   }
120 
121   // execdir: accumulated execs in this directory's children.
122   newargs = xmalloc(sizeof(char *)*(aa->arglen+bb->namecount+1));
123   if (aa->curly < 0) {
124     memcpy(newargs, aa->argstart, sizeof(char *)*aa->arglen);
125     newargs[aa->arglen] = 0;
126   } else {
127     int pos = aa->curly, rest = aa->arglen - aa->curly;
128     struct double_list *dl;
129 
130     // Collate argument list
131     memcpy(newargs, aa->argstart, sizeof(char *)*pos);
132     for (dl = bb->names; dl; dl = dl->next) newargs[pos++] = dl->data;
133     rest = aa->arglen - aa->curly - 1;
134     memcpy(newargs+pos, aa->argstart+aa->curly+1, sizeof(char *)*rest);
135     newargs[pos+rest] = 0;
136   }
137 
138   rc = xrun(newargs);
139 
140   llist_traverse(bb->names, llist_free_double);
141   bb->names = 0;
142   bb->namecount = 0;
143 
144   if (revert) revert = fchdir(TT.topdir);
145 
146   return rc;
147 }
148 
149 // Return numeric value with explicit sign
compare_numsign(long val,long units,char * str)150 static int compare_numsign(long val, long units, char *str)
151 {
152   char sign = 0;
153   long myval;
154 
155   if (*str == '+' || *str == '-') sign = *(str++);
156   else if (!isdigit(*str)) error_exit("%s not [+-]N", str);
157   myval = atolx(str);
158   if (units && isdigit(str[strlen(str)-1])) myval *= units;
159 
160   if (sign == '+') return val > myval;
161   if (sign == '-') return val < myval;
162   return val == myval;
163 }
164 
do_print(struct dirtree * new,char c)165 static void do_print(struct dirtree *new, char c)
166 {
167   char *s=dirtree_path(new, 0);
168 
169   xprintf("%s%c", s, c);
170   free(s);
171 }
172 
173 // Descend or ascend -execdir + directory level
execdir(struct dirtree * new,int flush)174 static void execdir(struct dirtree *new, int flush)
175 {
176   struct double_list *dl;
177   struct exec_range *aa;
178   struct execdir_data *bb;
179 
180   if (new && TT.topdir == -1) return;
181 
182   for (dl = TT.argdata; dl; dl = dl->next) {
183     if (dl->prev != (void *)1) continue;
184     aa = (void *)dl;
185     if (!aa->plus || (new && !aa->dir)) continue;
186 
187     if (flush) {
188 
189       // Flush pending "-execdir +" instances for this dir
190       // or flush everything for -exec at top
191       toys.exitval |= flush_exec(new, aa);
192 
193       // pop per-directory struct
194       if ((bb = aa->execdir)) {
195         aa->execdir = bb->next;
196         free(bb);
197       }
198     } else if (aa->dir) {
199 
200       // Push new per-directory struct for -execdir/okdir + codepath. (Can't
201       // use new->extra because command line may have multiple -execdir)
202       bb = xzalloc(sizeof(struct execdir_data));
203       bb->next = aa->execdir;
204       aa->execdir = bb;
205     }
206   }
207 }
208 
209 // Call this with 0 for first pass argument parsing and syntax checking (which
210 // populates argdata). Later commands traverse argdata (in order) when they
211 // need "do once" results.
do_find(struct dirtree * new)212 static int do_find(struct dirtree *new)
213 {
214   int pcount = 0, print = 0, not = 0, active = !!new, test = active, recurse;
215   struct double_list *argdata = TT.argdata;
216   char *s, **ss, *arg;
217 
218   recurse = DIRTREE_STATLESS|DIRTREE_COMEAGAIN|DIRTREE_SYMFOLLOW*FLAG(L);
219 
220   // skip . and .. below topdir, handle -xdev and -depth
221   if (new) {
222     // Handle stat failures first.
223     if (new->again&DIRTREE_STATLESS) {
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&DIRTREE_COMEAGAIN)) {
238         struct dirtree *n;
239 
240         for (n = new->parent; n; n = n->parent) {
241           if (same_file(&n->st, &new->st)) {
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; (s = *ss); ss++) {
270     int check = active && test;
271 
272     // if (!new) perform one-time setup, if (check) perform test
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") || !strcmp(s, "readable")) {
356       if (check && faccessat(dirtree_parentfd(new), new->name,
357           *s=='r' ? R_OK : X_OK, 0)) test = 0;
358     } else if (!strcmp(s, "quit")) {
359       if (check) {
360         execdir(0, 1);
361         xexit();
362       }
363 
364     // Remaining filters take an argument
365     } else {
366       arg = *++ss;
367       if (!strcmp(s, "name") || !strcmp(s, "iname")
368         || !strcmp(s, "wholename") || !strcmp(s, "iwholename")
369         || !strcmp(s, "path") || !strcmp(s, "ipath")
370         || !strcmp(s, "lname") || !strcmp(s, "ilname"))
371       {
372         int i = (*s == 'i'), is_path = (s[i] != 'n');
373         char *path = 0, *name = new ? new->name : arg;
374 
375         // Handle path expansion and case flattening
376         if (new && s[i] == 'l')
377           name = path = xreadlinkat(dirtree_parentfd(new), new->name);
378         else if (new && is_path) name = path = dirtree_path(new, 0);
379         if (i) {
380           if ((check || !new) && name) name = strlower(name);
381           if (!new) dlist_add(&TT.argdata, name);
382           else arg = ((struct double_list *)llist_pop(&argdata))->data;
383         }
384 
385         if (check) {
386           test = !fnmatch(arg, path ? name : basename(name),
387             FNM_PATHNAME*(!is_path));
388           if (i) free(name);
389         }
390         free(path);
391       } else if (!CFG_TOYBOX_LSM_NONE && !strcmp(s, "context")) {
392         if (check) {
393           char *path = dirtree_path(new, 0), *context;
394 
395           if (lsm_get_context(path, &context) != -1) {
396             test = !fnmatch(arg, context, 0);
397             free(context);
398           } else test = 0;
399           free(path);
400         }
401       } else if (!strcmp(s, "perm")) {
402         if (check) {
403           int match_min = *arg == '-', match_any = *arg == '/';
404           mode_t m1 = string_to_mode(arg+(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 
415           for (; *arg; arg++) {
416             if (*arg == ',') continue;
417             i = stridx("bcdlpfs", *arg);
418             if (i<0) error_exit("bad -type '%c'", *arg);
419             if ((new->st.st_mode & S_IFMT) == types[i]) break;
420           }
421           test = *arg;
422         }
423 
424       } else if (strchr("acm", *s)
425         && (!strcmp(s+1, "time") || !strcmp(s+1, "min")))
426       {
427         if (check) {
428           time_t thyme = (int []){new->st.st_atime, new->st.st_ctime,
429                                   new->st.st_mtime}[stridx("acm", *s)];
430           int len = strlen(arg), uu, units = (s[1]=='m') ? 60 : 86400;
431 
432           if (len && -1!=(uu = stridx("dhms",tolower(arg[len-1])))) {
433             arg = xstrdup(arg);
434             arg[--len] = 0;
435             units = (int []){86400, 3600, 60, 1}[uu];
436           }
437           test = compare_numsign(TT.now - thyme, units, arg);
438           if (*ss != arg) free(arg);
439         }
440       } else if (!strcmp(s, "size")) {
441         if (check) test = compare_numsign(new->st.st_size, -512, arg) &&
442                           S_ISREG(new->st.st_mode);
443       } else if (!strcmp(s, "links")) {
444         if (check) test = compare_numsign(new->st.st_nlink, 0, arg);
445       } else if (!strcmp(s, "inum")) {
446         if (check) test = compare_numsign(new->st.st_ino, 0, arg);
447       } else if (!strcmp(s, "mindepth") || !strcmp(s, "maxdepth")) {
448         if (check) {
449           struct dirtree *dt = new;
450           int i = 0, d = atolx(arg);
451 
452           while ((dt = dt->parent)) i++;
453           if (s[1] == 'i') {
454             test = i >= d;
455             if (i == d && not) recurse = 0;
456           } else {
457             test = i <= d;
458             if (i == d && !not) recurse = 0;
459           }
460         }
461       } else if (!strcmp(s, "user") || !strcmp(s, "group")
462               || !strncmp(s, "newer", 5) || !strcmp(s, "samefile"))
463       {
464         int macoff[] = {offsetof(struct stat, st_mtim),
465           offsetof(struct stat, st_atim), offsetof(struct stat, st_ctim)};
466         struct {
467           void *next, *prev;
468           union {
469             uid_t uid;
470             gid_t gid;
471             struct timespec tm;
472             struct dev_ino di;
473           };
474         } *udl;
475         struct stat st;
476 
477         if (!new) {
478           if (arg) {
479             udl = xmalloc(sizeof(*udl));
480             dlist_add_nomalloc(&TT.argdata, (void *)udl);
481 
482             if (strchr("sn", *s)) {
483               if (*s=='n' && s[5] && (s[7] || !strchr("Bmac", s[5]) || !strchr("tBmac", s[6])))
484                 goto error;
485               if (*s=='s' || !s[5] || s[6]!='t') {
486                 xstat(arg, &st);
487                 if (*s=='s') udl->di.dev = st.st_dev, udl->di.ino = st.st_ino;
488                 else udl->tm = *(struct timespec *)(((char *)&st)
489                                + macoff[!s[5] ? 0 : stridx("ac", s[6])+1]);
490               } else if (s[6] == 't') {
491                 unsigned nano;
492 
493                 xparsedate(arg, &(udl->tm.tv_sec), &nano, 1);
494                 udl->tm.tv_nsec = nano;
495               }
496             } else if (*s == 'u') udl->uid = xgetuid(arg);
497             else udl->gid = xgetgid(arg);
498           }
499         } else {
500           udl = (void *)llist_pop(&argdata);
501           if (check) {
502             if (*s == 'u') test = new->st.st_uid == udl->uid;
503             else if (*s == 'g') test = new->st.st_gid == udl->gid;
504             else if (*s == 's') test = same_dev_ino(&new->st, &udl->di);
505             else {
506               struct timespec *tm = (void *)(((char *)&new->st)
507                 + macoff[!s[5] ? 0 : stridx("ac", s[5])+1]);
508 
509               if (s[5] == 'B') test = 0;
510               else test = (tm->tv_sec == udl->tm.tv_sec)
511                 ? tm->tv_nsec > udl->tm.tv_nsec
512                 : tm->tv_sec > udl->tm.tv_sec;
513             }
514           }
515         }
516       } else if (!strcmp(s, "exec") || !strcmp("ok", s)
517               || !strcmp(s, "execdir") || !strcmp(s, "okdir"))
518       {
519         struct exec_range *aa;
520 
521         print++;
522 
523         // Initial argument parsing pass
524         if (!new) {
525           int len;
526 
527           // catch "-exec" with no args and "-exec \;"
528           if (!arg || !strcmp(arg, ";")) error_exit("'%s' needs 1 arg", s);
529 
530           dlist_add_nomalloc(&TT.argdata, (void *)(aa = xzalloc(sizeof(*aa))));
531           aa->argstart = ss;
532           aa->curly = -1;
533 
534           // Record command line arguments to -exec
535           for (len = 0; ss[len]; len++) {
536             if (!strcmp(ss[len], ";")) break;
537             else if (!strcmp(ss[len], "{}")) {
538               aa->curly = len;
539               if (ss[len+1] && !strcmp(ss[len+1], "+")) {
540                 aa->plus++;
541                 len++;
542                 break;
543               }
544             } else aa->argsize += sizeof(char *) + strlen(ss[len]) + 1;
545           }
546           if (!ss[len]) error_exit("-exec without %s",
547             aa->curly!=-1 ? "\\;" : "{}");
548           ss += len;
549           aa->arglen = len;
550           aa->dir = !!strchr(s, 'd');
551           if (TT.topdir == -1) TT.topdir = xopenro(".");
552 
553         // collect names and execute commands
554         } else {
555           char *name;
556           struct execdir_data *bb;
557 
558           // Grab command line exec argument list
559           aa = (void *)llist_pop(&argdata);
560           ss += aa->arglen;
561 
562           if (!check) goto cont;
563           // name is always a new malloc, so we can always free it.
564           name = aa->dir ? xstrdup(new->name) : dirtree_path(new, 0);
565 
566           if (*s == 'o') {
567             fprintf(stderr, "[%s] %s", arg, name);
568             if (!(test = yesno(0))) {
569               free(name);
570               goto cont;
571             }
572           }
573 
574           // Add next name to list (global list without -dir, local with)
575           bb = aa->execdir ? aa->execdir : &aa->exec;
576           dlist_add(&bb->names, name);
577           bb->namecount++;
578 
579           // -exec + collates and saves result in exitval
580           if (aa->plus) {
581             // Mark entry so COMEAGAIN can call flush_exec() in parent.
582             // This is never a valid pointer value for prev to have otherwise
583             // Done here vs argument parsing pass so it's after dlist_terminate
584             aa->prev = (void *)1;
585 
586             // Flush if the child's environment space gets too large.
587             // Linux caps individual arguments/variables at 131072 bytes,
588             // so this counter can't wrap.
589             if ((aa->plus += sizeof(char *)+strlen(name)+1) > TT.max_bytes) {
590               aa->plus = 1;
591               toys.exitval |= flush_exec(new, aa);
592             }
593           } else test = !flush_exec(new, aa);
594         }
595 
596         // Argument consumed, skip the check.
597         goto cont;
598       } else if (!strcmp(s, "printf")) {
599         char *fmt, *ff, next[32], buf[64], ch;
600         long ll;
601         int len;
602 
603         print++;
604         if (check) for (fmt = arg; *fmt; fmt++) {
605           // Print the parts that aren't escapes
606           if (*fmt == '\\') {
607             unsigned u;
608 
609             if (fmt[1] == 'c') break;
610             if ((u = unescape2(&fmt, 0))<128) putchar(u);
611             else printf("%.*s", (int)wcrtomb(buf, u, 0), buf);
612             fmt--;
613           } else if (*fmt != '%') putchar(*fmt);
614           else if (*++fmt == '%') putchar('%');
615           else {
616             fmt = next_printf(ff = fmt-1, 0);
617             if ((len = fmt-ff)>28) error_exit("bad %.*s", len+1, ff);
618             memcpy(next, ff, len);
619             ff = 0;
620             ch = *fmt;
621 
622             // long long is its own stack size on LP64, so handle separately
623             if (ch == 'i' || ch == 's') {
624               strcpy(next+len, "lld");
625               printf(next, (ch == 'i') ? (long long)new->st.st_ino
626                 : (long long)new->st.st_size);
627             } else {
628 
629               // LP64 says these are all a single "long" argument to printf
630               strcpy(next+len, "s");
631               if (ch == 'G') next[len] = 'd', ll = new->st.st_gid;
632               else if (ch == 'm') next[len] = 'o', ll = new->st.st_mode&~S_IFMT;
633               else if (ch == 'U') next[len] = 'd', ll = new->st.st_uid;
634               else if (ch == 'f') ll = (long)new->name;
635               else if (ch == 'g') ll = (long)getgroupname(new->st.st_gid);
636               else if (ch == 'u') ll = (long)getusername(new->st.st_uid);
637               else if (ch == 'l') {
638                 ll = (long)(ff = xreadlinkat(dirtree_parentfd(new), new->name));
639                 if (!ll) ll = (long)"";
640               } else if (ch == 'M') {
641                 mode_to_string(new->st.st_mode, buf);
642                 ll = (long)buf;
643               } else if (ch == 'P') {
644                 ch = *TT.start;
645                 *TT.start = 0;
646                 ll = (long)(ff = dirtree_path(new, 0));
647                 *TT.start = ch;
648               } else if (ch == 'p') ll = (long)(ff = dirtree_path(new, 0));
649               else if (ch == 'T') {
650                 if (*++fmt!='@') error_exit("bad -printf %%T: %%T%c", *fmt);
651                 sprintf(buf, "%lld.%ld", (long long)new->st.st_mtim.tv_sec,
652                              new->st.st_mtim.tv_nsec);
653                 ll = (long)buf;
654               } else if (ch == 'Z') {
655                 char *path = dirtree_path(new, 0);
656 
657                 ll = (lsm_get_context(path, &ff) != -1) ? (long)ff : (long)"?";
658                 free(path);
659               } else error_exit("bad -printf %%%c", ch);
660 
661               printf(next, ll);
662               free(ff);
663             }
664           }
665         }
666       } else goto error;
667 
668       // This test can go at the end because we do a syntax checking
669       // pass first. Putting it here gets the error message (-unknown
670       // vs -known noarg) right.
671       if (!check && !arg) error_exit("'%s' needs 1 arg", s-1);
672     }
673 cont:
674     // Apply pending "!" to result
675     if (active && not) test = !test;
676     not = 0;
677   }
678 
679   if (new) {
680     // If there was no action, print
681     if (!print && test) do_print(new, '\n');
682 
683     if (S_ISDIR(new->st.st_mode)) execdir(new, 0);
684 
685   } else dlist_terminate(TT.argdata);
686 
687   return recurse;
688 
689 error:
690   if (!*ss) --ss;
691   error_exit("bad arg '%s'", *ss);
692 }
693 
find_main(void)694 void find_main(void)
695 {
696   int i, len;
697   char **ss = (char *[]){"."};
698 
699   TT.topdir = -1;
700   TT.max_bytes = sysconf(_SC_ARG_MAX) - environ_bytes();
701 
702   // Distinguish paths from filters
703   for (len = 0; toys.optargs[len]; len++)
704     if (*toys.optargs[len] && strchr("-!(", *toys.optargs[len])) break;
705   TT.filter = toys.optargs+len;
706 
707   // use "." if no paths
708   if (len) ss = toys.optargs;
709   else len = 1;
710 
711   // first pass argument parsing, verify args match up, handle "evaluate once"
712   TT.now = time(0);
713   do_find(0);
714 
715   // Loop through paths
716   for (i = 0; i < len; i++)
717     dirtree_flagread(ss[i],
718       DIRTREE_STATLESS|(DIRTREE_SYMFOLLOW*!!(toys.optflags&(FLAG_H|FLAG_L))),
719       do_find);
720 
721   execdir(0, 1);
722 
723   if (CFG_TOYBOX_FREE) {
724     close(TT.topdir);
725     llist_traverse(TT.argdata, free);
726   }
727 }
728