Imported Upstream version 4.5.10
[platform/upstream/findutils.git] / find / pred.c
1 /* pred.c -- execute the expression tree.
2    Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2003,
3                  2004, 2005, 2006, 2007, 2008, 2009,
4                  2010 Free Software Foundation, Inc.
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation, either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <config.h>
21 #include "defs.h"
22
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 <errno.h>
31 #include <assert.h>
32 #include <stdarg.h>
33 #include <fcntl.h>
34 #include <locale.h>
35 #include <ctype.h>
36 #include <unistd.h> /* for unlinkat() */
37 #include "xalloc.h"
38 #include "dirname.h"
39 #include "human.h"
40 #include "filemode.h"
41 #include "printquoted.h"
42 #include "buildcmd.h"
43 #include "yesno.h"
44 #include "listfile.h"
45 #include "stat-time.h"
46 #include "dircallback.h"
47 #include "error.h"
48 #include "verify.h"
49 #include "fdleak.h"
50 #include "areadlink.h"
51 #include "cloexec.h"
52 #include "save-cwd.h"
53
54 #include <selinux/selinux.h>
55
56 #if ENABLE_NLS
57 # include <libintl.h>
58 # define _(Text) gettext (Text)
59 #else
60 # define _(Text) Text
61 #endif
62 #ifdef gettext_noop
63 # define N_(String) gettext_noop (String)
64 #else
65 /* See locate.c for explanation as to why not use (String) */
66 # define N_(String) String
67 #endif
68
69 #if !defined(SIGCHLD) && defined(SIGCLD)
70 #define SIGCHLD SIGCLD
71 #endif
72
73
74 #include <sys/wait.h>
75
76 #if HAVE_DIRENT_H
77 # include <dirent.h>
78 # define NAMLEN(dirent) strlen((dirent)->d_name)
79 #else
80 # define dirent direct
81 # define NAMLEN(dirent) (dirent)->d_namlen
82 # if HAVE_SYS_NDIR_H
83 #  include <sys/ndir.h>
84 # endif
85 # if HAVE_SYS_DIR_H
86 #  include <sys/dir.h>
87 # endif
88 # if HAVE_NDIR_H
89 #  include <ndir.h>
90 # endif
91 #endif
92
93 #ifdef CLOSEDIR_VOID
94 /* Fake a return value. */
95 #define CLOSEDIR(d) (closedir (d), 0)
96 #else
97 #define CLOSEDIR(d) closedir (d)
98 #endif
99
100
101
102
103 /* Get or fake the disk device blocksize.
104    Usually defined by sys/param.h (if at all).  */
105 #ifndef DEV_BSIZE
106 # ifdef BSIZE
107 #  define DEV_BSIZE BSIZE
108 # else /* !BSIZE */
109 #  define DEV_BSIZE 4096
110 # endif /* !BSIZE */
111 #endif /* !DEV_BSIZE */
112
113 /* Extract or fake data from a `struct stat'.
114    ST_BLKSIZE: Preferred I/O blocksize for the file, in bytes.
115    ST_NBLOCKS: Number of blocks in the file, including indirect blocks.
116    ST_NBLOCKSIZE: Size of blocks used when calculating ST_NBLOCKS.  */
117 #ifndef HAVE_STRUCT_STAT_ST_BLOCKS
118 # define ST_BLKSIZE(statbuf) DEV_BSIZE
119 # if defined _POSIX_SOURCE || !defined BSIZE /* fileblocks.c uses BSIZE.  */
120 #  define ST_NBLOCKS(statbuf) \
121   (S_ISREG ((statbuf).st_mode) \
122    || S_ISDIR ((statbuf).st_mode) \
123    ? (statbuf).st_size / ST_NBLOCKSIZE + ((statbuf).st_size % ST_NBLOCKSIZE != 0) : 0)
124 # else /* !_POSIX_SOURCE && BSIZE */
125 #  define ST_NBLOCKS(statbuf) \
126   (S_ISREG ((statbuf).st_mode) \
127    || S_ISDIR ((statbuf).st_mode) \
128    ? st_blocks ((statbuf).st_size) : 0)
129 # endif /* !_POSIX_SOURCE && BSIZE */
130 #else /* HAVE_STRUCT_STAT_ST_BLOCKS */
131 /* Some systems, like Sequents, return st_blksize of 0 on pipes. */
132 # define ST_BLKSIZE(statbuf) ((statbuf).st_blksize > 0 \
133                                ? (statbuf).st_blksize : DEV_BSIZE)
134 # if defined hpux || defined __hpux__ || defined __hpux
135 /* HP-UX counts st_blocks in 1024-byte units.
136    This loses when mixing HP-UX and BSD file systems with NFS.  */
137 #  define ST_NBLOCKSIZE 1024
138 # else /* !hpux */
139 #  if defined _AIX && defined _I386
140 /* AIX PS/2 counts st_blocks in 4K units.  */
141 #   define ST_NBLOCKSIZE (4 * 1024)
142 #  else /* not AIX PS/2 */
143 #   if defined _CRAY
144 #    define ST_NBLOCKS(statbuf) \
145   (S_ISREG ((statbuf).st_mode) \
146    || S_ISDIR ((statbuf).st_mode) \
147    ? (statbuf).st_blocks * ST_BLKSIZE(statbuf)/ST_NBLOCKSIZE : 0)
148 #   endif /* _CRAY */
149 #  endif /* not AIX PS/2 */
150 # endif /* !hpux */
151 #endif /* HAVE_STRUCT_STAT_ST_BLOCKS */
152
153 #ifndef ST_NBLOCKS
154 # define ST_NBLOCKS(statbuf) \
155   (S_ISREG ((statbuf).st_mode) \
156    || S_ISDIR ((statbuf).st_mode) \
157    ? (statbuf).st_blocks : 0)
158 #endif
159
160 #ifndef ST_NBLOCKSIZE
161 # define ST_NBLOCKSIZE 512
162 #endif
163
164
165 #undef MAX
166 #define MAX(a, b) ((a) > (b) ? (a) : (b))
167
168 static bool match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, bool ignore_case);
169
170 static char *format_date (struct timespec ts, int kind);
171 static char *ctime_format (struct timespec ts);
172
173 #ifdef  DEBUG
174 struct pred_assoc
175 {
176   PRED_FUNC pred_func;
177   char *pred_name;
178 };
179
180 struct pred_assoc pred_table[] =
181 {
182   {pred_amin, "amin    "},
183   {pred_and, "and     "},
184   {pred_anewer, "anewer  "},
185   {pred_atime, "atime   "},
186   {pred_closeparen, ")       "},
187   {pred_cmin, "cmin    "},
188   {pred_cnewer, "cnewer  "},
189   {pred_comma, ",       "},
190   {pred_ctime, "ctime   "},
191   {pred_delete, "delete  "},
192   {pred_empty, "empty   "},
193   {pred_exec, "exec    "},
194   {pred_execdir, "execdir "},
195   {pred_executable, "executable "},
196   {pred_false, "false   "},
197   {pred_fprint, "fprint  "},
198   {pred_fprint0, "fprint0 "},
199   {pred_fprintf, "fprintf "},
200   {pred_fstype, "fstype  "},
201   {pred_gid, "gid     "},
202   {pred_group, "group   "},
203   {pred_ilname, "ilname  "},
204   {pred_iname, "iname   "},
205   {pred_inum, "inum    "},
206   {pred_ipath, "ipath   "},
207   {pred_links, "links   "},
208   {pred_lname, "lname   "},
209   {pred_ls, "ls      "},
210   {pred_mmin, "mmin    "},
211   {pred_mtime, "mtime   "},
212   {pred_name, "name    "},
213   {pred_negate, "not     "},
214   {pred_newer, "newer   "},
215   {pred_newerXY, "newerXY   "},
216   {pred_nogroup, "nogroup "},
217   {pred_nouser, "nouser  "},
218   {pred_ok, "ok      "},
219   {pred_okdir, "okdir   "},
220   {pred_openparen, "(       "},
221   {pred_or, "or      "},
222   {pred_path, "path    "},
223   {pred_perm, "perm    "},
224   {pred_print, "print   "},
225   {pred_print0, "print0  "},
226   {pred_prune, "prune   "},
227   {pred_quit, "quit    "},
228   {pred_readable, "readable    "},
229   {pred_regex, "regex   "},
230   {pred_samefile,"samefile "},
231   {pred_size, "size    "},
232   {pred_true, "true    "},
233   {pred_type, "type    "},
234   {pred_uid, "uid     "},
235   {pred_used, "used    "},
236   {pred_user, "user    "},
237   {pred_writable, "writable "},
238   {pred_xtype, "xtype   "},
239   {pred_context, "context"},
240   {0, "none    "}
241 };
242 #endif
243
244 /* Returns ts1 - ts2 */
245 static double ts_difference (struct timespec ts1,
246                              struct timespec ts2)
247 {
248   double d =  difftime (ts1.tv_sec, ts2.tv_sec)
249     + (1.0e-9 * (ts1.tv_nsec - ts2.tv_nsec));
250   return d;
251 }
252
253
254 static int
255 compare_ts (struct timespec ts1,
256             struct timespec ts2)
257 {
258   if ((ts1.tv_sec == ts2.tv_sec) &&
259       (ts1.tv_nsec == ts2.tv_nsec))
260     {
261       return 0;
262     }
263   else
264     {
265       double diff = ts_difference (ts1, ts2);
266       return diff < 0.0 ? -1 : +1;
267     }
268 }
269
270 /* Predicate processing routines.
271
272    PATHNAME is the full pathname of the file being checked.
273    *STAT_BUF contains information about PATHNAME.
274    *PRED_PTR contains information for applying the predicate.
275
276    Return true if the file passes this predicate, false if not. */
277
278
279 /* pred_timewindow
280  *
281  * Returns true if THE_TIME is
282  * COMP_GT: after the specified time
283  * COMP_LT: before the specified time
284  * COMP_EQ: after the specified time but by not more than WINDOW seconds.
285  */
286 static bool
287 pred_timewindow (struct timespec ts, struct predicate const *pred_ptr, int window)
288 {
289   switch (pred_ptr->args.reftime.kind)
290     {
291     case COMP_GT:
292       return compare_ts (ts, pred_ptr->args.reftime.ts) > 0;
293
294     case COMP_LT:
295       return compare_ts (ts, pred_ptr->args.reftime.ts) < 0;
296
297     case COMP_EQ:
298       {
299         /* consider "find . -mtime 0".
300          *
301          * Here, the origin is exactly 86400 seconds before the start
302          * of the program (since -daystart was not specified).   This
303          * function will be called with window=86400 and
304          * pred_ptr->args.reftime.ts as the origin.  Hence a file
305          * created the instant the program starts will show a time
306          * difference (value of delta) of 86400.   Similarly, a file
307          * created exactly 24h ago would be the newest file which was
308          * _not_ created today.   So, if delta is 0.0, the file
309          * was not created today.  If the delta is 86400, the file
310          * was created this instant.
311          */
312         double delta = ts_difference (ts, pred_ptr->args.reftime.ts);
313         return (delta > 0.0 && delta <= window);
314       }
315     }
316   assert (0);
317   abort ();
318 }
319
320
321 bool
322 pred_amin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
323 {
324   (void) &pathname;
325   return pred_timewindow (get_stat_atime(stat_buf), pred_ptr, 60);
326 }
327
328 bool
329 pred_and (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
330 {
331   if (pred_ptr->pred_left == NULL
332       || apply_predicate (pathname, stat_buf, pred_ptr->pred_left))
333     {
334       return apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
335     }
336   else
337     return false;
338 }
339
340 bool
341 pred_anewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
342 {
343   (void) &pathname;
344   assert (COMP_GT == pred_ptr->args.reftime.kind);
345   return compare_ts (get_stat_atime(stat_buf), pred_ptr->args.reftime.ts) > 0;
346 }
347
348 bool
349 pred_atime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
350 {
351   (void) &pathname;
352   return pred_timewindow (get_stat_atime(stat_buf), pred_ptr, DAYSECS);
353 }
354
355 bool
356 pred_closeparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
357 {
358   (void) &pathname;
359   (void) &stat_buf;
360   (void) &pred_ptr;
361
362   return true;
363 }
364
365 bool
366 pred_cmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
367 {
368   (void) pathname;
369   return pred_timewindow (get_stat_ctime(stat_buf), pred_ptr, 60);
370 }
371
372 bool
373 pred_cnewer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
374 {
375   (void) pathname;
376
377   assert (COMP_GT == pred_ptr->args.reftime.kind);
378   return compare_ts (get_stat_ctime(stat_buf), pred_ptr->args.reftime.ts) > 0;
379 }
380
381 bool
382 pred_comma (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
383 {
384   if (pred_ptr->pred_left != NULL)
385     {
386       apply_predicate (pathname, stat_buf,pred_ptr->pred_left);
387     }
388   return apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
389 }
390
391 bool
392 pred_ctime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
393 {
394   (void) &pathname;
395   return pred_timewindow (get_stat_ctime(stat_buf), pred_ptr, DAYSECS);
396 }
397
398 static bool
399 perform_delete (int flags)
400 {
401   return 0 == unlinkat (state.cwd_dir_fd, state.rel_pathname, flags);
402 }
403
404
405 bool
406 pred_delete (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
407 {
408   (void) pred_ptr;
409   (void) stat_buf;
410   if (strcmp (state.rel_pathname, "."))
411     {
412       int flags=0;
413       if (state.have_stat && S_ISDIR(stat_buf->st_mode))
414         flags |= AT_REMOVEDIR;
415       if (perform_delete (flags))
416         {
417           return true;
418         }
419       else
420         {
421           if (EISDIR == errno)
422             {
423               if ((flags & AT_REMOVEDIR) == 0)
424                 {
425                   /* unlink() operation failed because we should have done rmdir(). */
426                   flags |= AT_REMOVEDIR;
427                   if (perform_delete (flags))
428                     return true;
429                 }
430             }
431         }
432       error (0, errno, _("cannot delete %s"),
433              safely_quote_err_filename (0, pathname));
434       /* Previously I had believed that having the -delete action
435        * return false provided the user with control over whether an
436        * error message is issued.  While this is true, the policy of
437        * not affecting the exit status is contrary to the POSIX
438        * requirement that diagnostic messages are accompanied by a
439        * nonzero exit status.  While -delete is not a POSIX option and
440        * we can therefore opt not to follow POSIX in this case, that
441        * seems somewhat arbitrary and confusing.  So, as of
442        * findutils-4.3.11, we also set the exit status in this case.
443        */
444       state.exit_status = 1;
445       return false;
446     }
447   else
448     {
449       /* nothing to do. */
450       return true;
451     }
452 }
453
454 bool
455 pred_empty (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
456 {
457   (void) pathname;
458   (void) pred_ptr;
459
460   if (S_ISDIR (stat_buf->st_mode))
461     {
462       int fd;
463       DIR *d;
464       struct dirent *dp;
465       bool empty = true;
466
467       errno = 0;
468       if ((fd = openat (state.cwd_dir_fd, state.rel_pathname, O_RDONLY
469 #if defined O_LARGEFILE
470                         |O_LARGEFILE
471 #endif
472                        )) < 0)
473         {
474           error (0, errno, "%s", safely_quote_err_filename (0, pathname));
475           state.exit_status = 1;
476           return false;
477         }
478       d = fdopendir (fd);
479       if (d == NULL)
480         {
481           error (0, errno, "%s", safely_quote_err_filename (0, pathname));
482           state.exit_status = 1;
483           return false;
484         }
485       for (dp = readdir (d); dp; dp = readdir (d))
486         {
487           if (dp->d_name[0] != '.'
488               || (dp->d_name[1] != '\0'
489                   && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
490             {
491               empty = false;
492               break;
493             }
494         }
495       if (CLOSEDIR (d))
496         {
497           error (0, errno, "%s", safely_quote_err_filename (0, pathname));
498           state.exit_status = 1;
499           return false;
500         }
501       return (empty);
502     }
503   else if (S_ISREG (stat_buf->st_mode))
504     return (stat_buf->st_size == 0);
505   else
506     return (false);
507 }
508
509
510 /* Initialise exec->wd_for_exec.
511
512    We save in exec->wd_for_exec the directory whose path relative to
513    cwd_df is dir.
514  */
515 static bool
516 initialise_wd_for_exec (struct exec_val *execp, int cwd_fd, const char *dir)
517 {
518   execp->wd_for_exec = xmalloc (sizeof (*execp->wd_for_exec));
519   execp->wd_for_exec->name = NULL;
520   execp->wd_for_exec->desc = openat (cwd_fd, dir, O_RDONLY);
521   if (execp->wd_for_exec->desc < 0)
522     return false;
523   set_cloexec_flag (execp->wd_for_exec->desc, true);
524   return true;
525 }
526
527
528 static bool
529 record_exec_dir (struct exec_val *execp)
530 {
531   if (!execp->state.todo)
532     {
533       /* Record the WD. If we're using -L or fts chooses to do so for
534          any other reason, state.cwd_dir_fd may in fact not be the
535          directory containing the target file.  When this happens,
536          rel_path will contain directory components (since it is the
537          path from state.cwd_dir_fd to the target file).
538
539          We deal with this by extracting any directory part and using
540          that to adjust what goes into execp->wd_for_exec.
541       */
542       if (strchr (state.rel_pathname, '/'))
543         {
544           char *dir = mdir_name (state.rel_pathname);
545           bool result = initialise_wd_for_exec (execp, state.cwd_dir_fd, dir);
546           free (dir);
547           return result;
548         }
549       else
550         {
551           return initialise_wd_for_exec (execp, state.cwd_dir_fd, ".");
552         }
553     }
554   return true;
555 }
556
557
558 static bool
559 impl_pred_exec (const char *pathname,
560                 struct stat *stat_buf,
561                 struct predicate *pred_ptr)
562 {
563   struct exec_val *execp = &pred_ptr->args.exec_vec;
564   char *target;
565   bool result;
566   const bool local = is_exec_in_local_dir (pred_ptr->pred_func);
567   char *prefix;
568   size_t pfxlen;
569
570   (void) stat_buf;
571   if (local)
572     {
573       /* For -execdir/-okdir predicates, the parser did not fill in
574          the wd_for_exec member of sturct exec_val.  So for those
575          predicates, we do so now.
576       */
577       if (!record_exec_dir (execp))
578         {
579           error (EXIT_FAILURE, errno,
580                  _("Failed to save working directory in order to "
581                    "run a command on %s"),
582                  safely_quote_err_filename (0, pathname));
583           /*NOTREACHED*/
584         }
585       target = base_name (state.rel_pathname);
586       if ('/' == target[0])
587         {
588           /* find / execdir ls -d {} \; */
589           prefix = NULL;
590           pfxlen = 0;
591         }
592       else
593         {
594           prefix = "./";
595           pfxlen = 2u;
596         }
597     }
598   else
599     {
600       /* For the others (-exec, -ok), the parser should
601          have set wd_for_exec to initial_wd, indicating
602          that the exec should take place from find's initial
603          working directory.
604       */
605       assert (execp->wd_for_exec == initial_wd);
606       target = pathname;
607       prefix = NULL;
608       pfxlen = 0u;
609     }
610
611   if (execp->multiple)
612     {
613       /* Push the argument onto the current list.
614        * The command may or may not be run at this point,
615        * depending on the command line length limits.
616        */
617       bc_push_arg (&execp->ctl,
618                    &execp->state,
619                    target, strlen (target)+1,
620                    prefix, pfxlen,
621                    0);
622
623       /* remember that there are pending execdirs. */
624       state.execdirs_outstanding = true;
625
626       /* POSIX: If the primary expression is punctuated by a plus
627        * sign, the primary shall always evaluate as true
628        */
629       result = true;
630     }
631   else
632     {
633       int i;
634
635       for (i=0; i<execp->num_args; ++i)
636         {
637           bc_do_insert (&execp->ctl,
638                         &execp->state,
639                         execp->replace_vec[i],
640                         strlen (execp->replace_vec[i]),
641                         prefix, pfxlen,
642                         target, strlen (target),
643                         0);
644         }
645
646       /* Actually invoke the command. */
647       bc_do_exec (&execp->ctl, &execp->state);
648       if (WIFEXITED(execp->last_child_status))
649         {
650           if (0 == WEXITSTATUS(execp->last_child_status))
651             result = true;      /* The child succeeded. */
652           else
653             result = false;
654         }
655       else
656         {
657           result = false;
658         }
659     }
660   if (target != pathname)
661     {
662       assert (local);
663       free (target);
664     }
665   return result;
666 }
667
668
669 bool
670 pred_exec (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
671 {
672   return impl_pred_exec (pathname, stat_buf, pred_ptr);
673 }
674
675 bool
676 pred_execdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
677 {
678    (void) &pathname;
679    return impl_pred_exec (state.rel_pathname, stat_buf, pred_ptr);
680 }
681
682 bool
683 pred_false (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
684 {
685   (void) &pathname;
686   (void) &stat_buf;
687   (void) &pred_ptr;
688
689
690   return (false);
691 }
692
693 bool
694 pred_fls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
695 {
696   FILE * stream = pred_ptr->args.printf_vec.stream;
697   list_file (pathname, state.cwd_dir_fd, state.rel_pathname, stat_buf,
698              options.start_time.tv_sec,
699              options.output_block_size,
700              pred_ptr->literal_control_chars, stream);
701   return true;
702 }
703
704 bool
705 pred_fprint (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
706 {
707   (void) &pathname;
708   (void) &stat_buf;
709
710   print_quoted (pred_ptr->args.printf_vec.stream,
711                 pred_ptr->args.printf_vec.quote_opts,
712                 pred_ptr->args.printf_vec.dest_is_tty,
713                 "%s\n",
714                 pathname);
715   return true;
716 }
717
718 bool
719 pred_fprint0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
720 {
721   FILE * fp = pred_ptr->args.printf_vec.stream;
722
723   (void) &stat_buf;
724
725   fputs (pathname, fp);
726   putc (0, fp);
727   return true;
728 }
729
730
731
732 static char*
733 mode_to_filetype (mode_t m)
734 {
735 #define HANDLE_TYPE(t,letter) if (m==t) { return letter; }
736 #ifdef S_IFREG
737   HANDLE_TYPE(S_IFREG,  "f");   /* regular file */
738 #endif
739 #ifdef S_IFDIR
740   HANDLE_TYPE(S_IFDIR,  "d");   /* directory */
741 #endif
742 #ifdef S_IFLNK
743   HANDLE_TYPE(S_IFLNK,  "l");   /* symbolic link */
744 #endif
745 #ifdef S_IFSOCK
746   HANDLE_TYPE(S_IFSOCK, "s");   /* Unix domain socket */
747 #endif
748 #ifdef S_IFBLK
749   HANDLE_TYPE(S_IFBLK,  "b");   /* block device */
750 #endif
751 #ifdef S_IFCHR
752   HANDLE_TYPE(S_IFCHR,  "c");   /* character device */
753 #endif
754 #ifdef S_IFIFO
755   HANDLE_TYPE(S_IFIFO,  "p");   /* FIFO */
756 #endif
757 #ifdef S_IFDOOR
758   HANDLE_TYPE(S_IFDOOR, "D");   /* Door (e.g. on Solaris) */
759 #endif
760   return "U";                   /* Unknown */
761 }
762
763 static double
764 file_sparseness (const struct stat *p)
765 {
766 #if defined HAVE_STRUCT_STAT_ST_BLOCKS
767   if (0 == p->st_size)
768     {
769       if (0 == p->st_blocks)
770         return 1.0;
771       else
772         return p->st_blocks < 0 ? -HUGE_VAL : HUGE_VAL;
773     }
774   else
775     {
776       double blklen = file_blocksize (p) * (double)p->st_blocks;
777       return blklen / p->st_size;
778     }
779 #else
780   return 1.0;
781 #endif
782 }
783
784
785
786 static void
787 checked_fprintf (struct format_val *dest, const char *fmt, ...)
788 {
789   int rv;
790   va_list ap;
791
792   va_start (ap, fmt);
793   rv = vfprintf (dest->stream, fmt, ap);
794   if (rv < 0)
795     nonfatal_nontarget_file_error (errno, dest->filename);
796 }
797
798
799 static void
800 checked_print_quoted (struct format_val *dest,
801                            const char *format, const char *s)
802 {
803   int rv = print_quoted (dest->stream, dest->quote_opts, dest->dest_is_tty,
804                          format, s);
805   if (rv < 0)
806     nonfatal_nontarget_file_error (errno, dest->filename);
807 }
808
809
810 static void
811 checked_fwrite (void *p, size_t siz, size_t nmemb, struct format_val *dest)
812 {
813   int items_written = fwrite (p, siz, nmemb, dest->stream);
814   if (items_written < nmemb)
815     nonfatal_nontarget_file_error (errno, dest->filename);
816 }
817
818 static void
819 checked_fflush (struct format_val *dest)
820 {
821   if (0 != fflush (dest->stream))
822     {
823       nonfatal_nontarget_file_error (errno, dest->filename);
824     }
825 }
826
827 static void
828 do_fprintf (struct format_val *dest,
829             struct segment *segment,
830             const char *pathname,
831             const struct stat *stat_buf)
832 {
833   char hbuf[LONGEST_HUMAN_READABLE + 1];
834   const char *cp;
835
836   switch (segment->segkind)
837     {
838     case KIND_PLAIN:    /* Plain text string (no % conversion). */
839       /* trusted */
840       checked_fwrite(segment->text, 1, segment->text_len, dest);
841       break;
842
843     case KIND_STOP:             /* Terminate argument and flush output. */
844       /* trusted */
845       checked_fwrite (segment->text, 1, segment->text_len, dest);
846       checked_fflush (dest);
847       break;
848
849     case KIND_FORMAT:
850       switch (segment->format_char[0])
851         {
852         case 'a':               /* atime in `ctime' format. */
853           /* UNTRUSTED, probably unexploitable */
854           checked_fprintf (dest, segment->text, ctime_format (get_stat_atime (stat_buf)));
855           break;
856         case 'b':               /* size in 512-byte blocks */
857           /* UNTRUSTED, probably unexploitable */
858           checked_fprintf (dest, segment->text,
859                            human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
860                                            hbuf, human_ceiling,
861                                            ST_NBLOCKSIZE, 512));
862           break;
863         case 'c':               /* ctime in `ctime' format */
864           /* UNTRUSTED, probably unexploitable */
865           checked_fprintf (dest, segment->text, ctime_format (get_stat_ctime (stat_buf)));
866           break;
867         case 'd':               /* depth in search tree */
868           /* UNTRUSTED, probably unexploitable */
869           checked_fprintf (dest, segment->text, state.curdepth);
870           break;
871         case 'D':               /* Device on which file exists (stat.st_dev) */
872           /* trusted */
873           checked_fprintf (dest, segment->text,
874                            human_readable ((uintmax_t) stat_buf->st_dev, hbuf,
875                                            human_ceiling, 1, 1));
876           break;
877         case 'f':               /* base name of path */
878           /* sanitised */
879           {
880             char *base = base_name (pathname);
881             checked_print_quoted (dest, segment->text, base);
882             free (base);
883           }
884           break;
885         case 'F':               /* file system type */
886           /* trusted */
887           checked_print_quoted (dest, segment->text, filesystem_type (stat_buf, pathname));
888           break;
889         case 'g':               /* group name */
890           /* trusted */
891           /* (well, the actual group is selected by the user but
892            * its name was selected by the system administrator)
893            */
894           {
895             struct group *g;
896
897             g = getgrgid (stat_buf->st_gid);
898             if (g)
899               {
900                 segment->text[segment->text_len] = 's';
901                 checked_fprintf (dest, segment->text, g->gr_name);
902                 break;
903               }
904             else
905               {
906                 /* Do nothing. */
907                 /*FALLTHROUGH*/
908               }
909           }
910           /*FALLTHROUGH*/ /*...sometimes, so 'G' case.*/
911
912         case 'G':               /* GID number */
913           /* UNTRUSTED, probably unexploitable */
914           checked_fprintf (dest, segment->text,
915                            human_readable ((uintmax_t) stat_buf->st_gid, hbuf,
916                                            human_ceiling, 1, 1));
917           break;
918         case 'h':               /* leading directories part of path */
919           /* sanitised */
920           {
921             cp = strrchr (pathname, '/');
922             if (cp == NULL)     /* No leading directories. */
923               {
924                 /* If there is no slash in the pathname, we still
925                  * print the string because it contains characters
926                  * other than just '%s'.  The %h expands to ".".
927                  */
928                 checked_print_quoted (dest, segment->text, ".");
929               }
930             else
931               {
932                 char *s = strdup (pathname);
933                 s[cp - pathname] = 0;
934                 checked_print_quoted (dest, segment->text, s);
935                 free (s);
936               }
937           }
938           break;
939
940         case 'H':               /* ARGV element file was found under */
941           /* trusted */
942           {
943             char *s = xmalloc (state.starting_path_length+1);
944             memcpy (s, pathname, state.starting_path_length);
945             s[state.starting_path_length] = 0;
946             checked_fprintf (dest, segment->text, s);
947             free (s);
948           }
949           break;
950
951         case 'i':               /* inode number */
952           /* UNTRUSTED, but not exploitable I think */
953           checked_fprintf (dest, segment->text,
954                            human_readable ((uintmax_t) stat_buf->st_ino, hbuf,
955                                            human_ceiling,
956                                            1, 1));
957           break;
958         case 'k':               /* size in 1K blocks */
959           /* UNTRUSTED, but not exploitable I think */
960           checked_fprintf (dest, segment->text,
961                            human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
962                                            hbuf, human_ceiling,
963                                            ST_NBLOCKSIZE, 1024));
964           break;
965         case 'l':               /* object of symlink */
966           /* sanitised */
967 #ifdef S_ISLNK
968           {
969             char *linkname = 0;
970
971             if (S_ISLNK (stat_buf->st_mode))
972               {
973                 linkname = areadlinkat (state.cwd_dir_fd, state.rel_pathname);
974                 if (linkname == NULL)
975                   {
976                     nonfatal_target_file_error (errno, pathname);
977                     state.exit_status = 1;
978                   }
979               }
980             if (linkname)
981               {
982                 checked_print_quoted (dest, segment->text, linkname);
983               }
984             else
985               {
986                 /* We still need to honour the field width etc., so this is
987                  * not a no-op.
988                  */
989                 checked_print_quoted (dest, segment->text, "");
990               }
991             free (linkname);
992           }
993 #endif                          /* S_ISLNK */
994           break;
995
996         case 'M':               /* mode as 10 chars (eg., "-rwxr-x--x" */
997           /* UNTRUSTED, probably unexploitable */
998           {
999             char modestring[16] ;
1000             filemodestring (stat_buf, modestring);
1001             modestring[10] = '\0';
1002             checked_fprintf (dest, segment->text, modestring);
1003           }
1004           break;
1005
1006         case 'm':               /* mode as octal number (perms only) */
1007           /* UNTRUSTED, probably unexploitable */
1008           {
1009             /* Output the mode portably using the traditional numbers,
1010                even if the host unwisely uses some other numbering
1011                scheme.  But help the compiler in the common case where
1012                the host uses the traditional numbering scheme.  */
1013             mode_t m = stat_buf->st_mode;
1014             bool traditional_numbering_scheme =
1015               (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000
1016                && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100
1017                && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010
1018                && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001);
1019             checked_fprintf (dest, segment->text,
1020                      (traditional_numbering_scheme
1021                       ? m & MODE_ALL
1022                       : ((m & S_ISUID ? 04000 : 0)
1023                          | (m & S_ISGID ? 02000 : 0)
1024                          | (m & S_ISVTX ? 01000 : 0)
1025                          | (m & S_IRUSR ? 00400 : 0)
1026                          | (m & S_IWUSR ? 00200 : 0)
1027                          | (m & S_IXUSR ? 00100 : 0)
1028                          | (m & S_IRGRP ? 00040 : 0)
1029                          | (m & S_IWGRP ? 00020 : 0)
1030                          | (m & S_IXGRP ? 00010 : 0)
1031                          | (m & S_IROTH ? 00004 : 0)
1032                          | (m & S_IWOTH ? 00002 : 0)
1033                          | (m & S_IXOTH ? 00001 : 0))));
1034           }
1035           break;
1036
1037         case 'n':               /* number of links */
1038           /* UNTRUSTED, probably unexploitable */
1039           checked_fprintf (dest, segment->text,
1040                    human_readable ((uintmax_t) stat_buf->st_nlink,
1041                                    hbuf,
1042                                    human_ceiling,
1043                                    1, 1));
1044           break;
1045
1046         case 'p':               /* pathname */
1047           /* sanitised */
1048           checked_print_quoted (dest, segment->text, pathname);
1049           break;
1050
1051         case 'P':               /* pathname with ARGV element stripped */
1052           /* sanitised */
1053           if (state.curdepth > 0)
1054             {
1055               cp = pathname + state.starting_path_length;
1056               if (*cp == '/')
1057                 /* Move past the slash between the ARGV element
1058                    and the rest of the pathname.  But if the ARGV element
1059                    ends in a slash, we didn't add another, so we've
1060                    already skipped past it.  */
1061                 cp++;
1062             }
1063           else
1064             {
1065               cp = "";
1066             }
1067           checked_print_quoted (dest, segment->text, cp);
1068           break;
1069
1070         case 's':               /* size in bytes */
1071           /* UNTRUSTED, probably unexploitable */
1072           checked_fprintf (dest, segment->text,
1073                    human_readable ((uintmax_t) stat_buf->st_size,
1074                                    hbuf, human_ceiling, 1, 1));
1075           break;
1076
1077         case 'S':               /* sparseness */
1078           /* UNTRUSTED, probably unexploitable */
1079           checked_fprintf (dest, segment->text, file_sparseness (stat_buf));;
1080           break;
1081
1082         case 't':               /* mtime in `ctime' format */
1083           /* UNTRUSTED, probably unexploitable */
1084           checked_fprintf (dest, segment->text,
1085                            ctime_format (get_stat_mtime (stat_buf)));
1086           break;
1087
1088         case 'u':               /* user name */
1089           /* trusted */
1090           /* (well, the actual user is selected by the user on systems
1091            * where chown is not restricted, but the user name was
1092            * selected by the system administrator)
1093            */
1094           {
1095             struct passwd *p;
1096
1097             p = getpwuid (stat_buf->st_uid);
1098             if (p)
1099               {
1100                 segment->text[segment->text_len] = 's';
1101                 checked_fprintf (dest, segment->text, p->pw_name);
1102                 break;
1103               }
1104             /* else fallthru */
1105           }
1106           /* FALLTHROUGH*/ /* .. to case U */
1107
1108         case 'U':               /* UID number */
1109           /* UNTRUSTED, probably unexploitable */
1110           checked_fprintf (dest, segment->text,
1111                            human_readable ((uintmax_t) stat_buf->st_uid, hbuf,
1112                                            human_ceiling, 1, 1));
1113           break;
1114
1115           /* %Y: type of file system entry like `ls -l`:
1116            *     (d,-,l,s,p,b,c,n) n=nonexistent (symlink)
1117            */
1118         case 'Y':               /* in case of symlink */
1119           /* trusted */
1120           {
1121 #ifdef S_ISLNK
1122             if (S_ISLNK (stat_buf->st_mode))
1123               {
1124                 struct stat sbuf;
1125                 /* If we would normally follow links, do not do so.
1126                  * If we would normally not follow links, do so.
1127                  */
1128                 if ((following_links () ? optionp_stat : optionl_stat)
1129                     (state.rel_pathname, &sbuf) != 0)
1130                   {
1131                     if ( errno == ENOENT )
1132                       {
1133                         checked_fprintf (dest, segment->text, "N");
1134                         break;
1135                       }
1136                     else if ( errno == ELOOP )
1137                       {
1138                         checked_fprintf (dest, segment->text, "L");
1139                         break;
1140                       }
1141                     else
1142                       {
1143                         checked_fprintf (dest, segment->text, "?");
1144                         error (0, errno, "%s",
1145                                safely_quote_err_filename (0, pathname));
1146                         /* exit_status = 1;
1147                            return ; */
1148                         break;
1149                       }
1150                   }
1151                 checked_fprintf (dest, segment->text,
1152                                  mode_to_filetype (sbuf.st_mode & S_IFMT));
1153               }
1154 #endif /* S_ISLNK */
1155             else
1156               {
1157                 checked_fprintf (dest, segment->text,
1158                                  mode_to_filetype (stat_buf->st_mode & S_IFMT));
1159               }
1160           }
1161           break;
1162
1163         case 'y':
1164           /* trusted */
1165           {
1166             checked_fprintf (dest, segment->text,
1167                              mode_to_filetype (stat_buf->st_mode & S_IFMT));
1168           }
1169           break;
1170
1171         case 'Z':               /* SELinux security context */
1172           {
1173             security_context_t scontext;
1174             int rv = (*options.x_getfilecon) (state.cwd_dir_fd, state.rel_pathname,
1175                                               &scontext);
1176             if (rv < 0)
1177               {
1178                 /* If getfilecon fails, there will in the general case
1179                    still be some text to print.   We just make %Z expand
1180                    to an empty string. */
1181                 checked_fprintf (dest, segment->text, "");
1182
1183                 error (0, errno, _("getfilecon failed: %s"),
1184                     safely_quote_err_filename (0, pathname));
1185                 state.exit_status = 1;
1186               }
1187             else
1188               {
1189                 checked_fprintf (dest, segment->text, scontext);
1190                 freecon (scontext);
1191               }
1192           }
1193           break;
1194         }
1195       /* end of KIND_FORMAT case */
1196       break;
1197     }
1198 }
1199
1200 bool
1201 pred_fprintf (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1202 {
1203   struct format_val *dest = &pred_ptr->args.printf_vec;
1204   struct segment *segment;
1205
1206   for (segment = dest->segment; segment; segment = segment->next)
1207     {
1208       if ( (KIND_FORMAT == segment->segkind) && segment->format_char[1]) /* Component of date. */
1209         {
1210           struct timespec ts;
1211           int valid = 0;
1212
1213           switch (segment->format_char[0])
1214             {
1215             case 'A':
1216               ts = get_stat_atime (stat_buf);
1217               valid = 1;
1218               break;
1219             case 'B':
1220               ts = get_stat_birthtime (stat_buf);
1221               if ('@' == segment->format_char[1])
1222                 valid = 1;
1223               else
1224                 valid = (ts.tv_nsec >= 0);
1225               break;
1226             case 'C':
1227               ts = get_stat_ctime (stat_buf);
1228               valid = 1;
1229               break;
1230             case 'T':
1231               ts = get_stat_mtime (stat_buf);
1232               valid = 1;
1233               break;
1234             default:
1235               assert (0);
1236               abort ();
1237             }
1238           /* We trust the output of format_date not to contain
1239            * nasty characters, though the value of the date
1240            * is itself untrusted data.
1241            */
1242           if (valid)
1243             {
1244               /* trusted */
1245               checked_fprintf (dest, segment->text,
1246                                format_date (ts, segment->format_char[1]));
1247             }
1248           else
1249             {
1250               /* The specified timestamp is not available, output
1251                * nothing for the timestamp, but use the rest (so that
1252                * for example find foo -printf '[%Bs] %p\n' can print
1253                * "[] foo").
1254                */
1255               /* trusted */
1256               checked_fprintf (dest, segment->text, "");
1257             }
1258         }
1259       else
1260         {
1261           /* Print a segment which is not a date. */
1262           do_fprintf (dest, segment, pathname, stat_buf);
1263         }
1264     }
1265   return true;
1266 }
1267
1268 bool
1269 pred_fstype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1270 {
1271   (void) pathname;
1272
1273   if (strcmp (filesystem_type (stat_buf, pathname), pred_ptr->args.str) == 0)
1274     return true;
1275   else
1276     return false;
1277 }
1278
1279 bool
1280 pred_gid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1281 {
1282   (void) pathname;
1283
1284   switch (pred_ptr->args.numinfo.kind)
1285     {
1286     case COMP_GT:
1287       if (stat_buf->st_gid > pred_ptr->args.numinfo.l_val)
1288         return (true);
1289       break;
1290     case COMP_LT:
1291       if (stat_buf->st_gid < pred_ptr->args.numinfo.l_val)
1292         return (true);
1293       break;
1294     case COMP_EQ:
1295       if (stat_buf->st_gid == pred_ptr->args.numinfo.l_val)
1296         return (true);
1297       break;
1298     }
1299   return (false);
1300 }
1301
1302 bool
1303 pred_group (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1304 {
1305   (void) pathname;
1306
1307   if (pred_ptr->args.gid == stat_buf->st_gid)
1308     return (true);
1309   else
1310     return (false);
1311 }
1312
1313 bool
1314 pred_ilname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1315 {
1316   return match_lname (pathname, stat_buf, pred_ptr, true);
1317 }
1318
1319 /* Common code between -name, -iname.  PATHNAME is being visited, STR
1320    is name to compare basename against, and FLAGS are passed to
1321    fnmatch.  Recall that 'find / -name /' is one of the few times where a '/'
1322    in the -name must actually find something. */
1323 static bool
1324 pred_name_common (const char *pathname, const char *str, int flags)
1325 {
1326   bool b;
1327   /* We used to use last_component() here, but that would not allow us to modify the
1328    * input string, which is const.   We could optimise by duplicating the string only
1329    * if we need to modify it, and I'll do that if there is a measurable
1330    * performance difference on a machine built after 1990...
1331    */
1332   char *base = base_name (pathname);
1333   /* remove trailing slashes, but leave  "/" or "//foo" unchanged. */
1334   strip_trailing_slashes (base);
1335
1336   /* FNM_PERIOD is not used here because POSIX requires that it not be.
1337    * See http://standards.ieee.org/reading/ieee/interp/1003-2-92_int/pasc-1003.2-126.html
1338    */
1339   b = fnmatch (str, base, flags) == 0;
1340   free (base);
1341   return b;
1342 }
1343
1344 bool
1345 pred_iname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1346 {
1347   (void) stat_buf;
1348   return pred_name_common (pathname, pred_ptr->args.str, FNM_CASEFOLD);
1349 }
1350
1351 bool
1352 pred_inum (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1353 {
1354   (void) pathname;
1355
1356   assert (stat_buf->st_ino != 0);
1357
1358   switch (pred_ptr->args.numinfo.kind)
1359     {
1360     case COMP_GT:
1361       if (stat_buf->st_ino > pred_ptr->args.numinfo.l_val)
1362         return (true);
1363       break;
1364     case COMP_LT:
1365       if (stat_buf->st_ino < pred_ptr->args.numinfo.l_val)
1366         return (true);
1367       break;
1368     case COMP_EQ:
1369       if (stat_buf->st_ino == pred_ptr->args.numinfo.l_val)
1370         return (true);
1371       break;
1372     }
1373   return (false);
1374 }
1375
1376 bool
1377 pred_ipath (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1378 {
1379   (void) stat_buf;
1380
1381   if (fnmatch (pred_ptr->args.str, pathname, FNM_CASEFOLD) == 0)
1382     return (true);
1383   return (false);
1384 }
1385
1386 bool
1387 pred_links (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1388 {
1389   (void) pathname;
1390
1391   switch (pred_ptr->args.numinfo.kind)
1392     {
1393     case COMP_GT:
1394       if (stat_buf->st_nlink > pred_ptr->args.numinfo.l_val)
1395         return (true);
1396       break;
1397     case COMP_LT:
1398       if (stat_buf->st_nlink < pred_ptr->args.numinfo.l_val)
1399         return (true);
1400       break;
1401     case COMP_EQ:
1402       if (stat_buf->st_nlink == pred_ptr->args.numinfo.l_val)
1403         return (true);
1404       break;
1405     }
1406   return (false);
1407 }
1408
1409 bool
1410 pred_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1411 {
1412   return match_lname (pathname, stat_buf, pred_ptr, false);
1413 }
1414
1415 static bool
1416 match_lname (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr, bool ignore_case)
1417 {
1418   bool ret = false;
1419 #ifdef S_ISLNK
1420   if (S_ISLNK (stat_buf->st_mode))
1421     {
1422       char *linkname = areadlinkat (state.cwd_dir_fd, state.rel_pathname);
1423       if (linkname)
1424         {
1425           if (fnmatch (pred_ptr->args.str, linkname,
1426                        ignore_case ? FNM_CASEFOLD : 0) == 0)
1427             ret = true;
1428         }
1429       else
1430         {
1431           nonfatal_target_file_error (errno, pathname);
1432           state.exit_status = 1;
1433         }
1434       free (linkname);
1435     }
1436 #endif /* S_ISLNK */
1437   return ret;
1438 }
1439
1440 bool
1441 pred_ls (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1442 {
1443   return pred_fls (pathname, stat_buf, pred_ptr);
1444 }
1445
1446 bool
1447 pred_mmin (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1448 {
1449   (void) &pathname;
1450   return pred_timewindow (get_stat_mtime(stat_buf), pred_ptr, 60);
1451 }
1452
1453 bool
1454 pred_mtime (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1455 {
1456   (void) pathname;
1457   return pred_timewindow (get_stat_mtime(stat_buf), pred_ptr, DAYSECS);
1458 }
1459
1460 bool
1461 pred_name (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1462 {
1463   (void) stat_buf;
1464   return pred_name_common (pathname, pred_ptr->args.str, 0);
1465 }
1466
1467 bool
1468 pred_negate (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1469 {
1470   return !apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
1471 }
1472
1473 bool
1474 pred_newer (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1475 {
1476   (void) pathname;
1477
1478   assert (COMP_GT == pred_ptr->args.reftime.kind);
1479   return compare_ts (get_stat_mtime(stat_buf), pred_ptr->args.reftime.ts) > 0;
1480 }
1481
1482 bool
1483 pred_newerXY (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1484 {
1485   struct timespec ts;
1486   bool collected = false;
1487
1488   assert (COMP_GT == pred_ptr->args.reftime.kind);
1489
1490   switch (pred_ptr->args.reftime.xval)
1491     {
1492     case XVAL_TIME:
1493       assert (pred_ptr->args.reftime.xval != XVAL_TIME);
1494       return false;
1495
1496     case XVAL_ATIME:
1497       ts = get_stat_atime (stat_buf);
1498       collected = true;
1499       break;
1500
1501     case XVAL_BIRTHTIME:
1502       ts = get_stat_birthtime (stat_buf);
1503       collected = true;
1504       if (ts.tv_nsec < 0);
1505         {
1506           /* XXX: Cannot determine birth time.  Warn once. */
1507           error (0, 0, _("WARNING: cannot determine birth time of file %s"),
1508                  safely_quote_err_filename (0, pathname));
1509           return false;
1510         }
1511       break;
1512
1513     case XVAL_CTIME:
1514       ts = get_stat_ctime (stat_buf);
1515       collected = true;
1516       break;
1517
1518     case XVAL_MTIME:
1519       ts = get_stat_mtime (stat_buf);
1520       collected = true;
1521       break;
1522     }
1523
1524   assert (collected);
1525   return compare_ts (ts, pred_ptr->args.reftime.ts) > 0;
1526 }
1527
1528 bool
1529 pred_nogroup (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1530 {
1531   (void) pathname;
1532   (void) pred_ptr;
1533
1534 #ifdef CACHE_IDS
1535   extern char *gid_unused;
1536
1537   return gid_unused[(unsigned) stat_buf->st_gid];
1538 #else
1539   return getgrgid (stat_buf->st_gid) == NULL;
1540 #endif
1541 }
1542
1543 bool
1544 pred_nouser (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1545 {
1546 #ifdef CACHE_IDS
1547   extern char *uid_unused;
1548 #endif
1549
1550   (void) pathname;
1551   (void) pred_ptr;
1552
1553 #ifdef CACHE_IDS
1554   return uid_unused[(unsigned) stat_buf->st_uid];
1555 #else
1556   return getpwuid (stat_buf->st_uid) == NULL;
1557 #endif
1558 }
1559
1560
1561 static bool
1562 is_ok (const char *program, const char *arg)
1563 {
1564   fflush (stdout);
1565   /* The draft open standard requires that, in the POSIX locale,
1566      the last non-blank character of this prompt be '?'.
1567      The exact format is not specified.
1568      This standard does not have requirements for locales other than POSIX
1569   */
1570   /* XXX: printing UNTRUSTED data here. */
1571   fprintf (stderr, _("< %s ... %s > ? "), program, arg);
1572   fflush (stderr);
1573   return yesno ();
1574 }
1575
1576 bool
1577 pred_ok (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1578 {
1579   if (is_ok (pred_ptr->args.exec_vec.replace_vec[0], pathname))
1580     return impl_pred_exec (pathname, stat_buf, pred_ptr);
1581   else
1582     return false;
1583 }
1584
1585 bool
1586 pred_okdir (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1587 {
1588   if (is_ok (pred_ptr->args.exec_vec.replace_vec[0], pathname))
1589     return impl_pred_exec (state.rel_pathname, stat_buf, pred_ptr);
1590   else
1591     return false;
1592 }
1593
1594 bool
1595 pred_openparen (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1596 {
1597   (void) pathname;
1598   (void) stat_buf;
1599   (void) pred_ptr;
1600   return true;
1601 }
1602
1603 bool
1604 pred_or (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1605 {
1606   if (pred_ptr->pred_left == NULL
1607       || !apply_predicate (pathname, stat_buf, pred_ptr->pred_left))
1608     {
1609       return apply_predicate (pathname, stat_buf, pred_ptr->pred_right);
1610     }
1611   else
1612     return true;
1613 }
1614
1615 bool
1616 pred_path (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1617 {
1618   (void) stat_buf;
1619   if (fnmatch (pred_ptr->args.str, pathname, 0) == 0)
1620     return (true);
1621   return (false);
1622 }
1623
1624 bool
1625 pred_perm (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1626 {
1627   mode_t mode = stat_buf->st_mode;
1628   mode_t perm_val = pred_ptr->args.perm.val[S_ISDIR (mode) != 0];
1629   (void) pathname;
1630   switch (pred_ptr->args.perm.kind)
1631     {
1632     case PERM_AT_LEAST:
1633       return (mode & perm_val) == perm_val;
1634       break;
1635
1636     case PERM_ANY:
1637       /* True if any of the bits set in the mask are also set in the file's mode.
1638        *
1639        *
1640        * Otherwise, if onum is prefixed by a hyphen, the primary shall
1641        * evaluate as true if at least all of the bits specified in
1642        * onum that are also set in the octal mask 07777 are set.
1643        *
1644        * Eric Blake's interpretation is that the mode argument is zero,
1645
1646        */
1647       if (0 == perm_val)
1648         return true;            /* Savannah bug 14748; we used to return false */
1649       else
1650         return (mode & perm_val) != 0;
1651       break;
1652
1653     case PERM_EXACT:
1654       return (mode & MODE_ALL) == perm_val;
1655       break;
1656
1657     default:
1658       abort ();
1659       break;
1660     }
1661 }
1662
1663
1664 bool
1665 pred_executable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1666 {
1667   (void) pathname;
1668   (void) stat_buf;
1669   (void) pred_ptr;
1670
1671   /* As for access, the check is performed with the real user id. */
1672   return 0 == faccessat (state.cwd_dir_fd, state.rel_pathname, X_OK, 0);
1673 }
1674
1675 bool
1676 pred_readable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1677 {
1678   (void) pathname;
1679   (void) stat_buf;
1680   (void) pred_ptr;
1681
1682   /* As for access, the check is performed with the real user id. */
1683   return 0 == faccessat (state.cwd_dir_fd, state.rel_pathname, R_OK, 0);
1684 }
1685
1686 bool
1687 pred_writable (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1688 {
1689   (void) pathname;
1690   (void) stat_buf;
1691   (void) pred_ptr;
1692
1693   /* As for access, the check is performed with the real user id. */
1694   return 0 == faccessat (state.cwd_dir_fd, state.rel_pathname, W_OK, 0);
1695 }
1696
1697 bool
1698 pred_print (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1699 {
1700   (void) stat_buf;
1701   (void) pred_ptr;
1702
1703   print_quoted (pred_ptr->args.printf_vec.stream,
1704                 pred_ptr->args.printf_vec.quote_opts,
1705                 pred_ptr->args.printf_vec.dest_is_tty,
1706                 "%s\n", pathname);
1707   return true;
1708 }
1709
1710 bool
1711 pred_print0 (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1712 {
1713   return pred_fprint0(pathname, stat_buf, pred_ptr);
1714 }
1715
1716 bool
1717 pred_prune (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1718 {
1719   (void) pathname;
1720   (void) pred_ptr;
1721
1722   if (options.do_dir_first == true) { /* no effect with -depth */
1723     assert (state.have_stat);
1724     if (stat_buf != NULL &&
1725         S_ISDIR(stat_buf->st_mode))
1726       state.stop_at_current_level = true;
1727   }
1728
1729   /* findutils used to return options.do_dir_first here, so that -prune
1730    * returns true only if -depth is not in effect.   But POSIX requires
1731    * that -prune always evaluate as true.
1732    */
1733   return true;
1734 }
1735
1736 bool
1737 pred_quit (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1738 {
1739   (void) pathname;
1740   (void) stat_buf;
1741   (void) pred_ptr;
1742
1743   /* Run any cleanups.  This includes executing any command lines
1744    * we have partly built but not executed.
1745    */
1746   cleanup ();
1747
1748   /* Since -exec and friends don't leave child processes running in the
1749    * background, there is no need to wait for them here.
1750    */
1751   exit (state.exit_status);     /* 0 for success, etc. */
1752 }
1753
1754 bool
1755 pred_regex (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1756 {
1757   int len = strlen (pathname);
1758 (void) stat_buf;
1759   if (re_match (pred_ptr->args.regex, pathname, len, 0,
1760                 (struct re_registers *) NULL) == len)
1761     return (true);
1762   return (false);
1763 }
1764
1765 bool
1766 pred_size (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1767 {
1768   uintmax_t f_val;
1769
1770   (void) pathname;
1771   f_val = ((stat_buf->st_size / pred_ptr->args.size.blocksize)
1772            + (stat_buf->st_size % pred_ptr->args.size.blocksize != 0));
1773   switch (pred_ptr->args.size.kind)
1774     {
1775     case COMP_GT:
1776       if (f_val > pred_ptr->args.size.size)
1777         return (true);
1778       break;
1779     case COMP_LT:
1780       if (f_val < pred_ptr->args.size.size)
1781         return (true);
1782       break;
1783     case COMP_EQ:
1784       if (f_val == pred_ptr->args.size.size)
1785         return (true);
1786       break;
1787     }
1788   return (false);
1789 }
1790
1791 bool
1792 pred_samefile (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1793 {
1794   /* Potential optimisation: because of the loop protection, we always
1795    * know the device of the current directory, hence the device number
1796    * of the file we're currently considering.  If -L is not in effect,
1797    * and the device number of the file we're looking for is not the
1798    * same as the device number of the current directory, this
1799    * predicate cannot return true.  Hence there would be no need to
1800    * stat the file we're looking at.
1801    *
1802    * For the moment, we simply compare inode numbers, which should cut
1803    * down greatly on the number of calls to stat.  Some of the
1804    * remainder will be unnecessary, but the additional complexity
1805    * probably isn't worthwhile.
1806    */
1807   (void) pathname;
1808
1809   /* We will often still have an fd open on the file under consideration,
1810    * but that's just to ensure inode number stability by maintaining
1811    * a reference to it; we don't need the file for anything else.
1812    */
1813   if (stat_buf->st_ino)
1814     {
1815       if (stat_buf->st_ino != pred_ptr->args.samefileid.ino)
1816         return false;
1817     }
1818   /* Now stat the file to check the device number. */
1819   if (0 == get_statinfo (pathname, state.rel_pathname, stat_buf))
1820     {
1821       /* the repeated test here is necessary in case stat_buf.st_ino had been zero. */
1822       return stat_buf->st_ino == pred_ptr->args.samefileid.ino
1823         && stat_buf->st_dev == pred_ptr->args.samefileid.dev;
1824     }
1825   else
1826     {
1827       /* get_statinfo will already have emitted an error message. */
1828       return false;
1829     }
1830 }
1831
1832 bool
1833 pred_true (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1834 {
1835   (void) pathname;
1836   (void) stat_buf;
1837   (void) pred_ptr;
1838   return true;
1839 }
1840
1841 bool
1842 pred_type (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1843 {
1844   mode_t mode;
1845   mode_t type = pred_ptr->args.type;
1846
1847   assert (state.have_type);
1848
1849   if (0 == state.type)
1850     {
1851       /* This can sometimes happen with broken NFS servers.
1852        * See Savannah bug #16378.
1853        */
1854       return false;
1855     }
1856
1857   (void) pathname;
1858
1859   if (state.have_stat)
1860      mode = stat_buf->st_mode;
1861   else
1862      mode = state.type;
1863
1864 #ifndef S_IFMT
1865   /* POSIX system; check `mode' the slow way. */
1866   if ((S_ISBLK (mode) && type == S_IFBLK)
1867       || (S_ISCHR (mode) && type == S_IFCHR)
1868       || (S_ISDIR (mode) && type == S_IFDIR)
1869       || (S_ISREG (mode) && type == S_IFREG)
1870 #ifdef S_IFLNK
1871       || (S_ISLNK (mode) && type == S_IFLNK)
1872 #endif
1873 #ifdef S_IFIFO
1874       || (S_ISFIFO (mode) && type == S_IFIFO)
1875 #endif
1876 #ifdef S_IFSOCK
1877       || (S_ISSOCK (mode) && type == S_IFSOCK)
1878 #endif
1879 #ifdef S_IFDOOR
1880       || (S_ISDOOR (mode) && type == S_IFDOOR)
1881 #endif
1882       )
1883 #else /* S_IFMT */
1884   /* Unix system; check `mode' the fast way. */
1885   if ((mode & S_IFMT) == type)
1886 #endif /* S_IFMT */
1887     return (true);
1888   else
1889     return (false);
1890 }
1891
1892 bool
1893 pred_uid (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1894 {
1895   (void) pathname;
1896   switch (pred_ptr->args.numinfo.kind)
1897     {
1898     case COMP_GT:
1899       if (stat_buf->st_uid > pred_ptr->args.numinfo.l_val)
1900         return (true);
1901       break;
1902     case COMP_LT:
1903       if (stat_buf->st_uid < pred_ptr->args.numinfo.l_val)
1904         return (true);
1905       break;
1906     case COMP_EQ:
1907       if (stat_buf->st_uid == pred_ptr->args.numinfo.l_val)
1908         return (true);
1909       break;
1910     }
1911   return (false);
1912 }
1913
1914 bool
1915 pred_used (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1916 {
1917   struct timespec delta, at, ct;
1918
1919   (void) pathname;
1920
1921   /* TODO: this needs to be retested carefully (manually, if necessary) */
1922   at = get_stat_atime (stat_buf);
1923   ct = get_stat_ctime (stat_buf);
1924   delta.tv_sec  = at.tv_sec  - ct.tv_sec;
1925   delta.tv_nsec = at.tv_nsec - ct.tv_nsec;
1926   if (delta.tv_nsec < 0)
1927     {
1928       delta.tv_nsec += 1000000000;
1929       delta.tv_sec  -=          1;
1930     }
1931   return pred_timewindow (delta, pred_ptr, DAYSECS);
1932 }
1933
1934 bool
1935 pred_user (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1936 {
1937   (void) pathname;
1938   if (pred_ptr->args.uid == stat_buf->st_uid)
1939     return (true);
1940   else
1941     return (false);
1942 }
1943
1944 bool
1945 pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_ptr)
1946 {
1947   struct stat sbuf;             /* local copy, not stat_buf because we're using a different stat method */
1948   int (*ystat) (const char*, struct stat *p);
1949
1950   /* If we would normally stat the link itself, stat the target instead.
1951    * If we would normally follow the link, stat the link itself instead.
1952    */
1953   if (following_links ())
1954     ystat = optionp_stat;
1955   else
1956     ystat = optionl_stat;
1957
1958   set_stat_placeholders (&sbuf);
1959   if ((*ystat) (state.rel_pathname, &sbuf) != 0)
1960     {
1961       if (following_links () && errno == ENOENT)
1962         {
1963           /* If we failed to follow the symlink,
1964            * fall back on looking at the symlink itself.
1965            */
1966           /* Mimic behavior of ls -lL. */
1967           return (pred_type (pathname, stat_buf, pred_ptr));
1968         }
1969       else
1970         {
1971           error (0, errno, "%s", safely_quote_err_filename (0, pathname));
1972           state.exit_status = 1;
1973         }
1974       return false;
1975     }
1976   /* Now that we have our stat() information, query it in the same
1977    * way that -type does.
1978    */
1979   return (pred_type (pathname, &sbuf, pred_ptr));
1980 }
1981
1982
1983 bool
1984 pred_context (const char *pathname, struct stat *stat_buf,
1985               struct predicate *pred_ptr)
1986 {
1987   security_context_t scontext;
1988   int rv = (*options.x_getfilecon) (state.cwd_dir_fd, state.rel_pathname,
1989                                     &scontext);
1990   if (rv < 0)
1991     {
1992       error (0, errno, _("getfilecon failed: %s"),
1993              safely_quote_err_filename (0, pathname));
1994       return false;
1995     }
1996
1997   rv = (fnmatch (pred_ptr->args.scontext, scontext, 0) == 0);
1998   freecon (scontext);
1999   return rv;
2000 }
2001
2002
2003 /*  1) fork to get a child; parent remembers the child pid
2004     2) child execs the command requested
2005     3) parent waits for child; checks for proper pid of child
2006
2007     Possible returns:
2008
2009     ret         errno   status(h)   status(l)
2010
2011     pid         x       signal#     0177        stopped
2012     pid         x       exit arg    0           term by _exit
2013     pid         x       0           signal #    term by signal
2014     -1          EINTR                           parent got signal
2015     -1          other                           some other kind of error
2016
2017     Return true only if the pid matches, status(l) is
2018     zero, and the exit arg (status high) is 0.
2019     Otherwise return false, possibly printing an error message. */
2020
2021
2022 static bool
2023 prep_child_for_exec (bool close_stdin, const struct saved_cwd *wd)
2024 {
2025   bool ok = true;
2026   if (close_stdin)
2027     {
2028       const char inputfile[] = "/dev/null";
2029
2030       if (close (0) < 0)
2031         {
2032           error (0, errno, _("Cannot close standard input"));
2033           ok = false;
2034         }
2035       else
2036         {
2037           if (open (inputfile, O_RDONLY
2038 #if defined O_LARGEFILE
2039                    |O_LARGEFILE
2040 #endif
2041                    ) < 0)
2042             {
2043               /* This is not entirely fatal, since
2044                * executing the child with a closed
2045                * stdin is almost as good as executing it
2046                * with its stdin attached to /dev/null.
2047                */
2048               error (0, errno, "%s", safely_quote_err_filename (0, inputfile));
2049               /* do not set ok=false, it is OK to continue anyway. */
2050             }
2051         }
2052     }
2053
2054   /* Even if DebugSearch is set, don't announce our change of
2055    * directory, since we're not going to emit a subsequent
2056    * announcement of a call to stat() anyway, as we're about to exec
2057    * something.
2058    */
2059   if (0 != restore_cwd (wd))
2060     {
2061       error (0, errno, _("Failed to change directory"));
2062       ok = false;
2063     }
2064   return ok;
2065 }
2066
2067
2068
2069
2070
2071
2072 int
2073 launch (struct buildcmd_control *ctl, void *usercontext, int argc, char **argv)
2074 {
2075   pid_t child_pid;
2076   static int first_time = 1;
2077   struct exec_val *execp = usercontext;
2078
2079   /* Make sure output of command doesn't get mixed with find output. */
2080   fflush (stdout);
2081   fflush (stderr);
2082
2083   /* Make sure to listen for the kids.  */
2084   if (first_time)
2085     {
2086       first_time = 0;
2087       signal (SIGCHLD, SIG_DFL);
2088     }
2089
2090   child_pid = fork ();
2091   if (child_pid == -1)
2092     error (EXIT_FAILURE, errno, _("cannot fork"));
2093   if (child_pid == 0)
2094     {
2095       /* We are the child. */
2096       assert (NULL != execp->wd_for_exec);
2097       if (!prep_child_for_exec (execp->close_stdin, execp->wd_for_exec))
2098         {
2099           _exit (1);
2100         }
2101       else
2102         {
2103           if (fd_leak_check_is_enabled ())
2104             {
2105               complain_about_leaky_fds ();
2106             }
2107         }
2108
2109       if (bc_args_exceed_testing_limit (argv))
2110         errno = E2BIG;
2111       else
2112         execvp (argv[0], argv);
2113       /* TODO: use a pipe to pass back the errno value, like xargs does */
2114       error (0, errno, "%s",
2115              safely_quote_err_filename (0, argv[0]));
2116       _exit (1);
2117     }
2118
2119   while (waitpid (child_pid, &(execp->last_child_status), 0) == (pid_t) -1)
2120     {
2121       if (errno != EINTR)
2122         {
2123           error (0, errno, _("error waiting for %s"),
2124                  safely_quote_err_filename (0, argv[0]));
2125           state.exit_status = 1;
2126           return 0;             /* FAIL */
2127         }
2128     }
2129
2130   if (WIFSIGNALED (execp->last_child_status))
2131     {
2132       error (0, 0, _("%s terminated by signal %d"),
2133              quotearg_n_style (0, options.err_quoting_style, argv[0]),
2134              WTERMSIG (execp->last_child_status));
2135
2136       if (execp->multiple)
2137         {
2138           /* -exec   \; just returns false if the invoked command fails.
2139            * -exec {} + returns true if the invoked command fails, but
2140            *            sets the program exit status.
2141            */
2142           state.exit_status = 1;
2143         }
2144
2145       return 1;                 /* OK */
2146     }
2147
2148   if (0 == WEXITSTATUS (execp->last_child_status))
2149     {
2150       return 1;                 /* OK */
2151     }
2152   else
2153     {
2154       if (execp->multiple)
2155         {
2156           /* -exec   \; just returns false if the invoked command fails.
2157            * -exec {} + returns true if the invoked command fails, but
2158            *            sets the program exit status.
2159            */
2160           state.exit_status = 1;
2161         }
2162       /* The child failed, but this is the exec callback.  We
2163        * don't want to run the child again in this case anwyay.
2164        */
2165       return 1;                 /* FAIL (but don't try again) */
2166     }
2167
2168 }
2169
2170
2171 static bool
2172 scan_for_digit_differences (const char *p, const char *q,
2173                             size_t *first, size_t *n)
2174 {
2175   bool seen = false;
2176   size_t i;
2177
2178   for (i=0; p[i] && q[i]; i++)
2179     {
2180       if (p[i] != q[i])
2181         {
2182           if (!isdigit ((unsigned char)q[i]) || !isdigit ((unsigned char)q[i]))
2183             return false;
2184
2185           if (!seen)
2186             {
2187               *first = i;
2188               *n = 1;
2189               seen = 1;
2190             }
2191           else
2192             {
2193               if (i-*first == *n)
2194                 {
2195                   /* Still in the first sequence of differing digits. */
2196                   ++*n;
2197                 }
2198               else
2199                 {
2200                   /* More than one differing contiguous character sequence. */
2201                   return false;
2202                 }
2203             }
2204         }
2205     }
2206   if (p[i] || q[i])
2207     {
2208       /* strings are different lengths. */
2209       return false;
2210     }
2211   return true;
2212 }
2213
2214
2215 static char*
2216 do_time_format (const char *fmt, const struct tm *p, const char *ns, size_t ns_size)
2217 {
2218   static char *buf = NULL;
2219   static size_t buf_size;
2220   char *timefmt = NULL;
2221   struct tm altered_time;
2222
2223
2224   /* If the format expands to nothing (%p in some locales, for
2225    * example), strftime can return 0.  We actually want to distinguish
2226    * the error case where the buffer is too short, so we just prepend
2227    * an otherwise uninteresting character to prevent the no-output
2228    * case.
2229    */
2230   timefmt = xmalloc (strlen (fmt) + 2u);
2231   sprintf (timefmt, "_%s", fmt);
2232
2233   /* altered_time is a similar time, but in which both
2234    * digits of the seconds field are different.
2235    */
2236   altered_time = *p;
2237   if (altered_time.tm_sec >= 11)
2238     altered_time.tm_sec -= 11;
2239   else
2240     altered_time.tm_sec += 11;
2241
2242   /* If we call strftime() with buf_size=0, the program will coredump
2243    * on Solaris, since it unconditionally writes the terminating null
2244    * character.
2245    */
2246   buf_size = 1u;
2247   buf = xmalloc (buf_size);
2248   while (true)
2249     {
2250       /* I'm not sure that Solaris will return 0 when the buffer is too small.
2251        * Therefore we do not check for (buf_used != 0) as the termination
2252        * condition.
2253        */
2254       size_t buf_used = strftime (buf, buf_size, timefmt, p);
2255       if (buf_used              /* Conforming POSIX system */
2256           && (buf_used < buf_size)) /* Solaris workaround */
2257         {
2258           char *altbuf;
2259           size_t i = 0, n = 0;
2260           size_t final_len = (buf_used
2261                               + 1u /* for \0 */
2262                               + ns_size);
2263           buf = xrealloc (buf, final_len);
2264           altbuf = xmalloc (final_len);
2265           strftime (altbuf, buf_size, timefmt, &altered_time);
2266
2267           /* Find the seconds digits; they should be the only changed part.
2268            * In theory the result of the two formatting operations could differ in
2269            * more than just one sequence of decimal digits (for example %X might
2270            * in theory return a spelled-out time like "thirty seconds past noon").
2271            * When that happens, we just avoid inserting the nanoseconds field.
2272            */
2273           if (scan_for_digit_differences (buf, altbuf, &i, &n)
2274               && (2==n) && !isdigit ((unsigned char)buf[i+n]))
2275             {
2276               const size_t end_of_seconds = i + n;
2277               const size_t suffix_len = buf_used-(end_of_seconds)+1;
2278
2279               /* Move the tail (including the \0).  Note that this
2280                * is a move of an overlapping memory block, so we
2281                * must use memmove instead of memcpy.  Then insert
2282                * the nanoseconds (but not its trailing \0).
2283                */
2284               assert (end_of_seconds + ns_size + suffix_len == final_len);
2285               memmove (buf+end_of_seconds+ns_size,
2286                        buf+end_of_seconds,
2287                        suffix_len);
2288               memcpy (buf+i+n, ns, ns_size);
2289             }
2290           else
2291             {
2292               /* No seconds digits.  No need to insert anything. */
2293             }
2294           /* The first character of buf is the underscore, which we actually
2295            * don't want.
2296            */
2297           free (timefmt);
2298           return buf+1;
2299         }
2300       else
2301         {
2302           buf = x2nrealloc (buf, &buf_size, 2u);
2303         }
2304     }
2305 }
2306
2307
2308
2309 /* Return a static string formatting the time WHEN according to the
2310  * strftime format character KIND.
2311  *
2312  * This function contains a number of assertions.  These look like
2313  * runtime checks of the results of computations, which would be a
2314  * problem since external events should not be tested for with
2315  * "assert" (instead you should use "if").  However, they are not
2316  * really runtime checks.  The assertions actually exist to verify
2317  * that the various buffers are correctly sized.
2318  */
2319 static char *
2320 format_date (struct timespec ts, int kind)
2321 {
2322   /* In theory, we use an extra 10 characters for 9 digits of
2323    * nanoseconds and 1 for the decimal point.  However, the real
2324    * world is more complex than that.
2325    *
2326    * For example, some systems return junk in the tv_nsec part of
2327    * st_birthtime.  An example of this is the NetBSD-4.0-RELENG kernel
2328    * (at Sat Mar 24 18:46:46 2007) running a NetBSD-3.1-RELEASE
2329    * runtime and examining files on an msdos filesytem.  So for that
2330    * reason we set NS_BUF_LEN to 32, which is simply "long enough" as
2331    * opposed to "exactly the right size".  Note that the behaviour of
2332    * NetBSD appears to be a result of the use of uninitialised data,
2333    * as it's not 100% reproducible (more like 25%).
2334    */
2335   enum {
2336     NS_BUF_LEN = 32,
2337     DATE_LEN_PERCENT_APLUS=21   /* length of result of %A+ (it's longer than %c)*/
2338   };
2339   static char buf[128u+10u + MAX(DATE_LEN_PERCENT_APLUS,
2340                             MAX (LONGEST_HUMAN_READABLE + 2, NS_BUF_LEN+64+200))];
2341   char ns_buf[NS_BUF_LEN]; /* -.9999999990 (- sign can happen!)*/
2342   int  charsprinted, need_ns_suffix;
2343   struct tm *tm;
2344   char fmt[6];
2345
2346   /* human_readable() assumes we pass a buffer which is at least as
2347    * long as LONGEST_HUMAN_READABLE.  We use an assertion here to
2348    * ensure that no nasty unsigned overflow happend in our calculation
2349    * of the size of buf.  Do the assertion here rather than in the
2350    * code for %@ so that we find the problem quickly if it exists.  If
2351    * you want to submit a patch to move this into the if statement, go
2352    * ahead, I'll apply it.  But include performance timings
2353    * demonstrating that the performance difference is actually
2354    * measurable.
2355    */
2356   verify (sizeof (buf) >= LONGEST_HUMAN_READABLE);
2357
2358   charsprinted = 0;
2359   need_ns_suffix = 0;
2360
2361   /* Format the main part of the time. */
2362   if (kind == '+')
2363     {
2364       strcpy (fmt, "%F+%T");
2365       need_ns_suffix = 1;
2366     }
2367   else
2368     {
2369       fmt[0] = '%';
2370       fmt[1] = kind;
2371       fmt[2] = '\0';
2372
2373       /* %a, %c, and %t are handled in ctime_format() */
2374       switch (kind)
2375         {
2376         case 'S':
2377         case 'T':
2378         case 'X':
2379         case '@':
2380           need_ns_suffix = 1;
2381           break;
2382         default:
2383           need_ns_suffix = 0;
2384           break;
2385         }
2386     }
2387
2388   if (need_ns_suffix)
2389     {
2390       /* Format the nanoseconds part.  Leave a trailing zero to
2391        * discourage people from writing scripts which extract the
2392        * fractional part of the timestamp by using column offsets.
2393        * The reason for discouraging this is that in the future, the
2394        * granularity may not be nanoseconds.
2395        */
2396       charsprinted = snprintf (ns_buf, NS_BUF_LEN, ".%09ld0", (long int)ts.tv_nsec);
2397       assert (charsprinted < NS_BUF_LEN);
2398     }
2399   else
2400     {
2401       charsprinted = 0;
2402       ns_buf[0] = 0;
2403     }
2404
2405   if (kind != '@')
2406     {
2407       tm = localtime (&ts.tv_sec);
2408       if (tm)
2409         {
2410           char *s = do_time_format (fmt, tm, ns_buf, charsprinted);
2411           if (s)
2412             return s;
2413         }
2414     }
2415
2416   /* If we get to here, either the format was %@, or we have fallen back to it
2417    * because strftime failed.
2418    */
2419   if (1)
2420     {
2421       uintmax_t w = ts.tv_sec;
2422       size_t used, len, remaining;
2423
2424       /* XXX: note that we are negating an unsigned type which is the
2425        * widest possible unsigned type.
2426        */
2427       char *p = human_readable (ts.tv_sec < 0 ? -w : w, buf + 1,
2428                                 human_ceiling, 1, 1);
2429       assert (p > buf);
2430       assert (p < (buf + (sizeof buf)));
2431       if (ts.tv_sec < 0)
2432         *--p = '-'; /* XXX: Ugh, relying on internal details of human_readable(). */
2433
2434       /* Add the nanoseconds part.  Because we cannot enforce a
2435        * particlar implementation of human_readable, we cannot assume
2436        * any particular value for (p-buf).  So we need to be careful
2437        * that there is enough space remaining in the buffer.
2438        */
2439       if (need_ns_suffix)
2440         {
2441           len = strlen (p);
2442           used = (p-buf) + len; /* Offset into buf of current end */
2443           assert (sizeof buf > used); /* Ensure we can perform subtraction safely. */
2444           remaining = sizeof buf - used - 1u; /* allow space for NUL */
2445
2446           if (strlen (ns_buf) >= remaining)
2447             {
2448               error (0, 0,
2449                      "charsprinted=%ld but remaining=%lu: ns_buf=%s",
2450                      (long)charsprinted, (unsigned long)remaining, ns_buf);
2451             }
2452           assert (strlen (ns_buf) < remaining);
2453           strcat (p, ns_buf);
2454         }
2455       return p;
2456     }
2457 }
2458
2459 static const char *weekdays[] =
2460   {
2461     "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
2462   };
2463 static char * months[] =
2464   {
2465     "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2466     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2467   };
2468
2469
2470 static char *
2471 ctime_format (struct timespec ts)
2472 {
2473   const struct tm * ptm;
2474 #define TIME_BUF_LEN 1024u
2475   static char resultbuf[TIME_BUF_LEN];
2476   int nout;
2477
2478   ptm = localtime (&ts.tv_sec);
2479   if (ptm)
2480     {
2481       assert (ptm->tm_wday >=  0);
2482       assert (ptm->tm_wday <   7);
2483       assert (ptm->tm_mon  >=  0);
2484       assert (ptm->tm_mon  <  12);
2485       assert (ptm->tm_hour >=  0);
2486       assert (ptm->tm_hour <  24);
2487       assert (ptm->tm_min  <  60);
2488       assert (ptm->tm_sec  <= 61); /* allows 2 leap seconds. */
2489
2490       /* wkday mon mday hh:mm:ss.nnnnnnnnn yyyy */
2491       nout = snprintf (resultbuf, TIME_BUF_LEN,
2492                        "%3s %3s %2d %02d:%02d:%02d.%010ld %04d",
2493                        weekdays[ptm->tm_wday],
2494                        months[ptm->tm_mon],
2495                        ptm->tm_mday,
2496                        ptm->tm_hour,
2497                        ptm->tm_min,
2498                        ptm->tm_sec,
2499                        (long int)ts.tv_nsec,
2500                        1900 + ptm->tm_year);
2501
2502       assert (nout < TIME_BUF_LEN);
2503       return resultbuf;
2504     }
2505   else
2506     {
2507       /* The time cannot be represented as a struct tm.
2508          Output it as an integer.  */
2509       return format_date (ts, '@');
2510     }
2511 }
2512
2513 /* Copy STR into BUF and trim blanks from the end of BUF.
2514    Return BUF. */
2515
2516 static char *
2517 blank_rtrim (str, buf)
2518      char *str;
2519      char *buf;
2520 {
2521   int i;
2522
2523   if (str == NULL)
2524     return (NULL);
2525   strcpy (buf, str);
2526   i = strlen (buf) - 1;
2527   while ((i >= 0) && ((buf[i] == ' ') || buf[i] == '\t'))
2528     i--;
2529   buf[++i] = '\0';
2530   return (buf);
2531 }
2532
2533 /* Print out the predicate list starting at NODE. */
2534 void
2535 print_list (FILE *fp, struct predicate *node)
2536 {
2537   struct predicate *cur;
2538   char name[256];
2539
2540   cur = node;
2541   while (cur != NULL)
2542     {
2543       fprintf (fp, "[%s] ", blank_rtrim (cur->p_name, name));
2544       cur = cur->pred_next;
2545     }
2546   fprintf (fp, "\n");
2547 }
2548
2549 /* Print out the predicate list starting at NODE. */
2550 static void
2551 print_parenthesised (FILE *fp, struct predicate *node)
2552 {
2553   int parens = 0;
2554
2555   if (node)
2556     {
2557       if ((pred_is (node, pred_or) || pred_is (node, pred_and))
2558           && node->pred_left == NULL)
2559         {
2560           /* We print "<nothing> or  X" as just "X"
2561            * We print "<nothing> and X" as just "X"
2562            */
2563           print_parenthesised(fp, node->pred_right);
2564         }
2565       else
2566         {
2567           if (node->pred_left || node->pred_right)
2568             parens = 1;
2569
2570           if (parens)
2571             fprintf (fp, "%s", " ( ");
2572           print_optlist (fp, node);
2573           if (parens)
2574             fprintf (fp, "%s", " ) ");
2575         }
2576     }
2577 }
2578
2579 void
2580 print_optlist (FILE *fp, const struct predicate *p)
2581 {
2582   if (p)
2583     {
2584       print_parenthesised (fp, p->pred_left);
2585       fprintf (fp,
2586                "%s%s%s",
2587                p->need_stat ? "[call stat] " : "",
2588                p->need_type ? "[need type] " : "",
2589                p->need_inum ? "[need inum] " : "");
2590       print_predicate (fp, p);
2591       fprintf (fp, " [%g] ", p->est_success_rate);
2592       if (options.debug_options & DebugSuccessRates)
2593         {
2594           fprintf (fp, "[%ld/%ld", p->perf.successes, p->perf.visits);
2595           if (p->perf.visits)
2596             {
2597               double real_rate = (double)p->perf.successes / (double)p->perf.visits;
2598               fprintf (fp, "=%g] ", real_rate);
2599             }
2600           else
2601             {
2602               fprintf (fp, "=_] ");
2603             }
2604         }
2605       print_parenthesised (fp, p->pred_right);
2606     }
2607 }
2608
2609 void show_success_rates (const struct predicate *p)
2610 {
2611   if (options.debug_options & DebugSuccessRates)
2612     {
2613       fprintf (stderr, "Predicate success rates after completion:\n");
2614       print_optlist (stderr, p);
2615       fprintf (stderr, "\n");
2616     }
2617 }
2618
2619
2620
2621
2622 #ifdef _NDEBUG
2623 /* If _NDEBUG is defined, the assertions will do nothing.   Hence
2624  * there is no point in having a function body for pred_sanity_check()
2625  * if that preprocessor macro is defined.
2626  */
2627 void
2628 pred_sanity_check (const struct predicate *predicates)
2629 {
2630   /* Do nothing, since assert is a no-op with _NDEBUG set */
2631   return;
2632 }
2633 #else
2634 void
2635 pred_sanity_check (const struct predicate *predicates)
2636 {
2637   const struct predicate *p;
2638
2639   for (p=predicates; p != NULL; p=p->pred_next)
2640     {
2641       /* All predicates must do something. */
2642       assert (p->pred_func != NULL);
2643
2644       /* All predicates must have a parser table entry. */
2645       assert (p->parser_entry != NULL);
2646
2647       /* If the parser table tells us that just one predicate function is
2648        * possible, verify that that is still the one that is in effect.
2649        * If the parser has NULL for the predicate function, that means that
2650        * the parse_xxx function fills it in, so we can't check it.
2651        */
2652       if (p->parser_entry->pred_func)
2653         {
2654           assert (p->parser_entry->pred_func == p->pred_func);
2655         }
2656
2657       switch (p->parser_entry->type)
2658         {
2659           /* Options all take effect during parsing, so there should
2660            * be no predicate entries corresponding to them.  Hence we
2661            * should not see any ARG_OPTION or ARG_POSITIONAL_OPTION
2662            * items.
2663            *
2664            * This is a silly way of coding this test, but it prevents
2665            * a compiler warning (i.e. otherwise it would think that
2666            * there would be case statements missing).
2667            */
2668         case ARG_OPTION:
2669         case ARG_POSITIONAL_OPTION:
2670           assert (p->parser_entry->type != ARG_OPTION);
2671           assert (p->parser_entry->type != ARG_POSITIONAL_OPTION);
2672           break;
2673
2674         case ARG_ACTION:
2675           assert (p->side_effects); /* actions have side effects. */
2676           if (!pred_is (p, pred_prune) && !pred_is(p, pred_quit))
2677             {
2678               /* actions other than -prune and -quit should
2679                * inhibit the default -print
2680                */
2681               assert (p->no_default_print);
2682             }
2683           break;
2684
2685         /* We happen to know that the only user of ARG_SPECIAL_PARSE
2686          * is a test, so handle it like ARG_TEST.
2687          */
2688         case ARG_SPECIAL_PARSE:
2689         case ARG_TEST:
2690         case ARG_PUNCTUATION:
2691         case ARG_NOOP:
2692           /* Punctuation and tests should have no side
2693            * effects and not inhibit default print.
2694            */
2695           assert (!p->no_default_print);
2696           assert (!p->side_effects);
2697           break;
2698         }
2699     }
2700 }
2701 #endif