cvsimport
[findutils.git] / find / pred.c
blobbc26b588122fa5e194362014886868191de711e4
1 /* pred.c -- execute the expression tree.
2 Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2003,
3 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include <config.h>
20 #include "defs.h"
22 #include <fnmatch.h>
23 #include <signal.h>
24 #include <math.h>
25 #include <pwd.h>
26 #include <grp.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <errno.h>
30 #include <assert.h>
31 #include <stdarg.h>
32 #include <fcntl.h>
33 #include <locale.h>
34 #include <openat.h>
35 #include "xalloc.h"
36 #include "dirname.h"
37 #include "human.h"
38 #include "modetype.h"
39 #include "filemode.h"
40 #include "wait.h"
41 #include "printquoted.h"
42 #include "buildcmd.h"
43 #include "yesno.h"
44 #include "listfile.h"
45 #include "stat-time.h"
46 #include "dircallback.h"
47 #include "error.h"
48 #include "verify.h"
50 #if ENABLE_NLS
51 # include <libintl.h>
52 # define _(Text) gettext (Text)
53 #else
54 # define _(Text) Text
55 #endif
56 #ifdef gettext_noop
57 # define N_(String) gettext_noop (String)
58 #else
59 /* See locate.c for explanation as to why not use (String) */
60 # define N_(String) String
61 #endif
63 #if !defined(SIGCHLD) && defined(SIGCLD)
64 #define SIGCHLD SIGCLD
65 #endif
69 #if HAVE_DIRENT_H
70 # include <dirent.h>
71 # define NAMLEN(dirent) strlen((dirent)->d_name)
72 #else
73 # define dirent direct
74 # define NAMLEN(dirent) (dirent)->d_namlen
75 # if HAVE_SYS_NDIR_H
76 # include <sys/ndir.h>
77 # endif
78 # if HAVE_SYS_DIR_H
79 # include <sys/dir.h>
80 # endif
81 # if HAVE_NDIR_H
82 # include <ndir.h>
83 # endif
84 #endif
86 #ifdef CLOSEDIR_VOID
87 /* Fake a return value. */
88 #define CLOSEDIR(d) (closedir (d), 0)
89 #else
90 #define CLOSEDIR(d) closedir (d)
91 #endif
96 /* Get or fake the disk device blocksize.
97 Usually defined by sys/param.h (if at all). */
98 #ifndef DEV_BSIZE
99 # ifdef BSIZE
100 # define DEV_BSIZE BSIZE
101 # else /* !BSIZE */
102 # define DEV_BSIZE 4096
103 # endif /* !BSIZE */
104 #endif /* !DEV_BSIZE */
106 /* Extract or fake data from a `struct stat'.
107 ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
108 ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
109 ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */
110 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
111 # define ST_BLKSIZE(statbuf) DEV_BSIZE
112 # if defined _POSIX_SOURCE || !defined BSIZE /* fileblocks.c uses BSIZE. */
113 # define ST_NBLOCKS(statbuf) \
114 (S_ISREG ((statbuf).st_mode) \
115 || S_ISDIR ((statbuf).st_mode) \
116 ? (statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0) : 0)
117 # else /* !_POSIX_SOURCE && BSIZE */
118 # define ST_NBLOCKS(statbuf) \
119 (S_ISREG ((statbuf).st_mode) \
120 || S_ISDIR ((statbuf).st_mode) \
121 ? st_blocks ((statbuf).st_size) : 0)
122 # endif /* !_POSIX_SOURCE && BSIZE */
123 #else /* HAVE_STRUCT_STAT_ST_BLOCKS */
124 /* Some systems, like Sequents, return st_blksize of 0 on pipes. */
125 # define ST_BLKSIZE(statbuf) ((statbuf).st_blksize > 0 \
126 ? (statbuf).st_blksize : DEV_BSIZE)
127 # if defined hpux || defined __hpux__ || defined __hpux
128 /* HP-UX counts st_blocks in 1024-byte units.
129 This loses when mixing HP-UX and BSD file systems with NFS. */
130 # define ST_NBLOCKSIZE 1024
131 # else /* !hpux */
132 # if defined _AIX && defined _I386
133 /* AIX PS/2 counts st_blocks in 4K units. */
134 # define ST_NBLOCKSIZE (4 * 1024)
135 # else /* not AIX PS/2 */
136 # if defined _CRAY
137 # define ST_NBLOCKS(statbuf) \
138 (S_ISREG ((statbuf).st_mode) \
139 || S_ISDIR ((statbuf).st_mode) \
140 ? (statbuf).st_blocks * ST_BLKSIZE(statbuf)/ST_NBLOCKSIZE : 0)
141 # endif /* _CRAY */
142 # endif /* not AIX PS/2 */
143 # endif /* !hpux */
144 #endif /* HAVE_STRUCT_STAT_ST_BLOCKS */
146 #ifndef ST_NBLOCKS
147 # define ST_NBLOCKS(statbuf) \
148 (S_ISREG ((statbuf).st_mode) \
149 || S_ISDIR ((statbuf).st_mode) \
150 ? (statbuf).st_blocks : 0)
151 #endif
153 #ifndef ST_NBLOCKSIZE
154 # define ST_NBLOCKSIZE 512
155 #endif
158 #undef MAX
159 #define MAX(a, b) ((a) > (b) ? (a) : (b))
161 static boolean match_lname PARAMS((const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case));
163 static char *format_date PARAMS((struct timespec ts, int kind));
164 static char *ctime_format PARAMS((struct timespec ts));
166 #ifdef DEBUG
167 struct pred_assoc
169 PRED_FUNC pred_func;
170 char *pred_name;
173 struct pred_assoc pred_table[] =
175 {pred_amin, "amin "},
176 {pred_and, "and "},
177 {pred_anewer, "anewer "},
178 {pred_atime, "atime "},
179 {pred_closeparen, ") "},
180 {pred_cmin, "cmin "},
181 {pred_cnewer, "cnewer "},
182 {pred_comma, ", "},
183 {pred_ctime, "ctime "},
184 {pred_delete, "delete "},
185 {pred_empty, "empty "},
186 {pred_exec, "exec "},
187 {pred_execdir, "execdir "},
188 {pred_executable, "executable "},
189 {pred_false, "false "},
190 {pred_fprint, "fprint "},
191 {pred_fprint0, "fprint0 "},
192 {pred_fprintf, "fprintf "},
193 {pred_fstype, "fstype "},
194 {pred_gid, "gid "},
195 {pred_group, "group "},
196 {pred_ilname, "ilname "},
197 {pred_iname, "iname "},
198 {pred_inum, "inum "},
199 {pred_ipath, "ipath "},
200 {pred_links, "links "},
201 {pred_lname, "lname "},
202 {pred_ls, "ls "},
203 {pred_mmin, "mmin "},
204 {pred_mtime, "mtime "},
205 {pred_name, "name "},
206 {pred_negate, "not "},
207 {pred_newer, "newer "},
208 {pred_newerXY, "newerXY "},
209 {pred_nogroup, "nogroup "},
210 {pred_nouser, "nouser "},
211 {pred_ok, "ok "},
212 {pred_okdir, "okdir "},
213 {pred_openparen, "( "},
214 {pred_or, "or "},
215 {pred_path, "path "},
216 {pred_perm, "perm "},
217 {pred_print, "print "},
218 {pred_print0, "print0 "},
219 {pred_prune, "prune "},
220 {pred_quit, "quit "},
221 {pred_readable, "readable "},
222 {pred_regex, "regex "},
223 {pred_samefile,"samefile "},
224 {pred_size, "size "},
225 {pred_true, "true "},
226 {pred_type, "type "},
227 {pred_uid, "uid "},
228 {pred_used, "used "},
229 {pred_user, "user "},
230 {pred_writable, "writable "},
231 {pred_xtype, "xtype "},
232 {0, "none "}
234 #endif
236 /* Returns ts1 - ts2 */
237 static double ts_difference(struct timespec ts1,
238 struct timespec ts2)
240 double d = difftime(ts1.tv_sec, ts2.tv_sec)
241 + (1.0e-9 * (ts1.tv_nsec - ts2.tv_nsec));
242 return d;
246 static int
247 compare_ts(struct timespec ts1,
248 struct timespec ts2)
250 if ((ts1.tv_sec == ts2.tv_sec) &&
251 (ts1.tv_nsec == ts2.tv_nsec))
253 return 0;
255 else
257 double diff = ts_difference(ts1, ts2);
258 return diff < 0.0 ? -1 : +1;
262 /* Predicate processing routines.
264 PATHNAME is the full pathname of the file being checked.
265 *STAT_BUF contains information about PATHNAME.
266 *PRED_PTR contains information for applying the predicate.
268 Return true if the file passes this predicate, false if not. */
271 /* pred_timewindow
273 * Returns true if THE_TIME is
274 * COMP_GT: after the specified time
275 * COMP_LT: before the specified time
276 * COMP_EQ: less than WINDOW seconds after the specified time.
278 static boolean
279 pred_timewindow(struct timespec ts, struct predicate const *pred_ptr, int window)
281 switch (pred_ptr->args.reftime.kind)
283 case COMP_GT:
284 return compare_ts(ts, pred_ptr->args.reftime.ts) > 0;
286 case COMP_LT:
287 return compare_ts(ts, pred_ptr->args.reftime.ts) < 0;
289 case COMP_EQ:
291 double delta = ts_difference(ts, pred_ptr->args.reftime.ts);
292 return (delta >= 0.0 && delta < window);
295 assert (0);
296 abort ();
300 boolean
301 pred_amin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
303 (void) &pathname;
304 return pred_timewindow(get_stat_atime(stat_buf), pred_ptr, 60);
307 boolean
308 pred_and (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
310 if (pred_ptr->pred_left == NULL
311 || apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
313 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
315 else
316 return false;
319 boolean
320 pred_anewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
322 (void) &pathname;
323 assert (COMP_GT == pred_ptr->args.reftime.kind);
324 return compare_ts(get_stat_atime(stat_buf), pred_ptr->args.reftime.ts) > 0;
327 boolean
328 pred_atime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
330 (void) &pathname;
331 return pred_timewindow(get_stat_atime(stat_buf), pred_ptr, DAYSECS);
334 boolean
335 pred_closeparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
337 (void) &pathname;
338 (void) &stat_buf;
339 (void) &pred_ptr;
341 return true;
344 boolean
345 pred_cmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
347 (void) pathname;
348 return pred_timewindow(get_stat_ctime(stat_buf), pred_ptr, 60);
351 boolean
352 pred_cnewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
354 (void) pathname;
356 assert (COMP_GT == pred_ptr->args.reftime.kind);
357 return compare_ts(get_stat_ctime(stat_buf), pred_ptr->args.reftime.ts) > 0;
360 boolean
361 pred_comma (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
363 if (pred_ptr->pred_left != NULL)
365 apply_predicate(pathname, stat_buf,pred_ptr->pred_left);
367 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
370 boolean
371 pred_ctime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
373 (void) &pathname;
374 return pred_timewindow(get_stat_ctime(stat_buf), pred_ptr, DAYSECS);
377 static boolean
378 perform_delete(int flags)
380 return 0 == unlinkat(state.cwd_dir_fd, state.rel_pathname, flags);
384 boolean
385 pred_delete (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
387 (void) pred_ptr;
388 (void) stat_buf;
389 if (strcmp (state.rel_pathname, "."))
391 int flags=0;
392 if (state.have_stat && S_ISDIR(stat_buf->st_mode))
393 flags |= AT_REMOVEDIR;
394 if (perform_delete(flags))
396 return true;
398 else
400 if (EISDIR == errno)
402 if ((flags & AT_REMOVEDIR) == 0)
404 /* unlink() operation failed because we should have done rmdir(). */
405 flags |= AT_REMOVEDIR;
406 if (perform_delete(flags))
407 return true;
411 error (0, errno, _("cannot delete %s"),
412 safely_quote_err_filename(0, pathname));
413 /* Previously I had believed that having the -delete action
414 * return false provided the user with control over whether an
415 * error message is issued. While this is true, the policy of
416 * not affecting the exit status is contrary to the POSIX
417 * requirement that diagnostic messages are accompanied by a
418 * nonzero exit status. While -delete is not a POSIX option and
419 * we can therefore opt not to follow POSIX in this case, that
420 * seems somewhat arbitrary and confusing. So, as of
421 * findutils-4.3.11, we also set the exit status in this case.
423 state.exit_status = 1;
424 return false;
426 else
428 /* nothing to do. */
429 return true;
433 boolean
434 pred_empty (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
436 (void) pathname;
437 (void) pred_ptr;
439 if (S_ISDIR (stat_buf->st_mode))
441 int fd;
442 DIR *d;
443 struct dirent *dp;
444 boolean empty = true;
446 errno = 0;
447 if ((fd = openat(state.cwd_dir_fd, state.rel_pathname, O_RDONLY
448 #if defined O_LARGEFILE
449 |O_LARGEFILE
450 #endif
451 )) < 0)
453 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
454 state.exit_status = 1;
455 return false;
457 d = fdopendir (fd);
458 if (d == NULL)
460 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
461 state.exit_status = 1;
462 return false;
464 for (dp = readdir (d); dp; dp = readdir (d))
466 if (dp->d_name[0] != '.'
467 || (dp->d_name[1] != '\0'
468 && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
470 empty = false;
471 break;
474 if (CLOSEDIR (d))
476 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
477 state.exit_status = 1;
478 return false;
480 return (empty);
482 else if (S_ISREG (stat_buf->st_mode))
483 return (stat_buf->st_size == 0);
484 else
485 return (false);
488 static boolean
489 new_impl_pred_exec (int dirfd, const char *pathname,
490 struct stat *stat_buf,
491 struct predicate *pred_ptr,
492 const char *prefix, size_t pfxlen)
494 struct exec_val *execp = &pred_ptr->args.exec_vec;
495 size_t len = strlen(pathname);
497 (void) stat_buf;
498 execp->dirfd = dirfd;
499 if (execp->multiple)
501 /* Push the argument onto the current list.
502 * The command may or may not be run at this point,
503 * depending on the command line length limits.
505 bc_push_arg(&execp->ctl,
506 &execp->state,
507 pathname, len+1,
508 prefix, pfxlen,
511 /* remember that there are pending execdirs. */
512 state.execdirs_outstanding = true;
514 /* POSIX: If the primary expression is punctuated by a plus
515 * sign, the primary shall always evaluate as true
517 return true;
519 else
521 int i;
523 for (i=0; i<execp->num_args; ++i)
525 bc_do_insert(&execp->ctl,
526 &execp->state,
527 execp->replace_vec[i],
528 strlen(execp->replace_vec[i]),
529 prefix, pfxlen,
530 pathname, len,
534 /* Actually invoke the command. */
535 return execp->ctl.exec_callback(&execp->ctl,
536 &execp->state);
541 boolean
542 pred_exec (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
544 return new_impl_pred_exec(get_start_dirfd(),
545 pathname, stat_buf, pred_ptr, NULL, 0);
548 boolean
549 pred_execdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
551 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
552 (void) &pathname;
553 return new_impl_pred_exec (get_current_dirfd(),
554 state.rel_pathname, stat_buf, pred_ptr,
555 prefix, (prefix ? 2 : 0));
558 boolean
559 pred_false (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
561 (void) &pathname;
562 (void) &stat_buf;
563 (void) &pred_ptr;
566 return (false);
569 boolean
570 pred_fls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
572 FILE * stream = pred_ptr->args.printf_vec.stream;
573 list_file (pathname, state.cwd_dir_fd, state.rel_pathname, stat_buf,
574 options.start_time.tv_sec,
575 options.output_block_size,
576 pred_ptr->literal_control_chars, stream);
577 return true;
580 boolean
581 pred_fprint (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
583 (void) &pathname;
584 (void) &stat_buf;
586 print_quoted(pred_ptr->args.printf_vec.stream,
587 pred_ptr->args.printf_vec.quote_opts,
588 pred_ptr->args.printf_vec.dest_is_tty,
589 "%s\n",
590 pathname);
591 return true;
594 boolean
595 pred_fprint0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
597 FILE * fp = pred_ptr->args.printf_vec.stream;
599 (void) &stat_buf;
601 fputs (pathname, fp);
602 putc (0, fp);
603 return true;
608 static char*
609 mode_to_filetype(mode_t m)
611 #define HANDLE_TYPE(t,letter) if (m==t) { return letter; }
612 #ifdef S_IFREG
613 HANDLE_TYPE(S_IFREG, "f"); /* regular file */
614 #endif
615 #ifdef S_IFDIR
616 HANDLE_TYPE(S_IFDIR, "d"); /* directory */
617 #endif
618 #ifdef S_IFLNK
619 HANDLE_TYPE(S_IFLNK, "l"); /* symbolic link */
620 #endif
621 #ifdef S_IFSOCK
622 HANDLE_TYPE(S_IFSOCK, "s"); /* Unix domain socket */
623 #endif
624 #ifdef S_IFBLK
625 HANDLE_TYPE(S_IFBLK, "b"); /* block device */
626 #endif
627 #ifdef S_IFCHR
628 HANDLE_TYPE(S_IFCHR, "c"); /* character device */
629 #endif
630 #ifdef S_IFIFO
631 HANDLE_TYPE(S_IFIFO, "p"); /* FIFO */
632 #endif
633 #ifdef S_IFDOOR
634 HANDLE_TYPE(S_IFDOOR, "D"); /* Door (e.g. on Solaris) */
635 #endif
636 return "U"; /* Unknown */
639 static double
640 file_sparseness(const struct stat *p)
642 #if defined HAVE_STRUCT_STAT_ST_BLOCKS
643 if (0 == p->st_size)
645 if (0 == p->st_blocks)
646 return 1.0;
647 else
648 return p->st_blocks < 0 ? -HUGE_VAL : HUGE_VAL;
650 else
652 double blklen = file_blocksize(p) * (double)p->st_blocks;
653 return blklen / p->st_size;
655 #else
656 return 1.0;
657 #endif
662 static void
663 checked_fprintf(struct format_val *dest, const char *fmt, ...)
665 int rv;
666 va_list ap;
668 va_start(ap, fmt);
669 rv = vfprintf(dest->stream, fmt, ap);
670 if (rv < 0)
671 nonfatal_file_error(dest->filename);
675 static void
676 checked_print_quoted (struct format_val *dest,
677 const char *format, const char *s)
679 int rv = print_quoted(dest->stream, dest->quote_opts, dest->dest_is_tty,
680 format, s);
681 if (rv < 0)
682 nonfatal_file_error(dest->filename);
686 static void
687 checked_fwrite(void *p, size_t siz, size_t nmemb, struct format_val *dest)
689 int items_written = fwrite(p, siz, nmemb, dest->stream);
690 if (items_written < nmemb)
691 nonfatal_file_error(dest->filename);
694 static void
695 checked_fflush(struct format_val *dest)
697 if (0 != fflush(dest->stream))
699 nonfatal_file_error(dest->filename);
703 static void
704 do_fprintf(struct format_val *dest,
705 struct segment *segment,
706 const char *pathname,
707 const struct stat *stat_buf)
709 char hbuf[LONGEST_HUMAN_READABLE + 1];
710 const char *cp;
712 switch (segment->segkind)
714 case KIND_PLAIN: /* Plain text string (no % conversion). */
715 /* trusted */
716 checked_fwrite(segment->text, 1, segment->text_len, dest);
717 break;
719 case KIND_STOP: /* Terminate argument and flush output. */
720 /* trusted */
721 checked_fwrite(segment->text, 1, segment->text_len, dest);
722 checked_fflush(dest);
723 break;
725 case KIND_FORMAT:
726 switch (segment->format_char[0])
728 case 'a': /* atime in `ctime' format. */
729 /* UNTRUSTED, probably unexploitable */
730 checked_fprintf (dest, segment->text, ctime_format (get_stat_atime(stat_buf)));
731 break;
732 case 'b': /* size in 512-byte blocks */
733 /* UNTRUSTED, probably unexploitable */
734 checked_fprintf (dest, segment->text,
735 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
736 hbuf, human_ceiling,
737 ST_NBLOCKSIZE, 512));
738 break;
739 case 'c': /* ctime in `ctime' format */
740 /* UNTRUSTED, probably unexploitable */
741 checked_fprintf (dest, segment->text, ctime_format (get_stat_ctime(stat_buf)));
742 break;
743 case 'd': /* depth in search tree */
744 /* UNTRUSTED, probably unexploitable */
745 checked_fprintf (dest, segment->text, state.curdepth);
746 break;
747 case 'D': /* Device on which file exists (stat.st_dev) */
748 /* trusted */
749 checked_fprintf (dest, segment->text,
750 human_readable ((uintmax_t) stat_buf->st_dev, hbuf,
751 human_ceiling, 1, 1));
752 break;
753 case 'f': /* base name of path */
754 /* sanitised */
756 char *base = base_name (pathname);
757 checked_print_quoted (dest, segment->text, base);
758 free (base);
760 break;
761 case 'F': /* file system type */
762 /* trusted */
763 checked_print_quoted (dest, segment->text, filesystem_type (stat_buf, pathname));
764 break;
765 case 'g': /* group name */
766 /* trusted */
767 /* (well, the actual group is selected by the user but
768 * its name was selected by the system administrator)
771 struct group *g;
773 g = getgrgid (stat_buf->st_gid);
774 if (g)
776 segment->text[segment->text_len] = 's';
777 checked_fprintf (dest, segment->text, g->gr_name);
778 break;
780 else
782 /* Do nothing. */
783 /*FALLTHROUGH*/
786 /*FALLTHROUGH*/ /*...sometimes, so 'G' case.*/
788 case 'G': /* GID number */
789 /* UNTRUSTED, probably unexploitable */
790 checked_fprintf (dest, segment->text,
791 human_readable ((uintmax_t) stat_buf->st_gid, hbuf,
792 human_ceiling, 1, 1));
793 break;
794 case 'h': /* leading directories part of path */
795 /* sanitised */
797 cp = strrchr (pathname, '/');
798 if (cp == NULL) /* No leading directories. */
800 /* If there is no slash in the pathname, we still
801 * print the string because it contains characters
802 * other than just '%s'. The %h expands to ".".
804 checked_print_quoted (dest, segment->text, ".");
806 else
808 char *s = strdup(pathname);
809 s[cp - pathname] = 0;
810 checked_print_quoted (dest, segment->text, s);
811 free(s);
814 break;
816 case 'H': /* ARGV element file was found under */
817 /* trusted */
819 char *s = xmalloc(state.starting_path_length+1);
820 memcpy(s, pathname, state.starting_path_length);
821 s[state.starting_path_length] = 0;
822 checked_fprintf (dest, segment->text, s);
823 free(s);
825 break;
827 case 'i': /* inode number */
828 /* UNTRUSTED, but not exploitable I think */
829 checked_fprintf (dest, segment->text,
830 human_readable ((uintmax_t) stat_buf->st_ino, hbuf,
831 human_ceiling,
832 1, 1));
833 break;
834 case 'k': /* size in 1K blocks */
835 /* UNTRUSTED, but not exploitable I think */
836 checked_fprintf (dest, segment->text,
837 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
838 hbuf, human_ceiling,
839 ST_NBLOCKSIZE, 1024));
840 break;
841 case 'l': /* object of symlink */
842 /* sanitised */
843 #ifdef S_ISLNK
845 char *linkname = 0;
847 if (S_ISLNK (stat_buf->st_mode))
849 linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
850 if (linkname == 0)
851 state.exit_status = 1;
853 if (linkname)
855 checked_print_quoted (dest, segment->text, linkname);
856 free (linkname);
858 else
860 /* We still need to honour the field width etc., so this is
861 * not a no-op.
863 checked_print_quoted (dest, segment->text, "");
866 #endif /* S_ISLNK */
867 break;
869 case 'M': /* mode as 10 chars (eg., "-rwxr-x--x" */
870 /* UNTRUSTED, probably unexploitable */
872 char modestring[16] ;
873 filemodestring (stat_buf, modestring);
874 modestring[10] = '\0';
875 checked_fprintf (dest, segment->text, modestring);
877 break;
879 case 'm': /* mode as octal number (perms only) */
880 /* UNTRUSTED, probably unexploitable */
882 /* Output the mode portably using the traditional numbers,
883 even if the host unwisely uses some other numbering
884 scheme. But help the compiler in the common case where
885 the host uses the traditional numbering scheme. */
886 mode_t m = stat_buf->st_mode;
887 boolean traditional_numbering_scheme =
888 (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000
889 && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100
890 && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010
891 && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001);
892 checked_fprintf (dest, segment->text,
893 (traditional_numbering_scheme
894 ? m & MODE_ALL
895 : ((m & S_ISUID ? 04000 : 0)
896 | (m & S_ISGID ? 02000 : 0)
897 | (m & S_ISVTX ? 01000 : 0)
898 | (m & S_IRUSR ? 00400 : 0)
899 | (m & S_IWUSR ? 00200 : 0)
900 | (m & S_IXUSR ? 00100 : 0)
901 | (m & S_IRGRP ? 00040 : 0)
902 | (m & S_IWGRP ? 00020 : 0)
903 | (m & S_IXGRP ? 00010 : 0)
904 | (m & S_IROTH ? 00004 : 0)
905 | (m & S_IWOTH ? 00002 : 0)
906 | (m & S_IXOTH ? 00001 : 0))));
908 break;
910 case 'n': /* number of links */
911 /* UNTRUSTED, probably unexploitable */
912 checked_fprintf (dest, segment->text,
913 human_readable ((uintmax_t) stat_buf->st_nlink,
914 hbuf,
915 human_ceiling,
916 1, 1));
917 break;
919 case 'p': /* pathname */
920 /* sanitised */
921 checked_print_quoted (dest, segment->text, pathname);
922 break;
924 case 'P': /* pathname with ARGV element stripped */
925 /* sanitised */
926 if (state.curdepth > 0)
928 cp = pathname + state.starting_path_length;
929 if (*cp == '/')
930 /* Move past the slash between the ARGV element
931 and the rest of the pathname. But if the ARGV element
932 ends in a slash, we didn't add another, so we've
933 already skipped past it. */
934 cp++;
936 else
938 cp = "";
940 checked_print_quoted (dest, segment->text, cp);
941 break;
943 case 's': /* size in bytes */
944 /* UNTRUSTED, probably unexploitable */
945 checked_fprintf (dest, segment->text,
946 human_readable ((uintmax_t) stat_buf->st_size,
947 hbuf, human_ceiling, 1, 1));
948 break;
950 case 'S': /* sparseness */
951 /* UNTRUSTED, probably unexploitable */
952 checked_fprintf (dest, segment->text, file_sparseness(stat_buf));;
953 break;
955 case 't': /* mtime in `ctime' format */
956 /* UNTRUSTED, probably unexploitable */
957 checked_fprintf (dest, segment->text,
958 ctime_format (get_stat_mtime(stat_buf)));
959 break;
961 case 'u': /* user name */
962 /* trusted */
963 /* (well, the actual user is selected by the user on systems
964 * where chown is not restricted, but the user name was
965 * selected by the system administrator)
968 struct passwd *p;
970 p = getpwuid (stat_buf->st_uid);
971 if (p)
973 segment->text[segment->text_len] = 's';
974 checked_fprintf (dest, segment->text, p->pw_name);
975 break;
977 /* else fallthru */
979 /* FALLTHROUGH*/ /* .. to case U */
981 case 'U': /* UID number */
982 /* UNTRUSTED, probably unexploitable */
983 checked_fprintf (dest, segment->text,
984 human_readable ((uintmax_t) stat_buf->st_uid, hbuf,
985 human_ceiling, 1, 1));
986 break;
988 /* %Y: type of file system entry like `ls -l`:
989 * (d,-,l,s,p,b,c,n) n=nonexistent(symlink)
991 case 'Y': /* in case of symlink */
992 /* trusted */
994 #ifdef S_ISLNK
995 if (S_ISLNK (stat_buf->st_mode))
997 struct stat sbuf;
998 /* If we would normally follow links, do not do so.
999 * If we would normally not follow links, do so.
1001 if ((following_links() ? lstat : stat)
1002 (state.rel_pathname, &sbuf) != 0)
1004 if ( errno == ENOENT )
1006 checked_fprintf (dest, segment->text, "N");
1007 break;
1009 else if ( errno == ELOOP )
1011 checked_fprintf (dest, segment->text, "L");
1012 break;
1014 else
1016 checked_fprintf (dest, segment->text, "?");
1017 error (0, errno, "%s",
1018 safely_quote_err_filename(0, pathname));
1019 /* exit_status = 1;
1020 return ; */
1021 break;
1024 checked_fprintf (dest, segment->text,
1025 mode_to_filetype(sbuf.st_mode & S_IFMT));
1027 #endif /* S_ISLNK */
1028 else
1030 checked_fprintf (dest, segment->text,
1031 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1034 break;
1036 case 'y':
1037 /* trusted */
1039 checked_fprintf (dest, segment->text,
1040 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1042 break;
1044 /* end of KIND_FORMAT case */
1045 break;
1049 boolean
1050 pred_fprintf (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1052 struct format_val *dest = &pred_ptr->args.printf_vec;
1053 struct segment *segment;
1055 for (segment = dest->segment; segment; segment = segment->next)
1057 if ( (KIND_FORMAT == segment->segkind) && segment->format_char[1]) /* Component of date. */
1059 struct timespec ts;
1060 int valid = 0;
1062 switch (segment->format_char[0])
1064 case 'A':
1065 ts = get_stat_atime(stat_buf);
1066 valid = 1;
1067 break;
1068 case 'B':
1069 ts = get_stat_birthtime(stat_buf);
1070 if ('@' == segment->format_char[1])
1071 valid = 1;
1072 else
1073 valid = (ts.tv_nsec >= 0);
1074 break;
1075 case 'C':
1076 ts = get_stat_ctime(stat_buf);
1077 valid = 1;
1078 break;
1079 case 'T':
1080 ts = get_stat_mtime(stat_buf);
1081 valid = 1;
1082 break;
1083 default:
1084 assert (0);
1085 abort ();
1087 /* We trust the output of format_date not to contain
1088 * nasty characters, though the value of the date
1089 * is itself untrusted data.
1091 if (valid)
1093 /* trusted */
1094 checked_fprintf (dest, segment->text,
1095 format_date (ts, segment->format_char[1]));
1097 else
1099 /* The specified timestamp is not available, output
1100 * nothing for the timestamp, but use the rest (so that
1101 * for example find foo -printf '[%Bs] %p\n' can print
1102 * "[] foo").
1104 /* trusted */
1105 checked_fprintf (dest, segment->text, "");
1108 else
1110 /* Print a segment which is not a date. */
1111 do_fprintf(dest, segment, pathname, stat_buf);
1114 return true;
1117 boolean
1118 pred_fstype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1120 (void) pathname;
1122 if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0)
1123 return true;
1124 else
1125 return false;
1128 boolean
1129 pred_gid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1131 (void) pathname;
1133 switch (pred_ptr->args.numinfo.kind)
1135 case COMP_GT:
1136 if (stat_buf->st_gid > pred_ptr->args.numinfo.l_val)
1137 return (true);
1138 break;
1139 case COMP_LT:
1140 if (stat_buf->st_gid < pred_ptr->args.numinfo.l_val)
1141 return (true);
1142 break;
1143 case COMP_EQ:
1144 if (stat_buf->st_gid == pred_ptr->args.numinfo.l_val)
1145 return (true);
1146 break;
1148 return (false);
1151 boolean
1152 pred_group (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1154 (void) pathname;
1156 if (pred_ptr->args.gid == stat_buf->st_gid)
1157 return (true);
1158 else
1159 return (false);
1162 boolean
1163 pred_ilname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1165 return match_lname (pathname, stat_buf, pred_ptr, true);
1168 /* Common code between -name, -iname. PATHNAME is being visited, STR
1169 is name to compare basename against, and FLAGS are passed to
1170 fnmatch. Recall that 'find / -name /' is one of the few times where a '/'
1171 in the -name must actually find something. */
1172 static boolean
1173 pred_name_common (const char *pathname, const char *str, int flags)
1175 char *p;
1176 boolean b;
1177 /* We used to use last_component() here, but that would not allow us to modify the
1178 * input string, which is const. We could optimise by duplicating the string only
1179 * if we need to modify it, and I'll do that if there is a measurable
1180 * performance difference on a machine built after 1990...
1182 char *base = base_name (pathname);
1183 /* remove trailing slashes, but leave "/" or "//foo" unchanged. */
1184 strip_trailing_slashes(base);
1186 /* FNM_PERIOD is not used here because POSIX requires that it not be.
1187 * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1189 b = fnmatch (str, base, flags) == 0;
1190 free (base);
1191 return b;
1194 boolean
1195 pred_iname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1197 (void) stat_buf;
1198 return pred_name_common (pathname, pred_ptr->args.str, FNM_CASEFOLD);
1201 boolean
1202 pred_inum (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1204 (void) pathname;
1206 switch (pred_ptr->args.numinfo.kind)
1208 case COMP_GT:
1209 if (stat_buf->st_ino > pred_ptr->args.numinfo.l_val)
1210 return (true);
1211 break;
1212 case COMP_LT:
1213 if (stat_buf->st_ino < pred_ptr->args.numinfo.l_val)
1214 return (true);
1215 break;
1216 case COMP_EQ:
1217 if (stat_buf->st_ino == pred_ptr->args.numinfo.l_val)
1218 return (true);
1219 break;
1221 return (false);
1224 boolean
1225 pred_ipath (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1227 (void) stat_buf;
1229 if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0)
1230 return (true);
1231 return (false);
1234 boolean
1235 pred_links (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1237 (void) pathname;
1239 switch (pred_ptr->args.numinfo.kind)
1241 case COMP_GT:
1242 if (stat_buf->st_nlink > pred_ptr->args.numinfo.l_val)
1243 return (true);
1244 break;
1245 case COMP_LT:
1246 if (stat_buf->st_nlink < pred_ptr->args.numinfo.l_val)
1247 return (true);
1248 break;
1249 case COMP_EQ:
1250 if (stat_buf->st_nlink == pred_ptr->args.numinfo.l_val)
1251 return (true);
1252 break;
1254 return (false);
1257 boolean
1258 pred_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1260 return match_lname (pathname, stat_buf, pred_ptr, false);
1263 static boolean
1264 match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case)
1266 boolean ret = false;
1267 #ifdef S_ISLNK
1268 if (S_ISLNK (stat_buf->st_mode))
1270 char *linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
1271 if (linkname)
1273 if (fnmatch (pred_ptr->args.str, linkname,
1274 ignore_case ? FNM_CASEFOLD : 0) == 0)
1275 ret = true;
1276 free (linkname);
1279 #endif /* S_ISLNK */
1280 return ret;
1283 boolean
1284 pred_ls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1286 return pred_fls(pathname, stat_buf, pred_ptr);
1289 boolean
1290 pred_mmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1292 (void) &pathname;
1293 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, 60);
1296 boolean
1297 pred_mtime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1299 (void) pathname;
1300 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, DAYSECS);
1303 boolean
1304 pred_name (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1306 (void) stat_buf;
1307 return pred_name_common (pathname, pred_ptr->args.str, 0);
1310 boolean
1311 pred_negate (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1313 return !apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1316 boolean
1317 pred_newer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1319 (void) pathname;
1321 assert (COMP_GT == pred_ptr->args.reftime.kind);
1322 return compare_ts(get_stat_mtime(stat_buf), pred_ptr->args.reftime.ts) > 0;
1325 boolean
1326 pred_newerXY (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1328 struct timespec ts;
1329 boolean collected = false;
1331 assert (COMP_GT == pred_ptr->args.reftime.kind);
1333 switch (pred_ptr->args.reftime.xval)
1335 case XVAL_TIME:
1336 assert (pred_ptr->args.reftime.xval != XVAL_TIME);
1337 return false;
1339 case XVAL_ATIME:
1340 ts = get_stat_atime(stat_buf);
1341 collected = true;
1342 break;
1344 case XVAL_BIRTHTIME:
1345 ts = get_stat_birthtime(stat_buf);
1346 collected = true;
1347 if (ts.tv_nsec < 0);
1349 /* XXX: Cannot determine birth time. Warn once. */
1350 error(0, 0, _("Warning: cannot determine birth time of file %s"),
1351 safely_quote_err_filename(0, pathname));
1352 return false;
1354 break;
1356 case XVAL_CTIME:
1357 ts = get_stat_ctime(stat_buf);
1358 collected = true;
1359 break;
1361 case XVAL_MTIME:
1362 ts = get_stat_mtime(stat_buf);
1363 collected = true;
1364 break;
1367 assert (collected);
1368 return compare_ts(ts, pred_ptr->args.reftime.ts) > 0;
1371 boolean
1372 pred_nogroup (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1374 (void) pathname;
1375 (void) pred_ptr;
1377 #ifdef CACHE_IDS
1378 extern char *gid_unused;
1380 return gid_unused[(unsigned) stat_buf->st_gid];
1381 #else
1382 return getgrgid (stat_buf->st_gid) == NULL;
1383 #endif
1386 boolean
1387 pred_nouser (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1389 #ifdef CACHE_IDS
1390 extern char *uid_unused;
1391 #endif
1393 (void) pathname;
1394 (void) pred_ptr;
1396 #ifdef CACHE_IDS
1397 return uid_unused[(unsigned) stat_buf->st_uid];
1398 #else
1399 return getpwuid (stat_buf->st_uid) == NULL;
1400 #endif
1404 static boolean
1405 is_ok(const char *program, const char *arg)
1407 fflush (stdout);
1408 /* The draft open standard requires that, in the POSIX locale,
1409 the last non-blank character of this prompt be '?'.
1410 The exact format is not specified.
1411 This standard does not have requirements for locales other than POSIX
1413 /* XXX: printing UNTRUSTED data here. */
1414 fprintf (stderr, _("< %s ... %s > ? "), program, arg);
1415 fflush (stderr);
1416 return yesno();
1419 boolean
1420 pred_ok (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1422 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1423 return new_impl_pred_exec (get_start_dirfd(),
1424 pathname, stat_buf, pred_ptr, NULL, 0);
1425 else
1426 return false;
1429 boolean
1430 pred_okdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1432 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
1433 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1434 return new_impl_pred_exec (get_current_dirfd(),
1435 state.rel_pathname, stat_buf, pred_ptr,
1436 prefix, (prefix ? 2 : 0));
1437 else
1438 return false;
1441 boolean
1442 pred_openparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1444 (void) pathname;
1445 (void) stat_buf;
1446 (void) pred_ptr;
1447 return true;
1450 boolean
1451 pred_or (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1453 if (pred_ptr->pred_left == NULL
1454 || !apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
1456 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1458 else
1459 return true;
1462 boolean
1463 pred_path (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1465 (void) stat_buf;
1466 if (fnmatch (pred_ptr->args.str, pathname, 0) == 0)
1467 return (true);
1468 return (false);
1471 boolean
1472 pred_perm (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1474 mode_t mode = stat_buf->st_mode;
1475 mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0];
1476 (void) pathname;
1477 switch (pred_ptr->args.perm.kind)
1479 case PERM_AT_LEAST:
1480 return (mode & perm_val) == perm_val;
1481 break;
1483 case PERM_ANY:
1484 /* True if any of the bits set in the mask are also set in the file's mode.
1487 * Otherwise, if onum is prefixed by a hyphen, the primary shall
1488 * evaluate as true if at least all of the bits specified in
1489 * onum that are also set in the octal mask 07777 are set.
1491 * Eric Blake's interpretation is that the mode argument is zero,
1494 if (0 == perm_val)
1495 return true; /* Savannah bug 14748; we used to return false */
1496 else
1497 return (mode & perm_val) != 0;
1498 break;
1500 case PERM_EXACT:
1501 return (mode & MODE_ALL) == perm_val;
1502 break;
1504 default:
1505 abort ();
1506 break;
1511 struct access_check_args
1513 const char *filename;
1514 int access_type;
1515 int cb_errno;
1519 static int
1520 access_callback(void *context)
1522 int rv;
1523 struct access_check_args *args = context;
1524 if ((rv = access(args->filename, args->access_type)) < 0)
1525 args->cb_errno = errno;
1526 return rv;
1529 static int
1530 can_access(int access_type)
1532 struct access_check_args args;
1533 args.filename = state.rel_pathname;
1534 args.access_type = access_type;
1535 args.cb_errno = 0;
1536 return 0 == run_in_dir(state.cwd_dir_fd, access_callback, &args);
1540 boolean
1541 pred_executable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1543 (void) pathname;
1544 (void) stat_buf;
1545 (void) pred_ptr;
1547 return can_access(X_OK);
1550 boolean
1551 pred_readable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1553 (void) pathname;
1554 (void) stat_buf;
1555 (void) pred_ptr;
1557 return can_access(R_OK);
1560 boolean
1561 pred_writable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1563 (void) pathname;
1564 (void) stat_buf;
1565 (void) pred_ptr;
1567 return can_access(W_OK);
1570 boolean
1571 pred_print (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1573 (void) stat_buf;
1574 (void) pred_ptr;
1576 print_quoted(pred_ptr->args.printf_vec.stream,
1577 pred_ptr->args.printf_vec.quote_opts,
1578 pred_ptr->args.printf_vec.dest_is_tty,
1579 "%s\n", pathname);
1580 return true;
1583 boolean
1584 pred_print0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1586 return pred_fprint0(pathname, stat_buf, pred_ptr);
1589 boolean
1590 pred_prune (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1592 (void) pathname;
1593 (void) pred_ptr;
1595 if (options.do_dir_first == true && /* no effect with -depth */
1596 stat_buf != NULL &&
1597 S_ISDIR(stat_buf->st_mode))
1598 state.stop_at_current_level = true;
1600 /* findutils used to return options.do_dir_first here, so that -prune
1601 * returns true only if -depth is not in effect. But POSIX requires
1602 * that -prune always evaluate as true.
1604 return true;
1607 boolean
1608 pred_quit (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1610 (void) pathname;
1611 (void) stat_buf;
1612 (void) pred_ptr;
1614 /* Run any cleanups. This includes executing any command lines
1615 * we have partly built but not executed.
1617 cleanup();
1619 /* Since -exec and friends don't leave child processes running in the
1620 * background, there is no need to wait for them here.
1622 exit(state.exit_status); /* 0 for success, etc. */
1625 boolean
1626 pred_regex (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1628 int len = strlen (pathname);
1629 (void) stat_buf;
1630 if (re_match (pred_ptr->args.regex, pathname, len, 0,
1631 (struct re_registers *) NULL) == len)
1632 return (true);
1633 return (false);
1636 boolean
1637 pred_size (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1639 uintmax_t f_val;
1641 (void) pathname;
1642 f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize)
1643 + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0));
1644 switch (pred_ptr->args.size.kind)
1646 case COMP_GT:
1647 if (f_val > pred_ptr->args.size.size)
1648 return (true);
1649 break;
1650 case COMP_LT:
1651 if (f_val < pred_ptr->args.size.size)
1652 return (true);
1653 break;
1654 case COMP_EQ:
1655 if (f_val == pred_ptr->args.size.size)
1656 return (true);
1657 break;
1659 return (false);
1662 boolean
1663 pred_samefile (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1665 /* Potential optimisation: because of the loop protection, we always
1666 * know the device of the current directory, hence the device number
1667 * of the file we're currently considering. If -L is not in effect,
1668 * and the device number of the file we're looking for is not the
1669 * same as the device number of the current directory, this
1670 * predicate cannot return true. Hence there would be no need to
1671 * stat the file we're looking at.
1673 (void) pathname;
1675 /* We will often still have an fd open on the file under consideration,
1676 * but that's just to ensure inode number stability by maintaining
1677 * a reference to it; we don't need the file for anything else.
1679 return stat_buf->st_ino == pred_ptr->args.samefileid.ino
1680 && stat_buf->st_dev == pred_ptr->args.samefileid.dev;
1683 boolean
1684 pred_true (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1686 (void) pathname;
1687 (void) stat_buf;
1688 (void) pred_ptr;
1689 return true;
1692 boolean
1693 pred_type (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1695 mode_t mode;
1696 mode_t type = pred_ptr->args.type;
1698 assert (state.have_type);
1700 if (0 == state.type)
1702 /* This can sometimes happen with broken NFS servers.
1703 * See Savannah bug #16378.
1705 return false;
1708 (void) pathname;
1710 if (state.have_stat)
1711 mode = stat_buf->st_mode;
1712 else
1713 mode = state.type;
1715 #ifndef S_IFMT
1716 /* POSIX system; check `mode' the slow way. */
1717 if ((S_ISBLK (mode) && type == S_IFBLK)
1718 || (S_ISCHR (mode) && type == S_IFCHR)
1719 || (S_ISDIR (mode) && type == S_IFDIR)
1720 || (S_ISREG (mode) && type == S_IFREG)
1721 #ifdef S_IFLNK
1722 || (S_ISLNK (mode) && type == S_IFLNK)
1723 #endif
1724 #ifdef S_IFIFO
1725 || (S_ISFIFO (mode) && type == S_IFIFO)
1726 #endif
1727 #ifdef S_IFSOCK
1728 || (S_ISSOCK (mode) && type == S_IFSOCK)
1729 #endif
1730 #ifdef S_IFDOOR
1731 || (S_ISDOOR (mode) && type == S_IFDOOR)
1732 #endif
1734 #else /* S_IFMT */
1735 /* Unix system; check `mode' the fast way. */
1736 if ((mode & S_IFMT) == type)
1737 #endif /* S_IFMT */
1738 return (true);
1739 else
1740 return (false);
1743 boolean
1744 pred_uid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1746 (void) pathname;
1747 switch (pred_ptr->args.numinfo.kind)
1749 case COMP_GT:
1750 if (stat_buf->st_uid > pred_ptr->args.numinfo.l_val)
1751 return (true);
1752 break;
1753 case COMP_LT:
1754 if (stat_buf->st_uid < pred_ptr->args.numinfo.l_val)
1755 return (true);
1756 break;
1757 case COMP_EQ:
1758 if (stat_buf->st_uid == pred_ptr->args.numinfo.l_val)
1759 return (true);
1760 break;
1762 return (false);
1765 boolean
1766 pred_used (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1768 struct timespec delta, at, ct;
1770 (void) pathname;
1772 /* TODO: this needs to be retested carefully (manually, if necessary) */
1773 at = get_stat_atime(stat_buf);
1774 ct = get_stat_ctime(stat_buf);
1775 delta.tv_sec = at.tv_sec - ct.tv_sec;
1776 delta.tv_nsec = at.tv_nsec - ct.tv_nsec;
1777 if (delta.tv_nsec < 0)
1779 delta.tv_nsec += 1000000000;
1780 delta.tv_sec -= 1;
1782 return pred_timewindow(delta, pred_ptr, DAYSECS);
1785 boolean
1786 pred_user (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1788 (void) pathname;
1789 if (pred_ptr->args.uid == stat_buf->st_uid)
1790 return (true);
1791 else
1792 return (false);
1795 boolean
1796 pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1798 struct stat sbuf; /* local copy, not stat_buf because we're using a different stat method */
1799 int (*ystat) (const char*, struct stat *p);
1801 /* If we would normally stat the link itself, stat the target instead.
1802 * If we would normally follow the link, stat the link itself instead.
1804 if (following_links())
1805 ystat = optionp_stat;
1806 else
1807 ystat = optionl_stat;
1809 set_stat_placeholders(&sbuf);
1810 if ((*ystat) (state.rel_pathname, &sbuf) != 0)
1812 if (following_links() && errno == ENOENT)
1814 /* If we failed to follow the symlink,
1815 * fall back on looking at the symlink itself.
1817 /* Mimic behavior of ls -lL. */
1818 return (pred_type (pathname, stat_buf, pred_ptr));
1820 else
1822 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
1823 state.exit_status = 1;
1825 return false;
1827 /* Now that we have our stat() information, query it in the same
1828 * way that -type does.
1830 return (pred_type (pathname, &sbuf, pred_ptr));
1833 /* 1) fork to get a child; parent remembers the child pid
1834 2) child execs the command requested
1835 3) parent waits for child; checks for proper pid of child
1837 Possible returns:
1839 ret errno status(h) status(l)
1841 pid x signal# 0177 stopped
1842 pid x exit arg 0 term by _exit
1843 pid x 0 signal # term by signal
1844 -1 EINTR parent got signal
1845 -1 other some other kind of error
1847 Return true only if the pid matches, status(l) is
1848 zero, and the exit arg (status high) is 0.
1849 Otherwise return false, possibly printing an error message. */
1852 static boolean
1853 prep_child_for_exec (boolean close_stdin, int dirfd)
1855 boolean ok = true;
1856 if (close_stdin)
1858 const char inputfile[] = "/dev/null";
1860 if (close(0) < 0)
1862 error(0, errno, _("Cannot close standard input"));
1863 ok = false;
1865 else
1867 if (open(inputfile, O_RDONLY
1868 #if defined O_LARGEFILE
1869 |O_LARGEFILE
1870 #endif
1871 ) < 0)
1873 /* This is not entirely fatal, since
1874 * executing the child with a closed
1875 * stdin is almost as good as executing it
1876 * with its stdin attached to /dev/null.
1878 error (0, errno, "%s", safely_quote_err_filename(0, inputfile));
1879 /* do not set ok=false, it is OK to continue anyway. */
1884 /* Even if DebugSearch is set, don't announce our change of
1885 * directory, since we're not going to emit a subsequent
1886 * announcement of a call to stat() anyway, as we're about to exec
1887 * something.
1889 if (dirfd != AT_FDCWD)
1891 assert (dirfd >= 0);
1892 if (0 != fchdir(dirfd))
1894 /* If we cannot execute our command in the correct directory,
1895 * we should not execute it at all.
1897 error(0, errno, _("Failed to change directory"));
1898 ok = false;
1901 return ok;
1907 launch (const struct buildcmd_control *ctl,
1908 struct buildcmd_state *buildstate)
1910 int wait_status;
1911 pid_t child_pid;
1912 static int first_time = 1;
1913 const struct exec_val *execp = buildstate->usercontext;
1915 if (!execp->use_current_dir)
1917 assert (starting_desc >= 0);
1918 assert (execp->dirfd == starting_desc);
1922 /* Null terminate the arg list. */
1923 bc_push_arg (ctl, buildstate, (char *) NULL, 0, NULL, 0, false);
1925 /* Make sure output of command doesn't get mixed with find output. */
1926 fflush (stdout);
1927 fflush (stderr);
1929 /* Make sure to listen for the kids. */
1930 if (first_time)
1932 first_time = 0;
1933 signal (SIGCHLD, SIG_DFL);
1936 child_pid = fork ();
1937 if (child_pid == -1)
1938 error (1, errno, _("cannot fork"));
1939 if (child_pid == 0)
1941 /* We are the child. */
1942 assert (starting_desc >= 0);
1943 if (!prep_child_for_exec(execp->close_stdin, execp->dirfd))
1945 _exit(1);
1948 execvp (buildstate->cmd_argv[0], buildstate->cmd_argv);
1949 error (0, errno, "%s",
1950 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1951 _exit (1);
1955 /* In parent; set up for next time. */
1956 bc_clear_args(ctl, buildstate);
1959 while (waitpid (child_pid, &wait_status, 0) == (pid_t) -1)
1961 if (errno != EINTR)
1963 error (0, errno, _("error waiting for %s"),
1964 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1965 state.exit_status = 1;
1966 return 0; /* FAIL */
1970 if (WIFSIGNALED (wait_status))
1972 error (0, 0, _("%s terminated by signal %d"),
1973 quotearg_n_style(0, options.err_quoting_style,
1974 buildstate->cmd_argv[0]),
1975 WTERMSIG (wait_status));
1977 if (execp->multiple)
1979 /* -exec \; just returns false if the invoked command fails.
1980 * -exec {} + returns true if the invoked command fails, but
1981 * sets the program exit status.
1983 state.exit_status = 1;
1986 return 1; /* OK */
1989 if (0 == WEXITSTATUS (wait_status))
1991 return 1; /* OK */
1993 else
1995 if (execp->multiple)
1997 /* -exec \; just returns false if the invoked command fails.
1998 * -exec {} + returns true if the invoked command fails, but
1999 * sets the program exit status.
2001 state.exit_status = 1;
2003 return 0; /* FAIL */
2009 /* Return a static string formatting the time WHEN according to the
2010 * strftime format character KIND.
2012 * This function contains a number of assertions. These look like
2013 * runtime checks of the results of computations, which would be a
2014 * problem since external events should not be tested for with
2015 * "assert" (instead you should use "if"). However, they are not
2016 * really runtime checks. The assertions actually exist to verify
2017 * that the various buffers are correctly sized.
2019 static char *
2020 format_date (struct timespec ts, int kind)
2022 /* In theory, we use an extra 10 characters for 9 digits of
2023 * nanoseconds and 1 for the decimal point. However, the real
2024 * world is more complex than that.
2026 * For example, some systems return junk in the tv_nsec part of
2027 * st_birthtime. An example of this is the NetBSD-4.0-RELENG kernel
2028 * (at Sat Mar 24 18:46:46 2007) running a NetBSD-3.1-RELEASE
2029 * runtime and examining files on an msdos filesytem. So for that
2030 * reason we set NS_BUF_LEN to 32, which is simply "long enough" as
2031 * opposed to "exactly the right size". Note that the behaviour of
2032 * NetBSD appears to be a result of the use of uninitialised data,
2033 * as it's not 100% reproducible (more like 25%).
2035 enum {
2036 NS_BUF_LEN = 32,
2037 DATE_LEN_PERCENT_APLUS=21 /* length of result of %A+ (it's longer than %c)*/
2039 static char buf[128u+10u + MAX(DATE_LEN_PERCENT_APLUS,
2040 MAX (LONGEST_HUMAN_READABLE + 2, NS_BUF_LEN+64+200))];
2041 char ns_buf[NS_BUF_LEN]; /* -.9999999990 (- sign can happen!)*/
2042 int charsprinted, need_ns_suffix;
2043 struct tm *tm;
2044 char fmt[6];
2046 /* human_readable() assumes we pass a buffer which is at least as
2047 * long as LONGEST_HUMAN_READABLE. We use an assertion here to
2048 * ensure that no nasty unsigned overflow happend in our calculation
2049 * of the size of buf. Do the assertion here rather than in the
2050 * code for %@ so that we find the problem quickly if it exists. If
2051 * you want to submit a patch to move this into the if statement, go
2052 * ahead, I'll apply it. But include performance timings
2053 * demonstrating that the performance difference is actually
2054 * measurable.
2056 verify (sizeof(buf) >= LONGEST_HUMAN_READABLE);
2058 charsprinted = 0;
2059 need_ns_suffix = 0;
2061 /* Format the main part of the time. */
2062 if (kind == '+')
2064 strcpy (fmt, "%F+%T");
2065 need_ns_suffix = 1;
2067 else
2069 fmt[0] = '%';
2070 fmt[1] = kind;
2071 fmt[2] = '\0';
2073 /* %a, %c, and %t are handled in ctime_format() */
2074 switch (kind)
2076 case 'S':
2077 case 'T':
2078 case 'X':
2079 case '@':
2080 need_ns_suffix = 1;
2081 break;
2082 default:
2083 need_ns_suffix = 0;
2084 break;
2088 if (need_ns_suffix)
2090 /* Format the nanoseconds part. Leave a trailing zero to
2091 * discourage people from writing scripts which extract the
2092 * fractional part of the timestamp by using column offsets.
2093 * The reason for discouraging this is that in the future, the
2094 * granularity may not be nanoseconds.
2096 ns_buf[0] = 0;
2097 charsprinted = snprintf(ns_buf, NS_BUF_LEN, ".%09ld0", (long int)ts.tv_nsec);
2098 assert (charsprinted < NS_BUF_LEN);
2101 if (kind != '@'
2102 && (tm = localtime (&ts.tv_sec))
2103 && strftime (buf, sizeof buf, fmt, tm))
2105 /* For %AS, %CS, %TS, add the fractional part of the seconds
2106 * information.
2108 if (need_ns_suffix)
2110 assert ((sizeof buf - strlen(buf)) > strlen(ns_buf));
2111 strcat(buf, ns_buf);
2113 return buf;
2115 else
2117 uintmax_t w = ts.tv_sec;
2118 size_t used, len, remaining;
2120 /* XXX: note that we are negating an unsigned type which is the
2121 * widest possible unsigned type.
2123 char *p = human_readable (ts.tv_sec < 0 ? -w : w, buf + 1,
2124 human_ceiling, 1, 1);
2125 assert (p > buf);
2126 assert (p < (buf + (sizeof buf)));
2127 if (ts.tv_sec < 0)
2128 *--p = '-'; /* XXX: Ugh, relying on internal details of human_readable(). */
2130 /* Add the nanoseconds part. Because we cannot enforce a
2131 * particlar implementation of human_readable, we cannot assume
2132 * any particular value for (p-buf). So we need to be careful
2133 * that there is enough space remaining in the buffer.
2135 if (need_ns_suffix)
2137 len = strlen(p);
2138 used = (p-buf) + len; /* Offset into buf of current end */
2139 assert (sizeof buf > used); /* Ensure we can perform subtraction safely. */
2140 remaining = sizeof buf - used - 1u; /* allow space for NUL */
2142 if (strlen(ns_buf) >= remaining)
2144 error(0, 0,
2145 "charsprinted=%ld but remaining=%lu: ns_buf=%s",
2146 (long)charsprinted, (unsigned long)remaining, ns_buf);
2148 assert (strlen(ns_buf) < remaining);
2149 strcat(p, ns_buf);
2151 return p;
2155 static const char *weekdays[] =
2157 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
2159 static char * months[] =
2161 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2162 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2166 static char *
2167 ctime_format (struct timespec ts)
2169 const struct tm * ptm;
2170 #define TIME_BUF_LEN 1024u
2171 static char resultbuf[TIME_BUF_LEN];
2172 int nout;
2174 ptm = localtime(&ts.tv_sec);
2175 if (ptm)
2177 assert (ptm->tm_wday >= 0);
2178 assert (ptm->tm_wday < 7);
2179 assert (ptm->tm_mon >= 0);
2180 assert (ptm->tm_mon < 12);
2181 assert (ptm->tm_hour >= 0);
2182 assert (ptm->tm_hour < 24);
2183 assert (ptm->tm_min < 60);
2184 assert (ptm->tm_sec <= 61); /* allows 2 leap seconds. */
2186 /* wkday mon mday hh:mm:ss.nnnnnnnnn yyyy */
2187 nout = snprintf(resultbuf, TIME_BUF_LEN,
2188 "%3s %3s %2d %02d:%02d:%02d.%010ld %04d",
2189 weekdays[ptm->tm_wday],
2190 months[ptm->tm_mon],
2191 ptm->tm_mday,
2192 ptm->tm_hour,
2193 ptm->tm_min,
2194 ptm->tm_sec,
2195 (long int)ts.tv_nsec,
2196 1900 + ptm->tm_year);
2198 assert (nout < TIME_BUF_LEN);
2199 return resultbuf;
2201 else
2203 /* The time cannot be represented as a struct tm.
2204 Output it as an integer. */
2205 return format_date (ts, '@');
2209 /* Copy STR into BUF and trim blanks from the end of BUF.
2210 Return BUF. */
2212 static char *
2213 blank_rtrim (str, buf)
2214 char *str;
2215 char *buf;
2217 int i;
2219 if (str == NULL)
2220 return (NULL);
2221 strcpy (buf, str);
2222 i = strlen (buf) - 1;
2223 while ((i >= 0) && ((buf[i] == ' ') || buf[i] == '\t'))
2224 i--;
2225 buf[++i] = '\0';
2226 return (buf);
2229 /* Print out the predicate list starting at NODE. */
2230 void
2231 print_list (FILE *fp, struct predicate *node)
2233 struct predicate *cur;
2234 char name[256];
2236 cur = node;
2237 while (cur != NULL)
2239 fprintf (fp, "[%s] ", blank_rtrim (cur->p_name, name));
2240 cur = cur->pred_next;
2242 fprintf (fp, "\n");
2245 /* Print out the predicate list starting at NODE. */
2246 static void
2247 print_parenthesised(FILE *fp, struct predicate *node)
2249 int parens = 0;
2251 if (node)
2253 if ((pred_is(node, pred_or) || pred_is(node, pred_and))
2254 && node->pred_left == NULL)
2256 /* We print "<nothing> or X" as just "X"
2257 * We print "<nothing> and X" as just "X"
2259 print_parenthesised(fp, node->pred_right);
2261 else
2263 if (node->pred_left || node->pred_right)
2264 parens = 1;
2266 if (parens)
2267 fprintf(fp, "%s", " ( ");
2268 print_optlist(fp, node);
2269 if (parens)
2270 fprintf(fp, "%s", " ) ");
2275 void
2276 print_optlist (FILE *fp, const struct predicate *p)
2278 if (p)
2280 print_parenthesised(fp, p->pred_left);
2281 fprintf (fp,
2282 "%s%s",
2283 p->need_stat ? "[call stat] " : "",
2284 p->need_type ? "[need type] " : "");
2285 print_predicate(fp, p);
2286 fprintf(fp, " [%g] ", p->est_success_rate);
2287 if (options.debug_options & DebugSuccessRates)
2289 fprintf(fp, "[%ld/%ld", p->perf.successes, p->perf.visits);
2290 if (p->perf.visits)
2292 double real_rate = (double)p->perf.successes / (double)p->perf.visits;
2293 fprintf(fp, "=%g] ", real_rate);
2295 else
2297 fprintf(fp, "=_] ");
2300 print_parenthesised(fp, p->pred_right);
2304 void show_success_rates(const struct predicate *p)
2306 if (options.debug_options & DebugSuccessRates)
2308 fprintf(stderr, "Predicate success rates after completion:\n");
2309 print_optlist(stderr, p);
2310 fprintf(stderr, "\n");
2317 #ifdef _NDEBUG
2318 /* If _NDEBUG is defined, the assertions will do nothing. Hence
2319 * there is no point in having a function body for pred_sanity_check()
2320 * if that preprocessor macro is defined.
2322 void
2323 pred_sanity_check(const struct predicate *predicates)
2325 /* Do nothing, since assert is a no-op with _NDEBUG set */
2326 return;
2328 #else
2329 void
2330 pred_sanity_check(const struct predicate *predicates)
2332 const struct predicate *p;
2334 for (p=predicates; p != NULL; p=p->pred_next)
2336 /* All predicates must do something. */
2337 assert (p->pred_func != NULL);
2339 /* All predicates must have a parser table entry. */
2340 assert (p->parser_entry != NULL);
2342 /* If the parser table tells us that just one predicate function is
2343 * possible, verify that that is still the one that is in effect.
2344 * If the parser has NULL for the predicate function, that means that
2345 * the parse_xxx function fills it in, so we can't check it.
2347 if (p->parser_entry->pred_func)
2349 assert (p->parser_entry->pred_func == p->pred_func);
2352 switch (p->parser_entry->type)
2354 /* Options all take effect during parsing, so there should
2355 * be no predicate entries corresponding to them. Hence we
2356 * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION
2357 * items.
2359 * This is a silly way of coding this test, but it prevents
2360 * a compiler warning (i.e. otherwise it would think that
2361 * there would be case statements missing).
2363 case ARG_OPTION:
2364 case ARG_POSITIONAL_OPTION:
2365 assert (p->parser_entry->type != ARG_OPTION);
2366 assert (p->parser_entry->type != ARG_POSITIONAL_OPTION);
2367 break;
2369 case ARG_ACTION:
2370 assert(p->side_effects); /* actions have side effects. */
2371 if (!pred_is(p, pred_prune) && !pred_is(p, pred_quit))
2373 /* actions other than -prune and -quit should
2374 * inhibit the default -print
2376 assert (p->no_default_print);
2378 break;
2380 /* We happen to know that the only user of ARG_SPECIAL_PARSE
2381 * is a test, so handle it like ARG_TEST.
2383 case ARG_SPECIAL_PARSE:
2384 case ARG_TEST:
2385 case ARG_PUNCTUATION:
2386 case ARG_NOOP:
2387 /* Punctuation and tests should have no side
2388 * effects and not inhibit default print.
2390 assert (!p->no_default_print);
2391 assert (!p->side_effects);
2392 break;
2396 #endif