xref: /freebsd/usr.bin/find/function.c (revision f2ac424af7b980ba4d858ecfd1644ce197d6869d)
1 /*-
2  * Copyright (c) 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Cimarron D. Taylor of the University of California, Berkeley.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 #if 0
39 static const char sccsid[] = "@(#)function.c	8.10 (Berkeley) 5/4/95";
40 #else
41 static const char rcsid[] =
42   "$FreeBSD$";
43 #endif
44 #endif /* not lint */
45 
46 #include <sys/param.h>
47 #include <sys/ucred.h>
48 #include <sys/stat.h>
49 #include <sys/wait.h>
50 #include <sys/mount.h>
51 #include <sys/timeb.h>
52 
53 #include <dirent.h>
54 #include <err.h>
55 #include <errno.h>
56 #include <fnmatch.h>
57 #include <fts.h>
58 #include <grp.h>
59 #include <pwd.h>
60 #include <regex.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65 
66 #include "find.h"
67 
68 static PLAN *palloc __P((OPTION *));
69 static long long find_parsenum __P((PLAN *, const char *, char *, char *));
70 static long long find_parsetime __P((PLAN *, const char *, char *));
71 static char *nextarg __P((OPTION *, char ***));
72 time_t get_date __P((char *, struct timeb *));
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)
89 	OPTION *option;
90 {
91 	PLAN *new;
92 
93 	if ((new = malloc(sizeof(PLAN))) == NULL)
94 		err(1, NULL);
95 	new->execute = option->execute;
96 	new->flags = option->flags;
97 	new->next = NULL;
98 	return new;
99 }
100 
101 /*
102  * find_parsenum --
103  *	Parse a string of the form [+-]# and return the value.
104  */
105 static long long
106 find_parsenum(plan, option, vp, endch)
107 	PLAN *plan;
108 	const char *option;
109 	char *vp, *endch;
110 {
111 	long long value;
112 	char *endchar, *str;	/* Pointer to character ending conversion. */
113 
114 	/* Determine comparison from leading + or -. */
115 	str = vp;
116 	switch (*str) {
117 	case '+':
118 		++str;
119 		plan->flags |= F_GREATER;
120 		break;
121 	case '-':
122 		++str;
123 		plan->flags |= F_LESSTHAN;
124 		break;
125 	default:
126 		plan->flags |= F_EQUAL;
127 		break;
128 	}
129 
130 	/*
131 	 * Convert the string with strtoq().  Note, if strtoq() returns zero
132 	 * and endchar points to the beginning of the string we know we have
133 	 * a syntax error.
134 	 */
135 	value = strtoq(str, &endchar, 10);
136 	if (value == 0 && endchar == str)
137 		errx(1, "%s: %s: illegal numeric value", option, vp);
138 	if (endchar[0] && (endch == NULL || endchar[0] != *endch))
139 		errx(1, "%s: %s: illegal trailing character", option, vp);
140 	if (endch)
141 		*endch = endchar[0];
142 	return value;
143 }
144 
145 /*
146  * find_parsetime --
147  *	Parse a string of the form [+-]([0-9]+[smhdw]?)+ and return the value.
148  */
149 static long long
150 find_parsetime(plan, option, vp)
151 	PLAN *plan;
152 	const char *option;
153 	char *vp;
154 {
155 	long long secs, value;
156 	char *str, *unit;	/* Pointer to character ending conversion. */
157 
158 	/* Determine comparison from leading + or -. */
159 	str = vp;
160 	switch (*str) {
161 	case '+':
162 		++str;
163 		plan->flags |= F_GREATER;
164 		break;
165 	case '-':
166 		++str;
167 		plan->flags |= F_LESSTHAN;
168 		break;
169 	default:
170 		plan->flags |= F_EQUAL;
171 		break;
172 	}
173 
174 	value = strtoq(str, &unit, 10);
175 	if (value == 0 && unit == str) {
176 		errx(1, "%s: %s: illegal time value", option, vp);
177 		/* NOTREACHED */
178 	}
179 	if (*unit == '\0')
180 		return value;
181 
182 	/* Units syntax. */
183 	secs = 0;
184 	for (;;) {
185 		switch(*unit) {
186 		case 's':	/* seconds */
187 			secs += value;
188 			break;
189 		case 'm':	/* minutes */
190 			secs += value * 60;
191 			break;
192 		case 'h':	/* hours */
193 			secs += value * 3600;
194 			break;
195 		case 'd':	/* days */
196 			secs += value * 86400;
197 			break;
198 		case 'w':	/* weeks */
199 			secs += value * 604800;
200 			break;
201 		default:
202 			errx(1, "%s: %s: bad unit '%c'", option, vp, *unit);
203 			/* NOTREACHED */
204 		}
205 		str = unit + 1;
206 		if (*str == '\0')	/* EOS */
207 			break;
208 		value = strtoq(str, &unit, 10);
209 		if (value == 0 && unit == str) {
210 			errx(1, "%s: %s: illegal time value", option, vp);
211 			/* NOTREACHED */
212 		}
213 		if (*unit == '\0') {
214 			errx(1, "%s: %s: missing trailing unit", option, vp);
215 			/* NOTREACHED */
216 		}
217 	}
218 	plan->flags |= F_EXACTTIME;
219 	return secs;
220 }
221 
222 /*
223  * nextarg --
224  *	Check that another argument still exists, return a pointer to it,
225  *	and increment the argument vector pointer.
226  */
227 static char *
228 nextarg(option, argvp)
229 	OPTION *option;
230 	char ***argvp;
231 {
232 	char *arg;
233 
234 	if ((arg = **argvp) == 0)
235 		errx(1, "%s: requires additional arguments", option->name);
236 	(*argvp)++;
237 	return arg;
238 } /* nextarg() */
239 
240 /*
241  * The value of n for the inode times (atime, ctime, and mtime) is a range,
242  * i.e. n matches from (n - 1) to n 24 hour periods.  This interacts with
243  * -n, such that "-mtime -1" would be less than 0 days, which isn't what the
244  * user wanted.  Correct so that -1 is "less than 1".
245  */
246 #define	TIME_CORRECT(p) \
247 	if (((p)->flags & F_ELG_MASK) == F_LESSTHAN) \
248 		++((p)->t_data);
249 
250 /*
251  * -[acm]min n functions --
252  *
253  *    True if the difference between the
254  *		file access time (-amin)
255  *		last change of file status information (-cmin)
256  *		file modification time (-mmin)
257  *    and the current time is n min periods.
258  */
259 int
260 f_Xmin(plan, entry)
261 	PLAN *plan;
262 	FTSENT *entry;
263 {
264 	extern time_t now;
265 
266 	if (plan->flags & F_TIME_C) {
267 		COMPARE((now - entry->fts_statp->st_ctime +
268 		    60 - 1) / 60, plan->t_data);
269 	} else if (plan->flags & F_TIME_A) {
270 		COMPARE((now - entry->fts_statp->st_atime +
271 		    60 - 1) / 60, plan->t_data);
272 	} else {
273 		COMPARE((now - entry->fts_statp->st_mtime +
274 		    60 - 1) / 60, plan->t_data);
275 	}
276 }
277 
278 PLAN *
279 c_Xmin(option, argvp)
280 	OPTION *option;
281 	char ***argvp;
282 {
283 	char *nmins;
284 	PLAN *new;
285 
286 	nmins = nextarg(option, argvp);
287 	ftsoptions &= ~FTS_NOSTAT;
288 
289 	new = palloc(option);
290 	new->t_data = find_parsenum(new, option->name, nmins, NULL);
291 	TIME_CORRECT(new);
292 	return new;
293 }
294 
295 /*
296  * -[acm]time n functions --
297  *
298  *	True if the difference between the
299  *		file access time (-atime)
300  *		last change of file status information (-ctime)
301  *		file modification time (-mtime)
302  *	and the current time is n 24 hour periods.
303  */
304 
305 int
306 f_Xtime(plan, entry)
307 	PLAN *plan;
308 	FTSENT *entry;
309 {
310 	extern time_t now;
311 	time_t xtime;
312 
313 	if (plan->flags & F_TIME_A)
314 		xtime = entry->fts_statp->st_atime;
315 	else if (plan->flags & F_TIME_C)
316 		xtime = entry->fts_statp->st_ctime;
317 	else
318 		xtime = entry->fts_statp->st_mtime;
319 
320 	if (plan->flags & F_EXACTTIME)
321 		COMPARE(now - xtime, plan->t_data);
322 	else
323 		COMPARE((now - xtime + 86400 - 1) / 86400, plan->t_data);
324 }
325 
326 PLAN *
327 c_Xtime(option, argvp)
328 	OPTION *option;
329 	char ***argvp;
330 {
331 	char *value;
332 	PLAN *new;
333 
334 	value = nextarg(option, argvp);
335 	ftsoptions &= ~FTS_NOSTAT;
336 
337 	new = palloc(option);
338 	new->t_data = find_parsetime(new, option->name, value);
339 	if (!(new->flags & F_EXACTTIME))
340 		TIME_CORRECT(new);
341 	return new;
342 }
343 
344 /*
345  * -maxdepth/-mindepth n functions --
346  *
347  *        Does the same as -prune if the level of the current file is
348  *        greater/less than the specified maximum/minimum depth.
349  *
350  *        Note that -maxdepth and -mindepth are handled specially in
351  *        find_execute() so their f_* functions are set to f_always_true().
352  */
353 PLAN *
354 c_mXXdepth(option, argvp)
355 	OPTION *option;
356 	char ***argvp;
357 {
358 	char *dstr;
359 	PLAN *new;
360 
361 	dstr = nextarg(option, argvp);
362 	if (dstr[0] == '-')
363 		/* all other errors handled by find_parsenum() */
364 		errx(1, "%s: %s: value must be positive", option->name, dstr);
365 
366 	new = palloc(option);
367 	if (option->flags & F_MAXDEPTH)
368 		maxdepth = find_parsenum(new, option->name, dstr, NULL);
369 	else
370 		mindepth = find_parsenum(new, option->name, dstr, NULL);
371 	return new;
372 }
373 
374 /*
375  * -delete functions --
376  *
377  *	True always.  Makes its best shot and continues on regardless.
378  */
379 int
380 f_delete(plan, entry)
381 	PLAN *plan __unused;
382 	FTSENT *entry;
383 {
384 	/* ignore these from fts */
385 	if (strcmp(entry->fts_accpath, ".") == 0 ||
386 	    strcmp(entry->fts_accpath, "..") == 0)
387 		return 1;
388 
389 	/* sanity check */
390 	if (isdepth == 0 ||			/* depth off */
391 	    (ftsoptions & FTS_NOSTAT) ||	/* not stat()ing */
392 	    !(ftsoptions & FTS_PHYSICAL) ||	/* physical off */
393 	    (ftsoptions & FTS_LOGICAL))		/* or finally, logical on */
394 		errx(1, "-delete: insecure options got turned on");
395 
396 	/* Potentially unsafe - do not accept relative paths whatsoever */
397 	if (strchr(entry->fts_accpath, '/') != NULL)
398 		errx(1, "-delete: %s: relative path potentially not safe",
399 			entry->fts_accpath);
400 
401 	/* Turn off user immutable bits if running as root */
402 	if ((entry->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
403 	    !(entry->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
404 	    geteuid() == 0)
405 		chflags(entry->fts_accpath,
406 		       entry->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
407 
408 	/* rmdir directories, unlink everything else */
409 	if (S_ISDIR(entry->fts_statp->st_mode)) {
410 		if (rmdir(entry->fts_accpath) < 0 && errno != ENOTEMPTY)
411 			warn("-delete: rmdir(%s)", entry->fts_path);
412 	} else {
413 		if (unlink(entry->fts_accpath) < 0)
414 			warn("-delete: unlink(%s)", entry->fts_path);
415 	}
416 
417 	/* "succeed" */
418 	return 1;
419 }
420 
421 PLAN *
422 c_delete(option, argvp)
423 	OPTION *option;
424 	char ***argvp __unused;
425 {
426 
427 	ftsoptions &= ~FTS_NOSTAT;	/* no optimise */
428 	ftsoptions |= FTS_PHYSICAL;	/* disable -follow */
429 	ftsoptions &= ~FTS_LOGICAL;	/* disable -follow */
430 	isoutput = 1;			/* possible output */
431 	isdepth = 1;			/* -depth implied */
432 
433 	return palloc(option);
434 }
435 
436 
437 /*
438  * -depth functions --
439  *
440  *	Always true, causes descent of the directory hierarchy to be done
441  *	so that all entries in a directory are acted on before the directory
442  *	itself.
443  */
444 int
445 f_always_true(plan, entry)
446 	PLAN *plan __unused;
447 	FTSENT *entry __unused;
448 {
449 	return 1;
450 }
451 
452 PLAN *
453 c_depth(option, argvp)
454 	OPTION *option;
455 	char ***argvp __unused;
456 {
457 	isdepth = 1;
458 
459 	return palloc(option);
460 }
461 
462 /*
463  * -empty functions --
464  *
465  *	True if the file or directory is empty
466  */
467 int
468 f_empty(plan, entry)
469 	PLAN *plan __unused;
470 	FTSENT *entry;
471 {
472 	if (S_ISREG(entry->fts_statp->st_mode) &&
473 	    entry->fts_statp->st_size == 0)
474 		return 1;
475 	if (S_ISDIR(entry->fts_statp->st_mode)) {
476 		struct dirent *dp;
477 		int empty;
478 		DIR *dir;
479 
480 		empty = 1;
481 		dir = opendir(entry->fts_accpath);
482 		if (dir == NULL)
483 			err(1, "%s", entry->fts_accpath);
484 		for (dp = readdir(dir); dp; dp = readdir(dir))
485 			if (dp->d_name[0] != '.' ||
486 			    (dp->d_name[1] != '\0' &&
487 			     (dp->d_name[1] != '.' || dp->d_name[2] != '\0'))) {
488 				empty = 0;
489 				break;
490 			}
491 		closedir(dir);
492 		return empty;
493 	}
494 	return 0;
495 }
496 
497 PLAN *
498 c_empty(option, argvp)
499 	OPTION *option;
500 	char ***argvp __unused;
501 {
502 	ftsoptions &= ~FTS_NOSTAT;
503 
504 	return palloc(option);
505 }
506 
507 /*
508  * [-exec | -execdir | -ok] utility [arg ... ] ; functions --
509  *
510  *	True if the executed utility returns a zero value as exit status.
511  *	The end of the primary expression is delimited by a semicolon.  If
512  *	"{}" occurs anywhere, it gets replaced by the current pathname,
513  *	or, in the case of -execdir, the current basename (filename
514  *	without leading directory prefix). For -exec and -ok,
515  *	the current directory for the execution of utility is the same as
516  *	the current directory when the find utility was started, whereas
517  *	for -execdir, it is the directory the file resides in.
518  *
519  *	The primary -ok differs from -exec in that it requests affirmation
520  *	of the user before executing the utility.
521  */
522 int
523 f_exec(plan, entry)
524 	PLAN *plan;
525 	FTSENT *entry;
526 {
527 	extern int dotfd;
528 	int cnt;
529 	pid_t pid;
530 	int status;
531 	char *file;
532 
533 	/* XXX - if file/dir ends in '/' this will not work -- can it? */
534 	if ((plan->flags & F_EXECDIR) && \
535 	    (file = strrchr(entry->fts_path, '/')))
536 		file++;
537 	else
538 		file = entry->fts_path;
539 
540 	for (cnt = 0; plan->e_argv[cnt]; ++cnt)
541 		if (plan->e_len[cnt])
542 			brace_subst(plan->e_orig[cnt], &plan->e_argv[cnt],
543 			    file, plan->e_len[cnt]);
544 
545 	if ((plan->flags & F_NEEDOK) && !queryuser(plan->e_argv))
546 		return 0;
547 
548 	/* make sure find output is interspersed correctly with subprocesses */
549 	fflush(stdout);
550 	fflush(stderr);
551 
552 	switch (pid = fork()) {
553 	case -1:
554 		err(1, "fork");
555 		/* NOTREACHED */
556 	case 0:
557 		/* change dir back from where we started */
558 		if (!(plan->flags & F_EXECDIR) && fchdir(dotfd)) {
559 			warn("chdir");
560 			_exit(1);
561 		}
562 		execvp(plan->e_argv[0], plan->e_argv);
563 		warn("%s", plan->e_argv[0]);
564 		_exit(1);
565 	}
566 	pid = waitpid(pid, &status, 0);
567 	return (pid != -1 && WIFEXITED(status) && !WEXITSTATUS(status));
568 }
569 
570 /*
571  * c_exec, c_execdir, c_ok --
572  *	build three parallel arrays, one with pointers to the strings passed
573  *	on the command line, one with (possibly duplicated) pointers to the
574  *	argv array, and one with integer values that are lengths of the
575  *	strings, but also flags meaning that the string has to be massaged.
576  */
577 PLAN *
578 c_exec(option, argvp)
579 	OPTION *option;
580 	char ***argvp;
581 {
582 	PLAN *new;			/* node returned */
583 	int cnt;
584 	char **argv, **ap, *p;
585 
586 	/* XXX - was in c_execdir, but seems unnecessary!?
587 	ftsoptions &= ~FTS_NOSTAT;
588 	*/
589 	isoutput = 1;
590 
591 	/* XXX - this is a change from the previous coding */
592 	new = palloc(option);
593 
594 	for (ap = argv = *argvp;; ++ap) {
595 		if (!*ap)
596 			errx(1,
597 			    "%s: no terminating \";\"", option->name);
598 		if (**ap == ';')
599 			break;
600 	}
601 
602 	cnt = ap - *argvp + 1;
603 	if ((new->e_argv = malloc((u_int)cnt * sizeof(char *))) == NULL)
604 		err(1, (char *)NULL);
605 	if ((new->e_orig = malloc((u_int)cnt * sizeof(char *))) == NULL)
606 		err(1, (char *)NULL);
607 	if ((new->e_len = malloc((u_int)cnt * sizeof(int))) == NULL)
608 		err(1, (char *)NULL);
609 
610 	for (argv = *argvp, cnt = 0; argv < ap; ++argv, ++cnt) {
611 		new->e_orig[cnt] = *argv;
612 		for (p = *argv; *p; ++p)
613 			if (p[0] == '{' && p[1] == '}') {
614 				if ((new->e_argv[cnt] =
615 				    malloc((u_int)MAXPATHLEN)) == NULL)
616 					err(1, (char *)NULL);
617 				new->e_len[cnt] = MAXPATHLEN;
618 				break;
619 			}
620 		if (!*p) {
621 			new->e_argv[cnt] = *argv;
622 			new->e_len[cnt] = 0;
623 		}
624 	}
625 	new->e_argv[cnt] = new->e_orig[cnt] = NULL;
626 
627 	*argvp = argv + 1;
628 	return new;
629 }
630 
631 int
632 f_flags(plan, entry)
633 	PLAN *plan;
634 	FTSENT *entry;
635 {
636 	u_long flags;
637 
638 	flags = entry->fts_statp->st_flags;
639 	if (plan->flags & F_ATLEAST)
640 		return (flags | plan->fl_flags) == flags &&
641 		    !(flags & plan->fl_notflags);
642 	else if (plan->flags & F_ANY)
643 		return (flags & plan->fl_flags) ||
644 		    (flags | plan->fl_notflags) != flags;
645 	else
646 		return flags == plan->fl_flags &&
647 		    !(plan->fl_flags & plan->fl_notflags);
648 }
649 
650 PLAN *
651 c_flags(option, argvp)
652 	OPTION *option;
653 	char ***argvp;
654 {
655 	char *flags_str;
656 	PLAN *new;
657 	u_long flags, notflags;
658 
659 	flags_str = nextarg(option, argvp);
660 	ftsoptions &= ~FTS_NOSTAT;
661 
662 	new = palloc(option);
663 
664 	if (*flags_str == '-') {
665 		new->flags |= F_ATLEAST;
666 		flags_str++;
667 	} else if (*flags_str == '+') {
668 		new->flags |= F_ANY;
669 		flags_str++;
670 	}
671 	if (strtofflags(&flags_str, &flags, &notflags) == 1)
672 		errx(1, "%s: %s: illegal flags string", option->name, flags_str);
673 
674 	new->fl_flags = flags;
675 	new->fl_notflags = notflags;
676 	return new;
677 }
678 
679 /*
680  * -follow functions --
681  *
682  *	Always true, causes symbolic links to be followed on a global
683  *	basis.
684  */
685 PLAN *
686 c_follow(option, argvp)
687 	OPTION *option;
688 	char ***argvp __unused;
689 {
690 	ftsoptions &= ~FTS_PHYSICAL;
691 	ftsoptions |= FTS_LOGICAL;
692 
693 	return palloc(option);
694 }
695 
696 /*
697  * -fstype functions --
698  *
699  *	True if the file is of a certain type.
700  */
701 int
702 f_fstype(plan, entry)
703 	PLAN *plan;
704 	FTSENT *entry;
705 {
706 	static dev_t curdev;	/* need a guaranteed illegal dev value */
707 	static int first = 1;
708 	struct statfs sb;
709 	static int val_type, val_flags;
710 	char *p, save[2];
711 
712 	if ((plan->flags & F_MTMASK) == F_MTUNKNOWN)
713 		return 0;
714 
715 	/* Only check when we cross mount point. */
716 	if (first || curdev != entry->fts_statp->st_dev) {
717 		curdev = entry->fts_statp->st_dev;
718 
719 		/*
720 		 * Statfs follows symlinks; find wants the link's file system,
721 		 * not where it points.
722 		 */
723 		if (entry->fts_info == FTS_SL ||
724 		    entry->fts_info == FTS_SLNONE) {
725 			if ((p = strrchr(entry->fts_accpath, '/')) != NULL)
726 				++p;
727 			else
728 				p = entry->fts_accpath;
729 			save[0] = p[0];
730 			p[0] = '.';
731 			save[1] = p[1];
732 			p[1] = '\0';
733 		} else
734 			p = NULL;
735 
736 		if (statfs(entry->fts_accpath, &sb))
737 			err(1, "%s", entry->fts_accpath);
738 
739 		if (p) {
740 			p[0] = save[0];
741 			p[1] = save[1];
742 		}
743 
744 		first = 0;
745 
746 		/*
747 		 * Further tests may need both of these values, so
748 		 * always copy both of them.
749 		 */
750 		val_flags = sb.f_flags;
751 		val_type = sb.f_type;
752 	}
753 	switch (plan->flags & F_MTMASK) {
754 	case F_MTFLAG:
755 		return val_flags & plan->mt_data;
756 	case F_MTTYPE:
757 		return val_type == plan->mt_data;
758 	default:
759 		abort();
760 	}
761 }
762 
763 #if !defined(__NetBSD__)
764 PLAN *
765 c_fstype(option, argvp)
766 	OPTION *option;
767 	char ***argvp;
768 {
769 	char *fsname;
770 	PLAN *new;
771 	struct vfsconf vfc;
772 
773 	fsname = nextarg(option, argvp);
774 	ftsoptions &= ~FTS_NOSTAT;
775 
776 	new = palloc(option);
777 
778 	/*
779 	 * Check first for a filesystem name.
780 	 */
781 	if (getvfsbyname(fsname, &vfc) == 0) {
782 		new->flags |= F_MTTYPE;
783 		new->mt_data = vfc.vfc_typenum;
784 		return new;
785 	}
786 
787 	switch (*fsname) {
788 	case 'l':
789 		if (!strcmp(fsname, "local")) {
790 			new->flags |= F_MTFLAG;
791 			new->mt_data = MNT_LOCAL;
792 			return new;
793 		}
794 		break;
795 	case 'r':
796 		if (!strcmp(fsname, "rdonly")) {
797 			new->flags |= F_MTFLAG;
798 			new->mt_data = MNT_RDONLY;
799 			return new;
800 		}
801 		break;
802 	}
803 
804 	/*
805 	 * We need to make filesystem checks for filesystems
806 	 * that exists but aren't in the kernel work.
807 	 */
808 	fprintf(stderr, "Warning: Unknown filesystem type %s\n", fsname);
809 	new->flags |= F_MTUNKNOWN;
810 	return new;
811 }
812 #endif /* __NetBSD__ */
813 
814 /*
815  * -group gname functions --
816  *
817  *	True if the file belongs to the group gname.  If gname is numeric and
818  *	an equivalent of the getgrnam() function does not return a valid group
819  *	name, gname is taken as a group ID.
820  */
821 int
822 f_group(plan, entry)
823 	PLAN *plan;
824 	FTSENT *entry;
825 {
826 	return entry->fts_statp->st_gid == plan->g_data;
827 }
828 
829 PLAN *
830 c_group(option, argvp)
831 	OPTION *option;
832 	char ***argvp;
833 {
834 	char *gname;
835 	PLAN *new;
836 	struct group *g;
837 	gid_t gid;
838 
839 	gname = nextarg(option, argvp);
840 	ftsoptions &= ~FTS_NOSTAT;
841 
842 	g = getgrnam(gname);
843 	if (g == NULL) {
844 		gid = atoi(gname);
845 		if (gid == 0 && gname[0] != '0')
846 			errx(1, "%s: %s: no such group", option->name, gname);
847 	} else
848 		gid = g->gr_gid;
849 
850 	new = palloc(option);
851 	new->g_data = gid;
852 	return new;
853 }
854 
855 /*
856  * -inum n functions --
857  *
858  *	True if the file has inode # n.
859  */
860 int
861 f_inum(plan, entry)
862 	PLAN *plan;
863 	FTSENT *entry;
864 {
865 	COMPARE(entry->fts_statp->st_ino, plan->i_data);
866 }
867 
868 PLAN *
869 c_inum(option, argvp)
870 	OPTION *option;
871 	char ***argvp;
872 {
873 	char *inum_str;
874 	PLAN *new;
875 
876 	inum_str = nextarg(option, argvp);
877 	ftsoptions &= ~FTS_NOSTAT;
878 
879 	new = palloc(option);
880 	new->i_data = find_parsenum(new, option->name, inum_str, NULL);
881 	return new;
882 }
883 
884 /*
885  * -links n functions --
886  *
887  *	True if the file has n links.
888  */
889 int
890 f_links(plan, entry)
891 	PLAN *plan;
892 	FTSENT *entry;
893 {
894 	COMPARE(entry->fts_statp->st_nlink, plan->l_data);
895 }
896 
897 PLAN *
898 c_links(option, argvp)
899 	OPTION *option;
900 	char ***argvp;
901 {
902 	char *nlinks;
903 	PLAN *new;
904 
905 	nlinks = nextarg(option, argvp);
906 	ftsoptions &= ~FTS_NOSTAT;
907 
908 	new = palloc(option);
909 	new->l_data = (nlink_t)find_parsenum(new, option->name, nlinks, NULL);
910 	return new;
911 }
912 
913 /*
914  * -ls functions --
915  *
916  *	Always true - prints the current entry to stdout in "ls" format.
917  */
918 int
919 f_ls(plan, entry)
920 	PLAN *plan __unused;
921 	FTSENT *entry;
922 {
923 	printlong(entry->fts_path, entry->fts_accpath, entry->fts_statp);
924 	return 1;
925 }
926 
927 PLAN *
928 c_ls(option, argvp)
929 	OPTION *option;
930 	char ***argvp __unused;
931 {
932 	ftsoptions &= ~FTS_NOSTAT;
933 	isoutput = 1;
934 
935 	return palloc(option);
936 }
937 
938 /*
939  * -name functions --
940  *
941  *	True if the basename of the filename being examined
942  *	matches pattern using Pattern Matching Notation S3.14
943  */
944 int
945 f_name(plan, entry)
946 	PLAN *plan;
947 	FTSENT *entry;
948 {
949 	return !fnmatch(plan->c_data, entry->fts_name,
950 	    plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
951 }
952 
953 PLAN *
954 c_name(option, argvp)
955 	OPTION *option;
956 	char ***argvp;
957 {
958 	char *pattern;
959 	PLAN *new;
960 
961 	pattern = nextarg(option, argvp);
962 	new = palloc(option);
963 	new->c_data = pattern;
964 	return new;
965 }
966 
967 /*
968  * -newer file functions --
969  *
970  *	True if the current file has been modified more recently
971  *	then the modification time of the file named by the pathname
972  *	file.
973  */
974 int
975 f_newer(plan, entry)
976 	PLAN *plan;
977 	FTSENT *entry;
978 {
979 	if (plan->flags & F_TIME_C)
980 		return entry->fts_statp->st_ctime > plan->t_data;
981 	else if (plan->flags & F_TIME_A)
982 		return entry->fts_statp->st_atime > plan->t_data;
983 	else
984 		return entry->fts_statp->st_mtime > plan->t_data;
985 }
986 
987 PLAN *
988 c_newer(option, argvp)
989 	OPTION *option;
990 	char ***argvp;
991 {
992 	char *fn_or_tspec;
993 	PLAN *new;
994 	struct stat sb;
995 
996 	fn_or_tspec = nextarg(option, argvp);
997 	ftsoptions &= ~FTS_NOSTAT;
998 
999 	new = palloc(option);
1000 	/* compare against what */
1001 	if (option->flags & F_TIME2_T) {
1002 		new->t_data = get_date(fn_or_tspec, (struct timeb *) 0);
1003 		if (new->t_data == (time_t) -1)
1004 			errx(1, "Can't parse date/time: %s", fn_or_tspec);
1005 	} else {
1006 		if (stat(fn_or_tspec, &sb))
1007 			err(1, "%s", fn_or_tspec);
1008 		if (option->flags & F_TIME2_C)
1009 			new->t_data = sb.st_ctime;
1010 		else if (option->flags & F_TIME2_A)
1011 			new->t_data = sb.st_atime;
1012 		else
1013 			new->t_data = sb.st_mtime;
1014 	}
1015 	return new;
1016 }
1017 
1018 /*
1019  * -nogroup functions --
1020  *
1021  *	True if file belongs to a user ID for which the equivalent
1022  *	of the getgrnam() 9.2.1 [POSIX.1] function returns NULL.
1023  */
1024 int
1025 f_nogroup(plan, entry)
1026 	PLAN *plan __unused;
1027 	FTSENT *entry;
1028 {
1029 	return group_from_gid(entry->fts_statp->st_gid, 1) == NULL;
1030 }
1031 
1032 PLAN *
1033 c_nogroup(option, argvp)
1034 	OPTION *option;
1035 	char ***argvp __unused;
1036 {
1037 	ftsoptions &= ~FTS_NOSTAT;
1038 
1039 	return palloc(option);
1040 }
1041 
1042 /*
1043  * -nouser functions --
1044  *
1045  *	True if file belongs to a user ID for which the equivalent
1046  *	of the getpwuid() 9.2.2 [POSIX.1] function returns NULL.
1047  */
1048 int
1049 f_nouser(plan, entry)
1050 	PLAN *plan __unused;
1051 	FTSENT *entry;
1052 {
1053 	return user_from_uid(entry->fts_statp->st_uid, 1) == NULL;
1054 }
1055 
1056 PLAN *
1057 c_nouser(option, argvp)
1058 	OPTION *option;
1059 	char ***argvp __unused;
1060 {
1061 	ftsoptions &= ~FTS_NOSTAT;
1062 
1063 	return palloc(option);
1064 }
1065 
1066 /*
1067  * -path functions --
1068  *
1069  *	True if the path of the filename being examined
1070  *	matches pattern using Pattern Matching Notation S3.14
1071  */
1072 int
1073 f_path(plan, entry)
1074 	PLAN *plan;
1075 	FTSENT *entry;
1076 {
1077 	return !fnmatch(plan->c_data, entry->fts_path,
1078 	    plan->flags & F_IGNCASE ? FNM_CASEFOLD : 0);
1079 }
1080 
1081 /* c_path is the same as c_name */
1082 
1083 /*
1084  * -perm functions --
1085  *
1086  *	The mode argument is used to represent file mode bits.  If it starts
1087  *	with a leading digit, it's treated as an octal mode, otherwise as a
1088  *	symbolic mode.
1089  */
1090 int
1091 f_perm(plan, entry)
1092 	PLAN *plan;
1093 	FTSENT *entry;
1094 {
1095 	mode_t mode;
1096 
1097 	mode = entry->fts_statp->st_mode &
1098 	    (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO);
1099 	if (plan->flags & F_ATLEAST)
1100 		return (plan->m_data | mode) == mode;
1101 	else if (plan->flags & F_ANY)
1102 		return (mode & plan->m_data);
1103 	else
1104 		return mode == plan->m_data;
1105 	/* NOTREACHED */
1106 }
1107 
1108 PLAN *
1109 c_perm(option, argvp)
1110 	OPTION *option;
1111 	char ***argvp;
1112 {
1113 	char *perm;
1114 	PLAN *new;
1115 	mode_t *set;
1116 
1117 	perm = nextarg(option, argvp);
1118 	ftsoptions &= ~FTS_NOSTAT;
1119 
1120 	new = palloc(option);
1121 
1122 	if (*perm == '-') {
1123 		new->flags |= F_ATLEAST;
1124 		++perm;
1125 	} else if (*perm == '+') {
1126 		new->flags |= F_ANY;
1127 		++perm;
1128 	}
1129 
1130 	if ((set = setmode(perm)) == NULL)
1131 		errx(1, "%s: %s: illegal mode string", option->name, perm);
1132 
1133 	new->m_data = getmode(set, 0);
1134 	free(set);
1135 	return new;
1136 }
1137 
1138 /*
1139  * -print functions --
1140  *
1141  *	Always true, causes the current pathame to be written to
1142  *	standard output.
1143  */
1144 int
1145 f_print(plan, entry)
1146 	PLAN *plan __unused;
1147 	FTSENT *entry;
1148 {
1149 	(void)puts(entry->fts_path);
1150 	return 1;
1151 }
1152 
1153 PLAN *
1154 c_print(option, argvp)
1155 	OPTION *option;
1156 	char ***argvp __unused;
1157 {
1158 	isoutput = 1;
1159 
1160 	return palloc(option);
1161 }
1162 
1163 /*
1164  * -print0 functions --
1165  *
1166  *	Always true, causes the current pathame to be written to
1167  *	standard output followed by a NUL character
1168  */
1169 int
1170 f_print0(plan, entry)
1171 	PLAN *plan __unused;
1172 	FTSENT *entry;
1173 {
1174 	fputs(entry->fts_path, stdout);
1175 	fputc('\0', stdout);
1176 	return 1;
1177 }
1178 
1179 /* c_print0 is the same as c_print */
1180 
1181 /*
1182  * -prune functions --
1183  *
1184  *	Prune a portion of the hierarchy.
1185  */
1186 int
1187 f_prune(plan, entry)
1188 	PLAN *plan __unused;
1189 	FTSENT *entry;
1190 {
1191 	extern FTS *tree;
1192 
1193 	if (fts_set(tree, entry, FTS_SKIP))
1194 		err(1, "%s", entry->fts_path);
1195 	return 1;
1196 }
1197 
1198 /* c_prune == c_simple */
1199 
1200 /*
1201  * -regex functions --
1202  *
1203  *	True if the whole path of the file matches pattern using
1204  *	regular expression.
1205  */
1206 int
1207 f_regex(plan, entry)
1208 	PLAN *plan;
1209 	FTSENT *entry;
1210 {
1211 	char *str;
1212 	size_t len;
1213 	regex_t *pre;
1214 	regmatch_t pmatch;
1215 	int errcode;
1216 	char errbuf[LINE_MAX];
1217 	int matched;
1218 
1219 	pre = plan->re_data;
1220 	str = entry->fts_path;
1221 	len = strlen(str);
1222 	matched = 0;
1223 
1224 	pmatch.rm_so = 0;
1225 	pmatch.rm_eo = len;
1226 
1227 	errcode = regexec(pre, str, 1, &pmatch, REG_STARTEND);
1228 
1229 	if (errcode != 0 && errcode != REG_NOMATCH) {
1230 		regerror(errcode, pre, errbuf, sizeof errbuf);
1231 		errx(1, "%s: %s",
1232 		     plan->flags & F_IGNCASE ? "-iregex" : "-regex", errbuf);
1233 	}
1234 
1235 	if (errcode == 0 && pmatch.rm_so == 0 && pmatch.rm_eo == len)
1236 		matched = 1;
1237 
1238 	return matched;
1239 }
1240 
1241 PLAN *
1242 c_regex(option, argvp)
1243 	OPTION *option;
1244 	char ***argvp;
1245 {
1246 	PLAN *new;
1247 	char *pattern;
1248 	regex_t *pre;
1249 	int errcode;
1250 	char errbuf[LINE_MAX];
1251 
1252 	if ((pre = malloc(sizeof(regex_t))) == NULL)
1253 		err(1, NULL);
1254 
1255 	pattern = nextarg(option, argvp);
1256 
1257 	if ((errcode = regcomp(pre, pattern,
1258 	    regexp_flags | (option->flags & F_IGNCASE ? REG_ICASE : 0))) != 0) {
1259 		regerror(errcode, pre, errbuf, sizeof errbuf);
1260 		errx(1, "%s: %s: %s",
1261 		     option->flags & F_IGNCASE ? "-iregex" : "-regex",
1262 		     pattern, errbuf);
1263 	}
1264 
1265 	new = palloc(option);
1266 	new->re_data = pre;
1267 
1268 	return new;
1269 }
1270 
1271 /* c_simple covers c_prune, c_openparen, c_closeparen, c_not, c_or */
1272 
1273 PLAN *
1274 c_simple(option, argvp)
1275 	OPTION *option;
1276 	char ***argvp __unused;
1277 {
1278 	return palloc(option);
1279 }
1280 
1281 /*
1282  * -size n[c] functions --
1283  *
1284  *	True if the file size in bytes, divided by an implementation defined
1285  *	value and rounded up to the next integer, is n.  If n is followed by
1286  *	a c, the size is in bytes.
1287  */
1288 #define	FIND_SIZE	512
1289 static int divsize = 1;
1290 
1291 int
1292 f_size(plan, entry)
1293 	PLAN *plan;
1294 	FTSENT *entry;
1295 {
1296 	off_t size;
1297 
1298 	size = divsize ? (entry->fts_statp->st_size + FIND_SIZE - 1) /
1299 	    FIND_SIZE : entry->fts_statp->st_size;
1300 	COMPARE(size, plan->o_data);
1301 }
1302 
1303 PLAN *
1304 c_size(option, argvp)
1305 	OPTION *option;
1306 	char ***argvp;
1307 {
1308 	char *size_str;
1309 	PLAN *new;
1310 	char endch;
1311 
1312 	size_str = nextarg(option, argvp);
1313 	ftsoptions &= ~FTS_NOSTAT;
1314 
1315 	new = palloc(option);
1316 	endch = 'c';
1317 	new->o_data = find_parsenum(new, option->name, size_str, &endch);
1318 	if (endch == 'c')
1319 		divsize = 0;
1320 	return new;
1321 }
1322 
1323 /*
1324  * -type c functions --
1325  *
1326  *	True if the type of the file is c, where c is b, c, d, p, f or w
1327  *	for block special file, character special file, directory, FIFO,
1328  *	regular file or whiteout respectively.
1329  */
1330 int
1331 f_type(plan, entry)
1332 	PLAN *plan;
1333 	FTSENT *entry;
1334 {
1335 	return (entry->fts_statp->st_mode & S_IFMT) == plan->m_data;
1336 }
1337 
1338 PLAN *
1339 c_type(option, argvp)
1340 	OPTION *option;
1341 	char ***argvp;
1342 {
1343 	char *typestring;
1344 	PLAN *new;
1345 	mode_t  mask;
1346 
1347 	typestring = nextarg(option, argvp);
1348 	ftsoptions &= ~FTS_NOSTAT;
1349 
1350 	switch (typestring[0]) {
1351 	case 'b':
1352 		mask = S_IFBLK;
1353 		break;
1354 	case 'c':
1355 		mask = S_IFCHR;
1356 		break;
1357 	case 'd':
1358 		mask = S_IFDIR;
1359 		break;
1360 	case 'f':
1361 		mask = S_IFREG;
1362 		break;
1363 	case 'l':
1364 		mask = S_IFLNK;
1365 		break;
1366 	case 'p':
1367 		mask = S_IFIFO;
1368 		break;
1369 	case 's':
1370 		mask = S_IFSOCK;
1371 		break;
1372 #ifdef FTS_WHITEOUT
1373 	case 'w':
1374 		mask = S_IFWHT;
1375 		ftsoptions |= FTS_WHITEOUT;
1376 		break;
1377 #endif /* FTS_WHITEOUT */
1378 	default:
1379 		errx(1, "%s: %s: unknown type", option->name, typestring);
1380 	}
1381 
1382 	new = palloc(option);
1383 	new->m_data = mask;
1384 	return new;
1385 }
1386 
1387 /*
1388  * -user uname functions --
1389  *
1390  *	True if the file belongs to the user uname.  If uname is numeric and
1391  *	an equivalent of the getpwnam() S9.2.2 [POSIX.1] function does not
1392  *	return a valid user name, uname is taken as a user ID.
1393  */
1394 int
1395 f_user(plan, entry)
1396 	PLAN *plan;
1397 	FTSENT *entry;
1398 {
1399 	return entry->fts_statp->st_uid == plan->u_data;
1400 }
1401 
1402 PLAN *
1403 c_user(option, argvp)
1404 	OPTION *option;
1405 	char ***argvp;
1406 {
1407 	char *username;
1408 	PLAN *new;
1409 	struct passwd *p;
1410 	uid_t uid;
1411 
1412 	username = nextarg(option, argvp);
1413 	ftsoptions &= ~FTS_NOSTAT;
1414 
1415 	p = getpwnam(username);
1416 	if (p == NULL) {
1417 		uid = atoi(username);
1418 		if (uid == 0 && username[0] != '0')
1419 			errx(1, "%s: %s: no such user", option->name, username);
1420 	} else
1421 		uid = p->pw_uid;
1422 
1423 	new = palloc(option);
1424 	new->u_data = uid;
1425 	return new;
1426 }
1427 
1428 /*
1429  * -xdev functions --
1430  *
1431  *	Always true, causes find not to decend past directories that have a
1432  *	different device ID (st_dev, see stat() S5.6.2 [POSIX.1])
1433  */
1434 PLAN *
1435 c_xdev(option, argvp)
1436 	OPTION *option;
1437 	char ***argvp __unused;
1438 {
1439 	ftsoptions |= FTS_XDEV;
1440 
1441 	return palloc(option);
1442 }
1443 
1444 /*
1445  * ( expression ) functions --
1446  *
1447  *	True if expression is true.
1448  */
1449 int
1450 f_expr(plan, entry)
1451 	PLAN *plan;
1452 	FTSENT *entry;
1453 {
1454 	PLAN *p;
1455 	int state = 0;
1456 
1457 	for (p = plan->p_data[0];
1458 	    p && (state = (p->execute)(p, entry)); p = p->next);
1459 	return state;
1460 }
1461 
1462 /*
1463  * f_openparen and f_closeparen nodes are temporary place markers.  They are
1464  * eliminated during phase 2 of find_formplan() --- the '(' node is converted
1465  * to a f_expr node containing the expression and the ')' node is discarded.
1466  * The functions themselves are only used as constants.
1467  */
1468 
1469 int
1470 f_openparen(plan, entry)
1471 	PLAN *plan __unused;
1472 	FTSENT *entry __unused;
1473 {
1474 	abort();
1475 }
1476 
1477 int
1478 f_closeparen(plan, entry)
1479 	PLAN *plan __unused;
1480 	FTSENT *entry __unused;
1481 {
1482 	abort();
1483 }
1484 
1485 /* c_openparen == c_simple */
1486 /* c_closeparen == c_simple */
1487 
1488 /*
1489  * AND operator. Since AND is implicit, no node is allocated.
1490  */
1491 PLAN *
1492 c_and(option, argvp)
1493 	OPTION *option __unused;
1494 	char ***argvp __unused;
1495 {
1496 	return NULL;
1497 }
1498 
1499 /*
1500  * ! expression functions --
1501  *
1502  *	Negation of a primary; the unary NOT operator.
1503  */
1504 int
1505 f_not(plan, entry)
1506 	PLAN *plan;
1507 	FTSENT *entry;
1508 {
1509 	PLAN *p;
1510 	int state = 0;
1511 
1512 	for (p = plan->p_data[0];
1513 	    p && (state = (p->execute)(p, entry)); p = p->next);
1514 	return !state;
1515 }
1516 
1517 /* c_not == c_simple */
1518 
1519 /*
1520  * expression -o expression functions --
1521  *
1522  *	Alternation of primaries; the OR operator.  The second expression is
1523  * not evaluated if the first expression is true.
1524  */
1525 int
1526 f_or(plan, entry)
1527 	PLAN *plan;
1528 	FTSENT *entry;
1529 {
1530 	PLAN *p;
1531 	int state = 0;
1532 
1533 	for (p = plan->p_data[0];
1534 	    p && (state = (p->execute)(p, entry)); p = p->next);
1535 
1536 	if (state)
1537 		return 1;
1538 
1539 	for (p = plan->p_data[1];
1540 	    p && (state = (p->execute)(p, entry)); p = p->next);
1541 	return state;
1542 }
1543 
1544 /* c_or == c_simple */
1545