Issue states messages in a way which indicates more clearly what's
[findutils.git] / find / parser.c
blob8a3c6511a732ead6c9327d311c5d292f9b4dcd9c
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 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
8 any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
18 USA.
22 #include "defs.h"
23 #include <ctype.h>
24 #include <assert.h>
25 #include <pwd.h>
26 #include <grp.h>
27 #include <fnmatch.h>
28 #include "modechange.h"
29 #include "modetype.h"
30 #include "xstrtol.h"
31 #include "xalloc.h"
32 #include "quote.h"
33 #include "quotearg.h"
34 #include "buildcmd.h"
35 #include "nextelem.h"
36 #include "stdio-safer.h"
37 #include "regextype.h"
39 #ifdef HAVE_FCNTL_H
40 #include <fcntl.h>
41 #else
42 #include <sys/file.h>
43 #endif
45 /* The presence of unistd.h is assumed by gnulib these days, so we
46 * might as well assume it too.
48 /* We need <unistd.h> for isatty(). */
49 #include <unistd.h>
51 #if ENABLE_NLS
52 # include <libintl.h>
53 # define _(Text) gettext (Text)
54 #else
55 # define _(Text) Text
56 #endif
57 #ifdef gettext_noop
58 # define N_(String) gettext_noop (String)
59 #else
60 /* See locate.c for explanation as to why not use (String) */
61 # define N_(String) String
62 #endif
64 #if !defined (isascii) || defined (STDC_HEADERS)
65 #ifdef isascii
66 #undef isascii
67 #endif
68 #define isascii(c) 1
69 #endif
71 #define ISDIGIT(c) (isascii ((unsigned char)c) && isdigit ((unsigned char)c))
72 #define ISUPPER(c) (isascii ((unsigned char)c) && isupper ((unsigned char)c))
74 #ifndef HAVE_ENDGRENT
75 #define endgrent()
76 #endif
77 #ifndef HAVE_ENDPWENT
78 #define endpwent()
79 #endif
81 static boolean parse_accesscheck PARAMS((const struct parser_table* entry, char **argv, int *arg_ptr));
82 static boolean parse_amin PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
83 static boolean parse_and PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
84 static boolean parse_anewer PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
85 static boolean parse_cmin PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
86 static boolean parse_cnewer PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
87 static boolean parse_comma PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
88 static boolean parse_daystart PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
89 static boolean parse_delete PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
90 static boolean parse_d PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
91 static boolean parse_depth PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
92 static boolean parse_empty PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
93 static boolean parse_exec PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
94 static boolean parse_execdir PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
95 static boolean parse_false PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
96 static boolean parse_fls PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
97 static boolean parse_fprintf PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
98 static boolean parse_follow PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
99 static boolean parse_fprint PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
100 static boolean parse_fprint0 PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
101 static boolean parse_fstype PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
102 static boolean parse_gid PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
103 static boolean parse_group PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
104 static boolean parse_help PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
105 static boolean parse_ilname PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
106 static boolean parse_iname PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
107 static boolean parse_inum PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
108 static boolean parse_ipath PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
109 static boolean parse_iregex PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
110 static boolean parse_iwholename PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
111 static boolean parse_links PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
112 static boolean parse_lname PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
113 static boolean parse_ls PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
114 static boolean parse_maxdepth PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
115 static boolean parse_mindepth PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
116 static boolean parse_mmin PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
117 static boolean parse_name PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
118 static boolean parse_negate PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
119 static boolean parse_newer PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
120 static boolean parse_noleaf PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
121 static boolean parse_nogroup PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
122 static boolean parse_nouser PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
123 static boolean parse_nowarn PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
124 static boolean parse_ok PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
125 static boolean parse_okdir PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
126 static boolean parse_or PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
127 static boolean parse_path PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
128 static boolean parse_perm PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
129 static boolean parse_print0 PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
130 static boolean parse_printf PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
131 static boolean parse_prune PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
132 static boolean parse_regex PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
133 static boolean parse_regextype PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
134 static boolean parse_samefile PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
135 #if 0
136 static boolean parse_show_control_chars PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
137 #endif
138 static boolean parse_size PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
139 static boolean parse_time PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
140 static boolean parse_true PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
141 static boolean parse_type PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
142 static boolean parse_uid PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
143 static boolean parse_used PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
144 static boolean parse_user PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
145 static boolean parse_version PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
146 static boolean parse_wholename PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
147 static boolean parse_xdev PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
148 static boolean parse_ignore_race PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
149 static boolean parse_noignore_race PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
150 static boolean parse_warn PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
151 static boolean parse_xtype PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
152 static boolean parse_quit PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
154 boolean parse_print PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
157 static boolean insert_type PARAMS((char **argv, int *arg_ptr, const struct parser_table *entry, PRED_FUNC which_pred));
158 static boolean insert_regex PARAMS((char *argv[], int *arg_ptr, const struct parser_table *entry, int regex_options));
159 static boolean insert_fprintf PARAMS((FILE *fp, const struct parser_table *entry, PRED_FUNC func, char *argv[], int *arg_ptr));
161 static struct segment **make_segment PARAMS((struct segment **segment, char *format, int len, int kind, struct predicate *pred));
162 static boolean insert_exec_ok PARAMS((const char *action, const struct parser_table *entry, char *argv[], int *arg_ptr));
163 static boolean get_num_days PARAMS((char *str, uintmax_t *num_days, enum comparison_type *comp_type));
164 static boolean get_num PARAMS((char *str, uintmax_t *num, enum comparison_type *comp_type));
165 static struct predicate* insert_num PARAMS((char *argv[], int *arg_ptr, const struct parser_table *entry));
166 static FILE *open_output_file PARAMS((char *path));
167 static boolean stream_is_tty(FILE *fp);
168 static boolean parse_noop PARAMS((const struct parser_table* entry, char **argv, int *arg_ptr));
170 #define PASTE(x,y) x##y
171 #define STRINGIFY(s) #s
173 #define PARSE_OPTION(what,suffix) \
174 { (ARG_OPTION), (what), PASTE(parse_,suffix), NULL }
176 #define PARSE_POSOPT(what,suffix) \
177 { (ARG_POSITIONAL_OPTION), (what), PASTE(parse_,suffix), NULL }
179 #define PARSE_TEST(what,suffix) \
180 { (ARG_TEST), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) }
182 #define PARSE_TEST_NP(what,suffix) \
183 { (ARG_TEST), (what), PASTE(parse_,suffix), NULL }
185 #define PARSE_ACTION(what,suffix) \
186 { (ARG_ACTION), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) }
188 #define PARSE_ACTION_NP(what,suffix) \
189 { (ARG_ACTION), (what), PASTE(parse_,suffix), NULL }
191 #define PARSE_PUNCTUATION(what,suffix) \
192 { (ARG_PUNCTUATION), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) }
195 /* GNU find predicates that are not mentioned in POSIX.2 are marked `GNU'.
196 If they are in some Unix versions of find, they are marked `Unix'. */
198 static struct parser_table const parse_table[] =
200 PARSE_PUNCTUATION("!", negate),
201 PARSE_PUNCTUATION("not", negate), /* GNU */
202 PARSE_PUNCTUATION("(", open),
203 PARSE_PUNCTUATION(")", close),
204 PARSE_PUNCTUATION(",", comma), /* GNU */
205 PARSE_PUNCTUATION("a", and),
206 PARSE_TEST ("amin", amin), /* GNU */
207 PARSE_PUNCTUATION("and", and), /* GNU */
208 PARSE_TEST ("anewer", anewer), /* GNU */
209 {ARG_TEST, "atime", parse_time, pred_atime},
210 PARSE_TEST ("cmin", cmin), /* GNU */
211 PARSE_TEST ("cnewer", cnewer), /* GNU */
212 {ARG_TEST, "ctime", parse_time, pred_ctime},
213 PARSE_POSOPT ("daystart", daystart), /* GNU */
214 PARSE_ACTION ("delete", delete), /* GNU, Mac OS, FreeBSD */
215 PARSE_OPTION ("d", d), /* Mac OS X, FreeBSD, NetBSD, OpenBSD, but deprecated in favour of -depth */
216 PARSE_OPTION ("depth", depth),
217 PARSE_TEST ("empty", empty), /* GNU */
218 {ARG_ACTION, "exec", parse_exec, pred_exec}, /* POSIX */
219 {ARG_TEST, "executable", parse_accesscheck, pred_executable}, /* GNU, 4.3.0+ */
220 PARSE_ACTION ("execdir", execdir), /* *BSD, GNU */
221 PARSE_ACTION ("fls", fls), /* GNU */
222 PARSE_POSOPT ("follow", follow), /* GNU, Unix */
223 PARSE_ACTION ("fprint", fprint), /* GNU */
224 PARSE_ACTION ("fprint0", fprint0), /* GNU */
225 {ARG_ACTION, "fprintf", parse_fprintf, pred_fprintf}, /* GNU */
226 PARSE_TEST ("fstype", fstype), /* GNU, Unix */
227 PARSE_TEST ("gid", gid), /* GNU */
228 PARSE_TEST ("group", group),
229 PARSE_OPTION ("ignore_readdir_race", ignore_race), /* GNU */
230 PARSE_TEST ("ilname", ilname), /* GNU */
231 PARSE_TEST ("iname", iname), /* GNU */
232 PARSE_TEST ("inum", inum), /* GNU, Unix */
233 PARSE_TEST ("ipath", ipath), /* GNU, deprecated in favour of iwholename */
234 PARSE_TEST_NP ("iregex", iregex), /* GNU */
235 PARSE_TEST_NP ("iwholename", iwholename), /* GNU */
236 PARSE_TEST ("links", links),
237 PARSE_TEST ("lname", lname), /* GNU */
238 PARSE_ACTION ("ls", ls), /* GNU, Unix */
239 PARSE_OPTION ("maxdepth", maxdepth), /* GNU */
240 PARSE_OPTION ("mindepth", mindepth), /* GNU */
241 PARSE_TEST ("mmin", mmin), /* GNU */
242 PARSE_OPTION ("mount", xdev), /* Unix */
243 {ARG_TEST, "mtime", parse_time, pred_mtime},
244 PARSE_TEST ("name", name),
245 #ifdef UNIMPLEMENTED_UNIX
246 PARSE(ARG_UNIMPLEMENTED, "ncpio", ncpio), /* Unix */
247 #endif
248 PARSE_TEST ("newer", newer),
249 PARSE_OPTION ("noleaf", noleaf), /* GNU */
250 PARSE_TEST ("nogroup", nogroup),
251 PARSE_TEST ("nouser", nouser),
252 PARSE_OPTION ("noignore_readdir_race", noignore_race), /* GNU */
253 PARSE_POSOPT ("nowarn", nowarn), /* GNU */
254 PARSE_PUNCTUATION("o", or),
255 PARSE_PUNCTUATION("or", or), /* GNU */
256 PARSE_ACTION ("ok", ok),
257 PARSE_ACTION ("okdir", okdir), /* GNU (-execdir is BSD) */
258 PARSE_TEST ("path", path), /* GNU, HP-UX, GNU prefers wholename */
259 PARSE_TEST ("perm", perm),
260 PARSE_ACTION ("print", print),
261 PARSE_ACTION ("print0", print0), /* GNU */
262 {ARG_ACTION, "printf", parse_printf, NULL}, /* GNU */
263 PARSE_ACTION ("prune", prune),
264 PARSE_ACTION ("quit", quit), /* GNU */
265 {ARG_TEST, "readable", parse_accesscheck, pred_readable}, /* GNU, 4.3.0+ */
266 PARSE_TEST ("regex", regex), /* GNU */
267 PARSE_OPTION ("regextype", regextype), /* GNU */
268 PARSE_TEST ("samefile", samefile), /* GNU */
269 #if 0
270 PARSE_OPTION ("show-control-chars", show_control_chars), /* GNU, 4.3.0+ */
271 #endif
272 PARSE_TEST ("size", size),
273 PARSE_TEST ("type", type),
274 PARSE_TEST ("uid", uid), /* GNU */
275 PARSE_TEST ("used", used), /* GNU */
276 PARSE_TEST ("user", user),
277 PARSE_OPTION ("warn", warn), /* GNU */
278 PARSE_TEST_NP ("wholename", wholename), /* GNU, replaces -path */
279 {ARG_TEST, "writable", parse_accesscheck, pred_writable}, /* GNU, 4.3.0+ */
280 PARSE_OPTION ("xdev", xdev),
281 PARSE_TEST ("xtype", xtype), /* GNU */
282 #ifdef UNIMPLEMENTED_UNIX
283 /* It's pretty ugly for find to know about archive formats.
284 Plus what it could do with cpio archives is very limited.
285 Better to leave it out. */
286 PARSE(ARG_UNIMPLEMENTED, "cpio", cpio), /* Unix */
287 #endif
288 /* gnulib's stdbool.h might have made true and false into macros,
289 * so we can't leave named 'true' and 'false' tokens, so we have
290 * to expeant the relevant entries longhand.
292 {ARG_TEST, "false", parse_false, pred_false}, /* GNU */
293 {ARG_TEST, "true", parse_true, pred_true }, /* GNU */
294 {ARG_NOOP, "noop", NULL, pred_true }, /* GNU, internal use only */
296 /* Various other cases that don't fit neatly into our macro scheme. */
297 {ARG_TEST, "help", parse_help, NULL}, /* GNU */
298 {ARG_TEST, "-help", parse_help, NULL}, /* GNU */
299 {ARG_TEST, "version", parse_version, NULL}, /* GNU */
300 {ARG_TEST, "-version", parse_version, NULL}, /* GNU */
301 {0, 0, 0, 0}
305 static const char *first_nonoption_arg = NULL;
306 static const struct parser_table *noop = NULL;
310 static const struct parser_table*
311 get_noop(void)
313 int i;
314 if (NULL == noop)
316 for (i = 0; parse_table[i].parser_name != 0; i++)
318 if (ARG_NOOP ==parse_table[i].type)
320 noop = &(parse_table[i]);
321 break;
325 return noop;
330 void
331 set_follow_state(enum SymlinkOption opt)
333 if (options.debug_options & DebugStat)
335 /* For DebugStat, the choice is made at runtime within debug_stat()
336 * by checking the contents of the symlink_handling variable.
338 options.xstat = debug_stat;
340 else
342 switch (opt)
344 case SYMLINK_ALWAYS_DEREF: /* -L */
345 options.xstat = optionl_stat;
346 options.no_leaf_check = true;
347 break;
349 case SYMLINK_NEVER_DEREF: /* -P (default) */
350 options.xstat = optionp_stat;
351 /* Can't turn no_leaf_check off because the user might have specified
352 * -noleaf anyway
354 break;
356 case SYMLINK_DEREF_ARGSONLY: /* -H */
357 options.xstat = optionh_stat;
358 options.no_leaf_check = true;
361 options.symlink_handling = opt;
365 void
366 parse_begin_user_args (char **args, int argno, const struct predicate *last, const struct predicate *predicates)
368 (void) args;
369 (void) argno;
370 (void) last;
371 (void) predicates;
372 first_nonoption_arg = NULL;
375 void
376 parse_end_user_args (char **args, int argno, const struct predicate *last, const struct predicate *predicates)
378 /* does nothing */
379 (void) args;
380 (void) argno;
381 (void) last;
382 (void) predicates;
388 /* Return a pointer to the parser function to invoke for predicate
389 SEARCH_NAME.
390 Return NULL if SEARCH_NAME is not a valid predicate name. */
392 const struct parser_table*
393 find_parser (char *search_name)
395 int i;
396 const char *original_arg = search_name;
398 if (*search_name == '-')
399 search_name++;
400 for (i = 0; parse_table[i].parser_name != 0; i++)
402 if (strcmp (parse_table[i].parser_name, search_name) == 0)
404 /* If this is an option, but we have already had a
405 * non-option argument, the user may be under the
406 * impression that the behaviour of the option
407 * argument is conditional on some preceding
408 * tests. This might typically be the case with,
409 * for example, -maxdepth.
411 * The options -daystart and -follow are exempt
412 * from this treatment, since their positioning
413 * in the command line does have an effect on
414 * subsequent tests but not previous ones. That
415 * might be intentional on the part of the user.
417 if (parse_table[i].type != ARG_POSITIONAL_OPTION)
419 /* Something other than -follow/-daystart.
420 * If this is an option, check if it followed
421 * a non-option and if so, issue a warning.
423 if (parse_table[i].type == ARG_OPTION)
425 if ((first_nonoption_arg != NULL)
426 && options.warnings )
428 /* option which follows a non-option */
429 error (0, 0,
430 _("warning: you have specified the %s "
431 "option after a non-option argument %s, "
432 "but options are not positional (%s affects "
433 "tests specified before it as well as those "
434 "specified after it). Please specify options "
435 "before other arguments.\n"),
436 original_arg,
437 first_nonoption_arg,
438 original_arg);
441 else
443 /* Not an option or a positional option,
444 * so remember we've seen it in order to
445 * use it in a possible future warning message.
447 if (first_nonoption_arg == NULL)
449 first_nonoption_arg = original_arg;
454 return &parse_table[i];
457 return NULL;
460 static float
461 estimate_file_age_success_rate(float num_days)
463 if (num_days < 0.1)
465 /* Assume 1% of files have timestamps in the future */
466 return 0.01f;
468 else if (num_days < 1)
470 /* Assume 30% of files have timestamps today */
471 return 0.3f;
473 else if (num_days > 100)
475 /* Assume 30% of files are very old */
476 return 0.3f;
478 else
480 /* Assume 39% of files are between 1 and 100 days old. */
481 return 0.39f;
485 static float
486 estimate_timestamp_success_rate(time_t when)
488 int num_days = (when - options.cur_day_start) / 86400;
489 return estimate_file_age_success_rate(num_days);
493 /* The parsers are responsible to continue scanning ARGV for
494 their arguments. Each parser knows what is and isn't
495 allowed for itself.
497 ARGV is the argument array.
498 *ARG_PTR is the index to start at in ARGV,
499 updated to point beyond the last element consumed.
501 The predicate structure is updated with the new information. */
503 static boolean
504 parse_amin (const struct parser_table* entry, char **argv, int *arg_ptr)
506 struct predicate *our_pred;
507 uintmax_t num;
508 enum comparison_type c_type;
509 time_t t;
511 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
512 return false;
513 if (!get_num_days (argv[*arg_ptr], &num, &c_type))
514 return false;
515 t = options.cur_day_start + DAYSECS - num * 60;
516 our_pred = insert_primary (entry);
517 our_pred->args.info.kind = c_type;
518 our_pred->args.info.negative = t < 0;
519 our_pred->args.info.l_val = t;
520 our_pred->est_success_rate = estimate_file_age_success_rate(num);
521 (*arg_ptr)++;
522 return true;
525 static boolean
526 parse_and (const struct parser_table* entry, char **argv, int *arg_ptr)
528 struct predicate *our_pred;
530 (void) argv;
531 (void) arg_ptr;
533 our_pred = get_new_pred (entry);
534 our_pred->pred_func = pred_and;
535 our_pred->p_type = BI_OP;
536 our_pred->p_prec = AND_PREC;
537 our_pred->need_stat = our_pred->need_type = false;
538 return true;
541 static boolean
542 parse_anewer (const struct parser_table* entry, char **argv, int *arg_ptr)
544 struct predicate *our_pred;
545 struct stat stat_newer;
547 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
548 return false;
549 if ((*options.xstat) (argv[*arg_ptr], &stat_newer))
550 error (1, errno, "%s", argv[*arg_ptr]);
551 our_pred = insert_primary (entry);
552 our_pred->args.time = stat_newer.st_mtime;
553 our_pred->est_success_rate = estimate_timestamp_success_rate(stat_newer.st_mtime);
554 (*arg_ptr)++;
555 return true;
558 boolean
559 parse_close (const struct parser_table* entry, char **argv, int *arg_ptr)
561 struct predicate *our_pred;
563 (void) argv;
564 (void) arg_ptr;
566 our_pred = get_new_pred (entry);
567 our_pred->pred_func = pred_close;
568 our_pred->p_type = CLOSE_PAREN;
569 our_pred->p_prec = NO_PREC;
570 our_pred->need_stat = our_pred->need_type = false;
571 return true;
574 static boolean
575 parse_cmin (const struct parser_table* entry, char **argv, int *arg_ptr)
577 struct predicate *our_pred;
578 uintmax_t num;
579 enum comparison_type c_type;
580 time_t t;
582 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
583 return false;
584 if (!get_num_days (argv[*arg_ptr], &num, &c_type))
585 return false;
586 t = options.cur_day_start + DAYSECS - num * 60;
587 our_pred = insert_primary (entry);
588 our_pred->args.info.kind = c_type;
589 our_pred->args.info.negative = t < 0;
590 our_pred->args.info.l_val = t;
591 our_pred->est_success_rate = estimate_file_age_success_rate(num);
592 (*arg_ptr)++;
593 return true;
596 static boolean
597 parse_cnewer (const struct parser_table* entry, char **argv, int *arg_ptr)
599 struct predicate *our_pred;
600 struct stat stat_newer;
602 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
603 return false;
604 if ((*options.xstat) (argv[*arg_ptr], &stat_newer))
605 error (1, errno, "%s", argv[*arg_ptr]);
606 our_pred = insert_primary (entry);
607 our_pred->args.time = stat_newer.st_mtime;
608 our_pred->est_success_rate = estimate_timestamp_success_rate(stat_newer.st_mtime);
609 (*arg_ptr)++;
610 return true;
613 static boolean
614 parse_comma (const struct parser_table* entry, char **argv, int *arg_ptr)
616 struct predicate *our_pred;
618 (void) argv;
619 (void) arg_ptr;
621 our_pred = get_new_pred (entry);
622 our_pred->pred_func = pred_comma;
623 our_pred->p_type = BI_OP;
624 our_pred->p_prec = COMMA_PREC;
625 our_pred->need_stat = our_pred->need_type = false;
626 our_pred->est_success_rate = 1.0f;
627 return true;
630 static boolean
631 parse_daystart (const struct parser_table* entry, char **argv, int *arg_ptr)
633 struct tm *local;
635 (void) entry;
636 (void) argv;
637 (void) arg_ptr;
639 if (options.full_days == false)
641 options.cur_day_start += DAYSECS;
642 local = localtime (&options.cur_day_start);
643 options.cur_day_start -= (local
644 ? (local->tm_sec + local->tm_min * 60
645 + local->tm_hour * 3600)
646 : options.cur_day_start % DAYSECS);
647 options.full_days = true;
649 return true;
652 static boolean
653 parse_delete (const struct parser_table* entry, char *argv[], int *arg_ptr)
655 struct predicate *our_pred;
656 (void) argv;
657 (void) arg_ptr;
659 our_pred = insert_primary (entry);
660 our_pred->side_effects = our_pred->no_default_print = true;
661 /* -delete implies -depth */
662 options.do_dir_first = false;
663 our_pred->est_success_rate = 1.0f;
664 return true;
667 static boolean
668 parse_depth (const struct parser_table* entry, char **argv, int *arg_ptr)
670 (void) entry;
671 (void) argv;
672 (void) arg_ptr;
674 options.do_dir_first = false;
675 return parse_noop(entry, argv, arg_ptr);
678 static boolean
679 parse_d (const struct parser_table* entry, char **argv, int *arg_ptr)
681 (void) argv;
682 (void) arg_ptr;
684 if (options.warnings)
686 error (0, 0,
687 _("warning: the -d option is deprecated; please use -depth instead, because the latter is a POSIX-compliant feature."));
689 return parse_depth(entry, argv, arg_ptr);
692 static boolean
693 parse_empty (const struct parser_table* entry, char **argv, int *arg_ptr)
695 struct predicate *our_pred;
696 (void) argv;
697 (void) arg_ptr;
699 our_pred = insert_primary (entry);
700 our_pred->est_success_rate = 0.01f; /* assume 1% of files are empty. */
701 return true;
704 static boolean
705 parse_exec (const struct parser_table* entry, char **argv, int *arg_ptr)
707 return insert_exec_ok ("-exec", entry, argv, arg_ptr);
710 static boolean
711 parse_execdir (const struct parser_table* entry, char **argv, int *arg_ptr)
713 return insert_exec_ok ("-execdir", entry, argv, arg_ptr);
716 static boolean
717 parse_false (const struct parser_table* entry, char **argv, int *arg_ptr)
719 struct predicate *our_pred;
721 (void) argv;
722 (void) arg_ptr;
724 our_pred = insert_primary (entry);
725 our_pred->need_stat = our_pred->need_type = false;
726 our_pred->side_effects = our_pred->no_default_print = false;
727 our_pred->est_success_rate = 0.0f;
728 return true;
731 static boolean
732 parse_fls (const struct parser_table* entry, char **argv, int *arg_ptr)
734 struct predicate *our_pred;
736 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
737 return false;
738 our_pred = insert_primary (entry);
739 our_pred->args.stream = open_output_file (argv[*arg_ptr]);
740 our_pred->side_effects = our_pred->no_default_print = true;
741 our_pred->est_success_rate = 1.0f;
742 (*arg_ptr)++;
743 return true;
746 static boolean
747 parse_fprintf (const struct parser_table* entry, char **argv, int *arg_ptr)
749 FILE *fp;
751 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
752 return false;
753 if (argv[*arg_ptr + 1] == NULL)
755 /* Ensure we get "missing arg" message, not "invalid arg". */
756 (*arg_ptr)++;
757 return false;
759 fp = open_output_file (argv[*arg_ptr]);
760 (*arg_ptr)++;
761 return insert_fprintf (fp, entry, pred_fprintf, argv, arg_ptr);
764 static boolean
765 parse_follow (const struct parser_table* entry, char **argv, int *arg_ptr)
767 (void) entry;
768 (void) argv;
769 (void) arg_ptr;
771 set_follow_state(SYMLINK_ALWAYS_DEREF);
772 return parse_noop(entry, argv, arg_ptr);
775 static boolean
776 parse_fprint (const struct parser_table* entry, char **argv, int *arg_ptr)
778 struct predicate *our_pred;
780 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
781 return false;
782 our_pred = insert_primary (entry);
783 our_pred->args.printf_vec.segment = NULL;
784 our_pred->args.printf_vec.stream = open_output_file (argv[*arg_ptr]);
785 our_pred->args.printf_vec.dest_is_tty = stream_is_tty(our_pred->args.printf_vec.stream);
786 our_pred->args.printf_vec.quote_opts = clone_quoting_options (NULL);
787 our_pred->side_effects = our_pred->no_default_print = true;
788 our_pred->need_stat = our_pred->need_type = false;
789 our_pred->est_success_rate = 1.0f;
790 (*arg_ptr)++;
791 return true;
794 static boolean
795 parse_fprint0 (const struct parser_table* entry, char **argv, int *arg_ptr)
797 struct predicate *our_pred;
799 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
800 return false;
801 our_pred = insert_primary (entry);
802 our_pred->args.stream = open_output_file (argv[*arg_ptr]);
803 our_pred->side_effects = our_pred->no_default_print = true;
804 our_pred->need_stat = our_pred->need_type = false;
805 our_pred->est_success_rate = 1.0f;
806 (*arg_ptr)++;
807 return true;
810 static float estimate_fstype_success_rate(const char *fsname)
812 struct stat dir_stat;
813 const char *dir = "/";
814 if (0 == stat(dir, &dir_stat))
816 const char *fstype = filesystem_type(&dir_stat, dir);
817 /* Assume most files are on the same filesystem type as the root fs. */
818 if (0 == strcmp(fsname, fstype))
819 return 0.7f;
820 else
821 return 0.3f;
823 return 1.0f;
827 static boolean
828 parse_fstype (const struct parser_table* entry, char **argv, int *arg_ptr)
830 struct predicate *our_pred;
832 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
833 return false;
834 our_pred = insert_primary (entry);
835 our_pred->args.str = argv[*arg_ptr];
837 /* This is an expensive operation, so although there are
838 * circumstances where it is selective, we ignore this fact because
839 * we probably don't want to promote this test to the front anyway.
841 our_pred->est_success_rate = estimate_fstype_success_rate(argv[*arg_ptr]);
842 (*arg_ptr)++;
843 return true;
846 static boolean
847 parse_gid (const struct parser_table* entry, char **argv, int *arg_ptr)
849 struct predicate *p = insert_num (argv, arg_ptr, entry);
850 p->est_success_rate = (p->args.info.l_val < 100) ? 0.99 : 0.2;
851 return p;
854 static boolean
855 parse_group (const struct parser_table* entry, char **argv, int *arg_ptr)
857 struct group *cur_gr;
858 struct predicate *our_pred;
859 gid_t gid;
860 int gid_len;
862 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
863 return false;
864 cur_gr = getgrnam (argv[*arg_ptr]);
865 endgrent ();
866 if (cur_gr != NULL)
867 gid = cur_gr->gr_gid;
868 else
870 gid_len = strspn (argv[*arg_ptr], "0123456789");
871 if ((gid_len == 0) || (argv[*arg_ptr][gid_len] != '\0'))
872 return false;
873 gid = atoi (argv[*arg_ptr]);
875 our_pred = insert_primary (entry);
876 our_pred->args.gid = gid;
877 our_pred->est_success_rate = (our_pred->args.info.l_val < 100) ? 0.99 : 0.2;
878 (*arg_ptr)++;
879 return true;
882 static boolean
883 parse_help (const struct parser_table* entry, char **argv, int *arg_ptr)
885 (void) entry;
886 (void) argv;
887 (void) arg_ptr;
889 usage(stdout, 0, NULL);
890 puts (_("\n\
891 default path is the current directory; default expression is -print\n\
892 expression may consist of: operators, options, tests, and actions:\n"));
893 puts (_("\
894 operators (decreasing precedence; -and is implicit where no others are given):\n\
895 ( EXPR ) ! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2\n\
896 EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2\n"));
897 puts (_("\
898 positional options (always true): -daystart -follow -regextype\n\n\
899 normal options (always true, specified before other expressions):\n\
900 -depth --help -maxdepth LEVELS -mindepth LEVELS -mount -noleaf\n\
901 --version -xdev -ignore_readdir_race -noignore_readdir_race\n"));
902 puts (_("\
903 tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N\n\
904 -cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME\n\
905 -ilname PATTERN -iname PATTERN -inum N -iwholename PATTERN -iregex PATTERN\n\
906 -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE"));
907 puts (_("\
908 -nouser -nogroup -path PATTERN -perm [+-]MODE -regex PATTERN\n\
909 -readable -writable -executable\n\
910 -wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N\n\
911 -used N -user NAME -xtype [bcdpfls]\n"));
912 puts (_("\
913 actions: -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print \n\
914 -fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit\n\
915 -exec COMMAND ; -exec COMMAND {} + -ok COMMAND ;\n\
916 -execdir COMMAND ; -execdir COMMAND {} + -okdir COMMAND ;\n\
917 "));
918 puts (_("Report (and track progress on fixing) bugs via the findutils bug-reporting\n\
919 page at http://savannah.gnu.org/ or, if you have no web access, by sending\n\
920 email to <bug-findutils@gnu.org>."));
921 exit (0);
924 static float estimate_pattern_match_rate(const char *pattern, int is_regex)
926 if (strpbrk(pattern, "*?[") || (is_regex && strpbrk(pattern, ".")))
928 /* A wildcard; assume the pattern matches most files. */
929 return 0.8f;
931 else
933 return 0.1f;
937 static boolean
938 parse_ilname (const struct parser_table* entry, char **argv, int *arg_ptr)
940 struct predicate *our_pred;
942 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
943 return false;
944 our_pred = insert_primary (entry);
945 our_pred->args.str = argv[*arg_ptr];
946 /* Use the generic glob pattern estimator to figure out how many
947 * links will match, but bear in mind that most files won't be links.
949 our_pred->est_success_rate = 0.1 * estimate_pattern_match_rate(our_pred->args.str, 0);
950 (*arg_ptr)++;
951 return true;
955 /* sanity check the fnmatch() function to make sure
956 * it really is the GNU version.
958 static boolean
959 fnmatch_sanitycheck(void)
961 /* fprintf(stderr, "Performing find sanity check..."); */
962 if (0 != fnmatch("foo", "foo", 0)
963 || 0 == fnmatch("Foo", "foo", 0)
964 || 0 != fnmatch("Foo", "foo", FNM_CASEFOLD))
966 error (1, 0, _("sanity check of the fnmatch() library function failed."));
967 /* fprintf(stderr, "FAILED\n"); */
968 return false;
971 /* fprintf(stderr, "OK\n"); */
972 return true;
976 static boolean
977 check_name_arg(const char *pred, const char *arg)
979 if (strchr(arg, '/'))
981 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'."),
982 pred, arg, arg);
984 return true; /* allow it anyway */
989 static boolean
990 parse_iname (const struct parser_table* entry, char **argv, int *arg_ptr)
992 struct predicate *our_pred;
994 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
995 return false;
996 if (!check_name_arg("-iname", argv[*arg_ptr]))
997 return false;
999 fnmatch_sanitycheck();
1001 our_pred = insert_primary (entry);
1002 our_pred->need_stat = our_pred->need_type = false;
1003 our_pred->args.str = argv[*arg_ptr];
1004 our_pred->est_success_rate = estimate_pattern_match_rate(our_pred->args.str, 0);
1005 (*arg_ptr)++;
1006 return true;
1009 static boolean
1010 parse_inum (const struct parser_table* entry, char **argv, int *arg_ptr)
1012 struct predicate *p = insert_num (argv, arg_ptr, entry);
1013 /* inode number is exact match only, so very low proportions of files match */
1014 p->est_success_rate = 1e-6;
1015 return p;
1018 /* -ipath is deprecated (at RMS's request) in favour of
1019 * -iwholename. See the node "GNU Manuals" in standards.texi
1020 * for the rationale for this (basically, GNU prefers the use
1021 * of the phrase "file name" to "path name"
1023 static boolean
1024 parse_ipath (const struct parser_table* entry, char **argv, int *arg_ptr)
1026 error (0, 0,
1027 _("warning: the predicate -ipath is deprecated; please use -iwholename instead."));
1029 return parse_iwholename(entry, argv, arg_ptr);
1032 static boolean
1033 parse_iwholename (const struct parser_table* entry, char **argv, int *arg_ptr)
1035 struct predicate *our_pred;
1037 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1038 return false;
1040 fnmatch_sanitycheck();
1042 our_pred = insert_primary_withpred (entry, pred_ipath);
1043 our_pred->need_stat = our_pred->need_type = false;
1044 our_pred->args.str = argv[*arg_ptr];
1045 our_pred->est_success_rate = estimate_pattern_match_rate(our_pred->args.str, 0);
1046 (*arg_ptr)++;
1047 return true;
1050 static boolean
1051 parse_iregex (const struct parser_table* entry, char **argv, int *arg_ptr)
1053 return insert_regex (argv, arg_ptr, entry, RE_ICASE|options.regex_options);
1056 static boolean
1057 parse_links (const struct parser_table* entry, char **argv, int *arg_ptr)
1059 struct predicate *p = insert_num (argv, arg_ptr, entry);
1060 if (p->args.info.l_val == 1)
1061 p->est_success_rate = 0.99;
1062 else if (p->args.info.l_val == 2)
1063 p->est_success_rate = 0.01;
1064 else
1065 p->est_success_rate = 1e-3;
1066 return p;
1069 static boolean
1070 parse_lname (const struct parser_table* entry, char **argv, int *arg_ptr)
1072 struct predicate *our_pred;
1074 (void) argv;
1075 (void) arg_ptr;
1077 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1078 return false;
1080 fnmatch_sanitycheck();
1082 our_pred = insert_primary (entry);
1083 our_pred->args.str = argv[*arg_ptr];
1084 our_pred->est_success_rate = 0.1 * estimate_pattern_match_rate(our_pred->args.str, 0);
1085 (*arg_ptr)++;
1086 return true;
1089 static boolean
1090 parse_ls (const struct parser_table* entry, char **argv, int *arg_ptr)
1092 struct predicate *our_pred;
1094 (void) &argv;
1095 (void) &arg_ptr;
1097 our_pred = insert_primary (entry);
1098 our_pred->side_effects = our_pred->no_default_print = true;
1099 return true;
1102 static boolean
1103 parse_maxdepth (const struct parser_table* entry, char **argv, int *arg_ptr)
1105 int depth_len;
1106 (void) entry;
1108 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1109 return false;
1110 depth_len = strspn (argv[*arg_ptr], "0123456789");
1111 if ((depth_len == 0) || (argv[*arg_ptr][depth_len] != '\0'))
1112 return false;
1113 options.maxdepth = atoi (argv[*arg_ptr]);
1114 if (options.maxdepth < 0)
1115 return false;
1116 (*arg_ptr)++;
1117 return parse_noop(entry, argv, arg_ptr);
1120 static boolean
1121 parse_mindepth (const struct parser_table* entry, char **argv, int *arg_ptr)
1123 int depth_len;
1124 (void) entry;
1126 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1127 return false;
1128 depth_len = strspn (argv[*arg_ptr], "0123456789");
1129 if ((depth_len == 0) || (argv[*arg_ptr][depth_len] != '\0'))
1130 return false;
1131 options.mindepth = atoi (argv[*arg_ptr]);
1132 if (options.mindepth < 0)
1133 return false;
1134 (*arg_ptr)++;
1135 return parse_noop(entry, argv, arg_ptr);
1138 static boolean
1139 parse_mmin (const struct parser_table* entry, char **argv, int *arg_ptr)
1141 struct predicate *our_pred;
1142 uintmax_t num;
1143 enum comparison_type c_type;
1144 time_t t;
1146 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1147 return false;
1148 if (!get_num_days (argv[*arg_ptr], &num, &c_type))
1149 return false;
1150 t = options.cur_day_start + DAYSECS - num * 60;
1151 our_pred = insert_primary (entry);
1152 our_pred->args.info.kind = c_type;
1153 our_pred->args.info.negative = t < 0;
1154 our_pred->args.info.l_val = t;
1155 our_pred->est_success_rate = estimate_file_age_success_rate(num);
1156 (*arg_ptr)++;
1157 return true;
1160 static boolean
1161 parse_name (const struct parser_table* entry, char **argv, int *arg_ptr)
1163 struct predicate *our_pred;
1165 (void) argv;
1166 (void) arg_ptr;
1168 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1169 return false;
1170 if (!check_name_arg("-name", argv[*arg_ptr]))
1171 return false;
1172 fnmatch_sanitycheck();
1174 our_pred = insert_primary (entry);
1175 our_pred->need_stat = our_pred->need_type = false;
1176 our_pred->args.str = argv[*arg_ptr];
1177 our_pred->est_success_rate = estimate_pattern_match_rate(our_pred->args.str, 0);
1178 (*arg_ptr)++;
1179 return true;
1182 static boolean
1183 parse_negate (const struct parser_table* entry, char **argv, int *arg_ptr)
1185 struct predicate *our_pred;
1187 (void) &argv;
1188 (void) &arg_ptr;
1190 our_pred = get_new_pred_chk_op (entry);
1191 our_pred->pred_func = pred_negate;
1192 our_pred->p_type = UNI_OP;
1193 our_pred->p_prec = NEGATE_PREC;
1194 our_pred->need_stat = our_pred->need_type = false;
1195 return true;
1198 static boolean
1199 parse_newer (const struct parser_table* entry, char **argv, int *arg_ptr)
1201 struct predicate *our_pred;
1202 struct stat stat_newer;
1204 (void) argv;
1205 (void) arg_ptr;
1207 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1208 return false;
1209 if ((*options.xstat) (argv[*arg_ptr], &stat_newer))
1210 error (1, errno, "%s", argv[*arg_ptr]);
1211 our_pred = insert_primary (entry);
1212 our_pred->args.time = stat_newer.st_mtime;
1213 our_pred->est_success_rate = estimate_timestamp_success_rate(stat_newer.st_mtime);
1214 (*arg_ptr)++;
1215 return true;
1218 static boolean
1219 parse_noleaf (const struct parser_table* entry, char **argv, int *arg_ptr)
1221 (void) &argv;
1222 (void) &arg_ptr;
1223 (void) entry;
1225 options.no_leaf_check = true;
1226 return parse_noop(entry, argv, arg_ptr);
1229 #ifdef CACHE_IDS
1230 /* Arbitrary amount by which to increase size
1231 of `uid_unused' and `gid_unused'. */
1232 #define ALLOC_STEP 2048
1234 /* Boolean: if uid_unused[n] is nonzero, then UID n has no passwd entry. */
1235 char *uid_unused = NULL;
1237 /* Number of elements in `uid_unused'. */
1238 unsigned uid_allocated;
1240 /* Similar for GIDs and group entries. */
1241 char *gid_unused = NULL;
1242 unsigned gid_allocated;
1243 #endif
1245 static boolean
1246 parse_nogroup (const struct parser_table* entry, char **argv, int *arg_ptr)
1248 struct predicate *our_pred;
1250 (void) &argv;
1251 (void) &arg_ptr;
1253 our_pred = insert_primary (entry);
1254 our_pred->est_success_rate = 1e-4;
1255 #ifdef CACHE_IDS
1256 if (gid_unused == NULL)
1258 struct group *gr;
1260 gid_allocated = ALLOC_STEP;
1261 gid_unused = xmalloc (gid_allocated);
1262 memset (gid_unused, 1, gid_allocated);
1263 setgrent ();
1264 while ((gr = getgrent ()) != NULL)
1266 if ((unsigned) gr->gr_gid >= gid_allocated)
1268 unsigned new_allocated = (unsigned) gr->gr_gid + ALLOC_STEP;
1269 gid_unused = xrealloc (gid_unused, new_allocated);
1270 memset (gid_unused + gid_allocated, 1,
1271 new_allocated - gid_allocated);
1272 gid_allocated = new_allocated;
1274 gid_unused[(unsigned) gr->gr_gid] = 0;
1276 endgrent ();
1278 #endif
1279 return true;
1282 static boolean
1283 parse_nouser (const struct parser_table* entry, char **argv, int *arg_ptr)
1285 struct predicate *our_pred;
1286 (void) argv;
1287 (void) arg_ptr;
1290 our_pred = insert_primary (entry);
1291 our_pred->est_success_rate = 1e-3;
1292 #ifdef CACHE_IDS
1293 if (uid_unused == NULL)
1295 struct passwd *pw;
1297 uid_allocated = ALLOC_STEP;
1298 uid_unused = xmalloc (uid_allocated);
1299 memset (uid_unused, 1, uid_allocated);
1300 setpwent ();
1301 while ((pw = getpwent ()) != NULL)
1303 if ((unsigned) pw->pw_uid >= uid_allocated)
1305 unsigned new_allocated = (unsigned) pw->pw_uid + ALLOC_STEP;
1306 uid_unused = xrealloc (uid_unused, new_allocated);
1307 memset (uid_unused + uid_allocated, 1,
1308 new_allocated - uid_allocated);
1309 uid_allocated = new_allocated;
1311 uid_unused[(unsigned) pw->pw_uid] = 0;
1313 endpwent ();
1315 #endif
1316 return true;
1319 static boolean
1320 parse_nowarn (const struct parser_table* entry, char **argv, int *arg_ptr)
1322 (void) argv;
1323 (void) arg_ptr;
1324 (void) entry;
1326 options.warnings = false;
1327 return parse_noop(entry, argv, arg_ptr);
1330 static boolean
1331 parse_ok (const struct parser_table* entry, char **argv, int *arg_ptr)
1333 return insert_exec_ok ("-ok", entry, argv, arg_ptr);
1336 static boolean
1337 parse_okdir (const struct parser_table* entry, char **argv, int *arg_ptr)
1339 return insert_exec_ok ("-okdir", entry, argv, arg_ptr);
1342 boolean
1343 parse_open (const struct parser_table* entry, char **argv, int *arg_ptr)
1345 struct predicate *our_pred;
1347 (void) argv;
1348 (void) arg_ptr;
1350 our_pred = get_new_pred_chk_op (entry);
1351 our_pred->pred_func = pred_open;
1352 our_pred->p_type = OPEN_PAREN;
1353 our_pred->p_prec = NO_PREC;
1354 our_pred->need_stat = our_pred->need_type = false;
1355 return true;
1358 static boolean
1359 parse_or (const struct parser_table* entry, char **argv, int *arg_ptr)
1361 struct predicate *our_pred;
1363 (void) argv;
1364 (void) arg_ptr;
1366 our_pred = get_new_pred (entry);
1367 our_pred->pred_func = pred_or;
1368 our_pred->p_type = BI_OP;
1369 our_pred->p_prec = OR_PREC;
1370 our_pred->need_stat = our_pred->need_type = false;
1371 return true;
1374 /* -path is deprecated (at RMS's request) in favour of
1375 * -iwholename. See the node "GNU Manuals" in standards.texi
1376 * for the rationale for this (basically, GNU prefers the use
1377 * of the phrase "file name" to "path name".
1379 * We do not issue a warning that this usage is deprecated
1380 * since HPUX find supports this predicate also.
1382 static boolean
1383 parse_path (const struct parser_table* entry, char **argv, int *arg_ptr)
1385 return parse_wholename(entry, argv, arg_ptr);
1388 static boolean
1389 parse_wholename (const struct parser_table* entry, char **argv, int *arg_ptr)
1391 struct predicate *our_pred;
1393 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1394 return false;
1395 our_pred = insert_primary_withpred (entry, pred_path);
1396 our_pred->need_stat = our_pred->need_type = false;
1397 our_pred->args.str = argv[*arg_ptr];
1398 our_pred->est_success_rate = estimate_pattern_match_rate(our_pred->args.str, 0);
1399 (*arg_ptr)++;
1400 return true;
1403 static boolean
1404 parse_perm (const struct parser_table* entry, char **argv, int *arg_ptr)
1406 mode_t perm_val;
1407 float rate;
1408 int mode_start = 0;
1409 boolean havekind = false;
1410 enum permissions_type kind = PERM_EXACT;
1411 struct mode_change *change = NULL;
1412 struct predicate *our_pred;
1414 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1415 return false;
1417 switch (argv[*arg_ptr][0])
1419 case '-':
1420 mode_start = 1;
1421 kind = PERM_AT_LEAST;
1422 havekind = true;
1423 rate = 0.2;
1424 break;
1426 case '+':
1427 change = mode_compile (argv[*arg_ptr]);
1428 if (NULL == change)
1430 /* Most likely the caller is an old script that is still
1431 * using the obsolete GNU syntax '-perm +MODE'. This old
1432 * syntax was withdrawn in favor of '-perm /MODE' because
1433 * it is incompatible with POSIX in some cases, but we
1434 * still support uses of it that are not incompatible with
1435 * POSIX.
1437 mode_start = 1;
1438 kind = PERM_ANY;
1439 rate = 0.3;
1441 else
1443 /* This is a POSIX-compatible usage */
1444 mode_start = 0;
1445 kind = PERM_EXACT;
1446 rate = 0.1;
1448 havekind = true;
1449 break;
1451 case '/': /* GNU extension */
1452 mode_start = 1;
1453 kind = PERM_ANY;
1454 havekind = true;
1455 rate = 0.3;
1456 break;
1458 default:
1459 /* For example, '-perm 0644', which is valid and matches
1460 * only files whose mode is exactly 0644.
1462 * We do nothing here, because mode_start and kind are already
1463 * correctly set.
1465 rate = 0.01;
1466 break;
1469 if (NULL == change)
1471 change = mode_compile (argv[*arg_ptr] + mode_start);
1472 if (NULL == change)
1473 error (1, 0, _("invalid mode `%s'"), argv[*arg_ptr]);
1475 perm_val = mode_adjust (0, change, 0);
1476 free (change);
1478 our_pred = insert_primary (entry);
1479 our_pred->est_success_rate = rate;
1480 if (havekind)
1482 our_pred->args.perm.kind = kind;
1484 else
1487 switch (argv[*arg_ptr][0])
1489 case '-':
1490 our_pred->args.perm.kind = PERM_AT_LEAST;
1491 break;
1492 case '+':
1493 our_pred->args.perm.kind = PERM_ANY;
1494 break;
1495 default:
1496 our_pred->args.perm.kind = PERM_EXACT;
1497 break;
1500 if (('/' == argv[*arg_ptr][0]) && (0 == perm_val))
1502 /* The meaning of -perm /000 will change in the future.
1503 * It currently matches no files, but like -perm -000 it
1504 * should match all files.
1506 error (0, 0,
1507 _("warning: you have specified a mode pattern %s which is "
1508 "equivalent to 000. The meaning of -perm /000 will soon be "
1509 "changed to be consistent with -perm -000; that is, at the "
1510 "moment it matches no files but it will soon be changed to "
1511 "match all files."),
1512 argv[*arg_ptr]);
1515 our_pred->args.perm.val = perm_val & MODE_ALL;
1516 (*arg_ptr)++;
1517 return true;
1520 boolean
1521 parse_print (const struct parser_table* entry, char **argv, int *arg_ptr)
1523 struct predicate *our_pred;
1525 (void) argv;
1526 (void) arg_ptr;
1528 our_pred = insert_primary (entry);
1529 /* -print has the side effect of printing. This prevents us
1530 from doing undesired multiple printing when the user has
1531 already specified -print. */
1532 our_pred->side_effects = our_pred->no_default_print = true;
1533 our_pred->need_stat = our_pred->need_type = false;
1534 our_pred->args.printf_vec.segment = NULL;
1535 our_pred->args.printf_vec.stream = stdout;
1536 our_pred->args.printf_vec.dest_is_tty = stream_is_tty(stdout);
1537 our_pred->args.printf_vec.quote_opts = clone_quoting_options (NULL);
1539 return true;
1542 static boolean
1543 parse_print0 (const struct parser_table* entry, char **argv, int *arg_ptr)
1545 struct predicate *our_pred;
1547 (void) argv;
1548 (void) arg_ptr;
1550 our_pred = insert_primary (entry);
1551 /* -print0 has the side effect of printing. This prevents us
1552 from doing undesired multiple printing when the user has
1553 already specified -print0. */
1554 our_pred->side_effects = our_pred->no_default_print = true;
1555 our_pred->need_stat = our_pred->need_type = false;
1556 return true;
1559 static boolean
1560 parse_printf (const struct parser_table* entry, char **argv, int *arg_ptr)
1562 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1563 return false;
1564 return insert_fprintf (stdout, entry, pred_fprintf, argv, arg_ptr);
1567 static boolean
1568 parse_prune (const struct parser_table* entry, char **argv, int *arg_ptr)
1570 struct predicate *our_pred;
1572 (void) argv;
1573 (void) arg_ptr;
1575 our_pred = insert_primary (entry);
1576 our_pred->need_stat = our_pred->need_type = false;
1577 /* -prune has a side effect that it does not descend into
1578 the current directory. */
1579 our_pred->side_effects = true;
1580 our_pred->no_default_print = false;
1581 return true;
1584 static boolean
1585 parse_quit (const struct parser_table* entry, char **argv, int *arg_ptr)
1587 struct predicate *our_pred = insert_primary (entry);
1588 (void) argv;
1589 (void) arg_ptr;
1590 our_pred->need_stat = our_pred->need_type = false;
1591 our_pred->side_effects = true; /* Exiting is a side effect... */
1592 our_pred->no_default_print = false; /* Don't inhibit the default print, though. */
1593 our_pred->est_success_rate = 1e-6;
1594 return true;
1598 static boolean
1599 parse_regextype (const struct parser_table* entry, char **argv, int *arg_ptr)
1601 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1602 return false;
1604 /* collect the regex type name */
1605 options.regex_options = get_regex_type(argv[*arg_ptr]);
1606 (*arg_ptr)++;
1608 return parse_noop(entry, argv, arg_ptr);
1612 static boolean
1613 parse_regex (const struct parser_table* entry, char **argv, int *arg_ptr)
1615 return insert_regex (argv, arg_ptr, entry, options.regex_options);
1618 static boolean
1619 insert_regex (char **argv, int *arg_ptr, const struct parser_table *entry, int regex_options)
1621 struct predicate *our_pred;
1622 struct re_pattern_buffer *re;
1623 const char *error_message;
1625 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1626 return false;
1627 our_pred = insert_primary_withpred (entry, pred_regex);
1628 our_pred->need_stat = our_pred->need_type = false;
1629 re = (struct re_pattern_buffer *)
1630 xmalloc (sizeof (struct re_pattern_buffer));
1631 our_pred->args.regex = re;
1632 re->allocated = 100;
1633 re->buffer = (unsigned char *) xmalloc (re->allocated);
1634 re->fastmap = NULL;
1636 re_set_syntax(regex_options);
1637 re->syntax = regex_options;
1638 re->translate = NULL;
1640 error_message = re_compile_pattern (argv[*arg_ptr], strlen (argv[*arg_ptr]),
1641 re);
1642 if (error_message)
1643 error (1, 0, "%s", error_message);
1644 (*arg_ptr)++;
1645 our_pred->est_success_rate = estimate_pattern_match_rate(argv[*arg_ptr], 1);
1646 return true;
1649 static boolean
1650 parse_size (const struct parser_table* entry, char **argv, int *arg_ptr)
1652 struct predicate *our_pred;
1653 uintmax_t num;
1654 enum comparison_type c_type;
1655 int blksize = 512;
1656 int len;
1657 float rate = 1.0;
1659 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1660 return false;
1661 len = strlen (argv[*arg_ptr]);
1662 if (len == 0)
1663 error (1, 0, _("invalid null argument to -size"));
1664 switch (argv[*arg_ptr][len - 1])
1666 case 'b':
1667 blksize = 512;
1668 argv[*arg_ptr][len - 1] = '\0';
1669 break;
1671 case 'c':
1672 blksize = 1;
1673 argv[*arg_ptr][len - 1] = '\0';
1674 break;
1676 case 'k':
1677 blksize = 1024;
1678 argv[*arg_ptr][len - 1] = '\0';
1679 break;
1681 case 'M': /* Megabytes */
1682 blksize = 1024*1024;
1683 argv[*arg_ptr][len - 1] = '\0';
1684 break;
1686 case 'G': /* Gigabytes */
1687 blksize = 1024*1024*1024;
1688 argv[*arg_ptr][len - 1] = '\0';
1689 break;
1691 case 'w':
1692 blksize = 2;
1693 argv[*arg_ptr][len - 1] = '\0';
1694 break;
1696 case '0':
1697 case '1':
1698 case '2':
1699 case '3':
1700 case '4':
1701 case '5':
1702 case '6':
1703 case '7':
1704 case '8':
1705 case '9':
1706 break;
1708 default:
1709 error (1, 0, _("invalid -size type `%c'"), argv[*arg_ptr][len - 1]);
1711 if (!get_num (argv[*arg_ptr], &num, &c_type))
1712 return false;
1713 our_pred = insert_primary (entry);
1714 our_pred->args.size.kind = c_type;
1715 our_pred->args.size.blocksize = blksize;
1716 our_pred->args.size.size = num;
1717 our_pred->need_stat = true;
1718 our_pred->need_type = false;
1720 if (COMP_GT == c_type)
1721 our_pred->est_success_rate = (num*blksize > 20480) ? 0.1 : 0.9;
1722 else if (COMP_LT == c_type)
1723 our_pred->est_success_rate = (num*blksize > 20480) ? 0.9 : 0.1;
1724 else
1725 our_pred->est_success_rate = 0.01;
1727 (*arg_ptr)++;
1728 return true;
1732 static boolean
1733 parse_samefile (const struct parser_table* entry, char **argv, int *arg_ptr)
1735 struct predicate *our_pred;
1736 struct stat st;
1738 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1739 return false;
1740 if ((*options.xstat) (argv[*arg_ptr], &st))
1741 error (1, errno, "%s", argv[*arg_ptr]);
1743 our_pred = insert_primary (entry);
1744 our_pred->args.fileid.ino = st.st_ino;
1745 our_pred->args.fileid.dev = st.st_dev;
1746 our_pred->need_type = false;
1747 our_pred->need_stat = true;
1748 our_pred->est_success_rate = 0.01f;
1749 (*arg_ptr)++;
1750 return true;
1753 #if 0
1754 static boolean
1755 parse_show_control_chars (const struct parser_table* entry, char **argv, int *arg_ptr)
1757 const char *arg;
1758 const char *errmsg = _("The -show-control-chars option takes a single argument which "
1759 "must be 'literal' or 'safe'");
1761 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1763 error (1, errno, "%s", errmsg);
1764 return false;
1766 else
1768 arg = argv[*arg_ptr];
1770 if (0 == strcmp("literal", arg))
1772 options.literal_control_chars = true;
1774 else if (0 == strcmp("safe", arg))
1776 options.literal_control_chars = false;
1778 else
1780 error (1, errno, "%s", errmsg);
1781 return false;
1783 (*arg_ptr)++; /* consume the argument. */
1784 return true;
1787 #endif
1790 static boolean
1791 parse_true (const struct parser_table* entry, char **argv, int *arg_ptr)
1793 struct predicate *our_pred;
1795 (void) argv;
1796 (void) arg_ptr;
1798 our_pred = insert_primary (entry);
1799 our_pred->need_stat = our_pred->need_type = false;
1800 our_pred->est_success_rate = 1.0f;
1801 return true;
1804 static boolean
1805 parse_noop (const struct parser_table* entry, char **argv, int *arg_ptr)
1807 (void) entry;
1808 return parse_true(get_noop(), argv, arg_ptr);
1811 static boolean
1812 parse_accesscheck (const struct parser_table* entry, char **argv, int *arg_ptr)
1814 struct predicate *our_pred;
1815 (void) argv;
1816 (void) arg_ptr;
1817 our_pred = insert_primary (entry);
1818 our_pred->need_stat = our_pred->need_type = false;
1819 our_pred->side_effects = our_pred->no_default_print = false;
1820 if (our_pred->pred_func == pred_executable)
1821 our_pred->est_success_rate = 0.2;
1822 else
1823 our_pred->est_success_rate = 0.9;
1824 return true;
1827 static boolean
1828 parse_type (const struct parser_table* entry, char **argv, int *arg_ptr)
1830 return insert_type (argv, arg_ptr, entry, pred_type);
1833 static boolean
1834 parse_uid (const struct parser_table* entry, char **argv, int *arg_ptr)
1836 struct predicate *p = insert_num (argv, arg_ptr, entry);
1837 p->est_success_rate = (p->args.info.l_val < 100) ? 0.99 : 0.2;
1838 return p;
1841 static boolean
1842 parse_used (const struct parser_table* entry, char **argv, int *arg_ptr)
1844 struct predicate *our_pred;
1845 uintmax_t num_days;
1846 enum comparison_type c_type;
1847 time_t t;
1849 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1850 return false;
1851 if (!get_num (argv[*arg_ptr], &num_days, &c_type))
1852 return false;
1853 t = num_days * DAYSECS;
1854 our_pred = insert_primary (entry);
1855 our_pred->args.info.kind = c_type;
1856 our_pred->args.info.negative = t < 0;
1857 our_pred->args.info.l_val = t;
1858 our_pred->est_success_rate = estimate_file_age_success_rate(num_days);
1859 (*arg_ptr)++;
1860 return true;
1863 static boolean
1864 parse_user (const struct parser_table* entry, char **argv, int *arg_ptr)
1866 struct passwd *cur_pwd;
1867 struct predicate *our_pred;
1868 uid_t uid;
1869 int uid_len;
1871 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
1872 return false;
1873 cur_pwd = getpwnam (argv[*arg_ptr]);
1874 endpwent ();
1875 if (cur_pwd != NULL)
1876 uid = cur_pwd->pw_uid;
1877 else
1879 uid_len = strspn (argv[*arg_ptr], "0123456789");
1880 if ((uid_len == 0) || (argv[*arg_ptr][uid_len] != '\0'))
1881 return false;
1882 uid = atoi (argv[*arg_ptr]);
1884 our_pred = insert_primary (entry);
1885 our_pred->args.uid = uid;
1886 our_pred->est_success_rate = (our_pred->args.uid < 100) ? 0.99 : 0.2;
1887 (*arg_ptr)++;
1888 return true;
1891 static boolean
1892 parse_version (const struct parser_table* entry, char **argv, int *arg_ptr)
1894 extern char *version_string;
1895 int features = 0;
1897 (void) argv;
1898 (void) arg_ptr;
1899 (void) entry;
1901 fflush (stderr);
1902 printf (_("GNU find version %s\n"), version_string);
1903 printf (_("Features enabled: "));
1905 #if CACHE_IDS
1906 printf("CACHE_IDS ");
1907 ++features;
1908 #endif
1909 #if DEBUG
1910 printf("DEBUG ");
1911 ++features;
1912 #endif
1913 #if DEBUG_STAT
1914 printf("DEBUG_STAT ");
1915 ++features;
1916 #endif
1917 #if defined(USE_STRUCT_DIRENT_D_TYPE) && defined(HAVE_STRUCT_DIRENT_D_TYPE)
1918 printf("D_TYPE ");
1919 ++features;
1920 #endif
1921 #if defined(O_NOFOLLOW)
1922 printf("O_NOFOLLOW(%s) ",
1923 (options.open_nofollow_available ? "enabled" : "disabled"));
1924 ++features;
1925 #endif
1926 #if defined(LEAF_OPTIMISATION)
1927 printf("LEAF_OPTIMISATION ");
1928 ++features;
1929 #endif
1931 if (is_fts_enabled())
1933 printf("FTS ");
1934 ++features;
1937 printf("CBO(level=%d) ", (int)(options.optimisation_level));
1938 ++features;
1940 if (0 == features)
1942 /* For the moment, leave this as English in case someone wants
1943 to parse these strings. */
1944 printf("none");
1946 printf("\n");
1948 exit (0);
1951 static boolean
1952 parse_xdev (const struct parser_table* entry, char **argv, int *arg_ptr)
1954 (void) argv;
1955 (void) arg_ptr;
1956 (void) entry;
1957 options.stay_on_filesystem = true;
1958 return parse_noop(entry, argv, arg_ptr);
1961 static boolean
1962 parse_ignore_race (const struct parser_table* entry, char **argv, int *arg_ptr)
1964 (void) argv;
1965 (void) arg_ptr;
1966 (void) entry;
1967 options.ignore_readdir_race = true;
1968 return parse_noop(entry, argv, arg_ptr);
1971 static boolean
1972 parse_noignore_race (const struct parser_table* entry, char **argv, int *arg_ptr)
1974 (void) argv;
1975 (void) arg_ptr;
1976 (void) entry;
1977 options.ignore_readdir_race = false;
1978 return parse_noop(entry, argv, arg_ptr);
1981 static boolean
1982 parse_warn (const struct parser_table* entry, char **argv, int *arg_ptr)
1984 (void) argv;
1985 (void) arg_ptr;
1986 (void) entry;
1987 options.warnings = true;
1988 return parse_noop(entry, argv, arg_ptr);
1991 static boolean
1992 parse_xtype (const struct parser_table* entry, char **argv, int *arg_ptr)
1994 (void) argv;
1995 (void) arg_ptr;
1996 return insert_type (argv, arg_ptr, entry, pred_xtype);
1999 static boolean
2000 insert_type (char **argv, int *arg_ptr, const struct parser_table *entry, PRED_FUNC which_pred)
2002 mode_t type_cell;
2003 struct predicate *our_pred;
2004 float rate = 0.5;
2006 if ((argv == NULL) || (argv[*arg_ptr] == NULL)
2007 || (strlen (argv[*arg_ptr]) != 1))
2008 return false;
2009 switch (argv[*arg_ptr][0])
2011 case 'b': /* block special */
2012 type_cell = S_IFBLK;
2013 rate = 0.01f;
2014 break;
2015 case 'c': /* character special */
2016 type_cell = S_IFCHR;
2017 rate = 0.01f;
2018 break;
2019 case 'd': /* directory */
2020 type_cell = S_IFDIR;
2021 rate = 0.4f;
2022 break;
2023 case 'f': /* regular file */
2024 type_cell = S_IFREG;
2025 rate = 0.95f;
2026 break;
2027 #ifdef S_IFLNK
2028 case 'l': /* symbolic link */
2029 type_cell = S_IFLNK;
2030 rate = 0.1f;
2031 break;
2032 #endif
2033 #ifdef S_IFIFO
2034 case 'p': /* pipe */
2035 type_cell = S_IFIFO;
2036 rate = 0.01f;
2037 break;
2038 #endif
2039 #ifdef S_IFSOCK
2040 case 's': /* socket */
2041 type_cell = S_IFSOCK;
2042 rate = 0.01f;
2043 break;
2044 #endif
2045 #ifdef S_IFDOOR
2046 case 'D': /* Solaris door */
2047 type_cell = S_IFDOOR;
2048 rate = 0.01f;
2049 break;
2050 #endif
2051 default: /* None of the above ... nuke 'em. */
2052 return false;
2054 our_pred = insert_primary_withpred (entry, which_pred);
2055 our_pred->est_success_rate = rate;
2057 /* Figure out if we will need to stat the file, because if we don't
2058 * need to follow symlinks, we can avoid a stat call by using
2059 * struct dirent.d_type.
2061 if (which_pred == pred_xtype)
2063 our_pred->need_stat = true;
2064 our_pred->need_type = false;
2066 else
2068 our_pred->need_stat = false; /* struct dirent is enough */
2069 our_pred->need_type = true;
2071 our_pred->args.type = type_cell;
2072 (*arg_ptr)++; /* Move on to next argument. */
2073 return true;
2077 /* Return true if the file accessed via FP is a terminal.
2079 static boolean
2080 stream_is_tty(FILE *fp)
2082 int fd = fileno(fp);
2083 if (-1 == fd)
2085 return false; /* not a valid stream */
2087 else
2089 return isatty(fd) ? true : false;
2097 /* XXX: do we need to pass FUNC to this function? */
2098 static boolean
2099 insert_fprintf (FILE *fp, const struct parser_table *entry, PRED_FUNC func, char **argv, int *arg_ptr)
2101 char *format; /* Beginning of unprocessed format string. */
2102 register char *scan; /* Current address in scanning `format'. */
2103 register char *scan2; /* Address inside of element being scanned. */
2104 struct segment **segmentp; /* Address of current segment. */
2105 struct predicate *our_pred;
2107 format = argv[(*arg_ptr)++];
2109 our_pred = insert_primary_withpred (entry, func);
2110 our_pred->side_effects = our_pred->no_default_print = true;
2111 our_pred->args.printf_vec.stream = fp;
2112 our_pred->args.printf_vec.dest_is_tty = stream_is_tty(fp);
2113 our_pred->args.printf_vec.quote_opts = clone_quoting_options (NULL);
2114 our_pred->need_type = false;
2115 our_pred->need_stat = false;
2117 segmentp = &our_pred->args.printf_vec.segment;
2118 *segmentp = NULL;
2120 for (scan = format; *scan; scan++)
2122 if (*scan == '\\')
2124 scan2 = scan + 1;
2125 if (*scan2 >= '0' && *scan2 <= '7')
2127 register int n, i;
2129 for (i = n = 0; i < 3 && (*scan2 >= '0' && *scan2 <= '7');
2130 i++, scan2++)
2131 n = 8 * n + *scan2 - '0';
2132 scan2--;
2133 *scan = n;
2135 else
2137 switch (*scan2)
2139 case 'a':
2140 *scan = 7;
2141 break;
2142 case 'b':
2143 *scan = '\b';
2144 break;
2145 case 'c':
2146 make_segment (segmentp, format, scan - format, KIND_STOP,
2147 our_pred);
2148 if (our_pred->need_stat && (our_pred->p_cost < NeedsStatInfo))
2149 our_pred->p_cost = NeedsStatInfo;
2150 return true;
2151 case 'f':
2152 *scan = '\f';
2153 break;
2154 case 'n':
2155 *scan = '\n';
2156 break;
2157 case 'r':
2158 *scan = '\r';
2159 break;
2160 case 't':
2161 *scan = '\t';
2162 break;
2163 case 'v':
2164 *scan = '\v';
2165 break;
2166 case '\\':
2167 /* *scan = '\\'; * it already is */
2168 break;
2169 default:
2170 error (0, 0,
2171 _("warning: unrecognized escape `\\%c'"), *scan2);
2172 scan++;
2173 continue;
2176 segmentp = make_segment (segmentp, format, scan - format + 1,
2177 KIND_PLAIN, our_pred);
2178 format = scan2 + 1; /* Move past the escape. */
2179 scan = scan2; /* Incremented immediately by `for'. */
2181 else if (*scan == '%')
2183 if (scan[1] == '%')
2185 segmentp = make_segment (segmentp, format, scan - format + 1,
2186 KIND_PLAIN, our_pred);
2187 scan++;
2188 format = scan + 1;
2189 continue;
2191 /* Scan past flags, width and precision, to verify kind. */
2192 for (scan2 = scan; *++scan2 && strchr ("-+ #", *scan2);)
2193 /* Do nothing. */ ;
2194 while (ISDIGIT (*scan2))
2195 scan2++;
2196 if (*scan2 == '.')
2197 for (scan2++; ISDIGIT (*scan2); scan2++)
2198 /* Do nothing. */ ;
2199 if (strchr ("abcdDfFgGhHiklmMnpPstuUyY", *scan2))
2201 segmentp = make_segment (segmentp, format, scan2 - format,
2202 (int) *scan2, our_pred);
2203 scan = scan2;
2204 format = scan + 1;
2206 else if (strchr ("ACT", *scan2) && scan2[1])
2208 segmentp = make_segment (segmentp, format, scan2 - format,
2209 *scan2 | (scan2[1] << 8),
2210 our_pred);
2211 scan = scan2 + 1;
2212 format = scan + 1;
2213 continue;
2215 else
2217 /* An unrecognized % escape. Print the char after the %. */
2218 error (0, 0, _("warning: unrecognized format directive `%%%c'"),
2219 *scan2);
2220 segmentp = make_segment (segmentp, format, scan - format,
2221 KIND_PLAIN, our_pred);
2222 format = scan + 1;
2223 continue;
2228 if (scan > format)
2229 make_segment (segmentp, format, scan - format, KIND_PLAIN,
2230 our_pred);
2231 return true;
2234 /* Create a new fprintf segment in *SEGMENT, with type KIND,
2235 from the text in FORMAT, which has length LEN.
2236 Return the address of the `next' pointer of the new segment. */
2238 static struct segment **
2239 make_segment (struct segment **segment, char *format, int len, int kind,
2240 struct predicate *pred)
2242 enum EvaluationCost mycost = NeedsNothing;
2243 char *fmt;
2245 *segment = (struct segment *) xmalloc (sizeof (struct segment));
2247 (*segment)->kind = kind;
2248 (*segment)->next = NULL;
2249 (*segment)->text_len = len;
2251 fmt = (*segment)->text = xmalloc (len + sizeof "d");
2252 strncpy (fmt, format, len);
2253 fmt += len;
2255 switch (kind & 0xff)
2257 case KIND_PLAIN: /* Plain text string, no % conversion. */
2258 case KIND_STOP: /* Terminate argument, no newline. */
2259 break;
2261 case 'l': /* object of symlink */
2262 pred->need_stat = true;
2263 mycost = NeedsLinkName;
2264 *fmt++ = 's';
2265 break;
2267 case 'y': /* file type */
2268 pred->need_type = true;
2269 mycost = NeedsType;
2270 *fmt++ = 's';
2271 break;
2273 case 'a': /* atime in `ctime' format */
2274 case 'A': /* atime in user-specified strftime format */
2275 case 'c': /* ctime in `ctime' format */
2276 case 'C': /* ctime in user-specified strftime format */
2277 case 'F': /* filesystem type */
2278 case 'g': /* group name */
2279 case 'i': /* inode number */
2280 case 'M': /* mode in `ls -l' format (eg., "drwxr-xr-x") */
2281 case 's': /* size in bytes */
2282 case 't': /* mtime in `ctime' format */
2283 case 'T': /* mtime in user-specified strftime format */
2284 case 'u': /* user name */
2285 pred->need_stat = true;
2286 mycost = NeedsStatInfo;
2287 *fmt++ = 's';
2288 break;
2290 case 'Y': /* symlink pointed file type */
2291 pred->need_stat = true;
2292 mycost = NeedsType; /* true for amortised effect */
2293 *fmt++ = 's';
2294 break;
2296 case 'f': /* basename of path */
2297 case 'h': /* leading directories part of path */
2298 case 'H': /* ARGV element file was found under */
2299 case 'p': /* pathname */
2300 case 'P': /* pathname with ARGV element stripped */
2301 *fmt++ = 's';
2302 break;
2304 /* Numeric items that one might expect to honour
2305 * #, 0, + flags but which do not.
2307 case 'G': /* GID number */
2308 case 'U': /* UID number */
2309 case 'b': /* size in 512-byte blocks */
2310 case 'D': /* Filesystem device on which the file exits */
2311 case 'k': /* size in 1K blocks */
2312 case 'n': /* number of links */
2313 pred->need_stat = true;
2314 mycost = NeedsStatInfo;
2315 *fmt++ = 's';
2316 break;
2318 /* Numeric items that DO honour #, 0, + flags.
2320 case 'd': /* depth in search tree (0 = ARGV element) */
2321 *fmt++ = 'd';
2322 break;
2324 case 'm': /* mode as octal number (perms only) */
2325 *fmt++ = 'o';
2326 pred->need_stat = true;
2327 mycost = NeedsStatInfo;
2328 break;
2330 *fmt = '\0';
2332 if (mycost > pred->p_cost)
2333 pred->p_cost = mycost;
2334 return &(*segment)->next;
2337 static void
2338 check_path_safety(const char *action)
2340 const char *path = getenv("PATH");
2341 char *s;
2342 s = next_element(path, 1);
2343 while ((s = next_element ((char *) NULL, 1)) != NULL)
2345 if (0 == strcmp(s, "."))
2347 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)"),
2348 action);
2354 /* handles both exec and ok predicate */
2355 #if defined(NEW_EXEC)
2356 /* handles both exec and ok predicate */
2357 static boolean
2358 new_insert_exec_ok (const char *action,
2359 const struct parser_table *entry,
2360 char **argv,
2361 int *arg_ptr)
2363 int start, end; /* Indexes in ARGV of start & end of cmd. */
2364 int i; /* Index into cmd args */
2365 int saw_braces; /* True if previous arg was '{}'. */
2366 boolean allow_plus; /* True if + is a valid terminator */
2367 int brace_count; /* Number of instances of {}. */
2368 PRED_FUNC func = entry->pred_func;
2369 enum BC_INIT_STATUS bcstatus;
2371 struct predicate *our_pred;
2372 struct exec_val *execp; /* Pointer for efficiency. */
2374 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
2375 return false;
2377 our_pred = insert_primary_withpred (entry, func);
2378 our_pred->side_effects = our_pred->no_default_print = true;
2379 our_pred->need_type = our_pred->need_stat = false;
2381 execp = &our_pred->args.exec_vec;
2383 if ((func != pred_okdir) && (func != pred_ok))
2385 allow_plus = true;
2386 execp->close_stdin = false;
2388 else
2390 allow_plus = false;
2391 /* If find reads stdin (i.e. for -ok and similar), close stdin
2392 * in the child to prevent some script from consiming the output
2393 * intended for find.
2395 execp->close_stdin = true;
2399 if ((func == pred_execdir) || (func == pred_okdir))
2401 options.ignore_readdir_race = false;
2402 check_path_safety(action);
2403 execp->use_current_dir = true;
2405 else
2407 execp->use_current_dir = false;
2410 our_pred->args.exec_vec.multiple = 0;
2412 /* Count the number of args with path replacements, up until the ';'.
2413 * Also figure out if the command is terminated by ";" or by "+".
2415 start = *arg_ptr;
2416 for (end = start, saw_braces=0, brace_count=0;
2417 (argv[end] != NULL)
2418 && ((argv[end][0] != ';') || (argv[end][1] != '\0'));
2419 end++)
2421 /* For -exec and -execdir, "{} +" can terminate the command. */
2422 if ( allow_plus
2423 && argv[end][0] == '+' && argv[end][1] == 0
2424 && saw_braces)
2426 our_pred->args.exec_vec.multiple = 1;
2427 break;
2430 saw_braces = 0;
2431 if (strstr (argv[end], "{}"))
2433 saw_braces = 1;
2434 ++brace_count;
2436 if (0 == end && (func == pred_execdir || func == pred_okdir))
2438 /* The POSIX standard says that {} replacement should
2439 * occur even in the utility name. This is insecure
2440 * since it means we will be executing a command whose
2441 * name is chosen according to whatever find finds in
2442 * the filesystem. That can be influenced by an
2443 * attacker. Hence for -execdir and -okdir this is not
2444 * allowed. We can specify this as those options are
2445 * not defined by POSIX.
2447 error(1, 0, _("You may not use {} within the utility name for -execdir and -okdir, because this is a potential security problem."));
2452 /* Fail if no command given or no semicolon found. */
2453 if ((end == start) || (argv[end] == NULL))
2455 *arg_ptr = end;
2456 free(our_pred);
2457 return false;
2460 if (our_pred->args.exec_vec.multiple && brace_count > 1)
2463 const char *suffix;
2464 if (func == pred_execdir)
2465 suffix = "dir";
2466 else
2467 suffix = "";
2469 error(1, 0,
2470 _("Only one instance of {} is supported with -exec%s ... +"),
2471 suffix);
2474 /* We use a switch statement here so that
2475 * the compiler warns us when we forget to handle a
2476 * newly invented enum value.
2478 bcstatus = bc_init_controlinfo(&execp->ctl);
2479 switch (bcstatus)
2481 case BC_INIT_ENV_TOO_BIG:
2482 error(1, 0,
2483 _("The environment is too large for exec()."));
2484 break;
2485 case BC_INIT_OK:
2486 /* Good news. Carry on. */
2487 break;
2489 bc_use_sensible_arg_max(&execp->ctl);
2492 execp->ctl.exec_callback = launch;
2494 if (our_pred->args.exec_vec.multiple)
2496 /* "+" terminator, so we can just append our arguments after the
2497 * command and initial arguments.
2499 execp->replace_vec = NULL;
2500 execp->ctl.replace_pat = NULL;
2501 execp->ctl.rplen = 0;
2502 execp->ctl.lines_per_exec = 0; /* no limit */
2503 execp->ctl.args_per_exec = 0; /* no limit */
2505 /* remember how many arguments there are */
2506 execp->ctl.initial_argc = (end-start) - 1;
2508 /* execp->state = xmalloc(sizeof struct buildcmd_state); */
2509 bc_init_state(&execp->ctl, &execp->state, execp);
2511 /* Gather the initial arguments. Skip the {}. */
2512 for (i=start; i<end-1; ++i)
2514 bc_push_arg(&execp->ctl, &execp->state,
2515 argv[i], strlen(argv[i])+1,
2516 NULL, 0,
2520 else
2522 /* Semicolon terminator - more than one {} is supported, so we
2523 * have to do brace-replacement.
2525 execp->num_args = end - start;
2527 execp->ctl.replace_pat = "{}";
2528 execp->ctl.rplen = strlen(execp->ctl.replace_pat);
2529 execp->ctl.lines_per_exec = 0; /* no limit */
2530 execp->ctl.args_per_exec = 0; /* no limit */
2531 execp->replace_vec = xmalloc(sizeof(char*)*execp->num_args);
2534 /* execp->state = xmalloc(sizeof(*(execp->state))); */
2535 bc_init_state(&execp->ctl, &execp->state, execp);
2537 /* Remember the (pre-replacement) arguments for later. */
2538 for (i=0; i<execp->num_args; ++i)
2540 execp->replace_vec[i] = argv[i+start];
2544 if (argv[end] == NULL)
2545 *arg_ptr = end;
2546 else
2547 *arg_ptr = end + 1;
2549 return true;
2551 #else
2552 /* handles both exec and ok predicate */
2553 static boolean
2554 old_insert_exec_ok (boolean (*func) (/* ??? */), char **argv, int *arg_ptr)
2556 int start, end; /* Indexes in ARGV of start & end of cmd. */
2557 int num_paths; /* Number of args with path replacements. */
2558 int path_pos; /* Index in array of path replacements. */
2559 int vec_pos; /* Index in array of args. */
2560 struct predicate *our_pred;
2561 struct exec_val *execp; /* Pointer for efficiency. */
2563 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
2564 return false;
2566 /* Count the number of args with path replacements, up until the ';'. */
2567 start = *arg_ptr;
2568 for (end = start, num_paths = 0;
2569 (argv[end] != NULL)
2570 && ((argv[end][0] != ';') || (argv[end][1] != '\0'));
2571 end++)
2572 if (strstr (argv[end], "{}"))
2573 num_paths++;
2574 /* Fail if no command given or no semicolon found. */
2575 if ((end == start) || (argv[end] == NULL))
2577 *arg_ptr = end;
2578 return false;
2581 our_pred = insert_primary (func);
2582 our_pred->side_effects = our_pred->no_default_print = true;
2583 execp = &our_pred->args.exec_vec;
2584 execp->usercontext = our_pred;
2585 execp->use_current_dir = false;
2586 execp->paths =
2587 (struct path_arg *) xmalloc (sizeof (struct path_arg) * (num_paths + 1));
2588 execp->vec = (char **) xmalloc (sizeof (char *) * (end - start + 1));
2589 /* Record the positions of all args, and the args with path replacements. */
2590 for (end = start, path_pos = vec_pos = 0;
2591 (argv[end] != NULL)
2592 && ((argv[end][0] != ';') || (argv[end][1] != '\0'));
2593 end++)
2595 register char *p;
2597 execp->paths[path_pos].count = 0;
2598 for (p = argv[end]; *p; ++p)
2599 if (p[0] == '{' && p[1] == '}')
2601 execp->paths[path_pos].count++;
2602 ++p;
2604 if (execp->paths[path_pos].count)
2606 execp->paths[path_pos].offset = vec_pos;
2607 execp->paths[path_pos].origarg = argv[end];
2608 path_pos++;
2610 execp->vec[vec_pos++] = argv[end];
2612 execp->paths[path_pos].offset = -1;
2613 execp->vec[vec_pos] = NULL;
2615 if (argv[end] == NULL)
2616 *arg_ptr = end;
2617 else
2618 *arg_ptr = end + 1;
2619 return true;
2621 #endif
2625 static boolean
2626 insert_exec_ok (const char *action, const struct parser_table *entry, char **argv, int *arg_ptr)
2628 #if defined(NEW_EXEC)
2629 return new_insert_exec_ok(action, entry, argv, arg_ptr);
2630 #else
2631 return old_insert_exec_ok(func, argv, arg_ptr);
2632 #endif
2637 /* Get a number of days and comparison type.
2638 STR is the ASCII representation.
2639 Set *NUM_DAYS to the number of days, taken as being from
2640 the current moment (or possibly midnight). Thus the sense of the
2641 comparison type appears to be reversed.
2642 Set *COMP_TYPE to the kind of comparison that is requested.
2644 Return true if all okay, false if input error.
2646 Used by -atime, -ctime and -mtime (parsers) to
2647 get the appropriate information for a time predicate processor. */
2649 static boolean
2650 get_num_days (char *str, uintmax_t *num_days, enum comparison_type *comp_type)
2652 boolean r = get_num (str, num_days, comp_type);
2653 if (r)
2654 switch (*comp_type)
2656 case COMP_LT: *comp_type = COMP_GT; break;
2657 case COMP_GT: *comp_type = COMP_LT; break;
2658 default: break;
2660 return r;
2663 /* Insert a time predicate PRED.
2664 ARGV is a pointer to the argument array.
2665 ARG_PTR is a pointer to an index into the array, incremented if
2666 all went well.
2668 Return true if input is valid, false if not.
2670 A new predicate node is assigned, along with an argument node
2671 obtained with malloc.
2673 Used by -atime, -ctime, and -mtime parsers. */
2675 static boolean
2676 parse_time (const struct parser_table* entry, char *argv[], int *arg_ptr)
2678 struct predicate *our_pred;
2679 uintmax_t num_days;
2680 enum comparison_type c_type;
2681 time_t t;
2683 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
2684 return false;
2685 if (!get_num_days (argv[*arg_ptr], &num_days, &c_type))
2686 return false;
2688 /* Figure out the timestamp value we are looking for. */
2689 t = ( options.cur_day_start - num_days * DAYSECS
2690 + ((c_type == COMP_GT) ? DAYSECS - 1 : 0));
2692 if (1)
2694 /* We introduce a scope in which 'val' can be declared, for the
2695 * benefit of compilers that are really C89 compilers
2696 * which support intmax_t because config.h #defines it
2698 intmax_t val = ( (intmax_t)options.cur_day_start - num_days * DAYSECS
2699 + ((c_type == COMP_GT) ? DAYSECS - 1 : 0));
2700 t = val;
2702 /* Check for possibility of an overflow */
2703 if ( (intmax_t)t != val )
2705 error (1, 0, "arithmetic overflow while converting %s days to a number of seconds", argv[*arg_ptr]);
2709 our_pred = insert_primary (entry);
2710 our_pred->args.info.kind = c_type;
2711 our_pred->args.info.negative = t < 0;
2712 our_pred->args.info.l_val = t;
2713 our_pred->est_success_rate = estimate_file_age_success_rate(num_days);
2714 (*arg_ptr)++;
2716 if (options.debug_options & DebugExpressionTree)
2718 fprintf (stderr, "inserting %s\n", our_pred->p_name);
2719 fprintf (stderr, " type: %s %s ",
2720 (c_type == COMP_GT) ? "gt" :
2721 ((c_type == COMP_LT) ? "lt" : ((c_type == COMP_EQ) ? "eq" : "?")),
2722 (c_type == COMP_GT) ? " >" :
2723 ((c_type == COMP_LT) ? " <" : ((c_type == COMP_EQ) ? ">=" : " ?")));
2724 t = our_pred->args.info.l_val;
2725 fprintf (stderr, "%ju %s", (uintmax_t) our_pred->args.info.l_val, ctime (&t));
2726 if (c_type == COMP_EQ)
2728 t = our_pred->args.info.l_val += DAYSECS;
2729 fprintf (stderr, " < %ju %s",
2730 (uintmax_t) our_pred->args.info.l_val, ctime (&t));
2731 our_pred->args.info.l_val -= DAYSECS;
2735 return true;
2738 /* Get a number with comparison information.
2739 The sense of the comparison information is 'normal'; that is,
2740 '+' looks for a count > than the number and '-' less than.
2742 STR is the ASCII representation of the number.
2743 Set *NUM to the number.
2744 Set *COMP_TYPE to the kind of comparison that is requested.
2746 Return true if all okay, false if input error. */
2748 static boolean
2749 get_num (char *str, uintmax_t *num, enum comparison_type *comp_type)
2751 if (str == NULL)
2752 return false;
2753 switch (str[0])
2755 case '+':
2756 *comp_type = COMP_GT;
2757 str++;
2758 break;
2759 case '-':
2760 *comp_type = COMP_LT;
2761 str++;
2762 break;
2763 default:
2764 *comp_type = COMP_EQ;
2765 break;
2768 return xstrtoumax (str, NULL, 10, num, "") == LONGINT_OK;
2771 /* Insert a number predicate.
2772 ARGV is a pointer to the argument array.
2773 *ARG_PTR is an index into ARGV, incremented if all went well.
2774 *PRED is the predicate processor to insert.
2776 Return true if input is valid, false if error.
2778 A new predicate node is assigned, along with an argument node
2779 obtained with malloc.
2781 Used by -inum and -links parsers. */
2783 static struct predicate *
2784 insert_num (char **argv, int *arg_ptr, const struct parser_table *entry)
2786 struct predicate *our_pred;
2787 uintmax_t num;
2788 enum comparison_type c_type;
2790 if ((argv == NULL) || (argv[*arg_ptr] == NULL))
2791 return NULL;
2792 if (!get_num (argv[*arg_ptr], &num, &c_type))
2793 return NULL;
2794 our_pred = insert_primary (entry);
2795 our_pred->args.info.kind = c_type;
2796 our_pred->args.info.l_val = num;
2797 (*arg_ptr)++;
2799 if (options.debug_options & DebugExpressionTree)
2801 fprintf (stderr, "inserting %s\n", our_pred->p_name);
2802 fprintf (stderr, " type: %s %s ",
2803 (c_type == COMP_GT) ? "gt" :
2804 ((c_type == COMP_LT) ? "lt" : ((c_type == COMP_EQ) ? "eq" : "?")),
2805 (c_type == COMP_GT) ? " >" :
2806 ((c_type == COMP_LT) ? " <" : ((c_type == COMP_EQ) ? " =" : " ?")));
2807 fprintf (stderr, "%ju\n", our_pred->args.info.l_val);
2809 return our_pred;
2812 static FILE *
2813 open_output_file (char *path)
2815 FILE *f;
2817 if (!strcmp (path, "/dev/stderr"))
2818 return stderr;
2819 else if (!strcmp (path, "/dev/stdout"))
2820 return stdout;
2821 f = fopen_safer (path, "w");
2822 if (f == NULL)
2823 error (1, errno, "%s", path);
2824 return f;