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