function.c revision 330897
1/*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1990, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Cimarron D. Taylor of the University of California, Berkeley.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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 * 4. 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.
21 *
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
32 * SUCH DAMAGE.
33 */
34
35#ifndef lint
36#if 0
37static const char sccsid[] = "@(#)function.c	8.10 (Berkeley) 5/4/95";
38#endif
39#endif /* not lint */
40
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD: stable/11/usr.bin/find/function.c 330897 2018-03-14 03:19:51Z eadler $");
43
44#include <sys/param.h>
45#include <sys/ucred.h>
46#include <sys/stat.h>
47#include <sys/types.h>
48#include <sys/acl.h>
49#include <sys/wait.h>
50#include <sys/mount.h>
51
52#include <dirent.h>
53#include <err.h>
54#include <errno.h>
55#include <fnmatch.h>
56#include <fts.h>
57#include <grp.h>
58#include <limits.h>
59#include <pwd.h>
60#include <regex.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <unistd.h>
65#include <ctype.h>
66
67#include "find.h"
68
69static PLAN *palloc(OPTION *);
70static long long find_parsenum(PLAN *, const char *, char *, char *);
71static long long find_parsetime(PLAN *, const char *, char *);
72static char *nextarg(OPTION *, char ***);
73
74extern char **environ;
75
76static PLAN *lastexecplus = NULL;
77
78#define	COMPARE(a, b) do {						\
79	switch (plan->flags & F_ELG_MASK) {				\
80	case F_EQUAL:							\
81		return (a == b);					\
82	case F_LESSTHAN:						\
83		return (a < b);						\
84	case F_GREATER:							\
85		return (a > b);						\
86	default:							\
87		abort();						\
88	}								\
89} while(0)
90
91static PLAN *
92palloc(OPTION *option)
93{
94	PLAN *new;
95
96	if ((new = malloc(sizeof(PLAN))) == NULL)
97		err(1, NULL);
98	new->execute = option->execute;
99	new->flags = option->flags;
100	new->next = NULL;
101	return new;
102}
103
104/*
105 * find_parsenum --
106 *	Parse a string of the form [+-]# and return the value.
107 */
108static long long
109find_parsenum(PLAN *plan, const char *option, char *vp, char *endch)
110{
111	long long value;
112	char *endchar, *str;	/* Pointer to character ending conversion. */
113
114	/* Determine comparison from leading + or -. */
115	str = vp;
116	switch (*str) {
117	case '+':
118		++str;
119		plan->flags |= F_GREATER;
120		break;
121	case '-':
122		++str;
123		plan->flags |= F_LESSTHAN;
124		break;
125	default:
126		plan->flags |= F_EQUAL;
127		break;
128	}
129
130	/*
131	 * Convert the string with strtoq().  Note, if strtoq() returns zero
132	 * and endchar points to the beginning of the string we know we have
133	 * a syntax error.
134	 */
135	value = strtoq(str, &endchar, 10);
136	if (value == 0 && endchar == str)
137		errx(1, "%s: %s: illegal numeric value", option, vp);
138	if (endchar[0] && endch == NULL)
139		errx(1, "%s: %s: illegal trailing character", option, vp);
140	if (endch)
141		*endch = endchar[0];
142	return value;
143}
144
145/*
146 * find_parsetime --
147 *	Parse a string of the form [+-]([0-9]+[smhdw]?)+ and return the value.
148 */
149static long long
150find_parsetime(PLAN *plan, const char *option, char *vp)
151{
152	long long secs, value;
153	char *str, *unit;	/* Pointer to character ending conversion. */
154
155	/* Determine comparison from leading + or -. */
156	str = vp;
157	switch (*str) {
158	case '+':
159		++str;
160		plan->flags |= F_GREATER;
161		break;
162	case '-':
163		++str;
164		plan->flags |= F_LESSTHAN;
165		break;
166	default:
167		plan->flags |= F_EQUAL;
168		break;
169	}
170
171	value = strtoq(str, &unit, 10);
172	if (value == 0 && unit == str) {
173		errx(1, "%s: %s: illegal time value", option, vp);
174		/* NOTREACHED */
175	}
176	if (*unit == '\0')
177		return value;
178
179	/* Units syntax. */
180	secs = 0;
181	for (;;) {
182		switch(*unit) {
183		case 's':	/* seconds */
184			secs += value;
185			break;
186		case 'm':	/* minutes */
187			secs += value * 60;
188			break;
189		case 'h':	/* hours */
190			secs += value * 3600;
191			break;
192		case 'd':	/* days */
193			secs += value * 86400;
194			break;
195		case 'w':	/* weeks */
196			secs += value * 604800;
197			break;
198		default:
199			errx(1, "%s: %s: bad unit '%c'", option, vp, *unit);
200			/* NOTREACHED */
201		}
202		str = unit + 1;
203		if (*str == '\0')	/* EOS */
204			break;
205		value = strtoq(str, &unit, 10);
206		if (value == 0 && unit == str) {
207			errx(1, "%s: %s: illegal time value", option, vp);
208			/* NOTREACHED */
209		}
210		if (*unit == '\0') {
211			errx(1, "%s: %s: missing trailing unit", option, vp);
212			/* NOTREACHED */
213		}
214	}
215	plan->flags |= F_EXACTTIME;
216	return secs;
217}
218
219/*
220 * nextarg --
221 *	Check that another argument still exists, return a pointer to it,
222 *	and increment the argument vector pointer.
223 */
224static char *
225nextarg(OPTION *option, char ***argvp)
226{
227	char *arg;
228
229	if ((arg = **argvp) == NULL)
230		errx(1, "%s: requires additional arguments", option->name);
231	(*argvp)++;
232	return arg;
233} /* nextarg() */
234
235/*
236 * The value of n for the inode times (atime, birthtime, ctime, mtime) is a
237 * range, i.e. n matches from (n - 1) to n 24 hour periods.  This interacts
238 * with -n, such that "-mtime -1" would be less than 0 days, which isn't what
239 * the user wanted.  Correct so that -1 is "less than 1".
240 */
241#define	TIME_CORRECT(p) \
242	if (((p)->flags & F_ELG_MASK) == F_LESSTHAN) \
243		++((p)->t_data.tv_sec);
244
245/*
246 * -[acm]min n functions --
247 *
248 *    True if the difference between the
249 *		file access time (-amin)
250 *		file birth time (-Bmin)
251 *		last change of file status information (-cmin)
252 *		file modification time (-mmin)
253 *    and the current time is n min periods.
254 */
255int
256f_Xmin(PLAN *plan, FTSENT *entry)
257{
258	if (plan->flags & F_TIME_C) {
259		COMPARE((now - entry->fts_statp->st_ctime +
260		    60 - 1) / 60, plan->t_data.tv_sec);
261	} else if (plan->flags & F_TIME_A) {
262		COMPARE((now - entry->fts_statp->st_atime +
263		    60 - 1) / 60, plan->t_data.tv_sec);
264	} else if (plan->flags & F_TIME_B) {
265		COMPARE((now - entry->fts_statp->st_birthtime +
266		    60 - 1) / 60, plan->t_data.tv_sec);
267	} else {
268		COMPARE((now - entry->fts_statp->st_mtime +
269		    60 - 1) / 60, plan->t_data.tv_sec);
270	}
271}
272
273PLAN *
274c_Xmin(OPTION *option, char ***argvp)
275{
276	char *nmins;
277	PLAN *new;
278
279	nmins = nextarg(option, argvp);
280	ftsoptions &= ~FTS_NOSTAT;
281
282	new = palloc(option);
283	new->t_data.tv_sec = find_parsenum(new, option->name, nmins, NULL);
284	new->t_data.tv_nsec = 0;
285	TIME_CORRECT(new);
286	return new;
287}
288
289/*
290 * -[acm]time n functions --
291 *
292 *	True if the difference between the
293 *		file access time (-atime)
294 *		file birth time (-Btime)
295 *		last change of file status information (-ctime)
296 *		file modification time (-mtime)
297 *	and the current time is n 24 hour periods.
298 */
299
300int
301f_Xtime(PLAN *plan, FTSENT *entry)
302{
303	time_t xtime;
304
305	if (plan->flags & F_TIME_A)
306		xtime = entry->fts_statp->st_atime;
307	else if (plan->flags & F_TIME_B)
308		xtime = entry->fts_statp->st_birthtime;
309	else if (plan->flags & F_TIME_C)
310		xtime = entry->fts_statp->st_ctime;
311	else
312		xtime = entry->fts_statp->st_mtime;
313
314	if (plan->flags & F_EXACTTIME)
315		COMPARE(now - xtime, plan->t_data.tv_sec);
316	else
317		COMPARE((now - xtime + 86400 - 1) / 86400, plan->t_data.tv_sec);
318}
319
320PLAN *
321c_Xtime(OPTION *option, char ***argvp)
322{
323	char *value;
324	PLAN *new;
325
326	value = nextarg(option, argvp);
327	ftsoptions &= ~FTS_NOSTAT;
328
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))
333		TIME_CORRECT(new);
334	return new;
335}
336
337/*
338 * -maxdepth/-mindepth n functions --
339 *
340 *        Does the same as -prune if the level of the current file is
341 *        greater/less than the specified maximum/minimum depth.
342 *
343 *        Note that -maxdepth and -mindepth are handled specially in
344 *        find_execute() so their f_* functions are set to f_always_true().
345 */
346PLAN *
347c_mXXdepth(OPTION *option, char ***argvp)
348{
349	char *dstr;
350	PLAN *new;
351
352	dstr = nextarg(option, argvp);
353	if (dstr[0] == '-')
354		/* all other errors handled by find_parsenum() */
355		errx(1, "%s: %s: value must be positive", option->name, dstr);
356
357	new = palloc(option);
358	if (option->flags & F_MAXDEPTH)
359		maxdepth = find_parsenum(new, option->name, dstr, NULL);
360	else
361		mindepth = find_parsenum(new, option->name, dstr, NULL);
362	return new;
363}
364
365/*
366 * -acl function --
367 *
368 *	Show files with EXTENDED ACL attributes.
369 */
370int
371f_acl(PLAN *plan __unused, FTSENT *entry)
372{
373	acl_t facl;
374	acl_type_t acl_type;
375	int acl_supported = 0, ret, trivial;
376
377	if (S_ISLNK(entry->fts_statp->st_mode))
378		return 0;
379	ret = pathconf(entry->fts_accpath, _PC_ACL_NFS4);
380	if (ret > 0) {
381		acl_supported = 1;
382		acl_type = ACL_TYPE_NFS4;
383	} else if (ret < 0 && errno != EINVAL) {
384		warn("%s", entry->fts_accpath);
385		return (0);
386	}
387	if (acl_supported == 0) {
388		ret = pathconf(entry->fts_accpath, _PC_ACL_EXTENDED);
389		if (ret > 0) {
390			acl_supported = 1;
391			acl_type = ACL_TYPE_ACCESS;
392		} else if (ret < 0 && errno != EINVAL) {
393			warn("%s", entry->fts_accpath);
394			return (0);
395		}
396	}
397	if (acl_supported == 0)
398		return (0);
399
400	facl = acl_get_file(entry->fts_accpath, acl_type);
401	if (facl == NULL) {
402		warn("%s", entry->fts_accpath);
403		return (0);
404	}
405	ret = acl_is_trivial_np(facl, &trivial);
406	acl_free(facl);
407	if (ret) {
408		warn("%s", entry->fts_accpath);
409		return (0);
410	}
411	if (trivial)
412		return (0);
413	return (1);
414}
415
416PLAN *
417c_acl(OPTION *option, char ***argvp __unused)
418{
419	ftsoptions &= ~FTS_NOSTAT;
420	return (palloc(option));
421}
422
423/*
424 * -delete functions --
425 *
426 *	True always.  Makes its best shot and continues on regardless.
427 */
428int
429f_delete(PLAN *plan __unused, FTSENT *entry)
430{
431	/* ignore these from fts */
432	if (strcmp(entry->fts_accpath, ".") == 0 ||
433	    strcmp(entry->fts_accpath, "..") == 0)
434		return 1;
435
436	/* sanity check */
437	if (isdepth == 0 ||			/* depth off */
438	    (ftsoptions & FTS_NOSTAT))		/* not stat()ing */
439		errx(1, "-delete: insecure options got turned on");
440
441	if (!(ftsoptions & FTS_PHYSICAL) ||	/* physical off */
442	    (ftsoptions & FTS_LOGICAL))		/* or finally, logical on */
443		errx(1, "-delete: forbidden when symlinks are followed");
444
445	/* Potentially unsafe - do not accept relative paths whatsoever */
446	if (entry->fts_level > FTS_ROOTLEVEL &&
447	    strchr(entry->fts_accpath, '/') != NULL)
448		errx(1, "-delete: %s: relative path potentially not safe",
449			entry->fts_accpath);
450
451	/* Turn off user immutable bits if running as root */
452	if ((entry->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
453	    !(entry->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
454	    geteuid() == 0)
455		lchflags(entry->fts_accpath,
456		       entry->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
457
458	/* rmdir directories, unlink everything else */
459	if (S_ISDIR(entry->fts_statp->st_mode)) {
460		if (rmdir(entry->fts_accpath) < 0 && errno != ENOTEMPTY)
461			warn("-delete: rmdir(%s)", entry->fts_path);
462	} else {
463		if (unlink(entry->fts_accpath) < 0)
464			warn("-delete: unlink(%s)", entry->fts_path);
465	}
466
467	/* "succeed" */
468	return 1;
469}
470
471PLAN *
472c_delete(OPTION *option, char ***argvp __unused)
473{
474
475	ftsoptions &= ~FTS_NOSTAT;	/* no optimise */
476	isoutput = 1;			/* possible output */
477	isdepth = 1;			/* -depth implied */
478
479	/*
480	 * Try to avoid the confusing error message about relative paths
481	 * being potentially not safe.
482	 */
483	if (ftsoptions & FTS_NOCHDIR)
484		errx(1, "%s: forbidden when the current directory cannot be opened",
485		    "-delete");
486
487	return palloc(option);
488}
489
490
491/*
492 * always_true --
493 *
494 *	Always true, used for -maxdepth, -mindepth, -xdev, -follow, and -true
495 */
496int
497f_always_true(PLAN *plan __unused, FTSENT *entry __unused)
498{
499	return 1;
500}
501
502/*
503 * -depth functions --
504 *
505 *	With argument: True if the file is at level n.
506 *	Without argument: Always true, causes descent of the directory hierarchy
507 *	to be done so that all entries in a directory are acted on before the
508 *	directory itself.
509 */
510int
511f_depth(PLAN *plan, FTSENT *entry)
512{
513	if (plan->flags & F_DEPTH)
514		COMPARE(entry->fts_level, plan->d_data);
515	else
516		return 1;
517}
518
519PLAN *
520c_depth(OPTION *option, char ***argvp)
521{
522	PLAN *new;
523	char *str;
524
525	new = palloc(option);
526
527	str = **argvp;
528	if (str && !(new->flags & F_DEPTH)) {
529		/* skip leading + or - */
530		if (*str == '+' || *str == '-')
531			str++;
532		/* skip sign */
533		if (*str == '+' || *str == '-')
534			str++;
535		if (isdigit(*str))
536			new->flags |= F_DEPTH;
537	}
538
539	if (new->flags & F_DEPTH) {	/* -depth n */
540		char *ndepth;
541
542		ndepth = nextarg(option, argvp);
543		new->d_data = find_parsenum(new, option->name, ndepth, NULL);
544	} else {			/* -d */
545		isdepth = 1;
546	}
547
548	return new;
549}
550
551/*
552 * -empty functions --
553 *
554 *	True if the file or directory is empty
555 */
556int
557f_empty(PLAN *plan __unused, FTSENT *entry)
558{
559	if (S_ISREG(entry->fts_statp->st_mode) &&
560	    entry->fts_statp->st_size == 0)
561		return 1;
562	if (S_ISDIR(entry->fts_statp->st_mode)) {
563		struct dirent *dp;
564		int empty;
565		DIR *dir;
566
567		empty = 1;
568		dir = opendir(entry->fts_accpath);
569		if (dir == NULL)
570			return 0;
571		for (dp = readdir(dir); dp; dp = readdir(dir))
572			if (dp->d_name[0] != '.' ||
573			    (dp->d_name[1] != '\0' &&
574			     (dp->d_name[1] != '.' || dp->d_name[2] != '\0'))) {
575				empty = 0;
576				break;
577			}
578		closedir(dir);
579		return empty;
580	}
581	return 0;
582}
583
584PLAN *
585c_empty(OPTION *option, char ***argvp __unused)
586{
587	ftsoptions &= ~FTS_NOSTAT;
588
589	return palloc(option);
590}
591
592/*
593 * [-exec | -execdir | -ok] utility [arg ... ] ; functions --
594 *
595 *	True if the executed utility returns a zero value as exit status.
596 *	The end of the primary expression is delimited by a semicolon.  If
597 *	"{}" occurs anywhere, it gets replaced by the current pathname,
598 *	or, in the case of -execdir, the current basename (filename
599 *	without leading directory prefix). For -exec and -ok,
600 *	the current directory for the execution of utility is the same as
601 *	the current directory when the find utility was started, whereas
602 *	for -execdir, it is the directory the file resides in.
603 *
604 *	The primary -ok differs from -exec in that it requests affirmation
605 *	of the user before executing the utility.
606 */
607int
608f_exec(PLAN *plan, FTSENT *entry)
609{
610	int cnt;
611	pid_t pid;
612	int status;
613	char *file;
614
615	if (entry == NULL && plan->flags & F_EXECPLUS) {
616		if (plan->e_ppos == plan->e_pbnum)
617			return (1);
618		plan->e_argv[plan->e_ppos] = NULL;
619		goto doexec;
620	}
621
622	/* XXX - if file/dir ends in '/' this will not work -- can it? */
623	if ((plan->flags & F_EXECDIR) && \
624	    (file = strrchr(entry->fts_path, '/')))
625		file++;
626	else
627		file = entry->fts_path;
628
629	if (plan->flags & F_EXECPLUS) {
630		if ((plan->e_argv[plan->e_ppos] = strdup(file)) == NULL)
631			err(1, NULL);
632		plan->e_len[plan->e_ppos] = strlen(file);
633		plan->e_psize += plan->e_len[plan->e_ppos];
634		if (++plan->e_ppos < plan->e_pnummax &&
635		    plan->e_psize < plan->e_psizemax)
636			return (1);
637		plan->e_argv[plan->e_ppos] = NULL;
638	} else {
639		for (cnt = 0; plan->e_argv[cnt]; ++cnt)
640			if (plan->e_len[cnt])
641				brace_subst(plan->e_orig[cnt],
642				    &plan->e_argv[cnt], file,
643				    plan->e_len[cnt]);
644	}
645
646doexec:	if ((plan->flags & F_NEEDOK) && !queryuser(plan->e_argv))
647		return 0;
648
649	/* make sure find output is interspersed correctly with subprocesses */
650	fflush(stdout);
651	fflush(stderr);
652
653	switch (pid = fork()) {
654	case -1:
655		err(1, "fork");
656		/* NOTREACHED */
657	case 0:
658		/* change dir back from where we started */
659		if (!(plan->flags & F_EXECDIR) &&
660		    !(ftsoptions & FTS_NOCHDIR) && fchdir(dotfd)) {
661			warn("chdir");
662			_exit(1);
663		}
664		execvp(plan->e_argv[0], plan->e_argv);
665		warn("%s", plan->e_argv[0]);
666		_exit(1);
667	}
668	if (plan->flags & F_EXECPLUS) {
669		while (--plan->e_ppos >= plan->e_pbnum)
670			free(plan->e_argv[plan->e_ppos]);
671		plan->e_ppos = plan->e_pbnum;
672		plan->e_psize = plan->e_pbsize;
673	}
674	pid = waitpid(pid, &status, 0);
675	if (pid != -1 && WIFEXITED(status) && !WEXITSTATUS(status))
676		return (1);
677	if (plan->flags & F_EXECPLUS) {
678		exitstatus = 1;
679		return (1);
680	}
681	return (0);
682}
683
684/*
685 * c_exec, c_execdir, c_ok --
686 *	build three parallel arrays, one with pointers to the strings passed
687 *	on the command line, one with (possibly duplicated) pointers to the
688 *	argv array, and one with integer values that are lengths of the
689 *	strings, but also flags meaning that the string has to be massaged.
690 */
691PLAN *
692c_exec(OPTION *option, char ***argvp)
693{
694	PLAN *new;			/* node returned */
695	long argmax;
696	int cnt, i;
697	char **argv, **ap, **ep, *p;
698
699	/* This would defeat -execdir's intended security. */
700	if (option->flags & F_EXECDIR && ftsoptions & FTS_NOCHDIR)
701		errx(1, "%s: forbidden when the current directory cannot be opened",
702		    "-execdir");
703
704	/* XXX - was in c_execdir, but seems unnecessary!?
705	ftsoptions &= ~FTS_NOSTAT;
706	*/
707	isoutput = 1;
708
709	/* XXX - this is a change from the previous coding */
710	new = palloc(option);
711
712	for (ap = argv = *argvp;; ++ap) {
713		if (!*ap)
714			errx(1,
715			    "%s: no terminating \";\" or \"+\"", option->name);
716		if (**ap == ';')
717			break;
718		if (**ap == '+' && ap != argv && strcmp(*(ap - 1), "{}") == 0) {
719			new->flags |= F_EXECPLUS;
720			break;
721		}
722	}
723
724	if (ap == argv)
725		errx(1, "%s: no command specified", option->name);
726
727	cnt = ap - *argvp + 1;
728	if (new->flags & F_EXECPLUS) {
729		new->e_ppos = new->e_pbnum = cnt - 2;
730		if ((argmax = sysconf(_SC_ARG_MAX)) == -1) {
731			warn("sysconf(_SC_ARG_MAX)");
732			argmax = _POSIX_ARG_MAX;
733		}
734		argmax -= 1024;
735		for (ep = environ; *ep != NULL; ep++)
736			argmax -= strlen(*ep) + 1 + sizeof(*ep);
737		argmax -= 1 + sizeof(*ep);
738		/*
739		 * Ensure that -execdir ... {} + does not mix files
740		 * from different directories in one invocation.
741		 * Files from the same directory should be handled
742		 * in one invocation but there is no code for it.
743		 */
744		new->e_pnummax = new->flags & F_EXECDIR ? 1 : argmax / 16;
745		argmax -= sizeof(char *) * new->e_pnummax;
746		if (argmax <= 0)
747			errx(1, "no space for arguments");
748		new->e_psizemax = argmax;
749		new->e_pbsize = 0;
750		cnt += new->e_pnummax + 1;
751		new->e_next = lastexecplus;
752		lastexecplus = new;
753	}
754	if ((new->e_argv = malloc(cnt * sizeof(char *))) == NULL)
755		err(1, NULL);
756	if ((new->e_orig = malloc(cnt * sizeof(char *))) == NULL)
757		err(1, NULL);
758	if ((new->e_len = malloc(cnt * sizeof(int))) == NULL)
759		err(1, NULL);
760
761	for (argv = *argvp, cnt = 0; argv < ap; ++argv, ++cnt) {
762		new->e_orig[cnt] = *argv;
763		if (new->flags & F_EXECPLUS)
764			new->e_pbsize += strlen(*argv) + 1;
765		for (p = *argv; *p; ++p)
766			if (!(new->flags & F_EXECPLUS) && p[0] == '{' &&
767			    p[1] == '}') {
768				if ((new->e_argv[cnt] =
769				    malloc(MAXPATHLEN)) == NULL)
770					err(1, NULL);
771				new->e_len[cnt] = MAXPATHLEN;
772				break;
773			}
774		if (!*p) {
775			new->e_argv[cnt] = *argv;
776			new->e_len[cnt] = 0;
777		}
778	}
779	if (new->flags & F_EXECPLUS) {
780		new->e_psize = new->e_pbsize;
781		cnt--;
782		for (i = 0; i < new->e_pnummax; i++) {
783			new->e_argv[cnt] = NULL;
784			new->e_len[cnt] = 0;
785			cnt++;
786		}
787		argv = ap;
788		goto done;
789	}
790	new->e_argv[cnt] = new->e_orig[cnt] = NULL;
791
792done:	*argvp = argv + 1;
793	return new;
794}
795
796/* Finish any pending -exec ... {} + functions. */
797void
798finish_execplus(void)
799{
800	PLAN *p;
801
802	p = lastexecplus;
803	while (p != NULL) {
804		(p->execute)(p, NULL);
805		p = p->e_next;
806	}
807}
808
809int
810f_flags(PLAN *plan, FTSENT *entry)
811{
812	u_long flags;
813
814	flags = entry->fts_statp->st_flags;
815	if (plan->flags & F_ATLEAST)
816		return (flags | plan->fl_flags) == flags &&
817		    !(flags & plan->fl_notflags);
818	else if (plan->flags & F_ANY)
819		return (flags & plan->fl_flags) ||
820		    (flags | plan->fl_notflags) != flags;
821	else
822		return flags == plan->fl_flags &&
823		    !(plan->fl_flags & plan->fl_notflags);
824}
825
826PLAN *
827c_flags(OPTION *option, char ***argvp)
828{
829	char *flags_str;
830	PLAN *new;
831	u_long flags, notflags;
832
833	flags_str = nextarg(option, argvp);
834	ftsoptions &= ~FTS_NOSTAT;
835
836	new = palloc(option);
837
838	if (*flags_str == '-') {
839		new->flags |= F_ATLEAST;
840		flags_str++;
841	} else if (*flags_str == '+') {
842		new->flags |= F_ANY;
843		flags_str++;
844	}
845	if (strtofflags(&flags_str, &flags, &notflags) == 1)
846		errx(1, "%s: %s: illegal flags string", option->name, flags_str);
847
848	new->fl_flags = flags;
849	new->fl_notflags = notflags;
850	return new;
851}
852
853/*
854 * -follow functions --
855 *
856 *	Always true, causes symbolic links to be followed on a global
857 *	basis.
858 */
859PLAN *
860c_follow(OPTION *option, char ***argvp __unused)
861{
862	ftsoptions &= ~FTS_PHYSICAL;
863	ftsoptions |= FTS_LOGICAL;
864
865	return palloc(option);
866}
867
868/*
869 * -fstype functions --
870 *
871 *	True if the file is of a certain type.
872 */
873int
874f_fstype(PLAN *plan, FTSENT *entry)
875{
876	static dev_t curdev;	/* need a guaranteed illegal dev value */
877	static int first = 1;
878	struct statfs sb;
879	static int val_flags;
880	static char fstype[sizeof(sb.f_fstypename)];
881	char *p, save[2] = {0,0};
882
883	if ((plan->flags & F_MTMASK) == F_MTUNKNOWN)
884		return 0;
885
886	/* Only check when we cross mount point. */
887	if (first || curdev != entry->fts_statp->st_dev) {
888		curdev = entry->fts_statp->st_dev;
889
890		/*
891		 * Statfs follows symlinks; find wants the link's filesystem,
892		 * not where it points.
893		 */
894		if (entry->fts_info == FTS_SL ||
895		    entry->fts_info == FTS_SLNONE) {
896			if ((p = strrchr(entry->fts_accpath, '/')) != NULL)
897				++p;
898			else
899				p = entry->fts_accpath;
900			save[0] = p[0];
901			p[0] = '.';
902			save[1] = p[1];
903			p[1] = '\0';
904		} else
905			p = NULL;
906
907		if (statfs(entry->fts_accpath, &sb)) {
908			if (!ignore_readdir_race || errno != ENOENT) {
909				warn("statfs: %s", entry->fts_accpath);
910				exitstatus = 1;
911			}
912			return 0;
913		}
914
915		if (p) {
916			p[0] = save[0];
917			p[1] = save[1];
918		}
919
920		first = 0;
921
922		/*
923		 * Further tests may need both of these values, so
924		 * always copy both of them.
925		 */
926		val_flags = sb.f_flags;
927		strlcpy(fstype, sb.f_fstypename, sizeof(fstype));
928	}
929	switch (plan->flags & F_MTMASK) {
930	case F_MTFLAG:
931		return val_flags & plan->mt_data;
932	case F_MTTYPE:
933		return (strncmp(fstype, plan->c_data, sizeof(fstype)) == 0);
934	default:
935		abort();
936	}
937}
938
939PLAN *
940c_fstype(OPTION *option, char ***argvp)
941{
942	char *fsname;
943	PLAN *new;
944
945	fsname = nextarg(option, argvp);
946	ftsoptions &= ~FTS_NOSTAT;
947
948	new = palloc(option);
949	switch (*fsname) {
950	case 'l':
951		if (!strcmp(fsname, "local")) {
952			new->flags |= F_MTFLAG;
953			new->mt_data = MNT_LOCAL;
954			return new;
955		}
956		break;
957	case 'r':
958		if (!strcmp(fsname, "rdonly")) {
959			new->flags |= F_MTFLAG;
960			new->mt_data = MNT_RDONLY;
961			return new;
962		}
963		break;
964	}
965
966	new->flags |= F_MTTYPE;
967	new->c_data = fsname;
968	return new;
969}
970
971/*
972 * -group gname functions --
973 *
974 *	True if the file belongs to the group gname.  If gname is numeric and
975 *	an equivalent of the getgrnam() function does not return a valid group
976 *	name, gname is taken as a group ID.
977 */
978int
979f_group(PLAN *plan, FTSENT *entry)
980{
981	COMPARE(entry->fts_statp->st_gid, plan->g_data);
982}
983
984PLAN *
985c_group(OPTION *option, char ***argvp)
986{
987	char *gname;
988	PLAN *new;
989	struct group *g;
990	gid_t gid;
991
992	gname = nextarg(option, argvp);
993	ftsoptions &= ~FTS_NOSTAT;
994
995	new = palloc(option);
996	g = getgrnam(gname);
997	if (g == NULL) {
998		char* cp = gname;
999		if (gname[0] == '-' || gname[0] == '+')
1000			gname++;
1001		gid = atoi(gname);
1002		if (gid == 0 && gname[0] != '0')
1003			errx(1, "%s: %s: no such group", option->name, gname);
1004		gid = find_parsenum(new, option->name, cp, NULL);
1005	} else
1006		gid = g->gr_gid;
1007
1008	new->g_data = gid;
1009	return new;
1010}
1011
1012/*
1013 * -ignore_readdir_race functions --
1014 *
1015 *	Always true. Ignore errors which occur if a file or a directory
1016 *	in a starting point gets deleted between reading the name and calling
1017 *	stat on it while find is traversing the starting point.
1018 */
1019
1020PLAN *
1021c_ignore_readdir_race(OPTION *option, char ***argvp __unused)
1022{
1023	if (strcmp(option->name, "-ignore_readdir_race") == 0)
1024		ignore_readdir_race = 1;
1025	else
1026		ignore_readdir_race = 0;
1027
1028	return palloc(option);
1029}
1030
1031/*
1032 * -inum n functions --
1033 *
1034 *	True if the file has inode # n.
1035 */
1036int
1037f_inum(PLAN *plan, FTSENT *entry)
1038{
1039	COMPARE(entry->fts_statp->st_ino, plan->i_data);
1040}
1041
1042PLAN *
1043c_inum(OPTION *option, char ***argvp)
1044{
1045	char *inum_str;
1046	PLAN *new;
1047
1048	inum_str = nextarg(option, argvp);
1049	ftsoptions &= ~FTS_NOSTAT;
1050
1051	new = palloc(option);
1052	new->i_data = find_parsenum(new, option->name, inum_str, NULL);
1053	return new;
1054}
1055
1056/*
1057 * -samefile FN
1058 *
1059 *	True if the file has the same inode (eg hard link) FN
1060 */
1061
1062/* f_samefile is just f_inum */
1063PLAN *
1064c_samefile(OPTION *option, char ***argvp)
1065{
1066	char *fn;
1067	PLAN *new;
1068	struct stat sb;
1069
1070	fn = nextarg(option, argvp);
1071	ftsoptions &= ~FTS_NOSTAT;
1072
1073	new = palloc(option);
1074	if (stat(fn, &sb))
1075		err(1, "%s", fn);
1076	new->i_data = sb.st_ino;
1077	return new;
1078}
1079
1080/*
1081 * -links n functions --
1082 *
1083 *	True if the file has n links.
1084 */
1085int
1086f_links(PLAN *plan, FTSENT *entry)
1087{
1088	COMPARE(entry->fts_statp->st_nlink, plan->l_data);
1089}
1090
1091PLAN *
1092c_links(OPTION *option, char ***argvp)
1093{
1094	char *nlinks;
1095	PLAN *new;
1096
1097	nlinks = nextarg(option, argvp);
1098	ftsoptions &= ~FTS_NOSTAT;
1099
1100	new = palloc(option);
1101	new->l_data = (nlink_t)find_parsenum(new, option->name, nlinks, NULL);
1102	return new;
1103}
1104
1105/*
1106 * -ls functions --
1107 *
1108 *	Always true - prints the current entry to stdout in "ls" format.
1109 */
1110int
1111f_ls(PLAN *plan __unused, FTSENT *entry)
1112{
1113	printlong(entry->fts_path, entry->fts_accpath, entry->fts_statp);
1114	return 1;
1115}
1116
1117PLAN *
1118c_ls(OPTION *option, char ***argvp __unused)
1119{
1120	ftsoptions &= ~FTS_NOSTAT;
1121	isoutput = 1;
1122
1123	return palloc(option);
1124}
1125
1126/*
1127 * -name functions --
1128 *
1129 *	True if the basename of the filename being examined
1130 *	matches pattern using Pattern Matching Notation S3.14
1131 */
1132int
1133f_name(PLAN *plan, FTSENT *entry)
1134{
1135	char fn[PATH_MAX];
1136	const char *name;
1137	ssize_t len;
1138
1139	if (plan->flags & F_LINK) {
1140		/*
1141		 * The below test both avoids obviously useless readlink()
1142		 * calls and ensures that symlinks with existent target do
1143		 * not match if symlinks are being followed.
1144		 * Assumption: fts will stat all symlinks that are to be
1145		 * followed and will return the stat information.
1146		 */
1147		if (entry->fts_info != FTS_NSOK && entry->fts_info != FTS_SL &&
1148		    entry->fts_info != FTS_SLNONE)
1149			return 0;
1150		len = readlink(entry->fts_accpath, fn, sizeof(fn) - 1);
1151		if (len == -1)
1152			return 0;
1153		fn[len] = '\0';
1154		name = fn;
1155	} else
1156		name = entry->fts_name;
1157	return !fnmatch(plan->c_data, name,
1158	    plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
1159}
1160
1161PLAN *
1162c_name(OPTION *option, char ***argvp)
1163{
1164	char *pattern;
1165	PLAN *new;
1166
1167	pattern = nextarg(option, argvp);
1168	new = palloc(option);
1169	new->c_data = pattern;
1170	return new;
1171}
1172
1173/*
1174 * -newer file functions --
1175 *
1176 *	True if the current file has been modified more recently
1177 *	then the modification time of the file named by the pathname
1178 *	file.
1179 */
1180int
1181f_newer(PLAN *plan, FTSENT *entry)
1182{
1183	struct timespec ft;
1184
1185	if (plan->flags & F_TIME_C)
1186		ft = entry->fts_statp->st_ctim;
1187	else if (plan->flags & F_TIME_A)
1188		ft = entry->fts_statp->st_atim;
1189	else if (plan->flags & F_TIME_B)
1190		ft = entry->fts_statp->st_birthtim;
1191	else
1192		ft = entry->fts_statp->st_mtim;
1193	return (ft.tv_sec > plan->t_data.tv_sec ||
1194	    (ft.tv_sec == plan->t_data.tv_sec &&
1195	    ft.tv_nsec > plan->t_data.tv_nsec));
1196}
1197
1198PLAN *
1199c_newer(OPTION *option, char ***argvp)
1200{
1201	char *fn_or_tspec;
1202	PLAN *new;
1203	struct stat sb;
1204
1205	fn_or_tspec = nextarg(option, argvp);
1206	ftsoptions &= ~FTS_NOSTAT;
1207
1208	new = palloc(option);
1209	/* compare against what */
1210	if (option->flags & F_TIME2_T) {
1211		new->t_data.tv_sec = get_date(fn_or_tspec);
1212		if (new->t_data.tv_sec == (time_t) -1)
1213			errx(1, "Can't parse date/time: %s", fn_or_tspec);
1214		/* Use the seconds only in the comparison. */
1215		new->t_data.tv_nsec = 999999999;
1216	} else {
1217		if (stat(fn_or_tspec, &sb))
1218			err(1, "%s", fn_or_tspec);
1219		if (option->flags & F_TIME2_C)
1220			new->t_data = sb.st_ctim;
1221		else if (option->flags & F_TIME2_A)
1222			new->t_data = sb.st_atim;
1223		else if (option->flags & F_TIME2_B)
1224			new->t_data = sb.st_birthtim;
1225		else
1226			new->t_data = sb.st_mtim;
1227	}
1228	return new;
1229}
1230
1231/*
1232 * -nogroup functions --
1233 *
1234 *	True if file belongs to a user ID for which the equivalent
1235 *	of the getgrnam() 9.2.1 [POSIX.1] function returns NULL.
1236 */
1237int
1238f_nogroup(PLAN *plan __unused, FTSENT *entry)
1239{
1240	return group_from_gid(entry->fts_statp->st_gid, 1) == NULL;
1241}
1242
1243PLAN *
1244c_nogroup(OPTION *option, char ***argvp __unused)
1245{
1246	ftsoptions &= ~FTS_NOSTAT;
1247
1248	return palloc(option);
1249}
1250
1251/*
1252 * -nouser functions --
1253 *
1254 *	True if file belongs to a user ID for which the equivalent
1255 *	of the getpwuid() 9.2.2 [POSIX.1] function returns NULL.
1256 */
1257int
1258f_nouser(PLAN *plan __unused, FTSENT *entry)
1259{
1260	return user_from_uid(entry->fts_statp->st_uid, 1) == NULL;
1261}
1262
1263PLAN *
1264c_nouser(OPTION *option, char ***argvp __unused)
1265{
1266	ftsoptions &= ~FTS_NOSTAT;
1267
1268	return palloc(option);
1269}
1270
1271/*
1272 * -path functions --
1273 *
1274 *	True if the path of the filename being examined
1275 *	matches pattern using Pattern Matching Notation S3.14
1276 */
1277int
1278f_path(PLAN *plan, FTSENT *entry)
1279{
1280	return !fnmatch(plan->c_data, entry->fts_path,
1281	    plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
1282}
1283
1284/* c_path is the same as c_name */
1285
1286/*
1287 * -perm functions --
1288 *
1289 *	The mode argument is used to represent file mode bits.  If it starts
1290 *	with a leading digit, it's treated as an octal mode, otherwise as a
1291 *	symbolic mode.
1292 */
1293int
1294f_perm(PLAN *plan, FTSENT *entry)
1295{
1296	mode_t mode;
1297
1298	mode = entry->fts_statp->st_mode &
1299	    (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO);
1300	if (plan->flags & F_ATLEAST)
1301		return (plan->m_data | mode) == mode;
1302	else if (plan->flags & F_ANY)
1303		return (mode & plan->m_data);
1304	else
1305		return mode == plan->m_data;
1306	/* NOTREACHED */
1307}
1308
1309PLAN *
1310c_perm(OPTION *option, char ***argvp)
1311{
1312	char *perm;
1313	PLAN *new;
1314	mode_t *set;
1315
1316	perm = nextarg(option, argvp);
1317	ftsoptions &= ~FTS_NOSTAT;
1318
1319	new = palloc(option);
1320
1321	if (*perm == '-') {
1322		new->flags |= F_ATLEAST;
1323		++perm;
1324	} else if (*perm == '+') {
1325		new->flags |= F_ANY;
1326		++perm;
1327	}
1328
1329	if ((set = setmode(perm)) == NULL)
1330		errx(1, "%s: %s: illegal mode string", option->name, perm);
1331
1332	new->m_data = getmode(set, 0);
1333	free(set);
1334	return new;
1335}
1336
1337/*
1338 * -print functions --
1339 *
1340 *	Always true, causes the current pathname to be written to
1341 *	standard output.
1342 */
1343int
1344f_print(PLAN *plan __unused, FTSENT *entry)
1345{
1346	(void)puts(entry->fts_path);
1347	return 1;
1348}
1349
1350PLAN *
1351c_print(OPTION *option, char ***argvp __unused)
1352{
1353	isoutput = 1;
1354
1355	return palloc(option);
1356}
1357
1358/*
1359 * -print0 functions --
1360 *
1361 *	Always true, causes the current pathname to be written to
1362 *	standard output followed by a NUL character
1363 */
1364int
1365f_print0(PLAN *plan __unused, FTSENT *entry)
1366{
1367	fputs(entry->fts_path, stdout);
1368	fputc('\0', stdout);
1369	return 1;
1370}
1371
1372/* c_print0 is the same as c_print */
1373
1374/*
1375 * -prune functions --
1376 *
1377 *	Prune a portion of the hierarchy.
1378 */
1379int
1380f_prune(PLAN *plan __unused, FTSENT *entry)
1381{
1382	if (fts_set(tree, entry, FTS_SKIP))
1383		err(1, "%s", entry->fts_path);
1384	return 1;
1385}
1386
1387/* c_prune == c_simple */
1388
1389/*
1390 * -regex functions --
1391 *
1392 *	True if the whole path of the file matches pattern using
1393 *	regular expression.
1394 */
1395int
1396f_regex(PLAN *plan, FTSENT *entry)
1397{
1398	char *str;
1399	int len;
1400	regex_t *pre;
1401	regmatch_t pmatch;
1402	int errcode;
1403	char errbuf[LINE_MAX];
1404	int matched;
1405
1406	pre = plan->re_data;
1407	str = entry->fts_path;
1408	len = strlen(str);
1409	matched = 0;
1410
1411	pmatch.rm_so = 0;
1412	pmatch.rm_eo = len;
1413
1414	errcode = regexec(pre, str, 1, &pmatch, REG_STARTEND);
1415
1416	if (errcode != 0 && errcode != REG_NOMATCH) {
1417		regerror(errcode, pre, errbuf, sizeof errbuf);
1418		errx(1, "%s: %s",
1419		     plan->flags & F_IGNCASE ? "-iregex" : "-regex", errbuf);
1420	}
1421
1422	if (errcode == 0 && pmatch.rm_so == 0 && pmatch.rm_eo == len)
1423		matched = 1;
1424
1425	return matched;
1426}
1427
1428PLAN *
1429c_regex(OPTION *option, char ***argvp)
1430{
1431	PLAN *new;
1432	char *pattern;
1433	regex_t *pre;
1434	int errcode;
1435	char errbuf[LINE_MAX];
1436
1437	if ((pre = malloc(sizeof(regex_t))) == NULL)
1438		err(1, NULL);
1439
1440	pattern = nextarg(option, argvp);
1441
1442	if ((errcode = regcomp(pre, pattern,
1443	    regexp_flags | (option->flags & F_IGNCASE ? REG_ICASE : 0))) != 0) {
1444		regerror(errcode, pre, errbuf, sizeof errbuf);
1445		errx(1, "%s: %s: %s",
1446		     option->flags & F_IGNCASE ? "-iregex" : "-regex",
1447		     pattern, errbuf);
1448	}
1449
1450	new = palloc(option);
1451	new->re_data = pre;
1452
1453	return new;
1454}
1455
1456/* c_simple covers c_prune, c_openparen, c_closeparen, c_not, c_or, c_true, c_false */
1457
1458PLAN *
1459c_simple(OPTION *option, char ***argvp __unused)
1460{
1461	return palloc(option);
1462}
1463
1464/*
1465 * -size n[c] functions --
1466 *
1467 *	True if the file size in bytes, divided by an implementation defined
1468 *	value and rounded up to the next integer, is n.  If n is followed by
1469 *      one of c k M G T P, the size is in bytes, kilobytes,
1470 *      megabytes, gigabytes, terabytes or petabytes respectively.
1471 */
1472#define	FIND_SIZE	512
1473static int divsize = 1;
1474
1475int
1476f_size(PLAN *plan, FTSENT *entry)
1477{
1478	off_t size;
1479
1480	size = divsize ? (entry->fts_statp->st_size + FIND_SIZE - 1) /
1481	    FIND_SIZE : entry->fts_statp->st_size;
1482	COMPARE(size, plan->o_data);
1483}
1484
1485PLAN *
1486c_size(OPTION *option, char ***argvp)
1487{
1488	char *size_str;
1489	PLAN *new;
1490	char endch;
1491	off_t scale;
1492
1493	size_str = nextarg(option, argvp);
1494	ftsoptions &= ~FTS_NOSTAT;
1495
1496	new = palloc(option);
1497	endch = 'c';
1498	new->o_data = find_parsenum(new, option->name, size_str, &endch);
1499	if (endch != '\0') {
1500		divsize = 0;
1501
1502		switch (endch) {
1503		case 'c':                       /* characters */
1504			scale = 0x1LL;
1505			break;
1506		case 'k':                       /* kilobytes 1<<10 */
1507			scale = 0x400LL;
1508			break;
1509		case 'M':                       /* megabytes 1<<20 */
1510			scale = 0x100000LL;
1511			break;
1512		case 'G':                       /* gigabytes 1<<30 */
1513			scale = 0x40000000LL;
1514			break;
1515		case 'T':                       /* terabytes 1<<40 */
1516			scale = 0x10000000000LL;
1517			break;
1518		case 'P':                       /* petabytes 1<<50 */
1519			scale = 0x4000000000000LL;
1520			break;
1521		default:
1522			errx(1, "%s: %s: illegal trailing character",
1523				option->name, size_str);
1524			break;
1525		}
1526		if (new->o_data > QUAD_MAX / scale)
1527			errx(1, "%s: %s: value too large",
1528				option->name, size_str);
1529		new->o_data *= scale;
1530	}
1531	return new;
1532}
1533
1534/*
1535 * -sparse functions --
1536 *
1537 *      Check if a file is sparse by finding if it occupies fewer blocks
1538 *      than we expect based on its size.
1539 */
1540int
1541f_sparse(PLAN *plan __unused, FTSENT *entry)
1542{
1543	off_t expected_blocks;
1544
1545	expected_blocks = (entry->fts_statp->st_size + 511) / 512;
1546	return entry->fts_statp->st_blocks < expected_blocks;
1547}
1548
1549PLAN *
1550c_sparse(OPTION *option, char ***argvp __unused)
1551{
1552	ftsoptions &= ~FTS_NOSTAT;
1553
1554	return palloc(option);
1555}
1556
1557/*
1558 * -type c functions --
1559 *
1560 *	True if the type of the file is c, where c is b, c, d, p, f or w
1561 *	for block special file, character special file, directory, FIFO,
1562 *	regular file or whiteout respectively.
1563 */
1564int
1565f_type(PLAN *plan, FTSENT *entry)
1566{
1567	if (plan->m_data == S_IFDIR)
1568		return (entry->fts_info == FTS_D || entry->fts_info == FTS_DC ||
1569		    entry->fts_info == FTS_DNR || entry->fts_info == FTS_DOT ||
1570		    entry->fts_info == FTS_DP);
1571	else
1572		return (entry->fts_statp->st_mode & S_IFMT) == plan->m_data;
1573}
1574
1575PLAN *
1576c_type(OPTION *option, char ***argvp)
1577{
1578	char *typestring;
1579	PLAN *new;
1580	mode_t  mask;
1581
1582	typestring = nextarg(option, argvp);
1583	if (typestring[0] != 'd')
1584		ftsoptions &= ~FTS_NOSTAT;
1585
1586	switch (typestring[0]) {
1587	case 'b':
1588		mask = S_IFBLK;
1589		break;
1590	case 'c':
1591		mask = S_IFCHR;
1592		break;
1593	case 'd':
1594		mask = S_IFDIR;
1595		break;
1596	case 'f':
1597		mask = S_IFREG;
1598		break;
1599	case 'l':
1600		mask = S_IFLNK;
1601		break;
1602	case 'p':
1603		mask = S_IFIFO;
1604		break;
1605	case 's':
1606		mask = S_IFSOCK;
1607		break;
1608#ifdef FTS_WHITEOUT
1609	case 'w':
1610		mask = S_IFWHT;
1611		ftsoptions |= FTS_WHITEOUT;
1612		break;
1613#endif /* FTS_WHITEOUT */
1614	default:
1615		errx(1, "%s: %s: unknown type", option->name, typestring);
1616	}
1617
1618	new = palloc(option);
1619	new->m_data = mask;
1620	return new;
1621}
1622
1623/*
1624 * -user uname functions --
1625 *
1626 *	True if the file belongs to the user uname.  If uname is numeric and
1627 *	an equivalent of the getpwnam() S9.2.2 [POSIX.1] function does not
1628 *	return a valid user name, uname is taken as a user ID.
1629 */
1630int
1631f_user(PLAN *plan, FTSENT *entry)
1632{
1633	COMPARE(entry->fts_statp->st_uid, plan->u_data);
1634}
1635
1636PLAN *
1637c_user(OPTION *option, char ***argvp)
1638{
1639	char *username;
1640	PLAN *new;
1641	struct passwd *p;
1642	uid_t uid;
1643
1644	username = nextarg(option, argvp);
1645	ftsoptions &= ~FTS_NOSTAT;
1646
1647	new = palloc(option);
1648	p = getpwnam(username);
1649	if (p == NULL) {
1650		char* cp = username;
1651		if( username[0] == '-' || username[0] == '+' )
1652			username++;
1653		uid = atoi(username);
1654		if (uid == 0 && username[0] != '0')
1655			errx(1, "%s: %s: no such user", option->name, username);
1656		uid = find_parsenum(new, option->name, cp, NULL);
1657	} else
1658		uid = p->pw_uid;
1659
1660	new->u_data = uid;
1661	return new;
1662}
1663
1664/*
1665 * -xdev functions --
1666 *
1667 *	Always true, causes find not to descend past directories that have a
1668 *	different device ID (st_dev, see stat() S5.6.2 [POSIX.1])
1669 */
1670PLAN *
1671c_xdev(OPTION *option, char ***argvp __unused)
1672{
1673	ftsoptions |= FTS_XDEV;
1674
1675	return palloc(option);
1676}
1677
1678/*
1679 * ( expression ) functions --
1680 *
1681 *	True if expression is true.
1682 */
1683int
1684f_expr(PLAN *plan, FTSENT *entry)
1685{
1686	PLAN *p;
1687	int state = 0;
1688
1689	for (p = plan->p_data[0];
1690	    p && (state = (p->execute)(p, entry)); p = p->next);
1691	return state;
1692}
1693
1694/*
1695 * f_openparen and f_closeparen nodes are temporary place markers.  They are
1696 * eliminated during phase 2 of find_formplan() --- the '(' node is converted
1697 * to a f_expr node containing the expression and the ')' node is discarded.
1698 * The functions themselves are only used as constants.
1699 */
1700
1701int
1702f_openparen(PLAN *plan __unused, FTSENT *entry __unused)
1703{
1704	abort();
1705}
1706
1707int
1708f_closeparen(PLAN *plan __unused, FTSENT *entry __unused)
1709{
1710	abort();
1711}
1712
1713/* c_openparen == c_simple */
1714/* c_closeparen == c_simple */
1715
1716/*
1717 * AND operator. Since AND is implicit, no node is allocated.
1718 */
1719PLAN *
1720c_and(OPTION *option __unused, char ***argvp __unused)
1721{
1722	return NULL;
1723}
1724
1725/*
1726 * ! expression functions --
1727 *
1728 *	Negation of a primary; the unary NOT operator.
1729 */
1730int
1731f_not(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	return !state;
1739}
1740
1741/* c_not == c_simple */
1742
1743/*
1744 * expression -o expression functions --
1745 *
1746 *	Alternation of primaries; the OR operator.  The second expression is
1747 * not evaluated if the first expression is true.
1748 */
1749int
1750f_or(PLAN *plan, FTSENT *entry)
1751{
1752	PLAN *p;
1753	int state = 0;
1754
1755	for (p = plan->p_data[0];
1756	    p && (state = (p->execute)(p, entry)); p = p->next);
1757
1758	if (state)
1759		return 1;
1760
1761	for (p = plan->p_data[1];
1762	    p && (state = (p->execute)(p, entry)); p = p->next);
1763	return state;
1764}
1765
1766/* c_or == c_simple */
1767
1768/*
1769 * -false
1770 *
1771 *	Always false.
1772 */
1773int
1774f_false(PLAN *plan __unused, FTSENT *entry __unused)
1775{
1776	return 0;
1777}
1778
1779/* c_false == c_simple */
1780
1781/*
1782 * -quit
1783 *
1784 *	Exits the program
1785 */
1786int
1787f_quit(PLAN *plan __unused, FTSENT *entry __unused)
1788{
1789	finish_execplus();
1790	exit(exitstatus);
1791}
1792
1793/* c_quit == c_simple */
1794