Imported Upstream version 4.5.14
[platform/upstream/findutils.git] / find / pred.c
1 /* pred.c -- execute the expression tree.
2    Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2003, 2004, 2005,
3    2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
4
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.
9
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.
14
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/>.
17 */
18
19 /* config.h always comes first. */
20 #include <config.h>
21
22 /* system headers. */
23 #include <assert.h>
24 #include <ctype.h>
25 #include <dirent.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <grp.h>
29 #include <locale.h>
30 #include <math.h>
31 #include <pwd.h>
32 #include <selinux/selinux.h>
33 #include <stdarg.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <sys/wait.h>
37 #include <unistd.h> /* for unlinkat() */
38
39 /* gnulib headers. */
40 #include "areadlink.h"
41 #include "dirname.h"
42 #include "error.h"
43 #include "fnmatch.h"
44 #include "gettext.h"
45 #include "stat-size.h"
46 #include "stat-time.h"
47 #include "yesno.h"
48
49 /* find headers. */
50 #include "defs.h"
51 #include "dircallback.h"
52 #include "listfile.h"
53 #include "printquoted.h"
54
55
56
57 #if ENABLE_NLS
58 # include <libintl.h>
59 # define _(Text) gettext (Text)
60 #else
61 # define _(Text) Text
62 #endif
63 #ifdef gettext_noop
64 # define N_(String) gettext_noop (String)
65 #else
66 /* See locate.c for explanation as to why not use (String) */
67 # define N_(String) String
68 #endif
69
70 #ifdef CLOSEDIR_VOID
71 /* Fake a return value. */
72 #define CLOSEDIR(d) (closedir (d), 0)
73 #else
74 #define CLOSEDIR(d) closedir (d)
75 #endif
76
77 static bool match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, bool ignore_case);
78
79 #ifdef  DEBUG
80 struct pred_assoc
81 {
82   PRED_FUNC pred_func;
83   char *pred_name;
84 };
85
86 struct pred_assoc pred_table[] =
87 {
88   {pred_amin, "amin    "},
89   {pred_and, "and     "},
90   {pred_anewer, "anewer  "},
91   {pred_atime, "atime   "},
92   {pred_closeparen, ")       "},
93   {pred_cmin, "cmin    "},
94   {pred_cnewer, "cnewer  "},
95   {pred_comma, ",       "},
96   {pred_ctime, "ctime   "},
97   {pred_delete, "delete  "},
98   {pred_empty, "empty   "},
99   {pred_exec, "exec    "},
100   {pred_execdir, "execdir "},
101   {pred_executable, "executable "},
102   {pred_false, "false   "},
103   {pred_fprint, "fprint  "},
104   {pred_fprint0, "fprint0 "},
105   {pred_fprintf, "fprintf "},
106   {pred_fstype, "fstype  "},
107   {pred_gid, "gid     "},
108   {pred_group, "group   "},
109   {pred_ilname, "ilname  "},
110   {pred_iname, "iname   "},
111   {pred_inum, "inum    "},
112   {pred_ipath, "ipath   "},
113   {pred_links, "links   "},
114   {pred_lname, "lname   "},
115   {pred_ls, "ls      "},
116   {pred_mmin, "mmin    "},
117   {pred_mtime, "mtime   "},
118   {pred_name, "name    "},
119   {pred_negate, "not     "},
120   {pred_newer, "newer   "},
121   {pred_newerXY, "newerXY   "},
122   {pred_nogroup, "nogroup "},
123   {pred_nouser, "nouser  "},
124   {pred_ok, "ok      "},
125   {pred_okdir, "okdir   "},
126   {pred_openparen, "(       "},
127   {pred_or, "or      "},
128   {pred_path, "path    "},
129   {pred_perm, "perm    "},
130   {pred_print, "print   "},
131   {pred_print0, "print0  "},
132   {pred_prune, "prune   "},
133   {pred_quit, "quit    "},
134   {pred_readable, "readable    "},
135   {pred_regex, "regex   "},
136   {pred_samefile,"samefile "},
137   {pred_size, "size    "},
138   {pred_true, "true    "},
139   {pred_type, "type    "},
140   {pred_uid, "uid     "},
141   {pred_used, "used    "},
142   {pred_user, "user    "},
143   {pred_writable, "writable "},
144   {pred_xtype, "xtype   "},
145   {pred_context, "context"},
146   {0, "none    "}
147 };
148 #endif
149
150 /* Returns ts1 - ts2 */
151 static double ts_difference (struct timespec ts1,
152                              struct timespec ts2)
153 {
154   double d =  difftime (ts1.tv_sec, ts2.tv_sec)
155     + (1.0e-9 * (ts1.tv_nsec - ts2.tv_nsec));
156   return d;
157 }
158
159
160 static int
161 compare_ts (struct timespec ts1,
162             struct timespec ts2)
163 {
164   if ((ts1.tv_sec == ts2.tv_sec) &&
165       (ts1.tv_nsec == ts2.tv_nsec))
166     {
167       return 0;
168     }
169   else
170     {
171       double diff = ts_difference (ts1, ts2);
172       return diff < 0.0 ? -1 : +1;
173     }
174 }
175
176 /* Predicate processing routines.
177
178    PATHNAME is the full pathname of the file being checked.
179    *STAT_BUF contains information about PATHNAME.
180    *PRED_PTR contains information for applying the predicate.
181
182    Return true if the file passes this predicate, false if not. */
183
184
185 /* pred_timewindow
186  *
187  * Returns true if THE_TIME is
188  * COMP_GT: after the specified time
189  * COMP_LT: before the specified time
190  * COMP_EQ: after the specified time but by not more than WINDOW seconds.
191  */
192 static bool
193 pred_timewindow (struct timespec ts, struct predicate const *pred_ptr, int window)
194 {
195   switch (pred_ptr->args.reftime.kind)
196     {
197     case COMP_GT:
198       return compare_ts (ts, pred_ptr->args.reftime.ts) > 0;
199
200     case COMP_LT:
201       return compare_ts (ts, pred_ptr->args.reftime.ts) < 0;
202
203     case COMP_EQ:
204       {
205         /* consider "find . -mtime 0".
206          *
207          * Here, the origin is exactly 86400 seconds before the start
208          * of the program (since -daystart was not specified).   This
209          * function will be called with window=86400 and
210          * pred_ptr->args.reftime.ts as the origin.  Hence a file
211          * created the instant the program starts will show a time
212          * difference (value of delta) of 86400.   Similarly, a file
213          * created exactly 24h ago would be the newest file which was
214          * _not_ created today.   So, if delta is 0.0, the file
215          * was not created today.  If the delta is 86400, the file
216          * was created this instant.
217          */
218         double delta = ts_difference (ts, pred_ptr->args.reftime.ts);
219         return (delta > 0.0 && delta <= window);
220       }
221     }
222   assert (0);
223   abort ();
224 }
225
226
227 bool
228 pred_amin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
229 {
230   (void) &pathname;
231   return pred_timewindow (get_stat_atime(stat_buf), pred_ptr, 60);
232 }
233
234 bool
235 pred_and (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
236 {
237   if (pred_ptr->pred_left == NULL
238       || apply_predicate (pathname, stat_buf, pred_ptr->pred_left))
239     {
240       return apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
241     }
242   else
243     return false;
244 }
245
246 bool
247 pred_anewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
248 {
249   (void) &pathname;
250   assert (COMP_GT == pred_ptr->args.reftime.kind);
251   return compare_ts (get_stat_atime(stat_buf), pred_ptr->args.reftime.ts) > 0;
252 }
253
254 bool
255 pred_atime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
256 {
257   (void) &pathname;
258   return pred_timewindow (get_stat_atime(stat_buf), pred_ptr, DAYSECS);
259 }
260
261 bool
262 pred_closeparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
263 {
264   (void) &pathname;
265   (void) &stat_buf;
266   (void) &pred_ptr;
267
268   return true;
269 }
270
271 bool
272 pred_cmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
273 {
274   (void) pathname;
275   return pred_timewindow (get_stat_ctime(stat_buf), pred_ptr, 60);
276 }
277
278 bool
279 pred_cnewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
280 {
281   (void) pathname;
282
283   assert (COMP_GT == pred_ptr->args.reftime.kind);
284   return compare_ts (get_stat_ctime(stat_buf), pred_ptr->args.reftime.ts) > 0;
285 }
286
287 bool
288 pred_comma (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
289 {
290   if (pred_ptr->pred_left != NULL)
291     {
292       apply_predicate (pathname, stat_buf,pred_ptr->pred_left);
293     }
294   return apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
295 }
296
297 bool
298 pred_ctime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
299 {
300   (void) &pathname;
301   return pred_timewindow (get_stat_ctime(stat_buf), pred_ptr, DAYSECS);
302 }
303
304 static bool
305 perform_delete (int flags)
306 {
307   return 0 == unlinkat (state.cwd_dir_fd, state.rel_pathname, flags);
308 }
309
310
311 bool
312 pred_delete (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
313 {
314   (void) pred_ptr;
315   (void) stat_buf;
316   if (strcmp (state.rel_pathname, "."))
317     {
318       int flags=0;
319       if (state.have_stat && S_ISDIR(stat_buf->st_mode))
320         flags |= AT_REMOVEDIR;
321       if (perform_delete (flags))
322         {
323           return true;
324         }
325       else
326         {
327           if (EISDIR == errno)
328             {
329               if ((flags & AT_REMOVEDIR) == 0)
330                 {
331                   /* unlink() operation failed because we should have done rmdir(). */
332                   flags |= AT_REMOVEDIR;
333                   if (perform_delete (flags))
334                     return true;
335                 }
336             }
337         }
338       error (0, errno, _("cannot delete %s"),
339              safely_quote_err_filename (0, pathname));
340       /* Previously I had believed that having the -delete action
341        * return false provided the user with control over whether an
342        * error message is issued.  While this is true, the policy of
343        * not affecting the exit status is contrary to the POSIX
344        * requirement that diagnostic messages are accompanied by a
345        * nonzero exit status.  While -delete is not a POSIX option and
346        * we can therefore opt not to follow POSIX in this case, that
347        * seems somewhat arbitrary and confusing.  So, as of
348        * findutils-4.3.11, we also set the exit status in this case.
349        */
350       state.exit_status = 1;
351       return false;
352     }
353   else
354     {
355       /* nothing to do. */
356       return true;
357     }
358 }
359
360 bool
361 pred_empty (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
362 {
363   (void) pathname;
364   (void) pred_ptr;
365
366   if (S_ISDIR (stat_buf->st_mode))
367     {
368       int fd;
369       DIR *d;
370       struct dirent *dp;
371       bool empty = true;
372
373       errno = 0;
374       if ((fd = openat (state.cwd_dir_fd, state.rel_pathname, O_RDONLY
375 #if defined O_LARGEFILE
376                         |O_LARGEFILE
377 #endif
378                        )) < 0)
379         {
380           error (0, errno, "%s", safely_quote_err_filename (0, pathname));
381           state.exit_status = 1;
382           return false;
383         }
384       d = fdopendir (fd);
385       if (d == NULL)
386         {
387           error (0, errno, "%s", safely_quote_err_filename (0, pathname));
388           state.exit_status = 1;
389           return false;
390         }
391       for (dp = readdir (d); dp; dp = readdir (d))
392         {
393           if (dp->d_name[0] != '.'
394               || (dp->d_name[1] != '\0'
395                   && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
396             {
397               empty = false;
398               break;
399             }
400         }
401       if (CLOSEDIR (d))
402         {
403           error (0, errno, "%s", safely_quote_err_filename (0, pathname));
404           state.exit_status = 1;
405           return false;
406         }
407       return (empty);
408     }
409   else if (S_ISREG (stat_buf->st_mode))
410     return (stat_buf->st_size == 0);
411   else
412     return (false);
413 }
414
415
416 bool
417 pred_exec (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
418 {
419   return impl_pred_exec (pathname, stat_buf, pred_ptr);
420 }
421
422 bool
423 pred_execdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
424 {
425    (void) &pathname;
426    return impl_pred_exec (state.rel_pathname, stat_buf, pred_ptr);
427 }
428
429 bool
430 pred_false (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
431 {
432   (void) &pathname;
433   (void) &stat_buf;
434   (void) &pred_ptr;
435
436
437   return (false);
438 }
439
440 bool
441 pred_fls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
442 {
443   FILE * stream = pred_ptr->args.printf_vec.stream;
444   list_file (pathname, state.cwd_dir_fd, state.rel_pathname, stat_buf,
445              options.start_time.tv_sec,
446              options.output_block_size,
447              pred_ptr->literal_control_chars, stream);
448   return true;
449 }
450
451 bool
452 pred_fprint (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
453 {
454   (void) &pathname;
455   (void) &stat_buf;
456
457   print_quoted (pred_ptr->args.printf_vec.stream,
458                 pred_ptr->args.printf_vec.quote_opts,
459                 pred_ptr->args.printf_vec.dest_is_tty,
460                 "%s\n",
461                 pathname);
462   return true;
463 }
464
465 bool
466 pred_fprint0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
467 {
468   FILE * fp = pred_ptr->args.printf_vec.stream;
469
470   (void) &stat_buf;
471
472   fputs (pathname, fp);
473   putc (0, fp);
474   return true;
475 }
476
477
478
479 bool
480 pred_fstype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
481 {
482   (void) pathname;
483
484   if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0)
485     return true;
486   else
487     return false;
488 }
489
490 bool
491 pred_gid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
492 {
493   (void) pathname;
494
495   switch (pred_ptr->args.numinfo.kind)
496     {
497     case COMP_GT:
498       if (stat_buf->st_gid > pred_ptr->args.numinfo.l_val)
499         return (true);
500       break;
501     case COMP_LT:
502       if (stat_buf->st_gid < pred_ptr->args.numinfo.l_val)
503         return (true);
504       break;
505     case COMP_EQ:
506       if (stat_buf->st_gid == pred_ptr->args.numinfo.l_val)
507         return (true);
508       break;
509     }
510   return (false);
511 }
512
513 bool
514 pred_group (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
515 {
516   (void) pathname;
517
518   if (pred_ptr->args.gid == stat_buf->st_gid)
519     return (true);
520   else
521     return (false);
522 }
523
524 bool
525 pred_ilname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
526 {
527   return match_lname (pathname, stat_buf, pred_ptr, true);
528 }
529
530 /* Common code between -name, -iname.  PATHNAME is being visited, STR
531    is name to compare basename against, and FLAGS are passed to
532    fnmatch.  Recall that 'find / -name /' is one of the few times where a '/'
533    in the -name must actually find something. */
534 static bool
535 pred_name_common (const char *pathname, const char *str, int flags)
536 {
537   bool b;
538   /* We used to use last_component() here, but that would not allow us to modify the
539    * input string, which is const.   We could optimise by duplicating the string only
540    * if we need to modify it, and I'll do that if there is a measurable
541    * performance difference on a machine built after 1990...
542    */
543   char *base = base_name (pathname);
544   /* remove trailing slashes, but leave  "/" or "//foo" unchanged. */
545   strip_trailing_slashes (base);
546
547   /* FNM_PERIOD is not used here because POSIX requires that it not be.
548    * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
549    */
550   b = fnmatch (str, base, flags) == 0;
551   free (base);
552   return b;
553 }
554
555 bool
556 pred_iname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
557 {
558   (void) stat_buf;
559   return pred_name_common (pathname, pred_ptr->args.str, FNM_CASEFOLD);
560 }
561
562 bool
563 pred_inum (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
564 {
565   (void) pathname;
566
567   assert (stat_buf->st_ino != 0);
568
569   switch (pred_ptr->args.numinfo.kind)
570     {
571     case COMP_GT:
572       if (stat_buf->st_ino > pred_ptr->args.numinfo.l_val)
573         return (true);
574       break;
575     case COMP_LT:
576       if (stat_buf->st_ino < pred_ptr->args.numinfo.l_val)
577         return (true);
578       break;
579     case COMP_EQ:
580       if (stat_buf->st_ino == pred_ptr->args.numinfo.l_val)
581         return (true);
582       break;
583     }
584   return (false);
585 }
586
587 bool
588 pred_ipath (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
589 {
590   (void) stat_buf;
591
592   if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0)
593     return (true);
594   return (false);
595 }
596
597 bool
598 pred_links (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
599 {
600   (void) pathname;
601
602   switch (pred_ptr->args.numinfo.kind)
603     {
604     case COMP_GT:
605       if (stat_buf->st_nlink > pred_ptr->args.numinfo.l_val)
606         return (true);
607       break;
608     case COMP_LT:
609       if (stat_buf->st_nlink < pred_ptr->args.numinfo.l_val)
610         return (true);
611       break;
612     case COMP_EQ:
613       if (stat_buf->st_nlink == pred_ptr->args.numinfo.l_val)
614         return (true);
615       break;
616     }
617   return (false);
618 }
619
620 bool
621 pred_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
622 {
623   return match_lname (pathname, stat_buf, pred_ptr, false);
624 }
625
626 static bool
627 match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, bool ignore_case)
628 {
629   bool ret = false;
630 #ifdef S_ISLNK
631   if (S_ISLNK (stat_buf->st_mode))
632     {
633       char *linkname = areadlinkat (state.cwd_dir_fd, state.rel_pathname);
634       if (linkname)
635         {
636           if (fnmatch (pred_ptr->args.str, linkname,
637                        ignore_case ? FNM_CASEFOLD : 0) == 0)
638             ret = true;
639         }
640       else
641         {
642           nonfatal_target_file_error (errno, pathname);
643           state.exit_status = 1;
644         }
645       free (linkname);
646     }
647 #endif /* S_ISLNK */
648   return ret;
649 }
650
651 bool
652 pred_ls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
653 {
654   return pred_fls (pathname, stat_buf, pred_ptr);
655 }
656
657 bool
658 pred_mmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
659 {
660   (void) &pathname;
661   return pred_timewindow (get_stat_mtime(stat_buf), pred_ptr, 60);
662 }
663
664 bool
665 pred_mtime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
666 {
667   (void) pathname;
668   return pred_timewindow (get_stat_mtime(stat_buf), pred_ptr, DAYSECS);
669 }
670
671 bool
672 pred_name (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
673 {
674   (void) stat_buf;
675   return pred_name_common (pathname, pred_ptr->args.str, 0);
676 }
677
678 bool
679 pred_negate (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
680 {
681   return !apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
682 }
683
684 bool
685 pred_newer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
686 {
687   (void) pathname;
688
689   assert (COMP_GT == pred_ptr->args.reftime.kind);
690   return compare_ts (get_stat_mtime(stat_buf), pred_ptr->args.reftime.ts) > 0;
691 }
692
693 bool
694 pred_newerXY (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
695 {
696   struct timespec ts;
697   bool collected = false;
698
699   assert (COMP_GT == pred_ptr->args.reftime.kind);
700
701   switch (pred_ptr->args.reftime.xval)
702     {
703     case XVAL_TIME:
704       assert (pred_ptr->args.reftime.xval != XVAL_TIME);
705       return false;
706
707     case XVAL_ATIME:
708       ts = get_stat_atime (stat_buf);
709       collected = true;
710       break;
711
712     case XVAL_BIRTHTIME:
713       ts = get_stat_birthtime (stat_buf);
714       collected = true;
715       if (ts.tv_nsec < 0)
716         {
717           /* XXX: Cannot determine birth time.  Warn once. */
718           error (0, 0, _("WARNING: cannot determine birth time of file %s"),
719                  safely_quote_err_filename (0, pathname));
720           return false;
721         }
722       break;
723
724     case XVAL_CTIME:
725       ts = get_stat_ctime (stat_buf);
726       collected = true;
727       break;
728
729     case XVAL_MTIME:
730       ts = get_stat_mtime (stat_buf);
731       collected = true;
732       break;
733     }
734
735   assert (collected);
736   return compare_ts (ts, pred_ptr->args.reftime.ts) > 0;
737 }
738
739 bool
740 pred_nogroup (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
741 {
742   (void) pathname;
743   (void) pred_ptr;
744
745 #ifdef CACHE_IDS
746   extern char *gid_unused;
747
748   return gid_unused[(unsigned) stat_buf->st_gid];
749 #else
750   return getgrgid (stat_buf->st_gid) == NULL;
751 #endif
752 }
753
754 bool
755 pred_nouser (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
756 {
757 #ifdef CACHE_IDS
758   extern char *uid_unused;
759 #endif
760
761   (void) pathname;
762   (void) pred_ptr;
763
764 #ifdef CACHE_IDS
765   return uid_unused[(unsigned) stat_buf->st_uid];
766 #else
767   return getpwuid (stat_buf->st_uid) == NULL;
768 #endif
769 }
770
771
772 static bool
773 is_ok (const char *program, const char *arg)
774 {
775   fflush (stdout);
776   /* The draft open standard requires that, in the POSIX locale,
777      the last non-blank character of this prompt be '?'.
778      The exact format is not specified.
779      This standard does not have requirements for locales other than POSIX
780   */
781   /* XXX: printing UNTRUSTED data here. */
782   if (fprintf (stderr, _("< %s ... %s > ? "), program, arg) < 0)
783     {
784       error (EXIT_FAILURE, errno, _("Failed to write prompt for -ok"));
785     }
786   fflush (stderr);
787   return yesno ();
788 }
789
790 bool
791 pred_ok (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
792 {
793   if (is_ok (pred_ptr->args.exec_vec.replace_vec[0], pathname))
794     return impl_pred_exec (pathname, stat_buf, pred_ptr);
795   else
796     return false;
797 }
798
799 bool
800 pred_okdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
801 {
802   if (is_ok (pred_ptr->args.exec_vec.replace_vec[0], pathname))
803     return impl_pred_exec (state.rel_pathname, stat_buf, pred_ptr);
804   else
805     return false;
806 }
807
808 bool
809 pred_openparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
810 {
811   (void) pathname;
812   (void) stat_buf;
813   (void) pred_ptr;
814   return true;
815 }
816
817 bool
818 pred_or (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
819 {
820   if (pred_ptr->pred_left == NULL
821       || !apply_predicate (pathname, stat_buf, pred_ptr->pred_left))
822     {
823       return apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
824     }
825   else
826     return true;
827 }
828
829 bool
830 pred_path (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
831 {
832   (void) stat_buf;
833   if (fnmatch (pred_ptr->args.str, pathname, 0) == 0)
834     return (true);
835   return (false);
836 }
837
838 bool
839 pred_perm (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
840 {
841   mode_t mode = stat_buf->st_mode;
842   mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0];
843   (void) pathname;
844   switch (pred_ptr->args.perm.kind)
845     {
846     case PERM_AT_LEAST:
847       return (mode & perm_val) == perm_val;
848       break;
849
850     case PERM_ANY:
851       /* True if any of the bits set in the mask are also set in the file's mode.
852        *
853        *
854        * Otherwise, if onum is prefixed by a hyphen, the primary shall
855        * evaluate as true if at least all of the bits specified in
856        * onum that are also set in the octal mask 07777 are set.
857        *
858        * Eric Blake's interpretation is that the mode argument is zero,
859
860        */
861       if (0 == perm_val)
862         return true;            /* Savannah bug 14748; we used to return false */
863       else
864         return (mode & perm_val) != 0;
865       break;
866
867     case PERM_EXACT:
868       return (mode & MODE_ALL) == perm_val;
869       break;
870
871     default:
872       abort ();
873       break;
874     }
875 }
876
877
878 bool
879 pred_executable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
880 {
881   (void) pathname;
882   (void) stat_buf;
883   (void) pred_ptr;
884
885   /* As for access, the check is performed with the real user id. */
886   return 0 == faccessat (state.cwd_dir_fd, state.rel_pathname, X_OK, 0);
887 }
888
889 bool
890 pred_readable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
891 {
892   (void) pathname;
893   (void) stat_buf;
894   (void) pred_ptr;
895
896   /* As for access, the check is performed with the real user id. */
897   return 0 == faccessat (state.cwd_dir_fd, state.rel_pathname, R_OK, 0);
898 }
899
900 bool
901 pred_writable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
902 {
903   (void) pathname;
904   (void) stat_buf;
905   (void) pred_ptr;
906
907   /* As for access, the check is performed with the real user id. */
908   return 0 == faccessat (state.cwd_dir_fd, state.rel_pathname, W_OK, 0);
909 }
910
911 bool
912 pred_print (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
913 {
914   (void) stat_buf;
915   (void) pred_ptr;
916
917   print_quoted (pred_ptr->args.printf_vec.stream,
918                 pred_ptr->args.printf_vec.quote_opts,
919                 pred_ptr->args.printf_vec.dest_is_tty,
920                 "%s\n", pathname);
921   return true;
922 }
923
924 bool
925 pred_print0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
926 {
927   return pred_fprint0(pathname, stat_buf, pred_ptr);
928 }
929
930 bool
931 pred_prune (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
932 {
933   (void) pathname;
934   (void) pred_ptr;
935
936   if (options.do_dir_first == true) { /* no effect with -depth */
937     assert (state.have_stat);
938     if (stat_buf != NULL &&
939         S_ISDIR(stat_buf->st_mode))
940       state.stop_at_current_level = true;
941   }
942
943   /* findutils used to return options.do_dir_first here, so that -prune
944    * returns true only if -depth is not in effect.   But POSIX requires
945    * that -prune always evaluate as true.
946    */
947   return true;
948 }
949
950 bool
951 pred_quit (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
952 {
953   (void) pathname;
954   (void) stat_buf;
955   (void) pred_ptr;
956
957   /* Run any cleanups.  This includes executing any command lines
958    * we have partly built but not executed.
959    */
960   cleanup ();
961
962   /* Since -exec and friends don't leave child processes running in the
963    * background, there is no need to wait for them here.
964    */
965   exit (state.exit_status);     /* 0 for success, etc. */
966 }
967
968 bool
969 pred_regex (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
970 {
971   int len = strlen (pathname);
972 (void) stat_buf;
973   if (re_match (pred_ptr->args.regex, pathname, len, 0,
974                 (struct re_registers *) NULL) == len)
975     return (true);
976   return (false);
977 }
978
979 bool
980 pred_size (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
981 {
982   uintmax_t f_val;
983
984   (void) pathname;
985   f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize)
986            + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0));
987   switch (pred_ptr->args.size.kind)
988     {
989     case COMP_GT:
990       if (f_val > pred_ptr->args.size.size)
991         return (true);
992       break;
993     case COMP_LT:
994       if (f_val < pred_ptr->args.size.size)
995         return (true);
996       break;
997     case COMP_EQ:
998       if (f_val == pred_ptr->args.size.size)
999         return (true);
1000       break;
1001     }
1002   return (false);
1003 }
1004
1005 bool
1006 pred_samefile (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1007 {
1008   /* Potential optimisation: because of the loop protection, we always
1009    * know the device of the current directory, hence the device number
1010    * of the file we're currently considering.  If -L is not in effect,
1011    * and the device number of the file we're looking for is not the
1012    * same as the device number of the current directory, this
1013    * predicate cannot return true.  Hence there would be no need to
1014    * stat the file we're looking at.
1015    *
1016    * For the moment, we simply compare inode numbers, which should cut
1017    * down greatly on the number of calls to stat.  Some of the
1018    * remainder will be unnecessary, but the additional complexity
1019    * probably isn't worthwhile.
1020    */
1021   (void) pathname;
1022
1023   /* We will often still have an fd open on the file under consideration,
1024    * but that's just to ensure inode number stability by maintaining
1025    * a reference to it; we don't need the file for anything else.
1026    */
1027   if (stat_buf->st_ino)
1028     {
1029       if (stat_buf->st_ino != pred_ptr->args.samefileid.ino)
1030         return false;
1031     }
1032   /* Now stat the file to check the device number. */
1033   if (0 == get_statinfo (pathname, state.rel_pathname, stat_buf))
1034     {
1035       /* the repeated test here is necessary in case stat_buf.st_ino had been zero. */
1036       return stat_buf->st_ino == pred_ptr->args.samefileid.ino
1037         && stat_buf->st_dev == pred_ptr->args.samefileid.dev;
1038     }
1039   else
1040     {
1041       /* get_statinfo will already have emitted an error message. */
1042       return false;
1043     }
1044 }
1045
1046 bool
1047 pred_true (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1048 {
1049   (void) pathname;
1050   (void) stat_buf;
1051   (void) pred_ptr;
1052   return true;
1053 }
1054
1055 bool
1056 pred_type (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1057 {
1058   mode_t mode;
1059   mode_t type = pred_ptr->args.type;
1060
1061   assert (state.have_type);
1062
1063   if (0 == state.type)
1064     {
1065       /* This can sometimes happen with broken NFS servers.
1066        * See Savannah bug #16378.
1067        */
1068       return false;
1069     }
1070
1071   (void) pathname;
1072
1073   if (state.have_stat)
1074      mode = stat_buf->st_mode;
1075   else
1076      mode = state.type;
1077
1078 #ifndef S_IFMT
1079   /* POSIX system; check `mode' the slow way. */
1080   if ((S_ISBLK (mode) && type == S_IFBLK)
1081       || (S_ISCHR (mode) && type == S_IFCHR)
1082       || (S_ISDIR (mode) && type == S_IFDIR)
1083       || (S_ISREG (mode) && type == S_IFREG)
1084 #ifdef S_IFLNK
1085       || (S_ISLNK (mode) && type == S_IFLNK)
1086 #endif
1087 #ifdef S_IFIFO
1088       || (S_ISFIFO (mode) && type == S_IFIFO)
1089 #endif
1090 #ifdef S_IFSOCK
1091       || (S_ISSOCK (mode) && type == S_IFSOCK)
1092 #endif
1093 #ifdef S_IFDOOR
1094       || (S_ISDOOR (mode) && type == S_IFDOOR)
1095 #endif
1096       )
1097 #else /* S_IFMT */
1098   /* Unix system; check `mode' the fast way. */
1099   if ((mode & S_IFMT) == type)
1100 #endif /* S_IFMT */
1101     return (true);
1102   else
1103     return (false);
1104 }
1105
1106 bool
1107 pred_uid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1108 {
1109   (void) pathname;
1110   switch (pred_ptr->args.numinfo.kind)
1111     {
1112     case COMP_GT:
1113       if (stat_buf->st_uid > pred_ptr->args.numinfo.l_val)
1114         return (true);
1115       break;
1116     case COMP_LT:
1117       if (stat_buf->st_uid < pred_ptr->args.numinfo.l_val)
1118         return (true);
1119       break;
1120     case COMP_EQ:
1121       if (stat_buf->st_uid == pred_ptr->args.numinfo.l_val)
1122         return (true);
1123       break;
1124     }
1125   return (false);
1126 }
1127
1128 bool
1129 pred_used (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1130 {
1131   struct timespec delta, at, ct;
1132
1133   (void) pathname;
1134
1135   /* TODO: this needs to be retested carefully (manually, if necessary) */
1136   at = get_stat_atime (stat_buf);
1137   ct = get_stat_ctime (stat_buf);
1138   delta.tv_sec  = at.tv_sec  - ct.tv_sec;
1139   delta.tv_nsec = at.tv_nsec - ct.tv_nsec;
1140   if (delta.tv_nsec < 0)
1141     {
1142       delta.tv_nsec += 1000000000;
1143       delta.tv_sec  -=          1;
1144     }
1145   return pred_timewindow (delta, pred_ptr, DAYSECS);
1146 }
1147
1148 bool
1149 pred_user (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1150 {
1151   (void) pathname;
1152   if (pred_ptr->args.uid == stat_buf->st_uid)
1153     return (true);
1154   else
1155     return (false);
1156 }
1157
1158 bool
1159 pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1160 {
1161   struct stat sbuf;             /* local copy, not stat_buf because we're using a different stat method */
1162   int (*ystat) (const char*, struct stat *p);
1163
1164   /* If we would normally stat the link itself, stat the target instead.
1165    * If we would normally follow the link, stat the link itself instead.
1166    */
1167   if (following_links ())
1168     ystat = optionp_stat;
1169   else
1170     ystat = optionl_stat;
1171
1172   set_stat_placeholders (&sbuf);
1173   if ((*ystat) (state.rel_pathname, &sbuf) != 0)
1174     {
1175       if (following_links () && errno == ENOENT)
1176         {
1177           /* If we failed to follow the symlink,
1178            * fall back on looking at the symlink itself.
1179            */
1180           /* Mimic behavior of ls -lL. */
1181           return (pred_type (pathname, stat_buf, pred_ptr));
1182         }
1183       else
1184         {
1185           error (0, errno, "%s", safely_quote_err_filename (0, pathname));
1186           state.exit_status = 1;
1187         }
1188       return false;
1189     }
1190   /* Now that we have our stat() information, query it in the same
1191    * way that -type does.
1192    */
1193   return (pred_type (pathname, &sbuf, pred_ptr));
1194 }
1195
1196
1197 bool
1198 pred_context (const char *pathname, struct stat *stat_buf,
1199               struct predicate *pred_ptr)
1200 {
1201   security_context_t scontext;
1202   int rv = (*options.x_getfilecon) (state.cwd_dir_fd, state.rel_pathname,
1203                                     &scontext);
1204   (void) stat_buf;
1205
1206   if (rv < 0)
1207     {
1208       error (0, errno, _("getfilecon failed: %s"),
1209              safely_quote_err_filename (0, pathname));
1210       return false;
1211     }
1212
1213   rv = (fnmatch (pred_ptr->args.scontext, scontext, 0) == 0);
1214   freecon (scontext);
1215   return rv;
1216 }
1217
1218 /* Copy STR into BUF and trim blanks from the end of BUF.
1219    Return BUF. */
1220
1221 static char *
1222 blank_rtrim (const char *str, char *buf)
1223 {
1224   int i;
1225
1226   if (str == NULL)
1227     return (NULL);
1228   strcpy (buf, str);
1229   i = strlen (buf) - 1;
1230   while ((i >= 0) && ((buf[i] == ' ') || buf[i] == '\t'))
1231     i--;
1232   buf[++i] = '\0';
1233   return buf;
1234 }
1235
1236 /* Print out the predicate list starting at NODE. */
1237 void
1238 print_list (FILE *fp, struct predicate *node)
1239 {
1240   struct predicate *cur;
1241   char name[256];
1242
1243   cur = node;
1244   while (cur != NULL)
1245     {
1246       fprintf (fp, "[%s] ", blank_rtrim (cur->p_name, name));
1247       cur = cur->pred_next;
1248     }
1249   fprintf (fp, "\n");
1250 }
1251
1252 /* Print out the predicate list starting at NODE. */
1253 static void
1254 print_parenthesised (FILE *fp, struct predicate *node)
1255 {
1256   int parens = 0;
1257
1258   if (node)
1259     {
1260       if ((pred_is (node, pred_or) || pred_is (node, pred_and))
1261           && node->pred_left == NULL)
1262         {
1263           /* We print "<nothing> or  X" as just "X"
1264            * We print "<nothing> and X" as just "X"
1265            */
1266           print_parenthesised(fp, node->pred_right);
1267         }
1268       else
1269         {
1270           if (node->pred_left || node->pred_right)
1271             parens = 1;
1272
1273           if (parens)
1274             fprintf (fp, "%s", " ( ");
1275           print_optlist (fp, node);
1276           if (parens)
1277             fprintf (fp, "%s", " ) ");
1278         }
1279     }
1280 }
1281
1282 void
1283 print_optlist (FILE *fp, const struct predicate *p)
1284 {
1285   if (p)
1286     {
1287       print_parenthesised (fp, p->pred_left);
1288       fprintf (fp,
1289                "%s%s%s",
1290                p->need_stat ? "[call stat] " : "",
1291                p->need_type ? "[need type] " : "",
1292                p->need_inum ? "[need inum] " : "");
1293       print_predicate (fp, p);
1294       fprintf (fp, " [%g] ", p->est_success_rate);
1295       if (options.debug_options & DebugSuccessRates)
1296         {
1297           fprintf (fp, "[%ld/%ld", p->perf.successes, p->perf.visits);
1298           if (p->perf.visits)
1299             {
1300               double real_rate = (double)p->perf.successes / (double)p->perf.visits;
1301               fprintf (fp, "=%g] ", real_rate);
1302             }
1303           else
1304             {
1305               fprintf (fp, "=_] ");
1306             }
1307         }
1308       print_parenthesised (fp, p->pred_right);
1309     }
1310 }
1311
1312 void show_success_rates (const struct predicate *p)
1313 {
1314   if (options.debug_options & DebugSuccessRates)
1315     {
1316       fprintf (stderr, "Predicate success rates after completion:\n");
1317       print_optlist (stderr, p);
1318       fprintf (stderr, "\n");
1319     }
1320 }
1321
1322
1323
1324
1325 #ifdef _NDEBUG
1326 /* If _NDEBUG is defined, the assertions will do nothing.   Hence
1327  * there is no point in having a function body for pred_sanity_check()
1328  * if that preprocessor macro is defined.
1329  */
1330 void
1331 pred_sanity_check (const struct predicate *predicates)
1332 {
1333   /* Do nothing, since assert is a no-op with _NDEBUG set */
1334   return;
1335 }
1336 #else
1337 void
1338 pred_sanity_check (const struct predicate *predicates)
1339 {
1340   const struct predicate *p;
1341
1342   for (p=predicates; p != NULL; p=p->pred_next)
1343     {
1344       /* All predicates must do something. */
1345       assert (p->pred_func != NULL);
1346
1347       /* All predicates must have a parser table entry. */
1348       assert (p->parser_entry != NULL);
1349
1350       /* If the parser table tells us that just one predicate function is
1351        * possible, verify that that is still the one that is in effect.
1352        * If the parser has NULL for the predicate function, that means that
1353        * the parse_xxx function fills it in, so we can't check it.
1354        */
1355       if (p->parser_entry->pred_func)
1356         {
1357           assert (p->parser_entry->pred_func == p->pred_func);
1358         }
1359
1360       switch (p->parser_entry->type)
1361         {
1362           /* Options all take effect during parsing, so there should
1363            * be no predicate entries corresponding to them.  Hence we
1364            * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION
1365            * items.
1366            *
1367            * This is a silly way of coding this test, but it prevents
1368            * a compiler warning (i.e. otherwise it would think that
1369            * there would be case statements missing).
1370            */
1371         case ARG_OPTION:
1372         case ARG_POSITIONAL_OPTION:
1373           assert (p->parser_entry->type != ARG_OPTION);
1374           assert (p->parser_entry->type != ARG_POSITIONAL_OPTION);
1375           break;
1376
1377         case ARG_ACTION:
1378           assert (p->side_effects); /* actions have side effects. */
1379           if (!pred_is (p, pred_prune) && !pred_is(p, pred_quit))
1380             {
1381               /* actions other than -prune and -quit should
1382                * inhibit the default -print
1383                */
1384               assert (p->no_default_print);
1385             }
1386           break;
1387
1388         /* We happen to know that the only user of ARG_SPECIAL_PARSE
1389          * is a test, so handle it like ARG_TEST.
1390          */
1391         case ARG_SPECIAL_PARSE:
1392         case ARG_TEST:
1393         case ARG_PUNCTUATION:
1394         case ARG_NOOP:
1395           /* Punctuation and tests should have no side
1396            * effects and not inhibit default print.
1397            */
1398           assert (!p->no_default_print);
1399           assert (!p->side_effects);
1400           break;
1401         }
1402     }
1403 }
1404 #endif