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