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