cvsimport
[findutils.git] / find / pred.c
blobd758276f9f2e6e8ca8716d60ab083f0a62f25f6f
1 /* pred.c -- execute the expression tree.
2 Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2003,
3 2004, 2005, 2006, 2007, 2008 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: after the specified time but by not more than WINDOW seconds.
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 /* consider "find . -mtime 0".
293 * Here, the origin is exactly 86400 seconds before the start
294 * of the program (since -daystart was not specified). This
295 * function will be called with window=86400 and
296 * pred_ptr->args.reftime.ts as the origin. Hence a file
297 * created the instant the program starts will show a time
298 * difference (value of delta) of 86400. Similarly, a file
299 * created exactly 24h ago would be the newest file which was
300 * _not_ created today. So, if delta is 0.0, the file
301 * was not created today. If the delta is 86400, the file
302 * was created this instant.
304 double delta = ts_difference(ts, pred_ptr->args.reftime.ts);
305 return (delta > 0.0 && delta <= window);
308 assert (0);
309 abort ();
313 boolean
314 pred_amin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
316 (void) &pathname;
317 return pred_timewindow(get_stat_atime(stat_buf), pred_ptr, 60);
320 boolean
321 pred_and (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
323 if (pred_ptr->pred_left == NULL
324 || apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
326 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
328 else
329 return false;
332 boolean
333 pred_anewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
335 (void) &pathname;
336 assert (COMP_GT == pred_ptr->args.reftime.kind);
337 return compare_ts(get_stat_atime(stat_buf), pred_ptr->args.reftime.ts) > 0;
340 boolean
341 pred_atime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
343 (void) &pathname;
344 return pred_timewindow(get_stat_atime(stat_buf), pred_ptr, DAYSECS);
347 boolean
348 pred_closeparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
350 (void) &pathname;
351 (void) &stat_buf;
352 (void) &pred_ptr;
354 return true;
357 boolean
358 pred_cmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
360 (void) pathname;
361 return pred_timewindow(get_stat_ctime(stat_buf), pred_ptr, 60);
364 boolean
365 pred_cnewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
367 (void) pathname;
369 assert (COMP_GT == pred_ptr->args.reftime.kind);
370 return compare_ts(get_stat_ctime(stat_buf), pred_ptr->args.reftime.ts) > 0;
373 boolean
374 pred_comma (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
376 if (pred_ptr->pred_left != NULL)
378 apply_predicate(pathname, stat_buf,pred_ptr->pred_left);
380 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
383 boolean
384 pred_ctime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
386 (void) &pathname;
387 return pred_timewindow(get_stat_ctime(stat_buf), pred_ptr, DAYSECS);
390 static boolean
391 perform_delete(int flags)
393 return 0 == unlinkat(state.cwd_dir_fd, state.rel_pathname, flags);
397 boolean
398 pred_delete (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
400 (void) pred_ptr;
401 (void) stat_buf;
402 if (strcmp (state.rel_pathname, "."))
404 int flags=0;
405 if (state.have_stat && S_ISDIR(stat_buf->st_mode))
406 flags |= AT_REMOVEDIR;
407 if (perform_delete(flags))
409 return true;
411 else
413 if (EISDIR == errno)
415 if ((flags & AT_REMOVEDIR) == 0)
417 /* unlink() operation failed because we should have done rmdir(). */
418 flags |= AT_REMOVEDIR;
419 if (perform_delete(flags))
420 return true;
424 error (0, errno, _("cannot delete %s"),
425 safely_quote_err_filename(0, pathname));
426 /* Previously I had believed that having the -delete action
427 * return false provided the user with control over whether an
428 * error message is issued. While this is true, the policy of
429 * not affecting the exit status is contrary to the POSIX
430 * requirement that diagnostic messages are accompanied by a
431 * nonzero exit status. While -delete is not a POSIX option and
432 * we can therefore opt not to follow POSIX in this case, that
433 * seems somewhat arbitrary and confusing. So, as of
434 * findutils-4.3.11, we also set the exit status in this case.
436 state.exit_status = 1;
437 return false;
439 else
441 /* nothing to do. */
442 return true;
446 boolean
447 pred_empty (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
449 (void) pathname;
450 (void) pred_ptr;
452 if (S_ISDIR (stat_buf->st_mode))
454 int fd;
455 DIR *d;
456 struct dirent *dp;
457 boolean empty = true;
459 errno = 0;
460 if ((fd = openat(state.cwd_dir_fd, state.rel_pathname, O_RDONLY
461 #if defined O_LARGEFILE
462 |O_LARGEFILE
463 #endif
464 )) < 0)
466 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
467 state.exit_status = 1;
468 return false;
470 d = fdopendir (fd);
471 if (d == NULL)
473 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
474 state.exit_status = 1;
475 return false;
477 for (dp = readdir (d); dp; dp = readdir (d))
479 if (dp->d_name[0] != '.'
480 || (dp->d_name[1] != '\0'
481 && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
483 empty = false;
484 break;
487 if (CLOSEDIR (d))
489 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
490 state.exit_status = 1;
491 return false;
493 return (empty);
495 else if (S_ISREG (stat_buf->st_mode))
496 return (stat_buf->st_size == 0);
497 else
498 return (false);
501 static boolean
502 new_impl_pred_exec (int dir_fd, const char *pathname,
503 struct stat *stat_buf,
504 struct predicate *pred_ptr,
505 const char *prefix, size_t pfxlen)
507 struct exec_val *execp = &pred_ptr->args.exec_vec;
508 size_t len = strlen(pathname);
510 (void) stat_buf;
511 execp->dir_fd = dir_fd;
512 if (execp->multiple)
514 /* Push the argument onto the current list.
515 * The command may or may not be run at this point,
516 * depending on the command line length limits.
518 bc_push_arg(&execp->ctl,
519 &execp->state,
520 pathname, len+1,
521 prefix, pfxlen,
524 /* remember that there are pending execdirs. */
525 state.execdirs_outstanding = true;
527 /* POSIX: If the primary expression is punctuated by a plus
528 * sign, the primary shall always evaluate as true
530 return true;
532 else
534 int i;
536 for (i=0; i<execp->num_args; ++i)
538 bc_do_insert(&execp->ctl,
539 &execp->state,
540 execp->replace_vec[i],
541 strlen(execp->replace_vec[i]),
542 prefix, pfxlen,
543 pathname, len,
547 /* Actually invoke the command. */
548 return execp->ctl.exec_callback(&execp->ctl,
549 &execp->state);
554 boolean
555 pred_exec (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
557 return new_impl_pred_exec(get_start_dirfd(),
558 pathname, stat_buf, pred_ptr, NULL, 0);
561 boolean
562 pred_execdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
564 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
565 (void) &pathname;
566 return new_impl_pred_exec (get_current_dirfd(),
567 state.rel_pathname, stat_buf, pred_ptr,
568 prefix, (prefix ? 2 : 0));
571 boolean
572 pred_false (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
574 (void) &pathname;
575 (void) &stat_buf;
576 (void) &pred_ptr;
579 return (false);
582 boolean
583 pred_fls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
585 FILE * stream = pred_ptr->args.printf_vec.stream;
586 list_file (pathname, state.cwd_dir_fd, state.rel_pathname, stat_buf,
587 options.start_time.tv_sec,
588 options.output_block_size,
589 pred_ptr->literal_control_chars, stream);
590 return true;
593 boolean
594 pred_fprint (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
596 (void) &pathname;
597 (void) &stat_buf;
599 print_quoted(pred_ptr->args.printf_vec.stream,
600 pred_ptr->args.printf_vec.quote_opts,
601 pred_ptr->args.printf_vec.dest_is_tty,
602 "%s\n",
603 pathname);
604 return true;
607 boolean
608 pred_fprint0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
610 FILE * fp = pred_ptr->args.printf_vec.stream;
612 (void) &stat_buf;
614 fputs (pathname, fp);
615 putc (0, fp);
616 return true;
621 static char*
622 mode_to_filetype(mode_t m)
624 #define HANDLE_TYPE(t,letter) if (m==t) { return letter; }
625 #ifdef S_IFREG
626 HANDLE_TYPE(S_IFREG, "f"); /* regular file */
627 #endif
628 #ifdef S_IFDIR
629 HANDLE_TYPE(S_IFDIR, "d"); /* directory */
630 #endif
631 #ifdef S_IFLNK
632 HANDLE_TYPE(S_IFLNK, "l"); /* symbolic link */
633 #endif
634 #ifdef S_IFSOCK
635 HANDLE_TYPE(S_IFSOCK, "s"); /* Unix domain socket */
636 #endif
637 #ifdef S_IFBLK
638 HANDLE_TYPE(S_IFBLK, "b"); /* block device */
639 #endif
640 #ifdef S_IFCHR
641 HANDLE_TYPE(S_IFCHR, "c"); /* character device */
642 #endif
643 #ifdef S_IFIFO
644 HANDLE_TYPE(S_IFIFO, "p"); /* FIFO */
645 #endif
646 #ifdef S_IFDOOR
647 HANDLE_TYPE(S_IFDOOR, "D"); /* Door (e.g. on Solaris) */
648 #endif
649 return "U"; /* Unknown */
652 static double
653 file_sparseness(const struct stat *p)
655 #if defined HAVE_STRUCT_STAT_ST_BLOCKS
656 if (0 == p->st_size)
658 if (0 == p->st_blocks)
659 return 1.0;
660 else
661 return p->st_blocks < 0 ? -HUGE_VAL : HUGE_VAL;
663 else
665 double blklen = file_blocksize(p) * (double)p->st_blocks;
666 return blklen / p->st_size;
668 #else
669 return 1.0;
670 #endif
675 static void
676 checked_fprintf(struct format_val *dest, const char *fmt, ...)
678 int rv;
679 va_list ap;
681 va_start(ap, fmt);
682 rv = vfprintf(dest->stream, fmt, ap);
683 if (rv < 0)
684 nonfatal_file_error(dest->filename);
688 static void
689 checked_print_quoted (struct format_val *dest,
690 const char *format, const char *s)
692 int rv = print_quoted(dest->stream, dest->quote_opts, dest->dest_is_tty,
693 format, s);
694 if (rv < 0)
695 nonfatal_file_error(dest->filename);
699 static void
700 checked_fwrite(void *p, size_t siz, size_t nmemb, struct format_val *dest)
702 int items_written = fwrite(p, siz, nmemb, dest->stream);
703 if (items_written < nmemb)
704 nonfatal_file_error(dest->filename);
707 static void
708 checked_fflush(struct format_val *dest)
710 if (0 != fflush(dest->stream))
712 nonfatal_file_error(dest->filename);
716 static void
717 do_fprintf(struct format_val *dest,
718 struct segment *segment,
719 const char *pathname,
720 const struct stat *stat_buf)
722 char hbuf[LONGEST_HUMAN_READABLE + 1];
723 const char *cp;
725 switch (segment->segkind)
727 case KIND_PLAIN: /* Plain text string (no % conversion). */
728 /* trusted */
729 checked_fwrite(segment->text, 1, segment->text_len, dest);
730 break;
732 case KIND_STOP: /* Terminate argument and flush output. */
733 /* trusted */
734 checked_fwrite(segment->text, 1, segment->text_len, dest);
735 checked_fflush(dest);
736 break;
738 case KIND_FORMAT:
739 switch (segment->format_char[0])
741 case 'a': /* atime in `ctime' format. */
742 /* UNTRUSTED, probably unexploitable */
743 checked_fprintf (dest, segment->text, ctime_format (get_stat_atime(stat_buf)));
744 break;
745 case 'b': /* size in 512-byte blocks */
746 /* UNTRUSTED, probably unexploitable */
747 checked_fprintf (dest, segment->text,
748 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
749 hbuf, human_ceiling,
750 ST_NBLOCKSIZE, 512));
751 break;
752 case 'c': /* ctime in `ctime' format */
753 /* UNTRUSTED, probably unexploitable */
754 checked_fprintf (dest, segment->text, ctime_format (get_stat_ctime(stat_buf)));
755 break;
756 case 'd': /* depth in search tree */
757 /* UNTRUSTED, probably unexploitable */
758 checked_fprintf (dest, segment->text, state.curdepth);
759 break;
760 case 'D': /* Device on which file exists (stat.st_dev) */
761 /* trusted */
762 checked_fprintf (dest, segment->text,
763 human_readable ((uintmax_t) stat_buf->st_dev, hbuf,
764 human_ceiling, 1, 1));
765 break;
766 case 'f': /* base name of path */
767 /* sanitised */
769 char *base = base_name (pathname);
770 checked_print_quoted (dest, segment->text, base);
771 free (base);
773 break;
774 case 'F': /* file system type */
775 /* trusted */
776 checked_print_quoted (dest, segment->text, filesystem_type (stat_buf, pathname));
777 break;
778 case 'g': /* group name */
779 /* trusted */
780 /* (well, the actual group is selected by the user but
781 * its name was selected by the system administrator)
784 struct group *g;
786 g = getgrgid (stat_buf->st_gid);
787 if (g)
789 segment->text[segment->text_len] = 's';
790 checked_fprintf (dest, segment->text, g->gr_name);
791 break;
793 else
795 /* Do nothing. */
796 /*FALLTHROUGH*/
799 /*FALLTHROUGH*/ /*...sometimes, so 'G' case.*/
801 case 'G': /* GID number */
802 /* UNTRUSTED, probably unexploitable */
803 checked_fprintf (dest, segment->text,
804 human_readable ((uintmax_t) stat_buf->st_gid, hbuf,
805 human_ceiling, 1, 1));
806 break;
807 case 'h': /* leading directories part of path */
808 /* sanitised */
810 cp = strrchr (pathname, '/');
811 if (cp == NULL) /* No leading directories. */
813 /* If there is no slash in the pathname, we still
814 * print the string because it contains characters
815 * other than just '%s'. The %h expands to ".".
817 checked_print_quoted (dest, segment->text, ".");
819 else
821 char *s = strdup(pathname);
822 s[cp - pathname] = 0;
823 checked_print_quoted (dest, segment->text, s);
824 free(s);
827 break;
829 case 'H': /* ARGV element file was found under */
830 /* trusted */
832 char *s = xmalloc(state.starting_path_length+1);
833 memcpy(s, pathname, state.starting_path_length);
834 s[state.starting_path_length] = 0;
835 checked_fprintf (dest, segment->text, s);
836 free(s);
838 break;
840 case 'i': /* inode number */
841 /* UNTRUSTED, but not exploitable I think */
842 checked_fprintf (dest, segment->text,
843 human_readable ((uintmax_t) stat_buf->st_ino, hbuf,
844 human_ceiling,
845 1, 1));
846 break;
847 case 'k': /* size in 1K blocks */
848 /* UNTRUSTED, but not exploitable I think */
849 checked_fprintf (dest, segment->text,
850 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
851 hbuf, human_ceiling,
852 ST_NBLOCKSIZE, 1024));
853 break;
854 case 'l': /* object of symlink */
855 /* sanitised */
856 #ifdef S_ISLNK
858 char *linkname = 0;
860 if (S_ISLNK (stat_buf->st_mode))
862 linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
863 if (linkname == 0)
864 state.exit_status = 1;
866 if (linkname)
868 checked_print_quoted (dest, segment->text, linkname);
869 free (linkname);
871 else
873 /* We still need to honour the field width etc., so this is
874 * not a no-op.
876 checked_print_quoted (dest, segment->text, "");
879 #endif /* S_ISLNK */
880 break;
882 case 'M': /* mode as 10 chars (eg., "-rwxr-x--x" */
883 /* UNTRUSTED, probably unexploitable */
885 char modestring[16] ;
886 filemodestring (stat_buf, modestring);
887 modestring[10] = '\0';
888 checked_fprintf (dest, segment->text, modestring);
890 break;
892 case 'm': /* mode as octal number (perms only) */
893 /* UNTRUSTED, probably unexploitable */
895 /* Output the mode portably using the traditional numbers,
896 even if the host unwisely uses some other numbering
897 scheme. But help the compiler in the common case where
898 the host uses the traditional numbering scheme. */
899 mode_t m = stat_buf->st_mode;
900 boolean traditional_numbering_scheme =
901 (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000
902 && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100
903 && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010
904 && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001);
905 checked_fprintf (dest, segment->text,
906 (traditional_numbering_scheme
907 ? m & MODE_ALL
908 : ((m & S_ISUID ? 04000 : 0)
909 | (m & S_ISGID ? 02000 : 0)
910 | (m & S_ISVTX ? 01000 : 0)
911 | (m & S_IRUSR ? 00400 : 0)
912 | (m & S_IWUSR ? 00200 : 0)
913 | (m & S_IXUSR ? 00100 : 0)
914 | (m & S_IRGRP ? 00040 : 0)
915 | (m & S_IWGRP ? 00020 : 0)
916 | (m & S_IXGRP ? 00010 : 0)
917 | (m & S_IROTH ? 00004 : 0)
918 | (m & S_IWOTH ? 00002 : 0)
919 | (m & S_IXOTH ? 00001 : 0))));
921 break;
923 case 'n': /* number of links */
924 /* UNTRUSTED, probably unexploitable */
925 checked_fprintf (dest, segment->text,
926 human_readable ((uintmax_t) stat_buf->st_nlink,
927 hbuf,
928 human_ceiling,
929 1, 1));
930 break;
932 case 'p': /* pathname */
933 /* sanitised */
934 checked_print_quoted (dest, segment->text, pathname);
935 break;
937 case 'P': /* pathname with ARGV element stripped */
938 /* sanitised */
939 if (state.curdepth > 0)
941 cp = pathname + state.starting_path_length;
942 if (*cp == '/')
943 /* Move past the slash between the ARGV element
944 and the rest of the pathname. But if the ARGV element
945 ends in a slash, we didn't add another, so we've
946 already skipped past it. */
947 cp++;
949 else
951 cp = "";
953 checked_print_quoted (dest, segment->text, cp);
954 break;
956 case 's': /* size in bytes */
957 /* UNTRUSTED, probably unexploitable */
958 checked_fprintf (dest, segment->text,
959 human_readable ((uintmax_t) stat_buf->st_size,
960 hbuf, human_ceiling, 1, 1));
961 break;
963 case 'S': /* sparseness */
964 /* UNTRUSTED, probably unexploitable */
965 checked_fprintf (dest, segment->text, file_sparseness(stat_buf));;
966 break;
968 case 't': /* mtime in `ctime' format */
969 /* UNTRUSTED, probably unexploitable */
970 checked_fprintf (dest, segment->text,
971 ctime_format (get_stat_mtime(stat_buf)));
972 break;
974 case 'u': /* user name */
975 /* trusted */
976 /* (well, the actual user is selected by the user on systems
977 * where chown is not restricted, but the user name was
978 * selected by the system administrator)
981 struct passwd *p;
983 p = getpwuid (stat_buf->st_uid);
984 if (p)
986 segment->text[segment->text_len] = 's';
987 checked_fprintf (dest, segment->text, p->pw_name);
988 break;
990 /* else fallthru */
992 /* FALLTHROUGH*/ /* .. to case U */
994 case 'U': /* UID number */
995 /* UNTRUSTED, probably unexploitable */
996 checked_fprintf (dest, segment->text,
997 human_readable ((uintmax_t) stat_buf->st_uid, hbuf,
998 human_ceiling, 1, 1));
999 break;
1001 /* %Y: type of file system entry like `ls -l`:
1002 * (d,-,l,s,p,b,c,n) n=nonexistent(symlink)
1004 case 'Y': /* in case of symlink */
1005 /* trusted */
1007 #ifdef S_ISLNK
1008 if (S_ISLNK (stat_buf->st_mode))
1010 struct stat sbuf;
1011 /* If we would normally follow links, do not do so.
1012 * If we would normally not follow links, do so.
1014 if ((following_links() ? lstat : stat)
1015 (state.rel_pathname, &sbuf) != 0)
1017 if ( errno == ENOENT )
1019 checked_fprintf (dest, segment->text, "N");
1020 break;
1022 else if ( errno == ELOOP )
1024 checked_fprintf (dest, segment->text, "L");
1025 break;
1027 else
1029 checked_fprintf (dest, segment->text, "?");
1030 error (0, errno, "%s",
1031 safely_quote_err_filename(0, pathname));
1032 /* exit_status = 1;
1033 return ; */
1034 break;
1037 checked_fprintf (dest, segment->text,
1038 mode_to_filetype(sbuf.st_mode & S_IFMT));
1040 #endif /* S_ISLNK */
1041 else
1043 checked_fprintf (dest, segment->text,
1044 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1047 break;
1049 case 'y':
1050 /* trusted */
1052 checked_fprintf (dest, segment->text,
1053 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1055 break;
1057 /* end of KIND_FORMAT case */
1058 break;
1062 boolean
1063 pred_fprintf (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1065 struct format_val *dest = &pred_ptr->args.printf_vec;
1066 struct segment *segment;
1068 for (segment = dest->segment; segment; segment = segment->next)
1070 if ( (KIND_FORMAT == segment->segkind) && segment->format_char[1]) /* Component of date. */
1072 struct timespec ts;
1073 int valid = 0;
1075 switch (segment->format_char[0])
1077 case 'A':
1078 ts = get_stat_atime(stat_buf);
1079 valid = 1;
1080 break;
1081 case 'B':
1082 ts = get_stat_birthtime(stat_buf);
1083 if ('@' == segment->format_char[1])
1084 valid = 1;
1085 else
1086 valid = (ts.tv_nsec >= 0);
1087 break;
1088 case 'C':
1089 ts = get_stat_ctime(stat_buf);
1090 valid = 1;
1091 break;
1092 case 'T':
1093 ts = get_stat_mtime(stat_buf);
1094 valid = 1;
1095 break;
1096 default:
1097 assert (0);
1098 abort ();
1100 /* We trust the output of format_date not to contain
1101 * nasty characters, though the value of the date
1102 * is itself untrusted data.
1104 if (valid)
1106 /* trusted */
1107 checked_fprintf (dest, segment->text,
1108 format_date (ts, segment->format_char[1]));
1110 else
1112 /* The specified timestamp is not available, output
1113 * nothing for the timestamp, but use the rest (so that
1114 * for example find foo -printf '[%Bs] %p\n' can print
1115 * "[] foo").
1117 /* trusted */
1118 checked_fprintf (dest, segment->text, "");
1121 else
1123 /* Print a segment which is not a date. */
1124 do_fprintf(dest, segment, pathname, stat_buf);
1127 return true;
1130 boolean
1131 pred_fstype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1133 (void) pathname;
1135 if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0)
1136 return true;
1137 else
1138 return false;
1141 boolean
1142 pred_gid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1144 (void) pathname;
1146 switch (pred_ptr->args.numinfo.kind)
1148 case COMP_GT:
1149 if (stat_buf->st_gid > pred_ptr->args.numinfo.l_val)
1150 return (true);
1151 break;
1152 case COMP_LT:
1153 if (stat_buf->st_gid < pred_ptr->args.numinfo.l_val)
1154 return (true);
1155 break;
1156 case COMP_EQ:
1157 if (stat_buf->st_gid == pred_ptr->args.numinfo.l_val)
1158 return (true);
1159 break;
1161 return (false);
1164 boolean
1165 pred_group (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1167 (void) pathname;
1169 if (pred_ptr->args.gid == stat_buf->st_gid)
1170 return (true);
1171 else
1172 return (false);
1175 boolean
1176 pred_ilname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1178 return match_lname (pathname, stat_buf, pred_ptr, true);
1181 /* Common code between -name, -iname. PATHNAME is being visited, STR
1182 is name to compare basename against, and FLAGS are passed to
1183 fnmatch. Recall that 'find / -name /' is one of the few times where a '/'
1184 in the -name must actually find something. */
1185 static boolean
1186 pred_name_common (const char *pathname, const char *str, int flags)
1188 boolean b;
1189 /* We used to use last_component() here, but that would not allow us to modify the
1190 * input string, which is const. We could optimise by duplicating the string only
1191 * if we need to modify it, and I'll do that if there is a measurable
1192 * performance difference on a machine built after 1990...
1194 char *base = base_name (pathname);
1195 /* remove trailing slashes, but leave "/" or "//foo" unchanged. */
1196 strip_trailing_slashes(base);
1198 /* FNM_PERIOD is not used here because POSIX requires that it not be.
1199 * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1201 b = fnmatch (str, base, flags) == 0;
1202 free (base);
1203 return b;
1206 boolean
1207 pred_iname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1209 (void) stat_buf;
1210 return pred_name_common (pathname, pred_ptr->args.str, FNM_CASEFOLD);
1213 boolean
1214 pred_inum (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1216 (void) pathname;
1218 switch (pred_ptr->args.numinfo.kind)
1220 case COMP_GT:
1221 if (stat_buf->st_ino > pred_ptr->args.numinfo.l_val)
1222 return (true);
1223 break;
1224 case COMP_LT:
1225 if (stat_buf->st_ino < pred_ptr->args.numinfo.l_val)
1226 return (true);
1227 break;
1228 case COMP_EQ:
1229 if (stat_buf->st_ino == pred_ptr->args.numinfo.l_val)
1230 return (true);
1231 break;
1233 return (false);
1236 boolean
1237 pred_ipath (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1239 (void) stat_buf;
1241 if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0)
1242 return (true);
1243 return (false);
1246 boolean
1247 pred_links (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1249 (void) pathname;
1251 switch (pred_ptr->args.numinfo.kind)
1253 case COMP_GT:
1254 if (stat_buf->st_nlink > pred_ptr->args.numinfo.l_val)
1255 return (true);
1256 break;
1257 case COMP_LT:
1258 if (stat_buf->st_nlink < pred_ptr->args.numinfo.l_val)
1259 return (true);
1260 break;
1261 case COMP_EQ:
1262 if (stat_buf->st_nlink == pred_ptr->args.numinfo.l_val)
1263 return (true);
1264 break;
1266 return (false);
1269 boolean
1270 pred_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1272 return match_lname (pathname, stat_buf, pred_ptr, false);
1275 static boolean
1276 match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case)
1278 boolean ret = false;
1279 #ifdef S_ISLNK
1280 if (S_ISLNK (stat_buf->st_mode))
1282 char *linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
1283 if (linkname)
1285 if (fnmatch (pred_ptr->args.str, linkname,
1286 ignore_case ? FNM_CASEFOLD : 0) == 0)
1287 ret = true;
1288 free (linkname);
1291 #endif /* S_ISLNK */
1292 return ret;
1295 boolean
1296 pred_ls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1298 return pred_fls(pathname, stat_buf, pred_ptr);
1301 boolean
1302 pred_mmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1304 (void) &pathname;
1305 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, 60);
1308 boolean
1309 pred_mtime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1311 (void) pathname;
1312 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, DAYSECS);
1315 boolean
1316 pred_name (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1318 (void) stat_buf;
1319 return pred_name_common (pathname, pred_ptr->args.str, 0);
1322 boolean
1323 pred_negate (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1325 return !apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1328 boolean
1329 pred_newer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1331 (void) pathname;
1333 assert (COMP_GT == pred_ptr->args.reftime.kind);
1334 return compare_ts(get_stat_mtime(stat_buf), pred_ptr->args.reftime.ts) > 0;
1337 boolean
1338 pred_newerXY (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1340 struct timespec ts;
1341 boolean collected = false;
1343 assert (COMP_GT == pred_ptr->args.reftime.kind);
1345 switch (pred_ptr->args.reftime.xval)
1347 case XVAL_TIME:
1348 assert (pred_ptr->args.reftime.xval != XVAL_TIME);
1349 return false;
1351 case XVAL_ATIME:
1352 ts = get_stat_atime(stat_buf);
1353 collected = true;
1354 break;
1356 case XVAL_BIRTHTIME:
1357 ts = get_stat_birthtime(stat_buf);
1358 collected = true;
1359 if (ts.tv_nsec < 0);
1361 /* XXX: Cannot determine birth time. Warn once. */
1362 error(0, 0, _("Warning: cannot determine birth time of file %s"),
1363 safely_quote_err_filename(0, pathname));
1364 return false;
1366 break;
1368 case XVAL_CTIME:
1369 ts = get_stat_ctime(stat_buf);
1370 collected = true;
1371 break;
1373 case XVAL_MTIME:
1374 ts = get_stat_mtime(stat_buf);
1375 collected = true;
1376 break;
1379 assert (collected);
1380 return compare_ts(ts, pred_ptr->args.reftime.ts) > 0;
1383 boolean
1384 pred_nogroup (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1386 (void) pathname;
1387 (void) pred_ptr;
1389 #ifdef CACHE_IDS
1390 extern char *gid_unused;
1392 return gid_unused[(unsigned) stat_buf->st_gid];
1393 #else
1394 return getgrgid (stat_buf->st_gid) == NULL;
1395 #endif
1398 boolean
1399 pred_nouser (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1401 #ifdef CACHE_IDS
1402 extern char *uid_unused;
1403 #endif
1405 (void) pathname;
1406 (void) pred_ptr;
1408 #ifdef CACHE_IDS
1409 return uid_unused[(unsigned) stat_buf->st_uid];
1410 #else
1411 return getpwuid (stat_buf->st_uid) == NULL;
1412 #endif
1416 static boolean
1417 is_ok(const char *program, const char *arg)
1419 fflush (stdout);
1420 /* The draft open standard requires that, in the POSIX locale,
1421 the last non-blank character of this prompt be '?'.
1422 The exact format is not specified.
1423 This standard does not have requirements for locales other than POSIX
1425 /* XXX: printing UNTRUSTED data here. */
1426 fprintf (stderr, _("< %s ... %s > ? "), program, arg);
1427 fflush (stderr);
1428 return yesno();
1431 boolean
1432 pred_ok (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1434 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1435 return new_impl_pred_exec (get_start_dirfd(),
1436 pathname, stat_buf, pred_ptr, NULL, 0);
1437 else
1438 return false;
1441 boolean
1442 pred_okdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1444 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
1445 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1446 return new_impl_pred_exec (get_current_dirfd(),
1447 state.rel_pathname, stat_buf, pred_ptr,
1448 prefix, (prefix ? 2 : 0));
1449 else
1450 return false;
1453 boolean
1454 pred_openparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1456 (void) pathname;
1457 (void) stat_buf;
1458 (void) pred_ptr;
1459 return true;
1462 boolean
1463 pred_or (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1465 if (pred_ptr->pred_left == NULL
1466 || !apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
1468 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1470 else
1471 return true;
1474 boolean
1475 pred_path (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1477 (void) stat_buf;
1478 if (fnmatch (pred_ptr->args.str, pathname, 0) == 0)
1479 return (true);
1480 return (false);
1483 boolean
1484 pred_perm (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1486 mode_t mode = stat_buf->st_mode;
1487 mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0];
1488 (void) pathname;
1489 switch (pred_ptr->args.perm.kind)
1491 case PERM_AT_LEAST:
1492 return (mode & perm_val) == perm_val;
1493 break;
1495 case PERM_ANY:
1496 /* True if any of the bits set in the mask are also set in the file's mode.
1499 * Otherwise, if onum is prefixed by a hyphen, the primary shall
1500 * evaluate as true if at least all of the bits specified in
1501 * onum that are also set in the octal mask 07777 are set.
1503 * Eric Blake's interpretation is that the mode argument is zero,
1506 if (0 == perm_val)
1507 return true; /* Savannah bug 14748; we used to return false */
1508 else
1509 return (mode & perm_val) != 0;
1510 break;
1512 case PERM_EXACT:
1513 return (mode & MODE_ALL) == perm_val;
1514 break;
1516 default:
1517 abort ();
1518 break;
1523 struct access_check_args
1525 const char *filename;
1526 int access_type;
1527 int cb_errno;
1531 static int
1532 access_callback(void *context)
1534 int rv;
1535 struct access_check_args *args = context;
1536 if ((rv = access(args->filename, args->access_type)) < 0)
1537 args->cb_errno = errno;
1538 return rv;
1541 static int
1542 can_access(int access_type)
1544 struct access_check_args args;
1545 args.filename = state.rel_pathname;
1546 args.access_type = access_type;
1547 args.cb_errno = 0;
1548 return 0 == run_in_dir(state.cwd_dir_fd, access_callback, &args);
1552 boolean
1553 pred_executable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1555 (void) pathname;
1556 (void) stat_buf;
1557 (void) pred_ptr;
1559 return can_access(X_OK);
1562 boolean
1563 pred_readable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1565 (void) pathname;
1566 (void) stat_buf;
1567 (void) pred_ptr;
1569 return can_access(R_OK);
1572 boolean
1573 pred_writable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1575 (void) pathname;
1576 (void) stat_buf;
1577 (void) pred_ptr;
1579 return can_access(W_OK);
1582 boolean
1583 pred_print (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1585 (void) stat_buf;
1586 (void) pred_ptr;
1588 print_quoted(pred_ptr->args.printf_vec.stream,
1589 pred_ptr->args.printf_vec.quote_opts,
1590 pred_ptr->args.printf_vec.dest_is_tty,
1591 "%s\n", pathname);
1592 return true;
1595 boolean
1596 pred_print0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1598 return pred_fprint0(pathname, stat_buf, pred_ptr);
1601 boolean
1602 pred_prune (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1604 (void) pathname;
1605 (void) pred_ptr;
1607 if (options.do_dir_first == true && /* no effect with -depth */
1608 stat_buf != NULL &&
1609 S_ISDIR(stat_buf->st_mode))
1610 state.stop_at_current_level = true;
1612 /* findutils used to return options.do_dir_first here, so that -prune
1613 * returns true only if -depth is not in effect. But POSIX requires
1614 * that -prune always evaluate as true.
1616 return true;
1619 boolean
1620 pred_quit (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1622 (void) pathname;
1623 (void) stat_buf;
1624 (void) pred_ptr;
1626 /* Run any cleanups. This includes executing any command lines
1627 * we have partly built but not executed.
1629 cleanup();
1631 /* Since -exec and friends don't leave child processes running in the
1632 * background, there is no need to wait for them here.
1634 exit(state.exit_status); /* 0 for success, etc. */
1637 boolean
1638 pred_regex (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1640 int len = strlen (pathname);
1641 (void) stat_buf;
1642 if (re_match (pred_ptr->args.regex, pathname, len, 0,
1643 (struct re_registers *) NULL) == len)
1644 return (true);
1645 return (false);
1648 boolean
1649 pred_size (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1651 uintmax_t f_val;
1653 (void) pathname;
1654 f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize)
1655 + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0));
1656 switch (pred_ptr->args.size.kind)
1658 case COMP_GT:
1659 if (f_val > pred_ptr->args.size.size)
1660 return (true);
1661 break;
1662 case COMP_LT:
1663 if (f_val < pred_ptr->args.size.size)
1664 return (true);
1665 break;
1666 case COMP_EQ:
1667 if (f_val == pred_ptr->args.size.size)
1668 return (true);
1669 break;
1671 return (false);
1674 boolean
1675 pred_samefile (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1677 /* Potential optimisation: because of the loop protection, we always
1678 * know the device of the current directory, hence the device number
1679 * of the file we're currently considering. If -L is not in effect,
1680 * and the device number of the file we're looking for is not the
1681 * same as the device number of the current directory, this
1682 * predicate cannot return true. Hence there would be no need to
1683 * stat the file we're looking at.
1685 (void) pathname;
1687 /* We will often still have an fd open on the file under consideration,
1688 * but that's just to ensure inode number stability by maintaining
1689 * a reference to it; we don't need the file for anything else.
1691 return stat_buf->st_ino == pred_ptr->args.samefileid.ino
1692 && stat_buf->st_dev == pred_ptr->args.samefileid.dev;
1695 boolean
1696 pred_true (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1698 (void) pathname;
1699 (void) stat_buf;
1700 (void) pred_ptr;
1701 return true;
1704 boolean
1705 pred_type (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1707 mode_t mode;
1708 mode_t type = pred_ptr->args.type;
1710 assert (state.have_type);
1712 if (0 == state.type)
1714 /* This can sometimes happen with broken NFS servers.
1715 * See Savannah bug #16378.
1717 return false;
1720 (void) pathname;
1722 if (state.have_stat)
1723 mode = stat_buf->st_mode;
1724 else
1725 mode = state.type;
1727 #ifndef S_IFMT
1728 /* POSIX system; check `mode' the slow way. */
1729 if ((S_ISBLK (mode) && type == S_IFBLK)
1730 || (S_ISCHR (mode) && type == S_IFCHR)
1731 || (S_ISDIR (mode) && type == S_IFDIR)
1732 || (S_ISREG (mode) && type == S_IFREG)
1733 #ifdef S_IFLNK
1734 || (S_ISLNK (mode) && type == S_IFLNK)
1735 #endif
1736 #ifdef S_IFIFO
1737 || (S_ISFIFO (mode) && type == S_IFIFO)
1738 #endif
1739 #ifdef S_IFSOCK
1740 || (S_ISSOCK (mode) && type == S_IFSOCK)
1741 #endif
1742 #ifdef S_IFDOOR
1743 || (S_ISDOOR (mode) && type == S_IFDOOR)
1744 #endif
1746 #else /* S_IFMT */
1747 /* Unix system; check `mode' the fast way. */
1748 if ((mode & S_IFMT) == type)
1749 #endif /* S_IFMT */
1750 return (true);
1751 else
1752 return (false);
1755 boolean
1756 pred_uid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1758 (void) pathname;
1759 switch (pred_ptr->args.numinfo.kind)
1761 case COMP_GT:
1762 if (stat_buf->st_uid > pred_ptr->args.numinfo.l_val)
1763 return (true);
1764 break;
1765 case COMP_LT:
1766 if (stat_buf->st_uid < pred_ptr->args.numinfo.l_val)
1767 return (true);
1768 break;
1769 case COMP_EQ:
1770 if (stat_buf->st_uid == pred_ptr->args.numinfo.l_val)
1771 return (true);
1772 break;
1774 return (false);
1777 boolean
1778 pred_used (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1780 struct timespec delta, at, ct;
1782 (void) pathname;
1784 /* TODO: this needs to be retested carefully (manually, if necessary) */
1785 at = get_stat_atime(stat_buf);
1786 ct = get_stat_ctime(stat_buf);
1787 delta.tv_sec = at.tv_sec - ct.tv_sec;
1788 delta.tv_nsec = at.tv_nsec - ct.tv_nsec;
1789 if (delta.tv_nsec < 0)
1791 delta.tv_nsec += 1000000000;
1792 delta.tv_sec -= 1;
1794 return pred_timewindow(delta, pred_ptr, DAYSECS);
1797 boolean
1798 pred_user (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1800 (void) pathname;
1801 if (pred_ptr->args.uid == stat_buf->st_uid)
1802 return (true);
1803 else
1804 return (false);
1807 boolean
1808 pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1810 struct stat sbuf; /* local copy, not stat_buf because we're using a different stat method */
1811 int (*ystat) (const char*, struct stat *p);
1813 /* If we would normally stat the link itself, stat the target instead.
1814 * If we would normally follow the link, stat the link itself instead.
1816 if (following_links())
1817 ystat = optionp_stat;
1818 else
1819 ystat = optionl_stat;
1821 set_stat_placeholders(&sbuf);
1822 if ((*ystat) (state.rel_pathname, &sbuf) != 0)
1824 if (following_links() && errno == ENOENT)
1826 /* If we failed to follow the symlink,
1827 * fall back on looking at the symlink itself.
1829 /* Mimic behavior of ls -lL. */
1830 return (pred_type (pathname, stat_buf, pred_ptr));
1832 else
1834 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
1835 state.exit_status = 1;
1837 return false;
1839 /* Now that we have our stat() information, query it in the same
1840 * way that -type does.
1842 return (pred_type (pathname, &sbuf, pred_ptr));
1845 /* 1) fork to get a child; parent remembers the child pid
1846 2) child execs the command requested
1847 3) parent waits for child; checks for proper pid of child
1849 Possible returns:
1851 ret errno status(h) status(l)
1853 pid x signal# 0177 stopped
1854 pid x exit arg 0 term by _exit
1855 pid x 0 signal # term by signal
1856 -1 EINTR parent got signal
1857 -1 other some other kind of error
1859 Return true only if the pid matches, status(l) is
1860 zero, and the exit arg (status high) is 0.
1861 Otherwise return false, possibly printing an error message. */
1864 static boolean
1865 prep_child_for_exec (boolean close_stdin, int dir_fd)
1867 boolean ok = true;
1868 if (close_stdin)
1870 const char inputfile[] = "/dev/null";
1872 if (close(0) < 0)
1874 error(0, errno, _("Cannot close standard input"));
1875 ok = false;
1877 else
1879 if (open(inputfile, O_RDONLY
1880 #if defined O_LARGEFILE
1881 |O_LARGEFILE
1882 #endif
1883 ) < 0)
1885 /* This is not entirely fatal, since
1886 * executing the child with a closed
1887 * stdin is almost as good as executing it
1888 * with its stdin attached to /dev/null.
1890 error (0, errno, "%s", safely_quote_err_filename(0, inputfile));
1891 /* do not set ok=false, it is OK to continue anyway. */
1896 /* Even if DebugSearch is set, don't announce our change of
1897 * directory, since we're not going to emit a subsequent
1898 * announcement of a call to stat() anyway, as we're about to exec
1899 * something.
1901 if (dir_fd != AT_FDCWD)
1903 assert (dir_fd >= 0);
1904 if (0 != fchdir(dir_fd))
1906 /* If we cannot execute our command in the correct directory,
1907 * we should not execute it at all.
1909 error(0, errno, _("Failed to change directory"));
1910 ok = false;
1913 return ok;
1919 launch (const struct buildcmd_control *ctl,
1920 struct buildcmd_state *buildstate)
1922 int wait_status;
1923 pid_t child_pid;
1924 static int first_time = 1;
1925 const struct exec_val *execp = buildstate->usercontext;
1927 if (!execp->use_current_dir)
1929 assert (starting_desc >= 0);
1930 assert (execp->dir_fd == starting_desc);
1934 /* Null terminate the arg list. */
1935 bc_push_arg (ctl, buildstate, (char *) NULL, 0, NULL, 0, false);
1937 /* Make sure output of command doesn't get mixed with find output. */
1938 fflush (stdout);
1939 fflush (stderr);
1941 /* Make sure to listen for the kids. */
1942 if (first_time)
1944 first_time = 0;
1945 signal (SIGCHLD, SIG_DFL);
1948 child_pid = fork ();
1949 if (child_pid == -1)
1950 error (1, errno, _("cannot fork"));
1951 if (child_pid == 0)
1953 /* We are the child. */
1954 assert (starting_desc >= 0);
1955 if (!prep_child_for_exec(execp->close_stdin, execp->dir_fd))
1957 _exit(1);
1960 execvp (buildstate->cmd_argv[0], buildstate->cmd_argv);
1961 error (0, errno, "%s",
1962 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1963 _exit (1);
1967 /* In parent; set up for next time. */
1968 bc_clear_args(ctl, buildstate);
1971 while (waitpid (child_pid, &wait_status, 0) == (pid_t) -1)
1973 if (errno != EINTR)
1975 error (0, errno, _("error waiting for %s"),
1976 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1977 state.exit_status = 1;
1978 return 0; /* FAIL */
1982 if (WIFSIGNALED (wait_status))
1984 error (0, 0, _("%s terminated by signal %d"),
1985 quotearg_n_style(0, options.err_quoting_style,
1986 buildstate->cmd_argv[0]),
1987 WTERMSIG (wait_status));
1989 if (execp->multiple)
1991 /* -exec \; just returns false if the invoked command fails.
1992 * -exec {} + returns true if the invoked command fails, but
1993 * sets the program exit status.
1995 state.exit_status = 1;
1998 return 1; /* OK */
2001 if (0 == WEXITSTATUS (wait_status))
2003 return 1; /* OK */
2005 else
2007 if (execp->multiple)
2009 /* -exec \; just returns false if the invoked command fails.
2010 * -exec {} + returns true if the invoked command fails, but
2011 * sets the program exit status.
2013 state.exit_status = 1;
2015 return 0; /* FAIL */
2021 /* Return a static string formatting the time WHEN according to the
2022 * strftime format character KIND.
2024 * This function contains a number of assertions. These look like
2025 * runtime checks of the results of computations, which would be a
2026 * problem since external events should not be tested for with
2027 * "assert" (instead you should use "if"). However, they are not
2028 * really runtime checks. The assertions actually exist to verify
2029 * that the various buffers are correctly sized.
2031 static char *
2032 format_date (struct timespec ts, int kind)
2034 /* In theory, we use an extra 10 characters for 9 digits of
2035 * nanoseconds and 1 for the decimal point. However, the real
2036 * world is more complex than that.
2038 * For example, some systems return junk in the tv_nsec part of
2039 * st_birthtime. An example of this is the NetBSD-4.0-RELENG kernel
2040 * (at Sat Mar 24 18:46:46 2007) running a NetBSD-3.1-RELEASE
2041 * runtime and examining files on an msdos filesytem. So for that
2042 * reason we set NS_BUF_LEN to 32, which is simply "long enough" as
2043 * opposed to "exactly the right size". Note that the behaviour of
2044 * NetBSD appears to be a result of the use of uninitialised data,
2045 * as it's not 100% reproducible (more like 25%).
2047 enum {
2048 NS_BUF_LEN = 32,
2049 DATE_LEN_PERCENT_APLUS=21 /* length of result of %A+ (it's longer than %c)*/
2051 static char buf[128u+10u + MAX(DATE_LEN_PERCENT_APLUS,
2052 MAX (LONGEST_HUMAN_READABLE + 2, NS_BUF_LEN+64+200))];
2053 char ns_buf[NS_BUF_LEN]; /* -.9999999990 (- sign can happen!)*/
2054 int charsprinted, need_ns_suffix;
2055 struct tm *tm;
2056 char fmt[6];
2058 /* human_readable() assumes we pass a buffer which is at least as
2059 * long as LONGEST_HUMAN_READABLE. We use an assertion here to
2060 * ensure that no nasty unsigned overflow happend in our calculation
2061 * of the size of buf. Do the assertion here rather than in the
2062 * code for %@ so that we find the problem quickly if it exists. If
2063 * you want to submit a patch to move this into the if statement, go
2064 * ahead, I'll apply it. But include performance timings
2065 * demonstrating that the performance difference is actually
2066 * measurable.
2068 verify (sizeof(buf) >= LONGEST_HUMAN_READABLE);
2070 charsprinted = 0;
2071 need_ns_suffix = 0;
2073 /* Format the main part of the time. */
2074 if (kind == '+')
2076 strcpy (fmt, "%F+%T");
2077 need_ns_suffix = 1;
2079 else
2081 fmt[0] = '%';
2082 fmt[1] = kind;
2083 fmt[2] = '\0';
2085 /* %a, %c, and %t are handled in ctime_format() */
2086 switch (kind)
2088 case 'S':
2089 case 'T':
2090 case 'X':
2091 case '@':
2092 need_ns_suffix = 1;
2093 break;
2094 default:
2095 need_ns_suffix = 0;
2096 break;
2100 if (need_ns_suffix)
2102 /* Format the nanoseconds part. Leave a trailing zero to
2103 * discourage people from writing scripts which extract the
2104 * fractional part of the timestamp by using column offsets.
2105 * The reason for discouraging this is that in the future, the
2106 * granularity may not be nanoseconds.
2108 ns_buf[0] = 0;
2109 charsprinted = snprintf(ns_buf, NS_BUF_LEN, ".%09ld0", (long int)ts.tv_nsec);
2110 assert (charsprinted < NS_BUF_LEN);
2113 if (kind != '@'
2114 && (tm = localtime (&ts.tv_sec))
2115 && strftime (buf, sizeof buf, fmt, tm))
2117 /* For %AS, %CS, %TS, add the fractional part of the seconds
2118 * information.
2120 if (need_ns_suffix)
2122 assert ((sizeof buf - strlen(buf)) > strlen(ns_buf));
2123 strcat(buf, ns_buf);
2125 return buf;
2127 else
2129 uintmax_t w = ts.tv_sec;
2130 size_t used, len, remaining;
2132 /* XXX: note that we are negating an unsigned type which is the
2133 * widest possible unsigned type.
2135 char *p = human_readable (ts.tv_sec < 0 ? -w : w, buf + 1,
2136 human_ceiling, 1, 1);
2137 assert (p > buf);
2138 assert (p < (buf + (sizeof buf)));
2139 if (ts.tv_sec < 0)
2140 *--p = '-'; /* XXX: Ugh, relying on internal details of human_readable(). */
2142 /* Add the nanoseconds part. Because we cannot enforce a
2143 * particlar implementation of human_readable, we cannot assume
2144 * any particular value for (p-buf). So we need to be careful
2145 * that there is enough space remaining in the buffer.
2147 if (need_ns_suffix)
2149 len = strlen(p);
2150 used = (p-buf) + len; /* Offset into buf of current end */
2151 assert (sizeof buf > used); /* Ensure we can perform subtraction safely. */
2152 remaining = sizeof buf - used - 1u; /* allow space for NUL */
2154 if (strlen(ns_buf) >= remaining)
2156 error(0, 0,
2157 "charsprinted=%ld but remaining=%lu: ns_buf=%s",
2158 (long)charsprinted, (unsigned long)remaining, ns_buf);
2160 assert (strlen(ns_buf) < remaining);
2161 strcat(p, ns_buf);
2163 return p;
2167 static const char *weekdays[] =
2169 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
2171 static char * months[] =
2173 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2174 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2178 static char *
2179 ctime_format (struct timespec ts)
2181 const struct tm * ptm;
2182 #define TIME_BUF_LEN 1024u
2183 static char resultbuf[TIME_BUF_LEN];
2184 int nout;
2186 ptm = localtime(&ts.tv_sec);
2187 if (ptm)
2189 assert (ptm->tm_wday >= 0);
2190 assert (ptm->tm_wday < 7);
2191 assert (ptm->tm_mon >= 0);
2192 assert (ptm->tm_mon < 12);
2193 assert (ptm->tm_hour >= 0);
2194 assert (ptm->tm_hour < 24);
2195 assert (ptm->tm_min < 60);
2196 assert (ptm->tm_sec <= 61); /* allows 2 leap seconds. */
2198 /* wkday mon mday hh:mm:ss.nnnnnnnnn yyyy */
2199 nout = snprintf(resultbuf, TIME_BUF_LEN,
2200 "%3s %3s %2d %02d:%02d:%02d.%010ld %04d",
2201 weekdays[ptm->tm_wday],
2202 months[ptm->tm_mon],
2203 ptm->tm_mday,
2204 ptm->tm_hour,
2205 ptm->tm_min,
2206 ptm->tm_sec,
2207 (long int)ts.tv_nsec,
2208 1900 + ptm->tm_year);
2210 assert (nout < TIME_BUF_LEN);
2211 return resultbuf;
2213 else
2215 /* The time cannot be represented as a struct tm.
2216 Output it as an integer. */
2217 return format_date (ts, '@');
2221 /* Copy STR into BUF and trim blanks from the end of BUF.
2222 Return BUF. */
2224 static char *
2225 blank_rtrim (str, buf)
2226 char *str;
2227 char *buf;
2229 int i;
2231 if (str == NULL)
2232 return (NULL);
2233 strcpy (buf, str);
2234 i = strlen (buf) - 1;
2235 while ((i >= 0) && ((buf[i] == ' ') || buf[i] == '\t'))
2236 i--;
2237 buf[++i] = '\0';
2238 return (buf);
2241 /* Print out the predicate list starting at NODE. */
2242 void
2243 print_list (FILE *fp, struct predicate *node)
2245 struct predicate *cur;
2246 char name[256];
2248 cur = node;
2249 while (cur != NULL)
2251 fprintf (fp, "[%s] ", blank_rtrim (cur->p_name, name));
2252 cur = cur->pred_next;
2254 fprintf (fp, "\n");
2257 /* Print out the predicate list starting at NODE. */
2258 static void
2259 print_parenthesised(FILE *fp, struct predicate *node)
2261 int parens = 0;
2263 if (node)
2265 if ((pred_is(node, pred_or) || pred_is(node, pred_and))
2266 && node->pred_left == NULL)
2268 /* We print "<nothing> or X" as just "X"
2269 * We print "<nothing> and X" as just "X"
2271 print_parenthesised(fp, node->pred_right);
2273 else
2275 if (node->pred_left || node->pred_right)
2276 parens = 1;
2278 if (parens)
2279 fprintf(fp, "%s", " ( ");
2280 print_optlist(fp, node);
2281 if (parens)
2282 fprintf(fp, "%s", " ) ");
2287 void
2288 print_optlist (FILE *fp, const struct predicate *p)
2290 if (p)
2292 print_parenthesised(fp, p->pred_left);
2293 fprintf (fp,
2294 "%s%s",
2295 p->need_stat ? "[call stat] " : "",
2296 p->need_type ? "[need type] " : "");
2297 print_predicate(fp, p);
2298 fprintf(fp, " [%g] ", p->est_success_rate);
2299 if (options.debug_options & DebugSuccessRates)
2301 fprintf(fp, "[%ld/%ld", p->perf.successes, p->perf.visits);
2302 if (p->perf.visits)
2304 double real_rate = (double)p->perf.successes / (double)p->perf.visits;
2305 fprintf(fp, "=%g] ", real_rate);
2307 else
2309 fprintf(fp, "=_] ");
2312 print_parenthesised(fp, p->pred_right);
2316 void show_success_rates(const struct predicate *p)
2318 if (options.debug_options & DebugSuccessRates)
2320 fprintf(stderr, "Predicate success rates after completion:\n");
2321 print_optlist(stderr, p);
2322 fprintf(stderr, "\n");
2329 #ifdef _NDEBUG
2330 /* If _NDEBUG is defined, the assertions will do nothing. Hence
2331 * there is no point in having a function body for pred_sanity_check()
2332 * if that preprocessor macro is defined.
2334 void
2335 pred_sanity_check(const struct predicate *predicates)
2337 /* Do nothing, since assert is a no-op with _NDEBUG set */
2338 return;
2340 #else
2341 void
2342 pred_sanity_check(const struct predicate *predicates)
2344 const struct predicate *p;
2346 for (p=predicates; p != NULL; p=p->pred_next)
2348 /* All predicates must do something. */
2349 assert (p->pred_func != NULL);
2351 /* All predicates must have a parser table entry. */
2352 assert (p->parser_entry != NULL);
2354 /* If the parser table tells us that just one predicate function is
2355 * possible, verify that that is still the one that is in effect.
2356 * If the parser has NULL for the predicate function, that means that
2357 * the parse_xxx function fills it in, so we can't check it.
2359 if (p->parser_entry->pred_func)
2361 assert (p->parser_entry->pred_func == p->pred_func);
2364 switch (p->parser_entry->type)
2366 /* Options all take effect during parsing, so there should
2367 * be no predicate entries corresponding to them. Hence we
2368 * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION
2369 * items.
2371 * This is a silly way of coding this test, but it prevents
2372 * a compiler warning (i.e. otherwise it would think that
2373 * there would be case statements missing).
2375 case ARG_OPTION:
2376 case ARG_POSITIONAL_OPTION:
2377 assert (p->parser_entry->type != ARG_OPTION);
2378 assert (p->parser_entry->type != ARG_POSITIONAL_OPTION);
2379 break;
2381 case ARG_ACTION:
2382 assert(p->side_effects); /* actions have side effects. */
2383 if (!pred_is(p, pred_prune) && !pred_is(p, pred_quit))
2385 /* actions other than -prune and -quit should
2386 * inhibit the default -print
2388 assert (p->no_default_print);
2390 break;
2392 /* We happen to know that the only user of ARG_SPECIAL_PARSE
2393 * is a test, so handle it like ARG_TEST.
2395 case ARG_SPECIAL_PARSE:
2396 case ARG_TEST:
2397 case ARG_PUNCTUATION:
2398 case ARG_NOOP:
2399 /* Punctuation and tests should have no side
2400 * effects and not inhibit default print.
2402 assert (!p->no_default_print);
2403 assert (!p->side_effects);
2404 break;
2408 #endif