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