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