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