Sweep-fix comparing pointers with 0 (and assigning 0 to pointers).
[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  */
39
40 #include <sys/param.h>
41 #include <sys/ucred.h>
42 #include <sys/stat.h>
43 #include <sys/types.h>
44 #include <sys/wait.h>
45 #include <sys/mount.h>
46 #include <sys/timeb.h>
47
48 #include <dirent.h>
49 #include <err.h>
50 #include <errno.h>
51 #include <fnmatch.h>
52 #include <fts.h>
53 #include <grp.h>
54 #include <limits.h>
55 #include <pwd.h>
56 #include <regex.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 #include <ctype.h>
62
63 #include "find.h"
64
65 static PLAN *palloc(OPTION *);
66 static long long find_parsenum(PLAN *, const char *, char *, char *);
67 static long long find_parsetime(PLAN *, const char *, char *);
68 static char *nextarg(OPTION *, char ***);
69
70 extern char **environ;
71
72 #define COMPARE(a, b) do {                                              \
73         switch (plan->flags & F_ELG_MASK) {                             \
74         case F_EQUAL:                                                   \
75                 return (a == b);                                        \
76         case F_LESSTHAN:                                                \
77                 return (a < b);                                         \
78         case F_GREATER:                                                 \
79                 return (a > b);                                         \
80         default:                                                        \
81                 abort();                                                \
82         }                                                               \
83 } while(0)
84
85 static PLAN *
86 palloc(OPTION *option)
87 {
88         PLAN *new;
89
90         if ((new = malloc(sizeof(PLAN))) == NULL)
91                 err(1, NULL);
92         new->execute = option->execute;
93         new->flags = option->flags;
94         new->next = NULL;
95         return new;
96 }
97
98 /*
99  * find_parsenum --
100  *      Parse a string of the form [+-]# and return the value.
101  */
102 static long long
103 find_parsenum(PLAN *plan, const char *option, char *vp, char *endch)
104 {
105         long long value;
106         char *endchar, *str;    /* Pointer to character ending conversion. */
107
108         /* Determine comparison from leading + or -. */
109         str = vp;
110         switch (*str) {
111         case '+':
112                 ++str;
113                 plan->flags |= F_GREATER;
114                 break;
115         case '-':
116                 ++str;
117                 plan->flags |= F_LESSTHAN;
118                 break;
119         default:
120                 plan->flags |= F_EQUAL;
121                 break;
122         }
123
124         /*
125          * Convert the string with strtoq().  Note, if strtoq() returns zero
126          * and endchar points to the beginning of the string we know we have
127          * a syntax error.
128          */
129         value = strtoq(str, &endchar, 10);
130         if (value == 0 && endchar == str)
131                 errx(1, "%s: %s: illegal numeric value", option, vp);
132         if (endchar[0] && (endch == NULL || endchar[0] != *endch))
133                 errx(1, "%s: %s: illegal trailing character", option, vp);
134         if (endch)
135                 *endch = endchar[0];
136         return value;
137 }
138
139 /*
140  * find_parsetime --
141  *      Parse a string of the form [+-]([0-9]+[smhdw]?)+ and return the value.
142  */
143 static long long
144 find_parsetime(PLAN *plan, const char *option, char *vp)
145 {
146         long long secs, value;
147         char *str, *unit;       /* Pointer to character ending conversion. */
148
149         /* Determine comparison from leading + or -. */
150         str = vp;
151         switch (*str) {
152         case '+':
153                 ++str;
154                 plan->flags |= F_GREATER;
155                 break;
156         case '-':
157                 ++str;
158                 plan->flags |= F_LESSTHAN;
159                 break;
160         default:
161                 plan->flags |= F_EQUAL;
162                 break;
163         }
164
165         value = strtoq(str, &unit, 10);
166         if (value == 0 && unit == str) {
167                 errx(1, "%s: %s: illegal time value", option, vp);
168                 /* NOTREACHED */
169         }
170         if (*unit == '\0')
171                 return value;
172
173         /* Units syntax. */
174         secs = 0;
175         for (;;) {
176                 switch(*unit) {
177                 case 's':       /* seconds */
178                         secs += value;
179                         break;
180                 case 'm':       /* minutes */
181                         secs += value * 60;
182                         break;
183                 case 'h':       /* hours */
184                         secs += value * 3600;
185                         break;
186                 case 'd':       /* days */
187                         secs += value * 86400;
188                         break;
189                 case 'w':       /* weeks */
190                         secs += value * 604800;
191                         break;
192                 default:
193                         errx(1, "%s: %s: bad unit '%c'", option, vp, *unit);
194                         /* NOTREACHED */
195                 }
196                 str = unit + 1;
197                 if (*str == '\0')       /* EOS */
198                         break;
199                 value = strtoq(str, &unit, 10);
200                 if (value == 0 && unit == str) {
201                         errx(1, "%s: %s: illegal time value", option, vp);
202                         /* NOTREACHED */
203                 }
204                 if (*unit == '\0') {
205                         errx(1, "%s: %s: missing trailing unit", option, vp);
206                         /* NOTREACHED */
207                 }
208         }
209         plan->flags |= F_EXACTTIME;
210         return secs;
211 }
212
213 /*
214  * nextarg --
215  *      Check that another argument still exists, return a pointer to it,
216  *      and increment the argument vector pointer.
217  */
218 static char *
219 nextarg(OPTION *option, char ***argvp)
220 {
221         char *arg;
222
223         if ((arg = **argvp) == NULL)
224                 errx(1, "%s: requires additional arguments", option->name);
225         (*argvp)++;
226         return arg;
227 } /* nextarg() */
228
229 /*
230  * The value of n for the inode times (atime, ctime, and mtime) is a range,
231  * i.e. n matches from (n - 1) to n 24 hour periods.  This interacts with
232  * -n, such that "-mtime -1" would be less than 0 days, which isn't what the
233  * user wanted.  Correct so that -1 is "less than 1".
234  */
235 #define TIME_CORRECT(p) \
236         if (((p)->flags & F_ELG_MASK) == F_LESSTHAN) \
237                 ++((p)->t_data);
238
239 /*
240  * -[acm]min n functions --
241  *
242  *    True if the difference between the
243  *              file access time (-amin)
244  *              last change of file status information (-cmin)
245  *              file modification time (-mmin)
246  *    and the current time is n min periods.
247  */
248 int
249 f_Xmin(PLAN *plan, FTSENT *entry)
250 {
251         if (plan->flags & F_TIME_C) {
252                 COMPARE((now - entry->fts_statp->st_ctime +
253                     60 - 1) / 60, plan->t_data);
254         } else if (plan->flags & F_TIME_A) {
255                 COMPARE((now - entry->fts_statp->st_atime +
256                     60 - 1) / 60, plan->t_data);
257         } else {
258                 COMPARE((now - entry->fts_statp->st_mtime +
259                     60 - 1) / 60, plan->t_data);
260         }
261 }
262
263 PLAN *
264 c_Xmin(OPTION *option, char ***argvp)
265 {
266         char *nmins;
267         PLAN *new;
268
269         nmins = nextarg(option, argvp);
270         ftsoptions &= ~FTS_NOSTAT;
271
272         new = palloc(option);
273         new->t_data = find_parsenum(new, option->name, nmins, NULL);
274         TIME_CORRECT(new);
275         return new;
276 }
277
278 /*
279  * -[acm]time n functions --
280  *
281  *      True if the difference between the
282  *              file access time (-atime)
283  *              last change of file status information (-ctime)
284  *              file modification time (-mtime)
285  *      and the current time is n 24 hour periods.
286  */
287
288 int
289 f_Xtime(PLAN *plan, FTSENT *entry)
290 {
291         time_t xtime;
292
293         if (plan->flags & F_TIME_A)
294                 xtime = entry->fts_statp->st_atime;
295         else if (plan->flags & F_TIME_C)
296                 xtime = entry->fts_statp->st_ctime;
297         else
298                 xtime = entry->fts_statp->st_mtime;
299
300         if (plan->flags & F_EXACTTIME)
301                 COMPARE(now - xtime, plan->t_data);
302         else
303                 COMPARE((now - xtime + 86400 - 1) / 86400, plan->t_data);
304 }
305
306 PLAN *
307 c_Xtime(OPTION *option, char ***argvp)
308 {
309         char *value;
310         PLAN *new;
311
312         value = nextarg(option, argvp);
313         ftsoptions &= ~FTS_NOSTAT;
314
315         new = palloc(option);
316         new->t_data = find_parsetime(new, option->name, value);
317         if (!(new->flags & F_EXACTTIME))
318                 TIME_CORRECT(new);
319         return new;
320 }
321
322 /*
323  * -maxdepth/-mindepth n functions --
324  *
325  *        Does the same as -prune if the level of the current file is
326  *        greater/less than the specified maximum/minimum depth.
327  *
328  *        Note that -maxdepth and -mindepth are handled specially in
329  *        find_execute() so their f_* functions are set to f_always_true().
330  */
331 PLAN *
332 c_mXXdepth(OPTION *option, char ***argvp)
333 {
334         char *dstr;
335         PLAN *new;
336
337         dstr = nextarg(option, argvp);
338         if (dstr[0] == '-')
339                 /* all other errors handled by find_parsenum() */
340                 errx(1, "%s: %s: value must be positive", option->name, dstr);
341
342         new = palloc(option);
343         if (option->flags & F_MAXDEPTH)
344                 maxdepth = find_parsenum(new, option->name, dstr, NULL);
345         else
346                 mindepth = find_parsenum(new, option->name, dstr, NULL);
347         return new;
348 }
349
350 /*
351  * -delete functions --
352  *
353  *      True always.  Makes its best shot and continues on regardless.
354  */
355 int
356 f_delete(PLAN *plan __unused, FTSENT *entry)
357 {
358         /* ignore these from fts */
359         if (strcmp(entry->fts_accpath, ".") == 0 ||
360             strcmp(entry->fts_accpath, "..") == 0)
361                 return 1;
362
363         /* sanity check */
364         if (isdepth == 0 ||                     /* depth off */
365             (ftsoptions & FTS_NOSTAT) ||        /* not stat()ing */
366             !(ftsoptions & FTS_PHYSICAL) ||     /* physical off */
367             (ftsoptions & FTS_LOGICAL))         /* or finally, logical on */
368                 errx(1, "-delete: insecure options got turned on");
369
370         /* Potentially unsafe - do not accept relative paths whatsoever */
371         if (strchr(entry->fts_accpath, '/') != NULL)
372                 errx(1, "-delete: %s: relative path potentially not safe",
373                         entry->fts_accpath);
374
375         /* Turn off user immutable bits if running as root */
376         if ((entry->fts_statp->st_flags & (UF_APPEND|UF_IMMUTABLE)) &&
377             !(entry->fts_statp->st_flags & (SF_APPEND|SF_IMMUTABLE)) &&
378             geteuid() == 0)
379                 chflags(entry->fts_accpath,
380                        entry->fts_statp->st_flags &= ~(UF_APPEND|UF_IMMUTABLE));
381
382         /* rmdir directories, unlink everything else */
383         if (S_ISDIR(entry->fts_statp->st_mode)) {
384                 if (rmdir(entry->fts_accpath) < 0 && errno != ENOTEMPTY)
385                         warn("-delete: rmdir(%s)", entry->fts_path);
386         } else {
387                 if (unlink(entry->fts_accpath) < 0)
388                         warn("-delete: unlink(%s)", entry->fts_path);
389         }
390
391         /* "succeed" */
392         return 1;
393 }
394
395 PLAN *
396 c_delete(OPTION *option, char ***argvp __unused)
397 {
398
399         ftsoptions &= ~FTS_NOSTAT;      /* no optimise */
400         ftsoptions |= FTS_PHYSICAL;     /* disable -follow */
401         ftsoptions &= ~FTS_LOGICAL;     /* disable -follow */
402         isoutput = 1;                   /* possible output */
403         isdepth = 1;                    /* -depth implied */
404
405         return palloc(option);
406 }
407
408
409 /*
410  * always_true --
411  *
412  *      Always true, used for -maxdepth, -mindepth, -xdev and -follow
413  */
414 int
415 f_always_true(PLAN *plan __unused, FTSENT *entry __unused)
416 {
417         return 1;
418 }
419
420 /*
421  * -depth functions --
422  *
423  *      With argument: True if the file is at level n.
424  *      Without argument: Always true, causes descent of the directory hierarchy
425  *      to be done so that all entries in a directory are acted on before the
426  *      directory itself.
427  */
428 int
429 f_depth(PLAN *plan, FTSENT *entry)
430 {
431         if (plan->flags & F_DEPTH)
432                 COMPARE(entry->fts_level, plan->d_data);
433         else
434                 return 1;
435 }
436
437 PLAN *
438 c_depth(OPTION *option, char ***argvp)
439 {
440         PLAN *new;
441         char *str;
442
443         new = palloc(option);
444
445         str = **argvp;
446         if (str && !(new->flags & F_DEPTH)) {
447                 /* skip leading + or - */
448                 if (*str == '+' || *str == '-')
449                         str++;
450                 /* skip sign */
451                 if (*str == '+' || *str == '-')
452                         str++;
453                 if (isdigit(*str))
454                         new->flags |= F_DEPTH;
455         }
456
457         if (new->flags & F_DEPTH) {     /* -depth n */
458                 char *ndepth;
459
460                 ndepth = nextarg(option, argvp);
461                 new->d_data = find_parsenum(new, option->name, ndepth, NULL);
462         } else {                        /* -d */
463                 isdepth = 1;
464         }
465
466         return new;
467 }
468  
469 /*
470  * -empty functions --
471  *
472  *      True if the file or directory is empty
473  */
474 int
475 f_empty(PLAN *plan __unused, FTSENT *entry)
476 {
477         if (S_ISREG(entry->fts_statp->st_mode) &&
478             entry->fts_statp->st_size == 0)
479                 return 1;
480         if (S_ISDIR(entry->fts_statp->st_mode)) {
481                 struct dirent *dp;
482                 int empty;
483                 DIR *dir;
484
485                 empty = 1;
486                 dir = opendir(entry->fts_accpath);
487                 if (dir == NULL)
488                         err(1, "%s", entry->fts_accpath);
489                 for (dp = readdir(dir); dp; dp = readdir(dir))
490                         if (dp->d_name[0] != '.' ||
491                             (dp->d_name[1] != '\0' &&
492                              (dp->d_name[1] != '.' || dp->d_name[2] != '\0'))) {
493                                 empty = 0;
494                                 break;
495                         }
496                 closedir(dir);
497                 return empty;
498         }
499         return 0;
500 }
501
502 PLAN *
503 c_empty(OPTION *option, char ***argvp __unused)
504 {
505         ftsoptions &= ~FTS_NOSTAT;
506
507         return palloc(option);
508 }
509
510 /*
511  * [-exec | -execdir | -ok] utility [arg ... ] ; functions --
512  *
513  *      True if the executed utility returns a zero value as exit status.
514  *      The end of the primary expression is delimited by a semicolon.  If
515  *      "{}" occurs anywhere, it gets replaced by the current pathname,
516  *      or, in the case of -execdir, the current basename (filename
517  *      without leading directory prefix). For -exec and -ok,
518  *      the current directory for the execution of utility is the same as
519  *      the current directory when the find utility was started, whereas
520  *      for -execdir, it is the directory the file resides in.
521  *
522  *      The primary -ok differs from -exec in that it requests affirmation
523  *      of the user before executing the utility.
524  */
525 int
526 f_exec(PLAN *plan, FTSENT *entry)
527 {
528         int cnt;
529         pid_t pid;
530         int status;
531         char *file;
532
533         if (entry == NULL && plan->flags & F_EXECPLUS) {
534                 if (plan->e_ppos == plan->e_pbnum)
535                         return (1);
536                 plan->e_argv[plan->e_ppos] = NULL;
537                 goto doexec;
538         }
539
540         /* XXX - if file/dir ends in '/' this will not work -- can it? */
541         if ((plan->flags & F_EXECDIR) && \
542             (file = strrchr(entry->fts_path, '/')))
543                 file++;
544         else
545                 file = entry->fts_path;
546
547         if (plan->flags & F_EXECPLUS) {
548                 if ((plan->e_argv[plan->e_ppos] = strdup(file)) == NULL)
549                         err(1, NULL);
550                 plan->e_len[plan->e_ppos] = strlen(file);
551                 plan->e_psize += plan->e_len[plan->e_ppos];
552                 if (++plan->e_ppos < plan->e_pnummax &&
553                     plan->e_psize < plan->e_psizemax)
554                         return (1);
555                 plan->e_argv[plan->e_ppos] = NULL;
556         } else {
557                 for (cnt = 0; plan->e_argv[cnt]; ++cnt)
558                         if (plan->e_len[cnt])
559                                 brace_subst(plan->e_orig[cnt],
560                                     &plan->e_argv[cnt], file,
561                                     plan->e_len[cnt]);
562         }
563
564 doexec: if ((plan->flags & F_NEEDOK) && !queryuser(plan->e_argv))
565                 return 0;
566
567         /* make sure find output is interspersed correctly with subprocesses */
568         fflush(stdout);
569         fflush(stderr);
570
571         switch (pid = fork()) {
572         case -1:
573                 err(1, "fork");
574                 /* NOTREACHED */
575         case 0:
576                 /* change dir back from where we started */
577                 if (!(plan->flags & F_EXECDIR) && fchdir(dotfd)) {
578                         warn("chdir");
579                         _exit(1);
580                 }
581                 execvp(plan->e_argv[0], plan->e_argv);
582                 warn("%s", plan->e_argv[0]);
583                 _exit(1);
584         }
585         if (plan->flags & F_EXECPLUS) {
586                 while (--plan->e_ppos >= plan->e_pbnum)
587                         free(plan->e_argv[plan->e_ppos]);
588                 plan->e_ppos = plan->e_pbnum;
589                 plan->e_psize = plan->e_pbsize;
590         }
591         pid = waitpid(pid, &status, 0);
592         return (pid != -1 && WIFEXITED(status) && !WEXITSTATUS(status));
593 }
594
595 /*
596  * c_exec, c_execdir, c_ok --
597  *      build three parallel arrays, one with pointers to the strings passed
598  *      on the command line, one with (possibly duplicated) pointers to the
599  *      argv array, and one with integer values that are lengths of the
600  *      strings, but also flags meaning that the string has to be massaged.
601  */
602 PLAN *
603 c_exec(OPTION *option, char ***argvp)
604 {
605         PLAN *new;                      /* node returned */
606         long argmax;
607         int cnt, i;
608         char **argv, **ap, **ep, *p;
609
610         /* XXX - was in c_execdir, but seems unnecessary!?
611         ftsoptions &= ~FTS_NOSTAT;
612         */
613         isoutput = 1;
614
615         /* XXX - this is a change from the previous coding */
616         new = palloc(option);
617
618         for (ap = argv = *argvp;; ++ap) {
619                 if (!*ap)
620                         errx(1,
621                             "%s: no terminating \";\" or \"+\"", option->name);
622                 if (**ap == ';')
623                         break;
624                 if (**ap == '+' && ap != argv && strcmp(*(ap - 1), "{}") == 0) {
625                         new->flags |= F_EXECPLUS;
626                         break;
627                 }
628         }
629
630         if (ap == argv)
631                 errx(1, "%s: no command specified", option->name);
632
633         cnt = ap - *argvp + 1;
634         if (new->flags & F_EXECPLUS) {
635                 new->e_ppos = new->e_pbnum = cnt - 2;
636                 if ((argmax = sysconf(_SC_ARG_MAX)) == -1) {
637                         warn("sysconf(_SC_ARG_MAX)");
638                         argmax = _POSIX_ARG_MAX;
639                 }
640                 argmax -= 1024;
641                 for (ep = environ; *ep != NULL; ep++)
642                         argmax -= strlen(*ep) + 1 + sizeof(*ep);
643                 argmax -= 1 + sizeof(*ep);
644                 new->e_pnummax = argmax / 16;
645                 argmax -= sizeof(char *) * new->e_pnummax;
646                 if (argmax <= 0)
647                         errx(1, "no space for arguments");
648                 new->e_psizemax = argmax;
649                 new->e_pbsize = 0;
650                 cnt += new->e_pnummax + 1;
651         }
652         if ((new->e_argv = malloc(cnt * sizeof(char *))) == NULL)
653                 err(1, NULL);
654         if ((new->e_orig = malloc(cnt * sizeof(char *))) == NULL)
655                 err(1, NULL);
656         if ((new->e_len = malloc(cnt * sizeof(int))) == NULL)
657                 err(1, NULL);
658
659         for (argv = *argvp, cnt = 0; argv < ap; ++argv, ++cnt) {
660                 new->e_orig[cnt] = *argv;
661                 if (new->flags & F_EXECPLUS)
662                         new->e_pbsize += strlen(*argv) + 1;
663                 for (p = *argv; *p; ++p)
664                         if (!(new->flags & F_EXECPLUS) && p[0] == '{' &&
665                             p[1] == '}') {
666                                 if ((new->e_argv[cnt] =
667                                     malloc(MAXPATHLEN)) == NULL)
668                                         err(1, NULL);
669                                 new->e_len[cnt] = MAXPATHLEN;
670                                 break;
671                         }
672                 if (!*p) {
673                         new->e_argv[cnt] = *argv;
674                         new->e_len[cnt] = 0;
675                 }
676         }
677         if (new->flags & F_EXECPLUS) {
678                 new->e_psize = new->e_pbsize;
679                 cnt--;
680                 for (i = 0; i < new->e_pnummax; i++) {
681                         new->e_argv[cnt] = NULL;
682                         new->e_len[cnt] = 0;
683                         cnt++;
684                 }
685                 argv = ap;
686                 goto done;
687         }
688         new->e_argv[cnt] = new->e_orig[cnt] = NULL;
689
690 done:   *argvp = argv + 1;
691         return new;
692 }
693
694 int
695 f_flags(PLAN *plan, FTSENT *entry)
696 {
697         u_long flags;
698
699         flags = entry->fts_statp->st_flags;
700         if (plan->flags & F_ATLEAST)
701                 return (flags | plan->fl_flags) == flags &&
702                     !(flags & plan->fl_notflags);
703         else if (plan->flags & F_ANY)
704                 return (flags & plan->fl_flags) ||
705                     (flags | plan->fl_notflags) != flags;
706         else
707                 return flags == plan->fl_flags &&
708                     !(plan->fl_flags & plan->fl_notflags);
709 }
710
711 PLAN *
712 c_flags(OPTION *option, char ***argvp)
713 {
714         char *flags_str;
715         PLAN *new;
716         u_long flags, notflags;
717
718         flags_str = nextarg(option, argvp);
719         ftsoptions &= ~FTS_NOSTAT;
720
721         new = palloc(option);
722
723         if (*flags_str == '-') {
724                 new->flags |= F_ATLEAST;
725                 flags_str++;
726         } else if (*flags_str == '+') {
727                 new->flags |= F_ANY;
728                 flags_str++;
729         }
730         if (strtofflags(&flags_str, &flags, &notflags) == 1)
731                 errx(1, "%s: %s: illegal flags string", option->name, flags_str);
732
733         new->fl_flags = flags;
734         new->fl_notflags = notflags;
735         return new;
736 }
737
738 /*
739  * -follow functions --
740  *
741  *      Always true, causes symbolic links to be followed on a global
742  *      basis.
743  */
744 PLAN *
745 c_follow(OPTION *option, char ***argvp __unused)
746 {
747         ftsoptions &= ~FTS_PHYSICAL;
748         ftsoptions |= FTS_LOGICAL;
749
750         return palloc(option);
751 }
752
753 /*
754  * -fstype functions --
755  *
756  *      True if the file is of a certain type.
757  */
758 int
759 f_fstype(PLAN *plan, FTSENT *entry)
760 {
761         static dev_t curdev;    /* need a guaranteed illegal dev value */
762         static int first = 1;
763         struct statfs sb;
764         static int val_type, val_flags;
765         char *p, save[2] = {0,0};
766
767         if ((plan->flags & F_MTMASK) == F_MTUNKNOWN)
768                 return 0;
769
770         /* Only check when we cross mount point. */
771         if (first || curdev != entry->fts_statp->st_dev) {
772                 curdev = entry->fts_statp->st_dev;
773
774                 /*
775                  * Statfs follows symlinks; find wants the link's filesystem,
776                  * not where it points.
777                  */
778                 if (entry->fts_info == FTS_SL ||
779                     entry->fts_info == FTS_SLNONE) {
780                         if ((p = strrchr(entry->fts_accpath, '/')) != NULL)
781                                 ++p;
782                         else
783                                 p = entry->fts_accpath;
784                         save[0] = p[0];
785                         p[0] = '.';
786                         save[1] = p[1];
787                         p[1] = '\0';
788                 } else
789                         p = NULL;
790
791                 if (statfs(entry->fts_accpath, &sb)) {
792                         warn("%s", entry->fts_accpath);
793                         return 0;
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, NULL);
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 */