AHCI - Fix a polled command issue.
[dragonfly.git] / usr.bin / find / function.c
blobf5bbaa5d12d74060e27944a105ea9b6cd799da74
1 /*-
2 * Copyright (c) 1990, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Cimarron D. Taylor of the University of California, Berkeley.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
36 * @(#)function.c 8.10 (Berkeley) 5/4/95
37 * $FreeBSD: src/usr.bin/find/function.c,v 1.52 2004/07/29 03:33:55 tjr Exp $
38 * $DragonFly: src/usr.bin/find/function.c,v 1.7 2005/03/13 22:22:42 y0netan1 Exp $
41 #include <sys/param.h>
42 #include <sys/ucred.h>
43 #include <sys/stat.h>
44 #include <sys/types.h>
45 #include <sys/wait.h>
46 #include <sys/mount.h>
47 #include <sys/timeb.h>
49 #include <dirent.h>
50 #include <err.h>
51 #include <errno.h>
52 #include <fnmatch.h>
53 #include <fts.h>
54 #include <grp.h>
55 #include <limits.h>
56 #include <pwd.h>
57 #include <regex.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 #include <ctype.h>
64 #include "find.h"
66 static PLAN *palloc(OPTION *);
67 static long long find_parsenum(PLAN *, const char *, char *, char *);
68 static long long find_parsetime(PLAN *, const char *, char *);
69 static char *nextarg(OPTION *, char ***);
71 extern char **environ;
73 #define COMPARE(a, b) do { \
74 switch (plan->flags & F_ELG_MASK) { \
75 case F_EQUAL: \
76 return (a == b); \
77 case F_LESSTHAN: \
78 return (a < b); \
79 case F_GREATER: \
80 return (a > b); \
81 default: \
82 abort(); \
83 } \
84 } while(0)
86 static PLAN *
87 palloc(OPTION *option)
89 PLAN *new;
91 if ((new = malloc(sizeof(PLAN))) == NULL)
92 err(1, NULL);
93 new->execute = option->execute;
94 new->flags = option->flags;
95 new->next = NULL;
96 return new;
100 * find_parsenum --
101 * Parse a string of the form [+-]# and return the value.
103 static long long
104 find_parsenum(PLAN *plan, const char *option, char *vp, char *endch)
106 long long value;
107 char *endchar, *str; /* Pointer to character ending conversion. */
109 /* Determine comparison from leading + or -. */
110 str = vp;
111 switch (*str) {
112 case '+':
113 ++str;
114 plan->flags |= F_GREATER;
115 break;
116 case '-':
117 ++str;
118 plan->flags |= F_LESSTHAN;
119 break;
120 default:
121 plan->flags |= F_EQUAL;
122 break;
126 * Convert the string with strtoq(). Note, if strtoq() returns zero
127 * and endchar points to the beginning of the string we know we have
128 * a syntax error.
130 value = strtoq(str, &endchar, 10);
131 if (value == 0 && endchar == str)
132 errx(1, "%s: %s: illegal numeric value", option, vp);
133 if (endchar[0] && (endch == NULL || endchar[0] != *endch))
134 errx(1, "%s: %s: illegal trailing character", option, vp);
135 if (endch)
136 *endch = endchar[0];
137 return value;
141 * find_parsetime --
142 * Parse a string of the form [+-]([0-9]+[smhdw]?)+ and return the value.
144 static long long
145 find_parsetime(PLAN *plan, const char *option, char *vp)
147 long long secs, value;
148 char *str, *unit; /* Pointer to character ending conversion. */
150 /* Determine comparison from leading + or -. */
151 str = vp;
152 switch (*str) {
153 case '+':
154 ++str;
155 plan->flags |= F_GREATER;
156 break;
157 case '-':
158 ++str;
159 plan->flags |= F_LESSTHAN;
160 break;
161 default:
162 plan->flags |= F_EQUAL;
163 break;
166 value = strtoq(str, &unit, 10);
167 if (value == 0 && unit == str) {
168 errx(1, "%s: %s: illegal time value", option, vp);
169 /* NOTREACHED */
171 if (*unit == '\0')
172 return value;
174 /* Units syntax. */
175 secs = 0;
176 for (;;) {
177 switch(*unit) {
178 case 's': /* seconds */
179 secs += value;
180 break;
181 case 'm': /* minutes */
182 secs += value * 60;
183 break;
184 case 'h': /* hours */
185 secs += value * 3600;
186 break;
187 case 'd': /* days */
188 secs += value * 86400;
189 break;
190 case 'w': /* weeks */
191 secs += value * 604800;
192 break;
193 default:
194 errx(1, "%s: %s: bad unit '%c'", option, vp, *unit);
195 /* NOTREACHED */
197 str = unit + 1;
198 if (*str == '\0') /* EOS */
199 break;
200 value = strtoq(str, &unit, 10);
201 if (value == 0 && unit == str) {
202 errx(1, "%s: %s: illegal time value", option, vp);
203 /* NOTREACHED */
205 if (*unit == '\0') {
206 errx(1, "%s: %s: missing trailing unit", option, vp);
207 /* NOTREACHED */
210 plan->flags |= F_EXACTTIME;
211 return secs;
215 * nextarg --
216 * Check that another argument still exists, return a pointer to it,
217 * and increment the argument vector pointer.
219 static char *
220 nextarg(OPTION *option, char ***argvp)
222 char *arg;
224 if ((arg = **argvp) == 0)
225 errx(1, "%s: requires additional arguments", option->name);
226 (*argvp)++;
227 return arg;
228 } /* nextarg() */
231 * The value of n for the inode times (atime, ctime, and mtime) is a range,
232 * i.e. n matches from (n - 1) to n 24 hour periods. This interacts with
233 * -n, such that "-mtime -1" would be less than 0 days, which isn't what the
234 * user wanted. Correct so that -1 is "less than 1".
236 #define TIME_CORRECT(p) \
237 if (((p)->flags & F_ELG_MASK) == F_LESSTHAN) \
238 ++((p)->t_data);
241 * -[acm]min n functions --
243 * True if the difference between the
244 * file access time (-amin)
245 * last change of file status information (-cmin)
246 * file modification time (-mmin)
247 * and the current time is n min periods.
250 f_Xmin(PLAN *plan, FTSENT *entry)
252 if (plan->flags & F_TIME_C) {
253 COMPARE((now - entry->fts_statp->st_ctime +
254 60 - 1) / 60, plan->t_data);
255 } else if (plan->flags & F_TIME_A) {
256 COMPARE((now - entry->fts_statp->st_atime +
257 60 - 1) / 60, plan->t_data);
258 } else {
259 COMPARE((now - entry->fts_statp->st_mtime +
260 60 - 1) / 60, plan->t_data);
264 PLAN *
265 c_Xmin(OPTION *option, char ***argvp)
267 char *nmins;
268 PLAN *new;
270 nmins = nextarg(option, argvp);
271 ftsoptions &= ~FTS_NOSTAT;
273 new = palloc(option);
274 new->t_data = find_parsenum(new, option->name, nmins, NULL);
275 TIME_CORRECT(new);
276 return new;
280 * -[acm]time n functions --
282 * True if the difference between the
283 * file access time (-atime)
284 * last change of file status information (-ctime)
285 * file modification time (-mtime)
286 * and the current time is n 24 hour periods.
290 f_Xtime(PLAN *plan, FTSENT *entry)
292 time_t xtime;
294 if (plan->flags & F_TIME_A)
295 xtime = entry->fts_statp->st_atime;
296 else if (plan->flags & F_TIME_C)
297 xtime = entry->fts_statp->st_ctime;
298 else
299 xtime = entry->fts_statp->st_mtime;
301 if (plan->flags & F_EXACTTIME)
302 COMPARE(now - xtime, plan->t_data);
303 else
304 COMPARE((now - xtime + 86400 - 1) / 86400, plan->t_data);
307 PLAN *
308 c_Xtime(OPTION *option, char ***argvp)
310 char *value;
311 PLAN *new;
313 value = nextarg(option, argvp);
314 ftsoptions &= ~FTS_NOSTAT;
316 new = palloc(option);
317 new->t_data = find_parsetime(new, option->name, value);
318 if (!(new->flags & F_EXACTTIME))
319 TIME_CORRECT(new);
320 return new;
324 * -maxdepth/-mindepth n functions --
326 * Does the same as -prune if the level of the current file is
327 * greater/less than the specified maximum/minimum depth.
329 * Note that -maxdepth and -mindepth are handled specially in
330 * find_execute() so their f_* functions are set to f_always_true().
332 PLAN *
333 c_mXXdepth(OPTION *option, char ***argvp)
335 char *dstr;
336 PLAN *new;
338 dstr = nextarg(option, argvp);
339 if (dstr[0] == '-')
340 /* all other errors handled by find_parsenum() */
341 errx(1, "%s: %s: value must be positive", option->name, dstr);
343 new = palloc(option);
344 if (option->flags & F_MAXDEPTH)
345 maxdepth = find_parsenum(new, option->name, dstr, NULL);
346 else
347 mindepth = find_parsenum(new, option->name, dstr, NULL);
348 return new;
352 * -delete functions --
354 * True always. Makes its best shot and continues on regardless.
357 f_delete(PLAN *plan __unused, FTSENT *entry)
359 /* ignore these from fts */
360 if (strcmp(entry->fts_accpath, ".") == 0 ||
361 strcmp(entry->fts_accpath, "..") == 0)
362 return 1;
364 /* sanity check */
365 if (isdepth == 0 || /* depth off */
366 (ftsoptions & FTS_NOSTAT) || /* not stat()ing */
367 !(ftsoptions & FTS_PHYSICAL) || /* physical off */
368 (ftsoptions & FTS_LOGICAL)) /* or finally, logical on */
369 errx(1, "-delete: insecure options got turned on");
371 /* Potentially unsafe - do not accept relative paths whatsoever */
372 if (strchr(entry->fts_accpath, '/') != NULL)
373 errx(1, "-delete: %s: relative path potentially not safe",
374 entry->fts_accpath);
376 /* Turn off user immutable bits if running as root */
377 if ((entry->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
378 !(entry->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
379 geteuid() == 0)
380 chflags(entry->fts_accpath,
381 entry->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
383 /* rmdir directories, unlink everything else */
384 if (S_ISDIR(entry->fts_statp->st_mode)) {
385 if (rmdir(entry->fts_accpath) < 0 && errno != ENOTEMPTY)
386 warn("-delete: rmdir(%s)", entry->fts_path);
387 } else {
388 if (unlink(entry->fts_accpath) < 0)
389 warn("-delete: unlink(%s)", entry->fts_path);
392 /* "succeed" */
393 return 1;
396 PLAN *
397 c_delete(OPTION *option, char ***argvp __unused)
400 ftsoptions &= ~FTS_NOSTAT; /* no optimise */
401 ftsoptions |= FTS_PHYSICAL; /* disable -follow */
402 ftsoptions &= ~FTS_LOGICAL; /* disable -follow */
403 isoutput = 1; /* possible output */
404 isdepth = 1; /* -depth implied */
406 return palloc(option);
411 * always_true --
413 * Always true, used for -maxdepth, -mindepth, -xdev and -follow
416 f_always_true(PLAN *plan __unused, FTSENT *entry __unused)
418 return 1;
422 * -depth functions --
424 * With argument: True if the file is at level n.
425 * Without argument: Always true, causes descent of the directory hierarchy
426 * to be done so that all entries in a directory are acted on before the
427 * directory itself.
430 f_depth(PLAN *plan, FTSENT *entry)
432 if (plan->flags & F_DEPTH)
433 COMPARE(entry->fts_level, plan->d_data);
434 else
435 return 1;
438 PLAN *
439 c_depth(OPTION *option, char ***argvp)
441 PLAN *new;
442 char *str;
444 new = palloc(option);
446 str = **argvp;
447 if (str && !(new->flags & F_DEPTH)) {
448 /* skip leading + or - */
449 if (*str == '+' || *str == '-')
450 str++;
451 /* skip sign */
452 if (*str == '+' || *str == '-')
453 str++;
454 if (isdigit(*str))
455 new->flags |= F_DEPTH;
458 if (new->flags & F_DEPTH) { /* -depth n */
459 char *ndepth;
461 ndepth = nextarg(option, argvp);
462 new->d_data = find_parsenum(new, option->name, ndepth, NULL);
463 } else { /* -d */
464 isdepth = 1;
467 return new;
471 * -empty functions --
473 * True if the file or directory is empty
476 f_empty(PLAN *plan __unused, FTSENT *entry)
478 if (S_ISREG(entry->fts_statp->st_mode) &&
479 entry->fts_statp->st_size == 0)
480 return 1;
481 if (S_ISDIR(entry->fts_statp->st_mode)) {
482 struct dirent *dp;
483 int empty;
484 DIR *dir;
486 empty = 1;
487 dir = opendir(entry->fts_accpath);
488 if (dir == NULL)
489 err(1, "%s", entry->fts_accpath);
490 for (dp = readdir(dir); dp; dp = readdir(dir))
491 if (dp->d_name[0] != '.' ||
492 (dp->d_name[1] != '\0' &&
493 (dp->d_name[1] != '.' || dp->d_name[2] != '\0'))) {
494 empty = 0;
495 break;
497 closedir(dir);
498 return empty;
500 return 0;
503 PLAN *
504 c_empty(OPTION *option, char ***argvp __unused)
506 ftsoptions &= ~FTS_NOSTAT;
508 return palloc(option);
512 * [-exec | -execdir | -ok] utility [arg ... ] ; functions --
514 * True if the executed utility returns a zero value as exit status.
515 * The end of the primary expression is delimited by a semicolon. If
516 * "{}" occurs anywhere, it gets replaced by the current pathname,
517 * or, in the case of -execdir, the current basename (filename
518 * without leading directory prefix). For -exec and -ok,
519 * the current directory for the execution of utility is the same as
520 * the current directory when the find utility was started, whereas
521 * for -execdir, it is the directory the file resides in.
523 * The primary -ok differs from -exec in that it requests affirmation
524 * of the user before executing the utility.
527 f_exec(PLAN *plan, FTSENT *entry)
529 int cnt;
530 pid_t pid;
531 int status;
532 char *file;
534 if (entry == NULL && plan->flags & F_EXECPLUS) {
535 if (plan->e_ppos == plan->e_pbnum)
536 return (1);
537 plan->e_argv[plan->e_ppos] = NULL;
538 goto doexec;
541 /* XXX - if file/dir ends in '/' this will not work -- can it? */
542 if ((plan->flags & F_EXECDIR) && \
543 (file = strrchr(entry->fts_path, '/')))
544 file++;
545 else
546 file = entry->fts_path;
548 if (plan->flags & F_EXECPLUS) {
549 if ((plan->e_argv[plan->e_ppos] = strdup(file)) == NULL)
550 err(1, NULL);
551 plan->e_len[plan->e_ppos] = strlen(file);
552 plan->e_psize += plan->e_len[plan->e_ppos];
553 if (++plan->e_ppos < plan->e_pnummax &&
554 plan->e_psize < plan->e_psizemax)
555 return (1);
556 plan->e_argv[plan->e_ppos] = NULL;
557 } else {
558 for (cnt = 0; plan->e_argv[cnt]; ++cnt)
559 if (plan->e_len[cnt])
560 brace_subst(plan->e_orig[cnt],
561 &plan->e_argv[cnt], file,
562 plan->e_len[cnt]);
565 doexec: if ((plan->flags & F_NEEDOK) && !queryuser(plan->e_argv))
566 return 0;
568 /* make sure find output is interspersed correctly with subprocesses */
569 fflush(stdout);
570 fflush(stderr);
572 switch (pid = fork()) {
573 case -1:
574 err(1, "fork");
575 /* NOTREACHED */
576 case 0:
577 /* change dir back from where we started */
578 if (!(plan->flags & F_EXECDIR) && fchdir(dotfd)) {
579 warn("chdir");
580 _exit(1);
582 execvp(plan->e_argv[0], plan->e_argv);
583 warn("%s", plan->e_argv[0]);
584 _exit(1);
586 if (plan->flags & F_EXECPLUS) {
587 while (--plan->e_ppos >= plan->e_pbnum)
588 free(plan->e_argv[plan->e_ppos]);
589 plan->e_ppos = plan->e_pbnum;
590 plan->e_psize = plan->e_pbsize;
592 pid = waitpid(pid, &status, 0);
593 return (pid != -1 && WIFEXITED(status) && !WEXITSTATUS(status));
597 * c_exec, c_execdir, c_ok --
598 * build three parallel arrays, one with pointers to the strings passed
599 * on the command line, one with (possibly duplicated) pointers to the
600 * argv array, and one with integer values that are lengths of the
601 * strings, but also flags meaning that the string has to be massaged.
603 PLAN *
604 c_exec(OPTION *option, char ***argvp)
606 PLAN *new; /* node returned */
607 long argmax;
608 int cnt, i;
609 char **argv, **ap, **ep, *p;
611 /* XXX - was in c_execdir, but seems unnecessary!?
612 ftsoptions &= ~FTS_NOSTAT;
614 isoutput = 1;
616 /* XXX - this is a change from the previous coding */
617 new = palloc(option);
619 for (ap = argv = *argvp;; ++ap) {
620 if (!*ap)
621 errx(1,
622 "%s: no terminating \";\" or \"+\"", option->name);
623 if (**ap == ';')
624 break;
625 if (**ap == '+' && ap != argv && strcmp(*(ap - 1), "{}") == 0) {
626 new->flags |= F_EXECPLUS;
627 break;
631 if (ap == argv)
632 errx(1, "%s: no command specified", option->name);
634 cnt = ap - *argvp + 1;
635 if (new->flags & F_EXECPLUS) {
636 new->e_ppos = new->e_pbnum = cnt - 2;
637 if ((argmax = sysconf(_SC_ARG_MAX)) == -1) {
638 warn("sysconf(_SC_ARG_MAX)");
639 argmax = _POSIX_ARG_MAX;
641 argmax -= 1024;
642 for (ep = environ; *ep != NULL; ep++)
643 argmax -= strlen(*ep) + 1 + sizeof(*ep);
644 argmax -= 1 + sizeof(*ep);
645 new->e_pnummax = argmax / 16;
646 argmax -= sizeof(char *) * new->e_pnummax;
647 if (argmax <= 0)
648 errx(1, "no space for arguments");
649 new->e_psizemax = argmax;
650 new->e_pbsize = 0;
651 cnt += new->e_pnummax + 1;
653 if ((new->e_argv = malloc(cnt * sizeof(char *))) == NULL)
654 err(1, NULL);
655 if ((new->e_orig = malloc(cnt * sizeof(char *))) == NULL)
656 err(1, NULL);
657 if ((new->e_len = malloc(cnt * sizeof(int))) == NULL)
658 err(1, NULL);
660 for (argv = *argvp, cnt = 0; argv < ap; ++argv, ++cnt) {
661 new->e_orig[cnt] = *argv;
662 if (new->flags & F_EXECPLUS)
663 new->e_pbsize += strlen(*argv) + 1;
664 for (p = *argv; *p; ++p)
665 if (!(new->flags & F_EXECPLUS) && p[0] == '{' &&
666 p[1] == '}') {
667 if ((new->e_argv[cnt] =
668 malloc(MAXPATHLEN)) == NULL)
669 err(1, NULL);
670 new->e_len[cnt] = MAXPATHLEN;
671 break;
673 if (!*p) {
674 new->e_argv[cnt] = *argv;
675 new->e_len[cnt] = 0;
678 if (new->flags & F_EXECPLUS) {
679 new->e_psize = new->e_pbsize;
680 cnt--;
681 for (i = 0; i < new->e_pnummax; i++) {
682 new->e_argv[cnt] = NULL;
683 new->e_len[cnt] = 0;
684 cnt++;
686 argv = ap;
687 goto done;
689 new->e_argv[cnt] = new->e_orig[cnt] = NULL;
691 done: *argvp = argv + 1;
692 return new;
696 f_flags(PLAN *plan, FTSENT *entry)
698 u_long flags;
700 flags = entry->fts_statp->st_flags;
701 if (plan->flags & F_ATLEAST)
702 return (flags | plan->fl_flags) == flags &&
703 !(flags & plan->fl_notflags);
704 else if (plan->flags & F_ANY)
705 return (flags & plan->fl_flags) ||
706 (flags | plan->fl_notflags) != flags;
707 else
708 return flags == plan->fl_flags &&
709 !(plan->fl_flags & plan->fl_notflags);
712 PLAN *
713 c_flags(OPTION *option, char ***argvp)
715 char *flags_str;
716 PLAN *new;
717 u_long flags, notflags;
719 flags_str = nextarg(option, argvp);
720 ftsoptions &= ~FTS_NOSTAT;
722 new = palloc(option);
724 if (*flags_str == '-') {
725 new->flags |= F_ATLEAST;
726 flags_str++;
727 } else if (*flags_str == '+') {
728 new->flags |= F_ANY;
729 flags_str++;
731 if (strtofflags(&flags_str, &flags, &notflags) == 1)
732 errx(1, "%s: %s: illegal flags string", option->name, flags_str);
734 new->fl_flags = flags;
735 new->fl_notflags = notflags;
736 return new;
740 * -follow functions --
742 * Always true, causes symbolic links to be followed on a global
743 * basis.
745 PLAN *
746 c_follow(OPTION *option, char ***argvp __unused)
748 ftsoptions &= ~FTS_PHYSICAL;
749 ftsoptions |= FTS_LOGICAL;
751 return palloc(option);
755 * -fstype functions --
757 * True if the file is of a certain type.
760 f_fstype(PLAN *plan, FTSENT *entry)
762 static dev_t curdev; /* need a guaranteed illegal dev value */
763 static int first = 1;
764 struct statfs sb;
765 static int val_type, val_flags;
766 char *p, save[2] = {0,0};
768 if ((plan->flags & F_MTMASK) == F_MTUNKNOWN)
769 return 0;
771 /* Only check when we cross mount point. */
772 if (first || curdev != entry->fts_statp->st_dev) {
773 curdev = entry->fts_statp->st_dev;
776 * Statfs follows symlinks; find wants the link's filesystem,
777 * not where it points.
779 if (entry->fts_info == FTS_SL ||
780 entry->fts_info == FTS_SLNONE) {
781 if ((p = strrchr(entry->fts_accpath, '/')) != NULL)
782 ++p;
783 else
784 p = entry->fts_accpath;
785 save[0] = p[0];
786 p[0] = '.';
787 save[1] = p[1];
788 p[1] = '\0';
789 } else
790 p = NULL;
792 if (statfs(entry->fts_accpath, &sb)) {
793 warn("%s", entry->fts_accpath);
794 return 0;
796 if (p) {
797 p[0] = save[0];
798 p[1] = save[1];
801 first = 0;
804 * Further tests may need both of these values, so
805 * always copy both of them.
807 val_flags = sb.f_flags;
808 val_type = sb.f_type;
810 switch (plan->flags & F_MTMASK) {
811 case F_MTFLAG:
812 return val_flags & plan->mt_data;
813 case F_MTTYPE:
814 return val_type == plan->mt_data;
815 default:
816 abort();
820 PLAN *
821 c_fstype(OPTION *option, char ***argvp)
823 char *fsname;
824 PLAN *new;
825 struct vfsconf vfc;
827 fsname = nextarg(option, argvp);
828 ftsoptions &= ~FTS_NOSTAT;
830 new = palloc(option);
833 * Check first for a filesystem name.
835 if (getvfsbyname(fsname, &vfc) == 0) {
836 new->flags |= F_MTTYPE;
837 new->mt_data = vfc.vfc_typenum;
838 return new;
841 switch (*fsname) {
842 case 'l':
843 if (!strcmp(fsname, "local")) {
844 new->flags |= F_MTFLAG;
845 new->mt_data = MNT_LOCAL;
846 return new;
848 break;
849 case 'r':
850 if (!strcmp(fsname, "rdonly")) {
851 new->flags |= F_MTFLAG;
852 new->mt_data = MNT_RDONLY;
853 return new;
855 break;
859 * We need to make filesystem checks for filesystems
860 * that exists but aren't in the kernel work.
862 fprintf(stderr, "Warning: Unknown filesystem type %s\n", fsname);
863 new->flags |= F_MTUNKNOWN;
864 return new;
868 * -group gname functions --
870 * True if the file belongs to the group gname. If gname is numeric and
871 * an equivalent of the getgrnam() function does not return a valid group
872 * name, gname is taken as a group ID.
875 f_group(PLAN *plan, FTSENT *entry)
877 return entry->fts_statp->st_gid == plan->g_data;
880 PLAN *
881 c_group(OPTION *option, char ***argvp)
883 char *gname;
884 PLAN *new;
885 struct group *g;
886 gid_t gid;
888 gname = nextarg(option, argvp);
889 ftsoptions &= ~FTS_NOSTAT;
891 g = getgrnam(gname);
892 if (g == NULL) {
893 gid = atoi(gname);
894 if (gid == 0 && gname[0] != '0')
895 errx(1, "%s: %s: no such group", option->name, gname);
896 } else
897 gid = g->gr_gid;
899 new = palloc(option);
900 new->g_data = gid;
901 return new;
905 * -inum n functions --
907 * True if the file has inode # n.
910 f_inum(PLAN *plan, FTSENT *entry)
912 COMPARE(entry->fts_statp->st_ino, plan->i_data);
915 PLAN *
916 c_inum(OPTION *option, char ***argvp)
918 char *inum_str;
919 PLAN *new;
921 inum_str = nextarg(option, argvp);
922 ftsoptions &= ~FTS_NOSTAT;
924 new = palloc(option);
925 new->i_data = find_parsenum(new, option->name, inum_str, NULL);
926 return new;
930 * -links n functions --
932 * True if the file has n links.
935 f_links(PLAN *plan, FTSENT *entry)
937 COMPARE(entry->fts_statp->st_nlink, plan->l_data);
940 PLAN *
941 c_links(OPTION *option, char ***argvp)
943 char *nlinks;
944 PLAN *new;
946 nlinks = nextarg(option, argvp);
947 ftsoptions &= ~FTS_NOSTAT;
949 new = palloc(option);
950 new->l_data = (nlink_t)find_parsenum(new, option->name, nlinks, NULL);
951 return new;
955 * -ls functions --
957 * Always true - prints the current entry to stdout in "ls" format.
960 f_ls(PLAN *plan __unused, FTSENT *entry)
962 printlong(entry->fts_path, entry->fts_accpath, entry->fts_statp);
963 return 1;
966 PLAN *
967 c_ls(OPTION *option, char ***argvp __unused)
969 ftsoptions &= ~FTS_NOSTAT;
970 isoutput = 1;
972 return palloc(option);
976 * -name functions --
978 * True if the basename of the filename being examined
979 * matches pattern using Pattern Matching Notation S3.14
982 f_name(PLAN *plan, FTSENT *entry)
984 return !fnmatch(plan->c_data, entry->fts_name,
985 plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
988 PLAN *
989 c_name(OPTION *option, char ***argvp)
991 char *pattern;
992 PLAN *new;
994 pattern = nextarg(option, argvp);
995 new = palloc(option);
996 new->c_data = pattern;
997 return new;
1001 * -newer file functions --
1003 * True if the current file has been modified more recently
1004 * then the modification time of the file named by the pathname
1005 * file.
1008 f_newer(PLAN *plan, FTSENT *entry)
1010 if (plan->flags & F_TIME_C)
1011 return entry->fts_statp->st_ctime > plan->t_data;
1012 else if (plan->flags & F_TIME_A)
1013 return entry->fts_statp->st_atime > plan->t_data;
1014 else
1015 return entry->fts_statp->st_mtime > plan->t_data;
1018 PLAN *
1019 c_newer(OPTION *option, char ***argvp)
1021 char *fn_or_tspec;
1022 PLAN *new;
1023 struct stat sb;
1025 fn_or_tspec = nextarg(option, argvp);
1026 ftsoptions &= ~FTS_NOSTAT;
1028 new = palloc(option);
1029 /* compare against what */
1030 if (option->flags & F_TIME2_T) {
1031 new->t_data = get_date(fn_or_tspec, NULL);
1032 if (new->t_data == (time_t) -1)
1033 errx(1, "Can't parse date/time: %s", fn_or_tspec);
1034 } else {
1035 if (stat(fn_or_tspec, &sb))
1036 err(1, "%s", fn_or_tspec);
1037 if (option->flags & F_TIME2_C)
1038 new->t_data = sb.st_ctime;
1039 else if (option->flags & F_TIME2_A)
1040 new->t_data = sb.st_atime;
1041 else
1042 new->t_data = sb.st_mtime;
1044 return new;
1048 * -nogroup functions --
1050 * True if file belongs to a user ID for which the equivalent
1051 * of the getgrnam() 9.2.1 [POSIX.1] function returns NULL.
1054 f_nogroup(PLAN *plan __unused, FTSENT *entry)
1056 return group_from_gid(entry->fts_statp->st_gid, 1) == NULL;
1059 PLAN *
1060 c_nogroup(OPTION *option, char ***argvp __unused)
1062 ftsoptions &= ~FTS_NOSTAT;
1064 return palloc(option);
1068 * -nouser functions --
1070 * True if file belongs to a user ID for which the equivalent
1071 * of the getpwuid() 9.2.2 [POSIX.1] function returns NULL.
1074 f_nouser(PLAN *plan __unused, FTSENT *entry)
1076 return user_from_uid(entry->fts_statp->st_uid, 1) == NULL;
1079 PLAN *
1080 c_nouser(OPTION *option, char ***argvp __unused)
1082 ftsoptions &= ~FTS_NOSTAT;
1084 return palloc(option);
1088 * -path functions --
1090 * True if the path of the filename being examined
1091 * matches pattern using Pattern Matching Notation S3.14
1094 f_path(PLAN *plan, FTSENT *entry)
1096 return !fnmatch(plan->c_data, entry->fts_path,
1097 plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
1100 /* c_path is the same as c_name */
1103 * -perm functions --
1105 * The mode argument is used to represent file mode bits. If it starts
1106 * with a leading digit, it's treated as an octal mode, otherwise as a
1107 * symbolic mode.
1110 f_perm(PLAN *plan, FTSENT *entry)
1112 mode_t mode;
1114 mode = entry->fts_statp->st_mode &
1115 (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO);
1116 if (plan->flags & F_ATLEAST)
1117 return (plan->m_data | mode) == mode;
1118 else if (plan->flags & F_ANY)
1119 return (mode & plan->m_data);
1120 else
1121 return mode == plan->m_data;
1122 /* NOTREACHED */
1125 PLAN *
1126 c_perm(OPTION *option, char ***argvp)
1128 char *perm;
1129 PLAN *new;
1130 mode_t *set;
1132 perm = nextarg(option, argvp);
1133 ftsoptions &= ~FTS_NOSTAT;
1135 new = palloc(option);
1137 if (*perm == '-') {
1138 new->flags |= F_ATLEAST;
1139 ++perm;
1140 } else if (*perm == '+') {
1141 new->flags |= F_ANY;
1142 ++perm;
1145 if ((set = setmode(perm)) == NULL)
1146 errx(1, "%s: %s: illegal mode string", option->name, perm);
1148 new->m_data = getmode(set, 0);
1149 free(set);
1150 return new;
1154 * -print functions --
1156 * Always true, causes the current pathname to be written to
1157 * standard output.
1160 f_print(PLAN *plan __unused, FTSENT *entry)
1162 puts(entry->fts_path);
1163 return 1;
1166 PLAN *
1167 c_print(OPTION *option, char ***argvp __unused)
1169 isoutput = 1;
1171 return palloc(option);
1175 * -print0 functions --
1177 * Always true, causes the current pathname to be written to
1178 * standard output followed by a NUL character
1181 f_print0(PLAN *plan __unused, FTSENT *entry)
1183 fputs(entry->fts_path, stdout);
1184 fputc('\0', stdout);
1185 return 1;
1188 /* c_print0 is the same as c_print */
1191 * -prune functions --
1193 * Prune a portion of the hierarchy.
1196 f_prune(PLAN *plan __unused, FTSENT *entry)
1198 if (fts_set(tree, entry, FTS_SKIP))
1199 err(1, "%s", entry->fts_path);
1200 return 1;
1203 /* c_prune == c_simple */
1206 * -regex functions --
1208 * True if the whole path of the file matches pattern using
1209 * regular expression.
1212 f_regex(PLAN *plan, FTSENT *entry)
1214 char *str;
1215 int len;
1216 regex_t *pre;
1217 regmatch_t pmatch;
1218 int errcode;
1219 char errbuf[LINE_MAX];
1220 int matched;
1222 pre = plan->re_data;
1223 str = entry->fts_path;
1224 len = strlen(str);
1225 matched = 0;
1227 pmatch.rm_so = 0;
1228 pmatch.rm_eo = len;
1230 errcode = regexec(pre, str, 1, &pmatch, REG_STARTEND);
1232 if (errcode != 0 && errcode != REG_NOMATCH) {
1233 regerror(errcode, pre, errbuf, sizeof errbuf);
1234 errx(1, "%s: %s",
1235 plan->flags & F_IGNCASE ? "-iregex" : "-regex", errbuf);
1238 if (errcode == 0 && pmatch.rm_so == 0 && pmatch.rm_eo == len)
1239 matched = 1;
1241 return matched;
1244 PLAN *
1245 c_regex(OPTION *option, char ***argvp)
1247 PLAN *new;
1248 char *pattern;
1249 regex_t *pre;
1250 int errcode;
1251 char errbuf[LINE_MAX];
1253 if ((pre = malloc(sizeof(regex_t))) == NULL)
1254 err(1, NULL);
1256 pattern = nextarg(option, argvp);
1258 if ((errcode = regcomp(pre, pattern,
1259 regexp_flags | (option->flags & F_IGNCASE ? REG_ICASE : 0))) != 0) {
1260 regerror(errcode, pre, errbuf, sizeof errbuf);
1261 errx(1, "%s: %s: %s",
1262 option->flags & F_IGNCASE ? "-iregex" : "-regex",
1263 pattern, errbuf);
1266 new = palloc(option);
1267 new->re_data = pre;
1269 return new;
1272 /* c_simple covers c_prune, c_openparen, c_closeparen, c_not, c_or */
1274 PLAN *
1275 c_simple(OPTION *option, char ***argvp __unused)
1277 return palloc(option);
1281 * -size n[c] functions --
1283 * True if the file size in bytes, divided by an implementation defined
1284 * value and rounded up to the next integer, is n. If n is followed by
1285 * a c, the size is in bytes.
1287 #define FIND_SIZE 512
1288 static int divsize = 1;
1291 f_size(PLAN *plan, FTSENT *entry)
1293 off_t size;
1295 size = divsize ? (entry->fts_statp->st_size + FIND_SIZE - 1) /
1296 FIND_SIZE : entry->fts_statp->st_size;
1297 COMPARE(size, plan->o_data);
1300 PLAN *
1301 c_size(OPTION *option, char ***argvp)
1303 char *size_str;
1304 PLAN *new;
1305 char endch;
1307 size_str = nextarg(option, argvp);
1308 ftsoptions &= ~FTS_NOSTAT;
1310 new = palloc(option);
1311 endch = 'c';
1312 new->o_data = find_parsenum(new, option->name, size_str, &endch);
1313 if (endch == 'c')
1314 divsize = 0;
1315 return new;
1319 * -type c functions --
1321 * True if the type of the file is c, where c is b, c, d, p, f or w
1322 * for block special file, character special file, directory, FIFO,
1323 * regular file or whiteout respectively.
1326 f_type(PLAN *plan, FTSENT *entry)
1328 return (entry->fts_statp->st_mode & S_IFMT) == plan->m_data;
1331 PLAN *
1332 c_type(OPTION *option, char ***argvp)
1334 char *typestring;
1335 PLAN *new;
1336 mode_t mask;
1338 typestring = nextarg(option, argvp);
1339 ftsoptions &= ~FTS_NOSTAT;
1341 switch (typestring[0]) {
1342 case 'b':
1343 mask = S_IFBLK;
1344 break;
1345 case 'c':
1346 mask = S_IFCHR;
1347 break;
1348 case 'd':
1349 mask = S_IFDIR;
1350 break;
1351 case 'f':
1352 mask = S_IFREG;
1353 break;
1354 case 'l':
1355 mask = S_IFLNK;
1356 break;
1357 case 'p':
1358 mask = S_IFIFO;
1359 break;
1360 case 's':
1361 mask = S_IFSOCK;
1362 break;
1363 #ifdef FTS_WHITEOUT
1364 case 'w':
1365 mask = S_IFWHT;
1366 ftsoptions |= FTS_WHITEOUT;
1367 break;
1368 #endif /* FTS_WHITEOUT */
1369 default:
1370 errx(1, "%s: %s: unknown type", option->name, typestring);
1373 new = palloc(option);
1374 new->m_data = mask;
1375 return new;
1379 * -user uname functions --
1381 * True if the file belongs to the user uname. If uname is numeric and
1382 * an equivalent of the getpwnam() S9.2.2 [POSIX.1] function does not
1383 * return a valid user name, uname is taken as a user ID.
1386 f_user(PLAN *plan, FTSENT *entry)
1388 return entry->fts_statp->st_uid == plan->u_data;
1391 PLAN *
1392 c_user(OPTION *option, char ***argvp)
1394 char *username;
1395 PLAN *new;
1396 struct passwd *p;
1397 uid_t uid;
1399 username = nextarg(option, argvp);
1400 ftsoptions &= ~FTS_NOSTAT;
1402 p = getpwnam(username);
1403 if (p == NULL) {
1404 uid = atoi(username);
1405 if (uid == 0 && username[0] != '0')
1406 errx(1, "%s: %s: no such user", option->name, username);
1407 } else
1408 uid = p->pw_uid;
1410 new = palloc(option);
1411 new->u_data = uid;
1412 return new;
1416 * -xdev functions --
1418 * Always true, causes find not to descend past directories that have a
1419 * different device ID (st_dev, see stat() S5.6.2 [POSIX.1])
1421 PLAN *
1422 c_xdev(OPTION *option, char ***argvp __unused)
1424 ftsoptions |= FTS_XDEV;
1426 return palloc(option);
1430 * ( expression ) functions --
1432 * True if expression is true.
1435 f_expr(PLAN *plan, FTSENT *entry)
1437 PLAN *p;
1438 int state = 0;
1440 for (p = plan->p_data[0];
1441 p && (state = (p->execute)(p, entry)); p = p->next);
1442 return state;
1446 * f_openparen and f_closeparen nodes are temporary place markers. They are
1447 * eliminated during phase 2 of find_formplan() --- the '(' node is converted
1448 * to a f_expr node containing the expression and the ')' node is discarded.
1449 * The functions themselves are only used as constants.
1453 f_openparen(PLAN *plan __unused, FTSENT *entry __unused)
1455 abort();
1459 f_closeparen(PLAN *plan __unused, FTSENT *entry __unused)
1461 abort();
1464 /* c_openparen == c_simple */
1465 /* c_closeparen == c_simple */
1468 * AND operator. Since AND is implicit, no node is allocated.
1470 PLAN *
1471 c_and(OPTION *option __unused, char ***argvp __unused)
1473 return NULL;
1477 * ! expression functions --
1479 * Negation of a primary; the unary NOT operator.
1482 f_not(PLAN *plan, FTSENT *entry)
1484 PLAN *p;
1485 int state = 0;
1487 for (p = plan->p_data[0];
1488 p && (state = (p->execute)(p, entry)); p = p->next);
1489 return !state;
1492 /* c_not == c_simple */
1495 * expression -o expression functions --
1497 * Alternation of primaries; the OR operator. The second expression is
1498 * not evaluated if the first expression is true.
1501 f_or(PLAN *plan, FTSENT *entry)
1503 PLAN *p;
1504 int state = 0;
1506 for (p = plan->p_data[0];
1507 p && (state = (p->execute)(p, entry)); p = p->next);
1509 if (state)
1510 return 1;
1512 for (p = plan->p_data[1];
1513 p && (state = (p->execute)(p, entry)); p = p->next);
1514 return state;
1517 /* c_or == c_simple */