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