2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Cimarron D. Taylor of the University of California, Berkeley.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 static const char sccsid[] = "@(#)function.c 8.10 (Berkeley) 5/4/95";
39 #include <sys/cdefs.h>
40 #include <sys/param.h>
41 #include <sys/ucred.h>
43 #include <sys/types.h>
46 #include <sys/mount.h>
65 static PLAN *palloc(OPTION *);
66 static long long find_parsenum(PLAN *, const char *, char *, char *);
67 static long long find_parsetime(PLAN *, const char *, char *);
68 static char *nextarg(OPTION *, char ***);
70 extern char **environ;
72 static PLAN *lastexecplus = NULL;
74 #define COMPARE(a, b) do { \
75 switch (plan->flags & F_ELG_MASK) { \
88 palloc(OPTION *option)
92 if ((new = malloc(sizeof(PLAN))) == NULL)
94 new->execute = option->execute;
95 new->flags = option->flags;
102 * Parse a string of the form [+-]# and return the value.
105 find_parsenum(PLAN *plan, const char *option, char *vp, char *endch)
108 char *endchar, *str; /* Pointer to character ending conversion. */
110 /* Determine comparison from leading + or -. */
115 plan->flags |= F_GREATER;
119 plan->flags |= F_LESSTHAN;
122 plan->flags |= F_EQUAL;
127 * Convert the string with strtoq(). Note, if strtoq() returns zero
128 * and endchar points to the beginning of the string we know we have
131 value = strtoq(str, &endchar, 10);
132 if (value == 0 && endchar == str)
133 errx(1, "%s: %s: illegal numeric value", option, vp);
134 if (endchar[0] && endch == NULL)
135 errx(1, "%s: %s: illegal trailing character", option, vp);
143 * Parse a string of the form [+-]([0-9]+[smhdw]?)+ and return the value.
146 find_parsetime(PLAN *plan, const char *option, char *vp)
148 long long secs, value;
149 char *str, *unit; /* Pointer to character ending conversion. */
151 /* Determine comparison from leading + or -. */
156 plan->flags |= F_GREATER;
160 plan->flags |= F_LESSTHAN;
163 plan->flags |= F_EQUAL;
167 value = strtoq(str, &unit, 10);
168 if (value == 0 && unit == str) {
169 errx(1, "%s: %s: illegal time value", option, vp);
179 case 's': /* seconds */
182 case 'm': /* minutes */
185 case 'h': /* hours */
186 secs += value * 3600;
189 secs += value * 86400;
191 case 'w': /* weeks */
192 secs += value * 604800;
195 errx(1, "%s: %s: bad unit '%c'", option, vp, *unit);
199 if (*str == '\0') /* EOS */
201 value = strtoq(str, &unit, 10);
202 if (value == 0 && unit == str) {
203 errx(1, "%s: %s: illegal time value", option, vp);
207 errx(1, "%s: %s: missing trailing unit", option, vp);
211 plan->flags |= F_EXACTTIME;
217 * Check that another argument still exists, return a pointer to it,
218 * and increment the argument vector pointer.
221 nextarg(OPTION *option, char ***argvp)
225 if ((arg = **argvp) == NULL)
226 errx(1, "%s: requires additional arguments", option->name);
232 * The value of n for the inode times (atime, birthtime, ctime, mtime) is a
233 * range, i.e. n matches from (n - 1) to n 24 hour periods. This interacts
234 * with -n, such that "-mtime -1" would be less than 0 days, which isn't what
235 * the user wanted. Correct so that -1 is "less than 1".
237 #define TIME_CORRECT(p) \
238 if (((p)->flags & F_ELG_MASK) == F_LESSTHAN) \
239 ++((p)->t_data.tv_sec);
242 * -[acm]min n functions --
244 * True if the difference between the
245 * file access time (-amin)
246 * file birth time (-Bmin)
247 * last change of file status information (-cmin)
248 * file modification time (-mmin)
249 * and the current time is n min periods.
252 f_Xmin(PLAN *plan, FTSENT *entry)
254 if (plan->flags & F_TIME_C) {
255 COMPARE((now - entry->fts_statp->st_ctime +
256 60 - 1) / 60, plan->t_data.tv_sec);
257 } else if (plan->flags & F_TIME_A) {
258 COMPARE((now - entry->fts_statp->st_atime +
259 60 - 1) / 60, plan->t_data.tv_sec);
260 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
261 } else if (plan->flags & F_TIME_B) {
262 COMPARE((now - entry->fts_statp->st_birthtime +
263 60 - 1) / 60, plan->t_data.tv_sec);
266 COMPARE((now - entry->fts_statp->st_mtime +
267 60 - 1) / 60, plan->t_data.tv_sec);
272 c_Xmin(OPTION *option, char ***argvp)
277 nmins = nextarg(option, argvp);
278 ftsoptions &= ~FTS_NOSTAT;
280 new = palloc(option);
281 new->t_data.tv_sec = find_parsenum(new, option->name, nmins, NULL);
282 new->t_data.tv_nsec = 0;
288 * -[acm]time n functions --
290 * True if the difference between the
291 * file access time (-atime)
292 * file birth time (-Btime)
293 * last change of file status information (-ctime)
294 * file modification time (-mtime)
295 * and the current time is n 24 hour periods.
299 f_Xtime(PLAN *plan, FTSENT *entry)
303 if (plan->flags & F_TIME_A)
304 xtime = entry->fts_statp->st_atime;
305 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
306 else if (plan->flags & F_TIME_B)
307 xtime = entry->fts_statp->st_birthtime;
309 else if (plan->flags & F_TIME_C)
310 xtime = entry->fts_statp->st_ctime;
312 xtime = entry->fts_statp->st_mtime;
314 if (plan->flags & F_EXACTTIME)
315 COMPARE(now - xtime, plan->t_data.tv_sec);
317 COMPARE((now - xtime + 86400 - 1) / 86400, plan->t_data.tv_sec);
321 c_Xtime(OPTION *option, char ***argvp)
326 value = nextarg(option, argvp);
327 ftsoptions &= ~FTS_NOSTAT;
329 new = palloc(option);
330 new->t_data.tv_sec = find_parsetime(new, option->name, value);
331 new->t_data.tv_nsec = 0;
332 if (!(new->flags & F_EXACTTIME))
338 * -maxdepth/-mindepth n functions --
340 * Does the same as -prune if the level of the current file is
341 * greater/less than the specified maximum/minimum depth.
343 * Note that -maxdepth and -mindepth are handled specially in
344 * find_execute() so their f_* functions are set to f_always_true().
347 c_mXXdepth(OPTION *option, char ***argvp)
352 dstr = nextarg(option, argvp);
354 /* all other errors handled by find_parsenum() */
355 errx(1, "%s: %s: value must be positive", option->name, dstr);
357 new = palloc(option);
358 if (option->flags & F_MAXDEPTH)
359 maxdepth = find_parsenum(new, option->name, dstr, NULL);
361 mindepth = find_parsenum(new, option->name, dstr, NULL);
369 * Show files with EXTENDED ACL attributes.
372 f_acl(PLAN *plan __unused, FTSENT *entry)
376 int acl_supported = 0, ret, trivial;
378 if (S_ISLNK(entry->fts_statp->st_mode))
380 ret = pathconf(entry->fts_accpath, _PC_ACL_NFS4);
383 acl_type = ACL_TYPE_NFS4;
384 } else if (ret < 0 && errno != EINVAL) {
385 warn("%s", entry->fts_accpath);
388 if (acl_supported == 0) {
389 ret = pathconf(entry->fts_accpath, _PC_ACL_EXTENDED);
392 acl_type = ACL_TYPE_ACCESS;
393 } else if (ret < 0 && errno != EINVAL) {
394 warn("%s", entry->fts_accpath);
398 if (acl_supported == 0)
401 facl = acl_get_file(entry->fts_accpath, acl_type);
403 warn("%s", entry->fts_accpath);
406 ret = acl_is_trivial_np(facl, &trivial);
409 warn("%s", entry->fts_accpath);
419 c_acl(OPTION *option, char ***argvp __unused)
421 ftsoptions &= ~FTS_NOSTAT;
422 return (palloc(option));
426 * -delete functions --
428 * True always. Makes its best shot and continues on regardless.
431 f_delete(PLAN *plan __unused, FTSENT *entry)
433 /* ignore these from fts */
434 if (strcmp(entry->fts_accpath, ".") == 0 ||
435 strcmp(entry->fts_accpath, "..") == 0)
439 if (isdepth == 0 || /* depth off */
440 (ftsoptions & FTS_NOSTAT)) /* not stat()ing */
441 errx(1, "-delete: insecure options got turned on");
443 if (!(ftsoptions & FTS_PHYSICAL) || /* physical off */
444 (ftsoptions & FTS_LOGICAL)) /* or finally, logical on */
445 errx(1, "-delete: forbidden when symlinks are followed");
447 /* Potentially unsafe - do not accept relative paths whatsoever */
448 if (entry->fts_level > FTS_ROOTLEVEL &&
449 strchr(entry->fts_accpath, '/') != NULL)
450 errx(1, "-delete: %s: relative path potentially not safe",
453 #if HAVE_STRUCT_STAT_ST_FLAGS
454 /* Turn off user immutable bits if running as root */
455 if ((entry->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
456 !(entry->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
458 lchflags(entry->fts_accpath,
459 entry->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
462 /* rmdir directories, unlink everything else */
463 if (S_ISDIR(entry->fts_statp->st_mode)) {
464 if (rmdir(entry->fts_accpath) < 0 && errno != ENOTEMPTY)
465 warn("-delete: rmdir(%s)", entry->fts_path);
467 if (unlink(entry->fts_accpath) < 0)
468 warn("-delete: unlink(%s)", entry->fts_path);
476 c_delete(OPTION *option, char ***argvp __unused)
479 ftsoptions &= ~FTS_NOSTAT; /* no optimise */
480 isoutput = 1; /* possible output */
481 isdepth = 1; /* -depth implied */
484 * Try to avoid the confusing error message about relative paths
485 * being potentially not safe.
487 if (ftsoptions & FTS_NOCHDIR)
488 errx(1, "%s: forbidden when the current directory cannot be opened",
491 return palloc(option);
498 * Always true, used for -maxdepth, -mindepth, -xdev, -follow, and -true
501 f_always_true(PLAN *plan __unused, FTSENT *entry __unused)
507 * -depth functions --
509 * With argument: True if the file is at level n.
510 * Without argument: Always true, causes descent of the directory hierarchy
511 * to be done so that all entries in a directory are acted on before the
515 f_depth(PLAN *plan, FTSENT *entry)
517 if (plan->flags & F_DEPTH)
518 COMPARE(entry->fts_level, plan->d_data);
524 c_depth(OPTION *option, char ***argvp)
529 new = palloc(option);
532 if (str && !(new->flags & F_DEPTH)) {
533 /* skip leading + or - */
534 if (*str == '+' || *str == '-')
537 if (*str == '+' || *str == '-')
540 new->flags |= F_DEPTH;
543 if (new->flags & F_DEPTH) { /* -depth n */
546 ndepth = nextarg(option, argvp);
547 new->d_data = find_parsenum(new, option->name, ndepth, NULL);
556 * -empty functions --
558 * True if the file or directory is empty
561 f_empty(PLAN *plan __unused, FTSENT *entry)
563 if (S_ISREG(entry->fts_statp->st_mode) &&
564 entry->fts_statp->st_size == 0)
566 if (S_ISDIR(entry->fts_statp->st_mode)) {
572 dir = opendir(entry->fts_accpath);
575 for (dp = readdir(dir); dp; dp = readdir(dir))
576 if (dp->d_name[0] != '.' ||
577 (dp->d_name[1] != '\0' &&
578 (dp->d_name[1] != '.' || dp->d_name[2] != '\0'))) {
589 c_empty(OPTION *option, char ***argvp __unused)
591 ftsoptions &= ~FTS_NOSTAT;
593 return palloc(option);
597 * [-exec | -execdir | -ok] utility [arg ... ] ; functions --
599 * True if the executed utility returns a zero value as exit status.
600 * The end of the primary expression is delimited by a semicolon. If
601 * "{}" occurs anywhere, it gets replaced by the current pathname,
602 * or, in the case of -execdir, the current basename (filename
603 * without leading directory prefix). For -exec and -ok,
604 * the current directory for the execution of utility is the same as
605 * the current directory when the find utility was started, whereas
606 * for -execdir, it is the directory the file resides in.
608 * The primary -ok differs from -exec in that it requests affirmation
609 * of the user before executing the utility.
612 f_exec(PLAN *plan, FTSENT *entry)
619 if (entry == NULL && plan->flags & F_EXECPLUS) {
620 if (plan->e_ppos == plan->e_pbnum)
622 plan->e_argv[plan->e_ppos] = NULL;
626 /* XXX - if file/dir ends in '/' this will not work -- can it? */
627 if ((plan->flags & F_EXECDIR) && \
628 (file = strrchr(entry->fts_path, '/')))
631 file = entry->fts_path;
633 if (plan->flags & F_EXECPLUS) {
634 if ((plan->e_argv[plan->e_ppos] = strdup(file)) == NULL)
636 plan->e_len[plan->e_ppos] = strlen(file);
637 plan->e_psize += plan->e_len[plan->e_ppos];
638 if (++plan->e_ppos < plan->e_pnummax &&
639 plan->e_psize < plan->e_psizemax)
641 plan->e_argv[plan->e_ppos] = NULL;
643 for (cnt = 0; plan->e_argv[cnt]; ++cnt)
644 if (plan->e_len[cnt])
645 brace_subst(plan->e_orig[cnt],
646 &plan->e_argv[cnt], file,
650 doexec: if ((plan->flags & F_NEEDOK) && !queryuser(plan->e_argv))
653 /* make sure find output is interspersed correctly with subprocesses */
657 switch (pid = fork()) {
662 /* change dir back from where we started */
663 if (!(plan->flags & F_EXECDIR) &&
664 !(ftsoptions & FTS_NOCHDIR) && fchdir(dotfd)) {
668 execvp(plan->e_argv[0], plan->e_argv);
669 warn("%s", plan->e_argv[0]);
672 if (plan->flags & F_EXECPLUS) {
673 while (--plan->e_ppos >= plan->e_pbnum)
674 free(plan->e_argv[plan->e_ppos]);
675 plan->e_ppos = plan->e_pbnum;
676 plan->e_psize = plan->e_pbsize;
678 pid = waitpid(pid, &status, 0);
679 if (pid != -1 && WIFEXITED(status) && !WEXITSTATUS(status))
681 if (plan->flags & F_EXECPLUS) {
689 * c_exec, c_execdir, c_ok --
690 * build three parallel arrays, one with pointers to the strings passed
691 * on the command line, one with (possibly duplicated) pointers to the
692 * argv array, and one with integer values that are lengths of the
693 * strings, but also flags meaning that the string has to be massaged.
696 c_exec(OPTION *option, char ***argvp)
698 PLAN *new; /* node returned */
701 char **argv, **ap, **ep, *p;
703 /* This would defeat -execdir's intended security. */
704 if (option->flags & F_EXECDIR && ftsoptions & FTS_NOCHDIR)
705 errx(1, "%s: forbidden when the current directory cannot be opened",
708 /* XXX - was in c_execdir, but seems unnecessary!?
709 ftsoptions &= ~FTS_NOSTAT;
713 /* XXX - this is a change from the previous coding */
714 new = palloc(option);
716 for (ap = argv = *argvp;; ++ap) {
719 "%s: no terminating \";\" or \"+\"", option->name);
722 if (**ap == '+' && ap != argv && strcmp(*(ap - 1), "{}") == 0) {
723 new->flags |= F_EXECPLUS;
729 errx(1, "%s: no command specified", option->name);
731 cnt = ap - *argvp + 1;
732 if (new->flags & F_EXECPLUS) {
733 new->e_ppos = new->e_pbnum = cnt - 2;
734 if ((argmax = sysconf(_SC_ARG_MAX)) == -1) {
735 warn("sysconf(_SC_ARG_MAX)");
736 argmax = _POSIX_ARG_MAX;
739 for (ep = environ; *ep != NULL; ep++)
740 argmax -= strlen(*ep) + 1 + sizeof(*ep);
741 argmax -= 1 + sizeof(*ep);
743 * Ensure that -execdir ... {} + does not mix files
744 * from different directories in one invocation.
745 * Files from the same directory should be handled
746 * in one invocation but there is no code for it.
748 new->e_pnummax = new->flags & F_EXECDIR ? 1 : argmax / 16;
749 argmax -= sizeof(char *) * new->e_pnummax;
751 errx(1, "no space for arguments");
752 new->e_psizemax = argmax;
754 cnt += new->e_pnummax + 1;
755 new->e_next = lastexecplus;
758 if ((new->e_argv = malloc(cnt * sizeof(char *))) == NULL)
760 if ((new->e_orig = malloc(cnt * sizeof(char *))) == NULL)
762 if ((new->e_len = malloc(cnt * sizeof(int))) == NULL)
765 for (argv = *argvp, cnt = 0; argv < ap; ++argv, ++cnt) {
766 new->e_orig[cnt] = *argv;
767 if (new->flags & F_EXECPLUS)
768 new->e_pbsize += strlen(*argv) + 1;
769 for (p = *argv; *p; ++p)
770 if (!(new->flags & F_EXECPLUS) && p[0] == '{' &&
772 if ((new->e_argv[cnt] =
773 malloc(MAXPATHLEN)) == NULL)
775 new->e_len[cnt] = MAXPATHLEN;
779 new->e_argv[cnt] = *argv;
783 if (new->flags & F_EXECPLUS) {
784 new->e_psize = new->e_pbsize;
786 for (i = 0; i < new->e_pnummax; i++) {
787 new->e_argv[cnt] = NULL;
794 new->e_argv[cnt] = new->e_orig[cnt] = NULL;
796 done: *argvp = argv + 1;
800 /* Finish any pending -exec ... {} + functions. */
802 finish_execplus(void)
808 (p->execute)(p, NULL);
813 #if HAVE_STRUCT_STAT_ST_FLAGS
815 f_flags(PLAN *plan, FTSENT *entry)
819 flags = entry->fts_statp->st_flags;
820 if (plan->flags & F_ATLEAST)
821 return (flags | plan->fl_flags) == flags &&
822 !(flags & plan->fl_notflags);
823 else if (plan->flags & F_ANY)
824 return (flags & plan->fl_flags) ||
825 (flags | plan->fl_notflags) != flags;
827 return flags == plan->fl_flags &&
828 !(plan->fl_flags & plan->fl_notflags);
832 c_flags(OPTION *option, char ***argvp)
836 u_long flags, notflags;
838 flags_str = nextarg(option, argvp);
839 ftsoptions &= ~FTS_NOSTAT;
841 new = palloc(option);
843 if (*flags_str == '-') {
844 new->flags |= F_ATLEAST;
846 } else if (*flags_str == '+') {
850 if (strtofflags(&flags_str, &flags, ¬flags) == 1)
851 errx(1, "%s: %s: illegal flags string", option->name, flags_str);
853 new->fl_flags = flags;
854 new->fl_notflags = notflags;
860 * -follow functions --
862 * Always true, causes symbolic links to be followed on a global
866 c_follow(OPTION *option, char ***argvp __unused)
868 ftsoptions &= ~FTS_PHYSICAL;
869 ftsoptions |= FTS_LOGICAL;
871 return palloc(option);
874 #if HAVE_STRUCT_STATFS_F_FSTYPENAME
876 * -fstype functions --
878 * True if the file is of a certain type.
881 f_fstype(PLAN *plan, FTSENT *entry)
883 static dev_t curdev; /* need a guaranteed illegal dev value */
884 static int first = 1;
886 static int val_flags;
887 static char fstype[sizeof(sb.f_fstypename)];
888 char *p, save[2] = {0,0};
890 if ((plan->flags & F_MTMASK) == F_MTUNKNOWN)
893 /* Only check when we cross mount point. */
894 if (first || curdev != entry->fts_statp->st_dev) {
895 curdev = entry->fts_statp->st_dev;
898 * Statfs follows symlinks; find wants the link's filesystem,
899 * not where it points.
901 if (entry->fts_info == FTS_SL ||
902 entry->fts_info == FTS_SLNONE) {
903 if ((p = strrchr(entry->fts_accpath, '/')) != NULL)
906 p = entry->fts_accpath;
914 if (statfs(entry->fts_accpath, &sb)) {
915 if (!ignore_readdir_race || errno != ENOENT) {
916 warn("statfs: %s", entry->fts_accpath);
930 * Further tests may need both of these values, so
931 * always copy both of them.
933 val_flags = sb.f_flags;
934 strlcpy(fstype, sb.f_fstypename, sizeof(fstype));
936 switch (plan->flags & F_MTMASK) {
938 return val_flags & plan->mt_data;
940 return (strncmp(fstype, plan->c_data, sizeof(fstype)) == 0);
947 c_fstype(OPTION *option, char ***argvp)
952 fsname = nextarg(option, argvp);
953 ftsoptions &= ~FTS_NOSTAT;
955 new = palloc(option);
958 if (!strcmp(fsname, "local")) {
959 new->flags |= F_MTFLAG;
960 new->mt_data = MNT_LOCAL;
965 if (!strcmp(fsname, "rdonly")) {
966 new->flags |= F_MTFLAG;
967 new->mt_data = MNT_RDONLY;
973 new->flags |= F_MTTYPE;
974 new->c_data = fsname;
980 * -group gname functions --
982 * True if the file belongs to the group gname. If gname is numeric and
983 * an equivalent of the getgrnam() function does not return a valid group
984 * name, gname is taken as a group ID.
987 f_group(PLAN *plan, FTSENT *entry)
989 COMPARE(entry->fts_statp->st_gid, plan->g_data);
993 c_group(OPTION *option, char ***argvp)
1000 gname = nextarg(option, argvp);
1001 ftsoptions &= ~FTS_NOSTAT;
1003 new = palloc(option);
1004 g = getgrnam(gname);
1007 if (gname[0] == '-' || gname[0] == '+')
1010 if (gid == 0 && gname[0] != '0')
1011 errx(1, "%s: %s: no such group", option->name, gname);
1012 gid = find_parsenum(new, option->name, cp, NULL);
1021 * -ignore_readdir_race functions --
1023 * Always true. Ignore errors which occur if a file or a directory
1024 * in a starting point gets deleted between reading the name and calling
1025 * stat on it while find is traversing the starting point.
1029 c_ignore_readdir_race(OPTION *option, char ***argvp __unused)
1031 if (strcmp(option->name, "-ignore_readdir_race") == 0)
1032 ignore_readdir_race = 1;
1034 ignore_readdir_race = 0;
1036 return palloc(option);
1040 * -inum n functions --
1042 * True if the file has inode # n.
1045 f_inum(PLAN *plan, FTSENT *entry)
1047 COMPARE(entry->fts_statp->st_ino, plan->i_data);
1051 c_inum(OPTION *option, char ***argvp)
1056 inum_str = nextarg(option, argvp);
1057 ftsoptions &= ~FTS_NOSTAT;
1059 new = palloc(option);
1060 new->i_data = find_parsenum(new, option->name, inum_str, NULL);
1067 * True if the file has the same inode (eg hard link) FN
1070 /* f_samefile is just f_inum */
1072 c_samefile(OPTION *option, char ***argvp)
1079 fn = nextarg(option, argvp);
1080 ftsoptions &= ~FTS_NOSTAT;
1082 new = palloc(option);
1083 if (ftsoptions & FTS_PHYSICAL)
1084 error = lstat(fn, &sb);
1086 error = stat(fn, &sb);
1089 new->i_data = sb.st_ino;
1094 * -links n functions --
1096 * True if the file has n links.
1099 f_links(PLAN *plan, FTSENT *entry)
1101 COMPARE(entry->fts_statp->st_nlink, plan->l_data);
1105 c_links(OPTION *option, char ***argvp)
1110 nlinks = nextarg(option, argvp);
1111 ftsoptions &= ~FTS_NOSTAT;
1113 new = palloc(option);
1114 new->l_data = (nlink_t)find_parsenum(new, option->name, nlinks, NULL);
1121 * Always true - prints the current entry to stdout in "ls" format.
1124 f_ls(PLAN *plan __unused, FTSENT *entry)
1126 printlong(entry->fts_path, entry->fts_accpath, entry->fts_statp);
1131 c_ls(OPTION *option, char ***argvp __unused)
1133 ftsoptions &= ~FTS_NOSTAT;
1136 return palloc(option);
1140 * -name functions --
1142 * True if the basename of the filename being examined
1143 * matches pattern using Pattern Matching Notation S3.14
1146 f_name(PLAN *plan, FTSENT *entry)
1152 if (plan->flags & F_LINK) {
1154 * The below test both avoids obviously useless readlink()
1155 * calls and ensures that symlinks with existent target do
1156 * not match if symlinks are being followed.
1157 * Assumption: fts will stat all symlinks that are to be
1158 * followed and will return the stat information.
1160 if (entry->fts_info != FTS_NSOK && entry->fts_info != FTS_SL &&
1161 entry->fts_info != FTS_SLNONE)
1163 len = readlink(entry->fts_accpath, fn, sizeof(fn) - 1);
1169 name = entry->fts_name;
1170 return !fnmatch(plan->c_data, name,
1171 plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
1175 c_name(OPTION *option, char ***argvp)
1180 pattern = nextarg(option, argvp);
1181 new = palloc(option);
1182 new->c_data = pattern;
1187 * -newer file functions --
1189 * True if the current file has been modified more recently
1190 * then the modification time of the file named by the pathname
1194 f_newer(PLAN *plan, FTSENT *entry)
1198 if (plan->flags & F_TIME_C)
1199 ft = entry->fts_statp->st_ctim;
1200 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
1201 else if (plan->flags & F_TIME_A)
1202 ft = entry->fts_statp->st_atim;
1203 else if (plan->flags & F_TIME_B)
1204 ft = entry->fts_statp->st_birthtim;
1207 ft = entry->fts_statp->st_mtim;
1208 return (ft.tv_sec > plan->t_data.tv_sec ||
1209 (ft.tv_sec == plan->t_data.tv_sec &&
1210 ft.tv_nsec > plan->t_data.tv_nsec));
1214 c_newer(OPTION *option, char ***argvp)
1221 fn_or_tspec = nextarg(option, argvp);
1222 ftsoptions &= ~FTS_NOSTAT;
1224 new = palloc(option);
1225 /* compare against what */
1226 if (option->flags & F_TIME2_T) {
1227 new->t_data.tv_sec = get_date(fn_or_tspec);
1228 if (new->t_data.tv_sec == (time_t) -1)
1229 errx(1, "Can't parse date/time: %s", fn_or_tspec);
1230 /* Use the seconds only in the comparison. */
1231 new->t_data.tv_nsec = 999999999;
1233 if (ftsoptions & FTS_PHYSICAL)
1234 error = lstat(fn_or_tspec, &sb);
1236 error = stat(fn_or_tspec, &sb);
1238 err(1, "%s", fn_or_tspec);
1239 if (option->flags & F_TIME2_C)
1240 new->t_data = sb.st_ctim;
1241 else if (option->flags & F_TIME2_A)
1242 new->t_data = sb.st_atim;
1243 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
1244 else if (option->flags & F_TIME2_B)
1245 new->t_data = sb.st_birthtim;
1248 new->t_data = sb.st_mtim;
1254 * -nogroup functions --
1256 * True if file belongs to a user ID for which the equivalent
1257 * of the getgrnam() 9.2.1 [POSIX.1] function returns NULL.
1260 f_nogroup(PLAN *plan __unused, FTSENT *entry)
1262 return group_from_gid(entry->fts_statp->st_gid, 1) == NULL;
1266 c_nogroup(OPTION *option, char ***argvp __unused)
1268 ftsoptions &= ~FTS_NOSTAT;
1270 return palloc(option);
1274 * -nouser functions --
1276 * True if file belongs to a user ID for which the equivalent
1277 * of the getpwuid() 9.2.2 [POSIX.1] function returns NULL.
1280 f_nouser(PLAN *plan __unused, FTSENT *entry)
1282 return user_from_uid(entry->fts_statp->st_uid, 1) == NULL;
1286 c_nouser(OPTION *option, char ***argvp __unused)
1288 ftsoptions &= ~FTS_NOSTAT;
1290 return palloc(option);
1294 * -path functions --
1296 * True if the path of the filename being examined
1297 * matches pattern using Pattern Matching Notation S3.14
1300 f_path(PLAN *plan, FTSENT *entry)
1302 return !fnmatch(plan->c_data, entry->fts_path,
1303 plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
1306 /* c_path is the same as c_name */
1309 * -perm functions --
1311 * The mode argument is used to represent file mode bits. If it starts
1312 * with a leading digit, it's treated as an octal mode, otherwise as a
1316 f_perm(PLAN *plan, FTSENT *entry)
1320 mode = entry->fts_statp->st_mode &
1321 (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO);
1322 if (plan->flags & F_ATLEAST)
1323 return (plan->m_data | mode) == mode;
1324 else if (plan->flags & F_ANY)
1325 return (mode & plan->m_data);
1327 return mode == plan->m_data;
1332 c_perm(OPTION *option, char ***argvp)
1338 perm = nextarg(option, argvp);
1339 ftsoptions &= ~FTS_NOSTAT;
1341 new = palloc(option);
1344 new->flags |= F_ATLEAST;
1346 } else if (*perm == '+') {
1347 new->flags |= F_ANY;
1351 if ((set = setmode(perm)) == NULL)
1352 errx(1, "%s: %s: illegal mode string", option->name, perm);
1354 new->m_data = getmode(set, 0);
1360 * -print functions --
1362 * Always true, causes the current pathname to be written to
1366 f_print(PLAN *plan __unused, FTSENT *entry)
1368 (void)puts(entry->fts_path);
1373 c_print(OPTION *option, char ***argvp __unused)
1377 return palloc(option);
1381 * -print0 functions --
1383 * Always true, causes the current pathname to be written to
1384 * standard output followed by a NUL character
1387 f_print0(PLAN *plan __unused, FTSENT *entry)
1389 fputs(entry->fts_path, stdout);
1390 fputc('\0', stdout);
1394 /* c_print0 is the same as c_print */
1397 * -prune functions --
1399 * Prune a portion of the hierarchy.
1402 f_prune(PLAN *plan __unused, FTSENT *entry)
1404 if (fts_set(tree, entry, FTS_SKIP))
1405 err(1, "%s", entry->fts_path);
1409 /* c_prune == c_simple */
1412 * -regex functions --
1414 * True if the whole path of the file matches pattern using
1415 * regular expression.
1418 f_regex(PLAN *plan, FTSENT *entry)
1425 char errbuf[LINE_MAX];
1428 pre = plan->re_data;
1429 str = entry->fts_path;
1436 errcode = regexec(pre, str, 1, &pmatch, REG_STARTEND);
1438 if (errcode != 0 && errcode != REG_NOMATCH) {
1439 regerror(errcode, pre, errbuf, sizeof errbuf);
1441 plan->flags & F_IGNCASE ? "-iregex" : "-regex", errbuf);
1444 if (errcode == 0 && pmatch.rm_so == 0 && pmatch.rm_eo == len)
1451 c_regex(OPTION *option, char ***argvp)
1457 char errbuf[LINE_MAX];
1459 if ((pre = malloc(sizeof(regex_t))) == NULL)
1462 pattern = nextarg(option, argvp);
1464 if ((errcode = regcomp(pre, pattern,
1465 regexp_flags | (option->flags & F_IGNCASE ? REG_ICASE : 0))) != 0) {
1466 regerror(errcode, pre, errbuf, sizeof errbuf);
1467 errx(1, "%s: %s: %s",
1468 option->flags & F_IGNCASE ? "-iregex" : "-regex",
1472 new = palloc(option);
1478 /* c_simple covers c_prune, c_openparen, c_closeparen, c_not, c_or, c_true, c_false */
1481 c_simple(OPTION *option, char ***argvp __unused)
1483 return palloc(option);
1487 * -size n[c] functions --
1489 * True if the file size in bytes, divided by an implementation defined
1490 * value and rounded up to the next integer, is n. If n is followed by
1491 * one of c k M G T P, the size is in bytes, kilobytes,
1492 * megabytes, gigabytes, terabytes or petabytes respectively.
1494 #define FIND_SIZE 512
1495 static int divsize = 1;
1498 f_size(PLAN *plan, FTSENT *entry)
1502 size = divsize ? (entry->fts_statp->st_size + FIND_SIZE - 1) /
1503 FIND_SIZE : entry->fts_statp->st_size;
1504 COMPARE(size, plan->o_data);
1508 c_size(OPTION *option, char ***argvp)
1515 size_str = nextarg(option, argvp);
1516 ftsoptions &= ~FTS_NOSTAT;
1518 new = palloc(option);
1520 new->o_data = find_parsenum(new, option->name, size_str, &endch);
1521 if (endch != '\0') {
1525 case 'c': /* characters */
1528 case 'k': /* kilobytes 1<<10 */
1531 case 'M': /* megabytes 1<<20 */
1534 case 'G': /* gigabytes 1<<30 */
1535 scale = 0x40000000LL;
1537 case 'T': /* terabytes 1<<40 */
1538 scale = 0x10000000000LL;
1540 case 'P': /* petabytes 1<<50 */
1541 scale = 0x4000000000000LL;
1544 errx(1, "%s: %s: illegal trailing character",
1545 option->name, size_str);
1548 if (new->o_data > QUAD_MAX / scale)
1549 errx(1, "%s: %s: value too large",
1550 option->name, size_str);
1551 new->o_data *= scale;
1557 * -sparse functions --
1559 * Check if a file is sparse by finding if it occupies fewer blocks
1560 * than we expect based on its size.
1563 f_sparse(PLAN *plan __unused, FTSENT *entry)
1565 off_t expected_blocks;
1567 expected_blocks = (entry->fts_statp->st_size + 511) / 512;
1568 return entry->fts_statp->st_blocks < expected_blocks;
1572 c_sparse(OPTION *option, char ***argvp __unused)
1574 ftsoptions &= ~FTS_NOSTAT;
1576 return palloc(option);
1580 * -type c functions --
1582 * True if the type of the file is c, where c is b, c, d, p, f or w
1583 * for block special file, character special file, directory, FIFO,
1584 * regular file or whiteout respectively.
1587 f_type(PLAN *plan, FTSENT *entry)
1589 if (plan->m_data == S_IFDIR)
1590 return (entry->fts_info == FTS_D || entry->fts_info == FTS_DC ||
1591 entry->fts_info == FTS_DNR || entry->fts_info == FTS_DOT ||
1592 entry->fts_info == FTS_DP);
1594 return (entry->fts_statp->st_mode & S_IFMT) == plan->m_data;
1598 c_type(OPTION *option, char ***argvp)
1604 typestring = nextarg(option, argvp);
1605 if (typestring[0] != 'd')
1606 ftsoptions &= ~FTS_NOSTAT;
1608 switch (typestring[0]) {
1630 #if defined(FTS_WHITEOUT) && defined(S_IFWHT)
1633 ftsoptions |= FTS_WHITEOUT;
1635 #endif /* FTS_WHITEOUT */
1637 errx(1, "%s: %s: unknown type", option->name, typestring);
1640 new = palloc(option);
1646 * -user uname functions --
1648 * True if the file belongs to the user uname. If uname is numeric and
1649 * an equivalent of the getpwnam() S9.2.2 [POSIX.1] function does not
1650 * return a valid user name, uname is taken as a user ID.
1653 f_user(PLAN *plan, FTSENT *entry)
1655 COMPARE(entry->fts_statp->st_uid, plan->u_data);
1659 c_user(OPTION *option, char ***argvp)
1666 username = nextarg(option, argvp);
1667 ftsoptions &= ~FTS_NOSTAT;
1669 new = palloc(option);
1670 p = getpwnam(username);
1672 char* cp = username;
1673 if( username[0] == '-' || username[0] == '+' )
1675 uid = atoi(username);
1676 if (uid == 0 && username[0] != '0')
1677 errx(1, "%s: %s: no such user", option->name, username);
1678 uid = find_parsenum(new, option->name, cp, NULL);
1687 * -xdev functions --
1689 * Always true, causes find not to descend past directories that have a
1690 * different device ID (st_dev, see stat() S5.6.2 [POSIX.1])
1693 c_xdev(OPTION *option, char ***argvp __unused)
1695 ftsoptions |= FTS_XDEV;
1697 return palloc(option);
1701 * ( expression ) functions --
1703 * True if expression is true.
1706 f_expr(PLAN *plan, FTSENT *entry)
1711 for (p = plan->p_data[0];
1712 p && (state = (p->execute)(p, entry)); p = p->next);
1717 * f_openparen and f_closeparen nodes are temporary place markers. They are
1718 * eliminated during phase 2 of find_formplan() --- the '(' node is converted
1719 * to a f_expr node containing the expression and the ')' node is discarded.
1720 * The functions themselves are only used as constants.
1724 f_openparen(PLAN *plan __unused, FTSENT *entry __unused)
1730 f_closeparen(PLAN *plan __unused, FTSENT *entry __unused)
1735 /* c_openparen == c_simple */
1736 /* c_closeparen == c_simple */
1739 * AND operator. Since AND is implicit, no node is allocated.
1742 c_and(OPTION *option __unused, char ***argvp __unused)
1748 * ! expression functions --
1750 * Negation of a primary; the unary NOT operator.
1753 f_not(PLAN *plan, FTSENT *entry)
1758 for (p = plan->p_data[0];
1759 p && (state = (p->execute)(p, entry)); p = p->next);
1763 /* c_not == c_simple */
1766 * expression -o expression functions --
1768 * Alternation of primaries; the OR operator. The second expression is
1769 * not evaluated if the first expression is true.
1772 f_or(PLAN *plan, FTSENT *entry)
1777 for (p = plan->p_data[0];
1778 p && (state = (p->execute)(p, entry)); p = p->next);
1783 for (p = plan->p_data[1];
1784 p && (state = (p->execute)(p, entry)); p = p->next);
1788 /* c_or == c_simple */
1796 f_false(PLAN *plan __unused, FTSENT *entry __unused)
1801 /* c_false == c_simple */
1809 f_quit(PLAN *plan __unused, FTSENT *entry __unused)
1815 /* c_quit == c_simple */