Fix Savannah bug #20871.
[findutils.git] / find / pred.c
blob730a87653aec90e7a445eb078eba3868b9938f87
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 return false;
415 else
417 /* nothing to do. */
418 return true;
422 boolean
423 pred_empty (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
425 (void) pathname;
426 (void) pred_ptr;
428 if (S_ISDIR (stat_buf->st_mode))
430 int fd;
431 DIR *d;
432 struct dirent *dp;
433 boolean empty = true;
435 errno = 0;
436 if ((fd = openat(state.cwd_dir_fd, state.rel_pathname, O_RDONLY
437 #if defined O_LARGEFILE
438 |O_LARGEFILE
439 #endif
440 )) < 0)
442 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
443 state.exit_status = 1;
444 return false;
446 d = fdopendir (fd);
447 if (d == NULL)
449 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
450 state.exit_status = 1;
451 return false;
453 for (dp = readdir (d); dp; dp = readdir (d))
455 if (dp->d_name[0] != '.'
456 || (dp->d_name[1] != '\0'
457 && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
459 empty = false;
460 break;
463 if (CLOSEDIR (d))
465 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
466 state.exit_status = 1;
467 return false;
469 return (empty);
471 else if (S_ISREG (stat_buf->st_mode))
472 return (stat_buf->st_size == 0);
473 else
474 return (false);
477 static boolean
478 new_impl_pred_exec (int dirfd, const char *pathname,
479 struct stat *stat_buf,
480 struct predicate *pred_ptr,
481 const char *prefix, size_t pfxlen)
483 struct exec_val *execp = &pred_ptr->args.exec_vec;
484 size_t len = strlen(pathname);
486 (void) stat_buf;
487 execp->dirfd = dirfd;
488 if (execp->multiple)
490 /* Push the argument onto the current list.
491 * The command may or may not be run at this point,
492 * depending on the command line length limits.
494 bc_push_arg(&execp->ctl,
495 &execp->state,
496 pathname, len+1,
497 prefix, pfxlen,
500 /* remember that there are pending execdirs. */
501 state.execdirs_outstanding = true;
503 /* POSIX: If the primary expression is punctuated by a plus
504 * sign, the primary shall always evaluate as true
506 return true;
508 else
510 int i;
512 for (i=0; i<execp->num_args; ++i)
514 bc_do_insert(&execp->ctl,
515 &execp->state,
516 execp->replace_vec[i],
517 strlen(execp->replace_vec[i]),
518 prefix, pfxlen,
519 pathname, len,
523 /* Actually invoke the command. */
524 return execp->ctl.exec_callback(&execp->ctl,
525 &execp->state);
530 boolean
531 pred_exec (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
533 return new_impl_pred_exec(get_start_dirfd(),
534 pathname, stat_buf, pred_ptr, NULL, 0);
537 boolean
538 pred_execdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
540 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
541 (void) &pathname;
542 return new_impl_pred_exec (get_current_dirfd(),
543 state.rel_pathname, stat_buf, pred_ptr,
544 prefix, (prefix ? 2 : 0));
547 boolean
548 pred_false (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
550 (void) &pathname;
551 (void) &stat_buf;
552 (void) &pred_ptr;
555 return (false);
558 boolean
559 pred_fls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
561 FILE * stream = pred_ptr->args.printf_vec.stream;
562 list_file (pathname, state.cwd_dir_fd, state.rel_pathname, stat_buf,
563 options.start_time.tv_sec,
564 options.output_block_size,
565 pred_ptr->literal_control_chars, stream);
566 return true;
569 boolean
570 pred_fprint (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
572 (void) &pathname;
573 (void) &stat_buf;
575 print_quoted(pred_ptr->args.printf_vec.stream,
576 pred_ptr->args.printf_vec.quote_opts,
577 pred_ptr->args.printf_vec.dest_is_tty,
578 "%s\n",
579 pathname);
580 return true;
583 boolean
584 pred_fprint0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
586 FILE * fp = pred_ptr->args.printf_vec.stream;
588 (void) &stat_buf;
590 fputs (pathname, fp);
591 putc (0, fp);
592 return true;
597 static char*
598 mode_to_filetype(mode_t m)
600 #define HANDLE_TYPE(t,letter) if (m==t) { return letter; }
601 #ifdef S_IFREG
602 HANDLE_TYPE(S_IFREG, "f"); /* regular file */
603 #endif
604 #ifdef S_IFDIR
605 HANDLE_TYPE(S_IFDIR, "d"); /* directory */
606 #endif
607 #ifdef S_IFLNK
608 HANDLE_TYPE(S_IFLNK, "l"); /* symbolic link */
609 #endif
610 #ifdef S_IFSOCK
611 HANDLE_TYPE(S_IFSOCK, "s"); /* Unix domain socket */
612 #endif
613 #ifdef S_IFBLK
614 HANDLE_TYPE(S_IFBLK, "b"); /* block device */
615 #endif
616 #ifdef S_IFCHR
617 HANDLE_TYPE(S_IFCHR, "c"); /* character device */
618 #endif
619 #ifdef S_IFIFO
620 HANDLE_TYPE(S_IFIFO, "p"); /* FIFO */
621 #endif
622 #ifdef S_IFDOOR
623 HANDLE_TYPE(S_IFDOOR, "D"); /* Door (e.g. on Solaris) */
624 #endif
625 return "U"; /* Unknown */
628 static double
629 file_sparseness(const struct stat *p)
631 #if defined HAVE_STRUCT_STAT_ST_BLOCKS
632 if (0 == p->st_size)
634 if (0 == p->st_blocks)
635 return 1.0;
636 else
637 return p->st_blocks < 0 ? -HUGE_VAL : HUGE_VAL;
639 else
641 double blklen = file_blocksize(p) * (double)p->st_blocks;
642 return blklen / p->st_size;
644 #else
645 return 1.0;
646 #endif
651 static void
652 checked_fprintf(struct format_val *dest, const char *fmt, ...)
654 int rv;
655 va_list ap;
657 va_start(ap, fmt);
658 rv = vfprintf(dest->stream, fmt, ap);
659 if (rv < 0)
660 nonfatal_file_error(dest->filename);
664 static void
665 checked_print_quoted (struct format_val *dest,
666 const char *format, const char *s)
668 int rv = print_quoted(dest->stream, dest->quote_opts, dest->dest_is_tty,
669 format, s);
670 if (rv < 0)
671 nonfatal_file_error(dest->filename);
675 static void
676 checked_fwrite(void *p, size_t siz, size_t nmemb, struct format_val *dest)
678 int items_written = fwrite(p, siz, nmemb, dest->stream);
679 if (items_written < nmemb)
680 nonfatal_file_error(dest->filename);
683 static void
684 checked_fflush(struct format_val *dest)
686 if (0 != fflush(dest->stream))
688 nonfatal_file_error(dest->filename);
692 static void
693 do_fprintf(struct format_val *dest,
694 struct segment *segment,
695 const char *pathname,
696 const struct stat *stat_buf)
698 char hbuf[LONGEST_HUMAN_READABLE + 1];
699 const char *cp;
701 switch (segment->segkind)
703 case KIND_PLAIN: /* Plain text string (no % conversion). */
704 /* trusted */
705 checked_fwrite(segment->text, 1, segment->text_len, dest);
706 break;
708 case KIND_STOP: /* Terminate argument and flush output. */
709 /* trusted */
710 checked_fwrite(segment->text, 1, segment->text_len, dest);
711 checked_fflush(dest);
712 break;
714 case KIND_FORMAT:
715 switch (segment->format_char[0])
717 case 'a': /* atime in `ctime' format. */
718 /* UNTRUSTED, probably unexploitable */
719 checked_fprintf (dest, segment->text, ctime_format (get_stat_atime(stat_buf)));
720 break;
721 case 'b': /* size in 512-byte blocks */
722 /* UNTRUSTED, probably unexploitable */
723 checked_fprintf (dest, segment->text,
724 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
725 hbuf, human_ceiling,
726 ST_NBLOCKSIZE, 512));
727 break;
728 case 'c': /* ctime in `ctime' format */
729 /* UNTRUSTED, probably unexploitable */
730 checked_fprintf (dest, segment->text, ctime_format (get_stat_ctime(stat_buf)));
731 break;
732 case 'd': /* depth in search tree */
733 /* UNTRUSTED, probably unexploitable */
734 checked_fprintf (dest, segment->text, state.curdepth);
735 break;
736 case 'D': /* Device on which file exists (stat.st_dev) */
737 /* trusted */
738 checked_fprintf (dest, segment->text,
739 human_readable ((uintmax_t) stat_buf->st_dev, hbuf,
740 human_ceiling, 1, 1));
741 break;
742 case 'f': /* base name of path */
743 /* sanitised */
745 char *base = base_name (pathname);
746 checked_print_quoted (dest, segment->text, base);
747 free (base);
749 break;
750 case 'F': /* file system type */
751 /* trusted */
752 checked_print_quoted (dest, segment->text, filesystem_type (stat_buf, pathname));
753 break;
754 case 'g': /* group name */
755 /* trusted */
756 /* (well, the actual group is selected by the user but
757 * its name was selected by the system administrator)
760 struct group *g;
762 g = getgrgid (stat_buf->st_gid);
763 if (g)
765 segment->text[segment->text_len] = 's';
766 checked_fprintf (dest, segment->text, g->gr_name);
767 break;
769 else
771 /* Do nothing. */
772 /*FALLTHROUGH*/
775 /*FALLTHROUGH*/ /*...sometimes, so 'G' case.*/
777 case 'G': /* GID number */
778 /* UNTRUSTED, probably unexploitable */
779 checked_fprintf (dest, segment->text,
780 human_readable ((uintmax_t) stat_buf->st_gid, hbuf,
781 human_ceiling, 1, 1));
782 break;
783 case 'h': /* leading directories part of path */
784 /* sanitised */
786 cp = strrchr (pathname, '/');
787 if (cp == NULL) /* No leading directories. */
789 /* If there is no slash in the pathname, we still
790 * print the string because it contains characters
791 * other than just '%s'. The %h expands to ".".
793 checked_print_quoted (dest, segment->text, ".");
795 else
797 char *s = strdup(pathname);
798 s[cp - pathname] = 0;
799 checked_print_quoted (dest, segment->text, s);
800 free(s);
803 break;
805 case 'H': /* ARGV element file was found under */
806 /* trusted */
808 char *s = xmalloc(state.starting_path_length+1);
809 memcpy(s, pathname, state.starting_path_length);
810 s[state.starting_path_length] = 0;
811 checked_fprintf (dest, segment->text, s);
812 free(s);
814 break;
816 case 'i': /* inode number */
817 /* UNTRUSTED, but not exploitable I think */
818 checked_fprintf (dest, segment->text,
819 human_readable ((uintmax_t) stat_buf->st_ino, hbuf,
820 human_ceiling,
821 1, 1));
822 break;
823 case 'k': /* size in 1K blocks */
824 /* UNTRUSTED, but not exploitable I think */
825 checked_fprintf (dest, segment->text,
826 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
827 hbuf, human_ceiling,
828 ST_NBLOCKSIZE, 1024));
829 break;
830 case 'l': /* object of symlink */
831 /* sanitised */
832 #ifdef S_ISLNK
834 char *linkname = 0;
836 if (S_ISLNK (stat_buf->st_mode))
838 linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
839 if (linkname == 0)
840 state.exit_status = 1;
842 if (linkname)
844 checked_print_quoted (dest, segment->text, linkname);
845 free (linkname);
847 else
849 /* We still need to honour the field width etc., so this is
850 * not a no-op.
852 checked_print_quoted (dest, segment->text, "");
855 #endif /* S_ISLNK */
856 break;
858 case 'M': /* mode as 10 chars (eg., "-rwxr-x--x" */
859 /* UNTRUSTED, probably unexploitable */
861 char modestring[16] ;
862 filemodestring (stat_buf, modestring);
863 modestring[10] = '\0';
864 checked_fprintf (dest, segment->text, modestring);
866 break;
868 case 'm': /* mode as octal number (perms only) */
869 /* UNTRUSTED, probably unexploitable */
871 /* Output the mode portably using the traditional numbers,
872 even if the host unwisely uses some other numbering
873 scheme. But help the compiler in the common case where
874 the host uses the traditional numbering scheme. */
875 mode_t m = stat_buf->st_mode;
876 boolean traditional_numbering_scheme =
877 (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000
878 && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100
879 && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010
880 && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001);
881 checked_fprintf (dest, segment->text,
882 (traditional_numbering_scheme
883 ? m & MODE_ALL
884 : ((m & S_ISUID ? 04000 : 0)
885 | (m & S_ISGID ? 02000 : 0)
886 | (m & S_ISVTX ? 01000 : 0)
887 | (m & S_IRUSR ? 00400 : 0)
888 | (m & S_IWUSR ? 00200 : 0)
889 | (m & S_IXUSR ? 00100 : 0)
890 | (m & S_IRGRP ? 00040 : 0)
891 | (m & S_IWGRP ? 00020 : 0)
892 | (m & S_IXGRP ? 00010 : 0)
893 | (m & S_IROTH ? 00004 : 0)
894 | (m & S_IWOTH ? 00002 : 0)
895 | (m & S_IXOTH ? 00001 : 0))));
897 break;
899 case 'n': /* number of links */
900 /* UNTRUSTED, probably unexploitable */
901 checked_fprintf (dest, segment->text,
902 human_readable ((uintmax_t) stat_buf->st_nlink,
903 hbuf,
904 human_ceiling,
905 1, 1));
906 break;
908 case 'p': /* pathname */
909 /* sanitised */
910 checked_print_quoted (dest, segment->text, pathname);
911 break;
913 case 'P': /* pathname with ARGV element stripped */
914 /* sanitised */
915 if (state.curdepth > 0)
917 cp = pathname + state.starting_path_length;
918 if (*cp == '/')
919 /* Move past the slash between the ARGV element
920 and the rest of the pathname. But if the ARGV element
921 ends in a slash, we didn't add another, so we've
922 already skipped past it. */
923 cp++;
925 else
927 cp = "";
929 checked_print_quoted (dest, segment->text, cp);
930 break;
932 case 's': /* size in bytes */
933 /* UNTRUSTED, probably unexploitable */
934 checked_fprintf (dest, segment->text,
935 human_readable ((uintmax_t) stat_buf->st_size,
936 hbuf, human_ceiling, 1, 1));
937 break;
939 case 'S': /* sparseness */
940 /* UNTRUSTED, probably unexploitable */
941 checked_fprintf (dest, segment->text, file_sparseness(stat_buf));;
942 break;
944 case 't': /* mtime in `ctime' format */
945 /* UNTRUSTED, probably unexploitable */
946 checked_fprintf (dest, segment->text,
947 ctime_format (get_stat_mtime(stat_buf)));
948 break;
950 case 'u': /* user name */
951 /* trusted */
952 /* (well, the actual user is selected by the user on systems
953 * where chown is not restricted, but the user name was
954 * selected by the system administrator)
957 struct passwd *p;
959 p = getpwuid (stat_buf->st_uid);
960 if (p)
962 segment->text[segment->text_len] = 's';
963 checked_fprintf (dest, segment->text, p->pw_name);
964 break;
966 /* else fallthru */
968 /* FALLTHROUGH*/ /* .. to case U */
970 case 'U': /* UID number */
971 /* UNTRUSTED, probably unexploitable */
972 checked_fprintf (dest, segment->text,
973 human_readable ((uintmax_t) stat_buf->st_uid, hbuf,
974 human_ceiling, 1, 1));
975 break;
977 /* %Y: type of file system entry like `ls -l`:
978 * (d,-,l,s,p,b,c,n) n=nonexistent(symlink)
980 case 'Y': /* in case of symlink */
981 /* trusted */
983 #ifdef S_ISLNK
984 if (S_ISLNK (stat_buf->st_mode))
986 struct stat sbuf;
987 /* If we would normally follow links, do not do so.
988 * If we would normally not follow links, do so.
990 if ((following_links() ? lstat : stat)
991 (state.rel_pathname, &sbuf) != 0)
993 if ( errno == ENOENT )
995 checked_fprintf (dest, segment->text, "N");
996 break;
998 else if ( errno == ELOOP )
1000 checked_fprintf (dest, segment->text, "L");
1001 break;
1003 else
1005 checked_fprintf (dest, segment->text, "?");
1006 error (0, errno, "%s",
1007 safely_quote_err_filename(0, pathname));
1008 /* exit_status = 1;
1009 return ; */
1010 break;
1013 checked_fprintf (dest, segment->text,
1014 mode_to_filetype(sbuf.st_mode & S_IFMT));
1016 #endif /* S_ISLNK */
1017 else
1019 checked_fprintf (dest, segment->text,
1020 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1023 break;
1025 case 'y':
1026 /* trusted */
1028 checked_fprintf (dest, segment->text,
1029 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1031 break;
1033 /* end of KIND_FORMAT case */
1034 break;
1038 boolean
1039 pred_fprintf (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1041 struct format_val *dest = &pred_ptr->args.printf_vec;
1042 struct segment *segment;
1044 for (segment = dest->segment; segment; segment = segment->next)
1046 if ( (KIND_FORMAT == segment->segkind) && segment->format_char[1]) /* Component of date. */
1048 struct timespec ts;
1049 int valid = 0;
1051 switch (segment->format_char[0])
1053 case 'A':
1054 ts = get_stat_atime(stat_buf);
1055 valid = 1;
1056 break;
1057 case 'B':
1058 ts = get_stat_birthtime(stat_buf);
1059 if ('@' == segment->format_char[1])
1060 valid = 1;
1061 else
1062 valid = (ts.tv_nsec >= 0);
1063 break;
1064 case 'C':
1065 ts = get_stat_ctime(stat_buf);
1066 valid = 1;
1067 break;
1068 case 'T':
1069 ts = get_stat_mtime(stat_buf);
1070 valid = 1;
1071 break;
1072 default:
1073 assert (0);
1074 abort ();
1076 /* We trust the output of format_date not to contain
1077 * nasty characters, though the value of the date
1078 * is itself untrusted data.
1080 if (valid)
1082 /* trusted */
1083 checked_fprintf (dest, segment->text,
1084 format_date (ts, segment->format_char[1]));
1086 else
1088 /* The specified timestamp is not available, output
1089 * nothing for the timestamp, but use the rest (so that
1090 * for example find foo -printf '[%Bs] %p\n' can print
1091 * "[] foo").
1093 /* trusted */
1094 checked_fprintf (dest, segment->text, "");
1097 else
1099 /* Print a segment which is not a date. */
1100 do_fprintf(dest, segment, pathname, stat_buf);
1103 return true;
1106 boolean
1107 pred_fstype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1109 (void) pathname;
1111 if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0)
1112 return true;
1113 else
1114 return false;
1117 boolean
1118 pred_gid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1120 (void) pathname;
1122 switch (pred_ptr->args.numinfo.kind)
1124 case COMP_GT:
1125 if (stat_buf->st_gid > pred_ptr->args.numinfo.l_val)
1126 return (true);
1127 break;
1128 case COMP_LT:
1129 if (stat_buf->st_gid < pred_ptr->args.numinfo.l_val)
1130 return (true);
1131 break;
1132 case COMP_EQ:
1133 if (stat_buf->st_gid == pred_ptr->args.numinfo.l_val)
1134 return (true);
1135 break;
1137 return (false);
1140 boolean
1141 pred_group (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1143 (void) pathname;
1145 if (pred_ptr->args.gid == stat_buf->st_gid)
1146 return (true);
1147 else
1148 return (false);
1151 boolean
1152 pred_ilname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1154 return match_lname (pathname, stat_buf, pred_ptr, true);
1157 /* Common code between -name, -iname. PATHNAME is being visited, STR
1158 is name to compare basename against, and FLAGS are passed to
1159 fnmatch. */
1160 static boolean
1161 pred_name_common (const char *pathname, const char *str, int flags)
1163 /* Prefer last_component over base_name, to avoid malloc when
1164 possible. */
1165 char *base = last_component (pathname);
1167 /* base is empty only if pathname is a file system root. But recall
1168 that 'find / -name /' is one of the few times where a '/' in the
1169 -name must actually find something. */
1170 if (!*base)
1172 boolean b;
1173 base = base_name (pathname);
1174 b = fnmatch (str, base, flags) == 0;
1175 free (base);
1176 return b;
1178 /* FNM_PERIOD is not used here because POSIX requires that it not be.
1179 * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1181 return fnmatch (str, base, flags) == 0;
1184 boolean
1185 pred_iname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1187 (void) stat_buf;
1188 return pred_name_common (pathname, pred_ptr->args.str, FNM_CASEFOLD);
1191 boolean
1192 pred_inum (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1194 (void) pathname;
1196 switch (pred_ptr->args.numinfo.kind)
1198 case COMP_GT:
1199 if (stat_buf->st_ino > pred_ptr->args.numinfo.l_val)
1200 return (true);
1201 break;
1202 case COMP_LT:
1203 if (stat_buf->st_ino < pred_ptr->args.numinfo.l_val)
1204 return (true);
1205 break;
1206 case COMP_EQ:
1207 if (stat_buf->st_ino == pred_ptr->args.numinfo.l_val)
1208 return (true);
1209 break;
1211 return (false);
1214 boolean
1215 pred_ipath (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1217 (void) stat_buf;
1219 if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0)
1220 return (true);
1221 return (false);
1224 boolean
1225 pred_links (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1227 (void) pathname;
1229 switch (pred_ptr->args.numinfo.kind)
1231 case COMP_GT:
1232 if (stat_buf->st_nlink > pred_ptr->args.numinfo.l_val)
1233 return (true);
1234 break;
1235 case COMP_LT:
1236 if (stat_buf->st_nlink < pred_ptr->args.numinfo.l_val)
1237 return (true);
1238 break;
1239 case COMP_EQ:
1240 if (stat_buf->st_nlink == pred_ptr->args.numinfo.l_val)
1241 return (true);
1242 break;
1244 return (false);
1247 boolean
1248 pred_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1250 return match_lname (pathname, stat_buf, pred_ptr, false);
1253 static boolean
1254 match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case)
1256 boolean ret = false;
1257 #ifdef S_ISLNK
1258 if (S_ISLNK (stat_buf->st_mode))
1260 char *linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
1261 if (linkname)
1263 if (fnmatch (pred_ptr->args.str, linkname,
1264 ignore_case ? FNM_CASEFOLD : 0) == 0)
1265 ret = true;
1266 free (linkname);
1269 #endif /* S_ISLNK */
1270 return ret;
1273 boolean
1274 pred_ls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1276 return pred_fls(pathname, stat_buf, pred_ptr);
1279 boolean
1280 pred_mmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1282 (void) &pathname;
1283 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, 60);
1286 boolean
1287 pred_mtime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1289 (void) pathname;
1290 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, DAYSECS);
1293 boolean
1294 pred_name (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1296 (void) stat_buf;
1297 return pred_name_common (pathname, pred_ptr->args.str, 0);
1300 boolean
1301 pred_negate (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1303 return !apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1306 boolean
1307 pred_newer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1309 (void) pathname;
1311 assert (COMP_GT == pred_ptr->args.reftime.kind);
1312 return compare_ts(get_stat_mtime(stat_buf), pred_ptr->args.reftime.ts) > 0;
1315 boolean
1316 pred_newerXY (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1318 struct timespec ts;
1319 boolean collected = false;
1321 assert (COMP_GT == pred_ptr->args.reftime.kind);
1323 switch (pred_ptr->args.reftime.xval)
1325 case XVAL_TIME:
1326 assert (pred_ptr->args.reftime.xval != XVAL_TIME);
1327 return false;
1329 case XVAL_ATIME:
1330 ts = get_stat_atime(stat_buf);
1331 collected = true;
1332 break;
1334 case XVAL_BIRTHTIME:
1335 ts = get_stat_birthtime(stat_buf);
1336 collected = true;
1337 if (ts.tv_nsec < 0);
1339 /* XXX: Cannot determine birth time. Warn once. */
1340 error(0, 0, _("Warning: cannot determine birth time of file %s"),
1341 safely_quote_err_filename(0, pathname));
1342 return false;
1344 break;
1346 case XVAL_CTIME:
1347 ts = get_stat_ctime(stat_buf);
1348 collected = true;
1349 break;
1351 case XVAL_MTIME:
1352 ts = get_stat_mtime(stat_buf);
1353 collected = true;
1354 break;
1357 assert (collected);
1358 return compare_ts(ts, pred_ptr->args.reftime.ts) > 0;
1361 boolean
1362 pred_nogroup (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1364 (void) pathname;
1365 (void) pred_ptr;
1367 #ifdef CACHE_IDS
1368 extern char *gid_unused;
1370 return gid_unused[(unsigned) stat_buf->st_gid];
1371 #else
1372 return getgrgid (stat_buf->st_gid) == NULL;
1373 #endif
1376 boolean
1377 pred_nouser (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1379 #ifdef CACHE_IDS
1380 extern char *uid_unused;
1381 #endif
1383 (void) pathname;
1384 (void) pred_ptr;
1386 #ifdef CACHE_IDS
1387 return uid_unused[(unsigned) stat_buf->st_uid];
1388 #else
1389 return getpwuid (stat_buf->st_uid) == NULL;
1390 #endif
1394 static boolean
1395 is_ok(const char *program, const char *arg)
1397 fflush (stdout);
1398 /* The draft open standard requires that, in the POSIX locale,
1399 the last non-blank character of this prompt be '?'.
1400 The exact format is not specified.
1401 This standard does not have requirements for locales other than POSIX
1403 /* XXX: printing UNTRUSTED data here. */
1404 fprintf (stderr, _("< %s ... %s > ? "), program, arg);
1405 fflush (stderr);
1406 return yesno();
1409 boolean
1410 pred_ok (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1412 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1413 return new_impl_pred_exec (get_start_dirfd(),
1414 pathname, stat_buf, pred_ptr, NULL, 0);
1415 else
1416 return false;
1419 boolean
1420 pred_okdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1422 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
1423 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1424 return new_impl_pred_exec (get_current_dirfd(),
1425 state.rel_pathname, stat_buf, pred_ptr,
1426 prefix, (prefix ? 2 : 0));
1427 else
1428 return false;
1431 boolean
1432 pred_openparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1434 (void) pathname;
1435 (void) stat_buf;
1436 (void) pred_ptr;
1437 return true;
1440 boolean
1441 pred_or (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1443 if (pred_ptr->pred_left == NULL
1444 || !apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
1446 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1448 else
1449 return true;
1452 boolean
1453 pred_path (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1455 (void) stat_buf;
1456 if (fnmatch (pred_ptr->args.str, pathname, 0) == 0)
1457 return (true);
1458 return (false);
1461 boolean
1462 pred_perm (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1464 mode_t mode = stat_buf->st_mode;
1465 mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0];
1466 (void) pathname;
1467 switch (pred_ptr->args.perm.kind)
1469 case PERM_AT_LEAST:
1470 return (mode & perm_val) == perm_val;
1471 break;
1473 case PERM_ANY:
1474 /* True if any of the bits set in the mask are also set in the file's mode.
1477 * Otherwise, if onum is prefixed by a hyphen, the primary shall
1478 * evaluate as true if at least all of the bits specified in
1479 * onum that are also set in the octal mask 07777 are set.
1481 * Eric Blake's interpretation is that the mode argument is zero,
1484 if (0 == perm_val)
1485 return true; /* Savannah bug 14748; we used to return false */
1486 else
1487 return (mode & perm_val) != 0;
1488 break;
1490 case PERM_EXACT:
1491 return (mode & MODE_ALL) == perm_val;
1492 break;
1494 default:
1495 abort ();
1496 break;
1501 struct access_check_args
1503 const char *filename;
1504 int access_type;
1505 int cb_errno;
1509 static int
1510 access_callback(void *context)
1512 int rv;
1513 struct access_check_args *args = context;
1514 if ((rv = access(args->filename, args->access_type)) < 0)
1515 args->cb_errno = errno;
1516 return rv;
1519 static int
1520 can_access(int access_type)
1522 struct access_check_args args;
1523 args.filename = state.rel_pathname;
1524 args.access_type = access_type;
1525 args.cb_errno = 0;
1526 return 0 == run_in_dir(state.cwd_dir_fd, access_callback, &args);
1530 boolean
1531 pred_executable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1533 (void) pathname;
1534 (void) stat_buf;
1535 (void) pred_ptr;
1537 return can_access(X_OK);
1540 boolean
1541 pred_readable (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(R_OK);
1550 boolean
1551 pred_writable (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(W_OK);
1560 boolean
1561 pred_print (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1563 (void) stat_buf;
1564 (void) pred_ptr;
1566 print_quoted(pred_ptr->args.printf_vec.stream,
1567 pred_ptr->args.printf_vec.quote_opts,
1568 pred_ptr->args.printf_vec.dest_is_tty,
1569 "%s\n", pathname);
1570 return true;
1573 boolean
1574 pred_print0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1576 return pred_fprint0(pathname, stat_buf, pred_ptr);
1579 boolean
1580 pred_prune (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1582 (void) pathname;
1583 (void) pred_ptr;
1585 if (options.do_dir_first == true &&
1586 stat_buf != NULL &&
1587 S_ISDIR(stat_buf->st_mode))
1588 state.stop_at_current_level = true;
1590 return (options.do_dir_first); /* This is what SunOS find seems to do. */
1593 boolean
1594 pred_quit (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1596 (void) pathname;
1597 (void) stat_buf;
1598 (void) pred_ptr;
1600 /* Run any cleanups. This includes executing any command lines
1601 * we have partly built but not executed.
1603 cleanup();
1605 /* Since -exec and friends don't leave child processes running in the
1606 * background, there is no need to wait for them here.
1608 exit(state.exit_status); /* 0 for success, etc. */
1611 boolean
1612 pred_regex (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1614 int len = strlen (pathname);
1615 (void) stat_buf;
1616 if (re_match (pred_ptr->args.regex, pathname, len, 0,
1617 (struct re_registers *) NULL) == len)
1618 return (true);
1619 return (false);
1622 boolean
1623 pred_size (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1625 uintmax_t f_val;
1627 (void) pathname;
1628 f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize)
1629 + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0));
1630 switch (pred_ptr->args.size.kind)
1632 case COMP_GT:
1633 if (f_val > pred_ptr->args.size.size)
1634 return (true);
1635 break;
1636 case COMP_LT:
1637 if (f_val < pred_ptr->args.size.size)
1638 return (true);
1639 break;
1640 case COMP_EQ:
1641 if (f_val == pred_ptr->args.size.size)
1642 return (true);
1643 break;
1645 return (false);
1648 boolean
1649 pred_samefile (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1651 /* Potential optimisation: because of the loop protection, we always
1652 * know the device of the current directory, hence the device number
1653 * of the file we're currently considering. If -L is not in effect,
1654 * and the device number of the file we're looking for is not the
1655 * same as the device number of the current directory, this
1656 * predicate cannot return true. Hence there would be no need to
1657 * stat the file we're looking at.
1659 (void) pathname;
1661 /* We will often still have an fd open on the file under consideration,
1662 * but that's just to ensure inode number stability by maintaining
1663 * a reference to it; we don't need the file for anything else.
1665 return stat_buf->st_ino == pred_ptr->args.samefileid.ino
1666 && stat_buf->st_dev == pred_ptr->args.samefileid.dev;
1669 boolean
1670 pred_true (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1672 (void) pathname;
1673 (void) stat_buf;
1674 (void) pred_ptr;
1675 return true;
1678 boolean
1679 pred_type (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1681 mode_t mode;
1682 mode_t type = pred_ptr->args.type;
1684 assert (state.have_type);
1686 if (0 == state.type)
1688 /* This can sometimes happen with broken NFS servers.
1689 * See Savannah bug #16378.
1691 return false;
1694 (void) pathname;
1696 if (state.have_stat)
1697 mode = stat_buf->st_mode;
1698 else
1699 mode = state.type;
1701 #ifndef S_IFMT
1702 /* POSIX system; check `mode' the slow way. */
1703 if ((S_ISBLK (mode) && type == S_IFBLK)
1704 || (S_ISCHR (mode) && type == S_IFCHR)
1705 || (S_ISDIR (mode) && type == S_IFDIR)
1706 || (S_ISREG (mode) && type == S_IFREG)
1707 #ifdef S_IFLNK
1708 || (S_ISLNK (mode) && type == S_IFLNK)
1709 #endif
1710 #ifdef S_IFIFO
1711 || (S_ISFIFO (mode) && type == S_IFIFO)
1712 #endif
1713 #ifdef S_IFSOCK
1714 || (S_ISSOCK (mode) && type == S_IFSOCK)
1715 #endif
1716 #ifdef S_IFDOOR
1717 || (S_ISDOOR (mode) && type == S_IFDOOR)
1718 #endif
1720 #else /* S_IFMT */
1721 /* Unix system; check `mode' the fast way. */
1722 if ((mode & S_IFMT) == type)
1723 #endif /* S_IFMT */
1724 return (true);
1725 else
1726 return (false);
1729 boolean
1730 pred_uid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1732 (void) pathname;
1733 switch (pred_ptr->args.numinfo.kind)
1735 case COMP_GT:
1736 if (stat_buf->st_uid > pred_ptr->args.numinfo.l_val)
1737 return (true);
1738 break;
1739 case COMP_LT:
1740 if (stat_buf->st_uid < pred_ptr->args.numinfo.l_val)
1741 return (true);
1742 break;
1743 case COMP_EQ:
1744 if (stat_buf->st_uid == pred_ptr->args.numinfo.l_val)
1745 return (true);
1746 break;
1748 return (false);
1751 boolean
1752 pred_used (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1754 struct timespec delta, at, ct;
1756 (void) pathname;
1758 /* TODO: this needs to be retested carefully (manually, if necessary) */
1759 at = get_stat_atime(stat_buf);
1760 ct = get_stat_ctime(stat_buf);
1761 delta.tv_sec = at.tv_sec - ct.tv_sec;
1762 delta.tv_nsec = at.tv_nsec - ct.tv_nsec;
1763 if (delta.tv_nsec < 0)
1765 delta.tv_nsec += 1000000000;
1766 delta.tv_sec -= 1;
1768 return pred_timewindow(delta, pred_ptr, DAYSECS);
1771 boolean
1772 pred_user (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1774 (void) pathname;
1775 if (pred_ptr->args.uid == stat_buf->st_uid)
1776 return (true);
1777 else
1778 return (false);
1781 boolean
1782 pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1784 struct stat sbuf; /* local copy, not stat_buf because we're using a different stat method */
1785 int (*ystat) (const char*, struct stat *p);
1787 /* If we would normally stat the link itself, stat the target instead.
1788 * If we would normally follow the link, stat the link itself instead.
1790 if (following_links())
1791 ystat = optionp_stat;
1792 else
1793 ystat = optionl_stat;
1795 set_stat_placeholders(&sbuf);
1796 if ((*ystat) (state.rel_pathname, &sbuf) != 0)
1798 if (following_links() && errno == ENOENT)
1800 /* If we failed to follow the symlink,
1801 * fall back on looking at the symlink itself.
1803 /* Mimic behavior of ls -lL. */
1804 return (pred_type (pathname, stat_buf, pred_ptr));
1806 else
1808 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
1809 state.exit_status = 1;
1811 return false;
1813 /* Now that we have our stat() information, query it in the same
1814 * way that -type does.
1816 return (pred_type (pathname, &sbuf, pred_ptr));
1819 /* 1) fork to get a child; parent remembers the child pid
1820 2) child execs the command requested
1821 3) parent waits for child; checks for proper pid of child
1823 Possible returns:
1825 ret errno status(h) status(l)
1827 pid x signal# 0177 stopped
1828 pid x exit arg 0 term by _exit
1829 pid x 0 signal # term by signal
1830 -1 EINTR parent got signal
1831 -1 other some other kind of error
1833 Return true only if the pid matches, status(l) is
1834 zero, and the exit arg (status high) is 0.
1835 Otherwise return false, possibly printing an error message. */
1838 static boolean
1839 prep_child_for_exec (boolean close_stdin, int dirfd)
1841 boolean ok = true;
1842 if (close_stdin)
1844 const char inputfile[] = "/dev/null";
1846 if (close(0) < 0)
1848 error(0, errno, _("Cannot close standard input"));
1849 ok = false;
1851 else
1853 if (open(inputfile, O_RDONLY
1854 #if defined O_LARGEFILE
1855 |O_LARGEFILE
1856 #endif
1857 ) < 0)
1859 /* This is not entirely fatal, since
1860 * executing the child with a closed
1861 * stdin is almost as good as executing it
1862 * with its stdin attached to /dev/null.
1864 error (0, errno, "%s", safely_quote_err_filename(0, inputfile));
1865 /* do not set ok=false, it is OK to continue anyway. */
1870 /* Even if DebugSearch is set, don't announce our change of
1871 * directory, since we're not going to emit a subsequent
1872 * announcement of a call to stat() anyway, as we're about to exec
1873 * something.
1875 if (dirfd != AT_FDCWD)
1877 assert (dirfd >= 0);
1878 if (0 != fchdir(dirfd))
1880 /* If we cannot execute our command in the correct directory,
1881 * we should not execute it at all.
1883 error(0, errno, _("Failed to change directory"));
1884 ok = false;
1887 return ok;
1893 launch (const struct buildcmd_control *ctl,
1894 struct buildcmd_state *buildstate)
1896 int wait_status;
1897 pid_t child_pid;
1898 static int first_time = 1;
1899 const struct exec_val *execp = buildstate->usercontext;
1901 if (!execp->use_current_dir)
1903 assert (starting_desc >= 0);
1904 assert (execp->dirfd == starting_desc);
1908 /* Null terminate the arg list. */
1909 bc_push_arg (ctl, buildstate, (char *) NULL, 0, NULL, 0, false);
1911 /* Make sure output of command doesn't get mixed with find output. */
1912 fflush (stdout);
1913 fflush (stderr);
1915 /* Make sure to listen for the kids. */
1916 if (first_time)
1918 first_time = 0;
1919 signal (SIGCHLD, SIG_DFL);
1922 child_pid = fork ();
1923 if (child_pid == -1)
1924 error (1, errno, _("cannot fork"));
1925 if (child_pid == 0)
1927 /* We are the child. */
1928 assert (starting_desc >= 0);
1929 if (!prep_child_for_exec(execp->close_stdin, execp->dirfd))
1931 _exit(1);
1934 execvp (buildstate->cmd_argv[0], buildstate->cmd_argv);
1935 error (0, errno, "%s",
1936 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1937 _exit (1);
1941 /* In parent; set up for next time. */
1942 bc_clear_args(ctl, buildstate);
1945 while (waitpid (child_pid, &wait_status, 0) == (pid_t) -1)
1947 if (errno != EINTR)
1949 error (0, errno, _("error waiting for %s"),
1950 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1951 state.exit_status = 1;
1952 return 0; /* FAIL */
1956 if (WIFSIGNALED (wait_status))
1958 error (0, 0, _("%s terminated by signal %d"),
1959 quotearg_n_style(0, options.err_quoting_style,
1960 buildstate->cmd_argv[0]),
1961 WTERMSIG (wait_status));
1963 if (execp->multiple)
1965 /* -exec \; just returns false if the invoked command fails.
1966 * -exec {} + returns true if the invoked command fails, but
1967 * sets the program exit status.
1969 state.exit_status = 1;
1972 return 1; /* OK */
1975 if (0 == WEXITSTATUS (wait_status))
1977 return 1; /* OK */
1979 else
1981 if (execp->multiple)
1983 /* -exec \; just returns false if the invoked command fails.
1984 * -exec {} + returns true if the invoked command fails, but
1985 * sets the program exit status.
1987 state.exit_status = 1;
1989 return 0; /* FAIL */
1995 /* Return a static string formatting the time WHEN according to the
1996 * strftime format character KIND.
1998 * This function contains a number of assertions. These look like
1999 * runtime checks of the results of computations, which would be a
2000 * problem since external events should not be tested for with
2001 * "assert" (instead you should use "if"). However, they are not
2002 * really runtime checks. The assertions actually exist to verify
2003 * that the various buffers are correctly sized.
2005 static char *
2006 format_date (struct timespec ts, int kind)
2008 /* In theory, we use an extra 10 characters for 9 digits of
2009 * nanoseconds and 1 for the decimal point. However, the real
2010 * world is more complex than that.
2012 * For example, some systems return junk in the tv_nsec part of
2013 * st_birthtime. An example of this is the NetBSD-4.0-RELENG kernel
2014 * (at Sat Mar 24 18:46:46 2007) running a NetBSD-3.1-RELEASE
2015 * runtime and examining files on an msdos filesytem. So for that
2016 * reason we set NS_BUF_LEN to 32, which is simply "long enough" as
2017 * opposed to "exactly the right size". Note that the behaviour of
2018 * NetBSD appears to be a result of the use of uninitialised data,
2019 * as it's not 100% reproducible (more like 25%).
2021 enum {
2022 NS_BUF_LEN = 32,
2023 DATE_LEN_PERCENT_APLUS=21 /* length of result of %A+ (it's longer than %c)*/
2025 static char buf[128u+10u + MAX(DATE_LEN_PERCENT_APLUS,
2026 MAX (LONGEST_HUMAN_READABLE + 2, NS_BUF_LEN+64+200))];
2027 char ns_buf[NS_BUF_LEN]; /* -.9999999990 (- sign can happen!)*/
2028 int charsprinted, need_ns_suffix;
2029 struct tm *tm;
2030 char fmt[6];
2032 /* human_readable() assumes we pass a buffer which is at least as
2033 * long as LONGEST_HUMAN_READABLE. We use an assertion here to
2034 * ensure that no nasty unsigned overflow happend in our calculation
2035 * of the size of buf. Do the assertion here rather than in the
2036 * code for %@ so that we find the problem quickly if it exists. If
2037 * you want to submit a patch to move this into the if statement, go
2038 * ahead, I'll apply it. But include performance timings
2039 * demonstrating that the performance difference is actually
2040 * measurable.
2042 verify (sizeof(buf) >= LONGEST_HUMAN_READABLE);
2044 charsprinted = 0;
2045 need_ns_suffix = 0;
2047 /* Format the main part of the time. */
2048 if (kind == '+')
2050 strcpy (fmt, "%F+%T");
2051 need_ns_suffix = 1;
2053 else
2055 fmt[0] = '%';
2056 fmt[1] = kind;
2057 fmt[2] = '\0';
2059 /* %a, %c, and %t are handled in ctime_format() */
2060 switch (kind)
2062 case 'S':
2063 case 'T':
2064 case 'X':
2065 case '@':
2066 need_ns_suffix = 1;
2067 break;
2068 default:
2069 need_ns_suffix = 0;
2070 break;
2074 if (need_ns_suffix)
2076 /* Format the nanoseconds part. Leave a trailing zero to
2077 * discourage people from writing scripts which extract the
2078 * fractional part of the timestamp by using column offsets.
2079 * The reason for discouraging this is that in the future, the
2080 * granularity may not be nanoseconds.
2082 ns_buf[0] = 0;
2083 charsprinted = snprintf(ns_buf, NS_BUF_LEN, ".%09ld0", (long int)ts.tv_nsec);
2084 assert (charsprinted < NS_BUF_LEN);
2087 if (kind != '@'
2088 && (tm = localtime (&ts.tv_sec))
2089 && strftime (buf, sizeof buf, fmt, tm))
2091 /* For %AS, %CS, %TS, add the fractional part of the seconds
2092 * information.
2094 if (need_ns_suffix)
2096 assert ((sizeof buf - strlen(buf)) > strlen(ns_buf));
2097 strcat(buf, ns_buf);
2099 return buf;
2101 else
2103 uintmax_t w = ts.tv_sec;
2104 size_t used, len, remaining;
2106 /* XXX: note that we are negating an unsigned type which is the
2107 * widest possible unsigned type.
2109 char *p = human_readable (ts.tv_sec < 0 ? -w : w, buf + 1,
2110 human_ceiling, 1, 1);
2111 assert (p > buf);
2112 assert (p < (buf + (sizeof buf)));
2113 if (ts.tv_sec < 0)
2114 *--p = '-'; /* XXX: Ugh, relying on internal details of human_readable(). */
2116 /* Add the nanoseconds part. Because we cannot enforce a
2117 * particlar implementation of human_readable, we cannot assume
2118 * any particular value for (p-buf). So we need to be careful
2119 * that there is enough space remaining in the buffer.
2121 if (need_ns_suffix)
2123 len = strlen(p);
2124 used = (p-buf) + len; /* Offset into buf of current end */
2125 assert (sizeof buf > used); /* Ensure we can perform subtraction safely. */
2126 remaining = sizeof buf - used - 1u; /* allow space for NUL */
2128 if (strlen(ns_buf) >= remaining)
2130 error(0, 0,
2131 "charsprinted=%ld but remaining=%lu: ns_buf=%s",
2132 (long)charsprinted, (unsigned long)remaining, ns_buf);
2134 assert (strlen(ns_buf) < remaining);
2135 strcat(p, ns_buf);
2137 return p;
2141 static const char *weekdays[] =
2143 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
2145 static char * months[] =
2147 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2148 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2152 static char *
2153 ctime_format (struct timespec ts)
2155 const struct tm * ptm;
2156 #define TIME_BUF_LEN 1024u
2157 static char resultbuf[TIME_BUF_LEN];
2158 int nout;
2160 ptm = localtime(&ts.tv_sec);
2161 if (ptm)
2163 assert (ptm->tm_wday >= 0);
2164 assert (ptm->tm_wday < 7);
2165 assert (ptm->tm_mon >= 0);
2166 assert (ptm->tm_mon < 12);
2167 assert (ptm->tm_hour >= 0);
2168 assert (ptm->tm_hour < 24);
2169 assert (ptm->tm_min < 60);
2170 assert (ptm->tm_sec <= 61); /* allows 2 leap seconds. */
2172 /* wkday mon mday hh:mm:ss.nnnnnnnnn yyyy */
2173 nout = snprintf(resultbuf, TIME_BUF_LEN,
2174 "%3s %3s %2d %02d:%02d:%02d.%010ld %04d",
2175 weekdays[ptm->tm_wday],
2176 months[ptm->tm_mon],
2177 ptm->tm_mday,
2178 ptm->tm_hour,
2179 ptm->tm_min,
2180 ptm->tm_sec,
2181 (long int)ts.tv_nsec,
2182 1900 + ptm->tm_year);
2184 assert (nout < TIME_BUF_LEN);
2185 return resultbuf;
2187 else
2189 /* The time cannot be represented as a struct tm.
2190 Output it as an integer. */
2191 return format_date (ts, '@');
2195 /* Copy STR into BUF and trim blanks from the end of BUF.
2196 Return BUF. */
2198 static char *
2199 blank_rtrim (str, buf)
2200 char *str;
2201 char *buf;
2203 int i;
2205 if (str == NULL)
2206 return (NULL);
2207 strcpy (buf, str);
2208 i = strlen (buf) - 1;
2209 while ((i >= 0) && ((buf[i] == ' ') || buf[i] == '\t'))
2210 i--;
2211 buf[++i] = '\0';
2212 return (buf);
2215 /* Print out the predicate list starting at NODE. */
2216 void
2217 print_list (FILE *fp, struct predicate *node)
2219 struct predicate *cur;
2220 char name[256];
2222 cur = node;
2223 while (cur != NULL)
2225 fprintf (fp, "[%s] ", blank_rtrim (cur->p_name, name));
2226 cur = cur->pred_next;
2228 fprintf (fp, "\n");
2231 /* Print out the predicate list starting at NODE. */
2232 static void
2233 print_parenthesised(FILE *fp, struct predicate *node)
2235 int parens = 0;
2237 if (node)
2239 if ((pred_is(node, pred_or) || pred_is(node, pred_and))
2240 && node->pred_left == NULL)
2242 /* We print "<nothing> or X" as just "X"
2243 * We print "<nothing> and X" as just "X"
2245 print_parenthesised(fp, node->pred_right);
2247 else
2249 if (node->pred_left || node->pred_right)
2250 parens = 1;
2252 if (parens)
2253 fprintf(fp, "%s", " ( ");
2254 print_optlist(fp, node);
2255 if (parens)
2256 fprintf(fp, "%s", " ) ");
2261 void
2262 print_optlist (FILE *fp, const struct predicate *p)
2264 if (p)
2266 print_parenthesised(fp, p->pred_left);
2267 fprintf (fp,
2268 "%s%s",
2269 p->need_stat ? "[call stat] " : "",
2270 p->need_type ? "[need type] " : "");
2271 print_predicate(fp, p);
2272 fprintf(fp, " [%g] ", p->est_success_rate);
2273 if (options.debug_options & DebugSuccessRates)
2275 fprintf(fp, "[%ld/%ld", p->perf.successes, p->perf.visits);
2276 if (p->perf.visits)
2278 double real_rate = (double)p->perf.successes / (double)p->perf.visits;
2279 fprintf(fp, "=%g] ", real_rate);
2281 else
2283 fprintf(fp, "=_] ");
2286 print_parenthesised(fp, p->pred_right);
2290 void show_success_rates(const struct predicate *p)
2292 if (options.debug_options & DebugSuccessRates)
2294 fprintf(stderr, "Predicate success rates after completion:\n");
2295 print_optlist(stderr, p);
2296 fprintf(stderr, "\n");
2303 #ifdef _NDEBUG
2304 /* If _NDEBUG is defined, the assertions will do nothing. Hence
2305 * there is no point in having a function body for pred_sanity_check()
2306 * if that preprocessor macro is defined.
2308 void
2309 pred_sanity_check(const struct predicate *predicates)
2311 /* Do nothing, since assert is a no-op with _NDEBUG set */
2312 return;
2314 #else
2315 void
2316 pred_sanity_check(const struct predicate *predicates)
2318 const struct predicate *p;
2320 for (p=predicates; p != NULL; p=p->pred_next)
2322 /* All predicates must do something. */
2323 assert (p->pred_func != NULL);
2325 /* All predicates must have a parser table entry. */
2326 assert (p->parser_entry != NULL);
2328 /* If the parser table tells us that just one predicate function is
2329 * possible, verify that that is still the one that is in effect.
2330 * If the parser has NULL for the predicate function, that means that
2331 * the parse_xxx function fills it in, so we can't check it.
2333 if (p->parser_entry->pred_func)
2335 assert (p->parser_entry->pred_func == p->pred_func);
2338 switch (p->parser_entry->type)
2340 /* Options all take effect during parsing, so there should
2341 * be no predicate entries corresponding to them. Hence we
2342 * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION
2343 * items.
2345 * This is a silly way of coding this test, but it prevents
2346 * a compiler warning (i.e. otherwise it would think that
2347 * there would be case statements missing).
2349 case ARG_OPTION:
2350 case ARG_POSITIONAL_OPTION:
2351 assert (p->parser_entry->type != ARG_OPTION);
2352 assert (p->parser_entry->type != ARG_POSITIONAL_OPTION);
2353 break;
2355 case ARG_ACTION:
2356 assert(p->side_effects); /* actions have side effects. */
2357 if (!pred_is(p, pred_prune) && !pred_is(p, pred_quit))
2359 /* actions other than -prune and -quit should
2360 * inhibit the default -print
2362 assert (p->no_default_print);
2364 break;
2366 /* We happen to know that the only user of ARG_SPECIAL_PARSE
2367 * is a test, so handle it like ARG_TEST.
2369 case ARG_SPECIAL_PARSE:
2370 case ARG_TEST:
2371 case ARG_PUNCTUATION:
2372 case ARG_NOOP:
2373 /* Punctuation and tests should have no side
2374 * effects and not inhibit default print.
2376 assert (!p->no_default_print);
2377 assert (!p->side_effects);
2378 break;
2382 #endif