Migrated from GPL version 2 to GPL version 3
[findutils.git] / find / pred.c
blob5e3adb70754e8a40dfa40635bff8bd67b5c063aa
1 /* pred.c -- execute the expression tree.
2 Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2003,
3 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include <config.h>
20 #include "defs.h"
22 #include <fnmatch.h>
23 #include <signal.h>
24 #include <math.h>
25 #include <pwd.h>
26 #include <grp.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <errno.h>
30 #include <assert.h>
31 #include <stdarg.h>
32 #include <fcntl.h>
33 #include <locale.h>
34 #include <openat.h>
35 #include "xalloc.h"
36 #include "dirname.h"
37 #include "human.h"
38 #include "modetype.h"
39 #include "filemode.h"
40 #include "wait.h"
41 #include "printquoted.h"
42 #include "buildcmd.h"
43 #include "yesno.h"
44 #include "listfile.h"
45 #include "stat-time.h"
46 #include "dircallback.h"
47 #include "error.h"
48 #include "verify.h"
50 #if ENABLE_NLS
51 # include <libintl.h>
52 # define _(Text) gettext (Text)
53 #else
54 # define _(Text) Text
55 #endif
56 #ifdef gettext_noop
57 # define N_(String) gettext_noop (String)
58 #else
59 /* See locate.c for explanation as to why not use (String) */
60 # define N_(String) String
61 #endif
63 #if !defined(SIGCHLD) && defined(SIGCLD)
64 #define SIGCHLD SIGCLD
65 #endif
69 #if HAVE_DIRENT_H
70 # include <dirent.h>
71 # define NAMLEN(dirent) strlen((dirent)->d_name)
72 #else
73 # define dirent direct
74 # define NAMLEN(dirent) (dirent)->d_namlen
75 # if HAVE_SYS_NDIR_H
76 # include <sys/ndir.h>
77 # endif
78 # if HAVE_SYS_DIR_H
79 # include <sys/dir.h>
80 # endif
81 # if HAVE_NDIR_H
82 # include <ndir.h>
83 # endif
84 #endif
86 #ifdef CLOSEDIR_VOID
87 /* Fake a return value. */
88 #define CLOSEDIR(d) (closedir (d), 0)
89 #else
90 #define CLOSEDIR(d) closedir (d)
91 #endif
96 /* Get or fake the disk device blocksize.
97 Usually defined by sys/param.h (if at all). */
98 #ifndef DEV_BSIZE
99 # ifdef BSIZE
100 # define DEV_BSIZE BSIZE
101 # else /* !BSIZE */
102 # define DEV_BSIZE 4096
103 # endif /* !BSIZE */
104 #endif /* !DEV_BSIZE */
106 /* Extract or fake data from a `struct stat'.
107 ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
108 ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
109 ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */
110 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
111 # define ST_BLKSIZE(statbuf) DEV_BSIZE
112 # if defined _POSIX_SOURCE || !defined BSIZE /* fileblocks.c uses BSIZE. */
113 # define ST_NBLOCKS(statbuf) \
114 (S_ISREG ((statbuf).st_mode) \
115 || S_ISDIR ((statbuf).st_mode) \
116 ? (statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0) : 0)
117 # else /* !_POSIX_SOURCE && BSIZE */
118 # define ST_NBLOCKS(statbuf) \
119 (S_ISREG ((statbuf).st_mode) \
120 || S_ISDIR ((statbuf).st_mode) \
121 ? st_blocks ((statbuf).st_size) : 0)
122 # endif /* !_POSIX_SOURCE && BSIZE */
123 #else /* HAVE_STRUCT_STAT_ST_BLOCKS */
124 /* Some systems, like Sequents, return st_blksize of 0 on pipes. */
125 # define ST_BLKSIZE(statbuf) ((statbuf).st_blksize > 0 \
126 ? (statbuf).st_blksize : DEV_BSIZE)
127 # if defined hpux || defined __hpux__ || defined __hpux
128 /* HP-UX counts st_blocks in 1024-byte units.
129 This loses when mixing HP-UX and BSD file systems with NFS. */
130 # define ST_NBLOCKSIZE 1024
131 # else /* !hpux */
132 # if defined _AIX && defined _I386
133 /* AIX PS/2 counts st_blocks in 4K units. */
134 # define ST_NBLOCKSIZE (4 * 1024)
135 # else /* not AIX PS/2 */
136 # if defined _CRAY
137 # define ST_NBLOCKS(statbuf) \
138 (S_ISREG ((statbuf).st_mode) \
139 || S_ISDIR ((statbuf).st_mode) \
140 ? (statbuf).st_blocks * ST_BLKSIZE(statbuf)/ST_NBLOCKSIZE : 0)
141 # endif /* _CRAY */
142 # endif /* not AIX PS/2 */
143 # endif /* !hpux */
144 #endif /* HAVE_STRUCT_STAT_ST_BLOCKS */
146 #ifndef ST_NBLOCKS
147 # define ST_NBLOCKS(statbuf) \
148 (S_ISREG ((statbuf).st_mode) \
149 || S_ISDIR ((statbuf).st_mode) \
150 ? (statbuf).st_blocks : 0)
151 #endif
153 #ifndef ST_NBLOCKSIZE
154 # define ST_NBLOCKSIZE 512
155 #endif
158 #undef MAX
159 #define MAX(a, b) ((a) > (b) ? (a) : (b))
161 static boolean match_lname PARAMS((const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case));
163 static char *format_date PARAMS((struct timespec ts, int kind));
164 static char *ctime_format PARAMS((struct timespec ts));
166 #ifdef DEBUG
167 struct pred_assoc
169 PRED_FUNC pred_func;
170 char *pred_name;
173 struct pred_assoc pred_table[] =
175 {pred_amin, "amin "},
176 {pred_and, "and "},
177 {pred_anewer, "anewer "},
178 {pred_atime, "atime "},
179 {pred_closeparen, ") "},
180 {pred_cmin, "cmin "},
181 {pred_cnewer, "cnewer "},
182 {pred_comma, ", "},
183 {pred_ctime, "ctime "},
184 {pred_delete, "delete "},
185 {pred_empty, "empty "},
186 {pred_exec, "exec "},
187 {pred_execdir, "execdir "},
188 {pred_executable, "executable "},
189 {pred_false, "false "},
190 {pred_fprint, "fprint "},
191 {pred_fprint0, "fprint0 "},
192 {pred_fprintf, "fprintf "},
193 {pred_fstype, "fstype "},
194 {pred_gid, "gid "},
195 {pred_group, "group "},
196 {pred_ilname, "ilname "},
197 {pred_iname, "iname "},
198 {pred_inum, "inum "},
199 {pred_ipath, "ipath "},
200 {pred_links, "links "},
201 {pred_lname, "lname "},
202 {pred_ls, "ls "},
203 {pred_mmin, "mmin "},
204 {pred_mtime, "mtime "},
205 {pred_name, "name "},
206 {pred_negate, "not "},
207 {pred_newer, "newer "},
208 {pred_newerXY, "newerXY "},
209 {pred_nogroup, "nogroup "},
210 {pred_nouser, "nouser "},
211 {pred_ok, "ok "},
212 {pred_okdir, "okdir "},
213 {pred_openparen, "( "},
214 {pred_or, "or "},
215 {pred_path, "path "},
216 {pred_perm, "perm "},
217 {pred_print, "print "},
218 {pred_print0, "print0 "},
219 {pred_prune, "prune "},
220 {pred_quit, "quit "},
221 {pred_readable, "readable "},
222 {pred_regex, "regex "},
223 {pred_samefile,"samefile "},
224 {pred_size, "size "},
225 {pred_true, "true "},
226 {pred_type, "type "},
227 {pred_uid, "uid "},
228 {pred_used, "used "},
229 {pred_user, "user "},
230 {pred_writable, "writable "},
231 {pred_xtype, "xtype "},
232 {0, "none "}
234 #endif
236 /* Returns ts1 - ts2 */
237 static double ts_difference(struct timespec ts1,
238 struct timespec ts2)
240 double d = difftime(ts1.tv_sec, ts2.tv_sec)
241 + (1.0e-9 * (ts1.tv_nsec - ts2.tv_nsec));
242 return d;
246 static int
247 compare_ts(struct timespec ts1,
248 struct timespec ts2)
250 if ((ts1.tv_sec == ts2.tv_sec) &&
251 (ts1.tv_nsec == ts2.tv_nsec))
253 return 0;
255 else
257 double diff = ts_difference(ts1, ts2);
258 return diff < 0.0 ? -1 : +1;
262 /* Predicate processing routines.
264 PATHNAME is the full pathname of the file being checked.
265 *STAT_BUF contains information about PATHNAME.
266 *PRED_PTR contains information for applying the predicate.
268 Return true if the file passes this predicate, false if not. */
271 /* pred_timewindow
273 * Returns true if THE_TIME is
274 * COMP_GT: after the specified time
275 * COMP_LT: before the specified time
276 * COMP_EQ: less than WINDOW seconds after the specified time.
278 static boolean
279 pred_timewindow(struct timespec ts, struct predicate const *pred_ptr, int window)
281 switch (pred_ptr->args.reftime.kind)
283 case COMP_GT:
284 return compare_ts(ts, pred_ptr->args.reftime.ts) > 0;
286 case COMP_LT:
287 return compare_ts(ts, pred_ptr->args.reftime.ts) < 0;
289 case COMP_EQ:
291 double delta = ts_difference(ts, pred_ptr->args.reftime.ts);
292 return (delta >= 0.0 && delta < window);
295 assert (0);
296 abort ();
300 boolean
301 pred_amin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
303 (void) &pathname;
304 return pred_timewindow(get_stat_atime(stat_buf), pred_ptr, 60);
307 boolean
308 pred_and (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
310 if (pred_ptr->pred_left == NULL
311 || apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
313 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
315 else
316 return false;
319 boolean
320 pred_anewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
322 (void) &pathname;
323 assert (COMP_GT == pred_ptr->args.reftime.kind);
324 return compare_ts(get_stat_atime(stat_buf), pred_ptr->args.reftime.ts) > 0;
327 boolean
328 pred_atime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
330 (void) &pathname;
331 return pred_timewindow(get_stat_atime(stat_buf), pred_ptr, DAYSECS);
334 boolean
335 pred_closeparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
337 (void) &pathname;
338 (void) &stat_buf;
339 (void) &pred_ptr;
341 return true;
344 boolean
345 pred_cmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
347 (void) pathname;
348 return pred_timewindow(get_stat_ctime(stat_buf), pred_ptr, 60);
351 boolean
352 pred_cnewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
354 (void) pathname;
356 assert (COMP_GT == pred_ptr->args.reftime.kind);
357 return compare_ts(get_stat_ctime(stat_buf), pred_ptr->args.reftime.ts) > 0;
360 boolean
361 pred_comma (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
363 if (pred_ptr->pred_left != NULL)
365 apply_predicate(pathname, stat_buf,pred_ptr->pred_left);
367 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
370 boolean
371 pred_ctime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
373 (void) &pathname;
374 return pred_timewindow(get_stat_ctime(stat_buf), pred_ptr, DAYSECS);
377 static boolean
378 perform_delete(int flags)
380 return 0 == unlinkat(state.cwd_dir_fd, state.rel_pathname, flags);
384 boolean
385 pred_delete (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
387 (void) pred_ptr;
388 (void) stat_buf;
389 if (strcmp (state.rel_pathname, "."))
391 int flags=0;
392 if (state.have_stat && S_ISDIR(stat_buf->st_mode))
393 flags |= AT_REMOVEDIR;
394 if (perform_delete(flags))
396 return true;
398 else
400 if (EISDIR == errno)
402 if ((flags & AT_REMOVEDIR) == 0)
404 /* unlink() operation failed because we should have done rmdir(). */
405 flags |= AT_REMOVEDIR;
406 if (perform_delete(flags))
407 return true;
411 error (0, errno, _("cannot delete %s"),
412 safely_quote_err_filename(0, pathname));
413 return false;
415 else
417 /* nothing to do. */
418 return true;
422 boolean
423 pred_empty (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
425 (void) pathname;
426 (void) pred_ptr;
428 if (S_ISDIR (stat_buf->st_mode))
430 int fd;
431 DIR *d;
432 struct dirent *dp;
433 boolean empty = true;
435 errno = 0;
436 if ((fd = openat(state.cwd_dir_fd, state.rel_pathname, O_RDONLY
437 #if defined O_LARGEFILE
438 |O_LARGEFILE
439 #endif
440 )) < 0)
442 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
443 state.exit_status = 1;
444 return false;
446 d = fdopendir (fd);
447 if (d == NULL)
449 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
450 state.exit_status = 1;
451 return false;
453 for (dp = readdir (d); dp; dp = readdir (d))
455 if (dp->d_name[0] != '.'
456 || (dp->d_name[1] != '\0'
457 && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
459 empty = false;
460 break;
463 if (CLOSEDIR (d))
465 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
466 state.exit_status = 1;
467 return false;
469 return (empty);
471 else if (S_ISREG (stat_buf->st_mode))
472 return (stat_buf->st_size == 0);
473 else
474 return (false);
477 static boolean
478 new_impl_pred_exec (int dirfd, const char *pathname,
479 struct stat *stat_buf,
480 struct predicate *pred_ptr,
481 const char *prefix, size_t pfxlen)
483 struct exec_val *execp = &pred_ptr->args.exec_vec;
484 size_t len = strlen(pathname);
486 (void) stat_buf;
487 execp->dirfd = dirfd;
488 if (execp->multiple)
490 /* Push the argument onto the current list.
491 * The command may or may not be run at this point,
492 * depending on the command line length limits.
494 bc_push_arg(&execp->ctl,
495 &execp->state,
496 pathname, len+1,
497 prefix, pfxlen,
500 /* remember that there are pending execdirs. */
501 state.execdirs_outstanding = true;
503 /* POSIX: If the primary expression is punctuated by a plus
504 * sign, the primary shall always evaluate as true
506 return true;
508 else
510 int i;
512 for (i=0; i<execp->num_args; ++i)
514 bc_do_insert(&execp->ctl,
515 &execp->state,
516 execp->replace_vec[i],
517 strlen(execp->replace_vec[i]),
518 prefix, pfxlen,
519 pathname, len,
523 /* Actually invoke the command. */
524 return execp->ctl.exec_callback(&execp->ctl,
525 &execp->state);
530 boolean
531 pred_exec (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
533 return new_impl_pred_exec(get_start_dirfd(),
534 pathname, stat_buf, pred_ptr, NULL, 0);
537 boolean
538 pred_execdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
540 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
541 (void) &pathname;
542 return new_impl_pred_exec (get_current_dirfd(),
543 state.rel_pathname, stat_buf, pred_ptr,
544 prefix, (prefix ? 2 : 0));
547 boolean
548 pred_false (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
550 (void) &pathname;
551 (void) &stat_buf;
552 (void) &pred_ptr;
555 return (false);
558 boolean
559 pred_fls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
561 FILE * stream = pred_ptr->args.printf_vec.stream;
562 list_file (pathname, state.cwd_dir_fd, state.rel_pathname, stat_buf,
563 options.start_time.tv_sec,
564 options.output_block_size,
565 pred_ptr->literal_control_chars, stream);
566 return true;
569 boolean
570 pred_fprint (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
572 (void) &pathname;
573 (void) &stat_buf;
575 print_quoted(pred_ptr->args.printf_vec.stream,
576 pred_ptr->args.printf_vec.quote_opts,
577 pred_ptr->args.printf_vec.dest_is_tty,
578 "%s\n",
579 pathname);
580 return true;
583 boolean
584 pred_fprint0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
586 FILE * fp = pred_ptr->args.printf_vec.stream;
588 (void) &stat_buf;
590 fputs (pathname, fp);
591 putc (0, fp);
592 return true;
597 static char*
598 mode_to_filetype(mode_t m)
600 #define HANDLE_TYPE(t,letter) if (m==t) { return letter; }
601 #ifdef S_IFREG
602 HANDLE_TYPE(S_IFREG, "f"); /* regular file */
603 #endif
604 #ifdef S_IFDIR
605 HANDLE_TYPE(S_IFDIR, "d"); /* directory */
606 #endif
607 #ifdef S_IFLNK
608 HANDLE_TYPE(S_IFLNK, "l"); /* symbolic link */
609 #endif
610 #ifdef S_IFSOCK
611 HANDLE_TYPE(S_IFSOCK, "s"); /* Unix domain socket */
612 #endif
613 #ifdef S_IFBLK
614 HANDLE_TYPE(S_IFBLK, "b"); /* block device */
615 #endif
616 #ifdef S_IFCHR
617 HANDLE_TYPE(S_IFCHR, "c"); /* character device */
618 #endif
619 #ifdef S_IFIFO
620 HANDLE_TYPE(S_IFIFO, "p"); /* FIFO */
621 #endif
622 #ifdef S_IFDOOR
623 HANDLE_TYPE(S_IFDOOR, "D"); /* Door (e.g. on Solaris) */
624 #endif
625 return "U"; /* Unknown */
628 static double
629 file_sparseness(const struct stat *p)
631 #if defined HAVE_STRUCT_STAT_ST_BLOCKS
632 if (0 == p->st_size)
634 if (0 == p->st_blocks)
635 return 1.0;
636 else
637 return p->st_blocks < 0 ? -HUGE_VAL : HUGE_VAL;
639 else
641 double blklen = file_blocksize(p) * (double)p->st_blocks;
642 return blklen / p->st_size;
644 #else
645 return 1.0;
646 #endif
651 static void
652 checked_fprintf(struct format_val *dest, const char *fmt, ...)
654 int rv;
655 va_list ap;
657 va_start(ap, fmt);
658 rv = vfprintf(dest->stream, fmt, ap);
659 if (rv < 0)
660 nonfatal_file_error(dest->filename);
664 static void
665 checked_print_quoted (struct format_val *dest,
666 const char *format, const char *s)
668 int rv = print_quoted(dest->stream, dest->quote_opts, dest->dest_is_tty,
669 format, s);
670 if (rv < 0)
671 nonfatal_file_error(dest->filename);
675 static void
676 checked_fwrite(void *p, size_t siz, size_t nmemb, struct format_val *dest)
678 int items_written = fwrite(p, siz, nmemb, dest->stream);
679 if (items_written < nmemb)
680 nonfatal_file_error(dest->filename);
683 static void
684 checked_fflush(struct format_val *dest)
686 if (0 != fflush(dest->stream))
688 nonfatal_file_error(dest->filename);
692 static void
693 do_fprintf(struct format_val *dest,
694 struct segment *segment,
695 const char *pathname,
696 const struct stat *stat_buf)
698 char hbuf[LONGEST_HUMAN_READABLE + 1];
699 const char *cp;
701 switch (segment->segkind)
703 case KIND_PLAIN: /* Plain text string (no % conversion). */
704 /* trusted */
705 checked_fwrite(segment->text, 1, segment->text_len, dest);
706 break;
708 case KIND_STOP: /* Terminate argument and flush output. */
709 /* trusted */
710 checked_fwrite(segment->text, 1, segment->text_len, dest);
711 checked_fflush(dest);
712 break;
714 case KIND_FORMAT:
715 switch (segment->format_char[0])
717 case 'a': /* atime in `ctime' format. */
718 /* UNTRUSTED, probably unexploitable */
719 checked_fprintf (dest, segment->text, ctime_format (get_stat_atime(stat_buf)));
720 break;
721 case 'b': /* size in 512-byte blocks */
722 /* UNTRUSTED, probably unexploitable */
723 checked_fprintf (dest, segment->text,
724 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
725 hbuf, human_ceiling,
726 ST_NBLOCKSIZE, 512));
727 break;
728 case 'c': /* ctime in `ctime' format */
729 /* UNTRUSTED, probably unexploitable */
730 checked_fprintf (dest, segment->text, ctime_format (get_stat_ctime(stat_buf)));
731 break;
732 case 'd': /* depth in search tree */
733 /* UNTRUSTED, probably unexploitable */
734 checked_fprintf (dest, segment->text, state.curdepth);
735 break;
736 case 'D': /* Device on which file exists (stat.st_dev) */
737 /* trusted */
738 checked_fprintf (dest, segment->text,
739 human_readable ((uintmax_t) stat_buf->st_dev, hbuf,
740 human_ceiling, 1, 1));
741 break;
742 case 'f': /* base name of path */
743 /* sanitised */
744 checked_print_quoted (dest, segment->text, base_name (pathname));
745 break;
746 case 'F': /* file system type */
747 /* trusted */
748 checked_print_quoted (dest, segment->text, filesystem_type (stat_buf, pathname));
749 break;
750 case 'g': /* group name */
751 /* trusted */
752 /* (well, the actual group is selected by the user but
753 * its name was selected by the system administrator)
756 struct group *g;
758 g = getgrgid (stat_buf->st_gid);
759 if (g)
761 segment->text[segment->text_len] = 's';
762 checked_fprintf (dest, segment->text, g->gr_name);
763 break;
765 else
767 /* Do nothing. */
768 /*FALLTHROUGH*/
771 /*FALLTHROUGH*/ /*...sometimes, so 'G' case.*/
773 case 'G': /* GID number */
774 /* UNTRUSTED, probably unexploitable */
775 checked_fprintf (dest, segment->text,
776 human_readable ((uintmax_t) stat_buf->st_gid, hbuf,
777 human_ceiling, 1, 1));
778 break;
779 case 'h': /* leading directories part of path */
780 /* sanitised */
782 cp = strrchr (pathname, '/');
783 if (cp == NULL) /* No leading directories. */
785 /* If there is no slash in the pathname, we still
786 * print the string because it contains characters
787 * other than just '%s'. The %h expands to ".".
789 checked_print_quoted (dest, segment->text, ".");
791 else
793 char *s = strdup(pathname);
794 s[cp - pathname] = 0;
795 checked_print_quoted (dest, segment->text, s);
796 free(s);
799 break;
801 case 'H': /* ARGV element file was found under */
802 /* trusted */
804 char *s = xmalloc(state.starting_path_length+1);
805 memcpy(s, pathname, state.starting_path_length);
806 s[state.starting_path_length] = 0;
807 checked_fprintf (dest, segment->text, s);
808 free(s);
810 break;
812 case 'i': /* inode number */
813 /* UNTRUSTED, but not exploitable I think */
814 checked_fprintf (dest, segment->text,
815 human_readable ((uintmax_t) stat_buf->st_ino, hbuf,
816 human_ceiling,
817 1, 1));
818 break;
819 case 'k': /* size in 1K blocks */
820 /* UNTRUSTED, but not exploitable I think */
821 checked_fprintf (dest, segment->text,
822 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
823 hbuf, human_ceiling,
824 ST_NBLOCKSIZE, 1024));
825 break;
826 case 'l': /* object of symlink */
827 /* sanitised */
828 #ifdef S_ISLNK
830 char *linkname = 0;
832 if (S_ISLNK (stat_buf->st_mode))
834 linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
835 if (linkname == 0)
836 state.exit_status = 1;
838 if (linkname)
840 checked_print_quoted (dest, segment->text, linkname);
841 free (linkname);
843 else
845 /* We still need to honour the field width etc., so this is
846 * not a no-op.
848 checked_print_quoted (dest, segment->text, "");
851 #endif /* S_ISLNK */
852 break;
854 case 'M': /* mode as 10 chars (eg., "-rwxr-x--x" */
855 /* UNTRUSTED, probably unexploitable */
857 char modestring[16] ;
858 filemodestring (stat_buf, modestring);
859 modestring[10] = '\0';
860 checked_fprintf (dest, segment->text, modestring);
862 break;
864 case 'm': /* mode as octal number (perms only) */
865 /* UNTRUSTED, probably unexploitable */
867 /* Output the mode portably using the traditional numbers,
868 even if the host unwisely uses some other numbering
869 scheme. But help the compiler in the common case where
870 the host uses the traditional numbering scheme. */
871 mode_t m = stat_buf->st_mode;
872 boolean traditional_numbering_scheme =
873 (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000
874 && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100
875 && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010
876 && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001);
877 checked_fprintf (dest, segment->text,
878 (traditional_numbering_scheme
879 ? m & MODE_ALL
880 : ((m & S_ISUID ? 04000 : 0)
881 | (m & S_ISGID ? 02000 : 0)
882 | (m & S_ISVTX ? 01000 : 0)
883 | (m & S_IRUSR ? 00400 : 0)
884 | (m & S_IWUSR ? 00200 : 0)
885 | (m & S_IXUSR ? 00100 : 0)
886 | (m & S_IRGRP ? 00040 : 0)
887 | (m & S_IWGRP ? 00020 : 0)
888 | (m & S_IXGRP ? 00010 : 0)
889 | (m & S_IROTH ? 00004 : 0)
890 | (m & S_IWOTH ? 00002 : 0)
891 | (m & S_IXOTH ? 00001 : 0))));
893 break;
895 case 'n': /* number of links */
896 /* UNTRUSTED, probably unexploitable */
897 checked_fprintf (dest, segment->text,
898 human_readable ((uintmax_t) stat_buf->st_nlink,
899 hbuf,
900 human_ceiling,
901 1, 1));
902 break;
904 case 'p': /* pathname */
905 /* sanitised */
906 checked_print_quoted (dest, segment->text, pathname);
907 break;
909 case 'P': /* pathname with ARGV element stripped */
910 /* sanitised */
911 if (state.curdepth > 0)
913 cp = pathname + state.starting_path_length;
914 if (*cp == '/')
915 /* Move past the slash between the ARGV element
916 and the rest of the pathname. But if the ARGV element
917 ends in a slash, we didn't add another, so we've
918 already skipped past it. */
919 cp++;
921 else
923 cp = "";
925 checked_print_quoted (dest, segment->text, cp);
926 break;
928 case 's': /* size in bytes */
929 /* UNTRUSTED, probably unexploitable */
930 checked_fprintf (dest, segment->text,
931 human_readable ((uintmax_t) stat_buf->st_size,
932 hbuf, human_ceiling, 1, 1));
933 break;
935 case 'S': /* sparseness */
936 /* UNTRUSTED, probably unexploitable */
937 checked_fprintf (dest, segment->text, file_sparseness(stat_buf));;
938 break;
940 case 't': /* mtime in `ctime' format */
941 /* UNTRUSTED, probably unexploitable */
942 checked_fprintf (dest, segment->text,
943 ctime_format (get_stat_mtime(stat_buf)));
944 break;
946 case 'u': /* user name */
947 /* trusted */
948 /* (well, the actual user is selected by the user on systems
949 * where chown is not restricted, but the user name was
950 * selected by the system administrator)
953 struct passwd *p;
955 p = getpwuid (stat_buf->st_uid);
956 if (p)
958 segment->text[segment->text_len] = 's';
959 checked_fprintf (dest, segment->text, p->pw_name);
960 break;
962 /* else fallthru */
964 /* FALLTHROUGH*/ /* .. to case U */
966 case 'U': /* UID number */
967 /* UNTRUSTED, probably unexploitable */
968 checked_fprintf (dest, segment->text,
969 human_readable ((uintmax_t) stat_buf->st_uid, hbuf,
970 human_ceiling, 1, 1));
971 break;
973 /* %Y: type of file system entry like `ls -l`:
974 * (d,-,l,s,p,b,c,n) n=nonexistent(symlink)
976 case 'Y': /* in case of symlink */
977 /* trusted */
979 #ifdef S_ISLNK
980 if (S_ISLNK (stat_buf->st_mode))
982 struct stat sbuf;
983 /* If we would normally follow links, do not do so.
984 * If we would normally not follow links, do so.
986 if ((following_links() ? lstat : stat)
987 (state.rel_pathname, &sbuf) != 0)
989 if ( errno == ENOENT )
991 checked_fprintf (dest, segment->text, "N");
992 break;
994 else if ( errno == ELOOP )
996 checked_fprintf (dest, segment->text, "L");
997 break;
999 else
1001 checked_fprintf (dest, segment->text, "?");
1002 error (0, errno, "%s",
1003 safely_quote_err_filename(0, pathname));
1004 /* exit_status = 1;
1005 return ; */
1006 break;
1009 checked_fprintf (dest, segment->text,
1010 mode_to_filetype(sbuf.st_mode & S_IFMT));
1012 #endif /* S_ISLNK */
1013 else
1015 checked_fprintf (dest, segment->text,
1016 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1019 break;
1021 case 'y':
1022 /* trusted */
1024 checked_fprintf (dest, segment->text,
1025 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1027 break;
1029 /* end of KIND_FORMAT case */
1030 break;
1034 boolean
1035 pred_fprintf (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1037 struct format_val *dest = &pred_ptr->args.printf_vec;
1038 struct segment *segment;
1040 for (segment = dest->segment; segment; segment = segment->next)
1042 if ( (KIND_FORMAT == segment->segkind) && segment->format_char[1]) /* Component of date. */
1044 struct timespec ts;
1045 int valid = 0;
1047 switch (segment->format_char[0])
1049 case 'A':
1050 ts = get_stat_atime(stat_buf);
1051 valid = 1;
1052 break;
1053 case 'B':
1054 ts = get_stat_birthtime(stat_buf);
1055 if ('@' == segment->format_char[1])
1056 valid = 1;
1057 else
1058 valid = (ts.tv_nsec >= 0);
1059 break;
1060 case 'C':
1061 ts = get_stat_ctime(stat_buf);
1062 valid = 1;
1063 break;
1064 case 'T':
1065 ts = get_stat_mtime(stat_buf);
1066 valid = 1;
1067 break;
1068 default:
1069 assert (0);
1070 abort ();
1072 /* We trust the output of format_date not to contain
1073 * nasty characters, though the value of the date
1074 * is itself untrusted data.
1076 if (valid)
1078 /* trusted */
1079 checked_fprintf (dest, segment->text,
1080 format_date (ts, segment->format_char[1]));
1082 else
1084 /* The specified timestamp is not available, output
1085 * nothing for the timestamp, but use the rest (so that
1086 * for example find foo -printf '[%Bs] %p\n' can print
1087 * "[] foo").
1089 /* trusted */
1090 checked_fprintf (dest, segment->text, "");
1093 else
1095 /* Print a segment which is not a date. */
1096 do_fprintf(dest, segment, pathname, stat_buf);
1099 return true;
1102 boolean
1103 pred_fstype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1105 (void) pathname;
1107 if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0)
1108 return true;
1109 else
1110 return false;
1113 boolean
1114 pred_gid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1116 (void) pathname;
1118 switch (pred_ptr->args.numinfo.kind)
1120 case COMP_GT:
1121 if (stat_buf->st_gid > pred_ptr->args.numinfo.l_val)
1122 return (true);
1123 break;
1124 case COMP_LT:
1125 if (stat_buf->st_gid < pred_ptr->args.numinfo.l_val)
1126 return (true);
1127 break;
1128 case COMP_EQ:
1129 if (stat_buf->st_gid == pred_ptr->args.numinfo.l_val)
1130 return (true);
1131 break;
1133 return (false);
1136 boolean
1137 pred_group (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1139 (void) pathname;
1141 if (pred_ptr->args.gid == stat_buf->st_gid)
1142 return (true);
1143 else
1144 return (false);
1147 boolean
1148 pred_ilname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1150 return match_lname (pathname, stat_buf, pred_ptr, true);
1153 boolean
1154 pred_iname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1156 const char *base;
1158 (void) stat_buf;
1160 /* FNM_PERIOD is not used here because POSIX requires that it not be.
1161 * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1163 base = base_name (pathname);
1164 if (fnmatch (pred_ptr->args.str, base, FNM_CASEFOLD) == 0)
1165 return (true);
1166 return (false);
1169 boolean
1170 pred_inum (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1172 (void) pathname;
1174 switch (pred_ptr->args.numinfo.kind)
1176 case COMP_GT:
1177 if (stat_buf->st_ino > pred_ptr->args.numinfo.l_val)
1178 return (true);
1179 break;
1180 case COMP_LT:
1181 if (stat_buf->st_ino < pred_ptr->args.numinfo.l_val)
1182 return (true);
1183 break;
1184 case COMP_EQ:
1185 if (stat_buf->st_ino == pred_ptr->args.numinfo.l_val)
1186 return (true);
1187 break;
1189 return (false);
1192 boolean
1193 pred_ipath (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1195 (void) stat_buf;
1197 if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0)
1198 return (true);
1199 return (false);
1202 boolean
1203 pred_links (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1205 (void) pathname;
1207 switch (pred_ptr->args.numinfo.kind)
1209 case COMP_GT:
1210 if (stat_buf->st_nlink > pred_ptr->args.numinfo.l_val)
1211 return (true);
1212 break;
1213 case COMP_LT:
1214 if (stat_buf->st_nlink < pred_ptr->args.numinfo.l_val)
1215 return (true);
1216 break;
1217 case COMP_EQ:
1218 if (stat_buf->st_nlink == pred_ptr->args.numinfo.l_val)
1219 return (true);
1220 break;
1222 return (false);
1225 boolean
1226 pred_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1228 return match_lname (pathname, stat_buf, pred_ptr, false);
1231 static boolean
1232 match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case)
1234 boolean ret = false;
1235 #ifdef S_ISLNK
1236 if (S_ISLNK (stat_buf->st_mode))
1238 char *linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
1239 if (linkname)
1241 if (fnmatch (pred_ptr->args.str, linkname,
1242 ignore_case ? FNM_CASEFOLD : 0) == 0)
1243 ret = true;
1244 free (linkname);
1247 #endif /* S_ISLNK */
1248 return ret;
1251 boolean
1252 pred_ls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1254 return pred_fls(pathname, stat_buf, pred_ptr);
1257 boolean
1258 pred_mmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1260 (void) &pathname;
1261 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, 60);
1264 boolean
1265 pred_mtime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1267 (void) pathname;
1268 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, DAYSECS);
1271 boolean
1272 pred_name (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1274 const char *base;
1276 (void) stat_buf;
1277 base = base_name (pathname);
1279 /* FNM_PERIOD is not used here because POSIX requires that it not be.
1280 * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1282 if (fnmatch (pred_ptr->args.str, base, 0) == 0)
1283 return (true);
1284 return (false);
1287 boolean
1288 pred_negate (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1290 return !apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1293 boolean
1294 pred_newer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1296 (void) pathname;
1298 assert (COMP_GT == pred_ptr->args.reftime.kind);
1299 return compare_ts(get_stat_mtime(stat_buf), pred_ptr->args.reftime.ts) > 0;
1302 boolean
1303 pred_newerXY (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1305 struct timespec ts;
1306 boolean collected = false;
1308 assert (COMP_GT == pred_ptr->args.reftime.kind);
1310 switch (pred_ptr->args.reftime.xval)
1312 case XVAL_TIME:
1313 assert (pred_ptr->args.reftime.xval != XVAL_TIME);
1314 return false;
1316 case XVAL_ATIME:
1317 ts = get_stat_atime(stat_buf);
1318 collected = true;
1319 break;
1321 case XVAL_BIRTHTIME:
1322 ts = get_stat_birthtime(stat_buf);
1323 collected = true;
1324 if (ts.tv_nsec < 0);
1326 /* XXX: Cannot determine birth time. Warn once. */
1327 error(0, 0, _("Warning: cannot determine birth time of file %s"),
1328 safely_quote_err_filename(0, pathname));
1329 return false;
1331 break;
1333 case XVAL_CTIME:
1334 ts = get_stat_ctime(stat_buf);
1335 collected = true;
1336 break;
1338 case XVAL_MTIME:
1339 ts = get_stat_mtime(stat_buf);
1340 collected = true;
1341 break;
1344 assert (collected);
1345 return compare_ts(ts, pred_ptr->args.reftime.ts) > 0;
1348 boolean
1349 pred_nogroup (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1351 (void) pathname;
1352 (void) pred_ptr;
1354 #ifdef CACHE_IDS
1355 extern char *gid_unused;
1357 return gid_unused[(unsigned) stat_buf->st_gid];
1358 #else
1359 return getgrgid (stat_buf->st_gid) == NULL;
1360 #endif
1363 boolean
1364 pred_nouser (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1366 #ifdef CACHE_IDS
1367 extern char *uid_unused;
1368 #endif
1370 (void) pathname;
1371 (void) pred_ptr;
1373 #ifdef CACHE_IDS
1374 return uid_unused[(unsigned) stat_buf->st_uid];
1375 #else
1376 return getpwuid (stat_buf->st_uid) == NULL;
1377 #endif
1381 static boolean
1382 is_ok(const char *program, const char *arg)
1384 fflush (stdout);
1385 /* The draft open standard requires that, in the POSIX locale,
1386 the last non-blank character of this prompt be '?'.
1387 The exact format is not specified.
1388 This standard does not have requirements for locales other than POSIX
1390 /* XXX: printing UNTRUSTED data here. */
1391 fprintf (stderr, _("< %s ... %s > ? "), program, arg);
1392 fflush (stderr);
1393 return yesno();
1396 boolean
1397 pred_ok (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1399 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1400 return new_impl_pred_exec (get_start_dirfd(),
1401 pathname, stat_buf, pred_ptr, NULL, 0);
1402 else
1403 return false;
1406 boolean
1407 pred_okdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1409 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
1410 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1411 return new_impl_pred_exec (get_current_dirfd(),
1412 state.rel_pathname, stat_buf, pred_ptr,
1413 prefix, (prefix ? 2 : 0));
1414 else
1415 return false;
1418 boolean
1419 pred_openparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1421 (void) pathname;
1422 (void) stat_buf;
1423 (void) pred_ptr;
1424 return true;
1427 boolean
1428 pred_or (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1430 if (pred_ptr->pred_left == NULL
1431 || !apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
1433 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1435 else
1436 return true;
1439 boolean
1440 pred_path (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1442 (void) stat_buf;
1443 if (fnmatch (pred_ptr->args.str, pathname, 0) == 0)
1444 return (true);
1445 return (false);
1448 boolean
1449 pred_perm (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1451 mode_t mode = stat_buf->st_mode;
1452 mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0];
1453 (void) pathname;
1454 switch (pred_ptr->args.perm.kind)
1456 case PERM_AT_LEAST:
1457 return (mode & perm_val) == perm_val;
1458 break;
1460 case PERM_ANY:
1461 /* True if any of the bits set in the mask are also set in the file's mode.
1464 * Otherwise, if onum is prefixed by a hyphen, the primary shall
1465 * evaluate as true if at least all of the bits specified in
1466 * onum that are also set in the octal mask 07777 are set.
1468 * Eric Blake's interpretation is that the mode argument is zero,
1471 if (0 == perm_val)
1472 return true; /* Savannah bug 14748; we used to return false */
1473 else
1474 return (mode & perm_val) != 0;
1475 break;
1477 case PERM_EXACT:
1478 return (mode & MODE_ALL) == perm_val;
1479 break;
1481 default:
1482 abort ();
1483 break;
1488 struct access_check_args
1490 const char *filename;
1491 int access_type;
1492 int cb_errno;
1496 static int
1497 access_callback(void *context)
1499 int rv;
1500 struct access_check_args *args = context;
1501 if ((rv = access(args->filename, args->access_type)) < 0)
1502 args->cb_errno = errno;
1503 return rv;
1506 static int
1507 can_access(int access_type)
1509 struct access_check_args args;
1510 args.filename = state.rel_pathname;
1511 args.access_type = access_type;
1512 args.cb_errno = 0;
1513 return 0 == run_in_dir(state.cwd_dir_fd, access_callback, &args);
1517 boolean
1518 pred_executable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1520 (void) pathname;
1521 (void) stat_buf;
1522 (void) pred_ptr;
1524 return can_access(X_OK);
1527 boolean
1528 pred_readable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1530 (void) pathname;
1531 (void) stat_buf;
1532 (void) pred_ptr;
1534 return can_access(R_OK);
1537 boolean
1538 pred_writable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1540 (void) pathname;
1541 (void) stat_buf;
1542 (void) pred_ptr;
1544 return can_access(W_OK);
1547 boolean
1548 pred_print (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1550 (void) stat_buf;
1551 (void) pred_ptr;
1553 print_quoted(pred_ptr->args.printf_vec.stream,
1554 pred_ptr->args.printf_vec.quote_opts,
1555 pred_ptr->args.printf_vec.dest_is_tty,
1556 "%s\n", pathname);
1557 return true;
1560 boolean
1561 pred_print0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1563 return pred_fprint0(pathname, stat_buf, pred_ptr);
1566 boolean
1567 pred_prune (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1569 (void) pathname;
1570 (void) pred_ptr;
1572 if (options.do_dir_first == true &&
1573 stat_buf != NULL &&
1574 S_ISDIR(stat_buf->st_mode))
1575 state.stop_at_current_level = true;
1577 return (options.do_dir_first); /* This is what SunOS find seems to do. */
1580 boolean
1581 pred_quit (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1583 (void) pathname;
1584 (void) stat_buf;
1585 (void) pred_ptr;
1587 /* Run any cleanups. This includes executing any command lines
1588 * we have partly built but not executed.
1590 cleanup();
1592 /* Since -exec and friends don't leave child processes running in the
1593 * background, there is no need to wait for them here.
1595 exit(state.exit_status); /* 0 for success, etc. */
1598 boolean
1599 pred_regex (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1601 int len = strlen (pathname);
1602 (void) stat_buf;
1603 if (re_match (pred_ptr->args.regex, pathname, len, 0,
1604 (struct re_registers *) NULL) == len)
1605 return (true);
1606 return (false);
1609 boolean
1610 pred_size (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1612 uintmax_t f_val;
1614 (void) pathname;
1615 f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize)
1616 + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0));
1617 switch (pred_ptr->args.size.kind)
1619 case COMP_GT:
1620 if (f_val > pred_ptr->args.size.size)
1621 return (true);
1622 break;
1623 case COMP_LT:
1624 if (f_val < pred_ptr->args.size.size)
1625 return (true);
1626 break;
1627 case COMP_EQ:
1628 if (f_val == pred_ptr->args.size.size)
1629 return (true);
1630 break;
1632 return (false);
1635 boolean
1636 pred_samefile (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1638 /* Potential optimisation: because of the loop protection, we always
1639 * know the device of the current directory, hence the device number
1640 * of the file we're currently considering. If -L is not in effect,
1641 * and the device number of the file we're looking for is not the
1642 * same as the device number of the current directory, this
1643 * predicate cannot return true. Hence there would be no need to
1644 * stat the file we're looking at.
1646 (void) pathname;
1648 /* We will often still have an fd open on the file under consideration,
1649 * but that's just to ensure inode number stability by maintaining
1650 * a reference to it; we don't need the file for anything else.
1652 return stat_buf->st_ino == pred_ptr->args.samefileid.ino
1653 && stat_buf->st_dev == pred_ptr->args.samefileid.dev;
1656 boolean
1657 pred_true (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1659 (void) pathname;
1660 (void) stat_buf;
1661 (void) pred_ptr;
1662 return true;
1665 boolean
1666 pred_type (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1668 mode_t mode;
1669 mode_t type = pred_ptr->args.type;
1671 assert (state.have_type);
1673 if (0 == state.type)
1675 /* This can sometimes happen with broken NFS servers.
1676 * See Savannah bug #16378.
1678 return false;
1681 (void) pathname;
1683 if (state.have_stat)
1684 mode = stat_buf->st_mode;
1685 else
1686 mode = state.type;
1688 #ifndef S_IFMT
1689 /* POSIX system; check `mode' the slow way. */
1690 if ((S_ISBLK (mode) && type == S_IFBLK)
1691 || (S_ISCHR (mode) && type == S_IFCHR)
1692 || (S_ISDIR (mode) && type == S_IFDIR)
1693 || (S_ISREG (mode) && type == S_IFREG)
1694 #ifdef S_IFLNK
1695 || (S_ISLNK (mode) && type == S_IFLNK)
1696 #endif
1697 #ifdef S_IFIFO
1698 || (S_ISFIFO (mode) && type == S_IFIFO)
1699 #endif
1700 #ifdef S_IFSOCK
1701 || (S_ISSOCK (mode) && type == S_IFSOCK)
1702 #endif
1703 #ifdef S_IFDOOR
1704 || (S_ISDOOR (mode) && type == S_IFDOOR)
1705 #endif
1707 #else /* S_IFMT */
1708 /* Unix system; check `mode' the fast way. */
1709 if ((mode & S_IFMT) == type)
1710 #endif /* S_IFMT */
1711 return (true);
1712 else
1713 return (false);
1716 boolean
1717 pred_uid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1719 (void) pathname;
1720 switch (pred_ptr->args.numinfo.kind)
1722 case COMP_GT:
1723 if (stat_buf->st_uid > pred_ptr->args.numinfo.l_val)
1724 return (true);
1725 break;
1726 case COMP_LT:
1727 if (stat_buf->st_uid < pred_ptr->args.numinfo.l_val)
1728 return (true);
1729 break;
1730 case COMP_EQ:
1731 if (stat_buf->st_uid == pred_ptr->args.numinfo.l_val)
1732 return (true);
1733 break;
1735 return (false);
1738 boolean
1739 pred_used (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1741 struct timespec delta, at, ct;
1743 (void) pathname;
1745 /* TODO: this needs to be retested carefully (manually, if necessary) */
1746 at = get_stat_atime(stat_buf);
1747 ct = get_stat_ctime(stat_buf);
1748 delta.tv_sec = at.tv_sec - ct.tv_sec;
1749 delta.tv_nsec = at.tv_nsec - ct.tv_nsec;
1750 if (delta.tv_nsec < 0)
1752 delta.tv_nsec += 1000000000;
1753 delta.tv_sec -= 1;
1755 return pred_timewindow(delta, pred_ptr, DAYSECS);
1758 boolean
1759 pred_user (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1761 (void) pathname;
1762 if (pred_ptr->args.uid == stat_buf->st_uid)
1763 return (true);
1764 else
1765 return (false);
1768 boolean
1769 pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1771 struct stat sbuf; /* local copy, not stat_buf because we're using a different stat method */
1772 int (*ystat) (const char*, struct stat *p);
1774 /* If we would normally stat the link itself, stat the target instead.
1775 * If we would normally follow the link, stat the link itself instead.
1777 if (following_links())
1778 ystat = optionp_stat;
1779 else
1780 ystat = optionl_stat;
1782 set_stat_placeholders(&sbuf);
1783 if ((*ystat) (state.rel_pathname, &sbuf) != 0)
1785 if (following_links() && errno == ENOENT)
1787 /* If we failed to follow the symlink,
1788 * fall back on looking at the symlink itself.
1790 /* Mimic behavior of ls -lL. */
1791 return (pred_type (pathname, stat_buf, pred_ptr));
1793 else
1795 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
1796 state.exit_status = 1;
1798 return false;
1800 /* Now that we have our stat() information, query it in the same
1801 * way that -type does.
1803 return (pred_type (pathname, &sbuf, pred_ptr));
1806 /* 1) fork to get a child; parent remembers the child pid
1807 2) child execs the command requested
1808 3) parent waits for child; checks for proper pid of child
1810 Possible returns:
1812 ret errno status(h) status(l)
1814 pid x signal# 0177 stopped
1815 pid x exit arg 0 term by _exit
1816 pid x 0 signal # term by signal
1817 -1 EINTR parent got signal
1818 -1 other some other kind of error
1820 Return true only if the pid matches, status(l) is
1821 zero, and the exit arg (status high) is 0.
1822 Otherwise return false, possibly printing an error message. */
1825 static boolean
1826 prep_child_for_exec (boolean close_stdin, int dirfd)
1828 boolean ok = true;
1829 if (close_stdin)
1831 const char inputfile[] = "/dev/null";
1833 if (close(0) < 0)
1835 error(0, errno, _("Cannot close standard input"));
1836 ok = false;
1838 else
1840 if (open(inputfile, O_RDONLY
1841 #if defined O_LARGEFILE
1842 |O_LARGEFILE
1843 #endif
1844 ) < 0)
1846 /* This is not entirely fatal, since
1847 * executing the child with a closed
1848 * stdin is almost as good as executing it
1849 * with its stdin attached to /dev/null.
1851 error (0, errno, "%s", safely_quote_err_filename(0, inputfile));
1852 /* do not set ok=false, it is OK to continue anyway. */
1857 /* Even if DebugSearch is set, don't announce our change of
1858 * directory, since we're not going to emit a subsequent
1859 * announcement of a call to stat() anyway, as we're about to exec
1860 * something.
1862 if (dirfd != AT_FDCWD)
1864 assert (dirfd >= 0);
1865 if (0 != fchdir(dirfd))
1867 /* If we cannot execute our command in the correct directory,
1868 * we should not execute it at all.
1870 error(0, errno, _("Failed to change directory"));
1871 ok = false;
1874 return ok;
1880 launch (const struct buildcmd_control *ctl,
1881 struct buildcmd_state *buildstate)
1883 int wait_status;
1884 pid_t child_pid;
1885 static int first_time = 1;
1886 const struct exec_val *execp = buildstate->usercontext;
1888 if (!execp->use_current_dir)
1890 assert (starting_desc >= 0);
1891 assert (execp->dirfd == starting_desc);
1895 /* Null terminate the arg list. */
1896 bc_push_arg (ctl, buildstate, (char *) NULL, 0, NULL, 0, false);
1898 /* Make sure output of command doesn't get mixed with find output. */
1899 fflush (stdout);
1900 fflush (stderr);
1902 /* Make sure to listen for the kids. */
1903 if (first_time)
1905 first_time = 0;
1906 signal (SIGCHLD, SIG_DFL);
1909 child_pid = fork ();
1910 if (child_pid == -1)
1911 error (1, errno, _("cannot fork"));
1912 if (child_pid == 0)
1914 /* We are the child. */
1915 assert (starting_desc >= 0);
1916 if (!prep_child_for_exec(execp->close_stdin, execp->dirfd))
1918 _exit(1);
1921 execvp (buildstate->cmd_argv[0], buildstate->cmd_argv);
1922 error (0, errno, "%s",
1923 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1924 _exit (1);
1928 /* In parent; set up for next time. */
1929 bc_clear_args(ctl, buildstate);
1932 while (waitpid (child_pid, &wait_status, 0) == (pid_t) -1)
1934 if (errno != EINTR)
1936 error (0, errno, _("error waiting for %s"),
1937 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1938 state.exit_status = 1;
1939 return 0; /* FAIL */
1943 if (WIFSIGNALED (wait_status))
1945 error (0, 0, _("%s terminated by signal %d"),
1946 quotearg_n_style(0, options.err_quoting_style,
1947 buildstate->cmd_argv[0]),
1948 WTERMSIG (wait_status));
1950 if (execp->multiple)
1952 /* -exec \; just returns false if the invoked command fails.
1953 * -exec {} + returns true if the invoked command fails, but
1954 * sets the program exit status.
1956 state.exit_status = 1;
1959 return 1; /* OK */
1962 if (0 == WEXITSTATUS (wait_status))
1964 return 1; /* OK */
1966 else
1968 if (execp->multiple)
1970 /* -exec \; just returns false if the invoked command fails.
1971 * -exec {} + returns true if the invoked command fails, but
1972 * sets the program exit status.
1974 state.exit_status = 1;
1976 return 0; /* FAIL */
1982 /* Return a static string formatting the time WHEN according to the
1983 * strftime format character KIND.
1985 * This function contains a number of assertions. These look like
1986 * runtime checks of the results of computations, which would be a
1987 * problem since external events should not be tested for with
1988 * "assert" (instead you should use "if"). However, they are not
1989 * really runtime checks. The assertions actually exist to verify
1990 * that the various buffers are correctly sized.
1992 static char *
1993 format_date (struct timespec ts, int kind)
1995 /* In theory, we use an extra 10 characters for 9 digits of
1996 * nanoseconds and 1 for the decimal point. However, the real
1997 * world is more complex than that.
1999 * For example, some systems return junk in the tv_nsec part of
2000 * st_birthtime. An example of this is the NetBSD-4.0-RELENG kernel
2001 * (at Sat Mar 24 18:46:46 2007) running a NetBSD-3.1-RELEASE
2002 * runtime and examining files on an msdos filesytem. So for that
2003 * reason we set NS_BUF_LEN to 32, which is simply "long enough" as
2004 * opposed to "exactly the right size". Note that the behaviour of
2005 * NetBSD appears to be a result of the use of uninitialised data,
2006 * as it's not 100% reproducible (more like 25%).
2008 enum {
2009 NS_BUF_LEN = 32,
2010 DATE_LEN_PERCENT_APLUS=21 /* length of result of %A+ (it's longer than %c)*/
2012 static char buf[128u+10u + MAX(DATE_LEN_PERCENT_APLUS,
2013 MAX (LONGEST_HUMAN_READABLE + 2, NS_BUF_LEN+64+200))];
2014 char ns_buf[NS_BUF_LEN]; /* -.9999999990 (- sign can happen!)*/
2015 int charsprinted, need_ns_suffix;
2016 struct tm *tm;
2017 char fmt[6];
2019 /* human_readable() assumes we pass a buffer which is at least as
2020 * long as LONGEST_HUMAN_READABLE. We use an assertion here to
2021 * ensure that no nasty unsigned overflow happend in our calculation
2022 * of the size of buf. Do the assertion here rather than in the
2023 * code for %@ so that we find the problem quickly if it exists. If
2024 * you want to submit a patch to move this into the if statement, go
2025 * ahead, I'll apply it. But include performance timings
2026 * demonstrating that the performance difference is actually
2027 * measurable.
2029 verify (sizeof(buf) >= LONGEST_HUMAN_READABLE);
2031 charsprinted = 0;
2032 need_ns_suffix = 0;
2034 /* Format the main part of the time. */
2035 if (kind == '+')
2037 strcpy (fmt, "%F+%T");
2038 need_ns_suffix = 1;
2040 else
2042 fmt[0] = '%';
2043 fmt[1] = kind;
2044 fmt[2] = '\0';
2046 /* %a, %c, and %t are handled in ctime_format() */
2047 switch (kind)
2049 case 'S':
2050 case 'T':
2051 case 'X':
2052 case '@':
2053 need_ns_suffix = 1;
2054 break;
2055 default:
2056 need_ns_suffix = 0;
2057 break;
2061 if (need_ns_suffix)
2063 /* Format the nanoseconds part. Leave a trailing zero to
2064 * discourage people from writing scripts which extract the
2065 * fractional part of the timestamp by using column offsets.
2066 * The reason for discouraging this is that in the future, the
2067 * granularity may not be nanoseconds.
2069 ns_buf[0] = 0;
2070 charsprinted = snprintf(ns_buf, NS_BUF_LEN, ".%09ld0", (long int)ts.tv_nsec);
2071 assert (charsprinted < NS_BUF_LEN);
2074 if (kind != '@'
2075 && (tm = localtime (&ts.tv_sec))
2076 && strftime (buf, sizeof buf, fmt, tm))
2078 /* For %AS, %CS, %TS, add the fractional part of the seconds
2079 * information.
2081 if (need_ns_suffix)
2083 assert ((sizeof buf - strlen(buf)) > strlen(ns_buf));
2084 strcat(buf, ns_buf);
2086 return buf;
2088 else
2090 uintmax_t w = ts.tv_sec;
2091 size_t used, len, remaining;
2093 /* XXX: note that we are negating an unsigned type which is the
2094 * widest possible unsigned type.
2096 char *p = human_readable (ts.tv_sec < 0 ? -w : w, buf + 1,
2097 human_ceiling, 1, 1);
2098 assert (p > buf);
2099 assert (p < (buf + (sizeof buf)));
2100 if (ts.tv_sec < 0)
2101 *--p = '-'; /* XXX: Ugh, relying on internal details of human_readable(). */
2103 /* Add the nanoseconds part. Because we cannot enforce a
2104 * particlar implementation of human_readable, we cannot assume
2105 * any particular value for (p-buf). So we need to be careful
2106 * that there is enough space remaining in the buffer.
2108 if (need_ns_suffix)
2110 len = strlen(p);
2111 used = (p-buf) + len; /* Offset into buf of current end */
2112 assert (sizeof buf > used); /* Ensure we can perform subtraction safely. */
2113 remaining = sizeof buf - used - 1u; /* allow space for NUL */
2115 if (strlen(ns_buf) >= remaining)
2117 error(0, 0,
2118 "charsprinted=%ld but remaining=%lu: ns_buf=%s",
2119 (long)charsprinted, (unsigned long)remaining, ns_buf);
2121 assert (strlen(ns_buf) < remaining);
2122 strcat(p, ns_buf);
2124 return p;
2128 static const char *weekdays[] =
2130 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
2132 static char * months[] =
2134 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2135 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2139 static char *
2140 ctime_format (struct timespec ts)
2142 const struct tm * ptm;
2143 #define TIME_BUF_LEN 1024u
2144 static char resultbuf[TIME_BUF_LEN];
2145 int nout;
2147 ptm = localtime(&ts.tv_sec);
2148 if (ptm)
2150 assert (ptm->tm_wday >= 0);
2151 assert (ptm->tm_wday < 7);
2152 assert (ptm->tm_mon >= 0);
2153 assert (ptm->tm_mon < 12);
2154 assert (ptm->tm_hour >= 0);
2155 assert (ptm->tm_hour < 24);
2156 assert (ptm->tm_min < 60);
2157 assert (ptm->tm_sec <= 61); /* allows 2 leap seconds. */
2159 /* wkday mon mday hh:mm:ss.nnnnnnnnn yyyy */
2160 nout = snprintf(resultbuf, TIME_BUF_LEN,
2161 "%3s %3s %2d %02d:%02d:%02d.%010ld %04d",
2162 weekdays[ptm->tm_wday],
2163 months[ptm->tm_mon],
2164 ptm->tm_mday,
2165 ptm->tm_hour,
2166 ptm->tm_min,
2167 ptm->tm_sec,
2168 (long int)ts.tv_nsec,
2169 1900 + ptm->tm_year);
2171 assert (nout < TIME_BUF_LEN);
2172 return resultbuf;
2174 else
2176 /* The time cannot be represented as a struct tm.
2177 Output it as an integer. */
2178 return format_date (ts, '@');
2182 /* Copy STR into BUF and trim blanks from the end of BUF.
2183 Return BUF. */
2185 static char *
2186 blank_rtrim (str, buf)
2187 char *str;
2188 char *buf;
2190 int i;
2192 if (str == NULL)
2193 return (NULL);
2194 strcpy (buf, str);
2195 i = strlen (buf) - 1;
2196 while ((i >= 0) && ((buf[i] == ' ') || buf[i] == '\t'))
2197 i--;
2198 buf[++i] = '\0';
2199 return (buf);
2202 /* Print out the predicate list starting at NODE. */
2203 void
2204 print_list (FILE *fp, struct predicate *node)
2206 struct predicate *cur;
2207 char name[256];
2209 cur = node;
2210 while (cur != NULL)
2212 fprintf (fp, "[%s] ", blank_rtrim (cur->p_name, name));
2213 cur = cur->pred_next;
2215 fprintf (fp, "\n");
2218 /* Print out the predicate list starting at NODE. */
2219 static void
2220 print_parenthesised(FILE *fp, struct predicate *node)
2222 int parens = 0;
2224 if (node)
2226 if ((pred_is(node, pred_or) || pred_is(node, pred_and))
2227 && node->pred_left == NULL)
2229 /* We print "<nothing> or X" as just "X"
2230 * We print "<nothing> and X" as just "X"
2232 print_parenthesised(fp, node->pred_right);
2234 else
2236 if (node->pred_left || node->pred_right)
2237 parens = 1;
2239 if (parens)
2240 fprintf(fp, "%s", " ( ");
2241 print_optlist(fp, node);
2242 if (parens)
2243 fprintf(fp, "%s", " ) ");
2248 void
2249 print_optlist (FILE *fp, const struct predicate *p)
2251 if (p)
2253 print_parenthesised(fp, p->pred_left);
2254 fprintf (fp,
2255 "%s%s",
2256 p->need_stat ? "[call stat] " : "",
2257 p->need_type ? "[need type] " : "");
2258 print_predicate(fp, p);
2259 fprintf(fp, " [%g] ", p->est_success_rate);
2260 if (options.debug_options & DebugSuccessRates)
2262 fprintf(fp, "[%ld/%ld", p->perf.successes, p->perf.visits);
2263 if (p->perf.visits)
2265 double real_rate = (double)p->perf.successes / (double)p->perf.visits;
2266 fprintf(fp, "=%g] ", real_rate);
2268 else
2270 fprintf(fp, "=_] ");
2273 print_parenthesised(fp, p->pred_right);
2277 void show_success_rates(const struct predicate *p)
2279 if (options.debug_options & DebugSuccessRates)
2281 fprintf(stderr, "Predicate success rates after completion:\n");
2282 print_optlist(stderr, p);
2283 fprintf(stderr, "\n");
2290 #ifdef _NDEBUG
2291 /* If _NDEBUG is defined, the assertions will do nothing. Hence
2292 * there is no point in having a function body for pred_sanity_check()
2293 * if that preprocessor macro is defined.
2295 void
2296 pred_sanity_check(const struct predicate *predicates)
2298 /* Do nothing, since assert is a no-op with _NDEBUG set */
2299 return;
2301 #else
2302 void
2303 pred_sanity_check(const struct predicate *predicates)
2305 const struct predicate *p;
2307 for (p=predicates; p != NULL; p=p->pred_next)
2309 /* All predicates must do something. */
2310 assert (p->pred_func != NULL);
2312 /* All predicates must have a parser table entry. */
2313 assert (p->parser_entry != NULL);
2315 /* If the parser table tells us that just one predicate function is
2316 * possible, verify that that is still the one that is in effect.
2317 * If the parser has NULL for the predicate function, that means that
2318 * the parse_xxx function fills it in, so we can't check it.
2320 if (p->parser_entry->pred_func)
2322 assert (p->parser_entry->pred_func == p->pred_func);
2325 switch (p->parser_entry->type)
2327 /* Options all take effect during parsing, so there should
2328 * be no predicate entries corresponding to them. Hence we
2329 * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION
2330 * items.
2332 * This is a silly way of coding this test, but it prevents
2333 * a compiler warning (i.e. otherwise it would think that
2334 * there would be case statements missing).
2336 case ARG_OPTION:
2337 case ARG_POSITIONAL_OPTION:
2338 assert (p->parser_entry->type != ARG_OPTION);
2339 assert (p->parser_entry->type != ARG_POSITIONAL_OPTION);
2340 break;
2342 case ARG_ACTION:
2343 assert(p->side_effects); /* actions have side effects. */
2344 if (!pred_is(p, pred_prune) && !pred_is(p, pred_quit))
2346 /* actions other than -prune and -quit should
2347 * inhibit the default -print
2349 assert (p->no_default_print);
2351 break;
2353 /* We happen to know that the only user of ARG_SPECIAL_PARSE
2354 * is a test, so handle it like ARG_TEST.
2356 case ARG_SPECIAL_PARSE:
2357 case ARG_TEST:
2358 case ARG_PUNCTUATION:
2359 case ARG_NOOP:
2360 /* Punctuation and tests should have no side
2361 * effects and not inhibit default print.
2363 assert (!p->no_default_print);
2364 assert (!p->side_effects);
2365 break;
2369 #endif