Do not use __attribute__((__noreturn__)) if it produces a compilation error
[findutils.git] / find / pred.c
blobcfe129b74c8e32f850d6a17f4a2ed7aa0bad6480
1 /* pred.c -- execute the expression tree.
2 Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2003,
3 2004, 2005 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 2, or (at your option)
8 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, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
18 USA.
21 #include "defs.h"
23 #include <fnmatch.h>
24 #include <signal.h>
25 #include <math.h>
26 #include <pwd.h>
27 #include <grp.h>
28 #include <sys/types.h>
29 #include <sys/stat.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"
49 #if ENABLE_NLS
50 # include <libintl.h>
51 # define _(Text) gettext (Text)
52 #else
53 # define _(Text) Text
54 #endif
55 #ifdef gettext_noop
56 # define N_(String) gettext_noop (String)
57 #else
58 /* See locate.c for explanation as to why not use (String) */
59 # define N_(String) String
60 #endif
62 #if !defined(SIGCHLD) && defined(SIGCLD)
63 #define SIGCHLD SIGCLD
64 #endif
68 #if HAVE_DIRENT_H
69 # include <dirent.h>
70 # define NAMLEN(dirent) strlen((dirent)->d_name)
71 #else
72 # define dirent direct
73 # define NAMLEN(dirent) (dirent)->d_namlen
74 # if HAVE_SYS_NDIR_H
75 # include <sys/ndir.h>
76 # endif
77 # if HAVE_SYS_DIR_H
78 # include <sys/dir.h>
79 # endif
80 # if HAVE_NDIR_H
81 # include <ndir.h>
82 # endif
83 #endif
85 #ifdef CLOSEDIR_VOID
86 /* Fake a return value. */
87 #define CLOSEDIR(d) (closedir (d), 0)
88 #else
89 #define CLOSEDIR(d) closedir (d)
90 #endif
95 /* Get or fake the disk device blocksize.
96 Usually defined by sys/param.h (if at all). */
97 #ifndef DEV_BSIZE
98 # ifdef BSIZE
99 # define DEV_BSIZE BSIZE
100 # else /* !BSIZE */
101 # define DEV_BSIZE 4096
102 # endif /* !BSIZE */
103 #endif /* !DEV_BSIZE */
105 /* Extract or fake data from a `struct stat'.
106 ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
107 ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
108 ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS. */
109 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
110 # define ST_BLKSIZE(statbuf) DEV_BSIZE
111 # if defined(_POSIX_SOURCE) || !defined(BSIZE) /* fileblocks.c uses BSIZE. */
112 # define ST_NBLOCKS(statbuf) \
113 (S_ISREG ((statbuf).st_mode) \
114 || S_ISDIR ((statbuf).st_mode) \
115 ? (statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0) : 0)
116 # else /* !_POSIX_SOURCE && BSIZE */
117 # define ST_NBLOCKS(statbuf) \
118 (S_ISREG ((statbuf).st_mode) \
119 || S_ISDIR ((statbuf).st_mode) \
120 ? st_blocks ((statbuf).st_size) : 0)
121 # endif /* !_POSIX_SOURCE && BSIZE */
122 #else /* HAVE_STRUCT_STAT_ST_BLOCKS */
123 /* Some systems, like Sequents, return st_blksize of 0 on pipes. */
124 # define ST_BLKSIZE(statbuf) ((statbuf).st_blksize > 0 \
125 ? (statbuf).st_blksize : DEV_BSIZE)
126 # if defined(hpux) || defined(__hpux__) || defined(__hpux)
127 /* HP-UX counts st_blocks in 1024-byte units.
128 This loses when mixing HP-UX and BSD filesystems with NFS. */
129 # define ST_NBLOCKSIZE 1024
130 # else /* !hpux */
131 # if defined(_AIX) && defined(_I386)
132 /* AIX PS/2 counts st_blocks in 4K units. */
133 # define ST_NBLOCKSIZE (4 * 1024)
134 # else /* not AIX PS/2 */
135 # if defined(_CRAY)
136 # define ST_NBLOCKS(statbuf) \
137 (S_ISREG ((statbuf).st_mode) \
138 || S_ISDIR ((statbuf).st_mode) \
139 ? (statbuf).st_blocks * ST_BLKSIZE(statbuf)/ST_NBLOCKSIZE : 0)
140 # endif /* _CRAY */
141 # endif /* not AIX PS/2 */
142 # endif /* !hpux */
143 #endif /* HAVE_STRUCT_STAT_ST_BLOCKS */
145 #ifndef ST_NBLOCKS
146 # define ST_NBLOCKS(statbuf) \
147 (S_ISREG ((statbuf).st_mode) \
148 || S_ISDIR ((statbuf).st_mode) \
149 ? (statbuf).st_blocks : 0)
150 #endif
152 #ifndef ST_NBLOCKSIZE
153 # define ST_NBLOCKSIZE 512
154 #endif
157 #undef MAX
158 #define MAX(a, b) ((a) > (b) ? (a) : (b))
160 static boolean match_lname PARAMS((const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case));
162 static char *format_date PARAMS((struct timespec ts, int kind));
163 static char *ctime_format PARAMS((struct timespec ts));
165 #ifdef DEBUG
166 struct pred_assoc
168 PRED_FUNC pred_func;
169 char *pred_name;
172 struct pred_assoc pred_table[] =
174 {pred_amin, "amin "},
175 {pred_and, "and "},
176 {pred_anewer, "anewer "},
177 {pred_atime, "atime "},
178 {pred_closeparen, ") "},
179 {pred_cmin, "cmin "},
180 {pred_cnewer, "cnewer "},
181 {pred_comma, ", "},
182 {pred_ctime, "ctime "},
183 {pred_delete, "delete "},
184 {pred_empty, "empty "},
185 {pred_exec, "exec "},
186 {pred_execdir, "execdir "},
187 {pred_executable, "executable "},
188 {pred_false, "false "},
189 {pred_fprint, "fprint "},
190 {pred_fprint0, "fprint0 "},
191 {pred_fprintf, "fprintf "},
192 {pred_fstype, "fstype "},
193 {pred_gid, "gid "},
194 {pred_group, "group "},
195 {pred_ilname, "ilname "},
196 {pred_iname, "iname "},
197 {pred_inum, "inum "},
198 {pred_ipath, "ipath "},
199 {pred_links, "links "},
200 {pred_lname, "lname "},
201 {pred_ls, "ls "},
202 {pred_mmin, "mmin "},
203 {pred_mtime, "mtime "},
204 {pred_name, "name "},
205 {pred_negate, "not "},
206 {pred_newer, "newer "},
207 {pred_newerXY, "newerXY "},
208 {pred_nogroup, "nogroup "},
209 {pred_nouser, "nouser "},
210 {pred_ok, "ok "},
211 {pred_okdir, "okdir "},
212 {pred_openparen, "( "},
213 {pred_or, "or "},
214 {pred_path, "path "},
215 {pred_perm, "perm "},
216 {pred_print, "print "},
217 {pred_print0, "print0 "},
218 {pred_prune, "prune "},
219 {pred_quit, "quit "},
220 {pred_readable, "readable "},
221 {pred_regex, "regex "},
222 {pred_samefile,"samefile "},
223 {pred_size, "size "},
224 {pred_true, "true "},
225 {pred_type, "type "},
226 {pred_uid, "uid "},
227 {pred_used, "used "},
228 {pred_user, "user "},
229 {pred_writable, "writable "},
230 {pred_xtype, "xtype "},
231 {0, "none "}
233 #endif
235 /* Returns ts1 - ts2 */
236 static double ts_difference(struct timespec ts1,
237 struct timespec ts2)
239 double d = difftime(ts1.tv_sec, ts2.tv_sec)
240 + (1.0e-9 * (ts1.tv_nsec - ts2.tv_nsec));
241 return d;
245 static int
246 compare_ts(struct timespec ts1,
247 struct timespec ts2)
249 if ((ts1.tv_sec == ts2.tv_sec) &&
250 (ts1.tv_nsec == ts2.tv_nsec))
252 return 0;
254 else
256 double diff = ts_difference(ts1, ts2);
257 return diff < 0.0 ? -1 : +1;
261 /* Predicate processing routines.
263 PATHNAME is the full pathname of the file being checked.
264 *STAT_BUF contains information about PATHNAME.
265 *PRED_PTR contains information for applying the predicate.
267 Return true if the file passes this predicate, false if not. */
270 /* pred_timewindow
272 * Returns true if THE_TIME is
273 * COMP_GT: after the specified time
274 * COMP_LT: before the specified time
275 * COMP_EQ: less than WINDOW seconds after the specified time.
277 static boolean
278 pred_timewindow(struct timespec ts, struct predicate const *pred_ptr, int window)
280 switch (pred_ptr->args.reftime.kind)
282 case COMP_GT:
283 return compare_ts(ts, pred_ptr->args.reftime.ts) > 0;
285 case COMP_LT:
286 return compare_ts(ts, pred_ptr->args.reftime.ts) < 0;
288 case COMP_EQ:
290 double delta = ts_difference(ts, pred_ptr->args.reftime.ts);
291 return (delta >= 0.0 && delta < window);
297 boolean
298 pred_amin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
300 (void) &pathname;
301 return pred_timewindow(get_stat_atime(stat_buf), pred_ptr, 60);
304 boolean
305 pred_and (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
307 if (pred_ptr->pred_left == NULL
308 || apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
310 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
312 else
313 return false;
316 boolean
317 pred_anewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
319 (void) &pathname;
320 assert(COMP_GT == pred_ptr->args.reftime.kind);
321 return compare_ts(get_stat_atime(stat_buf), pred_ptr->args.reftime.ts) > 0;
324 boolean
325 pred_atime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
327 (void) &pathname;
328 return pred_timewindow(get_stat_atime(stat_buf), pred_ptr, DAYSECS);
331 boolean
332 pred_closeparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
334 (void) &pathname;
335 (void) &stat_buf;
336 (void) &pred_ptr;
338 return true;
341 boolean
342 pred_cmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
344 (void) pathname;
345 return pred_timewindow(get_stat_ctime(stat_buf), pred_ptr, 60);
348 boolean
349 pred_cnewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
351 (void) pathname;
353 assert(COMP_GT == pred_ptr->args.reftime.kind);
354 return compare_ts(get_stat_ctime(stat_buf), pred_ptr->args.reftime.ts) > 0;
357 boolean
358 pred_comma (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
360 if (pred_ptr->pred_left != NULL)
362 apply_predicate(pathname, stat_buf,pred_ptr->pred_left);
364 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
367 boolean
368 pred_ctime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
370 (void) &pathname;
371 return pred_timewindow(get_stat_ctime(stat_buf), pred_ptr, DAYSECS);
374 static boolean
375 perform_delete(int flags)
377 return 0 == unlinkat(state.cwd_dir_fd, state.rel_pathname, flags);
381 boolean
382 pred_delete (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
384 (void) pred_ptr;
385 (void) stat_buf;
386 if (strcmp (state.rel_pathname, "."))
388 int flags=0;
389 if (state.have_stat && S_ISDIR(stat_buf->st_mode))
390 flags |= AT_REMOVEDIR;
391 if (perform_delete(flags))
393 return true;
395 else
397 if (EISDIR == errno)
399 if ((flags & AT_REMOVEDIR) == 0)
401 /* unlink() operation failed because we should have done rmdir(). */
402 flags |= AT_REMOVEDIR;
403 if (perform_delete(flags))
404 return true;
408 error (0, errno, "cannot delete %s",
409 safely_quote_err_filename(0, pathname));
410 return false;
412 else
414 /* nothing to do. */
415 return true;
419 boolean
420 pred_empty (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
422 (void) pathname;
423 (void) pred_ptr;
425 if (S_ISDIR (stat_buf->st_mode))
427 int fd;
428 DIR *d;
429 struct dirent *dp;
430 boolean empty = true;
432 errno = 0;
433 if ((fd = openat(state.cwd_dir_fd, state.rel_pathname, O_RDONLY
434 #if defined O_LARGEFILE
435 |O_LARGEFILE
436 #endif
437 )) < 0)
439 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
440 state.exit_status = 1;
441 return false;
443 d = fdopendir (fd);
444 if (d == NULL)
446 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
447 state.exit_status = 1;
448 return false;
450 for (dp = readdir (d); dp; dp = readdir (d))
452 if (dp->d_name[0] != '.'
453 || (dp->d_name[1] != '\0'
454 && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
456 empty = false;
457 break;
460 if (CLOSEDIR (d))
462 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
463 state.exit_status = 1;
464 return false;
466 return (empty);
468 else if (S_ISREG (stat_buf->st_mode))
469 return (stat_buf->st_size == 0);
470 else
471 return (false);
474 static boolean
475 new_impl_pred_exec (int dirfd, const char *pathname,
476 struct stat *stat_buf,
477 struct predicate *pred_ptr,
478 const char *prefix, size_t pfxlen)
480 struct exec_val *execp = &pred_ptr->args.exec_vec;
481 size_t len = strlen(pathname);
483 (void) stat_buf;
484 execp->dirfd = dirfd;
485 if (execp->multiple)
487 /* Push the argument onto the current list.
488 * The command may or may not be run at this point,
489 * depending on the command line length limits.
491 bc_push_arg(&execp->ctl,
492 &execp->state,
493 pathname, len+1,
494 prefix, pfxlen,
497 /* remember that there are pending execdirs. */
498 state.execdirs_outstanding = true;
500 /* POSIX: If the primary expression is punctuated by a plus
501 * sign, the primary shall always evaluate as true
503 return true;
505 else
507 int i;
509 for (i=0; i<execp->num_args; ++i)
511 bc_do_insert(&execp->ctl,
512 &execp->state,
513 execp->replace_vec[i],
514 strlen(execp->replace_vec[i]),
515 prefix, pfxlen,
516 pathname, len,
520 /* Actually invoke the command. */
521 return execp->ctl.exec_callback(&execp->ctl,
522 &execp->state);
527 boolean
528 pred_exec (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
530 return new_impl_pred_exec(get_start_dirfd(),
531 pathname, stat_buf, pred_ptr, NULL, 0);
534 boolean
535 pred_execdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
537 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
538 (void) &pathname;
539 return new_impl_pred_exec (get_current_dirfd(),
540 state.rel_pathname, stat_buf, pred_ptr,
541 prefix, (prefix ? 2 : 0));
544 boolean
545 pred_false (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
547 (void) &pathname;
548 (void) &stat_buf;
549 (void) &pred_ptr;
552 return (false);
555 boolean
556 pred_fls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
558 FILE * stream = pred_ptr->args.printf_vec.stream;
559 list_file (pathname, state.cwd_dir_fd, state.rel_pathname, stat_buf,
560 options.start_time.tv_sec,
561 options.output_block_size,
562 pred_ptr->literal_control_chars, stream);
563 return true;
566 boolean
567 pred_fprint (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
569 (void) &pathname;
570 (void) &stat_buf;
572 print_quoted(pred_ptr->args.printf_vec.stream,
573 pred_ptr->args.printf_vec.quote_opts,
574 pred_ptr->args.printf_vec.dest_is_tty,
575 "%s\n",
576 pathname);
577 return true;
580 boolean
581 pred_fprint0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
583 FILE * fp = pred_ptr->args.printf_vec.stream;
585 (void) &stat_buf;
587 fputs (pathname, fp);
588 putc (0, fp);
589 return true;
594 static char*
595 mode_to_filetype(mode_t m)
597 return
598 m == S_IFSOCK ? "s" :
599 m == S_IFLNK ? "l" :
600 m == S_IFREG ? "f" :
601 m == S_IFBLK ? "b" :
602 m == S_IFDIR ? "d" :
603 m == S_IFCHR ? "c" :
604 #ifdef S_IFDOOR
605 m == S_IFDOOR ? "D" :
606 #endif
607 m == S_IFIFO ? "p" : "U";
610 static double
611 file_sparseness(const struct stat *p)
613 if (0 == p->st_size)
615 if (0 == p->st_blocks)
616 return 1.0;
617 else
618 return p->st_blocks < 0 ? -HUGE_VAL : HUGE_VAL;
620 else
622 double blklen = file_blocksize(p) * (double)p->st_blocks;
623 return blklen / p->st_size;
629 static void
630 checked_fprintf(struct format_val *dest, const char *fmt, ...)
632 int rv;
633 va_list ap;
635 va_start(ap, fmt);
636 rv = vfprintf(dest->stream, fmt, ap);
637 if (rv < 0)
638 nonfatal_file_error(dest->filename);
642 static void
643 checked_print_quoted (struct format_val *dest,
644 const char *format, const char *s)
646 int rv = print_quoted(dest->stream, dest->quote_opts, dest->dest_is_tty,
647 format, s);
648 if (rv < 0)
649 nonfatal_file_error(dest->filename);
653 static void
654 checked_fwrite(void *p, size_t siz, size_t nmemb, struct format_val *dest)
656 int items_written = fwrite(p, siz, nmemb, dest->stream);
657 if (items_written < nmemb)
658 nonfatal_file_error(dest->filename);
661 static void
662 checked_fflush(struct format_val *dest)
664 if (0 != fflush(dest->stream))
666 nonfatal_file_error(dest->filename);
670 static void
671 do_fprintf(struct format_val *dest,
672 struct segment *segment,
673 const char *pathname,
674 const struct stat *stat_buf)
676 char hbuf[LONGEST_HUMAN_READABLE + 1];
677 const char *cp;
679 switch (segment->segkind)
681 case KIND_PLAIN: /* Plain text string (no % conversion). */
682 /* trusted */
683 checked_fwrite(segment->text, 1, segment->text_len, dest);
684 break;
686 case KIND_STOP: /* Terminate argument and flush output. */
687 /* trusted */
688 checked_fwrite(segment->text, 1, segment->text_len, dest);
689 checked_fflush(dest);
690 break;
692 case KIND_FORMAT:
693 switch (segment->format_char[0])
695 case 'a': /* atime in `ctime' format. */
696 /* UNTRUSTED, probably unexploitable */
697 checked_fprintf (dest, segment->text, ctime_format (get_stat_atime(stat_buf)));
698 break;
699 case 'b': /* size in 512-byte blocks */
700 /* UNTRUSTED, probably unexploitable */
701 checked_fprintf (dest, segment->text,
702 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
703 hbuf, human_ceiling,
704 ST_NBLOCKSIZE, 512));
705 break;
706 case 'c': /* ctime in `ctime' format */
707 /* UNTRUSTED, probably unexploitable */
708 checked_fprintf (dest, segment->text, ctime_format (get_stat_ctime(stat_buf)));
709 break;
710 case 'd': /* depth in search tree */
711 /* UNTRUSTED, probably unexploitable */
712 checked_fprintf (dest, segment->text, state.curdepth);
713 break;
714 case 'D': /* Device on which file exists (stat.st_dev) */
715 /* trusted */
716 checked_fprintf (dest, segment->text,
717 human_readable ((uintmax_t) stat_buf->st_dev, hbuf,
718 human_ceiling, 1, 1));
719 break;
720 case 'f': /* base name of path */
721 /* sanitised */
722 checked_print_quoted (dest, segment->text, base_name (pathname));
723 break;
724 case 'F': /* filesystem type */
725 /* trusted */
726 checked_print_quoted (dest, segment->text, filesystem_type (stat_buf, pathname));
727 break;
728 case 'g': /* group name */
729 /* trusted */
730 /* (well, the actual group is selected by the user but
731 * its name was selected by the system administrator)
734 struct group *g;
736 g = getgrgid (stat_buf->st_gid);
737 if (g)
739 segment->text[segment->text_len] = 's';
740 checked_fprintf (dest, segment->text, g->gr_name);
741 break;
743 else
745 /* Do nothing. */
746 /*FALLTHROUGH*/
749 /*FALLTHROUGH*/ /*...sometimes, so 'G' case.*/
751 case 'G': /* GID number */
752 /* UNTRUSTED, probably unexploitable */
753 checked_fprintf (dest, segment->text,
754 human_readable ((uintmax_t) stat_buf->st_gid, hbuf,
755 human_ceiling, 1, 1));
756 break;
757 case 'h': /* leading directories part of path */
758 /* sanitised */
760 cp = strrchr (pathname, '/');
761 if (cp == NULL) /* No leading directories. */
763 /* If there is no slash in the pathname, we still
764 * print the string because it contains characters
765 * other than just '%s'. The %h expands to ".".
767 checked_print_quoted (dest, segment->text, ".");
769 else
771 char *s = strdup(pathname);
772 s[cp - pathname] = 0;
773 checked_print_quoted (dest, segment->text, s);
774 free(s);
777 break;
779 case 'H': /* ARGV element file was found under */
780 /* trusted */
782 char *s = xmalloc(state.starting_path_length+1);
783 memcpy(s, pathname, state.starting_path_length);
784 s[state.starting_path_length] = 0;
785 checked_fprintf (dest, segment->text, s);
786 free(s);
788 break;
790 case 'i': /* inode number */
791 /* UNTRUSTED, but not exploitable I think */
792 checked_fprintf (dest, segment->text,
793 human_readable ((uintmax_t) stat_buf->st_ino, hbuf,
794 human_ceiling,
795 1, 1));
796 break;
797 case 'k': /* size in 1K blocks */
798 /* UNTRUSTED, but not exploitable I think */
799 checked_fprintf (dest, segment->text,
800 human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
801 hbuf, human_ceiling,
802 ST_NBLOCKSIZE, 1024));
803 break;
804 case 'l': /* object of symlink */
805 /* sanitised */
806 #ifdef S_ISLNK
808 char *linkname = 0;
810 if (S_ISLNK (stat_buf->st_mode))
812 linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
813 if (linkname == 0)
814 state.exit_status = 1;
816 if (linkname)
818 checked_print_quoted (dest, segment->text, linkname);
819 free (linkname);
821 else
823 /* We still need to honour the field width etc., so this is
824 * not a no-op.
826 checked_print_quoted (dest, segment->text, "");
829 #endif /* S_ISLNK */
830 break;
832 case 'M': /* mode as 10 chars (eg., "-rwxr-x--x" */
833 /* UNTRUSTED, probably unexploitable */
835 char modestring[16] ;
836 filemodestring (stat_buf, modestring);
837 modestring[10] = '\0';
838 checked_fprintf (dest, segment->text, modestring);
840 break;
842 case 'm': /* mode as octal number (perms only) */
843 /* UNTRUSTED, probably unexploitable */
845 /* Output the mode portably using the traditional numbers,
846 even if the host unwisely uses some other numbering
847 scheme. But help the compiler in the common case where
848 the host uses the traditional numbering scheme. */
849 mode_t m = stat_buf->st_mode;
850 boolean traditional_numbering_scheme =
851 (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000
852 && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100
853 && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010
854 && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001);
855 checked_fprintf (dest, segment->text,
856 (traditional_numbering_scheme
857 ? m & MODE_ALL
858 : ((m & S_ISUID ? 04000 : 0)
859 | (m & S_ISGID ? 02000 : 0)
860 | (m & S_ISVTX ? 01000 : 0)
861 | (m & S_IRUSR ? 00400 : 0)
862 | (m & S_IWUSR ? 00200 : 0)
863 | (m & S_IXUSR ? 00100 : 0)
864 | (m & S_IRGRP ? 00040 : 0)
865 | (m & S_IWGRP ? 00020 : 0)
866 | (m & S_IXGRP ? 00010 : 0)
867 | (m & S_IROTH ? 00004 : 0)
868 | (m & S_IWOTH ? 00002 : 0)
869 | (m & S_IXOTH ? 00001 : 0))));
871 break;
873 case 'n': /* number of links */
874 /* UNTRUSTED, probably unexploitable */
875 checked_fprintf (dest, segment->text,
876 human_readable ((uintmax_t) stat_buf->st_nlink,
877 hbuf,
878 human_ceiling,
879 1, 1));
880 break;
882 case 'p': /* pathname */
883 /* sanitised */
884 checked_print_quoted (dest, segment->text, pathname);
885 break;
887 case 'P': /* pathname with ARGV element stripped */
888 /* sanitised */
889 if (state.curdepth > 0)
891 cp = pathname + state.starting_path_length;
892 if (*cp == '/')
893 /* Move past the slash between the ARGV element
894 and the rest of the pathname. But if the ARGV element
895 ends in a slash, we didn't add another, so we've
896 already skipped past it. */
897 cp++;
899 else
901 cp = "";
903 checked_print_quoted (dest, segment->text, cp);
904 break;
906 case 's': /* size in bytes */
907 /* UNTRUSTED, probably unexploitable */
908 checked_fprintf (dest, segment->text,
909 human_readable ((uintmax_t) stat_buf->st_size,
910 hbuf, human_ceiling, 1, 1));
911 break;
913 case 'S': /* sparseness */
914 /* UNTRUSTED, probably unexploitable */
915 checked_fprintf (dest, segment->text, file_sparseness(stat_buf));;
916 break;
918 case 't': /* mtime in `ctime' format */
919 /* UNTRUSTED, probably unexploitable */
920 checked_fprintf (dest, segment->text,
921 ctime_format (get_stat_mtime(stat_buf)));
922 break;
924 case 'u': /* user name */
925 /* trusted */
926 /* (well, the actual user is selected by the user on systems
927 * where chown is not restricted, but the user name was
928 * selected by the system administrator)
931 struct passwd *p;
933 p = getpwuid (stat_buf->st_uid);
934 if (p)
936 segment->text[segment->text_len] = 's';
937 checked_fprintf (dest, segment->text, p->pw_name);
938 break;
940 /* else fallthru */
942 /* FALLTHROUGH*/ /* .. to case U */
944 case 'U': /* UID number */
945 /* UNTRUSTED, probably unexploitable */
946 checked_fprintf (dest, segment->text,
947 human_readable ((uintmax_t) stat_buf->st_uid, hbuf,
948 human_ceiling, 1, 1));
949 break;
951 /* %Y: type of filesystem entry like `ls -l`:
952 * (d,-,l,s,p,b,c,n) n=nonexistent(symlink)
954 case 'Y': /* in case of symlink */
955 /* trusted */
957 #ifdef S_ISLNK
958 if (S_ISLNK (stat_buf->st_mode))
960 struct stat sbuf;
961 /* If we would normally follow links, do not do so.
962 * If we would normally not follow links, do so.
964 if ((following_links() ? lstat : stat)
965 (state.rel_pathname, &sbuf) != 0)
967 if ( errno == ENOENT )
969 checked_fprintf (dest, segment->text, "N");
970 break;
972 else if ( errno == ELOOP )
974 checked_fprintf (dest, segment->text, "L");
975 break;
977 else
979 checked_fprintf (dest, segment->text, "?");
980 error (0, errno, "%s",
981 safely_quote_err_filename(0, pathname));
982 /* exit_status = 1;
983 return ; */
984 break;
987 checked_fprintf (dest, segment->text,
988 mode_to_filetype(sbuf.st_mode & S_IFMT));
990 #endif /* S_ISLNK */
991 else
993 checked_fprintf (dest, segment->text,
994 mode_to_filetype(stat_buf->st_mode & S_IFMT));
997 break;
999 case 'y':
1000 /* trusted */
1002 checked_fprintf (dest, segment->text,
1003 mode_to_filetype(stat_buf->st_mode & S_IFMT));
1005 break;
1007 /* end of KIND_FORMAT case */
1008 break;
1012 boolean
1013 pred_fprintf (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1015 struct format_val *dest = &pred_ptr->args.printf_vec;
1016 struct segment *segment;
1018 for (segment = dest->segment; segment; segment = segment->next)
1020 if ( (KIND_FORMAT == segment->segkind) && segment->format_char[1]) /* Component of date. */
1022 struct timespec ts;
1023 int valid = 0;
1025 switch (segment->format_char[0])
1027 case 'A':
1028 ts = get_stat_atime(stat_buf);
1029 valid = 1;
1030 break;
1031 case 'B':
1032 ts = get_stat_birthtime(stat_buf);
1033 if ('@' == segment->format_char[1])
1034 valid = 1;
1035 else
1036 valid = (ts.tv_nsec >= 0);
1037 break;
1038 case 'C':
1039 ts = get_stat_ctime(stat_buf);
1040 valid = 1;
1041 break;
1042 case 'T':
1043 ts = get_stat_mtime(stat_buf);
1044 valid = 1;
1045 break;
1046 default:
1047 assert(0);
1048 abort ();
1050 /* We trust the output of format_date not to contain
1051 * nasty characters, though the value of the date
1052 * is itself untrusted data.
1054 if (valid)
1056 /* trusted */
1057 checked_fprintf (dest, segment->text,
1058 format_date (ts, segment->format_char[1]));
1060 else
1062 /* The specified timestamp is not available, output
1063 * nothing for the timestamp, but use the rest (so that
1064 * for example find foo -printf '[%Bs] %p\n' can print
1065 * "[] foo").
1067 /* trusted */
1068 checked_fprintf (dest, segment->text, "");
1071 else
1073 /* Print a segment which is not a date. */
1074 do_fprintf(dest, segment, pathname, stat_buf);
1077 return true;
1080 boolean
1081 pred_fstype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1083 (void) pathname;
1085 if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0)
1086 return true;
1087 else
1088 return false;
1091 boolean
1092 pred_gid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1094 (void) pathname;
1096 switch (pred_ptr->args.numinfo.kind)
1098 case COMP_GT:
1099 if (stat_buf->st_gid > pred_ptr->args.numinfo.l_val)
1100 return (true);
1101 break;
1102 case COMP_LT:
1103 if (stat_buf->st_gid < pred_ptr->args.numinfo.l_val)
1104 return (true);
1105 break;
1106 case COMP_EQ:
1107 if (stat_buf->st_gid == pred_ptr->args.numinfo.l_val)
1108 return (true);
1109 break;
1111 return (false);
1114 boolean
1115 pred_group (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1117 (void) pathname;
1119 if (pred_ptr->args.gid == stat_buf->st_gid)
1120 return (true);
1121 else
1122 return (false);
1125 boolean
1126 pred_ilname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1128 return match_lname (pathname, stat_buf, pred_ptr, true);
1131 boolean
1132 pred_iname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1134 const char *base;
1136 (void) stat_buf;
1138 /* FNM_PERIOD is not used here because POSIX requires that it not be.
1139 * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1141 base = base_name (pathname);
1142 if (fnmatch (pred_ptr->args.str, base, FNM_CASEFOLD) == 0)
1143 return (true);
1144 return (false);
1147 boolean
1148 pred_inum (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1150 (void) pathname;
1152 switch (pred_ptr->args.numinfo.kind)
1154 case COMP_GT:
1155 if (stat_buf->st_ino > pred_ptr->args.numinfo.l_val)
1156 return (true);
1157 break;
1158 case COMP_LT:
1159 if (stat_buf->st_ino < pred_ptr->args.numinfo.l_val)
1160 return (true);
1161 break;
1162 case COMP_EQ:
1163 if (stat_buf->st_ino == pred_ptr->args.numinfo.l_val)
1164 return (true);
1165 break;
1167 return (false);
1170 boolean
1171 pred_ipath (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1173 (void) stat_buf;
1175 if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0)
1176 return (true);
1177 return (false);
1180 boolean
1181 pred_links (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1183 (void) pathname;
1185 switch (pred_ptr->args.numinfo.kind)
1187 case COMP_GT:
1188 if (stat_buf->st_nlink > pred_ptr->args.numinfo.l_val)
1189 return (true);
1190 break;
1191 case COMP_LT:
1192 if (stat_buf->st_nlink < pred_ptr->args.numinfo.l_val)
1193 return (true);
1194 break;
1195 case COMP_EQ:
1196 if (stat_buf->st_nlink == pred_ptr->args.numinfo.l_val)
1197 return (true);
1198 break;
1200 return (false);
1203 boolean
1204 pred_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1206 return match_lname (pathname, stat_buf, pred_ptr, false);
1209 static boolean
1210 match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, boolean ignore_case)
1212 boolean ret = false;
1213 #ifdef S_ISLNK
1214 if (S_ISLNK (stat_buf->st_mode))
1216 char *linkname = get_link_name_at (pathname, state.cwd_dir_fd, state.rel_pathname);
1217 if (linkname)
1219 if (fnmatch (pred_ptr->args.str, linkname,
1220 ignore_case ? FNM_CASEFOLD : 0) == 0)
1221 ret = true;
1222 free (linkname);
1225 #endif /* S_ISLNK */
1226 return ret;
1229 boolean
1230 pred_ls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1232 return pred_fls(pathname, stat_buf, pred_ptr);
1235 boolean
1236 pred_mmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1238 (void) &pathname;
1239 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, 60);
1242 boolean
1243 pred_mtime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1245 (void) pathname;
1246 return pred_timewindow(get_stat_mtime(stat_buf), pred_ptr, DAYSECS);
1249 boolean
1250 pred_name (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1252 const char *base;
1254 (void) stat_buf;
1255 base = base_name (pathname);
1257 /* FNM_PERIOD is not used here because POSIX requires that it not be.
1258 * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1260 if (fnmatch (pred_ptr->args.str, base, 0) == 0)
1261 return (true);
1262 return (false);
1265 boolean
1266 pred_negate (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1268 return !apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1271 boolean
1272 pred_newer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1274 (void) pathname;
1276 assert(COMP_GT == pred_ptr->args.reftime.kind);
1277 return compare_ts(get_stat_mtime(stat_buf), pred_ptr->args.reftime.ts) > 0;
1280 boolean
1281 pred_newerXY (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1283 struct timespec ts;
1284 boolean collected = false;
1286 assert(COMP_GT == pred_ptr->args.reftime.kind);
1288 switch (pred_ptr->args.reftime.xval)
1290 case XVAL_TIME:
1291 assert(pred_ptr->args.reftime.xval != XVAL_TIME);
1292 return false;
1294 case XVAL_ATIME:
1295 ts = get_stat_atime(stat_buf);
1296 collected = true;
1297 break;
1299 case XVAL_BIRTHTIME:
1300 ts = get_stat_birthtime(stat_buf);
1301 collected = true;
1302 if (ts.tv_nsec < 0);
1304 /* XXX: Cannot determine birth time. Warn once. */
1305 error(0, 0, _("Warning: cannot determine birth time of file %s"),
1306 safely_quote_err_filename(0, pathname));
1307 return false;
1309 break;
1311 case XVAL_CTIME:
1312 ts = get_stat_ctime(stat_buf);
1313 collected = true;
1314 break;
1316 case XVAL_MTIME:
1317 ts = get_stat_mtime(stat_buf);
1318 collected = true;
1319 break;
1322 assert(collected);
1323 return compare_ts(ts, pred_ptr->args.reftime.ts) > 0;
1326 boolean
1327 pred_nogroup (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1329 (void) pathname;
1330 (void) pred_ptr;
1332 #ifdef CACHE_IDS
1333 extern char *gid_unused;
1335 return gid_unused[(unsigned) stat_buf->st_gid];
1336 #else
1337 return getgrgid (stat_buf->st_gid) == NULL;
1338 #endif
1341 boolean
1342 pred_nouser (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1344 #ifdef CACHE_IDS
1345 extern char *uid_unused;
1346 #endif
1348 (void) pathname;
1349 (void) pred_ptr;
1351 #ifdef CACHE_IDS
1352 return uid_unused[(unsigned) stat_buf->st_uid];
1353 #else
1354 return getpwuid (stat_buf->st_uid) == NULL;
1355 #endif
1359 static boolean
1360 is_ok(const char *program, const char *arg)
1362 fflush (stdout);
1363 /* The draft open standard requires that, in the POSIX locale,
1364 the last non-blank character of this prompt be '?'.
1365 The exact format is not specified.
1366 This standard does not have requirements for locales other than POSIX
1368 /* XXX: printing UNTRUSTED data here. */
1369 fprintf (stderr, _("< %s ... %s > ? "), program, arg);
1370 fflush (stderr);
1371 return yesno();
1374 boolean
1375 pred_ok (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1377 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1378 return new_impl_pred_exec (get_start_dirfd(),
1379 pathname, stat_buf, pred_ptr, NULL, 0);
1380 else
1381 return false;
1384 boolean
1385 pred_okdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1387 const char *prefix = (state.rel_pathname[0] == '/') ? NULL : "./";
1388 if (is_ok(pred_ptr->args.exec_vec.replace_vec[0], pathname))
1389 return new_impl_pred_exec (get_current_dirfd(),
1390 state.rel_pathname, stat_buf, pred_ptr,
1391 prefix, (prefix ? 2 : 0));
1392 else
1393 return false;
1396 boolean
1397 pred_openparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1399 (void) pathname;
1400 (void) stat_buf;
1401 (void) pred_ptr;
1402 return true;
1405 boolean
1406 pred_or (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1408 if (pred_ptr->pred_left == NULL
1409 || !apply_predicate(pathname, stat_buf, pred_ptr->pred_left))
1411 return apply_predicate(pathname, stat_buf, pred_ptr->pred_right);
1413 else
1414 return true;
1417 boolean
1418 pred_path (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1420 (void) stat_buf;
1421 if (fnmatch (pred_ptr->args.str, pathname, 0) == 0)
1422 return (true);
1423 return (false);
1426 boolean
1427 pred_perm (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1429 mode_t mode = stat_buf->st_mode;
1430 mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0];
1431 (void) pathname;
1432 switch (pred_ptr->args.perm.kind)
1434 case PERM_AT_LEAST:
1435 return (mode & perm_val) == perm_val;
1436 break;
1438 case PERM_ANY:
1439 /* True if any of the bits set in the mask are also set in the file's mode.
1442 * Otherwise, if onum is prefixed by a hyphen, the primary shall
1443 * evaluate as true if at least all of the bits specified in
1444 * onum that are also set in the octal mask 07777 are set.
1446 * Eric Blake's interpretation is that the mode argument is zero,
1449 if (0 == perm_val)
1450 return true; /* Savannah bug 14748; we used to return false */
1451 else
1452 return (mode & perm_val) != 0;
1453 break;
1455 case PERM_EXACT:
1456 return (mode & MODE_ALL) == perm_val;
1457 break;
1459 default:
1460 abort ();
1461 break;
1466 struct access_check_args
1468 const char *filename;
1469 int access_type;
1470 int cb_errno;
1474 static int
1475 access_callback(void *context)
1477 int rv;
1478 struct access_check_args *args = context;
1479 if ((rv = access(args->filename, args->access_type)) < 0)
1480 args->cb_errno = errno;
1481 return rv;
1484 static int
1485 can_access(int access_type)
1487 struct access_check_args args;
1488 args.filename = state.rel_pathname;
1489 args.access_type = access_type;
1490 args.cb_errno = 0;
1491 return 0 == run_in_dir(state.cwd_dir_fd, access_callback, &args);
1495 boolean
1496 pred_executable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1498 (void) pathname;
1499 (void) stat_buf;
1500 (void) pred_ptr;
1502 return can_access(X_OK);
1505 boolean
1506 pred_readable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1508 (void) pathname;
1509 (void) stat_buf;
1510 (void) pred_ptr;
1512 return can_access(R_OK);
1515 boolean
1516 pred_writable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1518 (void) pathname;
1519 (void) stat_buf;
1520 (void) pred_ptr;
1522 return can_access(W_OK);
1525 boolean
1526 pred_print (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1528 (void) stat_buf;
1529 (void) pred_ptr;
1531 print_quoted(pred_ptr->args.printf_vec.stream,
1532 pred_ptr->args.printf_vec.quote_opts,
1533 pred_ptr->args.printf_vec.dest_is_tty,
1534 "%s\n", pathname);
1535 return true;
1538 boolean
1539 pred_print0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1541 return pred_fprint0(pathname, stat_buf, pred_ptr);
1544 boolean
1545 pred_prune (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1547 (void) pathname;
1548 (void) pred_ptr;
1550 if (options.do_dir_first == true &&
1551 stat_buf != NULL &&
1552 S_ISDIR(stat_buf->st_mode))
1553 state.stop_at_current_level = true;
1555 return (options.do_dir_first); /* This is what SunOS find seems to do. */
1558 boolean
1559 pred_quit (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1561 (void) pathname;
1562 (void) stat_buf;
1563 (void) pred_ptr;
1565 /* Run any cleanups. This includes executing any command lines
1566 * we have partly built but not executed.
1568 cleanup();
1570 /* Since -exec and friends don't leave child processes running in the
1571 * background, there is no need to wait for them here.
1573 exit(state.exit_status); /* 0 for success, etc. */
1576 boolean
1577 pred_regex (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1579 int len = strlen (pathname);
1580 (void) stat_buf;
1581 if (re_match (pred_ptr->args.regex, pathname, len, 0,
1582 (struct re_registers *) NULL) == len)
1583 return (true);
1584 return (false);
1587 boolean
1588 pred_size (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1590 uintmax_t f_val;
1592 (void) pathname;
1593 f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize)
1594 + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0));
1595 switch (pred_ptr->args.size.kind)
1597 case COMP_GT:
1598 if (f_val > pred_ptr->args.size.size)
1599 return (true);
1600 break;
1601 case COMP_LT:
1602 if (f_val < pred_ptr->args.size.size)
1603 return (true);
1604 break;
1605 case COMP_EQ:
1606 if (f_val == pred_ptr->args.size.size)
1607 return (true);
1608 break;
1610 return (false);
1613 boolean
1614 pred_samefile (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1616 /* Potential optimisation: because of the loop protection, we always
1617 * know the device of the current directory, hence the device number
1618 * of the file we're currently considering. If -L is not in effect,
1619 * and the device number of the file we're looking for is not the
1620 * same as the device number of the current directory, this
1621 * predicate cannot return true. Hence there would be no need to
1622 * stat the file we're looking at.
1624 (void) pathname;
1626 /* We will often still have an fd open on the file under consideration,
1627 * but that's just to ensure inode number stability by maintaining
1628 * a reference to it; we don't need the file for anything else.
1630 return stat_buf->st_ino == pred_ptr->args.samefileid.ino
1631 && stat_buf->st_dev == pred_ptr->args.samefileid.dev;
1634 boolean
1635 pred_true (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1637 (void) pathname;
1638 (void) stat_buf;
1639 (void) pred_ptr;
1640 return true;
1643 boolean
1644 pred_type (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1646 mode_t mode;
1647 mode_t type = pred_ptr->args.type;
1649 assert(state.have_type);
1651 if (0 == state.type)
1653 /* This can sometimes happen with broken NFS servers.
1654 * See Savannah bug #16378.
1656 return false;
1659 (void) pathname;
1661 if (state.have_stat)
1662 mode = stat_buf->st_mode;
1663 else
1664 mode = state.type;
1666 #ifndef S_IFMT
1667 /* POSIX system; check `mode' the slow way. */
1668 if ((S_ISBLK (mode) && type == S_IFBLK)
1669 || (S_ISCHR (mode) && type == S_IFCHR)
1670 || (S_ISDIR (mode) && type == S_IFDIR)
1671 || (S_ISREG (mode) && type == S_IFREG)
1672 #ifdef S_IFLNK
1673 || (S_ISLNK (mode) && type == S_IFLNK)
1674 #endif
1675 #ifdef S_IFIFO
1676 || (S_ISFIFO (mode) && type == S_IFIFO)
1677 #endif
1678 #ifdef S_IFSOCK
1679 || (S_ISSOCK (mode) && type == S_IFSOCK)
1680 #endif
1681 #ifdef S_IFDOOR
1682 || (S_ISDOOR (mode) && type == S_IFDOOR)
1683 #endif
1685 #else /* S_IFMT */
1686 /* Unix system; check `mode' the fast way. */
1687 if ((mode & S_IFMT) == type)
1688 #endif /* S_IFMT */
1689 return (true);
1690 else
1691 return (false);
1694 boolean
1695 pred_uid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1697 (void) pathname;
1698 switch (pred_ptr->args.numinfo.kind)
1700 case COMP_GT:
1701 if (stat_buf->st_uid > pred_ptr->args.numinfo.l_val)
1702 return (true);
1703 break;
1704 case COMP_LT:
1705 if (stat_buf->st_uid < pred_ptr->args.numinfo.l_val)
1706 return (true);
1707 break;
1708 case COMP_EQ:
1709 if (stat_buf->st_uid == pred_ptr->args.numinfo.l_val)
1710 return (true);
1711 break;
1713 return (false);
1716 boolean
1717 pred_used (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1719 struct timespec delta, at, ct;
1721 (void) pathname;
1723 /* TODO: this needs to be retested carefully (manually, if necessary) */
1724 at = get_stat_atime(stat_buf);
1725 ct = get_stat_ctime(stat_buf);
1726 delta.tv_sec = at.tv_sec - ct.tv_sec;
1727 delta.tv_nsec = at.tv_nsec - ct.tv_nsec;
1728 if (delta.tv_nsec < 0)
1730 delta.tv_nsec += 1000000000;
1731 delta.tv_sec -= 1;
1733 return pred_timewindow(delta, pred_ptr, DAYSECS);
1736 boolean
1737 pred_user (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1739 (void) pathname;
1740 if (pred_ptr->args.uid == stat_buf->st_uid)
1741 return (true);
1742 else
1743 return (false);
1746 boolean
1747 pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1749 struct stat sbuf; /* local copy, not stat_buf because we're using a different stat method */
1750 int (*ystat) (const char*, struct stat *p);
1752 /* If we would normally stat the link itself, stat the target instead.
1753 * If we would normally follow the link, stat the link itself instead.
1755 if (following_links())
1756 ystat = optionp_stat;
1757 else
1758 ystat = optionl_stat;
1760 set_stat_placeholders(&sbuf);
1761 if ((*ystat) (state.rel_pathname, &sbuf) != 0)
1763 if (following_links() && errno == ENOENT)
1765 /* If we failed to follow the symlink,
1766 * fall back on looking at the symlink itself.
1768 /* Mimic behavior of ls -lL. */
1769 return (pred_type (pathname, stat_buf, pred_ptr));
1771 else
1773 error (0, errno, "%s", safely_quote_err_filename(0, pathname));
1774 state.exit_status = 1;
1776 return false;
1778 /* Now that we have our stat() information, query it in the same
1779 * way that -type does.
1781 return (pred_type (pathname, &sbuf, pred_ptr));
1784 /* 1) fork to get a child; parent remembers the child pid
1785 2) child execs the command requested
1786 3) parent waits for child; checks for proper pid of child
1788 Possible returns:
1790 ret errno status(h) status(l)
1792 pid x signal# 0177 stopped
1793 pid x exit arg 0 term by _exit
1794 pid x 0 signal # term by signal
1795 -1 EINTR parent got signal
1796 -1 other some other kind of error
1798 Return true only if the pid matches, status(l) is
1799 zero, and the exit arg (status high) is 0.
1800 Otherwise return false, possibly printing an error message. */
1803 static boolean
1804 prep_child_for_exec (boolean close_stdin, int dirfd)
1806 boolean ok = true;
1807 if (close_stdin)
1809 const char inputfile[] = "/dev/null";
1811 if (close(0) < 0)
1813 error(0, errno, _("Cannot close standard input"));
1814 ok = false;
1816 else
1818 if (open(inputfile, O_RDONLY
1819 #if defined O_LARGEFILE
1820 |O_LARGEFILE
1821 #endif
1822 ) < 0)
1824 /* This is not entirely fatal, since
1825 * executing the child with a closed
1826 * stdin is almost as good as executing it
1827 * with its stdin attached to /dev/null.
1829 error (0, errno, "%s", safely_quote_err_filename(0, inputfile));
1830 /* do not set ok=false, it is OK to continue anyway. */
1835 /* Even if DebugSearch is set, don't announce our change of
1836 * directory, since we're not going to emit a subsequent
1837 * announcement of a call to stat() anyway, as we're about to exec
1838 * something.
1840 if (dirfd != AT_FDCWD)
1842 assert(dirfd >= 0);
1843 if (0 != fchdir(dirfd))
1845 /* If we cannot execute our command in the correct directory,
1846 * we should not execute it at all.
1848 error(0, errno, _("Failed to change directory"));
1849 ok = false;
1852 return ok;
1858 launch (const struct buildcmd_control *ctl,
1859 struct buildcmd_state *buildstate)
1861 int wait_status;
1862 pid_t child_pid;
1863 static int first_time = 1;
1864 const struct exec_val *execp = buildstate->usercontext;
1866 if (!execp->use_current_dir)
1868 assert(starting_desc >= 0);
1869 assert(execp->dirfd == starting_desc);
1873 /* Null terminate the arg list. */
1874 bc_push_arg (ctl, buildstate, (char *) NULL, 0, NULL, 0, false);
1876 /* Make sure output of command doesn't get mixed with find output. */
1877 fflush (stdout);
1878 fflush (stderr);
1880 /* Make sure to listen for the kids. */
1881 if (first_time)
1883 first_time = 0;
1884 signal (SIGCHLD, SIG_DFL);
1887 child_pid = fork ();
1888 if (child_pid == -1)
1889 error (1, errno, _("cannot fork"));
1890 if (child_pid == 0)
1892 /* We are the child. */
1893 assert(starting_desc >= 0);
1894 if (!prep_child_for_exec(execp->close_stdin, execp->dirfd))
1896 _exit(1);
1899 execvp (buildstate->cmd_argv[0], buildstate->cmd_argv);
1900 error (0, errno, "%s",
1901 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1902 _exit (1);
1906 /* In parent; set up for next time. */
1907 bc_clear_args(ctl, buildstate);
1910 while (waitpid (child_pid, &wait_status, 0) == (pid_t) -1)
1912 if (errno != EINTR)
1914 error (0, errno, _("error waiting for %s"),
1915 safely_quote_err_filename(0, buildstate->cmd_argv[0]));
1916 state.exit_status = 1;
1917 return 0; /* FAIL */
1921 if (WIFSIGNALED (wait_status))
1923 error (0, 0, _("%s terminated by signal %d"),
1924 quotearg_n_style(0, options.err_quoting_style,
1925 buildstate->cmd_argv[0]),
1926 WTERMSIG (wait_status));
1928 if (execp->multiple)
1930 /* -exec \; just returns false if the invoked command fails.
1931 * -exec {} + returns true if the invoked command fails, but
1932 * sets the program exit status.
1934 state.exit_status = 1;
1937 return 1; /* OK */
1940 if (0 == WEXITSTATUS (wait_status))
1942 return 1; /* OK */
1944 else
1946 if (execp->multiple)
1948 /* -exec \; just returns false if the invoked command fails.
1949 * -exec {} + returns true if the invoked command fails, but
1950 * sets the program exit status.
1952 state.exit_status = 1;
1954 return 0; /* FAIL */
1960 /* Return a static string formatting the time WHEN according to the
1961 * strftime format character KIND.
1963 * This function contains a number of assertions. These look like
1964 * runtime checks of the results of computations, which would be a
1965 * problem since external events should not be tested for with
1966 * "assert" (instead you should use "if"). However, they are not
1967 * really runtime checks. The assertions actually exist to verify
1968 * that the various buffers are correctly sized.
1970 static char *
1971 format_date (struct timespec ts, int kind)
1973 /* In theory, we use an extra 10 characters for 9 digits of
1974 * nanoseconds and 1 for the decimal point. However, the real
1975 * world is more complex than that.
1977 * For example, some systems return junk in the tv_nsec part of
1978 * st_birthtime. An example of this is the NetBSD-4.0-RELENG kernel
1979 * (at Sat Mar 24 18:46:46 2007) running a NetBSD-3.1-RELEASE
1980 * runtime and examining files on an msdos filesytem. So for that
1981 * reason we set NS_BUF_LEN to 32, which is simply "long enough" as
1982 * opposed to "exactly the right size". Note that the behaviour of
1983 * NetBSD appears to be a result of the use of uninitialised data,
1984 * as it's not 100% reproducible (more like 25%).
1986 enum {
1987 NS_BUF_LEN = 32,
1988 DATE_LEN_PERCENT_APLUS=21 /* length of result of %A+ (it's longer than %c)*/
1990 static char buf[128u+10u + MAX(DATE_LEN_PERCENT_APLUS,
1991 MAX (LONGEST_HUMAN_READABLE + 2, NS_BUF_LEN+64+200))];
1992 char ns_buf[NS_BUF_LEN]; /* -.9999999990 (- sign can happen!)*/
1993 int charsprinted, need_ns_suffix;
1994 struct tm *tm;
1995 char fmt[6];
1997 /* human_readable() assumes we pass a buffer which is at least as
1998 * long as LONGEST_HUMAN_READABLE. We use an assertion here to
1999 * ensure that no nasty unsigned overflow happend in our calculation
2000 * of the size of buf. Do the assertion here rather than in the
2001 * code for %@ so that we find the problem quickly if it exists. If
2002 * you want to submit a patch to move this into the if statement, go
2003 * ahead, I'll apply it. But include performance timings
2004 * demonstrating that the performance difference is actually
2005 * measurable.
2007 assert(sizeof(buf) >= LONGEST_HUMAN_READABLE);
2009 charsprinted = 0;
2010 need_ns_suffix = 0;
2012 /* Format the main part of the time. */
2013 if (kind == '+')
2015 strcpy (fmt, "%F+%T");
2016 need_ns_suffix = 1;
2018 else
2020 fmt[0] = '%';
2021 fmt[1] = kind;
2022 fmt[2] = '\0';
2024 /* %a, %c, and %t are handled in ctime_format() */
2025 switch (kind)
2027 case 'S':
2028 case 'T':
2029 case 'X':
2030 case '@':
2031 need_ns_suffix = 1;
2032 break;
2033 default:
2034 need_ns_suffix = 0;
2035 break;
2039 if (need_ns_suffix)
2041 /* Format the nanoseconds part. Leave a trailing zero to
2042 * discourage people from writing scripts which extract the
2043 * fractional part of the timestamp by using column offsets.
2044 * The reason for discouraging this is that in the future, the
2045 * granularity may not be nanoseconds.
2047 ns_buf[0] = 0;
2048 charsprinted = snprintf(ns_buf, NS_BUF_LEN, ".%09ld0", (long int)ts.tv_nsec);
2049 assert(charsprinted < NS_BUF_LEN);
2052 if (kind != '@'
2053 && (tm = localtime (&ts.tv_sec))
2054 && strftime (buf, sizeof buf, fmt, tm))
2056 /* For %AS, %CS, %TS, add the fractional part of the seconds
2057 * information.
2059 if (need_ns_suffix)
2061 assert((sizeof buf - strlen(buf)) > strlen(ns_buf));
2062 strcat(buf, ns_buf);
2064 return buf;
2066 else
2068 uintmax_t w = ts.tv_sec;
2069 size_t used, len, remaining;
2071 /* XXX: note that we are negating an unsigned type which is the
2072 * widest possible unsigned type.
2074 char *p = human_readable (ts.tv_sec < 0 ? -w : w, buf + 1,
2075 human_ceiling, 1, 1);
2076 assert(p > buf);
2077 assert(p < (buf + (sizeof buf)));
2078 if (ts.tv_sec < 0)
2079 *--p = '-'; /* XXX: Ugh, relying on internal details of human_readable(). */
2081 /* Add the nanoseconds part. Because we cannot enforce a
2082 * particlar implementation of human_readable, we cannot assume
2083 * any particular value for (p-buf). So we need to be careful
2084 * that there is enough space remaining in the buffer.
2086 if (need_ns_suffix)
2088 len = strlen(p);
2089 used = (p-buf) + len; /* Offset into buf of current end */
2090 assert(sizeof buf > used); /* Ensure we can perform subtraction safely. */
2091 remaining = sizeof buf - used - 1u; /* allow space for NUL */
2093 if (strlen(ns_buf) >= remaining)
2095 error(0, 0,
2096 "charsprinted=%ld but remaining=%lu: ns_buf=%s",
2097 (long)charsprinted, (unsigned long)remaining, ns_buf);
2099 assert(strlen(ns_buf) < remaining);
2100 strcat(p, ns_buf);
2102 return p;
2106 static const char *weekdays[] =
2108 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
2110 static char * months[] =
2112 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2113 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2117 static char *
2118 ctime_format (struct timespec ts)
2120 const struct tm * ptm;
2121 #define TIME_BUF_LEN 1024u
2122 static char resultbuf[TIME_BUF_LEN];
2123 int nout;
2125 ptm = localtime(&ts.tv_sec);
2126 if (ptm)
2128 assert(ptm->tm_wday >= 0);
2129 assert(ptm->tm_wday < 7);
2130 assert(ptm->tm_mon >= 0);
2131 assert(ptm->tm_mon < 12);
2132 assert(ptm->tm_hour >= 0);
2133 assert(ptm->tm_hour < 24);
2134 assert(ptm->tm_min < 60);
2135 assert(ptm->tm_sec <= 61); /* allows 2 leap seconds. */
2137 /* wkday mon mday hh:mm:ss.nnnnnnnnn yyyy */
2138 nout = snprintf(resultbuf, TIME_BUF_LEN,
2139 "%3s %3s %2d %02d:%02d:%02d.%010ld %04d",
2140 weekdays[ptm->tm_wday],
2141 months[ptm->tm_mon],
2142 ptm->tm_mday,
2143 ptm->tm_hour,
2144 ptm->tm_min,
2145 ptm->tm_sec,
2146 (long int)ts.tv_nsec,
2147 1900 + ptm->tm_year);
2149 assert(nout < TIME_BUF_LEN);
2150 return resultbuf;
2152 else
2154 /* The time cannot be represented as a struct tm.
2155 Output it as an integer. */
2156 return format_date (ts, '@');
2160 /* Copy STR into BUF and trim blanks from the end of BUF.
2161 Return BUF. */
2163 static char *
2164 blank_rtrim (str, buf)
2165 char *str;
2166 char *buf;
2168 int i;
2170 if (str == NULL)
2171 return (NULL);
2172 strcpy (buf, str);
2173 i = strlen (buf) - 1;
2174 while ((i >= 0) && ((buf[i] == ' ') || buf[i] == '\t'))
2175 i--;
2176 buf[++i] = '\0';
2177 return (buf);
2180 /* Print out the predicate list starting at NODE. */
2181 void
2182 print_list (FILE *fp, struct predicate *node)
2184 struct predicate *cur;
2185 char name[256];
2187 cur = node;
2188 while (cur != NULL)
2190 fprintf (fp, "%s ", blank_rtrim (cur->p_name, name));
2191 cur = cur->pred_next;
2193 fprintf (fp, "\n");
2196 /* Print out the predicate list starting at NODE. */
2197 static void
2198 print_parenthesised(FILE *fp, struct predicate *node)
2200 int parens = 0;
2202 if (node)
2204 if ((pred_is(node, pred_or) || pred_is(node, pred_and))
2205 && node->pred_left == NULL)
2207 /* We print "<nothing> or X" as just "X"
2208 * We print "<nothing> and X" as just "X"
2210 print_parenthesised(fp, node->pred_right);
2212 else
2214 if (node->pred_left || node->pred_right)
2215 parens = 1;
2217 if (parens)
2218 fprintf(fp, "%s", " ( ");
2219 print_optlist(fp, node);
2220 if (parens)
2221 fprintf(fp, "%s", " ) ");
2226 void
2227 print_optlist (FILE *fp, const struct predicate *p)
2229 if (p)
2231 print_parenthesised(fp, p->pred_left);
2232 fprintf (fp,
2233 "%s%s",
2234 p->need_stat ? "[call stat] " : "",
2235 p->need_type ? "[need type] " : "");
2236 print_predicate(fp, p);
2237 fprintf(fp, " [%g] ", p->est_success_rate);
2238 if (options.debug_options & DebugSuccessRates)
2240 fprintf(fp, "[%ld/%ld", p->perf.successes, p->perf.visits);
2241 if (p->perf.visits)
2243 double real_rate = (double)p->perf.successes / (double)p->perf.visits;
2244 fprintf(fp, "=%g] ", real_rate);
2246 else
2248 fprintf(fp, "=_] ");
2251 print_parenthesised(fp, p->pred_right);
2255 void show_success_rates(const struct predicate *p)
2257 if (options.debug_options & DebugSuccessRates)
2259 fprintf(stderr, "Predicate success rates after completion:\n");
2260 print_optlist(stderr, p);
2261 fprintf(stderr, "\n");
2268 #ifdef _NDEBUG
2269 /* If _NDEBUG is defined, the assertions will do nothing. Hence
2270 * there is no point in having a function body for pred_sanity_check()
2271 * if that preprocessor macro is defined.
2273 void
2274 pred_sanity_check(const struct predicate *predicates)
2276 /* Do nothing, since assert() is a no-op with _NDEBUG set */
2277 return;
2279 #else
2280 void
2281 pred_sanity_check(const struct predicate *predicates)
2283 const struct predicate *p;
2285 for (p=predicates; p != NULL; p=p->pred_next)
2287 /* All predicates must do something. */
2288 assert(p->pred_func != NULL);
2290 /* All predicates must have a parser table entry. */
2291 assert(p->parser_entry != NULL);
2293 /* If the parser table tells us that just one predicate function is
2294 * possible, verify that that is still the one that is in effect.
2295 * If the parser has NULL for the predicate function, that means that
2296 * the parse_xxx function fills it in, so we can't check it.
2298 if (p->parser_entry->pred_func)
2300 assert(p->parser_entry->pred_func == p->pred_func);
2303 switch (p->parser_entry->type)
2305 /* Options all take effect during parsing, so there should
2306 * be no predicate entries corresponding to them. Hence we
2307 * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION
2308 * items.
2310 * This is a silly way of coding this test, but it prevents
2311 * a compiler warning (i.e. otherwise it would think that
2312 * there would be case statements missing).
2314 case ARG_OPTION:
2315 case ARG_POSITIONAL_OPTION:
2316 assert(p->parser_entry->type != ARG_OPTION);
2317 assert(p->parser_entry->type != ARG_POSITIONAL_OPTION);
2318 break;
2320 case ARG_ACTION:
2321 assert(p->side_effects); /* actions have side effects. */
2322 if (!pred_is(p, pred_prune) && !pred_is(p, pred_quit))
2324 /* actions other than -prune and -quit should
2325 * inhibit the default -print
2327 assert(p->no_default_print);
2329 break;
2331 /* We happen to know that the only user of ARG_SPECIAL_PARSE
2332 * is a test, so handle it like ARG_TEST.
2334 case ARG_SPECIAL_PARSE:
2335 case ARG_TEST:
2336 case ARG_PUNCTUATION:
2337 case ARG_NOOP:
2338 /* Punctuation and tests should have no side
2339 * effects and not inhibit default print.
2341 assert(!p->no_default_print);
2342 assert(!p->side_effects);
2343 break;
2347 #endif