xref: /freebsd/usr.bin/find/function.c (revision 2ad872c5794e4c26fdf6ed219ad3f09ca0d5304a)
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 	extern int dotfd;
397 	register int cnt;
398 	pid_t pid;
399 	int status;
400 	char *file;
401 
402 	/* XXX - if file/dir ends in '/' this will not work -- can it? */
403 	if ((file = strrchr(entry->fts_path, '/')))
404 	    file++;
405 	else
406 	    file = entry->fts_path;
407 
408 	for (cnt = 0; plan->e_argv[cnt]; ++cnt)
409 		if (plan->e_len[cnt])
410 			brace_subst(plan->e_orig[cnt], &plan->e_argv[cnt],
411 			    file, plan->e_len[cnt]);
412 
413 	/* don't mix output of command with find output */
414 	fflush(stdout);
415 	fflush(stderr);
416 
417 	switch (pid = fork()) {
418 	case -1:
419 		err(1, "fork");
420 		/* NOTREACHED */
421 	case 0:
422 		execvp(plan->e_argv[0], plan->e_argv);
423 		warn("%s", plan->e_argv[0]);
424 		_exit(1);
425 	}
426 	pid = waitpid(pid, &status, 0);
427 	return (pid != -1 && WIFEXITED(status) && !WEXITSTATUS(status));
428 }
429 
430 /*
431  * c_execdir --
432  *	build three parallel arrays, one with pointers to the strings passed
433  *	on the command line, one with (possibly duplicated) pointers to the
434  *	argv array, and one with integer values that are lengths of the
435  *	strings, but also flags meaning that the string has to be massaged.
436  */
437 PLAN *
438 c_execdir(argvp)
439 	char ***argvp;
440 {
441 	PLAN *new;			/* node returned */
442 	register int cnt;
443 	register char **argv, **ap, *p;
444 
445 	ftsoptions &= ~FTS_NOSTAT;
446 	isoutput = 1;
447 
448 	new = palloc(N_EXECDIR, f_execdir);
449 
450 	for (ap = argv = *argvp;; ++ap) {
451 		if (!*ap)
452 			errx(1,
453 			    "-execdir: no terminating \";\"");
454 		if (**ap == ';')
455 			break;
456 	}
457 
458 	cnt = ap - *argvp + 1;
459 	new->e_argv = (char **)emalloc((u_int)cnt * sizeof(char *));
460 	new->e_orig = (char **)emalloc((u_int)cnt * sizeof(char *));
461 	new->e_len = (int *)emalloc((u_int)cnt * sizeof(int));
462 
463 	for (argv = *argvp, cnt = 0; argv < ap; ++argv, ++cnt) {
464 		new->e_orig[cnt] = *argv;
465 		for (p = *argv; *p; ++p)
466 			if (p[0] == '{' && p[1] == '}') {
467 				new->e_argv[cnt] = emalloc((u_int)MAXPATHLEN);
468 				new->e_len[cnt] = MAXPATHLEN;
469 				break;
470 			}
471 		if (!*p) {
472 			new->e_argv[cnt] = *argv;
473 			new->e_len[cnt] = 0;
474 		}
475 	}
476 	new->e_argv[cnt] = new->e_orig[cnt] = NULL;
477 
478 	*argvp = argv + 1;
479 	return (new);
480 }
481 
482 /*
483  * -follow functions --
484  *
485  *	Always true, causes symbolic links to be followed on a global
486  *	basis.
487  */
488 PLAN *
489 c_follow()
490 {
491 	ftsoptions &= ~FTS_PHYSICAL;
492 	ftsoptions |= FTS_LOGICAL;
493 
494 	return (palloc(N_FOLLOW, f_always_true));
495 }
496 
497 /*
498  * -fstype functions --
499  *
500  *	True if the file is of a certain type.
501  */
502 int
503 f_fstype(plan, entry)
504 	PLAN *plan;
505 	FTSENT *entry;
506 {
507 	static dev_t curdev;	/* need a guaranteed illegal dev value */
508 	static int first = 1;
509 	struct statfs sb;
510 	static int val_type, val_flags;
511 	char *p, save[2];
512 
513 	/* Only check when we cross mount point. */
514 	if (first || curdev != entry->fts_statp->st_dev) {
515 		curdev = entry->fts_statp->st_dev;
516 
517 		/*
518 		 * Statfs follows symlinks; find wants the link's file system,
519 		 * not where it points.
520 		 */
521 		if (entry->fts_info == FTS_SL ||
522 		    entry->fts_info == FTS_SLNONE) {
523 			if ((p = strrchr(entry->fts_accpath, '/')) != NULL)
524 				++p;
525 			else
526 				p = entry->fts_accpath;
527 			save[0] = p[0];
528 			p[0] = '.';
529 			save[1] = p[1];
530 			p[1] = '\0';
531 
532 		} else
533 			p = NULL;
534 
535 		if (statfs(entry->fts_accpath, &sb))
536 			err(1, "%s", entry->fts_accpath);
537 
538 		if (p) {
539 			p[0] = save[0];
540 			p[1] = save[1];
541 		}
542 
543 		first = 0;
544 
545 		/*
546 		 * Further tests may need both of these values, so
547 		 * always copy both of them.
548 		 */
549 		val_flags = sb.f_flags;
550 		val_type = sb.f_type;
551 	}
552 	switch (plan->flags) {
553 	case F_MTFLAG:
554 		return (val_flags & plan->mt_data) != 0;
555 	case F_MTTYPE:
556 		return (val_type == plan->mt_data);
557 	default:
558 		abort();
559 	}
560 }
561 
562 #if !defined(__NetBSD__)
563 PLAN *
564 c_fstype(arg)
565 	char *arg;
566 {
567 	register PLAN *new;
568 	struct vfsconf vfc;
569 
570 	ftsoptions &= ~FTS_NOSTAT;
571 
572 	new = palloc(N_FSTYPE, f_fstype);
573 
574 	/*
575 	 * Check first for a filesystem name.
576 	 */
577 	if (getvfsbyname(arg, &vfc) == 0) {
578 		new->flags = F_MTTYPE;
579 		new->mt_data = vfc.vfc_typenum;
580 		return (new);
581 	}
582 
583 	switch (*arg) {
584 	case 'l':
585 		if (!strcmp(arg, "local")) {
586 			new->flags = F_MTFLAG;
587 			new->mt_data = MNT_LOCAL;
588 			return (new);
589 		}
590 		break;
591 	case 'r':
592 		if (!strcmp(arg, "rdonly")) {
593 			new->flags = F_MTFLAG;
594 			new->mt_data = MNT_RDONLY;
595 			return (new);
596 		}
597 		break;
598 	}
599 	errx(1, "%s: unknown file type", arg);
600 	/* NOTREACHED */
601 }
602 #endif
603 
604 /*
605  * -group gname functions --
606  *
607  *	True if the file belongs to the group gname.  If gname is numeric and
608  *	an equivalent of the getgrnam() function does not return a valid group
609  *	name, gname is taken as a group ID.
610  */
611 int
612 f_group(plan, entry)
613 	PLAN *plan;
614 	FTSENT *entry;
615 {
616 	return (entry->fts_statp->st_gid == plan->g_data);
617 }
618 
619 PLAN *
620 c_group(gname)
621 	char *gname;
622 {
623 	PLAN *new;
624 	struct group *g;
625 	gid_t gid;
626 
627 	ftsoptions &= ~FTS_NOSTAT;
628 
629 	g = getgrnam(gname);
630 	if (g == NULL) {
631 		gid = atoi(gname);
632 		if (gid == 0 && gname[0] != '0')
633 			errx(1, "-group: %s: no such group", gname);
634 	} else
635 		gid = g->gr_gid;
636 
637 	new = palloc(N_GROUP, f_group);
638 	new->g_data = gid;
639 	return (new);
640 }
641 
642 /*
643  * -inum n functions --
644  *
645  *	True if the file has inode # n.
646  */
647 int
648 f_inum(plan, entry)
649 	PLAN *plan;
650 	FTSENT *entry;
651 {
652 	COMPARE(entry->fts_statp->st_ino, plan->i_data);
653 }
654 
655 PLAN *
656 c_inum(arg)
657 	char *arg;
658 {
659 	PLAN *new;
660 
661 	ftsoptions &= ~FTS_NOSTAT;
662 
663 	new = palloc(N_INUM, f_inum);
664 	new->i_data = find_parsenum(new, "-inum", arg, NULL);
665 	return (new);
666 }
667 
668 /*
669  * -links n functions --
670  *
671  *	True if the file has n links.
672  */
673 int
674 f_links(plan, entry)
675 	PLAN *plan;
676 	FTSENT *entry;
677 {
678 	COMPARE(entry->fts_statp->st_nlink, plan->l_data);
679 }
680 
681 PLAN *
682 c_links(arg)
683 	char *arg;
684 {
685 	PLAN *new;
686 
687 	ftsoptions &= ~FTS_NOSTAT;
688 
689 	new = palloc(N_LINKS, f_links);
690 	new->l_data = (nlink_t)find_parsenum(new, "-links", arg, NULL);
691 	return (new);
692 }
693 
694 /*
695  * -ls functions --
696  *
697  *	Always true - prints the current entry to stdout in "ls" format.
698  */
699 int
700 f_ls(plan, entry)
701 	PLAN *plan;
702 	FTSENT *entry;
703 {
704 	printlong(entry->fts_path, entry->fts_accpath, entry->fts_statp);
705 	return (1);
706 }
707 
708 PLAN *
709 c_ls()
710 {
711 	ftsoptions &= ~FTS_NOSTAT;
712 	isoutput = 1;
713 
714 	return (palloc(N_LS, f_ls));
715 }
716 
717 /*
718  * -mtime n functions --
719  *
720  *	True if the difference between the file modification time and the
721  *	current time is n 24 hour periods.
722  */
723 int
724 f_mtime(plan, entry)
725 	PLAN *plan;
726 	FTSENT *entry;
727 {
728 	extern time_t now;
729 
730 	COMPARE((now - entry->fts_statp->st_mtime + 86400 - 1) /
731 	    86400, plan->t_data);
732 }
733 
734 PLAN *
735 c_mtime(arg)
736 	char *arg;
737 {
738 	PLAN *new;
739 
740 	ftsoptions &= ~FTS_NOSTAT;
741 
742 	new = palloc(N_MTIME, f_mtime);
743 	new->t_data = find_parsenum(new, "-mtime", arg, NULL);
744 	TIME_CORRECT(new, N_MTIME);
745 	return (new);
746 }
747 
748 /*
749  * -mmin n functions --
750  *
751  *	True if the difference between the file modification time and the
752  *	current time is n min periods.
753  */
754 int
755 f_mmin(plan, entry)
756 	PLAN *plan;
757 	FTSENT *entry;
758 {
759 	extern time_t now;
760 
761 	COMPARE((now - entry->fts_statp->st_mtime + 60 - 1) /
762 	    60, plan->t_data);
763 }
764 
765 PLAN *
766 c_mmin(arg)
767 	char *arg;
768 {
769 	PLAN *new;
770 
771 	ftsoptions &= ~FTS_NOSTAT;
772 
773 	new = palloc(N_MMIN, f_mmin);
774 	new->t_data = find_parsenum(new, "-mmin", arg, NULL);
775 	TIME_CORRECT(new, N_MMIN);
776 	return (new);
777 }
778 
779 
780 /*
781  * -name functions --
782  *
783  *	True if the basename of the filename being examined
784  *	matches pattern using Pattern Matching Notation S3.14
785  */
786 int
787 f_name(plan, entry)
788 	PLAN *plan;
789 	FTSENT *entry;
790 {
791 	return (!fnmatch(plan->c_data, entry->fts_name, 0));
792 }
793 
794 PLAN *
795 c_name(pattern)
796 	char *pattern;
797 {
798 	PLAN *new;
799 
800 	new = palloc(N_NAME, f_name);
801 	new->c_data = pattern;
802 	return (new);
803 }
804 
805 /*
806  * -newer file functions --
807  *
808  *	True if the current file has been modified more recently
809  *	then the modification time of the file named by the pathname
810  *	file.
811  */
812 int
813 f_newer(plan, entry)
814 	PLAN *plan;
815 	FTSENT *entry;
816 {
817 	return (entry->fts_statp->st_mtime > plan->t_data);
818 }
819 
820 PLAN *
821 c_newer(filename)
822 	char *filename;
823 {
824 	PLAN *new;
825 	struct stat sb;
826 
827 	ftsoptions &= ~FTS_NOSTAT;
828 
829 	if (stat(filename, &sb))
830 		err(1, "%s", filename);
831 	new = palloc(N_NEWER, f_newer);
832 	new->t_data = sb.st_mtime;
833 	return (new);
834 }
835 
836 /*
837  * -nogroup functions --
838  *
839  *	True if file belongs to a user ID for which the equivalent
840  *	of the getgrnam() 9.2.1 [POSIX.1] function returns NULL.
841  */
842 int
843 f_nogroup(plan, entry)
844 	PLAN *plan;
845 	FTSENT *entry;
846 {
847 	char *group_from_gid();
848 
849 	return (group_from_gid(entry->fts_statp->st_gid, 1) ? 0 : 1);
850 }
851 
852 PLAN *
853 c_nogroup()
854 {
855 	ftsoptions &= ~FTS_NOSTAT;
856 
857 	return (palloc(N_NOGROUP, f_nogroup));
858 }
859 
860 /*
861  * -nouser functions --
862  *
863  *	True if file belongs to a user ID for which the equivalent
864  *	of the getpwuid() 9.2.2 [POSIX.1] function returns NULL.
865  */
866 int
867 f_nouser(plan, entry)
868 	PLAN *plan;
869 	FTSENT *entry;
870 {
871 	char *user_from_uid();
872 
873 	return (user_from_uid(entry->fts_statp->st_uid, 1) ? 0 : 1);
874 }
875 
876 PLAN *
877 c_nouser()
878 {
879 	ftsoptions &= ~FTS_NOSTAT;
880 
881 	return (palloc(N_NOUSER, f_nouser));
882 }
883 
884 /*
885  * -path functions --
886  *
887  *	True if the path of the filename being examined
888  *	matches pattern using Pattern Matching Notation S3.14
889  */
890 int
891 f_path(plan, entry)
892 	PLAN *plan;
893 	FTSENT *entry;
894 {
895 	return (!fnmatch(plan->c_data, entry->fts_path, 0));
896 }
897 
898 PLAN *
899 c_path(pattern)
900 	char *pattern;
901 {
902 	PLAN *new;
903 
904 	new = palloc(N_NAME, f_path);
905 	new->c_data = pattern;
906 	return (new);
907 }
908 
909 /*
910  * -perm functions --
911  *
912  *	The mode argument is used to represent file mode bits.  If it starts
913  *	with a leading digit, it's treated as an octal mode, otherwise as a
914  *	symbolic mode.
915  */
916 int
917 f_perm(plan, entry)
918 	PLAN *plan;
919 	FTSENT *entry;
920 {
921 	mode_t mode;
922 
923 	mode = entry->fts_statp->st_mode &
924 	    (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO);
925 	if (plan->flags == F_ATLEAST)
926 		return ((plan->m_data | mode) == mode);
927 	else
928 		return (mode == plan->m_data);
929 	/* NOTREACHED */
930 }
931 
932 PLAN *
933 c_perm(perm)
934 	char *perm;
935 {
936 	PLAN *new;
937 	mode_t *set;
938 
939 	ftsoptions &= ~FTS_NOSTAT;
940 
941 	new = palloc(N_PERM, f_perm);
942 
943 	if (*perm == '-') {
944 		new->flags = F_ATLEAST;
945 		++perm;
946 	}
947 
948 	if ((set = setmode(perm)) == NULL)
949 		err(1, "-perm: %s: illegal mode string", perm);
950 
951 	new->m_data = getmode(set, 0);
952 	free(set);
953 	return (new);
954 }
955 
956 /*
957  * -print functions --
958  *
959  *	Always true, causes the current pathame to be written to
960  *	standard output.
961  */
962 int
963 f_print(plan, entry)
964 	PLAN *plan;
965 	FTSENT *entry;
966 {
967 	(void)puts(entry->fts_path);
968 	return (1);
969 }
970 
971 PLAN *
972 c_print()
973 {
974 	isoutput = 1;
975 
976 	return (palloc(N_PRINT, f_print));
977 }
978 
979 /*
980  * -print0 functions --
981  *
982  *	Always true, causes the current pathame to be written to
983  *	standard output followed by a NUL character
984  */
985 int
986 f_print0(plan, entry)
987 	PLAN *plan;
988 	FTSENT *entry;
989 {
990 	fputs(entry->fts_path, stdout);
991 	fputc('\0', stdout);
992 	return (1);
993 }
994 
995 PLAN *
996 c_print0()
997 {
998 	isoutput = 1;
999 
1000 	return (palloc(N_PRINT0, f_print0));
1001 }
1002 
1003 /*
1004  * -prune functions --
1005  *
1006  *	Prune a portion of the hierarchy.
1007  */
1008 int
1009 f_prune(plan, entry)
1010 	PLAN *plan;
1011 	FTSENT *entry;
1012 {
1013 	extern FTS *tree;
1014 
1015 	if (fts_set(tree, entry, FTS_SKIP))
1016 		err(1, "%s", entry->fts_path);
1017 	return (1);
1018 }
1019 
1020 PLAN *
1021 c_prune()
1022 {
1023 	return (palloc(N_PRUNE, f_prune));
1024 }
1025 
1026 /*
1027  * -size n[c] functions --
1028  *
1029  *	True if the file size in bytes, divided by an implementation defined
1030  *	value and rounded up to the next integer, is n.  If n is followed by
1031  *	a c, the size is in bytes.
1032  */
1033 #define	FIND_SIZE	512
1034 static int divsize = 1;
1035 
1036 int
1037 f_size(plan, entry)
1038 	PLAN *plan;
1039 	FTSENT *entry;
1040 {
1041 	off_t size;
1042 
1043 	size = divsize ? (entry->fts_statp->st_size + FIND_SIZE - 1) /
1044 	    FIND_SIZE : entry->fts_statp->st_size;
1045 	COMPARE(size, plan->o_data);
1046 }
1047 
1048 PLAN *
1049 c_size(arg)
1050 	char *arg;
1051 {
1052 	PLAN *new;
1053 	char endch;
1054 
1055 	ftsoptions &= ~FTS_NOSTAT;
1056 
1057 	new = palloc(N_SIZE, f_size);
1058 	endch = 'c';
1059 	new->o_data = find_parsenum(new, "-size", arg, &endch);
1060 	if (endch == 'c')
1061 		divsize = 0;
1062 	return (new);
1063 }
1064 
1065 /*
1066  * -type c functions --
1067  *
1068  *	True if the type of the file is c, where c is b, c, d, p, f or w
1069  *	for block special file, character special file, directory, FIFO,
1070  *	regular file or whiteout respectively.
1071  */
1072 int
1073 f_type(plan, entry)
1074 	PLAN *plan;
1075 	FTSENT *entry;
1076 {
1077 	return ((entry->fts_statp->st_mode & S_IFMT) == plan->m_data);
1078 }
1079 
1080 PLAN *
1081 c_type(typestring)
1082 	char *typestring;
1083 {
1084 	PLAN *new;
1085 	mode_t  mask;
1086 
1087 	ftsoptions &= ~FTS_NOSTAT;
1088 
1089 	switch (typestring[0]) {
1090 	case 'b':
1091 		mask = S_IFBLK;
1092 		break;
1093 	case 'c':
1094 		mask = S_IFCHR;
1095 		break;
1096 	case 'd':
1097 		mask = S_IFDIR;
1098 		break;
1099 	case 'f':
1100 		mask = S_IFREG;
1101 		break;
1102 	case 'l':
1103 		mask = S_IFLNK;
1104 		break;
1105 	case 'p':
1106 		mask = S_IFIFO;
1107 		break;
1108 	case 's':
1109 		mask = S_IFSOCK;
1110 		break;
1111 #ifdef FTS_WHITEOUT
1112 	case 'w':
1113 		mask = S_IFWHT;
1114 		ftsoptions |= FTS_WHITEOUT;
1115 		break;
1116 #endif /* FTS_WHITEOUT */
1117 	default:
1118 		errx(1, "-type: %s: unknown type", typestring);
1119 	}
1120 
1121 	new = palloc(N_TYPE, f_type);
1122 	new->m_data = mask;
1123 	return (new);
1124 }
1125 
1126 /*
1127  * -delete functions --
1128  *
1129  *	True always.  Makes it's best shot and continues on regardless.
1130  */
1131 int
1132 f_delete(plan, entry)
1133 	PLAN *plan;
1134 	FTSENT *entry;
1135 {
1136 	/* ignore these from fts */
1137 	if (strcmp(entry->fts_accpath, ".") == 0 ||
1138 	    strcmp(entry->fts_accpath, "..") == 0)
1139 		return (1);
1140 
1141 	/* sanity check */
1142 	if (isdepth == 0 ||			/* depth off */
1143 	    (ftsoptions & FTS_NOSTAT) ||	/* not stat()ing */
1144 	    !(ftsoptions & FTS_PHYSICAL) ||	/* physical off */
1145 	    (ftsoptions & FTS_LOGICAL))		/* or finally, logical on */
1146 		errx(1, "-delete: insecure options got turned on");
1147 
1148 	/* Potentially unsafe - do not accept relative paths whatsoever */
1149 	if (strchr(entry->fts_accpath, '/') != NULL)
1150 		errx(1, "-delete: %s: relative path potentially not safe",
1151 			entry->fts_accpath);
1152 
1153 	/* Turn off user immutable bits if running as root */
1154 	if ((entry->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
1155 	    !(entry->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
1156 	    geteuid() == 0)
1157 		chflags(entry->fts_accpath,
1158 		       entry->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
1159 
1160 	/* rmdir directories, unlink everything else */
1161 	if (S_ISDIR(entry->fts_statp->st_mode)) {
1162 		if (rmdir(entry->fts_accpath) < 0 && errno != ENOTEMPTY)
1163 			warn("-delete: rmdir(%s)", entry->fts_path);
1164 	} else {
1165 		if (unlink(entry->fts_accpath) < 0)
1166 			warn("-delete: unlink(%s)", entry->fts_path);
1167 	}
1168 
1169 	/* "succeed" */
1170 	return (1);
1171 }
1172 
1173 PLAN *
1174 c_delete()
1175 {
1176 
1177 	ftsoptions &= ~FTS_NOSTAT;	/* no optimise */
1178 	ftsoptions |= FTS_PHYSICAL;	/* disable -follow */
1179 	ftsoptions &= ~FTS_LOGICAL;	/* disable -follow */
1180 	isoutput = 1;			/* possible output */
1181 	isdepth = 1;			/* -depth implied */
1182 
1183 	return (palloc(N_DELETE, f_delete));
1184 }
1185 
1186 /*
1187  * -user uname functions --
1188  *
1189  *	True if the file belongs to the user uname.  If uname is numeric and
1190  *	an equivalent of the getpwnam() S9.2.2 [POSIX.1] function does not
1191  *	return a valid user name, uname is taken as a user ID.
1192  */
1193 int
1194 f_user(plan, entry)
1195 	PLAN *plan;
1196 	FTSENT *entry;
1197 {
1198 	return (entry->fts_statp->st_uid == plan->u_data);
1199 }
1200 
1201 PLAN *
1202 c_user(username)
1203 	char *username;
1204 {
1205 	PLAN *new;
1206 	struct passwd *p;
1207 	uid_t uid;
1208 
1209 	ftsoptions &= ~FTS_NOSTAT;
1210 
1211 	p = getpwnam(username);
1212 	if (p == NULL) {
1213 		uid = atoi(username);
1214 		if (uid == 0 && username[0] != '0')
1215 			errx(1, "-user: %s: no such user", username);
1216 	} else
1217 		uid = p->pw_uid;
1218 
1219 	new = palloc(N_USER, f_user);
1220 	new->u_data = uid;
1221 	return (new);
1222 }
1223 
1224 /*
1225  * -xdev functions --
1226  *
1227  *	Always true, causes find not to decend past directories that have a
1228  *	different device ID (st_dev, see stat() S5.6.2 [POSIX.1])
1229  */
1230 PLAN *
1231 c_xdev()
1232 {
1233 	ftsoptions |= FTS_XDEV;
1234 
1235 	return (palloc(N_XDEV, f_always_true));
1236 }
1237 
1238 /*
1239  * ( expression ) functions --
1240  *
1241  *	True if expression is true.
1242  */
1243 int
1244 f_expr(plan, entry)
1245 	PLAN *plan;
1246 	FTSENT *entry;
1247 {
1248 	register PLAN *p;
1249 	register int state;
1250 
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 	for (p = plan->p_data[0];
1287 	    p && (state = (p->eval)(p, entry)); p = p->next);
1288 	return (!state);
1289 }
1290 
1291 PLAN *
1292 c_not()
1293 {
1294 	return (palloc(N_NOT, f_not));
1295 }
1296 
1297 /*
1298  * expression -o expression functions --
1299  *
1300  *	Alternation of primaries; the OR operator.  The second expression is
1301  * not evaluated if the first expression is true.
1302  */
1303 int
1304 f_or(plan, entry)
1305 	PLAN *plan;
1306 	FTSENT *entry;
1307 {
1308 	register PLAN *p;
1309 	register int state;
1310 
1311 	for (p = plan->p_data[0];
1312 	    p && (state = (p->eval)(p, entry)); p = p->next);
1313 
1314 	if (state)
1315 		return (1);
1316 
1317 	for (p = plan->p_data[1];
1318 	    p && (state = (p->eval)(p, entry)); p = p->next);
1319 	return (state);
1320 }
1321 
1322 PLAN *
1323 c_or()
1324 {
1325 	return (palloc(N_OR, f_or));
1326 }
1327 
1328 static PLAN *
1329 palloc(t, f)
1330 	enum ntype t;
1331 	int (*f) __P((PLAN *, FTSENT *));
1332 {
1333 	PLAN *new;
1334 
1335 	if ((new = malloc(sizeof(PLAN))) == NULL)
1336 		err(1, NULL);
1337 	new->type = t;
1338 	new->eval = f;
1339 	new->flags = 0;
1340 	new->next = NULL;
1341 	return (new);
1342 }
1343