cvsimport
[findutils.git] / find / pred.c
blob1c00093177465d0d67b197eae9596a5361a5bcdc
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 /* TRANSLATORS: the argument is either a
413 * file or a directory, but we do not know which.
414 * Mail bug-findutils@gnu.org if you cannot correctly
415 * translate the string without knowing.
416 */),
417 safely_quote_err_filename(0, pathname));
418 /* Previously I had believed that having the -delete action
419 * return false provided the user with control over whether an
420 * error message is issued. While this is true, the policy of
421 * not affecting the exit status is contrary to the POSIX
422 * requirement that diagnostic messages are accompanied by a
423 * nonzero exit status. While -delete is not a POSIX option and
424 * we can therefore opt not to follow POSIX in this case, that
425 * seems somewhat arbitrary and confusing. So, as of
426 * findutils-4.3.11, we also set the exit status in this case.
428 state.exit_status = 1;
429 return false;
431 else
433 /* nothing to do. */
434 return true;
438 boolean
439 pred_empty (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
441 (void) pathname;
442 (void) pred_ptr;
444 if (S_ISDIR (stat_buf->st_mode))
446 int fd;
447 DIR *d;
448 struct dirent *dp;
449 boolean empty = true;
451 errno = 0;
452 if ((fd = openat(state.cwd_dir_fd, state.rel_pathname, O_RDONLY
453 #if defined O_LARGEFILE
454 |O_LARGEFILE
455 #endif
456 )) < 0)
458 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
459 state.exit_status = 1;
460 return false;
462 d = fdopendir (fd);
463 if (d == NULL)
465 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
466 state.exit_status = 1;
467 return false;
469 for (dp = readdir (d); dp; dp = readdir (d))
471 if (dp->d_name[0] != '.'
472 || (dp->d_name[1] != '\0'
473 && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
475 empty = false;
476 break;
479 if (CLOSEDIR (d))
481 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
482 state.exit_status = 1;
483 return false;
485 return (empty);
487 else if (S_ISREG (stat_buf->st_mode))
488 return (stat_buf->st_size == 0);
489 else
490 return (false);
493 static boolean
494 new_impl_pred_exec (int dirfd, const char *pathname,
495 struct stat *stat_buf,
496 struct predicate *pred_ptr,
497 const char *prefix, size_t pfxlen)
499 struct exec_val *execp = &pred_ptr->args.exec_vec;
500 size_t len = strlen(pathname);
502 (void) stat_buf;
503 execp->dirfd = dirfd;
504 if (execp->multiple)
506 /* Push the argument onto the current list.
507 * The command may or may not be run at this point,
508 * depending on the command line length limits.
510 bc_push_arg(&execp->ctl,
511 &execp->state,
512 pathname, len+1,
513 prefix, pfxlen,
516 /* remember that there are pending execdirs. */
517 state.execdirs_outstanding = true;
519 /* POSIX: If the primary expression is punctuated by a plus
520 * sign, the primary shall always evaluate as true
522 return true;
524 else
526 int i;
528 for (i=0; i<execp->num_args; ++i)
530 bc_do_insert(&execp->ctl,
531 &execp->state,
532 execp->replace_vec[i],
533 strlen(execp->replace_vec[i]),
534 prefix, pfxlen,
535 pathname, len,
539 /* Actually invoke the command. */
540 return execp->ctl.exec_callback(&execp->ctl,
541 &execp->state);
546 boolean
547 pred_exec (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
549 return new_impl_pred_exec(get_start_dirfd(),
550 pathname, stat_buf, pred_ptr, NULL, 0);
553 boolean
554 pred_execdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
556 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
557 (void) &pathname;
558 return new_impl_pred_exec (get_current_dirfd(),
559 state.rel_pathname, stat_buf, pred_ptr,
560 prefix, (prefix ? 2 : 0));
563 boolean
564 pred_false (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
566 (void) &pathname;
567 (void) &stat_buf;
568 (void) &pred_ptr;
571 return (false);
574 boolean
575 pred_fls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
577 FILE * stream = pred_ptr->args.printf_vec.stream;
578 list_file (pathname, state.cwd_dir_fd, state.rel_pathname, stat_buf,
579 options.start_time.tv_sec,
580 options.output_block_size,
581 pred_ptr->literal_control_chars, stream);
582 return true;
585 boolean
586 pred_fprint (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
588 (void) &pathname;
589 (void) &stat_buf;
591 print_quoted(pred_ptr->args.printf_vec.stream,
592 pred_ptr->args.printf_vec.quote_opts,
593 pred_ptr->args.printf_vec.dest_is_tty,
594 "%s\n",
595 pathname);
596 return true;
599 boolean
600 pred_fprint0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
602 FILE * fp = pred_ptr->args.printf_vec.stream;
604 (void) &stat_buf;
606 fputs (pathname, fp);
607 putc (0, fp);
608 return true;
613 static char*
614 mode_to_filetype(mode_t m)
616 #define HANDLE_TYPE(t,letter) if (m==t) { return letter; }
617 #ifdef S_IFREG
618 HANDLE_TYPE(S_IFREG, "f"); /* regular file */
619 #endif
620 #ifdef S_IFDIR
621 HANDLE_TYPE(S_IFDIR, "d"); /* directory */
622 #endif
623 #ifdef S_IFLNK
624 HANDLE_TYPE(S_IFLNK, "l"); /* symbolic link */
625 #endif
626 #ifdef S_IFSOCK
627 HANDLE_TYPE(S_IFSOCK, "s"); /* Unix domain socket */
628 #endif
629 #ifdef S_IFBLK
630 HANDLE_TYPE(S_IFBLK, "b"); /* block device */
631 #endif
632 #ifdef S_IFCHR
633 HANDLE_TYPE(S_IFCHR, "c"); /* character device */
634 #endif
635 #ifdef S_IFIFO
636 HANDLE_TYPE(S_IFIFO, "p"); /* FIFO */
637 #endif
638 #ifdef S_IFDOOR
639 HANDLE_TYPE(S_IFDOOR, "D"); /* Door (e.g. on Solaris) */
640 #endif
641 return "U"; /* Unknown */
644 static double
645 file_sparseness(const struct stat *p)
647 #if defined HAVE_STRUCT_STAT_ST_BLOCKS
648 if (0 == p->st_size)
650 if (0 == p->st_blocks)
651 return 1.0;
652 else
653 return p->st_blocks < 0 ? -HUGE_VAL : HUGE_VAL;
655 else
657 double blklen = file_blocksize(p) * (double)p->st_blocks;
658 return blklen / p->st_size;
660 #else
661 return 1.0;
662 #endif
667 static void
668 checked_fprintf(struct format_val *dest, const char *fmt, ...)
670 int rv;
671 va_list ap;
673 va_start(ap, fmt);
674 rv = vfprintf(dest->stream, fmt, ap);
675 if (rv < 0)
676 nonfatal_file_error(dest->filename);
680 static void
681 checked_print_quoted (struct format_val *dest,
682 const char *format, const char *s)
684 int rv = print_quoted(dest->stream, dest->quote_opts, dest->dest_is_tty,
685 format, s);
686 if (rv < 0)
687 nonfatal_file_error(dest->filename);
691 static void
692 checked_fwrite(void *p, size_t siz, size_t nmemb, struct format_val *dest)
694 int items_written = fwrite(p, siz, nmemb, dest->stream);
695 if (items_written < nmemb)
696 nonfatal_file_error(dest->filename);
699 static void
700 checked_fflush(struct format_val *dest)
702 if (0 != fflush(dest->stream))
704 nonfatal_file_error(dest->filename);
708 static void
709 do_fprintf(struct format_val *dest,
710 struct segment *segment,
711 const char *pathname,
712 const struct stat *stat_buf)
714 char hbuf[LONGEST_HUMAN_READABLE + 1];
715 const char *cp;
717 switch (segment->segkind)
719 case KIND_PLAIN: /* Plain text string (no % conversion). */
720 /* trusted */
721 checked_fwrite(segment->text, 1, segment->text_len, dest);
722 break;
724 case KIND_STOP: /* Terminate argument and flush output. */
725 /* trusted */
726 checked_fwrite(segment->text, 1, segment->text_len, dest);
727 checked_fflush(dest);
728 break;
730 case KIND_FORMAT:
731 switch (segment->format_char[0])
733 case 'a': /* atime in `ctime' format. */
734 /* UNTRUSTED, probably unexploitable */
735 checked_fprintf (dest, segment->text, ctime_format (get_stat_atime(stat_buf)));
736 break;
737 case 'b': /* size in 512-byte blocks */
738 /* UNTRUSTED, probably unexploitable */
739 checked_fprintf (dest, segment->text,
740 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
741 hbuf, human_ceiling,
742 ST_NBLOCKSIZE, 512));
743 break;
744 case 'c': /* ctime in `ctime' format */
745 /* UNTRUSTED, probably unexploitable */
746 checked_fprintf (dest, segment->text, ctime_format (get_stat_ctime(stat_buf)));
747 break;
748 case 'd': /* depth in search tree */
749 /* UNTRUSTED, probably unexploitable */
750 checked_fprintf (dest, segment->text, state.curdepth);
751 break;
752 case 'D': /* Device on which file exists (stat.st_dev) */
753 /* trusted */
754 checked_fprintf (dest, segment->text,
755 human_readable ((uintmax_t) stat_buf->st_dev, hbuf,
756 human_ceiling, 1, 1));
757 break;
758 case 'f': /* base name of path */
759 /* sanitised */
761 char *base = base_name (pathname);
762 checked_print_quoted (dest, segment->text, base);
763 free (base);
765 break;
766 case 'F': /* file system type */
767 /* trusted */
768 checked_print_quoted (dest, segment->text, filesystem_type (stat_buf, pathname));
769 break;
770 case 'g': /* group name */
771 /* trusted */
772 /* (well, the actual group is selected by the user but
773 * its name was selected by the system administrator)
776 struct group *g;
778 g = getgrgid (stat_buf->st_gid);
779 if (g)
781 segment->text[segment->text_len] = 's';
782 checked_fprintf (dest, segment->text, g->gr_name);
783 break;
785 else
787 /* Do nothing. */
788 /*FALLTHROUGH*/
791 /*FALLTHROUGH*/ /*...sometimes, so 'G' case.*/
793 case 'G': /* GID number */
794 /* UNTRUSTED, probably unexploitable */
795 checked_fprintf (dest, segment->text,
796 human_readable ((uintmax_t) stat_buf->st_gid, hbuf,
797 human_ceiling, 1, 1));
798 break;
799 case 'h': /* leading directories part of path */
800 /* sanitised */
802 cp = strrchr (pathname, '/');
803 if (cp == NULL) /* No leading directories. */
805 /* If there is no slash in the pathname, we still
806 * print the string because it contains characters
807 * other than just '%s'. The %h expands to ".".
809 checked_print_quoted (dest, segment->text, ".");
811 else
813 char *s = strdup(pathname);
814 s[cp - pathname] = 0;
815 checked_print_quoted (dest, segment->text, s);
816 free(s);
819 break;
821 case 'H': /* ARGV element file was found under */
822 /* trusted */
824 char *s = xmalloc(state.starting_path_length+1);
825 memcpy(s, pathname, state.starting_path_length);
826 s[state.starting_path_length] = 0;
827 checked_fprintf (dest, segment->text, s);
828 free(s);
830 break;
832 case 'i': /* inode number */
833 /* UNTRUSTED, but not exploitable I think */
834 checked_fprintf (dest, segment->text,
835 human_readable ((uintmax_t) stat_buf->st_ino, hbuf,
836 human_ceiling,
837 1, 1));
838 break;
839 case 'k': /* size in 1K blocks */
840 /* UNTRUSTED, but not exploitable I think */
841 checked_fprintf (dest, segment->text,
842 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
843 hbuf, human_ceiling,
844 ST_NBLOCKSIZE, 1024));
845 break;
846 case 'l': /* object of symlink */
847 /* sanitised */
848 #ifdef S_ISLNK
850 char *linkname = 0;
852 if (S_ISLNK (stat_buf->st_mode))
854 linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
855 if (linkname == 0)
856 state.exit_status = 1;
858 if (linkname)
860 checked_print_quoted (dest, segment->text, linkname);
861 free (linkname);
863 else
865 /* We still need to honour the field width etc., so this is
866 * not a no-op.
868 checked_print_quoted (dest, segment->text, "");
871 #endif /* S_ISLNK */
872 break;
874 case 'M': /* mode as 10 chars (eg., "-rwxr-x--x" */
875 /* UNTRUSTED, probably unexploitable */
877 char modestring[16] ;
878 filemodestring (stat_buf, modestring);
879 modestring[10] = '\0';
880 checked_fprintf (dest, segment->text, modestring);
882 break;
884 case 'm': /* mode as octal number (perms only) */
885 /* UNTRUSTED, probably unexploitable */
887 /* Output the mode portably using the traditional numbers,
888 even if the host unwisely uses some other numbering
889 scheme. But help the compiler in the common case where
890 the host uses the traditional numbering scheme. */
891 mode_t m = stat_buf->st_mode;
892 boolean traditional_numbering_scheme =
893 (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000
894 && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100
895 && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010
896 && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001);
897 checked_fprintf (dest, segment->text,
898 (traditional_numbering_scheme
899 ? m & MODE_ALL
900 : ((m & S_ISUID ? 04000 : 0)
901 | (m & S_ISGID ? 02000 : 0)
902 | (m & S_ISVTX ? 01000 : 0)
903 | (m & S_IRUSR ? 00400 : 0)
904 | (m & S_IWUSR ? 00200 : 0)
905 | (m & S_IXUSR ? 00100 : 0)
906 | (m & S_IRGRP ? 00040 : 0)
907 | (m & S_IWGRP ? 00020 : 0)
908 | (m & S_IXGRP ? 00010 : 0)
909 | (m & S_IROTH ? 00004 : 0)
910 | (m & S_IWOTH ? 00002 : 0)
911 | (m & S_IXOTH ? 00001 : 0))));
913 break;
915 case 'n': /* number of links */
916 /* UNTRUSTED, probably unexploitable */
917 checked_fprintf (dest, segment->text,
918 human_readable ((uintmax_t) stat_buf->st_nlink,
919 hbuf,
920 human_ceiling,
921 1, 1));
922 break;
924 case 'p': /* pathname */
925 /* sanitised */
926 checked_print_quoted (dest, segment->text, pathname);
927 break;
929 case 'P': /* pathname with ARGV element stripped */
930 /* sanitised */
931 if (state.curdepth > 0)
933 cp = pathname + state.starting_path_length;
934 if (*cp == '/')
935 /* Move past the slash between the ARGV element
936 and the rest of the pathname. But if the ARGV element
937 ends in a slash, we didn't add another, so we've
938 already skipped past it. */
939 cp++;
941 else
943 cp = "";
945 checked_print_quoted (dest, segment->text, cp);
946 break;
948 case 's': /* size in bytes */
949 /* UNTRUSTED, probably unexploitable */
950 checked_fprintf (dest, segment->text,
951 human_readable ((uintmax_t) stat_buf->st_size,
952 hbuf, human_ceiling, 1, 1));
953 break;
955 case 'S': /* sparseness */
956 /* UNTRUSTED, probably unexploitable */
957 checked_fprintf (dest, segment->text, file_sparseness(stat_buf));;
958 break;
960 case 't': /* mtime in `ctime' format */
961 /* UNTRUSTED, probably unexploitable */
962 checked_fprintf (dest, segment->text,
963 ctime_format (get_stat_mtime(stat_buf)));
964 break;
966 case 'u': /* user name */
967 /* trusted */
968 /* (well, the actual user is selected by the user on systems
969 * where chown is not restricted, but the user name was
970 * selected by the system administrator)
973 struct passwd *p;
975 p = getpwuid (stat_buf->st_uid);
976 if (p)
978 segment->text[segment->text_len] = 's';
979 checked_fprintf (dest, segment->text, p->pw_name);
980 break;
982 /* else fallthru */
984 /* FALLTHROUGH*/ /* .. to case U */
986 case 'U': /* UID number */
987 /* UNTRUSTED, probably unexploitable */
988 checked_fprintf (dest, segment->text,
989 human_readable ((uintmax_t) stat_buf->st_uid, hbuf,
990 human_ceiling, 1, 1));
991 break;
993 /* %Y: type of file system entry like `ls -l`:
994 * (d,-,l,s,p,b,c,n) n=nonexistent(symlink)
996 case 'Y': /* in case of symlink */
997 /* trusted */
999 #ifdef S_ISLNK
1000 if (S_ISLNK (stat_buf->st_mode))
1002 struct stat sbuf;
1003 /* If we would normally follow links, do not do so.
1004 * If we would normally not follow links, do so.
1006 if ((following_links() ? lstat : stat)
1007 (state.rel_pathname, &sbuf) != 0)
1009 if ( errno == ENOENT )
1011 checked_fprintf (dest, segment->text, "N");
1012 break;
1014 else if ( errno == ELOOP )
1016 checked_fprintf (dest, segment->text, "L");
1017 break;
1019 else
1021 checked_fprintf (dest, segment->text, "?");
1022 error (0, errno, "%s",
1023 safely_quote_err_filename(0, pathname));
1024 /* exit_status = 1;
1025 return ; */
1026 break;
1029 checked_fprintf (dest, segment->text,
1030 mode_to_filetype(sbuf.st_mode & S_IFMT));
1032 #endif /* S_ISLNK */
1033 else
1035 checked_fprintf (dest, segment->text,
1036 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1039 break;
1041 case 'y':
1042 /* trusted */
1044 checked_fprintf (dest, segment->text,
1045 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1047 break;
1049 /* end of KIND_FORMAT case */
1050 break;
1054 boolean
1055 pred_fprintf (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1057 struct format_val *dest = &pred_ptr->args.printf_vec;
1058 struct segment *segment;
1060 for (segment = dest->segment; segment; segment = segment->next)
1062 if ( (KIND_FORMAT == segment->segkind) && segment->format_char[1]) /* Component of date. */
1064 struct timespec ts;
1065 int valid = 0;
1067 switch (segment->format_char[0])
1069 case 'A':
1070 ts = get_stat_atime(stat_buf);
1071 valid = 1;
1072 break;
1073 case 'B':
1074 ts = get_stat_birthtime(stat_buf);
1075 if ('@' == segment->format_char[1])
1076 valid = 1;
1077 else
1078 valid = (ts.tv_nsec >= 0);
1079 break;
1080 case 'C':
1081 ts = get_stat_ctime(stat_buf);
1082 valid = 1;
1083 break;
1084 case 'T':
1085 ts = get_stat_mtime(stat_buf);
1086 valid = 1;
1087 break;
1088 default:
1089 assert (0);
1090 abort ();
1092 /* We trust the output of format_date not to contain
1093 * nasty characters, though the value of the date
1094 * is itself untrusted data.
1096 if (valid)
1098 /* trusted */
1099 checked_fprintf (dest, segment->text,
1100 format_date (ts, segment->format_char[1]));
1102 else
1104 /* The specified timestamp is not available, output
1105 * nothing for the timestamp, but use the rest (so that
1106 * for example find foo -printf '[%Bs] %p\n' can print
1107 * "[] foo").
1109 /* trusted */
1110 checked_fprintf (dest, segment->text, "");
1113 else
1115 /* Print a segment which is not a date. */
1116 do_fprintf(dest, segment, pathname, stat_buf);
1119 return true;
1122 boolean
1123 pred_fstype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1125 (void) pathname;
1127 if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0)
1128 return true;
1129 else
1130 return false;
1133 boolean
1134 pred_gid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1136 (void) pathname;
1138 switch (pred_ptr->args.numinfo.kind)
1140 case COMP_GT:
1141 if (stat_buf->st_gid > pred_ptr->args.numinfo.l_val)
1142 return (true);
1143 break;
1144 case COMP_LT:
1145 if (stat_buf->st_gid < pred_ptr->args.numinfo.l_val)
1146 return (true);
1147 break;
1148 case COMP_EQ:
1149 if (stat_buf->st_gid == pred_ptr->args.numinfo.l_val)
1150 return (true);
1151 break;
1153 return (false);
1156 boolean
1157 pred_group (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1159 (void) pathname;
1161 if (pred_ptr->args.gid == stat_buf->st_gid)
1162 return (true);
1163 else
1164 return (false);
1167 boolean
1168 pred_ilname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1170 return match_lname (pathname, stat_buf, pred_ptr, true);
1173 /* Common code between -name, -iname. PATHNAME is being visited, STR
1174 is name to compare basename against, and FLAGS are passed to
1175 fnmatch. Recall that 'find / -name /' is one of the few times where a '/'
1176 in the -name must actually find something. */
1177 static boolean
1178 pred_name_common (const char *pathname, const char *str, int flags)
1180 char *p;
1181 boolean b;
1182 /* We used to use last_component() here, but that would not allow us to modify the
1183 * input string, which is const. We could optimise by duplicating the string only
1184 * if we need to modify it, and I'll do that if there is a measurable
1185 * performance difference on a machine built after 1990...
1187 char *base = base_name (pathname);
1188 /* remove trailing slashes, but leave "/" or "//foo" unchanged. */
1189 strip_trailing_slashes(base);
1191 /* FNM_PERIOD is not used here because POSIX requires that it not be.
1192 * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1194 b = fnmatch (str, base, flags) == 0;
1195 free (base);
1196 return b;
1199 boolean
1200 pred_iname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1202 (void) stat_buf;
1203 return pred_name_common (pathname, pred_ptr->args.str, FNM_CASEFOLD);
1206 boolean
1207 pred_inum (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1209 (void) pathname;
1211 switch (pred_ptr->args.numinfo.kind)
1213 case COMP_GT:
1214 if (stat_buf->st_ino > pred_ptr->args.numinfo.l_val)
1215 return (true);
1216 break;
1217 case COMP_LT:
1218 if (stat_buf->st_ino < pred_ptr->args.numinfo.l_val)
1219 return (true);
1220 break;
1221 case COMP_EQ:
1222 if (stat_buf->st_ino == pred_ptr->args.numinfo.l_val)
1223 return (true);
1224 break;
1226 return (false);
1229 boolean
1230 pred_ipath (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1232 (void) stat_buf;
1234 if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0)
1235 return (true);
1236 return (false);
1239 boolean
1240 pred_links (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1242 (void) pathname;
1244 switch (pred_ptr->args.numinfo.kind)
1246 case COMP_GT:
1247 if (stat_buf->st_nlink > pred_ptr->args.numinfo.l_val)
1248 return (true);
1249 break;
1250 case COMP_LT:
1251 if (stat_buf->st_nlink < pred_ptr->args.numinfo.l_val)
1252 return (true);
1253 break;
1254 case COMP_EQ:
1255 if (stat_buf->st_nlink == pred_ptr->args.numinfo.l_val)
1256 return (true);
1257 break;
1259 return (false);
1262 boolean
1263 pred_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1265 return match_lname (pathname, stat_buf, pred_ptr, false);
1268 static boolean
1269 match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case)
1271 boolean ret = false;
1272 #ifdef S_ISLNK
1273 if (S_ISLNK (stat_buf->st_mode))
1275 char *linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
1276 if (linkname)
1278 if (fnmatch (pred_ptr->args.str, linkname,
1279 ignore_case ? FNM_CASEFOLD : 0) == 0)
1280 ret = true;
1281 free (linkname);
1284 #endif /* S_ISLNK */
1285 return ret;
1288 boolean
1289 pred_ls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1291 return pred_fls(pathname, stat_buf, pred_ptr);
1294 boolean
1295 pred_mmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1297 (void) &pathname;
1298 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, 60);
1301 boolean
1302 pred_mtime (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, DAYSECS);
1308 boolean
1309 pred_name (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1311 (void) stat_buf;
1312 return pred_name_common (pathname, pred_ptr->args.str, 0);
1315 boolean
1316 pred_negate (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1318 return !apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1321 boolean
1322 pred_newer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1324 (void) pathname;
1326 assert (COMP_GT == pred_ptr->args.reftime.kind);
1327 return compare_ts(get_stat_mtime(stat_buf), pred_ptr->args.reftime.ts) > 0;
1330 boolean
1331 pred_newerXY (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1333 struct timespec ts;
1334 boolean collected = false;
1336 assert (COMP_GT == pred_ptr->args.reftime.kind);
1338 switch (pred_ptr->args.reftime.xval)
1340 case XVAL_TIME:
1341 assert (pred_ptr->args.reftime.xval != XVAL_TIME);
1342 return false;
1344 case XVAL_ATIME:
1345 ts = get_stat_atime(stat_buf);
1346 collected = true;
1347 break;
1349 case XVAL_BIRTHTIME:
1350 ts = get_stat_birthtime(stat_buf);
1351 collected = true;
1352 if (ts.tv_nsec < 0);
1354 /* XXX: Cannot determine birth time. Warn once. */
1355 error(0, 0, _("Warning: cannot determine birth time of file %s"),
1356 safely_quote_err_filename(0, pathname));
1357 return false;
1359 break;
1361 case XVAL_CTIME:
1362 ts = get_stat_ctime(stat_buf);
1363 collected = true;
1364 break;
1366 case XVAL_MTIME:
1367 ts = get_stat_mtime(stat_buf);
1368 collected = true;
1369 break;
1372 assert (collected);
1373 return compare_ts(ts, pred_ptr->args.reftime.ts) > 0;
1376 boolean
1377 pred_nogroup (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1379 (void) pathname;
1380 (void) pred_ptr;
1382 #ifdef CACHE_IDS
1383 extern char *gid_unused;
1385 return gid_unused[(unsigned) stat_buf->st_gid];
1386 #else
1387 return getgrgid (stat_buf->st_gid) == NULL;
1388 #endif
1391 boolean
1392 pred_nouser (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1394 #ifdef CACHE_IDS
1395 extern char *uid_unused;
1396 #endif
1398 (void) pathname;
1399 (void) pred_ptr;
1401 #ifdef CACHE_IDS
1402 return uid_unused[(unsigned) stat_buf->st_uid];
1403 #else
1404 return getpwuid (stat_buf->st_uid) == NULL;
1405 #endif
1409 static boolean
1410 is_ok(const char *program, const char *arg)
1412 fflush (stdout);
1413 /* The draft open standard requires that, in the POSIX locale,
1414 the last non-blank character of this prompt be '?'.
1415 The exact format is not specified.
1416 This standard does not have requirements for locales other than POSIX
1418 /* XXX: printing UNTRUSTED data here. */
1419 fprintf (stderr, _("< %s ... %s > ? "
1420 /* TRANSLATORS: we would like, if possible, the final non-blank
1421 * character of this string to be '?', but it is not
1422 * wholly essential. */
1423 ), program, arg);
1424 fflush (stderr);
1425 return yesno();
1428 boolean
1429 pred_ok (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1431 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1432 return new_impl_pred_exec (get_start_dirfd(),
1433 pathname, stat_buf, pred_ptr, NULL, 0);
1434 else
1435 return false;
1438 boolean
1439 pred_okdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1441 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
1442 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1443 return new_impl_pred_exec (get_current_dirfd(),
1444 state.rel_pathname, stat_buf, pred_ptr,
1445 prefix, (prefix ? 2 : 0));
1446 else
1447 return false;
1450 boolean
1451 pred_openparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1453 (void) pathname;
1454 (void) stat_buf;
1455 (void) pred_ptr;
1456 return true;
1459 boolean
1460 pred_or (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1462 if (pred_ptr->pred_left == NULL
1463 || !apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
1465 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1467 else
1468 return true;
1471 boolean
1472 pred_path (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1474 (void) stat_buf;
1475 if (fnmatch (pred_ptr->args.str, pathname, 0) == 0)
1476 return (true);
1477 return (false);
1480 boolean
1481 pred_perm (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1483 mode_t mode = stat_buf->st_mode;
1484 mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0];
1485 (void) pathname;
1486 switch (pred_ptr->args.perm.kind)
1488 case PERM_AT_LEAST:
1489 return (mode & perm_val) == perm_val;
1490 break;
1492 case PERM_ANY:
1493 /* True if any of the bits set in the mask are also set in the file's mode.
1496 * Otherwise, if onum is prefixed by a hyphen, the primary shall
1497 * evaluate as true if at least all of the bits specified in
1498 * onum that are also set in the octal mask 07777 are set.
1500 * Eric Blake's interpretation is that the mode argument is zero,
1503 if (0 == perm_val)
1504 return true; /* Savannah bug 14748; we used to return false */
1505 else
1506 return (mode & perm_val) != 0;
1507 break;
1509 case PERM_EXACT:
1510 return (mode & MODE_ALL) == perm_val;
1511 break;
1513 default:
1514 abort ();
1515 break;
1520 struct access_check_args
1522 const char *filename;
1523 int access_type;
1524 int cb_errno;
1528 static int
1529 access_callback(void *context)
1531 int rv;
1532 struct access_check_args *args = context;
1533 if ((rv = access(args->filename, args->access_type)) < 0)
1534 args->cb_errno = errno;
1535 return rv;
1538 static int
1539 can_access(int access_type)
1541 struct access_check_args args;
1542 args.filename = state.rel_pathname;
1543 args.access_type = access_type;
1544 args.cb_errno = 0;
1545 return 0 == run_in_dir(state.cwd_dir_fd, access_callback, &args);
1549 boolean
1550 pred_executable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1552 (void) pathname;
1553 (void) stat_buf;
1554 (void) pred_ptr;
1556 return can_access(X_OK);
1559 boolean
1560 pred_readable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1562 (void) pathname;
1563 (void) stat_buf;
1564 (void) pred_ptr;
1566 return can_access(R_OK);
1569 boolean
1570 pred_writable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1572 (void) pathname;
1573 (void) stat_buf;
1574 (void) pred_ptr;
1576 return can_access(W_OK);
1579 boolean
1580 pred_print (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1582 (void) stat_buf;
1583 (void) pred_ptr;
1585 print_quoted(pred_ptr->args.printf_vec.stream,
1586 pred_ptr->args.printf_vec.quote_opts,
1587 pred_ptr->args.printf_vec.dest_is_tty,
1588 "%s\n", pathname);
1589 return true;
1592 boolean
1593 pred_print0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1595 return pred_fprint0(pathname, stat_buf, pred_ptr);
1598 boolean
1599 pred_prune (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1601 (void) pathname;
1602 (void) pred_ptr;
1604 if (options.do_dir_first == true && /* no effect with -depth */
1605 stat_buf != NULL &&
1606 S_ISDIR(stat_buf->st_mode))
1607 state.stop_at_current_level = true;
1609 /* findutils used to return options.do_dir_first here, so that -prune
1610 * returns true only if -depth is not in effect. But POSIX requires
1611 * that -prune always evaluate as true.
1613 return true;
1616 boolean
1617 pred_quit (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1619 (void) pathname;
1620 (void) stat_buf;
1621 (void) pred_ptr;
1623 /* Run any cleanups. This includes executing any command lines
1624 * we have partly built but not executed.
1626 cleanup();
1628 /* Since -exec and friends don't leave child processes running in the
1629 * background, there is no need to wait for them here.
1631 exit(state.exit_status); /* 0 for success, etc. */
1634 boolean
1635 pred_regex (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1637 int len = strlen (pathname);
1638 (void) stat_buf;
1639 if (re_match (pred_ptr->args.regex, pathname, len, 0,
1640 (struct re_registers *) NULL) == len)
1641 return (true);
1642 return (false);
1645 boolean
1646 pred_size (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1648 uintmax_t f_val;
1650 (void) pathname;
1651 f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize)
1652 + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0));
1653 switch (pred_ptr->args.size.kind)
1655 case COMP_GT:
1656 if (f_val > pred_ptr->args.size.size)
1657 return (true);
1658 break;
1659 case COMP_LT:
1660 if (f_val < pred_ptr->args.size.size)
1661 return (true);
1662 break;
1663 case COMP_EQ:
1664 if (f_val == pred_ptr->args.size.size)
1665 return (true);
1666 break;
1668 return (false);
1671 boolean
1672 pred_samefile (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1674 /* Potential optimisation: because of the loop protection, we always
1675 * know the device of the current directory, hence the device number
1676 * of the file we're currently considering. If -L is not in effect,
1677 * and the device number of the file we're looking for is not the
1678 * same as the device number of the current directory, this
1679 * predicate cannot return true. Hence there would be no need to
1680 * stat the file we're looking at.
1682 (void) pathname;
1684 /* We will often still have an fd open on the file under consideration,
1685 * but that's just to ensure inode number stability by maintaining
1686 * a reference to it; we don't need the file for anything else.
1688 return stat_buf->st_ino == pred_ptr->args.samefileid.ino
1689 && stat_buf->st_dev == pred_ptr->args.samefileid.dev;
1692 boolean
1693 pred_true (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1695 (void) pathname;
1696 (void) stat_buf;
1697 (void) pred_ptr;
1698 return true;
1701 boolean
1702 pred_type (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1704 mode_t mode;
1705 mode_t type = pred_ptr->args.type;
1707 assert (state.have_type);
1709 if (0 == state.type)
1711 /* This can sometimes happen with broken NFS servers.
1712 * See Savannah bug #16378.
1714 return false;
1717 (void) pathname;
1719 if (state.have_stat)
1720 mode = stat_buf->st_mode;
1721 else
1722 mode = state.type;
1724 #ifndef S_IFMT
1725 /* POSIX system; check `mode' the slow way. */
1726 if ((S_ISBLK (mode) && type == S_IFBLK)
1727 || (S_ISCHR (mode) && type == S_IFCHR)
1728 || (S_ISDIR (mode) && type == S_IFDIR)
1729 || (S_ISREG (mode) && type == S_IFREG)
1730 #ifdef S_IFLNK
1731 || (S_ISLNK (mode) && type == S_IFLNK)
1732 #endif
1733 #ifdef S_IFIFO
1734 || (S_ISFIFO (mode) && type == S_IFIFO)
1735 #endif
1736 #ifdef S_IFSOCK
1737 || (S_ISSOCK (mode) && type == S_IFSOCK)
1738 #endif
1739 #ifdef S_IFDOOR
1740 || (S_ISDOOR (mode) && type == S_IFDOOR)
1741 #endif
1743 #else /* S_IFMT */
1744 /* Unix system; check `mode' the fast way. */
1745 if ((mode & S_IFMT) == type)
1746 #endif /* S_IFMT */
1747 return (true);
1748 else
1749 return (false);
1752 boolean
1753 pred_uid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1755 (void) pathname;
1756 switch (pred_ptr->args.numinfo.kind)
1758 case COMP_GT:
1759 if (stat_buf->st_uid > pred_ptr->args.numinfo.l_val)
1760 return (true);
1761 break;
1762 case COMP_LT:
1763 if (stat_buf->st_uid < pred_ptr->args.numinfo.l_val)
1764 return (true);
1765 break;
1766 case COMP_EQ:
1767 if (stat_buf->st_uid == pred_ptr->args.numinfo.l_val)
1768 return (true);
1769 break;
1771 return (false);
1774 boolean
1775 pred_used (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1777 struct timespec delta, at, ct;
1779 (void) pathname;
1781 /* TODO: this needs to be retested carefully (manually, if necessary) */
1782 at = get_stat_atime(stat_buf);
1783 ct = get_stat_ctime(stat_buf);
1784 delta.tv_sec = at.tv_sec - ct.tv_sec;
1785 delta.tv_nsec = at.tv_nsec - ct.tv_nsec;
1786 if (delta.tv_nsec < 0)
1788 delta.tv_nsec += 1000000000;
1789 delta.tv_sec -= 1;
1791 return pred_timewindow(delta, pred_ptr, DAYSECS);
1794 boolean
1795 pred_user (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1797 (void) pathname;
1798 if (pred_ptr->args.uid == stat_buf->st_uid)
1799 return (true);
1800 else
1801 return (false);
1804 boolean
1805 pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1807 struct stat sbuf; /* local copy, not stat_buf because we're using a different stat method */
1808 int (*ystat) (const char*, struct stat *p);
1810 /* If we would normally stat the link itself, stat the target instead.
1811 * If we would normally follow the link, stat the link itself instead.
1813 if (following_links())
1814 ystat = optionp_stat;
1815 else
1816 ystat = optionl_stat;
1818 set_stat_placeholders(&sbuf);
1819 if ((*ystat) (state.rel_pathname, &sbuf) != 0)
1821 if (following_links() && errno == ENOENT)
1823 /* If we failed to follow the symlink,
1824 * fall back on looking at the symlink itself.
1826 /* Mimic behavior of ls -lL. */
1827 return (pred_type (pathname, stat_buf, pred_ptr));
1829 else
1831 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
1832 state.exit_status = 1;
1834 return false;
1836 /* Now that we have our stat() information, query it in the same
1837 * way that -type does.
1839 return (pred_type (pathname, &sbuf, pred_ptr));
1842 /* 1) fork to get a child; parent remembers the child pid
1843 2) child execs the command requested
1844 3) parent waits for child; checks for proper pid of child
1846 Possible returns:
1848 ret errno status(h) status(l)
1850 pid x signal# 0177 stopped
1851 pid x exit arg 0 term by _exit
1852 pid x 0 signal # term by signal
1853 -1 EINTR parent got signal
1854 -1 other some other kind of error
1856 Return true only if the pid matches, status(l) is
1857 zero, and the exit arg (status high) is 0.
1858 Otherwise return false, possibly printing an error message. */
1861 static boolean
1862 prep_child_for_exec (boolean close_stdin, int dirfd)
1864 boolean ok = true;
1865 if (close_stdin)
1867 const char inputfile[] = "/dev/null";
1869 if (close(0) < 0)
1871 error(0, errno, _("Cannot close standard input"));
1872 ok = false;
1874 else
1876 if (open(inputfile, O_RDONLY
1877 #if defined O_LARGEFILE
1878 |O_LARGEFILE
1879 #endif
1880 ) < 0)
1882 /* This is not entirely fatal, since
1883 * executing the child with a closed
1884 * stdin is almost as good as executing it
1885 * with its stdin attached to /dev/null.
1887 error (0, errno, "%s", safely_quote_err_filename(0, inputfile));
1888 /* do not set ok=false, it is OK to continue anyway. */
1893 /* Even if DebugSearch is set, don't announce our change of
1894 * directory, since we're not going to emit a subsequent
1895 * announcement of a call to stat() anyway, as we're about to exec
1896 * something.
1898 if (dirfd != AT_FDCWD)
1900 assert (dirfd >= 0);
1901 if (0 != fchdir(dirfd))
1903 /* If we cannot execute our command in the correct directory,
1904 * we should not execute it at all.
1906 error(0, errno, _("Failed to change directory"));
1907 ok = false;
1910 return ok;
1916 launch (const struct buildcmd_control *ctl,
1917 struct buildcmd_state *buildstate)
1919 int wait_status;
1920 pid_t child_pid;
1921 static int first_time = 1;
1922 const struct exec_val *execp = buildstate->usercontext;
1924 if (!execp->use_current_dir)
1926 assert (starting_desc >= 0);
1927 assert (execp->dirfd == starting_desc);
1931 /* Null terminate the arg list. */
1932 bc_push_arg (ctl, buildstate, (char *) NULL, 0, NULL, 0, false);
1934 /* Make sure output of command doesn't get mixed with find output. */
1935 fflush (stdout);
1936 fflush (stderr);
1938 /* Make sure to listen for the kids. */
1939 if (first_time)
1941 first_time = 0;
1942 signal (SIGCHLD, SIG_DFL);
1945 child_pid = fork ();
1946 if (child_pid == -1)
1947 error (1, errno, _("cannot fork"));
1948 if (child_pid == 0)
1950 /* We are the child. */
1951 assert (starting_desc >= 0);
1952 if (!prep_child_for_exec(execp->close_stdin, execp->dirfd))
1954 _exit(1);
1957 execvp (buildstate->cmd_argv[0], buildstate->cmd_argv);
1958 error (0, errno, "%s",
1959 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1960 _exit (1);
1964 /* In parent; set up for next time. */
1965 bc_clear_args(ctl, buildstate);
1968 while (waitpid (child_pid, &wait_status, 0) == (pid_t) -1)
1970 if (errno != EINTR)
1972 error (0, errno, _("error waiting for %s"),
1973 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1974 state.exit_status = 1;
1975 return 0; /* FAIL */
1979 if (WIFSIGNALED (wait_status))
1981 error (0, 0, _("%1$s terminated by signal %2$d"),
1982 quotearg_n_style(0, options.err_quoting_style,
1983 buildstate->cmd_argv[0]),
1984 WTERMSIG (wait_status));
1986 if (execp->multiple)
1988 /* -exec \; just returns false if the invoked command fails.
1989 * -exec {} + returns true if the invoked command fails, but
1990 * sets the program exit status.
1992 state.exit_status = 1;
1995 return 1; /* OK */
1998 if (0 == WEXITSTATUS (wait_status))
2000 return 1; /* OK */
2002 else
2004 if (execp->multiple)
2006 /* -exec \; just returns false if the invoked command fails.
2007 * -exec {} + returns true if the invoked command fails, but
2008 * sets the program exit status.
2010 state.exit_status = 1;
2012 return 0; /* FAIL */
2018 /* Return a static string formatting the time WHEN according to the
2019 * strftime format character KIND.
2021 * This function contains a number of assertions. These look like
2022 * runtime checks of the results of computations, which would be a
2023 * problem since external events should not be tested for with
2024 * "assert" (instead you should use "if"). However, they are not
2025 * really runtime checks. The assertions actually exist to verify
2026 * that the various buffers are correctly sized.
2028 static char *
2029 format_date (struct timespec ts, int kind)
2031 /* In theory, we use an extra 10 characters for 9 digits of
2032 * nanoseconds and 1 for the decimal point. However, the real
2033 * world is more complex than that.
2035 * For example, some systems return junk in the tv_nsec part of
2036 * st_birthtime. An example of this is the NetBSD-4.0-RELENG kernel
2037 * (at Sat Mar 24 18:46:46 2007) running a NetBSD-3.1-RELEASE
2038 * runtime and examining files on an msdos filesytem. So for that
2039 * reason we set NS_BUF_LEN to 32, which is simply "long enough" as
2040 * opposed to "exactly the right size". Note that the behaviour of
2041 * NetBSD appears to be a result of the use of uninitialised data,
2042 * as it's not 100% reproducible (more like 25%).
2044 enum {
2045 NS_BUF_LEN = 32,
2046 DATE_LEN_PERCENT_APLUS=21 /* length of result of %A+ (it's longer than %c)*/
2048 static char buf[128u+10u + MAX(DATE_LEN_PERCENT_APLUS,
2049 MAX (LONGEST_HUMAN_READABLE + 2, NS_BUF_LEN+64+200))];
2050 char ns_buf[NS_BUF_LEN]; /* -.9999999990 (- sign can happen!)*/
2051 int charsprinted, need_ns_suffix;
2052 struct tm *tm;
2053 char fmt[6];
2055 /* human_readable() assumes we pass a buffer which is at least as
2056 * long as LONGEST_HUMAN_READABLE. We use an assertion here to
2057 * ensure that no nasty unsigned overflow happend in our calculation
2058 * of the size of buf. Do the assertion here rather than in the
2059 * code for %@ so that we find the problem quickly if it exists. If
2060 * you want to submit a patch to move this into the if statement, go
2061 * ahead, I'll apply it. But include performance timings
2062 * demonstrating that the performance difference is actually
2063 * measurable.
2065 verify (sizeof(buf) >= LONGEST_HUMAN_READABLE);
2067 charsprinted = 0;
2068 need_ns_suffix = 0;
2070 /* Format the main part of the time. */
2071 if (kind == '+')
2073 strcpy (fmt, "%F+%T");
2074 need_ns_suffix = 1;
2076 else
2078 fmt[0] = '%';
2079 fmt[1] = kind;
2080 fmt[2] = '\0';
2082 /* %a, %c, and %t are handled in ctime_format() */
2083 switch (kind)
2085 case 'S':
2086 case 'T':
2087 case 'X':
2088 case '@':
2089 need_ns_suffix = 1;
2090 break;
2091 default:
2092 need_ns_suffix = 0;
2093 break;
2097 if (need_ns_suffix)
2099 /* Format the nanoseconds part. Leave a trailing zero to
2100 * discourage people from writing scripts which extract the
2101 * fractional part of the timestamp by using column offsets.
2102 * The reason for discouraging this is that in the future, the
2103 * granularity may not be nanoseconds.
2105 ns_buf[0] = 0;
2106 charsprinted = snprintf(ns_buf, NS_BUF_LEN, ".%09ld0", (long int)ts.tv_nsec);
2107 assert (charsprinted < NS_BUF_LEN);
2110 if (kind != '@'
2111 && (tm = localtime (&ts.tv_sec))
2112 && strftime (buf, sizeof buf, fmt, tm))
2114 /* For %AS, %CS, %TS, add the fractional part of the seconds
2115 * information.
2117 if (need_ns_suffix)
2119 assert ((sizeof buf - strlen(buf)) > strlen(ns_buf));
2120 strcat(buf, ns_buf);
2122 return buf;
2124 else
2126 uintmax_t w = ts.tv_sec;
2127 size_t used, len, remaining;
2129 /* XXX: note that we are negating an unsigned type which is the
2130 * widest possible unsigned type.
2132 char *p = human_readable (ts.tv_sec < 0 ? -w : w, buf + 1,
2133 human_ceiling, 1, 1);
2134 assert (p > buf);
2135 assert (p < (buf + (sizeof buf)));
2136 if (ts.tv_sec < 0)
2137 *--p = '-'; /* XXX: Ugh, relying on internal details of human_readable(). */
2139 /* Add the nanoseconds part. Because we cannot enforce a
2140 * particlar implementation of human_readable, we cannot assume
2141 * any particular value for (p-buf). So we need to be careful
2142 * that there is enough space remaining in the buffer.
2144 if (need_ns_suffix)
2146 len = strlen(p);
2147 used = (p-buf) + len; /* Offset into buf of current end */
2148 assert (sizeof buf > used); /* Ensure we can perform subtraction safely. */
2149 remaining = sizeof buf - used - 1u; /* allow space for NUL */
2151 if (strlen(ns_buf) >= remaining)
2153 error(0, 0,
2154 "charsprinted=%ld but remaining=%lu: ns_buf=%s",
2155 (long)charsprinted, (unsigned long)remaining, ns_buf);
2157 assert (strlen(ns_buf) < remaining);
2158 strcat(p, ns_buf);
2160 return p;
2164 static const char *weekdays[] =
2166 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
2168 static char * months[] =
2170 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2171 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2175 static char *
2176 ctime_format (struct timespec ts)
2178 const struct tm * ptm;
2179 #define TIME_BUF_LEN 1024u
2180 static char resultbuf[TIME_BUF_LEN];
2181 int nout;
2183 ptm = localtime(&ts.tv_sec);
2184 if (ptm)
2186 assert (ptm->tm_wday >= 0);
2187 assert (ptm->tm_wday < 7);
2188 assert (ptm->tm_mon >= 0);
2189 assert (ptm->tm_mon < 12);
2190 assert (ptm->tm_hour >= 0);
2191 assert (ptm->tm_hour < 24);
2192 assert (ptm->tm_min < 60);
2193 assert (ptm->tm_sec <= 61); /* allows 2 leap seconds. */
2195 /* wkday mon mday hh:mm:ss.nnnnnnnnn yyyy */
2196 nout = snprintf(resultbuf, TIME_BUF_LEN,
2197 "%3s %3s %2d %02d:%02d:%02d.%010ld %04d",
2198 weekdays[ptm->tm_wday],
2199 months[ptm->tm_mon],
2200 ptm->tm_mday,
2201 ptm->tm_hour,
2202 ptm->tm_min,
2203 ptm->tm_sec,
2204 (long int)ts.tv_nsec,
2205 1900 + ptm->tm_year);
2207 assert (nout < TIME_BUF_LEN);
2208 return resultbuf;
2210 else
2212 /* The time cannot be represented as a struct tm.
2213 Output it as an integer. */
2214 return format_date (ts, '@');
2218 /* Copy STR into BUF and trim blanks from the end of BUF.
2219 Return BUF. */
2221 static char *
2222 blank_rtrim (str, buf)
2223 char *str;
2224 char *buf;
2226 int i;
2228 if (str == NULL)
2229 return (NULL);
2230 strcpy (buf, str);
2231 i = strlen (buf) - 1;
2232 while ((i >= 0) && ((buf[i] == ' ') || buf[i] == '\t'))
2233 i--;
2234 buf[++i] = '\0';
2235 return (buf);
2238 /* Print out the predicate list starting at NODE. */
2239 void
2240 print_list (FILE *fp, struct predicate *node)
2242 struct predicate *cur;
2243 char name[256];
2245 cur = node;
2246 while (cur != NULL)
2248 fprintf (fp, "[%s] ", blank_rtrim (cur->p_name, name));
2249 cur = cur->pred_next;
2251 fprintf (fp, "\n");
2254 /* Print out the predicate list starting at NODE. */
2255 static void
2256 print_parenthesised(FILE *fp, struct predicate *node)
2258 int parens = 0;
2260 if (node)
2262 if ((pred_is(node, pred_or) || pred_is(node, pred_and))
2263 && node->pred_left == NULL)
2265 /* We print "<nothing> or X" as just "X"
2266 * We print "<nothing> and X" as just "X"
2268 print_parenthesised(fp, node->pred_right);
2270 else
2272 if (node->pred_left || node->pred_right)
2273 parens = 1;
2275 if (parens)
2276 fprintf(fp, "%s", " ( ");
2277 print_optlist(fp, node);
2278 if (parens)
2279 fprintf(fp, "%s", " ) ");
2284 void
2285 print_optlist (FILE *fp, const struct predicate *p)
2287 if (p)
2289 print_parenthesised(fp, p->pred_left);
2290 fprintf (fp,
2291 "%s%s",
2292 p->need_stat ? "[call stat] " : "",
2293 p->need_type ? "[need type] " : "");
2294 print_predicate(fp, p);
2295 fprintf(fp, " [%g] ", p->est_success_rate);
2296 if (options.debug_options & DebugSuccessRates)
2298 fprintf(fp, "[%ld/%ld", p->perf.successes, p->perf.visits);
2299 if (p->perf.visits)
2301 double real_rate = (double)p->perf.successes / (double)p->perf.visits;
2302 fprintf(fp, "=%g] ", real_rate);
2304 else
2306 fprintf(fp, "=_] ");
2309 print_parenthesised(fp, p->pred_right);
2313 void show_success_rates(const struct predicate *p)
2315 if (options.debug_options & DebugSuccessRates)
2317 fprintf(stderr, "Predicate success rates after completion:\n");
2318 print_optlist(stderr, p);
2319 fprintf(stderr, "\n");
2326 #ifdef _NDEBUG
2327 /* If _NDEBUG is defined, the assertions will do nothing. Hence
2328 * there is no point in having a function body for pred_sanity_check()
2329 * if that preprocessor macro is defined.
2331 void
2332 pred_sanity_check(const struct predicate *predicates)
2334 /* Do nothing, since assert is a no-op with _NDEBUG set */
2335 return;
2337 #else
2338 void
2339 pred_sanity_check(const struct predicate *predicates)
2341 const struct predicate *p;
2343 for (p=predicates; p != NULL; p=p->pred_next)
2345 /* All predicates must do something. */
2346 assert (p->pred_func != NULL);
2348 /* All predicates must have a parser table entry. */
2349 assert (p->parser_entry != NULL);
2351 /* If the parser table tells us that just one predicate function is
2352 * possible, verify that that is still the one that is in effect.
2353 * If the parser has NULL for the predicate function, that means that
2354 * the parse_xxx function fills it in, so we can't check it.
2356 if (p->parser_entry->pred_func)
2358 assert (p->parser_entry->pred_func == p->pred_func);
2361 switch (p->parser_entry->type)
2363 /* Options all take effect during parsing, so there should
2364 * be no predicate entries corresponding to them. Hence we
2365 * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION
2366 * items.
2368 * This is a silly way of coding this test, but it prevents
2369 * a compiler warning (i.e. otherwise it would think that
2370 * there would be case statements missing).
2372 case ARG_OPTION:
2373 case ARG_POSITIONAL_OPTION:
2374 assert (p->parser_entry->type != ARG_OPTION);
2375 assert (p->parser_entry->type != ARG_POSITIONAL_OPTION);
2376 break;
2378 case ARG_ACTION:
2379 assert(p->side_effects); /* actions have side effects. */
2380 if (!pred_is(p, pred_prune) && !pred_is(p, pred_quit))
2382 /* actions other than -prune and -quit should
2383 * inhibit the default -print
2385 assert (p->no_default_print);
2387 break;
2389 /* We happen to know that the only user of ARG_SPECIAL_PARSE
2390 * is a test, so handle it like ARG_TEST.
2392 case ARG_SPECIAL_PARSE:
2393 case ARG_TEST:
2394 case ARG_PUNCTUATION:
2395 case ARG_NOOP:
2396 /* Punctuation and tests should have no side
2397 * effects and not inhibit default print.
2399 assert (!p->no_default_print);
2400 assert (!p->side_effects);
2401 break;
2405 #endif