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