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