1 /* find.c - Search directories for matching files.
3 * Copyright 2014 Rob Landley <rob@landley.net>
5 * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/find.c
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
11 * TODO: -empty (dirs too!)
13 USE_FIND(NEWTOY(find, "?^HL[-HL]", TOYFLAG_USR|TOYFLAG_BIN))
19 usage: find [-HL] [DIR...] [<options>]
21 Search directories for matching files.
22 Default: search "." match all -print all matches.
24 -H Follow command line symlinks -L Follow all symlinks
27 -name PATTERN filename with wildcards -iname case insensitive -name
28 -path PATTERN path name with wildcards -ipath case insensitive -path
29 -user UNAME belongs to user UNAME -nouser user ID not known
30 -group GROUP belongs to group GROUP -nogroup group ID not known
31 -perm [-/]MODE permissions (-=min /=any) -prune ignore contents of dir
32 -size N[c] 512 byte blocks (c=bytes) -xdev only this filesystem
33 -links N hardlink count -atime N accessed N days ago
34 -ctime N created N days ago -mtime N modified N days ago
35 -newer FILE newer mtime than FILE -mindepth # at least # dirs down
36 -depth ignore contents of dir -maxdepth # at most # dirs down
37 -inum N inode number N -empty empty files and dirs
38 -type [bcdflps] (block, char, dir, file, symlink, pipe, socket)
40 Numbers N may be prefixed by a - (less than) or + (greater than):
43 !, -a, -o, ( ) not, and, or, group expressions
46 -print Print match with newline -print0 Print match with null
47 -exec Run command with path -execdir Run command in file's dir
48 -ok Ask before exec -okdir Ask before execdir
49 -delete Remove matching file/dir
51 Commands substitute "{}" with matched file. End with ";" to run each file,
52 or "+" (next argument after "{}") to collect and run with multiple files.
60 struct double_list *argdata;
61 int topdir, xdev, depth;
66 struct execdir_data *next;
69 struct double_list *names;
72 // None of this can go in TT because you can have more than one -exec
74 char *next, *prev; // layout compatible with struct double_list
76 int dir, plus, arglen, argsize, curly;
78 struct execdir_data exec, *execdir;
81 // Perform pending -exec (if any)
82 static int flush_exec(struct dirtree *new, struct exec_range *aa)
84 struct execdir_data *bb = aa->execdir ? aa->execdir : &aa->exec;
88 if (!bb->namecount) return 0;
90 dlist_terminate(bb->names);
92 // switch to directory for -execdir, or back to top if we have an -execdir
93 // _and_ a normal -exec, or are at top of tree in -execdir
94 if (TT.topdir != -1) {
95 if (aa->dir && new && new->parent) {
97 rc = fchdir(new->parent->dirfd);
98 } else rc = fchdir(TT.topdir);
100 perror_msg_raw(revert ? new->name : ".");
106 // execdir: accumulated execs in this directory's children.
107 newargs = xmalloc(sizeof(char *)*(aa->arglen+bb->namecount+1));
109 memcpy(newargs, aa->argstart, sizeof(char *)*aa->arglen);
110 newargs[aa->arglen] = 0;
112 int pos = aa->curly, rest = aa->arglen - aa->curly;
113 struct double_list *dl;
115 // Collate argument list
116 memcpy(newargs, aa->argstart, sizeof(char *)*pos);
117 for (dl = bb->names; dl; dl = dl->next) newargs[pos++] = dl->data;
118 rest = aa->arglen - aa->curly - 1;
119 memcpy(newargs+pos, aa->argstart+aa->curly+1, sizeof(char *)*rest);
120 newargs[pos+rest] = 0;
125 llist_traverse(bb->names, llist_free_double);
129 if (revert) revert = fchdir(TT.topdir);
134 // Return numeric value with explicit sign
135 static int compare_numsign(long val, long units, char *str)
140 if (*str == '+' || *str == '-') sign = *(str++);
141 else if (!isdigit(*str)) error_exit("%s not [+-]N", str);
143 if (units && isdigit(str[strlen(str)-1])) myval *= units;
145 if (sign == '+') return val > myval;
146 if (sign == '-') return val < myval;
150 static void do_print(struct dirtree *new, char c)
152 char *s=dirtree_path(new, 0);
154 xprintf("%s%c", s, c);
158 // Descend or ascend -execdir + directory level
159 static void execdir(struct dirtree *new, int flush)
161 struct double_list *dl;
162 struct exec_range *aa;
163 struct execdir_data *bb;
165 if (new && TT.topdir == -1) return;
167 for (dl = TT.argdata; dl; dl = dl->next) {
168 if (dl->prev != (void *)1) continue;
170 if (!aa->plus || (new && !aa->dir)) continue;
174 // Flush pending "-execdir +" instances for this dir
175 // or flush everything for -exec at top
176 toys.exitval |= flush_exec(new, aa);
178 // pop per-directory struct
179 if ((bb = aa->execdir)) {
180 aa->execdir = bb->next;
183 } else if (aa->dir) {
185 // Push new per-directory struct for -execdir/okdir + codepath. (Can't
186 // use new->extra because command line may have multiple -execdir)
187 bb = xzalloc(sizeof(struct execdir_data));
188 bb->next = aa->execdir;
194 // Call this with 0 for first pass argument parsing and syntax checking (which
195 // populates argdata). Later commands traverse argdata (in order) when they
196 // need "do once" results.
197 static int do_find(struct dirtree *new)
199 int pcount = 0, print = 0, not = 0, active = !!new, test = active, recurse;
200 struct double_list *argdata = TT.argdata;
203 recurse = DIRTREE_COMEAGAIN|(DIRTREE_SYMFOLLOW*!!(toys.optflags&FLAG_L));
205 // skip . and .. below topdir, handle -xdev and -depth
208 if (!dirtree_notdotdot(new)) return 0;
209 if (TT.xdev && new->st.st_dev != new->parent->st.st_dev) recurse = 0;
212 if (S_ISDIR(new->st.st_mode)) {
213 // Descending into new directory
217 for (n = new->parent; n; n = n->parent) {
218 if (n->st.st_ino==new->st.st_ino && n->st.st_dev==new->st.st_dev) {
219 error_msg("'%s': loop detected", s = dirtree_path(new, 0));
231 // Done with directory (COMEAGAIN call)
235 if (!TT.depth) return 0;
240 // pcount: parentheses stack depth (using toybuf bytes, 4096 max depth)
241 // test: result of most recent test
242 // active: if 0 don't perform tests
243 // not: a pending ! applies to this test (only set if performing tests)
244 // print: saw one of print/ok/exec, no need for default -print
246 if (TT.filter) for (ss = TT.filter; *ss; ss++) {
247 int check = active && test;
251 // handle ! ( ) using toybuf as a stack
253 if (s[1]) goto error;
256 // Don't invert if we're not making a decision
257 if (check) not = !not;
259 // Save old "not" and "active" on toybuf stack.
260 // Deactivate this parenthetical if !test
261 // Note: test value should never change while !active
262 } else if (*s == '(') {
263 if (pcount == sizeof(toybuf)) goto error;
264 toybuf[pcount++] = not+(active<<1);
265 if (!check) active = 0;
268 // Pop status, apply deferred not to test
269 } else if (*s == ')') {
270 if (--pcount < 0) goto error;
271 // Pop active state, apply deferred not (which was only set if checking)
272 active = (toybuf[pcount]>>1)&1;
273 if (active && (toybuf[pcount]&1)) test = !test;
280 if (!strcmp(s, "xdev")) TT.xdev = 1;
281 else if (!strcmp(s, "delete")) {
282 // Delete forces depth first
285 test = !unlinkat(dirtree_parentfd(new), new->name,
286 S_ISDIR(new->st.st_mode) ? AT_REMOVEDIR : 0);
287 } else if (!strcmp(s, "depth")) TT.depth = 1;
288 else if (!strcmp(s, "o") || !strcmp(s, "or")) {
292 else active = 0; // decision has been made until next ")"
294 } else if (!strcmp(s, "not")) {
295 if (check) not = !not;
297 // Mostly ignore NOP argument
298 } else if (!strcmp(s, "a") || !strcmp(s, "and") || !strcmp(s, "noleaf")) {
301 } else if (!strcmp(s, "print") || !strcmp("print0", s)) {
303 if (check) do_print(new, s[5] ? 0 : '\n');
305 } else if (!strcmp(s, "nouser")) {
306 if (check) if (bufgetpwuid(new->st.st_uid)) test = 0;
307 } else if (!strcmp(s, "nogroup")) {
308 if (check) if (bufgetgrgid(new->st.st_gid)) test = 0;
309 } else if (!strcmp(s, "prune")) {
310 if (check && S_ISDIR(new->st.st_mode) && !TT.depth) recurse = 0;
312 // Remaining filters take an argument
314 if (!strcmp(s, "name") || !strcmp(s, "iname")
315 || !strcmp(s, "path") || !strcmp(s, "ipath"))
318 char *arg = ss[1], *path = 0, *name = new ? new->name : arg;
320 // Handle path expansion and case flattening
321 if (new && s[i] == 'p') name = path = dirtree_path(new, 0);
323 if ((check || !new) && name) name = strlower(name);
324 if (!new) dlist_add(&TT.argdata, name);
325 else arg = ((struct double_list *)llist_pop(&argdata))->data;
329 test = !fnmatch(arg, name, FNM_PATHNAME*(s[i] == 'p'));
333 } else if (!strcmp(s, "perm")) {
336 int match_min = *m == '-',
337 match_any = *m == '/';
338 mode_t m1 = string_to_mode(m+(match_min || match_any), 0),
339 m2 = new->st.st_mode & 07777;
341 if (match_min || match_any) m2 &= m1;
342 test = match_any ? !m1 || m2 : m1 == m2;
344 } else if (!strcmp(s, "type")) {
346 int types[] = {S_IFBLK, S_IFCHR, S_IFDIR, S_IFLNK, S_IFIFO,
347 S_IFREG, S_IFSOCK}, i = stridx("bcdlpfs", *ss[1]);
349 if (i<0) error_exit("bad -type '%c'", *ss[1]);
350 if ((new->st.st_mode & S_IFMT) != types[i]) test = 0;
353 } else if (!strcmp(s, "atime")) {
355 test = compare_numsign(TT.now - new->st.st_atime, 86400, ss[1]);
356 } else if (!strcmp(s, "ctime")) {
358 test = compare_numsign(TT.now - new->st.st_ctime, 86400, ss[1]);
359 } else if (!strcmp(s, "mtime")) {
361 test = compare_numsign(TT.now - new->st.st_mtime, 86400, ss[1]);
362 } else if (!strcmp(s, "size")) {
364 test = compare_numsign(new->st.st_size, 512, ss[1]);
365 } else if (!strcmp(s, "links")) {
366 if (check) test = compare_numsign(new->st.st_nlink, 0, ss[1]);
367 } else if (!strcmp(s, "inum")) {
369 test = compare_numsign(new->st.st_ino, 0, ss[1]);
370 } else if (!strcmp(s, "mindepth") || !strcmp(s, "maxdepth")) {
372 struct dirtree *dt = new;
373 int i = 0, d = atolx(ss[1]);
375 while ((dt = dt->parent)) i++;
378 if (i == d && not) recurse = 0;
381 if (i == d && !not) recurse = 0;
384 } else if (!strcmp(s, "user") || !strcmp(s, "group")
385 || !strcmp(s, "newer"))
398 udl = xmalloc(sizeof(*udl));
399 dlist_add_nomalloc(&TT.argdata, (void *)udl);
401 if (*s == 'u') udl->u.uid = xgetpwnamid(ss[1])->pw_uid;
402 else if (*s == 'g') udl->u.gid = xgetgrnamid(ss[1])->gr_gid;
407 udl->u.tm = st.st_mtim;
411 udl = (void *)llist_pop(&argdata);
413 if (*s == 'u') test = new->st.st_uid == udl->u.uid;
414 else if (*s == 'g') test = new->st.st_gid == udl->u.gid;
416 test = new->st.st_mtim.tv_sec > udl->u.tm.tv_sec;
417 if (new->st.st_mtim.tv_sec == udl->u.tm.tv_sec)
418 test = new->st.st_mtim.tv_nsec > udl->u.tm.tv_nsec;
422 } else if (!strcmp(s, "exec") || !strcmp("ok", s)
423 || !strcmp(s, "execdir") || !strcmp(s, "okdir"))
425 struct exec_range *aa;
429 // Initial argument parsing pass
433 // catch "-exec" with no args and "-exec \;"
434 if (!ss[1] || !strcmp(ss[1], ";")) error_exit("'%s' needs 1 arg", s);
436 dlist_add_nomalloc(&TT.argdata, (void *)(aa = xzalloc(sizeof(*aa))));
440 // Record command line arguments to -exec
441 for (len = 0; ss[len]; len++) {
442 if (!strcmp(ss[len], ";")) break;
443 else if (!strcmp(ss[len], "{}")) {
445 if (ss[len+1] && !strcmp(ss[len+1], "+")) {
450 } else aa->argsize += sizeof(char *) + strlen(ss[len]) + 1;
452 if (!ss[len]) error_exit("-exec without %s",
453 aa->curly!=-1 ? "\\;" : "{}");
456 aa->dir = !!strchr(s, 'd');
457 if (TT.topdir == -1) TT.topdir = xopen(".", 0);
459 // collect names and execute commands
461 char *name, *ss1 = ss[1];
462 struct execdir_data *bb;
464 // Grab command line exec argument list
465 aa = (void *)llist_pop(&argdata);
466 ss += aa->arglen + 1;
468 if (!check) goto cont;
469 // name is always a new malloc, so we can always free it.
470 name = aa->dir ? xstrdup(new->name) : dirtree_path(new, 0);
473 fprintf(stderr, "[%s] %s", ss1, name);
474 if (!(test = yesno(0))) {
480 // Add next name to list (global list without -dir, local with)
481 bb = aa->execdir ? aa->execdir : &aa->exec;
482 dlist_add(&bb->names, name);
485 // -exec + collates and saves result in exitval
487 // Mark entry so COMEAGAIN can call flush_exec() in parent.
488 // This is never a valid pointer value for prev to have otherwise
489 // Done here vs argument parsing pass so it's after dlist_terminate
490 aa->prev = (void *)1;
492 // Flush if we pass 16 megs of environment space.
493 // An insanely long path (>2 gigs) could wrap the counter and
494 // defeat this test, which could potentially trigger OOM killer.
495 if ((aa->plus += sizeof(char *)+strlen(name)+1) > 1<<24) {
497 toys.exitval |= flush_exec(new, aa);
499 } else test = flush_exec(new, aa);
502 // Argument consumed, skip the check.
506 // This test can go at the end because we do a syntax checking
507 // pass first. Putting it here gets the error message (-unknown
508 // vs -known noarg) right.
509 if (!*++ss) error_exit("'%s' needs 1 arg", --s);
512 // Apply pending "!" to result
513 if (active && not) test = !test;
518 // If there was no action, print
519 if (!print && test) do_print(new, '\n');
521 if (S_ISDIR(new->st.st_mode)) execdir(new, 0);
523 } else dlist_terminate(TT.argdata);
528 error_exit("bad arg '%s'", *ss);
534 char **ss = toys.optargs;
538 // Distinguish paths from filters
539 for (len = 0; toys.optargs[len]; len++)
540 if (strchr("-!(", *toys.optargs[len])) break;
541 TT.filter = toys.optargs+len;
543 // use "." if no paths
545 ss = (char *[]){"."};
549 // first pass argument parsing, verify args match up, handle "evaluate once"
553 // Loop through paths
554 for (i = 0; i < len; i++)
555 dirtree_flagread(ss[i], DIRTREE_SYMFOLLOW*!!(toys.optflags&(FLAG_H|FLAG_L)),
560 if (CFG_TOYBOX_FREE) {
562 llist_traverse(TT.argdata, free);