Migrated from GPL version 2 to GPL version 3
[findutils.git] / find / parser.c
blobc085c2d54e3293b7e2084a907cde2d1f8ca54829
1 /* parser.c -- convert the command line args into an expression tree.
2 Copyright (C) 1990, 1991, 1992, 1993, 1994, 2000, 2001, 2003,
3 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include <config.h>
21 #include "defs.h"
22 #include <ctype.h>
23 #include <math.h>
24 #include <assert.h>
25 #include <pwd.h>
26 #include <errno.h>
27 #include <grp.h>
28 #include <fnmatch.h>
29 #include "modechange.h"
30 #include "modetype.h"
31 #include "xstrtol.h"
32 #include "xalloc.h"
33 #include "quote.h"
34 #include "quotearg.h"
35 #include "buildcmd.h"
36 #include "nextelem.h"
37 #include "stdio-safer.h"
38 #include "regextype.h"
39 #include "stat-time.h"
40 #include "xstrtod.h"
41 #include "fts_.h"
42 #include "getdate.h"
43 #include "error.h"
44 #include "gnulib-version.h"
46 #ifdef HAVE_FCNTL_H
47 #include <fcntl.h>
48 #else
49 #include <sys/file.h>
50 #endif
52 /* The presence of unistd.h is assumed by gnulib these days, so we
53 * might as well assume it too.
55 /* We need <unistd.h> for isatty(). */
56 #include <unistd.h>
57 #include <sys/stat.h>
59 #if ENABLE_NLS
60 # include <libintl.h>
61 # define _(Text) gettext (Text)
62 #else
63 # define _(Text) Text
64 #endif
65 #ifdef gettext_noop
66 # define N_(String) gettext_noop (String)
67 #else
68 /* See locate.c for explanation as to why not use (String) */
69 # define N_(String) String
70 #endif
72 #if !defined (isascii) || defined (STDC_HEADERS)
73 #ifdef isascii
74 #undef isascii
75 #endif
76 #define isascii(c) 1
77 #endif
79 #define ISDIGIT(c) (isascii ((unsigned char)c) && isdigit ((unsigned char)c))
80 #define ISUPPER(c) (isascii ((unsigned char)c) && isupper ((unsigned char)c))
82 #ifndef HAVE_ENDGRENT
83 #define endgrent()
84 #endif
85 #ifndef HAVE_ENDPWENT
86 #define endpwent()
87 #endif
89 static boolean parse_accesscheck PARAMS((const struct parser_table* entry, char **argv, int *arg_ptr));
90 static boolean parse_amin PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
91 static boolean parse_and PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
92 static boolean parse_anewer PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
93 static boolean parse_cmin PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
94 static boolean parse_cnewer PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
95 static boolean parse_comma PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
96 static boolean parse_daystart PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
97 static boolean parse_delete PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
98 static boolean parse_d PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
99 static boolean parse_depth PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
100 static boolean parse_empty PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
101 static boolean parse_exec PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
102 static boolean parse_execdir PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
103 static boolean parse_false PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
104 static boolean parse_fls PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
105 static boolean parse_fprintf PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
106 static boolean parse_follow PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
107 static boolean parse_fprint PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
108 static boolean parse_fprint0 PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
109 static boolean parse_fstype PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
110 static boolean parse_gid PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
111 static boolean parse_group PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
112 static boolean parse_help PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
113 static boolean parse_ilname PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
114 static boolean parse_iname PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
115 static boolean parse_inum PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
116 static boolean parse_ipath PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
117 static boolean parse_iregex PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
118 static boolean parse_iwholename PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
119 static boolean parse_links PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
120 static boolean parse_lname PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
121 static boolean parse_ls PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
122 static boolean parse_maxdepth PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
123 static boolean parse_mindepth PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
124 static boolean parse_mmin PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
125 static boolean parse_name PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
126 static boolean parse_negate PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
127 static boolean parse_newer PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
128 static boolean parse_newerXY PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
129 static boolean parse_noleaf PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
130 static boolean parse_nogroup PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
131 static boolean parse_nouser PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
132 static boolean parse_nowarn PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
133 static boolean parse_ok PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
134 static boolean parse_okdir PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
135 static boolean parse_or PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
136 static boolean parse_path PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
137 static boolean parse_perm PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
138 static boolean parse_print0 PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
139 static boolean parse_printf PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
140 static boolean parse_prune PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
141 static boolean parse_regex PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
142 static boolean parse_regextype PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
143 static boolean parse_samefile PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
144 #if 0
145 static boolean parse_show_control_chars PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
146 #endif
147 static boolean parse_size PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
148 static boolean parse_time PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
149 static boolean parse_true PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
150 static boolean parse_type PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
151 static boolean parse_uid PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
152 static boolean parse_used PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
153 static boolean parse_user PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
154 static boolean parse_version PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
155 static boolean parse_wholename PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
156 static boolean parse_xdev PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
157 static boolean parse_ignore_race PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
158 static boolean parse_noignore_race PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
159 static boolean parse_warn PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
160 static boolean parse_xtype PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
161 static boolean parse_quit PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
163 boolean parse_print PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
166 static boolean insert_type PARAMS((char **argv, int *arg_ptr, const struct parser_table *entry, PRED_FUNC which_pred));
167 static boolean insert_regex PARAMS((char *argv[], int *arg_ptr, const struct parser_table *entry, int regex_options));
168 static boolean insert_fprintf (struct format_val *vec,
169 const struct parser_table *entry,
170 PRED_FUNC func,
171 const char *format);
173 static struct segment **make_segment PARAMS((struct segment **segment, char *format, int len,
174 int kind, char format_char, char aux_format_char,
175 struct predicate *pred));
176 static boolean insert_exec_ok PARAMS((const char *action, const struct parser_table *entry, int dirfd, char *argv[], int *arg_ptr));
177 static boolean get_comp_type PARAMS((const char **str, enum comparison_type *comp_type));
178 static boolean get_relative_timestamp PARAMS((const char *str, struct time_val *tval, time_t origin, double sec_per_unit, const char *overflowmessage));
179 static boolean get_num PARAMS((const char *str, uintmax_t *num, enum comparison_type *comp_type));
180 static struct predicate* insert_num PARAMS((char *argv[], int *arg_ptr, const struct parser_table *entry));
181 static void open_output_file (const char *path, struct format_val *p);
182 static void open_stdout (struct format_val *p);
183 static boolean stream_is_tty(FILE *fp);
184 static boolean parse_noop PARAMS((const struct parser_table* entry, char **argv, int *arg_ptr));
186 #define PASTE(x,y) x##y
187 #define STRINGIFY(s) #s
189 #define PARSE_OPTION(what,suffix) \
190 { (ARG_OPTION), (what), PASTE(parse_,suffix), NULL }
192 #define PARSE_POSOPT(what,suffix) \
193 { (ARG_POSITIONAL_OPTION), (what), PASTE(parse_,suffix), NULL }
195 #define PARSE_TEST(what,suffix) \
196 { (ARG_TEST), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) }
198 #define PARSE_TEST_NP(what,suffix) \
199 { (ARG_TEST), (what), PASTE(parse_,suffix), NULL }
201 #define PARSE_ACTION(what,suffix) \
202 { (ARG_ACTION), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) }
204 #define PARSE_ACTION_NP(what,suffix) \
205 { (ARG_ACTION), (what), PASTE(parse_,suffix), NULL }
207 #define PARSE_PUNCTUATION(what,suffix) \
208 { (ARG_PUNCTUATION), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) }
211 /* Predicates we cannot handle in the usual way. If you add an entry
212 * to this table, double-check the switch statement in
213 * pred_sanity_check() to make sure that the new case is being
214 * correctly handled.
216 static struct parser_table const parse_entry_newerXY =
218 ARG_SPECIAL_PARSE, "newerXY", parse_newerXY, pred_newerXY /* BSD */
221 /* GNU find predicates that are not mentioned in POSIX.2 are marked `GNU'.
222 If they are in some Unix versions of find, they are marked `Unix'. */
224 static struct parser_table const parse_table[] =
226 PARSE_PUNCTUATION("!", negate),
227 PARSE_PUNCTUATION("not", negate), /* GNU */
228 PARSE_PUNCTUATION("(", openparen),
229 PARSE_PUNCTUATION(")", closeparen),
230 PARSE_PUNCTUATION(",", comma), /* GNU */
231 PARSE_PUNCTUATION("a", and),
232 PARSE_TEST ("amin", amin), /* GNU */
233 PARSE_PUNCTUATION("and", and), /* GNU */
234 PARSE_TEST ("anewer", anewer), /* GNU */
235 {ARG_TEST, "atime", parse_time, pred_atime},
236 PARSE_TEST ("cmin", cmin), /* GNU */
237 PARSE_TEST ("cnewer", cnewer), /* GNU */
238 {ARG_TEST, "ctime", parse_time, pred_ctime},
239 PARSE_POSOPT ("daystart", daystart), /* GNU */
240 PARSE_ACTION ("delete", delete), /* GNU, Mac OS, FreeBSD */
241 PARSE_OPTION ("d", d), /* Mac OS X, FreeBSD, NetBSD, OpenBSD, but deprecated in favour of -depth */
242 PARSE_OPTION ("depth", depth),
243 PARSE_TEST ("empty", empty), /* GNU */
244 {ARG_ACTION, "exec", parse_exec, pred_exec}, /* POSIX */
245 {ARG_TEST, "executable", parse_accesscheck, pred_executable}, /* GNU, 4.3.0+ */
246 PARSE_ACTION ("execdir", execdir), /* *BSD, GNU */
247 PARSE_ACTION ("fls", fls), /* GNU */
248 PARSE_POSOPT ("follow", follow), /* GNU, Unix */
249 PARSE_ACTION ("fprint", fprint), /* GNU */
250 PARSE_ACTION ("fprint0", fprint0), /* GNU */
251 {ARG_ACTION, "fprintf", parse_fprintf, pred_fprintf}, /* GNU */
252 PARSE_TEST ("fstype", fstype), /* GNU, Unix */
253 PARSE_TEST ("gid", gid), /* GNU */
254 PARSE_TEST ("group", group),
255 PARSE_OPTION ("ignore_readdir_race", ignore_race), /* GNU */
256 PARSE_TEST ("ilname", ilname), /* GNU */
257 PARSE_TEST ("iname", iname), /* GNU */
258 PARSE_TEST ("inum", inum), /* GNU, Unix */
259 PARSE_TEST ("ipath", ipath), /* GNU, deprecated in favour of iwholename */
260 PARSE_TEST_NP ("iregex", iregex), /* GNU */
261 PARSE_TEST_NP ("iwholename", iwholename), /* GNU */
262 PARSE_TEST ("links", links),
263 PARSE_TEST ("lname", lname), /* GNU */
264 PARSE_ACTION ("ls", ls), /* GNU, Unix */
265 PARSE_OPTION ("maxdepth", maxdepth), /* GNU */
266 PARSE_OPTION ("mindepth", mindepth), /* GNU */
267 PARSE_TEST ("mmin", mmin), /* GNU */
268 PARSE_OPTION ("mount", xdev), /* Unix */
269 {ARG_TEST, "mtime", parse_time, pred_mtime},
270 PARSE_TEST ("name", name),
271 #ifdef UNIMPLEMENTED_UNIX
272 PARSE(ARG_UNIMPLEMENTED, "ncpio", ncpio), /* Unix */
273 #endif
274 PARSE_TEST ("newer", newer),
275 {ARG_TEST, "atime", parse_time, pred_atime},
276 PARSE_OPTION ("noleaf", noleaf), /* GNU */
277 PARSE_TEST ("nogroup", nogroup),
278 PARSE_TEST ("nouser", nouser),
279 PARSE_OPTION ("noignore_readdir_race", noignore_race), /* GNU */
280 PARSE_POSOPT ("nowarn", nowarn), /* GNU */
281 PARSE_PUNCTUATION("o", or),
282 PARSE_PUNCTUATION("or", or), /* GNU */
283 PARSE_ACTION ("ok", ok),
284 PARSE_ACTION ("okdir", okdir), /* GNU (-execdir is BSD) */
285 PARSE_TEST ("path", path), /* GNU, HP-UX, GNU prefers wholename */
286 PARSE_TEST ("perm", perm),
287 PARSE_ACTION ("print", print),
288 PARSE_ACTION ("print0", print0), /* GNU */
289 {ARG_ACTION, "printf", parse_printf, NULL}, /* GNU */
290 PARSE_ACTION ("prune", prune),
291 PARSE_ACTION ("quit", quit), /* GNU */
292 {ARG_TEST, "readable", parse_accesscheck, pred_readable}, /* GNU, 4.3.0+ */
293 PARSE_TEST ("regex", regex), /* GNU */
294 PARSE_OPTION ("regextype", regextype), /* GNU */
295 PARSE_TEST ("samefile", samefile), /* GNU */
296 #if 0
297 PARSE_OPTION ("show-control-chars", show_control_chars), /* GNU, 4.3.0+ */
298 #endif
299 PARSE_TEST ("size", size),
300 PARSE_TEST ("type", type),
301 PARSE_TEST ("uid", uid), /* GNU */
302 PARSE_TEST ("used", used), /* GNU */
303 PARSE_TEST ("user", user),
304 PARSE_OPTION ("warn", warn), /* GNU */
305 PARSE_TEST_NP ("wholename", wholename), /* GNU, replaces -path */
306 {ARG_TEST, "writable", parse_accesscheck, pred_writable}, /* GNU, 4.3.0+ */
307 PARSE_OPTION ("xdev", xdev),
308 PARSE_TEST ("xtype", xtype), /* GNU */
309 #ifdef UNIMPLEMENTED_UNIX
310 /* It's pretty ugly for find to know about archive formats.
311 Plus what it could do with cpio archives is very limited.
312 Better to leave it out. */
313 PARSE(ARG_UNIMPLEMENTED, "cpio", cpio), /* Unix */
314 #endif
315 /* gnulib's stdbool.h might have made true and false into macros,
316 * so we can't leave named 'true' and 'false' tokens, so we have
317 * to expeant the relevant entries longhand.
319 {ARG_TEST, "false", parse_false, pred_false}, /* GNU */
320 {ARG_TEST, "true", parse_true, pred_true }, /* GNU */
321 {ARG_NOOP, "noop", NULL, pred_true }, /* GNU, internal use only */
323 /* Various other cases that don't fit neatly into our macro scheme. */
324 {ARG_TEST, "help", parse_help, NULL}, /* GNU */
325 {ARG_TEST, "-help", parse_help, NULL}, /* GNU */
326 {ARG_TEST, "version", parse_version, NULL}, /* GNU */
327 {ARG_TEST, "-version", parse_version, NULL}, /* GNU */
328 {0, 0, 0, 0}
332 static const char *first_nonoption_arg = NULL;
333 static const struct parser_table *noop = NULL;
336 static const struct parser_table*
337 get_noop(void)
339 int i;
340 if (NULL == noop)
342 for (i = 0; parse_table[i].parser_name != 0; i++)
344 if (ARG_NOOP ==parse_table[i].type)
346 noop = &(parse_table[i]);
347 break;
351 return noop;
354 static int
355 get_stat_Ytime(const struct stat *p,
356 char what,
357 struct timespec *ret)
359 switch (what)
361 case 'a':
362 *ret = get_stat_atime(p);
363 return 1;
364 case 'B':
365 *ret = get_stat_birthtime(p);
366 return (ret->tv_nsec >= 0);
367 case 'c':
368 *ret = get_stat_ctime(p);
369 return 1;
370 case 'm':
371 *ret = get_stat_mtime(p);
372 return 1;
373 default:
374 assert (0);
375 abort();
379 void
380 set_follow_state(enum SymlinkOption opt)
382 if (options.debug_options & DebugStat)
384 /* For DebugStat, the choice is made at runtime within debug_stat()
385 * by checking the contents of the symlink_handling variable.
387 options.xstat = debug_stat;
389 else
391 switch (opt)
393 case SYMLINK_ALWAYS_DEREF: /* -L */
394 options.xstat = optionl_stat;
395 options.no_leaf_check = true;
396 break;
398 case SYMLINK_NEVER_DEREF: /* -P (default) */
399 options.xstat = optionp_stat;
400 /* Can't turn no_leaf_check off because the user might have specified
401 * -noleaf anyway
403 break;
405 case SYMLINK_DEREF_ARGSONLY: /* -H */
406 options.xstat = optionh_stat;
407 options.no_leaf_check = true;
410 options.symlink_handling = opt;
414 void
415 parse_begin_user_args (char **args, int argno, const struct predicate *last, const struct predicate *predicates)
417 (void) args;
418 (void) argno;
419 (void) last;
420 (void) predicates;
421 first_nonoption_arg = NULL;
424 void
425 parse_end_user_args (char **args, int argno, const struct predicate *last, const struct predicate *predicates)
427 /* does nothing */
428 (void) args;
429 (void) argno;
430 (void) last;
431 (void) predicates;
435 /* Check that it is legal to fid the given primary in its
436 * position and return it.
438 const struct parser_table*
439 found_parser(const char *original_arg, const struct parser_table *entry)
441 /* If this is an option, but we have already had a
442 * non-option argument, the user may be under the
443 * impression that the behaviour of the option
444 * argument is conditional on some preceding
445 * tests. This might typically be the case with,
446 * for example, -maxdepth.
448 * The options -daystart and -follow are exempt
449 * from this treatment, since their positioning
450 * in the command line does have an effect on
451 * subsequent tests but not previous ones. That
452 * might be intentional on the part of the user.
454 if (entry->type != ARG_POSITIONAL_OPTION)
456 /* Something other than -follow/-daystart.
457 * If this is an option, check if it followed
458 * a non-option and if so, issue a warning.
460 if (entry->type == ARG_OPTION)
462 if ((first_nonoption_arg != NULL)
463 && options.warnings )
465 /* option which follows a non-option */
466 error (0, 0,
467 _("warning: you have specified the %s "
468 "option after a non-option argument %s, "
469 "but options are not positional (%s affects "
470 "tests specified before it as well as those "
471 "specified after it). Please specify options "
472 "before other arguments.\n"),
473 original_arg,
474 first_nonoption_arg,
475 original_arg);
478 else
480 /* Not an option or a positional option,
481 * so remember we've seen it in order to
482 * use it in a possible future warning message.
484 if (first_nonoption_arg == NULL)
486 first_nonoption_arg = original_arg;
491 return entry;
495 /* Return a pointer to the parser function to invoke for predicate
496 SEARCH_NAME.
497 Return NULL if SEARCH_NAME is not a valid predicate name. */
499 const struct parser_table*
500 find_parser (char *search_name)
502 int i;
503 const char *original_arg = search_name;
505 /* Ugh. Special case -newerXY. */
506 if (0 == strncmp("-newer", search_name, 6)
507 && (8 == strlen(search_name)))
509 return found_parser(original_arg, &parse_entry_newerXY);
512 if (*search_name == '-')
513 search_name++;
515 for (i = 0; parse_table[i].parser_name != 0; i++)
517 if (strcmp (parse_table[i].parser_name, search_name) == 0)
519 return found_parser(original_arg, &parse_table[i]);
522 return NULL;
525 static float
526 estimate_file_age_success_rate(float num_days)
528 if (num_days < 0.1)
530 /* Assume 1% of files have timestamps in the future */
531 return 0.01f;
533 else if (num_days < 1)
535 /* Assume 30% of files have timestamps today */
536 return 0.3f;
538 else if (num_days > 100)
540 /* Assume 30% of files are very old */
541 return 0.3f;
543 else
545 /* Assume 39% of files are between 1 and 100 days old. */
546 return 0.39f;
550 static float
551 estimate_timestamp_success_rate(time_t when)
553 int num_days = (options.cur_day_start - when) / 86400;
554 return estimate_file_age_success_rate(num_days);
557 /* Collect an argument from the argument list, or
558 * return false.
560 static boolean
561 collect_arg(char **argv, int *arg_ptr, const char **collected_arg)
563 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
565 *collected_arg = NULL;
566 return false;
568 else
570 *collected_arg = argv[*arg_ptr];
571 (*arg_ptr)++;
572 return true;
576 static boolean
577 collect_arg_stat_info(char **argv, int *arg_ptr, struct stat *p)
579 const char *filename;
580 if (collect_arg(argv, arg_ptr, &filename))
582 if (0 == (options.xstat)(filename, p))
584 return true;
586 else
588 fatal_file_error(filename);
591 else
593 return false;
597 /* The parsers are responsible to continue scanning ARGV for
598 their arguments. Each parser knows what is and isn't
599 allowed for itself.
601 ARGV is the argument array.
602 *ARG_PTR is the index to start at in ARGV,
603 updated to point beyond the last element consumed.
605 The predicate structure is updated with the new information. */
608 static boolean
609 parse_and (const struct parser_table* entry, char **argv, int *arg_ptr)
611 struct predicate *our_pred;
613 (void) argv;
614 (void) arg_ptr;
616 our_pred = get_new_pred (entry);
617 our_pred->pred_func = pred_and;
618 our_pred->p_type = BI_OP;
619 our_pred->p_prec = AND_PREC;
620 our_pred->need_stat = our_pred->need_type = false;
621 return true;
624 static boolean
625 parse_anewer (const struct parser_table* entry, char **argv, int *arg_ptr)
627 struct stat stat_newer;
629 set_stat_placeholders(&stat_newer);
630 if (collect_arg_stat_info(argv, arg_ptr, &stat_newer))
632 struct predicate *our_pred = insert_primary (entry);
633 our_pred->args.reftime.xval = XVAL_ATIME;
634 our_pred->args.reftime.ts = get_stat_mtime(&stat_newer);
635 our_pred->args.reftime.kind = COMP_GT;
636 our_pred->est_success_rate = estimate_timestamp_success_rate(stat_newer.st_mtime);
637 return true;
639 return false;
642 boolean
643 parse_closeparen (const struct parser_table* entry, char **argv, int *arg_ptr)
645 struct predicate *our_pred;
647 (void) argv;
648 (void) arg_ptr;
650 our_pred = get_new_pred (entry);
651 our_pred->pred_func = pred_closeparen;
652 our_pred->p_type = CLOSE_PAREN;
653 our_pred->p_prec = NO_PREC;
654 our_pred->need_stat = our_pred->need_type = false;
655 return true;
658 static boolean
659 parse_cnewer (const struct parser_table* entry, char **argv, int *arg_ptr)
661 struct stat stat_newer;
663 set_stat_placeholders(&stat_newer);
664 if (collect_arg_stat_info(argv, arg_ptr, &stat_newer))
666 struct predicate *our_pred = insert_primary (entry);
667 our_pred->args.reftime.xval = XVAL_CTIME; /* like -newercm */
668 our_pred->args.reftime.ts = get_stat_mtime(&stat_newer);
669 our_pred->args.reftime.kind = COMP_GT;
670 our_pred->est_success_rate = estimate_timestamp_success_rate(stat_newer.st_mtime);
671 return true;
673 return false;
676 static boolean
677 parse_comma (const struct parser_table* entry, char **argv, int *arg_ptr)
679 struct predicate *our_pred;
681 (void) argv;
682 (void) arg_ptr;
684 our_pred = get_new_pred (entry);
685 our_pred->pred_func = pred_comma;
686 our_pred->p_type = BI_OP;
687 our_pred->p_prec = COMMA_PREC;
688 our_pred->need_stat = our_pred->need_type = false;
689 our_pred->est_success_rate = 1.0f;
690 return true;
693 static boolean
694 parse_daystart (const struct parser_table* entry, char **argv, int *arg_ptr)
696 struct tm *local;
698 (void) entry;
699 (void) argv;
700 (void) arg_ptr;
702 if (options.full_days == false)
704 options.cur_day_start += DAYSECS;
705 local = localtime (&options.cur_day_start);
706 options.cur_day_start -= (local
707 ? (local->tm_sec + local->tm_min * 60
708 + local->tm_hour * 3600)
709 : options.cur_day_start % DAYSECS);
710 options.full_days = true;
712 return true;
715 static boolean
716 parse_delete (const struct parser_table* entry, char *argv[], int *arg_ptr)
718 struct predicate *our_pred;
719 (void) argv;
720 (void) arg_ptr;
722 our_pred = insert_primary (entry);
723 our_pred->side_effects = our_pred->no_default_print = true;
724 /* -delete implies -depth */
725 options.do_dir_first = false;
727 /* We do not need stat information because we check for the case
728 * (errno==EISDIR) in pred_delete.
730 our_pred->need_stat = our_pred->need_type = false;
732 our_pred->est_success_rate = 1.0f;
733 return true;
736 static boolean
737 parse_depth (const struct parser_table* entry, char **argv, int *arg_ptr)
739 (void) entry;
740 (void) argv;
742 options.do_dir_first = false;
743 return parse_noop(entry, argv, arg_ptr);
746 static boolean
747 parse_d (const struct parser_table* entry, char **argv, int *arg_ptr)
749 if (options.warnings)
751 error (0, 0,
752 _("warning: the -d option is deprecated; please use -depth instead, because the latter is a POSIX-compliant feature."));
754 return parse_depth(entry, argv, arg_ptr);
757 static boolean
758 parse_empty (const struct parser_table* entry, char **argv, int *arg_ptr)
760 struct predicate *our_pred;
761 (void) argv;
762 (void) arg_ptr;
764 our_pred = insert_primary (entry);
765 our_pred->est_success_rate = 0.01f; /* assume 1% of files are empty. */
766 return true;
769 static boolean
770 parse_exec (const struct parser_table* entry, char **argv, int *arg_ptr)
772 return insert_exec_ok ("-exec", entry, get_start_dirfd(), argv, arg_ptr);
775 static boolean
776 parse_execdir (const struct parser_table* entry, char **argv, int *arg_ptr)
778 return insert_exec_ok ("-execdir", entry, -1, argv, arg_ptr);
781 static boolean
782 parse_false (const struct parser_table* entry, char **argv, int *arg_ptr)
784 struct predicate *our_pred;
786 (void) argv;
787 (void) arg_ptr;
789 our_pred = insert_primary (entry);
790 our_pred->need_stat = our_pred->need_type = false;
791 our_pred->side_effects = our_pred->no_default_print = false;
792 our_pred->est_success_rate = 0.0f;
793 return true;
796 static boolean
797 insert_fls (const struct parser_table* entry, const char *filename)
799 struct predicate *our_pred = insert_primary (entry);
800 if (filename)
801 open_output_file (filename, &our_pred->args.printf_vec);
802 else
803 open_stdout (&our_pred->args.printf_vec);
804 our_pred->side_effects = our_pred->no_default_print = true;
805 our_pred->est_success_rate = 1.0f;
806 return true;
810 static boolean
811 parse_fls (const struct parser_table* entry, char **argv, int *arg_ptr)
813 const char *filename;
814 return collect_arg(argv, arg_ptr, &filename)
815 && insert_fls(entry, filename);
818 static boolean
819 parse_follow (const struct parser_table* entry, char **argv, int *arg_ptr)
821 set_follow_state(SYMLINK_ALWAYS_DEREF);
822 return parse_noop(entry, argv, arg_ptr);
825 static boolean
826 parse_fprint (const struct parser_table* entry, char **argv, int *arg_ptr)
828 struct predicate *our_pred;
829 const char *filename;
830 if (collect_arg(argv, arg_ptr, &filename))
832 our_pred = insert_primary (entry);
833 open_output_file (filename, &our_pred->args.printf_vec);
834 our_pred->side_effects = our_pred->no_default_print = true;
835 our_pred->need_stat = our_pred->need_type = false;
836 our_pred->est_success_rate = 1.0f;
837 return true;
839 else
841 return false;
845 static boolean
846 insert_fprint(const struct parser_table* entry, const char *filename)
848 struct predicate *our_pred = insert_primary (entry);
849 if (filename)
850 open_output_file (filename, &our_pred->args.printf_vec);
851 else
852 open_stdout (&our_pred->args.printf_vec);
853 our_pred->side_effects = our_pred->no_default_print = true;
854 our_pred->need_stat = our_pred->need_type = false;
855 our_pred->est_success_rate = 1.0f;
856 return true;
860 static boolean
861 parse_fprint0 (const struct parser_table* entry, char **argv, int *arg_ptr)
863 const char *filename;
864 if (collect_arg(argv, arg_ptr, &filename))
865 return insert_fprint(entry, filename);
866 else
867 return false;
870 static float estimate_fstype_success_rate(const char *fsname)
872 struct stat dir_stat;
873 const char *dir = "/";
874 if (0 == stat(dir, &dir_stat))
876 const char *fstype = filesystem_type(&dir_stat, dir);
877 /* Assume most files are on the same file system type as the root fs. */
878 if (0 == strcmp(fsname, fstype))
879 return 0.7f;
880 else
881 return 0.3f;
883 return 1.0f;
887 static boolean
888 parse_fstype (const struct parser_table* entry, char **argv, int *arg_ptr)
890 const char *typename;
891 if (collect_arg(argv, arg_ptr, &typename))
893 struct predicate *our_pred = insert_primary (entry);
894 our_pred->args.str = typename;
896 /* This is an expensive operation, so although there are
897 * circumstances where it is selective, we ignore this fact
898 * because we probably don't want to promote this test to the
899 * front anyway.
901 our_pred->est_success_rate = estimate_fstype_success_rate(typename);
902 return true;
904 else
906 return false;
910 static boolean
911 parse_gid (const struct parser_table* entry, char **argv, int *arg_ptr)
913 struct predicate *p = insert_num (argv, arg_ptr, entry);
914 if (p)
916 p->est_success_rate = (p->args.numinfo.l_val < 100) ? 0.99 : 0.2;
917 return true;
919 else
921 return false;
926 static int
927 safe_atoi (const char *s)
929 long lval;
930 char *end;
932 errno = 0;
933 lval = strtol(s, &end, 10);
934 if ( (LONG_MAX == lval) || (LONG_MIN == lval) )
936 /* max/min possible value, or an error. */
937 if (errno == ERANGE)
939 /* too big, or too small. */
940 error(1, errno, "%s", s);
942 else
944 /* not a valid number */
945 error(1, errno, "%s", s);
947 /* Otherwise, we do a range chack against INT_MAX and INT_MIN
948 * below.
952 if (lval > INT_MAX || lval < INT_MIN)
954 /* The number was in range for long, but not int. */
955 errno = ERANGE;
956 error(1, errno, "%s", s);
958 else if (*end)
960 error(1, errno, "Unexpected suffix %s on %s",
961 quotearg_n_style(0, options.err_quoting_style, end),
962 quotearg_n_style(1, options.err_quoting_style, s));
964 else if (end == s)
966 error(1, errno, "Expected an integer: %s",
967 quotearg_n_style(0, options.err_quoting_style, s));
969 return (int)lval;
973 static boolean
974 parse_group (const struct parser_table* entry, char **argv, int *arg_ptr)
976 const char *groupname;
978 if (collect_arg(argv, arg_ptr, &groupname))
980 gid_t gid;
981 struct predicate *our_pred;
982 struct group *cur_gr = getgrnam(groupname);
983 endgrent();
984 if (cur_gr)
986 gid = cur_gr->gr_gid;
988 else
990 const int gid_len = strspn (groupname, "0123456789");
991 if (gid_len)
993 if (groupname[gid_len] == 0)
995 gid = safe_atoi (groupname);
997 else
999 /* XXX: no test in test suite for this */
1000 error(1, 0, _("%s is not the name of an existing group and"
1001 " it does not look like a numeric group ID "
1002 "because it has the unexpected suffix %s"),
1003 quotearg_n_style(0, options.err_quoting_style, groupname),
1004 quotearg_n_style(1, options.err_quoting_style, groupname+gid_len));
1005 return false;
1008 else
1010 if (*groupname)
1012 /* XXX: no test in test suite for this */
1013 error(1, 0, _("%s is not the name of an existing group"),
1014 quotearg_n_style(0, options.err_quoting_style, groupname));
1016 else
1018 error(1, 0, _("argument to -group is empty, but should be a group name"));
1020 return false;
1023 our_pred = insert_primary (entry);
1024 our_pred->args.gid = gid;
1025 our_pred->est_success_rate = (our_pred->args.numinfo.l_val < 100) ? 0.99 : 0.2;
1026 return true;
1028 return false;
1031 static boolean
1032 parse_help (const struct parser_table* entry, char **argv, int *arg_ptr)
1034 (void) entry;
1035 (void) argv;
1036 (void) arg_ptr;
1038 usage(stdout, 0, NULL);
1039 puts (_("\n\
1040 default path is the current directory; default expression is -print\n\
1041 expression may consist of: operators, options, tests, and actions:\n"));
1042 puts (_("\
1043 operators (decreasing precedence; -and is implicit where no others are given):\n\
1044 ( EXPR ) ! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2\n\
1045 EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2\n"));
1046 puts (_("\
1047 positional options (always true): -daystart -follow -regextype\n\n\
1048 normal options (always true, specified before other expressions):\n\
1049 -depth --help -maxdepth LEVELS -mindepth LEVELS -mount -noleaf\n\
1050 --version -xdev -ignore_readdir_race -noignore_readdir_race\n"));
1051 puts (_("\
1052 tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N\n\
1053 -cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME\n\
1054 -ilname PATTERN -iname PATTERN -inum N -iwholename PATTERN -iregex PATTERN\n\
1055 -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE"));
1056 puts (_("\
1057 -nouser -nogroup -path PATTERN -perm [+-]MODE -regex PATTERN\n\
1058 -readable -writable -executable\n\
1059 -wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N\n\
1060 -used N -user NAME -xtype [bcdpfls]\n"));
1061 puts (_("\
1062 actions: -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print \n\
1063 -fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit\n\
1064 -exec COMMAND ; -exec COMMAND {} + -ok COMMAND ;\n\
1065 -execdir COMMAND ; -execdir COMMAND {} + -okdir COMMAND ;\n\
1066 "));
1067 puts (_("Report (and track progress on fixing) bugs via the findutils bug-reporting\n\
1068 page at http://savannah.gnu.org/ or, if you have no web access, by sending\n\
1069 email to <bug-findutils@gnu.org>."));
1070 exit (0);
1073 static float
1074 estimate_pattern_match_rate(const char *pattern, int is_regex)
1076 if (strpbrk(pattern, "*?[") || (is_regex && strpbrk(pattern, ".")))
1078 /* A wildcard; assume the pattern matches most files. */
1079 return 0.8f;
1081 else
1083 return 0.1f;
1087 static boolean
1088 parse_ilname (const struct parser_table* entry, char **argv, int *arg_ptr)
1090 const char *name;
1091 if (collect_arg(argv, arg_ptr, &name))
1093 struct predicate *our_pred = insert_primary (entry);
1094 our_pred->args.str = name;
1095 /* Use the generic glob pattern estimator to figure out how many
1096 * links will match, but bear in mind that most files won't be links.
1098 our_pred->est_success_rate = 0.1 * estimate_pattern_match_rate(name, 0);
1099 return true;
1101 else
1103 return false;
1108 /* sanity check the fnmatch() function to make sure that case folding
1109 * is supported (as opposed to just having the flag ignored).
1111 static boolean
1112 fnmatch_sanitycheck(void)
1114 static boolean checked = false;
1115 if (!checked)
1117 if (0 != fnmatch("foo", "foo", 0)
1118 || 0 == fnmatch("Foo", "foo", 0)
1119 || 0 != fnmatch("Foo", "foo", FNM_CASEFOLD))
1121 error (1, 0, _("sanity check of the fnmatch() library function failed."));
1122 return false;
1124 checked = true;
1126 return checked;
1130 static boolean
1131 check_name_arg(const char *pred, const char *arg)
1133 if (strchr(arg, '/'))
1135 error(0, 0,_("warning: Unix filenames usually don't contain slashes (though pathnames do). That means that '%s %s' will probably evaluate to false all the time on this system. You might find the '-wholename' test more useful, or perhaps '-samefile'. Alternatively, if you are using GNU grep, you could use 'find ... -print0 | grep -FzZ %s'."),
1136 pred,
1137 safely_quote_err_filename(0, arg),
1138 safely_quote_err_filename(1, arg));
1140 return true; /* allow it anyway */
1145 static boolean
1146 parse_iname (const struct parser_table* entry, char **argv, int *arg_ptr)
1148 const char *name;
1149 fnmatch_sanitycheck();
1150 if (collect_arg(argv, arg_ptr, &name))
1152 if (check_name_arg("-iname", name))
1154 struct predicate *our_pred = insert_primary (entry);
1155 our_pred->need_stat = our_pred->need_type = false;
1156 our_pred->args.str = name;
1157 our_pred->est_success_rate = estimate_pattern_match_rate(name, 0);
1158 return true;
1161 return false;
1164 static boolean
1165 parse_inum (const struct parser_table* entry, char **argv, int *arg_ptr)
1167 struct predicate *p = insert_num (argv, arg_ptr, entry);
1168 if (p)
1170 /* inode number is exact match only, so very low proportions of
1171 * files match
1173 p->est_success_rate = 1e-6;
1174 return true;
1176 else
1178 return false;
1182 /* -ipath is deprecated (at RMS's request) in favour of
1183 * -iwholename. See the node "GNU Manuals" in standards.texi
1184 * for the rationale for this (basically, GNU prefers the use
1185 * of the phrase "file name" to "path name"
1187 static boolean
1188 parse_ipath (const struct parser_table* entry, char **argv, int *arg_ptr)
1190 error (0, 0,
1191 _("warning: the predicate -ipath is deprecated; please use -iwholename instead."));
1193 return parse_iwholename(entry, argv, arg_ptr);
1196 static boolean
1197 parse_iwholename (const struct parser_table* entry, char **argv, int *arg_ptr)
1199 const char *name;
1201 fnmatch_sanitycheck();
1202 if (collect_arg(argv, arg_ptr, &name))
1204 struct predicate *our_pred = insert_primary_withpred (entry, pred_ipath);
1205 our_pred->need_stat = our_pred->need_type = false;
1206 our_pred->args.str = name;
1207 our_pred->est_success_rate = estimate_pattern_match_rate(name, 0);
1208 return true;
1210 return false;
1213 static boolean
1214 parse_iregex (const struct parser_table* entry, char **argv, int *arg_ptr)
1216 return insert_regex (argv, arg_ptr, entry, RE_ICASE|options.regex_options);
1219 static boolean
1220 parse_links (const struct parser_table* entry, char **argv, int *arg_ptr)
1222 struct predicate *p = insert_num (argv, arg_ptr, entry);
1223 if (p)
1225 if (p->args.numinfo.l_val == 1)
1226 p->est_success_rate = 0.99;
1227 else if (p->args.numinfo.l_val == 2)
1228 p->est_success_rate = 0.01;
1229 else
1230 p->est_success_rate = 1e-3;
1231 return true;
1233 else
1235 return false;
1239 static boolean
1240 parse_lname (const struct parser_table* entry, char **argv, int *arg_ptr)
1242 const char *name;
1243 fnmatch_sanitycheck();
1244 if (collect_arg(argv, arg_ptr, &name))
1246 struct predicate *our_pred = insert_primary (entry);
1247 our_pred->args.str = name;
1248 our_pred->est_success_rate = 0.1 * estimate_pattern_match_rate(name, 0);
1249 return true;
1251 return false;
1254 static boolean
1255 parse_ls (const struct parser_table* entry, char **argv, int *arg_ptr)
1257 (void) &argv;
1258 (void) &arg_ptr;
1259 return insert_fls(entry, NULL);
1262 static boolean
1263 insert_depthspec(const struct parser_table* entry, char **argv, int *arg_ptr,
1264 int *limitptr)
1266 const char *depthstr;
1267 int depth_len;
1268 const char *predicate = argv[(*arg_ptr)-1];
1269 if (collect_arg(argv, arg_ptr, &depthstr))
1271 depth_len = strspn (depthstr, "0123456789");
1272 if ((depth_len > 0) && (depthstr[depth_len] == 0))
1274 (*limitptr) = safe_atoi (depthstr);
1275 if (*limitptr >= 0)
1277 return parse_noop(entry, argv, arg_ptr);
1280 error(1, 0, _("Expected a positive decimal integer argument to %s, but got %s"),
1281 predicate,
1282 quotearg_n_style(0, options.err_quoting_style, depthstr));
1283 return false;
1285 /* missing argument */
1286 return false;
1290 static boolean
1291 parse_maxdepth (const struct parser_table* entry, char **argv, int *arg_ptr)
1293 return insert_depthspec(entry, argv, arg_ptr, &options.maxdepth);
1296 static boolean
1297 parse_mindepth (const struct parser_table* entry, char **argv, int *arg_ptr)
1299 return insert_depthspec(entry, argv, arg_ptr, &options.mindepth);
1303 static boolean
1304 do_parse_xmin (const struct parser_table* entry, char **argv, int *arg_ptr, enum xval xv)
1306 const char *minutes;
1308 if (collect_arg(argv, arg_ptr, &minutes))
1310 struct time_val tval;
1311 tval.xval = xv;
1312 if (get_relative_timestamp(minutes, &tval,
1313 options.cur_day_start + DAYSECS, 60,
1314 "arithmetic overflow while converting %s "
1315 "minutes to a number of seconds"))
1317 struct predicate *our_pred = insert_primary (entry);
1318 our_pred->args.reftime = tval;
1319 our_pred->est_success_rate = estimate_timestamp_success_rate(tval.ts.tv_sec);
1320 return true;
1323 return false;
1325 static boolean
1326 parse_amin (const struct parser_table* entry, char **argv, int *arg_ptr)
1328 return do_parse_xmin(entry, argv, arg_ptr, XVAL_ATIME);
1331 static boolean
1332 parse_cmin (const struct parser_table* entry, char **argv, int *arg_ptr)
1334 return do_parse_xmin(entry, argv, arg_ptr, XVAL_CTIME);
1338 static boolean
1339 parse_mmin (const struct parser_table* entry, char **argv, int *arg_ptr)
1341 return do_parse_xmin(entry, argv, arg_ptr, XVAL_MTIME);
1344 static boolean
1345 parse_name (const struct parser_table* entry, char **argv, int *arg_ptr)
1347 const char *name;
1348 if (collect_arg(argv, arg_ptr, &name))
1350 fnmatch_sanitycheck();
1351 if (check_name_arg("-name", name))
1353 struct predicate *our_pred = insert_primary (entry);
1354 our_pred->need_stat = our_pred->need_type = false;
1355 our_pred->args.str = name;
1356 our_pred->est_success_rate = estimate_pattern_match_rate(name, 0);
1357 return true;
1360 return false;
1363 static boolean
1364 parse_negate (const struct parser_table* entry, char **argv, int *arg_ptr)
1366 struct predicate *our_pred;
1368 (void) &argv;
1369 (void) &arg_ptr;
1371 our_pred = get_new_pred_chk_op (entry);
1372 our_pred->pred_func = pred_negate;
1373 our_pred->p_type = UNI_OP;
1374 our_pred->p_prec = NEGATE_PREC;
1375 our_pred->need_stat = our_pred->need_type = false;
1376 return true;
1379 static boolean
1380 parse_newer (const struct parser_table* entry, char **argv, int *arg_ptr)
1382 struct predicate *our_pred;
1383 struct stat stat_newer;
1385 set_stat_placeholders(&stat_newer);
1386 if (collect_arg_stat_info(argv, arg_ptr, &stat_newer))
1388 our_pred = insert_primary (entry);
1389 our_pred->args.reftime.ts = get_stat_mtime(&stat_newer);
1390 our_pred->args.reftime.xval = XVAL_MTIME;
1391 our_pred->args.reftime.kind = COMP_GT;
1392 our_pred->est_success_rate = estimate_timestamp_success_rate(stat_newer.st_mtime);
1393 return true;
1395 return false;
1399 static boolean
1400 parse_newerXY (const struct parser_table* entry, char **argv, int *arg_ptr)
1402 (void) argv;
1403 (void) arg_ptr;
1405 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1407 return false;
1409 else if (8u != strlen(argv[*arg_ptr]))
1411 return false;
1413 else
1415 char x, y;
1416 const char validchars[] = "aBcmt";
1418 assert (0 == strncmp("-newer", argv[*arg_ptr], 6));
1419 x = argv[*arg_ptr][6];
1420 y = argv[*arg_ptr][7];
1423 #if !defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) && !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC) && !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC)
1424 if ('B' == x || 'B' == y)
1426 error(0, 0,
1427 _("This system does not provide a way to find the birth time of a file."));
1428 return 0;
1430 #endif
1432 /* -newertY (for any Y) is invalid. */
1433 if (x == 't'
1434 || 0 == strchr(validchars, x)
1435 || 0 == strchr( validchars, y))
1437 return false;
1439 else
1441 struct predicate *our_pred;
1443 /* Because this item is ARG_SPECIAL_PARSE, we have to advance arg_ptr
1444 * past the test name (for most other tests, this is already done)
1446 (*arg_ptr)++;
1448 our_pred = insert_primary (entry);
1451 switch (x)
1453 case 'a':
1454 our_pred->args.reftime.xval = XVAL_ATIME;
1455 break;
1456 case 'B':
1457 our_pred->args.reftime.xval = XVAL_BIRTHTIME;
1458 break;
1459 case 'c':
1460 our_pred->args.reftime.xval = XVAL_CTIME;
1461 break;
1462 case 'm':
1463 our_pred->args.reftime.xval = XVAL_MTIME;
1464 break;
1465 default:
1466 assert (strchr(validchars, x));
1467 assert (0);
1470 if ('t' == y)
1472 if (!get_date(&our_pred->args.reftime.ts,
1473 argv[*arg_ptr],
1474 &options.start_time))
1476 error(1, 0,
1477 _("I cannot figure out how to interpret %s as a date or time"),
1478 quotearg_n_style(0, options.err_quoting_style, argv[*arg_ptr]));
1481 else
1483 struct stat stat_newer;
1485 /* Stat the named file. */
1486 set_stat_placeholders(&stat_newer);
1487 if ((*options.xstat) (argv[*arg_ptr], &stat_newer))
1488 fatal_file_error(argv[*arg_ptr]);
1490 if (!get_stat_Ytime(&stat_newer, y, &our_pred->args.reftime.ts))
1492 /* We cannot extract a timestamp from the struct stat. */
1493 error(1, 0, _("Cannot obtain birth time of file %s"),
1494 safely_quote_err_filename(0, argv[*arg_ptr]));
1497 our_pred->args.reftime.kind = COMP_GT;
1498 our_pred->est_success_rate = estimate_timestamp_success_rate(our_pred->args.reftime.ts.tv_sec);
1499 (*arg_ptr)++;
1501 assert (our_pred->pred_func != NULL);
1502 assert (our_pred->pred_func == pred_newerXY);
1503 assert (our_pred->need_stat);
1504 return true;
1510 static boolean
1511 parse_noleaf (const struct parser_table* entry, char **argv, int *arg_ptr)
1513 options.no_leaf_check = true;
1514 return parse_noop(entry, argv, arg_ptr);
1517 #ifdef CACHE_IDS
1518 /* Arbitrary amount by which to increase size
1519 of `uid_unused' and `gid_unused'. */
1520 #define ALLOC_STEP 2048
1522 /* Boolean: if uid_unused[n] is nonzero, then UID n has no passwd entry. */
1523 char *uid_unused = NULL;
1525 /* Number of elements in `uid_unused'. */
1526 unsigned uid_allocated;
1528 /* Similar for GIDs and group entries. */
1529 char *gid_unused = NULL;
1530 unsigned gid_allocated;
1531 #endif
1533 static boolean
1534 parse_nogroup (const struct parser_table* entry, char **argv, int *arg_ptr)
1536 struct predicate *our_pred;
1538 (void) &argv;
1539 (void) &arg_ptr;
1541 our_pred = insert_primary (entry);
1542 our_pred->est_success_rate = 1e-4;
1543 #ifdef CACHE_IDS
1544 if (gid_unused == NULL)
1546 struct group *gr;
1548 gid_allocated = ALLOC_STEP;
1549 gid_unused = xmalloc (gid_allocated);
1550 memset (gid_unused, 1, gid_allocated);
1551 setgrent ();
1552 while ((gr = getgrent ()) != NULL)
1554 if ((unsigned) gr->gr_gid >= gid_allocated)
1556 unsigned new_allocated = (unsigned) gr->gr_gid + ALLOC_STEP;
1557 gid_unused = xrealloc (gid_unused, new_allocated);
1558 memset (gid_unused + gid_allocated, 1,
1559 new_allocated - gid_allocated);
1560 gid_allocated = new_allocated;
1562 gid_unused[(unsigned) gr->gr_gid] = 0;
1564 endgrent ();
1566 #endif
1567 return true;
1570 static boolean
1571 parse_nouser (const struct parser_table* entry, char **argv, int *arg_ptr)
1573 struct predicate *our_pred;
1574 (void) argv;
1575 (void) arg_ptr;
1578 our_pred = insert_primary (entry);
1579 our_pred->est_success_rate = 1e-3;
1580 #ifdef CACHE_IDS
1581 if (uid_unused == NULL)
1583 struct passwd *pw;
1585 uid_allocated = ALLOC_STEP;
1586 uid_unused = xmalloc (uid_allocated);
1587 memset (uid_unused, 1, uid_allocated);
1588 setpwent ();
1589 while ((pw = getpwent ()) != NULL)
1591 if ((unsigned) pw->pw_uid >= uid_allocated)
1593 unsigned new_allocated = (unsigned) pw->pw_uid + ALLOC_STEP;
1594 uid_unused = xrealloc (uid_unused, new_allocated);
1595 memset (uid_unused + uid_allocated, 1,
1596 new_allocated - uid_allocated);
1597 uid_allocated = new_allocated;
1599 uid_unused[(unsigned) pw->pw_uid] = 0;
1601 endpwent ();
1603 #endif
1604 return true;
1607 static boolean
1608 parse_nowarn (const struct parser_table* entry, char **argv, int *arg_ptr)
1610 options.warnings = false;
1611 return parse_noop(entry, argv, arg_ptr);
1614 static boolean
1615 parse_ok (const struct parser_table* entry, char **argv, int *arg_ptr)
1617 return insert_exec_ok ("-ok", entry, get_start_dirfd(), argv, arg_ptr);
1620 static boolean
1621 parse_okdir (const struct parser_table* entry, char **argv, int *arg_ptr)
1623 return insert_exec_ok ("-okdir", entry, -1, argv, arg_ptr);
1626 boolean
1627 parse_openparen (const struct parser_table* entry, char **argv, int *arg_ptr)
1629 struct predicate *our_pred;
1631 (void) argv;
1632 (void) arg_ptr;
1634 our_pred = get_new_pred_chk_op (entry);
1635 our_pred->pred_func = pred_openparen;
1636 our_pred->p_type = OPEN_PAREN;
1637 our_pred->p_prec = NO_PREC;
1638 our_pred->need_stat = our_pred->need_type = false;
1639 return true;
1642 static boolean
1643 parse_or (const struct parser_table* entry, char **argv, int *arg_ptr)
1645 struct predicate *our_pred;
1647 (void) argv;
1648 (void) arg_ptr;
1650 our_pred = get_new_pred (entry);
1651 our_pred->pred_func = pred_or;
1652 our_pred->p_type = BI_OP;
1653 our_pred->p_prec = OR_PREC;
1654 our_pred->need_stat = our_pred->need_type = false;
1655 return true;
1658 /* -path is deprecated (at RMS's request) in favour of
1659 * -iwholename. See the node "GNU Manuals" in standards.texi
1660 * for the rationale for this (basically, GNU prefers the use
1661 * of the phrase "file name" to "path name".
1663 * We do not issue a warning that this usage is deprecated
1664 * since HPUX find supports this predicate also.
1666 static boolean
1667 parse_path (const struct parser_table* entry, char **argv, int *arg_ptr)
1669 return parse_wholename(entry, argv, arg_ptr);
1672 static boolean
1673 parse_wholename (const struct parser_table* entry, char **argv, int *arg_ptr)
1675 const char *name;
1676 if (collect_arg(argv, arg_ptr, &name))
1678 struct predicate *our_pred = insert_primary_withpred (entry, pred_path);
1679 our_pred->need_stat = our_pred->need_type = false;
1680 our_pred->args.str = name;
1681 our_pred->est_success_rate = estimate_pattern_match_rate(name, 0);
1682 return true;
1684 return false;
1687 static boolean
1688 parse_perm (const struct parser_table* entry, char **argv, int *arg_ptr)
1690 mode_t perm_val[2];
1691 float rate;
1692 int mode_start = 0;
1693 boolean havekind = false;
1694 enum permissions_type kind = PERM_EXACT;
1695 struct mode_change *change = NULL;
1696 struct predicate *our_pred;
1697 const char *perm_expr;
1699 if (!collect_arg(argv, arg_ptr, &perm_expr))
1700 return false;
1702 switch (perm_expr[0])
1704 case '-':
1705 mode_start = 1;
1706 kind = PERM_AT_LEAST;
1707 havekind = true;
1708 rate = 0.2;
1709 break;
1711 case '+':
1712 change = mode_compile (perm_expr);
1713 if (NULL == change)
1715 /* Most likely the caller is an old script that is still
1716 * using the obsolete GNU syntax '-perm +MODE'. This old
1717 * syntax was withdrawn in favor of '-perm /MODE' because
1718 * it is incompatible with POSIX in some cases, but we
1719 * still support uses of it that are not incompatible with
1720 * POSIX.
1722 mode_start = 1;
1723 kind = PERM_ANY;
1724 rate = 0.3;
1726 else
1728 /* This is a POSIX-compatible usage */
1729 mode_start = 0;
1730 kind = PERM_EXACT;
1731 rate = 0.1;
1733 havekind = true;
1734 break;
1736 case '/': /* GNU extension */
1737 mode_start = 1;
1738 kind = PERM_ANY;
1739 havekind = true;
1740 rate = 0.3;
1741 break;
1743 default:
1744 /* For example, '-perm 0644', which is valid and matches
1745 * only files whose mode is exactly 0644.
1747 mode_start = 0;
1748 kind = PERM_EXACT;
1749 havekind = true;
1750 rate = 0.01;
1751 break;
1754 if (NULL == change)
1756 change = mode_compile (perm_expr + mode_start);
1757 if (NULL == change)
1758 error (1, 0, _("invalid mode %s"),
1759 quotearg_n_style(0, options.err_quoting_style, perm_expr));
1761 perm_val[0] = mode_adjust (0, false, 0, change, NULL);
1762 perm_val[1] = mode_adjust (0, true, 0, change, NULL);
1763 free (change);
1765 if (('/' == perm_expr[0]) && (0 == perm_val[0]) && (0 == perm_val[1]))
1767 /* The meaning of -perm /000 will change in the future. It
1768 * currently matches no files, but like -perm -000 it should
1769 * match all files.
1771 * Starting in 2005, we used to issue a warning message
1772 * informing the user that the behaviour would change in the
1773 * future. We have now changed the behaviour and issue a
1774 * warning message that the behaviour recently changed.
1776 error (0, 0,
1777 _("warning: you have specified a mode pattern %s (which is "
1778 "equivalent to /000). The meaning of -perm /000 has now been "
1779 "changed to be consistent with -perm -000; that is, while it "
1780 "used to match no files, it now matches all files."),
1781 perm_expr);
1783 kind = PERM_AT_LEAST;
1784 havekind = true;
1786 /* The "magic" number below is just the fraction of files on my
1787 * own system that "-type l -xtype l" fails for (i.e. unbroken symlinks).
1788 * Actual totals are 1472 and 1073833.
1790 rate = 0.9986; /* probably matches anything but a broken symlink */
1793 our_pred = insert_primary (entry);
1794 our_pred->est_success_rate = rate;
1795 if (havekind)
1797 our_pred->args.perm.kind = kind;
1799 else
1802 switch (perm_expr[0])
1804 case '-':
1805 our_pred->args.perm.kind = PERM_AT_LEAST;
1806 break;
1807 case '+':
1808 our_pred->args.perm.kind = PERM_ANY;
1809 break;
1810 default:
1811 our_pred->args.perm.kind = PERM_EXACT;
1812 break;
1815 memcpy (our_pred->args.perm.val, perm_val, sizeof perm_val);
1816 return true;
1819 boolean
1820 parse_print (const struct parser_table* entry, char **argv, int *arg_ptr)
1822 struct predicate *our_pred;
1824 (void) argv;
1825 (void) arg_ptr;
1827 our_pred = insert_primary (entry);
1828 /* -print has the side effect of printing. This prevents us
1829 from doing undesired multiple printing when the user has
1830 already specified -print. */
1831 our_pred->side_effects = our_pred->no_default_print = true;
1832 our_pred->need_stat = our_pred->need_type = false;
1833 open_stdout(&our_pred->args.printf_vec);
1834 return true;
1837 static boolean
1838 parse_print0 (const struct parser_table* entry, char **argv, int *arg_ptr)
1840 return insert_fprint(entry, NULL);
1843 static boolean
1844 parse_printf (const struct parser_table* entry, char **argv, int *arg_ptr)
1846 const char *format;
1847 if (collect_arg(argv, arg_ptr, &format))
1849 struct format_val fmt;
1850 open_stdout(&fmt);
1851 return insert_fprintf (&fmt, entry, pred_fprintf, format);
1853 return false;
1856 static boolean
1857 parse_fprintf (const struct parser_table* entry, char **argv, int *arg_ptr)
1859 const char *format, *filename;
1860 if (collect_arg(argv, arg_ptr, &filename))
1862 if (collect_arg(argv, arg_ptr, &format))
1864 struct format_val fmt;
1865 open_output_file (filename, &fmt);
1866 return insert_fprintf (&fmt, entry, pred_fprintf, format);
1869 return false;
1872 static boolean
1873 parse_prune (const struct parser_table* entry, char **argv, int *arg_ptr)
1875 struct predicate *our_pred;
1877 (void) argv;
1878 (void) arg_ptr;
1880 our_pred = insert_primary (entry);
1881 our_pred->need_stat = our_pred->need_type = false;
1882 /* -prune has a side effect that it does not descend into
1883 the current directory. */
1884 our_pred->side_effects = true;
1885 our_pred->no_default_print = false;
1886 return true;
1889 static boolean
1890 parse_quit (const struct parser_table* entry, char **argv, int *arg_ptr)
1892 struct predicate *our_pred = insert_primary (entry);
1893 (void) argv;
1894 (void) arg_ptr;
1895 our_pred->need_stat = our_pred->need_type = false;
1896 our_pred->side_effects = true; /* Exiting is a side effect... */
1897 our_pred->no_default_print = false; /* Don't inhibit the default print, though. */
1898 our_pred->est_success_rate = 1.0f;
1899 return true;
1903 static boolean
1904 parse_regextype (const struct parser_table* entry, char **argv, int *arg_ptr)
1906 const char *type_name;
1907 if (collect_arg(argv, arg_ptr, &type_name))
1909 /* collect the regex type name */
1910 options.regex_options = get_regex_type(type_name);
1911 return parse_noop(entry, argv, arg_ptr);
1913 return false;
1917 static boolean
1918 parse_regex (const struct parser_table* entry, char **argv, int *arg_ptr)
1920 return insert_regex (argv, arg_ptr, entry, options.regex_options);
1923 static boolean
1924 insert_regex (char **argv, int *arg_ptr, const struct parser_table *entry, int regex_options)
1926 const char *rx;
1927 if (collect_arg(argv, arg_ptr, &rx))
1929 struct re_pattern_buffer *re;
1930 const char *error_message;
1931 struct predicate *our_pred = insert_primary_withpred (entry, pred_regex);
1932 our_pred->need_stat = our_pred->need_type = false;
1933 re = xmalloc (sizeof (struct re_pattern_buffer));
1934 our_pred->args.regex = re;
1935 re->allocated = 100;
1936 re->buffer = xmalloc (re->allocated);
1937 re->fastmap = NULL;
1939 re_set_syntax(regex_options);
1940 re->syntax = regex_options;
1941 re->translate = NULL;
1943 error_message = re_compile_pattern (rx, strlen(rx), re);
1944 if (error_message)
1945 error (1, 0, "%s", error_message);
1946 our_pred->est_success_rate = estimate_pattern_match_rate(rx, 1);
1947 return true;
1949 return false;
1952 static boolean
1953 parse_size (const struct parser_table* entry, char **argv, int *arg_ptr)
1955 struct predicate *our_pred;
1956 uintmax_t num;
1957 char suffix;
1958 enum comparison_type c_type;
1960 int blksize = 512;
1961 int len;
1963 /* XXX: cannot (yet) convert to ue collect_arg() as this
1964 * function modifies the args in-place.
1966 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1967 return false;
1969 len = strlen (argv[*arg_ptr]);
1970 if (len == 0)
1971 error (1, 0, _("invalid null argument to -size"));
1973 suffix = argv[*arg_ptr][len - 1];
1974 switch (suffix)
1976 case 'b':
1977 blksize = 512;
1978 argv[*arg_ptr][len - 1] = '\0';
1979 break;
1981 case 'c':
1982 blksize = 1;
1983 argv[*arg_ptr][len - 1] = '\0';
1984 break;
1986 case 'k':
1987 blksize = 1024;
1988 argv[*arg_ptr][len - 1] = '\0';
1989 break;
1991 case 'M': /* Megabytes */
1992 blksize = 1024*1024;
1993 argv[*arg_ptr][len - 1] = '\0';
1994 break;
1996 case 'G': /* Gigabytes */
1997 blksize = 1024*1024*1024;
1998 argv[*arg_ptr][len - 1] = '\0';
1999 break;
2001 case 'w':
2002 blksize = 2;
2003 argv[*arg_ptr][len - 1] = '\0';
2004 break;
2006 case '0':
2007 case '1':
2008 case '2':
2009 case '3':
2010 case '4':
2011 case '5':
2012 case '6':
2013 case '7':
2014 case '8':
2015 case '9':
2016 break;
2018 default:
2019 error (1, 0, _("invalid -size type `%c'"), argv[*arg_ptr][len - 1]);
2021 /* TODO: accept fractional megabytes etc. ? */
2022 if (!get_num (argv[*arg_ptr], &num, &c_type))
2024 error(1, 0, _("Invalid argument `%s%c' to -size"), argv[*arg_ptr], (int)suffix);
2025 return false;
2027 our_pred = insert_primary (entry);
2028 our_pred->args.size.kind = c_type;
2029 our_pred->args.size.blocksize = blksize;
2030 our_pred->args.size.size = num;
2031 our_pred->need_stat = true;
2032 our_pred->need_type = false;
2034 if (COMP_GT == c_type)
2035 our_pred->est_success_rate = (num*blksize > 20480) ? 0.1 : 0.9;
2036 else if (COMP_LT == c_type)
2037 our_pred->est_success_rate = (num*blksize > 20480) ? 0.9 : 0.1;
2038 else
2039 our_pred->est_success_rate = 0.01;
2041 (*arg_ptr)++;
2042 return true;
2046 static boolean
2047 parse_samefile (const struct parser_table* entry, char **argv, int *arg_ptr)
2049 /* General idea: stat the file, remember device and inode numbers.
2050 * If a candidate file matches those, it's the same file.
2052 struct predicate *our_pred;
2053 struct stat st, fst;
2054 int fd, openflags;
2056 set_stat_placeholders(&st);
2057 if (!collect_arg_stat_info(argv, arg_ptr, &st))
2058 return false;
2060 set_stat_placeholders(&fst);
2061 /* POSIX systems are free to re-use the inode number of a deleted
2062 * file. To ensure that we are not fooled by inode reuse, we hold
2063 * the file open if we can. This would prevent the system reusing
2064 * the file.
2066 fd = -3; /* means, uninitialised */
2067 openflags = O_RDONLY;
2069 if (options.symlink_handling == SYMLINK_NEVER_DEREF)
2071 if (options.open_nofollow_available)
2073 assert (O_NOFOLLOW != 0);
2074 openflags |= O_NOFOLLOW;
2075 fd = -1; /* safe to open it. */
2077 else
2079 if (S_ISLNK(st.st_mode))
2081 /* no way to ensure that a symlink will not be followed
2082 * by open(2), so fall back on using lstat(). Accept
2083 * the risk that the named file will be deleted and
2084 * replaced with another having the same inode.
2086 * Avoid opening the file.
2088 fd = -2; /* Do not open it */
2090 else
2092 fd = -1;
2093 /* Race condition here: the file might become a symlink here. */
2097 else
2099 /* We want to dereference the symlink anyway */
2100 fd = -1; /* safe to open it without O_NOFOLLOW */
2103 assert (fd != -3); /* check we made a decision */
2104 if (fd == -1)
2106 /* Race condition here. The file might become a
2107 * symbolic link in between out call to stat and
2108 * the call to open.
2110 fd = open(argv[*arg_ptr], openflags);
2112 if (fd >= 0)
2114 /* We stat the file again here to prevent a race condition
2115 * between the first stat and the call to open(2).
2117 if (0 != fstat(fd, &fst))
2119 fatal_file_error(argv[*arg_ptr]);
2121 else
2123 /* Worry about the race condition. If the file became a
2124 * symlink after our first stat and before our call to
2125 * open, fst may contain the stat information for the
2126 * destination of the link, not the link itself.
2128 if ((*options.xstat) (argv[*arg_ptr], &st))
2129 fatal_file_error(argv[*arg_ptr]);
2131 if ((options.symlink_handling == SYMLINK_NEVER_DEREF)
2132 && (!options.open_nofollow_available))
2134 if (S_ISLNK(st.st_mode))
2136 /* We lost the race. Leave the data in st. The
2137 * file descriptor points to the wrong thing.
2139 close(fd);
2140 fd = -1;
2142 else
2144 /* Several possibilities here:
2145 * 1. There was no race
2146 * 2. The file changed into a symlink after the stat and
2147 * before the open, and then back into a non-symlink
2148 * before the second stat.
2150 * In case (1) there is no problem. In case (2),
2151 * the stat() and fstat() calls will have returned
2152 * different data. O_NOFOLLOW was not available,
2153 * so the open() call may have followed a symlink
2154 * even if the -P option is in effect.
2156 if ((st.st_dev == fst.st_dev)
2157 && (st.st_ino == fst.st_ino))
2159 /* No race. No need to copy fst to st,
2160 * since they should be identical (modulo
2161 * differences in padding bytes).
2164 else
2166 /* We lost the race. Leave the data in st. The
2167 * file descriptor points to the wrong thing.
2169 close(fd);
2170 fd = -1;
2174 else
2176 st = fst;
2182 our_pred = insert_primary (entry);
2183 our_pred->args.samefileid.ino = st.st_ino;
2184 our_pred->args.samefileid.dev = st.st_dev;
2185 our_pred->args.samefileid.fd = fd;
2186 our_pred->need_type = false;
2187 our_pred->need_stat = true;
2188 our_pred->est_success_rate = 0.01f;
2189 return true;
2192 #if 0
2193 /* This function is commented out partly because support for it is
2194 * uneven.
2196 static boolean
2197 parse_show_control_chars (const struct parser_table* entry, char **argv, int *arg_ptr)
2199 const char *arg;
2200 const char *errmsg = _("The -show-control-chars option takes a single argument which "
2201 "must be 'literal' or 'safe'");
2203 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
2205 error (1, errno, "%s", errmsg);
2206 return false;
2208 else
2210 arg = argv[*arg_ptr];
2212 if (0 == strcmp("literal", arg))
2214 options.literal_control_chars = true;
2216 else if (0 == strcmp("safe", arg))
2218 options.literal_control_chars = false;
2220 else
2222 error (1, errno, "%s", errmsg);
2223 return false;
2225 (*arg_ptr)++; /* consume the argument. */
2226 return true;
2229 #endif
2232 static boolean
2233 parse_true (const struct parser_table* entry, char **argv, int *arg_ptr)
2235 struct predicate *our_pred;
2237 (void) argv;
2238 (void) arg_ptr;
2240 our_pred = insert_primary (entry);
2241 our_pred->need_stat = our_pred->need_type = false;
2242 our_pred->est_success_rate = 1.0f;
2243 return true;
2246 static boolean
2247 parse_noop (const struct parser_table* entry, char **argv, int *arg_ptr)
2249 (void) entry;
2250 return parse_true(get_noop(), argv, arg_ptr);
2253 static boolean
2254 parse_accesscheck (const struct parser_table* entry, char **argv, int *arg_ptr)
2256 struct predicate *our_pred;
2257 (void) argv;
2258 (void) arg_ptr;
2259 our_pred = insert_primary (entry);
2260 our_pred->need_stat = our_pred->need_type = false;
2261 our_pred->side_effects = our_pred->no_default_print = false;
2262 if (pred_is(our_pred, pred_executable))
2263 our_pred->est_success_rate = 0.2;
2264 else
2265 our_pred->est_success_rate = 0.9;
2266 return true;
2269 static boolean
2270 parse_type (const struct parser_table* entry, char **argv, int *arg_ptr)
2272 return insert_type (argv, arg_ptr, entry, pred_type);
2275 static boolean
2276 parse_uid (const struct parser_table* entry, char **argv, int *arg_ptr)
2278 struct predicate *p = insert_num (argv, arg_ptr, entry);
2279 if (p)
2281 p->est_success_rate = (p->args.numinfo.l_val < 100) ? 0.99 : 0.2;
2282 return true;
2284 else
2286 return false;
2290 static boolean
2291 parse_used (const struct parser_table* entry, char **argv, int *arg_ptr)
2293 struct predicate *our_pred;
2294 struct time_val tval;
2295 const char *offset_str;
2296 const char *errmsg = "arithmetic overflow while converting %s days to a number of seconds";
2298 if (collect_arg(argv, arg_ptr, &offset_str))
2300 /* The timespec is actually a delta value, so we use an origin of 0. */
2301 if (get_relative_timestamp(offset_str, &tval, 0, DAYSECS, errmsg))
2303 our_pred = insert_primary (entry);
2304 our_pred->args.reftime = tval;
2305 our_pred->est_success_rate = estimate_file_age_success_rate(tval.ts.tv_sec / DAYSECS);
2306 return true;
2308 else
2310 error(1, 0, _("Invalid argument %s to -used"), offset_str);
2311 return false;
2314 else
2316 return false; /* missing argument */
2320 static boolean
2321 parse_user (const struct parser_table* entry, char **argv, int *arg_ptr)
2323 const char *username;
2325 if (collect_arg(argv, arg_ptr, &username))
2327 struct predicate *our_pred;
2328 uid_t uid;
2329 struct passwd *cur_pwd = getpwnam(username);
2330 endpwent();
2331 if (cur_pwd != NULL)
2333 uid = cur_pwd->pw_uid;
2335 else
2337 int uid_len = strspn (username, "0123456789");
2338 if (uid_len && (username[uid_len]==0))
2339 uid = safe_atoi (username);
2340 else
2341 return false;
2343 our_pred = insert_primary (entry);
2344 our_pred->args.uid = uid;
2345 our_pred->est_success_rate = (our_pred->args.uid < 100) ? 0.99 : 0.2;
2346 return true;
2348 return false;
2351 static boolean
2352 parse_version (const struct parser_table* entry, char **argv, int *arg_ptr)
2354 extern char *version_string;
2355 int features = 0;
2356 int flags;
2358 (void) argv;
2359 (void) arg_ptr;
2360 (void) entry;
2362 fflush (stderr);
2363 printf (_("GNU find version %s\n"), version_string);
2364 printf (_("Built using GNU gnulib version %s\n"), gnulib_version);
2365 printf (_("Features enabled: "));
2367 #if CACHE_IDS
2368 printf("CACHE_IDS ");
2369 ++features;
2370 #endif
2371 #if DEBUG
2372 printf("DEBUG ");
2373 ++features;
2374 #endif
2375 #if DEBUG_STAT
2376 printf("DEBUG_STAT ");
2377 ++features;
2378 #endif
2379 #if defined USE_STRUCT_DIRENT_D_TYPE && defined HAVE_STRUCT_DIRENT_D_TYPE
2380 printf("D_TYPE ");
2381 ++features;
2382 #endif
2383 #if defined O_NOFOLLOW
2384 printf("O_NOFOLLOW(%s) ",
2385 (options.open_nofollow_available ? "enabled" : "disabled"));
2386 ++features;
2387 #endif
2388 #if defined LEAF_OPTIMISATION
2389 printf("LEAF_OPTIMISATION ");
2390 ++features;
2391 #endif
2393 flags = 0;
2394 if (is_fts_enabled(&flags))
2396 int nflags = 0;
2397 printf("FTS(");
2398 ++features;
2400 if (flags & FTS_CWDFD)
2402 if (nflags)
2404 printf(",");
2406 printf("FTS_CWDFD");
2407 ++nflags;
2409 printf(") ");
2412 printf("CBO(level=%d) ", (int)(options.optimisation_level));
2413 ++features;
2415 if (0 == features)
2417 /* For the moment, leave this as English in case someone wants
2418 to parse these strings. */
2419 printf("none");
2421 printf("\n");
2423 exit (0);
2426 static boolean
2427 parse_xdev (const struct parser_table* entry, char **argv, int *arg_ptr)
2429 options.stay_on_filesystem = true;
2430 return parse_noop(entry, argv, arg_ptr);
2433 static boolean
2434 parse_ignore_race (const struct parser_table* entry, char **argv, int *arg_ptr)
2436 options.ignore_readdir_race = true;
2437 return parse_noop(entry, argv, arg_ptr);
2440 static boolean
2441 parse_noignore_race (const struct parser_table* entry, char **argv, int *arg_ptr)
2443 options.ignore_readdir_race = false;
2444 return parse_noop(entry, argv, arg_ptr);
2447 static boolean
2448 parse_warn (const struct parser_table* entry, char **argv, int *arg_ptr)
2450 options.warnings = true;
2451 return parse_noop(entry, argv, arg_ptr);
2454 static boolean
2455 parse_xtype (const struct parser_table* entry, char **argv, int *arg_ptr)
2457 return insert_type (argv, arg_ptr, entry, pred_xtype);
2460 static boolean
2461 insert_type (char **argv, int *arg_ptr, const struct parser_table *entry, PRED_FUNC which_pred)
2463 mode_t type_cell;
2464 struct predicate *our_pred;
2465 float rate = 0.5;
2466 const char *typeletter;
2468 if (collect_arg(argv, arg_ptr, &typeletter))
2470 if (strlen(typeletter) != 1u)
2472 error(1, 0, _("Arguments to -type should contain only one letter"));
2473 return false;
2476 switch (typeletter[0])
2478 case 'b': /* block special */
2479 type_cell = S_IFBLK;
2480 rate = 0.01f;
2481 break;
2482 case 'c': /* character special */
2483 type_cell = S_IFCHR;
2484 rate = 0.01f;
2485 break;
2486 case 'd': /* directory */
2487 type_cell = S_IFDIR;
2488 rate = 0.4f;
2489 break;
2490 case 'f': /* regular file */
2491 type_cell = S_IFREG;
2492 rate = 0.95f;
2493 break;
2494 #ifdef S_IFLNK
2495 case 'l': /* symbolic link */
2496 type_cell = S_IFLNK;
2497 rate = 0.1f;
2498 break;
2499 #endif
2500 #ifdef S_IFIFO
2501 case 'p': /* pipe */
2502 type_cell = S_IFIFO;
2503 rate = 0.01f;
2504 break;
2505 #endif
2506 #ifdef S_IFSOCK
2507 case 's': /* socket */
2508 type_cell = S_IFSOCK;
2509 rate = 0.01f;
2510 break;
2511 #endif
2512 #ifdef S_IFDOOR
2513 case 'D': /* Solaris door */
2514 type_cell = S_IFDOOR;
2515 rate = 0.01f;
2516 break;
2517 #endif
2518 default: /* None of the above ... nuke 'em. */
2519 error(1, 0, _("Unknown argument to -type: %c"), (*typeletter));
2520 return false;
2522 our_pred = insert_primary_withpred (entry, which_pred);
2523 our_pred->est_success_rate = rate;
2525 /* Figure out if we will need to stat the file, because if we don't
2526 * need to follow symlinks, we can avoid a stat call by using
2527 * struct dirent.d_type.
2529 if (which_pred == pred_xtype)
2531 our_pred->need_stat = true;
2532 our_pred->need_type = false;
2534 else
2536 our_pred->need_stat = false; /* struct dirent is enough */
2537 our_pred->need_type = true;
2539 our_pred->args.type = type_cell;
2540 return true;
2542 return false;
2546 /* Return true if the file accessed via FP is a terminal.
2548 static boolean
2549 stream_is_tty(FILE *fp)
2551 int fd = fileno(fp);
2552 if (-1 == fd)
2554 return false; /* not a valid stream */
2556 else
2558 return isatty(fd) ? true : false;
2566 /* XXX: do we need to pass FUNC to this function? */
2567 static boolean
2568 insert_fprintf (struct format_val *vec,
2569 const struct parser_table *entry, PRED_FUNC func,
2570 const char *format_const)
2572 char *format = (char*)format_const; /* XXX: casting away constness */
2573 register char *scan; /* Current address in scanning `format'. */
2574 register char *scan2; /* Address inside of element being scanned. */
2575 struct segment **segmentp; /* Address of current segment. */
2576 struct predicate *our_pred;
2578 our_pred = insert_primary_withpred (entry, func);
2579 our_pred->side_effects = our_pred->no_default_print = true;
2580 our_pred->args.printf_vec = *vec;
2581 our_pred->need_type = false;
2582 our_pred->need_stat = false;
2583 our_pred->p_cost = NeedsNothing;
2585 segmentp = &our_pred->args.printf_vec.segment;
2586 *segmentp = NULL;
2588 for (scan = format; *scan; scan++)
2590 if (*scan == '\\')
2592 scan2 = scan + 1;
2593 if (*scan2 >= '0' && *scan2 <= '7')
2595 register int n, i;
2597 for (i = n = 0; i < 3 && (*scan2 >= '0' && *scan2 <= '7');
2598 i++, scan2++)
2599 n = 8 * n + *scan2 - '0';
2600 scan2--;
2601 *scan = n;
2603 else
2605 switch (*scan2)
2607 case 'a':
2608 *scan = 7;
2609 break;
2610 case 'b':
2611 *scan = '\b';
2612 break;
2613 case 'c':
2614 make_segment (segmentp, format, scan - format,
2615 KIND_STOP, 0, 0,
2616 our_pred);
2617 if (our_pred->need_stat && (our_pred->p_cost < NeedsStatInfo))
2618 our_pred->p_cost = NeedsStatInfo;
2619 return true;
2620 case 'f':
2621 *scan = '\f';
2622 break;
2623 case 'n':
2624 *scan = '\n';
2625 break;
2626 case 'r':
2627 *scan = '\r';
2628 break;
2629 case 't':
2630 *scan = '\t';
2631 break;
2632 case 'v':
2633 *scan = '\v';
2634 break;
2635 case '\\':
2636 /* *scan = '\\'; * it already is */
2637 break;
2638 default:
2639 error (0, 0,
2640 _("warning: unrecognized escape `\\%c'"), *scan2);
2641 scan++;
2642 continue;
2645 segmentp = make_segment (segmentp, format, scan - format + 1,
2646 KIND_PLAIN, 0, 0,
2647 our_pred);
2648 format = scan2 + 1; /* Move past the escape. */
2649 scan = scan2; /* Incremented immediately by `for'. */
2651 else if (*scan == '%')
2653 if (scan[1] == 0)
2655 /* Trailing %. We don't like those. */
2656 error (1, 0, _("error: %s at end of format string"), scan);
2658 else if (scan[1] == '%')
2660 segmentp = make_segment (segmentp, format, scan - format + 1,
2661 KIND_PLAIN, 0, 0,
2662 our_pred);
2663 scan++;
2664 format = scan + 1;
2665 continue;
2667 /* Scan past flags, width and precision, to verify kind. */
2668 for (scan2 = scan; *++scan2 && strchr ("-+ #", *scan2);)
2669 /* Do nothing. */ ;
2670 while (ISDIGIT (*scan2))
2671 scan2++;
2672 if (*scan2 == '.')
2673 for (scan2++; ISDIGIT (*scan2); scan2++)
2674 /* Do nothing. */ ;
2675 if (strchr ("abcdDfFgGhHiklmMnpPsStuUyY", *scan2))
2677 segmentp = make_segment (segmentp, format, scan2 - format,
2678 KIND_FORMAT, *scan2, 0,
2679 our_pred);
2680 scan = scan2;
2681 format = scan + 1;
2683 else if (strchr ("ABCT", *scan2) && scan2[1])
2685 segmentp = make_segment (segmentp, format, scan2 - format,
2686 KIND_FORMAT, scan2[0], scan2[1],
2687 our_pred);
2688 scan = scan2 + 1;
2689 format = scan + 1;
2690 continue;
2692 else
2694 /* An unrecognized % escape. Print the char after the %. */
2695 error (0, 0, _("warning: unrecognized format directive `%%%c'"),
2696 *scan2);
2697 segmentp = make_segment (segmentp, format, scan - format,
2698 KIND_PLAIN, 0, 0,
2699 our_pred);
2700 format = scan + 1;
2701 continue;
2706 if (scan > format)
2707 make_segment (segmentp, format, scan - format, KIND_PLAIN, 0, 0,
2708 our_pred);
2709 return true;
2712 /* Create a new fprintf segment in *SEGMENT, with type KIND,
2713 from the text in FORMAT, which has length LEN.
2714 Return the address of the `next' pointer of the new segment. */
2716 static struct segment **
2717 make_segment (struct segment **segment,
2718 char *format,
2719 int len,
2720 int kind,
2721 char format_char,
2722 char aux_format_char,
2723 struct predicate *pred)
2725 enum EvaluationCost mycost = NeedsNothing;
2726 char *fmt;
2728 *segment = xmalloc (sizeof (struct segment));
2730 (*segment)->segkind = kind;
2731 (*segment)->format_char[0] = format_char;
2732 (*segment)->format_char[1] = aux_format_char;
2733 (*segment)->next = NULL;
2734 (*segment)->text_len = len;
2736 fmt = (*segment)->text = xmalloc (len + sizeof "d");
2737 strncpy (fmt, format, len);
2738 fmt += len;
2740 switch (kind)
2742 case KIND_PLAIN: /* Plain text string, no % conversion. */
2743 case KIND_STOP: /* Terminate argument, no newline. */
2744 assert (0 == format_char);
2745 assert (0 == aux_format_char);
2746 *fmt = '\0';
2747 if (mycost > pred->p_cost)
2748 pred->p_cost = NeedsNothing;
2749 return &(*segment)->next;
2750 break;
2753 assert (kind == KIND_FORMAT);
2754 switch (format_char)
2756 case 'l': /* object of symlink */
2757 pred->need_stat = true;
2758 mycost = NeedsLinkName;
2759 *fmt++ = 's';
2760 break;
2762 case 'y': /* file type */
2763 pred->need_type = true;
2764 mycost = NeedsType;
2765 *fmt++ = 's';
2766 break;
2768 case 'a': /* atime in `ctime' format */
2769 case 'A': /* atime in user-specified strftime format */
2770 case 'B': /* birth time in user-specified strftime format */
2771 case 'c': /* ctime in `ctime' format */
2772 case 'C': /* ctime in user-specified strftime format */
2773 case 'F': /* file system type */
2774 case 'g': /* group name */
2775 case 'i': /* inode number */
2776 case 'M': /* mode in `ls -l' format (eg., "drwxr-xr-x") */
2777 case 's': /* size in bytes */
2778 case 't': /* mtime in `ctime' format */
2779 case 'T': /* mtime in user-specified strftime format */
2780 case 'u': /* user name */
2781 pred->need_stat = true;
2782 mycost = NeedsStatInfo;
2783 *fmt++ = 's';
2784 break;
2786 case 'S': /* sparseness */
2787 pred->need_stat = true;
2788 mycost = NeedsStatInfo;
2789 *fmt++ = 'g';
2790 break;
2792 case 'Y': /* symlink pointed file type */
2793 pred->need_stat = true;
2794 mycost = NeedsType; /* true for amortised effect */
2795 *fmt++ = 's';
2796 break;
2798 case 'f': /* basename of path */
2799 case 'h': /* leading directories part of path */
2800 case 'p': /* pathname */
2801 case 'P': /* pathname with ARGV element stripped */
2802 *fmt++ = 's';
2803 break;
2805 case 'H': /* ARGV element file was found under */
2806 *fmt++ = 's';
2807 break;
2809 /* Numeric items that one might expect to honour
2810 * #, 0, + flags but which do not.
2812 case 'G': /* GID number */
2813 case 'U': /* UID number */
2814 case 'b': /* size in 512-byte blocks (NOT birthtime in ctime fmt)*/
2815 case 'D': /* Filesystem device on which the file exits */
2816 case 'k': /* size in 1K blocks */
2817 case 'n': /* number of links */
2818 pred->need_stat = true;
2819 mycost = NeedsStatInfo;
2820 *fmt++ = 's';
2821 break;
2823 /* Numeric items that DO honour #, 0, + flags.
2825 case 'd': /* depth in search tree (0 = ARGV element) */
2826 *fmt++ = 'd';
2827 break;
2829 case 'm': /* mode as octal number (perms only) */
2830 *fmt++ = 'o';
2831 pred->need_stat = true;
2832 mycost = NeedsStatInfo;
2833 break;
2835 case '{':
2836 case '[':
2837 case '(':
2838 error (1, 0,
2839 _("error: the format directive `%%%c' is reserved for future use"),
2840 (int)kind);
2841 /*NOTREACHED*/
2842 break;
2844 *fmt = '\0';
2846 if (mycost > pred->p_cost)
2847 pred->p_cost = mycost;
2848 return &(*segment)->next;
2851 static void
2852 check_path_safety(const char *action, char **argv)
2854 const char *path = getenv("PATH");
2855 char *s;
2857 (void)argv;
2859 s = next_element(path, 1);
2860 while ((s = next_element ((char *) NULL, 1)) != NULL)
2862 if (0 == strcmp(s, "."))
2864 error(1, 0, _("The current directory is included in the PATH environment variable, which is insecure in combination with the %s action of find. Please remove the current directory from your $PATH (that is, remove \".\" or leading or trailing colons)"),
2865 action);
2867 else if ('/' != s[0])
2869 /* Relative paths are also dangerous in $PATH. */
2870 error(1, 0, _("The relative path %s is included in the PATH "
2871 "environment variable, which is insecure in "
2872 "combination with the %s action of find. "
2873 "Please remove that entry from $PATH"),
2874 safely_quote_err_filename(0, s),
2875 action);
2881 /* handles both exec and ok predicate */
2882 static boolean
2883 new_insert_exec_ok (const char *action,
2884 const struct parser_table *entry,
2885 int dirfd,
2886 char **argv,
2887 int *arg_ptr)
2889 int start, end; /* Indexes in ARGV of start & end of cmd. */
2890 int i; /* Index into cmd args */
2891 int saw_braces; /* True if previous arg was '{}'. */
2892 boolean allow_plus; /* True if + is a valid terminator */
2893 int brace_count; /* Number of instances of {}. */
2894 PRED_FUNC func = entry->pred_func;
2895 enum BC_INIT_STATUS bcstatus;
2897 struct predicate *our_pred;
2898 struct exec_val *execp; /* Pointer for efficiency. */
2900 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
2901 return false;
2903 our_pred = insert_primary_withpred (entry, func);
2904 our_pred->side_effects = our_pred->no_default_print = true;
2905 our_pred->need_type = our_pred->need_stat = false;
2907 execp = &our_pred->args.exec_vec;
2909 if ((func != pred_okdir) && (func != pred_ok))
2911 allow_plus = true;
2912 execp->close_stdin = false;
2914 else
2916 allow_plus = false;
2917 /* If find reads stdin (i.e. for -ok and similar), close stdin
2918 * in the child to prevent some script from consiming the output
2919 * intended for find.
2921 execp->close_stdin = true;
2925 if ((func == pred_execdir) || (func == pred_okdir))
2927 options.ignore_readdir_race = false;
2928 check_path_safety(action, argv);
2929 execp->use_current_dir = true;
2931 else
2933 execp->use_current_dir = false;
2936 our_pred->args.exec_vec.multiple = 0;
2938 /* Count the number of args with path replacements, up until the ';'.
2939 * Also figure out if the command is terminated by ";" or by "+".
2941 start = *arg_ptr;
2942 for (end = start, saw_braces=0, brace_count=0;
2943 (argv[end] != NULL)
2944 && ((argv[end][0] != ';') || (argv[end][1] != '\0'));
2945 end++)
2947 /* For -exec and -execdir, "{} +" can terminate the command. */
2948 if ( allow_plus
2949 && argv[end][0] == '+' && argv[end][1] == 0
2950 && saw_braces)
2952 our_pred->args.exec_vec.multiple = 1;
2953 break;
2956 saw_braces = 0;
2957 if (mbsstr (argv[end], "{}"))
2959 saw_braces = 1;
2960 ++brace_count;
2962 if (0 == end && (func == pred_execdir || func == pred_okdir))
2964 /* The POSIX standard says that {} replacement should
2965 * occur even in the utility name. This is insecure
2966 * since it means we will be executing a command whose
2967 * name is chosen according to whatever find finds in
2968 * the file system. That can be influenced by an
2969 * attacker. Hence for -execdir and -okdir this is not
2970 * allowed. We can specify this as those options are
2971 * not defined by POSIX.
2973 error(1, 0, _("You may not use {} within the utility name for -execdir and -okdir, because this is a potential security problem."));
2978 /* Fail if no command given or no semicolon found. */
2979 if ((end == start) || (argv[end] == NULL))
2981 *arg_ptr = end;
2982 free(our_pred);
2983 return false;
2986 if (our_pred->args.exec_vec.multiple && brace_count > 1)
2989 const char *suffix;
2990 if (func == pred_execdir)
2991 suffix = "dir";
2992 else
2993 suffix = "";
2995 error(1, 0,
2996 _("Only one instance of {} is supported with -exec%s ... +"),
2997 suffix);
3000 /* We use a switch statement here so that the compiler warns us when
3001 * we forget to handle a newly invented enum value.
3003 * Like xargs, we allow 2KiB of headroom for the launched utility to
3004 * export its own environment variables before calling something
3005 * else.
3007 bcstatus = bc_init_controlinfo(&execp->ctl, 2048u);
3008 switch (bcstatus)
3010 case BC_INIT_ENV_TOO_BIG:
3011 case BC_INIT_CANNOT_ACCOMODATE_HEADROOM:
3012 error(1, 0,
3013 _("The environment is too large for exec()."));
3014 break;
3015 case BC_INIT_OK:
3016 /* Good news. Carry on. */
3017 break;
3019 bc_use_sensible_arg_max(&execp->ctl);
3022 execp->ctl.exec_callback = launch;
3024 if (our_pred->args.exec_vec.multiple)
3026 /* "+" terminator, so we can just append our arguments after the
3027 * command and initial arguments.
3029 execp->replace_vec = NULL;
3030 execp->ctl.replace_pat = NULL;
3031 execp->ctl.rplen = 0;
3032 execp->ctl.lines_per_exec = 0; /* no limit */
3033 execp->ctl.args_per_exec = 0; /* no limit */
3035 /* remember how many arguments there are */
3036 execp->ctl.initial_argc = (end-start) - 1;
3038 /* execp->state = xmalloc(sizeof struct buildcmd_state); */
3039 bc_init_state(&execp->ctl, &execp->state, execp);
3041 /* Gather the initial arguments. Skip the {}. */
3042 for (i=start; i<end-1; ++i)
3044 bc_push_arg(&execp->ctl, &execp->state,
3045 argv[i], strlen(argv[i])+1,
3046 NULL, 0,
3050 else
3052 /* Semicolon terminator - more than one {} is supported, so we
3053 * have to do brace-replacement.
3055 execp->num_args = end - start;
3057 execp->ctl.replace_pat = "{}";
3058 execp->ctl.rplen = strlen(execp->ctl.replace_pat);
3059 execp->ctl.lines_per_exec = 0; /* no limit */
3060 execp->ctl.args_per_exec = 0; /* no limit */
3061 execp->replace_vec = xmalloc(sizeof(char*)*execp->num_args);
3064 /* execp->state = xmalloc(sizeof(*(execp->state))); */
3065 bc_init_state(&execp->ctl, &execp->state, execp);
3067 /* Remember the (pre-replacement) arguments for later. */
3068 for (i=0; i<execp->num_args; ++i)
3070 execp->replace_vec[i] = argv[i+start];
3074 if (argv[end] == NULL)
3075 *arg_ptr = end;
3076 else
3077 *arg_ptr = end + 1;
3079 return true;
3084 static boolean
3085 insert_exec_ok (const char *action, const struct parser_table *entry, int dirfd, char **argv, int *arg_ptr)
3087 return new_insert_exec_ok(action, entry, dirfd, argv, arg_ptr);
3092 /* Get a timestamp and comparison type.
3094 STR is the ASCII representation.
3095 Set *NUM_DAYS to the number of days/minutes/whatever, taken as being
3096 relative to ORIGIN (usually the current moment or midnight).
3097 Thus the sense of the comparison type appears to be reversed.
3098 Set *COMP_TYPE to the kind of comparison that is requested.
3099 Issue OVERFLOWMESSAGE if overflow occurs.
3100 Return true if all okay, false if input error.
3102 Used by -atime, -ctime and -mtime (parsers) to
3103 get the appropriate information for a time predicate processor. */
3105 static boolean
3106 get_relative_timestamp (const char *str,
3107 struct time_val *result,
3108 time_t origin,
3109 double sec_per_unit,
3110 const char *overflowmessage)
3112 uintmax_t checkval;
3113 double offset, seconds, f;
3115 if (get_comp_type(&str, &result->kind))
3117 /* Invert the sense of the comparison */
3118 switch (result->kind)
3120 case COMP_LT: result->kind = COMP_GT; break;
3121 case COMP_GT: result->kind = COMP_LT; break;
3122 default: break;
3125 /* Convert the ASCII number into floating-point. */
3126 if (xstrtod(str, NULL, &offset, strtod))
3128 /* Separate the floating point number the user specified
3129 * (which is a number of days, or minutes, etc) into an
3130 * integral number of seconds (SECONDS) and a fraction (F).
3132 f = modf(offset * sec_per_unit, &seconds);
3134 result->ts.tv_sec = origin - seconds;
3135 result->ts.tv_nsec = fabs(f * 1e9);
3137 /* Check for overflow. */
3138 checkval = (uintmax_t)origin - seconds;
3139 if (checkval != result->ts.tv_sec)
3141 /* an overflow has occurred. */
3142 error (1, 0, overflowmessage, str);
3144 return true;
3146 else
3148 /* Conversion from ASCII to double failed. */
3149 return false;
3152 else
3154 return false;
3158 /* Insert a time predicate based on the information in ENTRY.
3159 ARGV is a pointer to the argument array.
3160 ARG_PTR is a pointer to an index into the array, incremented if
3161 all went well.
3163 Return true if input is valid, false if not.
3165 A new predicate node is assigned, along with an argument node
3166 obtained with malloc.
3168 Used by -atime, -ctime, and -mtime parsers. */
3170 static boolean
3171 parse_time (const struct parser_table* entry, char *argv[], int *arg_ptr)
3173 struct predicate *our_pred;
3174 struct time_val tval;
3175 enum comparison_type comp;
3176 const char *timearg, *orig_timearg;
3177 const char *errmsg = "arithmetic overflow while converting %s days to a number of seconds";
3178 time_t origin;
3180 if (!collect_arg(argv, arg_ptr, &timearg))
3181 return false;
3182 orig_timearg = timearg;
3184 /* Decide the origin by previewing the comparison type. */
3185 origin = options.cur_day_start;
3187 if (get_comp_type(&timearg, &comp))
3189 /* Remember, we invert the sense of the comparison, so this tests
3190 * against COMP_LT instead of COMP_GT...
3192 if (COMP_LT == comp)
3194 uintmax_t expected = origin + (DAYSECS-1);
3195 origin += (DAYSECS-1);
3196 if (origin != expected)
3198 error(1, 0,
3199 _("arithmetic overflow when trying to calculate the end of today"));
3203 /* We discard the value of comp here, as get_relative_timestamp
3204 * will set tval.kind. For that to work, we have to restore
3205 * timearg so that it points to the +/- prefix, if any. get_comp_type()
3206 * will have advanced timearg, so we restore it.
3208 timearg = orig_timearg;
3210 if (!get_relative_timestamp(timearg, &tval, origin, DAYSECS, errmsg))
3211 return false;
3213 our_pred = insert_primary (entry);
3214 our_pred->args.reftime = tval;
3215 our_pred->est_success_rate = estimate_timestamp_success_rate(tval.ts.tv_sec);
3217 if (options.debug_options & DebugExpressionTree)
3219 time_t t;
3221 fprintf (stderr, "inserting %s\n", our_pred->p_name);
3222 fprintf (stderr, " type: %s %s ",
3223 (tval.kind == COMP_GT) ? "gt" :
3224 ((tval.kind == COMP_LT) ? "lt" : ((tval.kind == COMP_EQ) ? "eq" : "?")),
3225 (tval.kind == COMP_GT) ? " >" :
3226 ((tval.kind == COMP_LT) ? " <" : ((tval.kind == COMP_EQ) ? ">=" : " ?")));
3227 t = our_pred->args.reftime.ts.tv_sec;
3228 fprintf (stderr, "%ju %s", (uintmax_t) our_pred->args.reftime.ts.tv_sec, ctime (&t));
3229 if (tval.kind == COMP_EQ)
3231 t = our_pred->args.reftime.ts.tv_sec + DAYSECS;
3232 fprintf (stderr, " < %ju %s",
3233 (uintmax_t) t, ctime (&t));
3237 return true;
3240 /* Get the comparison type prefix (if any) from a number argument.
3241 The prefix is at *STR.
3242 Set *COMP_TYPE to the kind of comparison that is requested.
3243 Advance *STR beyond any initial comparison prefix.
3245 Return true if all okay, false if input error. */
3246 static boolean
3247 get_comp_type(const char **str, enum comparison_type *comp_type)
3249 switch (**str)
3251 case '+':
3252 *comp_type = COMP_GT;
3253 (*str)++;
3254 break;
3255 case '-':
3256 *comp_type = COMP_LT;
3257 (*str)++;
3258 break;
3259 default:
3260 *comp_type = COMP_EQ;
3261 break;
3263 return true;
3270 /* Get a number with comparison information.
3271 The sense of the comparison information is 'normal'; that is,
3272 '+' looks for a count > than the number and '-' less than.
3274 STR is the ASCII representation of the number.
3275 Set *NUM to the number.
3276 Set *COMP_TYPE to the kind of comparison that is requested.
3278 Return true if all okay, false if input error. */
3280 static boolean
3281 get_num (const char *str,
3282 uintmax_t *num,
3283 enum comparison_type *comp_type)
3285 char *pend;
3287 if (str == NULL)
3288 return false;
3290 /* Figure out the comparison type if the caller accepts one. */
3291 if (comp_type)
3293 if (!get_comp_type(&str, comp_type))
3294 return false;
3297 return xstrtoumax (str, &pend, 10, num, "") == LONGINT_OK;
3300 /* Insert a number predicate.
3301 ARGV is a pointer to the argument array.
3302 *ARG_PTR is an index into ARGV, incremented if all went well.
3303 *PRED is the predicate processor to insert.
3305 Return true if input is valid, false if error.
3307 A new predicate node is assigned, along with an argument node
3308 obtained with malloc.
3310 Used by -inum and -links parsers. */
3312 static struct predicate *
3313 insert_num (char **argv, int *arg_ptr, const struct parser_table *entry)
3315 const char *numstr;
3317 if (collect_arg(argv, arg_ptr, &numstr))
3319 uintmax_t num;
3320 enum comparison_type c_type;
3322 if (get_num (numstr, &num, &c_type))
3324 struct predicate *our_pred = insert_primary (entry);
3325 our_pred->args.numinfo.kind = c_type;
3326 our_pred->args.numinfo.l_val = num;
3328 if (options.debug_options & DebugExpressionTree)
3330 fprintf (stderr, "inserting %s\n", our_pred->p_name);
3331 fprintf (stderr, " type: %s %s ",
3332 (c_type == COMP_GT) ? "gt" :
3333 ((c_type == COMP_LT) ? "lt" : ((c_type == COMP_EQ) ? "eq" : "?")),
3334 (c_type == COMP_GT) ? " >" :
3335 ((c_type == COMP_LT) ? " <" : ((c_type == COMP_EQ) ? " =" : " ?")));
3336 fprintf (stderr, "%ju\n", our_pred->args.numinfo.l_val);
3338 return our_pred;
3341 return NULL;
3344 static void
3345 open_output_file (const char *path, struct format_val *p)
3347 p->segment = NULL;
3348 p->quote_opts = clone_quoting_options (NULL);
3350 if (!strcmp (path, "/dev/stderr"))
3352 p->stream = stderr;
3353 p->filename = _("standard error");
3355 else if (!strcmp (path, "/dev/stdout"))
3357 p->stream = stdout;
3358 p->filename = _("standard output");
3360 else
3362 p->stream = fopen_safer (path, "w");
3363 p->filename = path;
3365 if (p->stream == NULL)
3367 fatal_file_error(path);
3371 p->dest_is_tty = stream_is_tty(p->stream);
3374 static void
3375 open_stdout (struct format_val *p)
3377 open_output_file("/dev/stdout", p);