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