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