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