function.c revision 264782
11590Srgrimes/*-
21590Srgrimes * Copyright (c) 1990, 1993
31590Srgrimes *	The Regents of the University of California.  All rights reserved.
41590Srgrimes *
51590Srgrimes * This code is derived from software contributed to Berkeley by
61590Srgrimes * Cimarron D. Taylor of the University of California, Berkeley.
71590Srgrimes *
81590Srgrimes * Redistribution and use in source and binary forms, with or without
91590Srgrimes * modification, are permitted provided that the following conditions
101590Srgrimes * are met:
111590Srgrimes * 1. Redistributions of source code must retain the above copyright
121590Srgrimes *    notice, this list of conditions and the following disclaimer.
131590Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141590Srgrimes *    notice, this list of conditions and the following disclaimer in the
151590Srgrimes *    documentation and/or other materials provided with the distribution.
161590Srgrimes * 4. Neither the name of the University nor the names of its contributors
171590Srgrimes *    may be used to endorse or promote products derived from this software
181590Srgrimes *    without specific prior written permission.
191590Srgrimes *
201590Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211590Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221590Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231590Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241590Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251590Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261590Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271590Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281590Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291590Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301590Srgrimes * SUCH DAMAGE.
311590Srgrimes */
321590Srgrimes
331590Srgrimes#ifndef lint
3441568Sarchie#if 0
351590Srgrimesstatic const char sccsid[] = "@(#)function.c	8.10 (Berkeley) 5/4/95";
361590Srgrimes#endif
3787242Smarkm#endif /* not lint */
381590Srgrimes
3987628Sdwmalone#include <sys/cdefs.h>
401590Srgrimes__FBSDID("$FreeBSD: stable/10/usr.bin/find/function.c 264782 2014-04-22 21:13:25Z brueffer $");
4187628Sdwmalone
4258602Scharnier#include <sys/param.h>
4387628Sdwmalone#include <sys/ucred.h>
441590Srgrimes#include <sys/stat.h>
4587628Sdwmalone#include <sys/types.h>
4687628Sdwmalone#include <sys/acl.h>
4787628Sdwmalone#include <sys/wait.h>
48282949Sbapt#include <sys/mount.h>
49282949Sbapt
501590Srgrimes#include <dirent.h>
51282949Sbapt#include <err.h>
52132824Stjr#include <errno.h>
531590Srgrimes#include <fnmatch.h>
541590Srgrimes#include <fts.h>
55132825Stjr#include <grp.h>
56282949Sbapt#include <limits.h>
5723693Speter#include <pwd.h>
58132824Stjr#include <regex.h>
59132824Stjr#include <stdio.h>
601590Srgrimes#include <stdlib.h>
611590Srgrimes#include <string.h>
621590Srgrimes#include <unistd.h>
631590Srgrimes#include <ctype.h>
641590Srgrimes
651590Srgrimes#include "find.h"
661590Srgrimes
671590Srgrimesstatic PLAN *palloc(OPTION *);
681590Srgrimesstatic long long find_parsenum(PLAN *, const char *, char *, char *);
691590Srgrimesstatic long long find_parsetime(PLAN *, const char *, char *);
70282949Sbaptstatic char *nextarg(OPTION *, char ***);
71282949Sbapt
72282949Sbaptextern char **environ;
731590Srgrimes
741590Srgrimesstatic PLAN *lastexecplus = NULL;
751590Srgrimes
761590Srgrimes#define	COMPARE(a, b) do {						\
771590Srgrimes	switch (plan->flags & F_ELG_MASK) {				\
781590Srgrimes	case F_EQUAL:							\
791590Srgrimes		return (a == b);					\
801590Srgrimes	case F_LESSTHAN:						\
811590Srgrimes		return (a < b);						\
821590Srgrimes	case F_GREATER:							\
831590Srgrimes		return (a > b);						\
84132824Stjr	default:							\
85132824Stjr		abort();						\
861590Srgrimes	}								\
871590Srgrimes} while(0)
881590Srgrimes
891590Srgrimesstatic PLAN *
901590Srgrimespalloc(OPTION *option)
911590Srgrimes{
921590Srgrimes	PLAN *new;
931590Srgrimes
941590Srgrimes	if ((new = malloc(sizeof(PLAN))) == NULL)
951590Srgrimes		err(1, NULL);
961590Srgrimes	new->execute = option->execute;
971590Srgrimes	new->flags = option->flags;
981590Srgrimes	new->next = NULL;
99282949Sbapt	return new;
100227157Sed}
101227157Sed
102227157Sed/*
103227157Sed * find_parsenum --
104227157Sed *	Parse a string of the form [+-]# and return the value.
105227157Sed */
106227157Sedstatic long long
1071590Srgrimesfind_parsenum(PLAN *plan, const char *option, char *vp, char *endch)
108227157Sed{
109227157Sed	long long value;
110227157Sed	char *endchar, *str;	/* Pointer to character ending conversion. */
111227157Sed
112282949Sbapt	/* Determine comparison from leading + or -. */
113227157Sed	str = vp;
114227157Sed	switch (*str) {
115227157Sed	case '+':
1161590Srgrimes		++str;
1171590Srgrimes		plan->flags |= F_GREATER;
11878383Smikeh		break;
119132824Stjr	case '-':
12078383Smikeh		++str;
1215676Sbde		plan->flags |= F_LESSTHAN;
1221590Srgrimes		break;
1231590Srgrimes	default:
124102944Sdwmalone		plan->flags |= F_EQUAL;
1251590Srgrimes		break;
126132824Stjr	}
1271590Srgrimes
1281590Srgrimes	/*
1291590Srgrimes	 * Convert the string with strtoq().  Note, if strtoq() returns zero
1301590Srgrimes	 * and endchar points to the beginning of the string we know we have
1311590Srgrimes	 * a syntax error.
1321590Srgrimes	 */
1331590Srgrimes	value = strtoq(str, &endchar, 10);
1341590Srgrimes	if (value == 0 && endchar == str)
1351590Srgrimes		errx(1, "%s: %s: illegal numeric value", option, vp);
136132824Stjr	if (endchar[0] && endch == NULL)
137282949Sbapt		errx(1, "%s: %s: illegal trailing character", option, vp);
138282949Sbapt	if (endch)
139282949Sbapt		*endch = endchar[0];
1401590Srgrimes	return value;
14178383Smikeh}
14211765Sache
143282949Sbapt/*
144282949Sbapt * find_parsetime --
145282949Sbapt *	Parse a string of the form [+-]([0-9]+[smhdw]?)+ and return the value.
146282949Sbapt */
147282949Sbaptstatic long long
148282949Sbaptfind_parsetime(PLAN *plan, const char *option, char *vp)
149282949Sbapt{
150282949Sbapt	long long secs, value;
151282949Sbapt	char *str, *unit;	/* Pointer to character ending conversion. */
152282949Sbapt
153282949Sbapt	/* Determine comparison from leading + or -. */
154282949Sbapt	str = vp;
155282949Sbapt	switch (*str) {
156282949Sbapt	case '+':
1571590Srgrimes		++str;
15878384Smikeh		plan->flags |= F_GREATER;
1591590Srgrimes		break;
1601590Srgrimes	case '-':
1611590Srgrimes		++str;
1621590Srgrimes		plan->flags |= F_LESSTHAN;
1631590Srgrimes		break;
1641590Srgrimes	default:
1651590Srgrimes		plan->flags |= F_EQUAL;
1661590Srgrimes		break;
1671590Srgrimes	}
1681590Srgrimes
1691590Srgrimes	value = strtoq(str, &unit, 10);
170282949Sbapt	if (value == 0 && unit == str) {
171282949Sbapt		errx(1, "%s: %s: illegal time value", option, vp);
172282949Sbapt		/* NOTREACHED */
173282949Sbapt	}
174282949Sbapt	if (*unit == '\0')
1751590Srgrimes		return value;
17678384Smikeh
17778384Smikeh	/* Units syntax. */
17878384Smikeh	secs = 0;
1791590Srgrimes	for (;;) {
1801590Srgrimes		switch(*unit) {
1811590Srgrimes		case 's':	/* seconds */
1821590Srgrimes			secs += value;
1831590Srgrimes			break;
1841590Srgrimes		case 'm':	/* minutes */
1851590Srgrimes			secs += value * 60;
1861590Srgrimes			break;
1871590Srgrimes		case 'h':	/* hours */
1881590Srgrimes			secs += value * 3600;
1891590Srgrimes			break;
1901590Srgrimes		case 'd':	/* days */
1911590Srgrimes			secs += value * 86400;
1921590Srgrimes			break;
1931590Srgrimes		case 'w':	/* weeks */
1941590Srgrimes			secs += value * 604800;
195132824Stjr			break;
196132824Stjr		default:
1971590Srgrimes			errx(1, "%s: %s: bad unit '%c'", option, vp, *unit);
1981590Srgrimes			/* NOTREACHED */
1991590Srgrimes		}
2001590Srgrimes		str = unit + 1;
2011590Srgrimes		if (*str == '\0')	/* EOS */
2021590Srgrimes			break;
2031590Srgrimes		value = strtoq(str, &unit, 10);
2041590Srgrimes		if (value == 0 && unit == str) {
2051590Srgrimes			errx(1, "%s: %s: illegal time value", option, vp);
2061590Srgrimes			/* NOTREACHED */
207132824Stjr		}
208282949Sbapt		if (*unit == '\0') {
209282949Sbapt			errx(1, "%s: %s: missing trailing unit", option, vp);
210282949Sbapt			/* NOTREACHED */
211282949Sbapt		}
212282949Sbapt	}
213282949Sbapt	plan->flags |= F_EXACTTIME;
214282949Sbapt	return secs;
2151590Srgrimes}
216282949Sbapt
2171590Srgrimes/*
218282949Sbapt * nextarg --
219282949Sbapt *	Check that another argument still exists, return a pointer to it,
2201590Srgrimes *	and increment the argument vector pointer.
221282949Sbapt */
2221590Srgrimesstatic char *
223282949Sbaptnextarg(OPTION *option, char ***argvp)
224282949Sbapt{
2251590Srgrimes	char *arg;
226282949Sbapt
2271590Srgrimes	if ((arg = **argvp) == 0)
2281590Srgrimes		errx(1, "%s: requires additional arguments", option->name);
2291590Srgrimes	(*argvp)++;
2301590Srgrimes	return arg;
2311590Srgrimes} /* nextarg() */
232282949Sbapt
2331590Srgrimes/*
2341590Srgrimes * The value of n for the inode times (atime, birthtime, ctime, mtime) is a
2351590Srgrimes * range, i.e. n matches from (n - 1) to n 24 hour periods.  This interacts
2361590Srgrimes * with -n, such that "-mtime -1" would be less than 0 days, which isn't what
2371590Srgrimes * the user wanted.  Correct so that -1 is "less than 1".
2381590Srgrimes */
2391590Srgrimes#define	TIME_CORRECT(p) \
2401590Srgrimes	if (((p)->flags & F_ELG_MASK) == F_LESSTHAN) \
2411590Srgrimes		++((p)->t_data.tv_sec);
2421590Srgrimes
2431590Srgrimes/*
2441590Srgrimes * -[acm]min n functions --
2451590Srgrimes *
2461590Srgrimes *    True if the difference between the
2471590Srgrimes *		file access time (-amin)
2481590Srgrimes *		file birth time (-Bmin)
2491590Srgrimes *		last change of file status information (-cmin)
2501590Srgrimes *		file modification time (-mmin)
251282949Sbapt *    and the current time is n min periods.
2521590Srgrimes */
2531590Srgrimesint
254132824Stjrf_Xmin(PLAN *plan, FTSENT *entry)
255132824Stjr{
256132824Stjr	if (plan->flags & F_TIME_C) {
257132824Stjr		COMPARE((now - entry->fts_statp->st_ctime +
258132824Stjr		    60 - 1) / 60, plan->t_data.tv_sec);
25978384Smikeh	} else if (plan->flags & F_TIME_A) {
26078384Smikeh		COMPARE((now - entry->fts_statp->st_atime +
2611590Srgrimes		    60 - 1) / 60, plan->t_data.tv_sec);
2621590Srgrimes	} else if (plan->flags & F_TIME_B) {
2631590Srgrimes		COMPARE((now - entry->fts_statp->st_birthtime +
264282949Sbapt		    60 - 1) / 60, plan->t_data.tv_sec);
2651590Srgrimes	} else {
2661590Srgrimes		COMPARE((now - entry->fts_statp->st_mtime +
267282949Sbapt		    60 - 1) / 60, plan->t_data.tv_sec);
268282949Sbapt	}
269282949Sbapt}
270282949Sbapt
271282949SbaptPLAN *
272282949Sbaptc_Xmin(OPTION *option, char ***argvp)
273282949Sbapt{
274282949Sbapt	char *nmins;
2751590Srgrimes	PLAN *new;
276282949Sbapt
2771590Srgrimes	nmins = nextarg(option, argvp);
2781590Srgrimes	ftsoptions &= ~FTS_NOSTAT;
2791590Srgrimes
2801590Srgrimes	new = palloc(option);
2811590Srgrimes	new->t_data.tv_sec = find_parsenum(new, option->name, nmins, NULL);
2821590Srgrimes	new->t_data.tv_nsec = 0;
283282949Sbapt	TIME_CORRECT(new);
284282949Sbapt	return new;
2851590Srgrimes}
2861590Srgrimes
2871590Srgrimes/*
2881590Srgrimes * -[acm]time n functions --
2891590Srgrimes *
290282949Sbapt *	True if the difference between the
2911590Srgrimes *		file access time (-atime)
2921590Srgrimes *		file birth time (-Btime)
2931590Srgrimes *		last change of file status information (-ctime)
2941590Srgrimes *		file modification time (-mtime)
295282949Sbapt *	and the current time is n 24 hour periods.
2961590Srgrimes */
2971590Srgrimes
2981590Srgrimesint
2991590Srgrimesf_Xtime(PLAN *plan, FTSENT *entry)
300282949Sbapt{
301282949Sbapt	time_t xtime;
302282949Sbapt
303282949Sbapt	if (plan->flags & F_TIME_A)
304282949Sbapt		xtime = entry->fts_statp->st_atime;
3051590Srgrimes	else if (plan->flags & F_TIME_B)
306282949Sbapt		xtime = entry->fts_statp->st_birthtime;
3071590Srgrimes	else if (plan->flags & F_TIME_C)
3081590Srgrimes		xtime = entry->fts_statp->st_ctime;
309282949Sbapt	else
310282949Sbapt		xtime = entry->fts_statp->st_mtime;
311282949Sbapt
312282949Sbapt	if (plan->flags & F_EXACTTIME)
313282949Sbapt		COMPARE(now - xtime, plan->t_data.tv_sec);
314282949Sbapt	else
315282949Sbapt		COMPARE((now - xtime + 86400 - 1) / 86400, plan->t_data.tv_sec);
316282949Sbapt}
317282949Sbapt
318282949SbaptPLAN *
3191590Srgrimesc_Xtime(OPTION *option, char ***argvp)
3201590Srgrimes{
3211590Srgrimes	char *value;
3221590Srgrimes	PLAN *new;
3231590Srgrimes
3241590Srgrimes	value = nextarg(option, argvp);
3251590Srgrimes	ftsoptions &= ~FTS_NOSTAT;
32680293Sobrien
32780293Sobrien	new = palloc(option);
32880293Sobrien	new->t_data.tv_sec = find_parsetime(new, option->name, value);
3291590Srgrimes	new->t_data.tv_nsec = 0;
3301590Srgrimes	if (!(new->flags & F_EXACTTIME))
3311590Srgrimes		TIME_CORRECT(new);
3321590Srgrimes	return new;
3331590Srgrimes}
3341590Srgrimes
335132824Stjr/*
3361590Srgrimes * -maxdepth/-mindepth n functions --
3371590Srgrimes *
3381590Srgrimes *        Does the same as -prune if the level of the current file is
3391590Srgrimes *        greater/less than the specified maximum/minimum depth.
3401590Srgrimes *
3411590Srgrimes *        Note that -maxdepth and -mindepth are handled specially in
3421590Srgrimes *        find_execute() so their f_* functions are set to f_always_true().
3431590Srgrimes */
344132824StjrPLAN *
345132824Stjrc_mXXdepth(OPTION *option, char ***argvp)
3461590Srgrimes{
347132824Stjr	char *dstr;
348132824Stjr	PLAN *new;
349282949Sbapt
350282949Sbapt	dstr = nextarg(option, argvp);
35123693Speter	if (dstr[0] == '-')
3521590Srgrimes		/* all other errors handled by find_parsenum() */
3531590Srgrimes		errx(1, "%s: %s: value must be positive", option->name, dstr);
3541590Srgrimes
355282949Sbapt	new = palloc(option);
3561590Srgrimes	if (option->flags & F_MAXDEPTH)
3571590Srgrimes		maxdepth = find_parsenum(new, option->name, dstr, NULL);
3581590Srgrimes	else
359282949Sbapt		mindepth = find_parsenum(new, option->name, dstr, NULL);
3601590Srgrimes	return new;
3611590Srgrimes}
362282949Sbapt
363282949Sbapt/*
3641590Srgrimes * -acl function --
3651590Srgrimes *
3661590Srgrimes *	Show files with EXTENDED ACL attributes.
3671590Srgrimes */
3681590Srgrimesint
3691590Srgrimesf_acl(PLAN *plan __unused, FTSENT *entry)
370227157Sed{
371102944Sdwmalone	acl_t facl;
3721590Srgrimes	acl_type_t acl_type;
3731590Srgrimes	int acl_supported = 0, ret, trivial;
3741590Srgrimes
3751590Srgrimes	if (S_ISLNK(entry->fts_statp->st_mode))
3761590Srgrimes		return 0;
3771590Srgrimes	ret = pathconf(entry->fts_accpath, _PC_ACL_NFS4);
3781590Srgrimes	if (ret > 0) {
3791590Srgrimes		acl_supported = 1;
3801590Srgrimes		acl_type = ACL_TYPE_NFS4;
3811590Srgrimes	} else if (ret < 0 && errno != EINVAL) {
382282949Sbapt		warn("%s", entry->fts_accpath);
383282949Sbapt		return (0);
3841590Srgrimes	}
38578383Smikeh	if (acl_supported == 0) {
3861590Srgrimes		ret = pathconf(entry->fts_accpath, _PC_ACL_EXTENDED);
3871590Srgrimes		if (ret > 0) {
3881590Srgrimes			acl_supported = 1;
3891590Srgrimes			acl_type = ACL_TYPE_ACCESS;
3901590Srgrimes		} else if (ret < 0 && errno != EINVAL) {
3911590Srgrimes			warn("%s", entry->fts_accpath);
3921590Srgrimes			return (0);
3931590Srgrimes		}
3941590Srgrimes	}
3951590Srgrimes	if (acl_supported == 0)
3961590Srgrimes		return (0);
397227157Sed
398102944Sdwmalone	facl = acl_get_file(entry->fts_accpath, acl_type);
3991590Srgrimes	if (facl == NULL) {
4001590Srgrimes		warn("%s", entry->fts_accpath);
4011590Srgrimes		return (0);
4021590Srgrimes	}
4031590Srgrimes	ret = acl_is_trivial_np(facl, &trivial);
4041590Srgrimes	acl_free(facl);
4051590Srgrimes	if (ret) {
4061590Srgrimes		warn("%s", entry->fts_accpath);
4071590Srgrimes		return (0);
4081590Srgrimes	}
4091590Srgrimes	if (trivial)
4101590Srgrimes		return (0);
4111590Srgrimes	return (1);
4121590Srgrimes}
4131590Srgrimes
414282949SbaptPLAN *
415282949Sbaptc_acl(OPTION *option, char ***argvp __unused)
4161590Srgrimes{
4171590Srgrimes	ftsoptions &= ~FTS_NOSTAT;
4181590Srgrimes	return (palloc(option));
4191590Srgrimes}
4201590Srgrimes
4211590Srgrimes/*
4221590Srgrimes * -delete functions --
4231590Srgrimes *
4241590Srgrimes *	True always.  Makes its best shot and continues on regardless.
4251590Srgrimes */
426227157Sedint
427102944Sdwmalonef_delete(PLAN *plan __unused, FTSENT *entry)
4281590Srgrimes{
4291590Srgrimes	/* ignore these from fts */
430160464Sstefanf	if (strcmp(entry->fts_accpath, ".") == 0 ||
4311590Srgrimes	    strcmp(entry->fts_accpath, "..") == 0)
4321590Srgrimes		return 1;
4331590Srgrimes
4341590Srgrimes	/* sanity check */
4351590Srgrimes	if (isdepth == 0 ||			/* depth off */
4361590Srgrimes	    (ftsoptions & FTS_NOSTAT))		/* not stat()ing */
437160464Sstefanf		errx(1, "-delete: insecure options got turned on");
4381590Srgrimes
4391590Srgrimes	if (!(ftsoptions & FTS_PHYSICAL) ||	/* physical off */
4401590Srgrimes	    (ftsoptions & FTS_LOGICAL))		/* or finally, logical on */
4411590Srgrimes		errx(1, "-delete: forbidden when symlinks are followed");
4421590Srgrimes
4431590Srgrimes	/* Potentially unsafe - do not accept relative paths whatsoever */
4441590Srgrimes	if (entry->fts_level > FTS_ROOTLEVEL &&
44580293Sobrien	    strchr(entry->fts_accpath, '/') != NULL)
44680293Sobrien		errx(1, "-delete: %s: relative path potentially not safe",
44780293Sobrien			entry->fts_accpath);
4481590Srgrimes
4491590Srgrimes	/* Turn off user immutable bits if running as root */
4501590Srgrimes	if ((entry->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
45180293Sobrien	    !(entry->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
45280293Sobrien	    geteuid() == 0)
45380293Sobrien		lchflags(entry->fts_accpath,
4541590Srgrimes		       entry->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
45578383Smikeh
4561590Srgrimes	/* rmdir directories, unlink everything else */
4571590Srgrimes	if (S_ISDIR(entry->fts_statp->st_mode)) {
4581590Srgrimes		if (rmdir(entry->fts_accpath) < 0 && errno != ENOTEMPTY)
4591590Srgrimes			warn("-delete: rmdir(%s)", entry->fts_path);
4601590Srgrimes	} else {
4611590Srgrimes		if (unlink(entry->fts_accpath) < 0)
4621590Srgrimes			warn("-delete: unlink(%s)", entry->fts_path);
4631590Srgrimes	}
4641590Srgrimes
4651590Srgrimes	/* "succeed" */
4661590Srgrimes	return 1;
4671590Srgrimes}
4681590Srgrimes
4691590SrgrimesPLAN *
4701590Srgrimesc_delete(OPTION *option, char ***argvp __unused)
4711590Srgrimes{
4721590Srgrimes
4731590Srgrimes	ftsoptions &= ~FTS_NOSTAT;	/* no optimise */
4741590Srgrimes	isoutput = 1;			/* possible output */
4751590Srgrimes	isdepth = 1;			/* -depth implied */
4761590Srgrimes
4771590Srgrimes	/*
4781590Srgrimes	 * Try to avoid the confusing error message about relative paths
4791590Srgrimes	 * being potentially not safe.
4801590Srgrimes	 */
4811590Srgrimes	if (ftsoptions & FTS_NOCHDIR)
482132824Stjr		errx(1, "%s: forbidden when the current directory cannot be opened",
4831590Srgrimes		    "-delete");
484132824Stjr
485132824Stjr	return palloc(option);
486132824Stjr}
487132824Stjr
4881590Srgrimes
4891590Srgrimes/*
4901590Srgrimes * always_true --
4911590Srgrimes *
4921590Srgrimes *	Always true, used for -maxdepth, -mindepth, -xdev, -follow, and -true
4935676Sbde */
494210088Semasteint
4951590Srgrimesf_always_true(PLAN *plan __unused, FTSENT *entry __unused)
4965676Sbde{
4975676Sbde	return 1;
4985676Sbde}
4995676Sbde
5005676Sbde/*
5015676Sbde * -depth functions --
5025676Sbde *
5035676Sbde *	With argument: True if the file is at level n.
5045676Sbde *	Without argument: Always true, causes descent of the directory hierarchy
5055676Sbde *	to be done so that all entries in a directory are acted on before the
5065676Sbde *	directory itself.
5071590Srgrimes */
5081590Srgrimesint
5091590Srgrimesf_depth(PLAN *plan, FTSENT *entry)
5101590Srgrimes{
5111590Srgrimes	if (plan->flags & F_DEPTH)
5121590Srgrimes		COMPARE(entry->fts_level, plan->d_data);
5131590Srgrimes	else
5141590Srgrimes		return 1;
5151590Srgrimes}
5161590Srgrimes
517282949SbaptPLAN *
5181590Srgrimesc_depth(OPTION *option, char ***argvp)
5191590Srgrimes{
520282949Sbapt	PLAN *new;
5211590Srgrimes	char *str;
5221590Srgrimes
5231590Srgrimes	new = palloc(option);
5241590Srgrimes
525132824Stjr	str = **argvp;
526152394Sdwmalone	if (str && !(new->flags & F_DEPTH)) {
527132824Stjr		/* skip leading + or - */
5281590Srgrimes		if (*str == '+' || *str == '-')
5291590Srgrimes			str++;
5301590Srgrimes		/* skip sign */
531132824Stjr		if (*str == '+' || *str == '-')
5321590Srgrimes			str++;
5331590Srgrimes		if (isdigit(*str))
5341590Srgrimes			new->flags |= F_DEPTH;
535282949Sbapt	}
536282949Sbapt
537282949Sbapt	if (new->flags & F_DEPTH) {	/* -depth n */
538282949Sbapt		char *ndepth;
539282949Sbapt
540282949Sbapt		ndepth = nextarg(option, argvp);
541282949Sbapt		new->d_data = find_parsenum(new, option->name, ndepth, NULL);
542282949Sbapt	} else {			/* -d */
543282949Sbapt		isdepth = 1;
544282949Sbapt	}
545282949Sbapt
546282949Sbapt	return new;
547282949Sbapt}
548282949Sbapt
549282949Sbapt/*
550282949Sbapt * -empty functions --
551282949Sbapt *
5521590Srgrimes *	True if the file or directory is empty
5531590Srgrimes */
5541590Srgrimesint
5551590Srgrimesf_empty(PLAN *plan __unused, FTSENT *entry)
556227157Sed{
557102944Sdwmalone	if (S_ISREG(entry->fts_statp->st_mode) &&
5581590Srgrimes	    entry->fts_statp->st_size == 0)
5591590Srgrimes		return 1;
5601590Srgrimes	if (S_ISDIR(entry->fts_statp->st_mode)) {
5611590Srgrimes		struct dirent *dp;
5621590Srgrimes		int empty;
56380293Sobrien		DIR *dir;
56480293Sobrien
5651590Srgrimes		empty = 1;
5661590Srgrimes		dir = opendir(entry->fts_accpath);
5671590Srgrimes		if (dir == NULL)
5681590Srgrimes			return 0;
5691590Srgrimes		for (dp = readdir(dir); dp; dp = readdir(dir))
5701590Srgrimes			if (dp->d_name[0] != '.' ||
5711590Srgrimes			    (dp->d_name[1] != '\0' &&
5721590Srgrimes			     (dp->d_name[1] != '.' || dp->d_name[2] != '\0'))) {
5731590Srgrimes				empty = 0;
5741590Srgrimes				break;
5751590Srgrimes			}
5761590Srgrimes		closedir(dir);
577227157Sed		return empty;
578102944Sdwmalone	}
5791590Srgrimes	return 0;
5801590Srgrimes}
5811590Srgrimes
5821590SrgrimesPLAN *
5831590Srgrimesc_empty(OPTION *option, char ***argvp __unused)
5841590Srgrimes{
585227157Sed	ftsoptions &= ~FTS_NOSTAT;
586102944Sdwmalone
5871590Srgrimes	return palloc(option);
5881590Srgrimes}
58978384Smikeh
5901590Srgrimes/*
5911590Srgrimes * [-exec | -execdir | -ok] utility [arg ... ] ; functions --
5921590Srgrimes *
593227157Sed *	True if the executed utility returns a zero value as exit status.
594102944Sdwmalone *	The end of the primary expression is delimited by a semicolon.  If
5951590Srgrimes *	"{}" occurs anywhere, it gets replaced by the current pathname,
5961590Srgrimes *	or, in the case of -execdir, the current basename (filename
5971590Srgrimes *	without leading directory prefix). For -exec and -ok,
5981590Srgrimes *	the current directory for the execution of utility is the same as
5991590Srgrimes *	the current directory when the find utility was started, whereas
600 *	for -execdir, it is the directory the file resides in.
601 *
602 *	The primary -ok differs from -exec in that it requests affirmation
603 *	of the user before executing the utility.
604 */
605int
606f_exec(PLAN *plan, FTSENT *entry)
607{
608	int cnt;
609	pid_t pid;
610	int status;
611	char *file;
612
613	if (entry == NULL && plan->flags & F_EXECPLUS) {
614		if (plan->e_ppos == plan->e_pbnum)
615			return (1);
616		plan->e_argv[plan->e_ppos] = NULL;
617		goto doexec;
618	}
619
620	/* XXX - if file/dir ends in '/' this will not work -- can it? */
621	if ((plan->flags & F_EXECDIR) && \
622	    (file = strrchr(entry->fts_path, '/')))
623		file++;
624	else
625		file = entry->fts_path;
626
627	if (plan->flags & F_EXECPLUS) {
628		if ((plan->e_argv[plan->e_ppos] = strdup(file)) == NULL)
629			err(1, NULL);
630		plan->e_len[plan->e_ppos] = strlen(file);
631		plan->e_psize += plan->e_len[plan->e_ppos];
632		if (++plan->e_ppos < plan->e_pnummax &&
633		    plan->e_psize < plan->e_psizemax)
634			return (1);
635		plan->e_argv[plan->e_ppos] = NULL;
636	} else {
637		for (cnt = 0; plan->e_argv[cnt]; ++cnt)
638			if (plan->e_len[cnt])
639				brace_subst(plan->e_orig[cnt],
640				    &plan->e_argv[cnt], file,
641				    plan->e_len[cnt]);
642	}
643
644doexec:	if ((plan->flags & F_NEEDOK) && !queryuser(plan->e_argv))
645		return 0;
646
647	/* make sure find output is interspersed correctly with subprocesses */
648	fflush(stdout);
649	fflush(stderr);
650
651	switch (pid = fork()) {
652	case -1:
653		err(1, "fork");
654		/* NOTREACHED */
655	case 0:
656		/* change dir back from where we started */
657		if (!(plan->flags & F_EXECDIR) &&
658		    !(ftsoptions & FTS_NOCHDIR) && fchdir(dotfd)) {
659			warn("chdir");
660			_exit(1);
661		}
662		execvp(plan->e_argv[0], plan->e_argv);
663		warn("%s", plan->e_argv[0]);
664		_exit(1);
665	}
666	if (plan->flags & F_EXECPLUS) {
667		while (--plan->e_ppos >= plan->e_pbnum)
668			free(plan->e_argv[plan->e_ppos]);
669		plan->e_ppos = plan->e_pbnum;
670		plan->e_psize = plan->e_pbsize;
671	}
672	pid = waitpid(pid, &status, 0);
673	return (pid != -1 && WIFEXITED(status) && !WEXITSTATUS(status));
674}
675
676/*
677 * c_exec, c_execdir, c_ok --
678 *	build three parallel arrays, one with pointers to the strings passed
679 *	on the command line, one with (possibly duplicated) pointers to the
680 *	argv array, and one with integer values that are lengths of the
681 *	strings, but also flags meaning that the string has to be massaged.
682 */
683PLAN *
684c_exec(OPTION *option, char ***argvp)
685{
686	PLAN *new;			/* node returned */
687	long argmax;
688	int cnt, i;
689	char **argv, **ap, **ep, *p;
690
691	/* This would defeat -execdir's intended security. */
692	if (option->flags & F_EXECDIR && ftsoptions & FTS_NOCHDIR)
693		errx(1, "%s: forbidden when the current directory cannot be opened",
694		    "-execdir");
695
696	/* XXX - was in c_execdir, but seems unnecessary!?
697	ftsoptions &= ~FTS_NOSTAT;
698	*/
699	isoutput = 1;
700
701	/* XXX - this is a change from the previous coding */
702	new = palloc(option);
703
704	for (ap = argv = *argvp;; ++ap) {
705		if (!*ap)
706			errx(1,
707			    "%s: no terminating \";\" or \"+\"", option->name);
708		if (**ap == ';')
709			break;
710		if (**ap == '+' && ap != argv && strcmp(*(ap - 1), "{}") == 0) {
711			new->flags |= F_EXECPLUS;
712			break;
713		}
714	}
715
716	if (ap == argv)
717		errx(1, "%s: no command specified", option->name);
718
719	cnt = ap - *argvp + 1;
720	if (new->flags & F_EXECPLUS) {
721		new->e_ppos = new->e_pbnum = cnt - 2;
722		if ((argmax = sysconf(_SC_ARG_MAX)) == -1) {
723			warn("sysconf(_SC_ARG_MAX)");
724			argmax = _POSIX_ARG_MAX;
725		}
726		argmax -= 1024;
727		for (ep = environ; *ep != NULL; ep++)
728			argmax -= strlen(*ep) + 1 + sizeof(*ep);
729		argmax -= 1 + sizeof(*ep);
730		/*
731		 * Ensure that -execdir ... {} + does not mix files
732		 * from different directories in one invocation.
733		 * Files from the same directory should be handled
734		 * in one invocation but there is no code for it.
735		 */
736		new->e_pnummax = new->flags & F_EXECDIR ? 1 : argmax / 16;
737		argmax -= sizeof(char *) * new->e_pnummax;
738		if (argmax <= 0)
739			errx(1, "no space for arguments");
740		new->e_psizemax = argmax;
741		new->e_pbsize = 0;
742		cnt += new->e_pnummax + 1;
743		new->e_next = lastexecplus;
744		lastexecplus = new;
745	}
746	if ((new->e_argv = malloc(cnt * sizeof(char *))) == NULL)
747		err(1, NULL);
748	if ((new->e_orig = malloc(cnt * sizeof(char *))) == NULL)
749		err(1, NULL);
750	if ((new->e_len = malloc(cnt * sizeof(int))) == NULL)
751		err(1, NULL);
752
753	for (argv = *argvp, cnt = 0; argv < ap; ++argv, ++cnt) {
754		new->e_orig[cnt] = *argv;
755		if (new->flags & F_EXECPLUS)
756			new->e_pbsize += strlen(*argv) + 1;
757		for (p = *argv; *p; ++p)
758			if (!(new->flags & F_EXECPLUS) && p[0] == '{' &&
759			    p[1] == '}') {
760				if ((new->e_argv[cnt] =
761				    malloc(MAXPATHLEN)) == NULL)
762					err(1, NULL);
763				new->e_len[cnt] = MAXPATHLEN;
764				break;
765			}
766		if (!*p) {
767			new->e_argv[cnt] = *argv;
768			new->e_len[cnt] = 0;
769		}
770	}
771	if (new->flags & F_EXECPLUS) {
772		new->e_psize = new->e_pbsize;
773		cnt--;
774		for (i = 0; i < new->e_pnummax; i++) {
775			new->e_argv[cnt] = NULL;
776			new->e_len[cnt] = 0;
777			cnt++;
778		}
779		argv = ap;
780		goto done;
781	}
782	new->e_argv[cnt] = new->e_orig[cnt] = NULL;
783
784done:	*argvp = argv + 1;
785	return new;
786}
787
788/* Finish any pending -exec ... {} + functions. */
789void
790finish_execplus(void)
791{
792	PLAN *p;
793
794	p = lastexecplus;
795	while (p != NULL) {
796		(p->execute)(p, NULL);
797		p = p->e_next;
798	}
799}
800
801int
802f_flags(PLAN *plan, FTSENT *entry)
803{
804	u_long flags;
805
806	flags = entry->fts_statp->st_flags;
807	if (plan->flags & F_ATLEAST)
808		return (flags | plan->fl_flags) == flags &&
809		    !(flags & plan->fl_notflags);
810	else if (plan->flags & F_ANY)
811		return (flags & plan->fl_flags) ||
812		    (flags | plan->fl_notflags) != flags;
813	else
814		return flags == plan->fl_flags &&
815		    !(plan->fl_flags & plan->fl_notflags);
816}
817
818PLAN *
819c_flags(OPTION *option, char ***argvp)
820{
821	char *flags_str;
822	PLAN *new;
823	u_long flags, notflags;
824
825	flags_str = nextarg(option, argvp);
826	ftsoptions &= ~FTS_NOSTAT;
827
828	new = palloc(option);
829
830	if (*flags_str == '-') {
831		new->flags |= F_ATLEAST;
832		flags_str++;
833	} else if (*flags_str == '+') {
834		new->flags |= F_ANY;
835		flags_str++;
836	}
837	if (strtofflags(&flags_str, &flags, &notflags) == 1)
838		errx(1, "%s: %s: illegal flags string", option->name, flags_str);
839
840	new->fl_flags = flags;
841	new->fl_notflags = notflags;
842	return new;
843}
844
845/*
846 * -follow functions --
847 *
848 *	Always true, causes symbolic links to be followed on a global
849 *	basis.
850 */
851PLAN *
852c_follow(OPTION *option, char ***argvp __unused)
853{
854	ftsoptions &= ~FTS_PHYSICAL;
855	ftsoptions |= FTS_LOGICAL;
856
857	return palloc(option);
858}
859
860/*
861 * -fstype functions --
862 *
863 *	True if the file is of a certain type.
864 */
865int
866f_fstype(PLAN *plan, FTSENT *entry)
867{
868	static dev_t curdev;	/* need a guaranteed illegal dev value */
869	static int first = 1;
870	struct statfs sb;
871	static int val_flags;
872	static char fstype[sizeof(sb.f_fstypename)];
873	char *p, save[2] = {0,0};
874
875	if ((plan->flags & F_MTMASK) == F_MTUNKNOWN)
876		return 0;
877
878	/* Only check when we cross mount point. */
879	if (first || curdev != entry->fts_statp->st_dev) {
880		curdev = entry->fts_statp->st_dev;
881
882		/*
883		 * Statfs follows symlinks; find wants the link's filesystem,
884		 * not where it points.
885		 */
886		if (entry->fts_info == FTS_SL ||
887		    entry->fts_info == FTS_SLNONE) {
888			if ((p = strrchr(entry->fts_accpath, '/')) != NULL)
889				++p;
890			else
891				p = entry->fts_accpath;
892			save[0] = p[0];
893			p[0] = '.';
894			save[1] = p[1];
895			p[1] = '\0';
896		} else
897			p = NULL;
898
899		if (statfs(entry->fts_accpath, &sb))
900			err(1, "%s", entry->fts_accpath);
901
902		if (p) {
903			p[0] = save[0];
904			p[1] = save[1];
905		}
906
907		first = 0;
908
909		/*
910		 * Further tests may need both of these values, so
911		 * always copy both of them.
912		 */
913		val_flags = sb.f_flags;
914		strlcpy(fstype, sb.f_fstypename, sizeof(fstype));
915	}
916	switch (plan->flags & F_MTMASK) {
917	case F_MTFLAG:
918		return val_flags & plan->mt_data;
919	case F_MTTYPE:
920		return (strncmp(fstype, plan->c_data, sizeof(fstype)) == 0);
921	default:
922		abort();
923	}
924}
925
926PLAN *
927c_fstype(OPTION *option, char ***argvp)
928{
929	char *fsname;
930	PLAN *new;
931
932	fsname = nextarg(option, argvp);
933	ftsoptions &= ~FTS_NOSTAT;
934
935	new = palloc(option);
936	switch (*fsname) {
937	case 'l':
938		if (!strcmp(fsname, "local")) {
939			new->flags |= F_MTFLAG;
940			new->mt_data = MNT_LOCAL;
941			return new;
942		}
943		break;
944	case 'r':
945		if (!strcmp(fsname, "rdonly")) {
946			new->flags |= F_MTFLAG;
947			new->mt_data = MNT_RDONLY;
948			return new;
949		}
950		break;
951	}
952
953	new->flags |= F_MTTYPE;
954	new->c_data = fsname;
955	return new;
956}
957
958/*
959 * -group gname functions --
960 *
961 *	True if the file belongs to the group gname.  If gname is numeric and
962 *	an equivalent of the getgrnam() function does not return a valid group
963 *	name, gname is taken as a group ID.
964 */
965int
966f_group(PLAN *plan, FTSENT *entry)
967{
968	COMPARE(entry->fts_statp->st_gid, plan->g_data);
969}
970
971PLAN *
972c_group(OPTION *option, char ***argvp)
973{
974	char *gname;
975	PLAN *new;
976	struct group *g;
977	gid_t gid;
978
979	gname = nextarg(option, argvp);
980	ftsoptions &= ~FTS_NOSTAT;
981
982	new = palloc(option);
983	g = getgrnam(gname);
984	if (g == NULL) {
985		char* cp = gname;
986		if (gname[0] == '-' || gname[0] == '+')
987			gname++;
988		gid = atoi(gname);
989		if (gid == 0 && gname[0] != '0')
990			errx(1, "%s: %s: no such group", option->name, gname);
991		gid = find_parsenum(new, option->name, cp, NULL);
992	} else
993		gid = g->gr_gid;
994
995	new->g_data = gid;
996	return new;
997}
998
999/*
1000 * -ignore_readdir_race functions --
1001 *
1002 *	Always true. Ignore errors which occur if a file or a directory
1003 *	in a starting point gets deleted between reading the name and calling
1004 *	stat on it while find is traversing the starting point.
1005 */
1006
1007PLAN *
1008c_ignore_readdir_race(OPTION *option, char ***argvp __unused)
1009{
1010	if (strcmp(option->name, "-ignore_readdir_race") == 0)
1011		ignore_readdir_race = 1;
1012	else
1013		ignore_readdir_race = 0;
1014
1015	return palloc(option);
1016}
1017
1018/*
1019 * -inum n functions --
1020 *
1021 *	True if the file has inode # n.
1022 */
1023int
1024f_inum(PLAN *plan, FTSENT *entry)
1025{
1026	COMPARE(entry->fts_statp->st_ino, plan->i_data);
1027}
1028
1029PLAN *
1030c_inum(OPTION *option, char ***argvp)
1031{
1032	char *inum_str;
1033	PLAN *new;
1034
1035	inum_str = nextarg(option, argvp);
1036	ftsoptions &= ~FTS_NOSTAT;
1037
1038	new = palloc(option);
1039	new->i_data = find_parsenum(new, option->name, inum_str, NULL);
1040	return new;
1041}
1042
1043/*
1044 * -samefile FN
1045 *
1046 *	True if the file has the same inode (eg hard link) FN
1047 */
1048
1049/* f_samefile is just f_inum */
1050PLAN *
1051c_samefile(OPTION *option, char ***argvp)
1052{
1053	char *fn;
1054	PLAN *new;
1055	struct stat sb;
1056
1057	fn = nextarg(option, argvp);
1058	ftsoptions &= ~FTS_NOSTAT;
1059
1060	new = palloc(option);
1061	if (stat(fn, &sb))
1062		err(1, "%s", fn);
1063	new->i_data = sb.st_ino;
1064	return new;
1065}
1066
1067/*
1068 * -links n functions --
1069 *
1070 *	True if the file has n links.
1071 */
1072int
1073f_links(PLAN *plan, FTSENT *entry)
1074{
1075	COMPARE(entry->fts_statp->st_nlink, plan->l_data);
1076}
1077
1078PLAN *
1079c_links(OPTION *option, char ***argvp)
1080{
1081	char *nlinks;
1082	PLAN *new;
1083
1084	nlinks = nextarg(option, argvp);
1085	ftsoptions &= ~FTS_NOSTAT;
1086
1087	new = palloc(option);
1088	new->l_data = (nlink_t)find_parsenum(new, option->name, nlinks, NULL);
1089	return new;
1090}
1091
1092/*
1093 * -ls functions --
1094 *
1095 *	Always true - prints the current entry to stdout in "ls" format.
1096 */
1097int
1098f_ls(PLAN *plan __unused, FTSENT *entry)
1099{
1100	printlong(entry->fts_path, entry->fts_accpath, entry->fts_statp);
1101	return 1;
1102}
1103
1104PLAN *
1105c_ls(OPTION *option, char ***argvp __unused)
1106{
1107	ftsoptions &= ~FTS_NOSTAT;
1108	isoutput = 1;
1109
1110	return palloc(option);
1111}
1112
1113/*
1114 * -name functions --
1115 *
1116 *	True if the basename of the filename being examined
1117 *	matches pattern using Pattern Matching Notation S3.14
1118 */
1119int
1120f_name(PLAN *plan, FTSENT *entry)
1121{
1122	char fn[PATH_MAX];
1123	const char *name;
1124	ssize_t len;
1125
1126	if (plan->flags & F_LINK) {
1127		/*
1128		 * The below test both avoids obviously useless readlink()
1129		 * calls and ensures that symlinks with existent target do
1130		 * not match if symlinks are being followed.
1131		 * Assumption: fts will stat all symlinks that are to be
1132		 * followed and will return the stat information.
1133		 */
1134		if (entry->fts_info != FTS_NSOK && entry->fts_info != FTS_SL &&
1135		    entry->fts_info != FTS_SLNONE)
1136			return 0;
1137		len = readlink(entry->fts_accpath, fn, sizeof(fn) - 1);
1138		if (len == -1)
1139			return 0;
1140		fn[len] = '\0';
1141		name = fn;
1142	} else
1143		name = entry->fts_name;
1144	return !fnmatch(plan->c_data, name,
1145	    plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
1146}
1147
1148PLAN *
1149c_name(OPTION *option, char ***argvp)
1150{
1151	char *pattern;
1152	PLAN *new;
1153
1154	pattern = nextarg(option, argvp);
1155	new = palloc(option);
1156	new->c_data = pattern;
1157	return new;
1158}
1159
1160/*
1161 * -newer file functions --
1162 *
1163 *	True if the current file has been modified more recently
1164 *	then the modification time of the file named by the pathname
1165 *	file.
1166 */
1167int
1168f_newer(PLAN *plan, FTSENT *entry)
1169{
1170	struct timespec ft;
1171
1172	if (plan->flags & F_TIME_C)
1173		ft = entry->fts_statp->st_ctim;
1174	else if (plan->flags & F_TIME_A)
1175		ft = entry->fts_statp->st_atim;
1176	else if (plan->flags & F_TIME_B)
1177		ft = entry->fts_statp->st_birthtim;
1178	else
1179		ft = entry->fts_statp->st_mtim;
1180	return (ft.tv_sec > plan->t_data.tv_sec ||
1181	    (ft.tv_sec == plan->t_data.tv_sec &&
1182	    ft.tv_nsec > plan->t_data.tv_nsec));
1183}
1184
1185PLAN *
1186c_newer(OPTION *option, char ***argvp)
1187{
1188	char *fn_or_tspec;
1189	PLAN *new;
1190	struct stat sb;
1191
1192	fn_or_tspec = nextarg(option, argvp);
1193	ftsoptions &= ~FTS_NOSTAT;
1194
1195	new = palloc(option);
1196	/* compare against what */
1197	if (option->flags & F_TIME2_T) {
1198		new->t_data.tv_sec = get_date(fn_or_tspec);
1199		if (new->t_data.tv_sec == (time_t) -1)
1200			errx(1, "Can't parse date/time: %s", fn_or_tspec);
1201		/* Use the seconds only in the comparison. */
1202		new->t_data.tv_nsec = 999999999;
1203	} else {
1204		if (stat(fn_or_tspec, &sb))
1205			err(1, "%s", fn_or_tspec);
1206		if (option->flags & F_TIME2_C)
1207			new->t_data = sb.st_ctim;
1208		else if (option->flags & F_TIME2_A)
1209			new->t_data = sb.st_atim;
1210		else if (option->flags & F_TIME2_B)
1211			new->t_data = sb.st_birthtim;
1212		else
1213			new->t_data = sb.st_mtim;
1214	}
1215	return new;
1216}
1217
1218/*
1219 * -nogroup functions --
1220 *
1221 *	True if file belongs to a user ID for which the equivalent
1222 *	of the getgrnam() 9.2.1 [POSIX.1] function returns NULL.
1223 */
1224int
1225f_nogroup(PLAN *plan __unused, FTSENT *entry)
1226{
1227	return group_from_gid(entry->fts_statp->st_gid, 1) == NULL;
1228}
1229
1230PLAN *
1231c_nogroup(OPTION *option, char ***argvp __unused)
1232{
1233	ftsoptions &= ~FTS_NOSTAT;
1234
1235	return palloc(option);
1236}
1237
1238/*
1239 * -nouser functions --
1240 *
1241 *	True if file belongs to a user ID for which the equivalent
1242 *	of the getpwuid() 9.2.2 [POSIX.1] function returns NULL.
1243 */
1244int
1245f_nouser(PLAN *plan __unused, FTSENT *entry)
1246{
1247	return user_from_uid(entry->fts_statp->st_uid, 1) == NULL;
1248}
1249
1250PLAN *
1251c_nouser(OPTION *option, char ***argvp __unused)
1252{
1253	ftsoptions &= ~FTS_NOSTAT;
1254
1255	return palloc(option);
1256}
1257
1258/*
1259 * -path functions --
1260 *
1261 *	True if the path of the filename being examined
1262 *	matches pattern using Pattern Matching Notation S3.14
1263 */
1264int
1265f_path(PLAN *plan, FTSENT *entry)
1266{
1267	return !fnmatch(plan->c_data, entry->fts_path,
1268	    plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
1269}
1270
1271/* c_path is the same as c_name */
1272
1273/*
1274 * -perm functions --
1275 *
1276 *	The mode argument is used to represent file mode bits.  If it starts
1277 *	with a leading digit, it's treated as an octal mode, otherwise as a
1278 *	symbolic mode.
1279 */
1280int
1281f_perm(PLAN *plan, FTSENT *entry)
1282{
1283	mode_t mode;
1284
1285	mode = entry->fts_statp->st_mode &
1286	    (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO);
1287	if (plan->flags & F_ATLEAST)
1288		return (plan->m_data | mode) == mode;
1289	else if (plan->flags & F_ANY)
1290		return (mode & plan->m_data);
1291	else
1292		return mode == plan->m_data;
1293	/* NOTREACHED */
1294}
1295
1296PLAN *
1297c_perm(OPTION *option, char ***argvp)
1298{
1299	char *perm;
1300	PLAN *new;
1301	mode_t *set;
1302
1303	perm = nextarg(option, argvp);
1304	ftsoptions &= ~FTS_NOSTAT;
1305
1306	new = palloc(option);
1307
1308	if (*perm == '-') {
1309		new->flags |= F_ATLEAST;
1310		++perm;
1311	} else if (*perm == '+') {
1312		new->flags |= F_ANY;
1313		++perm;
1314	}
1315
1316	if ((set = setmode(perm)) == NULL)
1317		errx(1, "%s: %s: illegal mode string", option->name, perm);
1318
1319	new->m_data = getmode(set, 0);
1320	free(set);
1321	return new;
1322}
1323
1324/*
1325 * -print functions --
1326 *
1327 *	Always true, causes the current pathname to be written to
1328 *	standard output.
1329 */
1330int
1331f_print(PLAN *plan __unused, FTSENT *entry)
1332{
1333	(void)puts(entry->fts_path);
1334	return 1;
1335}
1336
1337PLAN *
1338c_print(OPTION *option, char ***argvp __unused)
1339{
1340	isoutput = 1;
1341
1342	return palloc(option);
1343}
1344
1345/*
1346 * -print0 functions --
1347 *
1348 *	Always true, causes the current pathname to be written to
1349 *	standard output followed by a NUL character
1350 */
1351int
1352f_print0(PLAN *plan __unused, FTSENT *entry)
1353{
1354	fputs(entry->fts_path, stdout);
1355	fputc('\0', stdout);
1356	return 1;
1357}
1358
1359/* c_print0 is the same as c_print */
1360
1361/*
1362 * -prune functions --
1363 *
1364 *	Prune a portion of the hierarchy.
1365 */
1366int
1367f_prune(PLAN *plan __unused, FTSENT *entry)
1368{
1369	if (fts_set(tree, entry, FTS_SKIP))
1370		err(1, "%s", entry->fts_path);
1371	return 1;
1372}
1373
1374/* c_prune == c_simple */
1375
1376/*
1377 * -regex functions --
1378 *
1379 *	True if the whole path of the file matches pattern using
1380 *	regular expression.
1381 */
1382int
1383f_regex(PLAN *plan, FTSENT *entry)
1384{
1385	char *str;
1386	int len;
1387	regex_t *pre;
1388	regmatch_t pmatch;
1389	int errcode;
1390	char errbuf[LINE_MAX];
1391	int matched;
1392
1393	pre = plan->re_data;
1394	str = entry->fts_path;
1395	len = strlen(str);
1396	matched = 0;
1397
1398	pmatch.rm_so = 0;
1399	pmatch.rm_eo = len;
1400
1401	errcode = regexec(pre, str, 1, &pmatch, REG_STARTEND);
1402
1403	if (errcode != 0 && errcode != REG_NOMATCH) {
1404		regerror(errcode, pre, errbuf, sizeof errbuf);
1405		errx(1, "%s: %s",
1406		     plan->flags & F_IGNCASE ? "-iregex" : "-regex", errbuf);
1407	}
1408
1409	if (errcode == 0 && pmatch.rm_so == 0 && pmatch.rm_eo == len)
1410		matched = 1;
1411
1412	return matched;
1413}
1414
1415PLAN *
1416c_regex(OPTION *option, char ***argvp)
1417{
1418	PLAN *new;
1419	char *pattern;
1420	regex_t *pre;
1421	int errcode;
1422	char errbuf[LINE_MAX];
1423
1424	if ((pre = malloc(sizeof(regex_t))) == NULL)
1425		err(1, NULL);
1426
1427	pattern = nextarg(option, argvp);
1428
1429	if ((errcode = regcomp(pre, pattern,
1430	    regexp_flags | (option->flags & F_IGNCASE ? REG_ICASE : 0))) != 0) {
1431		regerror(errcode, pre, errbuf, sizeof errbuf);
1432		errx(1, "%s: %s: %s",
1433		     option->flags & F_IGNCASE ? "-iregex" : "-regex",
1434		     pattern, errbuf);
1435	}
1436
1437	new = palloc(option);
1438	new->re_data = pre;
1439
1440	return new;
1441}
1442
1443/* c_simple covers c_prune, c_openparen, c_closeparen, c_not, c_or, c_true, c_false */
1444
1445PLAN *
1446c_simple(OPTION *option, char ***argvp __unused)
1447{
1448	return palloc(option);
1449}
1450
1451/*
1452 * -size n[c] functions --
1453 *
1454 *	True if the file size in bytes, divided by an implementation defined
1455 *	value and rounded up to the next integer, is n.  If n is followed by
1456 *      one of c k M G T P, the size is in bytes, kilobytes,
1457 *      megabytes, gigabytes, terabytes or petabytes respectively.
1458 */
1459#define	FIND_SIZE	512
1460static int divsize = 1;
1461
1462int
1463f_size(PLAN *plan, FTSENT *entry)
1464{
1465	off_t size;
1466
1467	size = divsize ? (entry->fts_statp->st_size + FIND_SIZE - 1) /
1468	    FIND_SIZE : entry->fts_statp->st_size;
1469	COMPARE(size, plan->o_data);
1470}
1471
1472PLAN *
1473c_size(OPTION *option, char ***argvp)
1474{
1475	char *size_str;
1476	PLAN *new;
1477	char endch;
1478	off_t scale;
1479
1480	size_str = nextarg(option, argvp);
1481	ftsoptions &= ~FTS_NOSTAT;
1482
1483	new = palloc(option);
1484	endch = 'c';
1485	new->o_data = find_parsenum(new, option->name, size_str, &endch);
1486	if (endch != '\0') {
1487		divsize = 0;
1488
1489		switch (endch) {
1490		case 'c':                       /* characters */
1491			scale = 0x1LL;
1492			break;
1493		case 'k':                       /* kilobytes 1<<10 */
1494			scale = 0x400LL;
1495			break;
1496		case 'M':                       /* megabytes 1<<20 */
1497			scale = 0x100000LL;
1498			break;
1499		case 'G':                       /* gigabytes 1<<30 */
1500			scale = 0x40000000LL;
1501			break;
1502		case 'T':                       /* terabytes 1<<40 */
1503			scale = 0x1000000000LL;
1504			break;
1505		case 'P':                       /* petabytes 1<<50 */
1506			scale = 0x4000000000000LL;
1507			break;
1508		default:
1509			errx(1, "%s: %s: illegal trailing character",
1510				option->name, size_str);
1511			break;
1512		}
1513		if (new->o_data > QUAD_MAX / scale)
1514			errx(1, "%s: %s: value too large",
1515				option->name, size_str);
1516		new->o_data *= scale;
1517	}
1518	return new;
1519}
1520
1521/*
1522 * -sparse functions --
1523 *
1524 *      Check if a file is sparse by finding if it occupies fewer blocks
1525 *      than we expect based on its size.
1526 */
1527int
1528f_sparse(PLAN *plan __unused, FTSENT *entry)
1529{
1530	off_t expected_blocks;
1531
1532	expected_blocks = (entry->fts_statp->st_size + 511) / 512;
1533	return entry->fts_statp->st_blocks < expected_blocks;
1534}
1535
1536PLAN *
1537c_sparse(OPTION *option, char ***argvp __unused)
1538{
1539	ftsoptions &= ~FTS_NOSTAT;
1540
1541	return palloc(option);
1542}
1543
1544/*
1545 * -type c functions --
1546 *
1547 *	True if the type of the file is c, where c is b, c, d, p, f or w
1548 *	for block special file, character special file, directory, FIFO,
1549 *	regular file or whiteout respectively.
1550 */
1551int
1552f_type(PLAN *plan, FTSENT *entry)
1553{
1554	return (entry->fts_statp->st_mode & S_IFMT) == plan->m_data;
1555}
1556
1557PLAN *
1558c_type(OPTION *option, char ***argvp)
1559{
1560	char *typestring;
1561	PLAN *new;
1562	mode_t  mask;
1563
1564	typestring = nextarg(option, argvp);
1565	ftsoptions &= ~FTS_NOSTAT;
1566
1567	switch (typestring[0]) {
1568	case 'b':
1569		mask = S_IFBLK;
1570		break;
1571	case 'c':
1572		mask = S_IFCHR;
1573		break;
1574	case 'd':
1575		mask = S_IFDIR;
1576		break;
1577	case 'f':
1578		mask = S_IFREG;
1579		break;
1580	case 'l':
1581		mask = S_IFLNK;
1582		break;
1583	case 'p':
1584		mask = S_IFIFO;
1585		break;
1586	case 's':
1587		mask = S_IFSOCK;
1588		break;
1589#ifdef FTS_WHITEOUT
1590	case 'w':
1591		mask = S_IFWHT;
1592		ftsoptions |= FTS_WHITEOUT;
1593		break;
1594#endif /* FTS_WHITEOUT */
1595	default:
1596		errx(1, "%s: %s: unknown type", option->name, typestring);
1597	}
1598
1599	new = palloc(option);
1600	new->m_data = mask;
1601	return new;
1602}
1603
1604/*
1605 * -user uname functions --
1606 *
1607 *	True if the file belongs to the user uname.  If uname is numeric and
1608 *	an equivalent of the getpwnam() S9.2.2 [POSIX.1] function does not
1609 *	return a valid user name, uname is taken as a user ID.
1610 */
1611int
1612f_user(PLAN *plan, FTSENT *entry)
1613{
1614	COMPARE(entry->fts_statp->st_uid, plan->u_data);
1615}
1616
1617PLAN *
1618c_user(OPTION *option, char ***argvp)
1619{
1620	char *username;
1621	PLAN *new;
1622	struct passwd *p;
1623	uid_t uid;
1624
1625	username = nextarg(option, argvp);
1626	ftsoptions &= ~FTS_NOSTAT;
1627
1628	new = palloc(option);
1629	p = getpwnam(username);
1630	if (p == NULL) {
1631		char* cp = username;
1632		if( username[0] == '-' || username[0] == '+' )
1633			username++;
1634		uid = atoi(username);
1635		if (uid == 0 && username[0] != '0')
1636			errx(1, "%s: %s: no such user", option->name, username);
1637		uid = find_parsenum(new, option->name, cp, NULL);
1638	} else
1639		uid = p->pw_uid;
1640
1641	new->u_data = uid;
1642	return new;
1643}
1644
1645/*
1646 * -xdev functions --
1647 *
1648 *	Always true, causes find not to descend past directories that have a
1649 *	different device ID (st_dev, see stat() S5.6.2 [POSIX.1])
1650 */
1651PLAN *
1652c_xdev(OPTION *option, char ***argvp __unused)
1653{
1654	ftsoptions |= FTS_XDEV;
1655
1656	return palloc(option);
1657}
1658
1659/*
1660 * ( expression ) functions --
1661 *
1662 *	True if expression is true.
1663 */
1664int
1665f_expr(PLAN *plan, FTSENT *entry)
1666{
1667	PLAN *p;
1668	int state = 0;
1669
1670	for (p = plan->p_data[0];
1671	    p && (state = (p->execute)(p, entry)); p = p->next);
1672	return state;
1673}
1674
1675/*
1676 * f_openparen and f_closeparen nodes are temporary place markers.  They are
1677 * eliminated during phase 2 of find_formplan() --- the '(' node is converted
1678 * to a f_expr node containing the expression and the ')' node is discarded.
1679 * The functions themselves are only used as constants.
1680 */
1681
1682int
1683f_openparen(PLAN *plan __unused, FTSENT *entry __unused)
1684{
1685	abort();
1686}
1687
1688int
1689f_closeparen(PLAN *plan __unused, FTSENT *entry __unused)
1690{
1691	abort();
1692}
1693
1694/* c_openparen == c_simple */
1695/* c_closeparen == c_simple */
1696
1697/*
1698 * AND operator. Since AND is implicit, no node is allocated.
1699 */
1700PLAN *
1701c_and(OPTION *option __unused, char ***argvp __unused)
1702{
1703	return NULL;
1704}
1705
1706/*
1707 * ! expression functions --
1708 *
1709 *	Negation of a primary; the unary NOT operator.
1710 */
1711int
1712f_not(PLAN *plan, FTSENT *entry)
1713{
1714	PLAN *p;
1715	int state = 0;
1716
1717	for (p = plan->p_data[0];
1718	    p && (state = (p->execute)(p, entry)); p = p->next);
1719	return !state;
1720}
1721
1722/* c_not == c_simple */
1723
1724/*
1725 * expression -o expression functions --
1726 *
1727 *	Alternation of primaries; the OR operator.  The second expression is
1728 * not evaluated if the first expression is true.
1729 */
1730int
1731f_or(PLAN *plan, FTSENT *entry)
1732{
1733	PLAN *p;
1734	int state = 0;
1735
1736	for (p = plan->p_data[0];
1737	    p && (state = (p->execute)(p, entry)); p = p->next);
1738
1739	if (state)
1740		return 1;
1741
1742	for (p = plan->p_data[1];
1743	    p && (state = (p->execute)(p, entry)); p = p->next);
1744	return state;
1745}
1746
1747/* c_or == c_simple */
1748
1749/*
1750 * -false
1751 *
1752 *	Always false.
1753 */
1754int
1755f_false(PLAN *plan __unused, FTSENT *entry __unused)
1756{
1757	return 0;
1758}
1759
1760/* c_false == c_simple */
1761
1762/*
1763 * -quit
1764 *
1765 *	Exits the program
1766 */
1767int
1768f_quit(PLAN *plan __unused, FTSENT *entry __unused)
1769{
1770	finish_execplus();
1771	exit(0);
1772}
1773
1774/* c_quit == c_simple */
1775