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/>.
29 #include "modechange.h"
37 #include "stdio-safer.h"
38 #include "regextype.h"
39 #include "stat-time.h"
44 #include "findutils-version.h"
49 /* The presence of unistd.h is assumed by gnulib these days, so we
50 * might as well assume it too.
52 /* We need <unistd.h> for isatty(). */
58 # define _(Text) gettext (Text)
63 # define N_(String) gettext_noop (String)
65 /* See locate.c for explanation as to why not use (String) */
66 # define N_(String) String
69 #if !defined (isascii) || defined (STDC_HEADERS)
76 #define ISDIGIT(c) (isascii ((unsigned char)c) && isdigit ((unsigned char)c))
77 #define ISUPPER(c) (isascii ((unsigned char)c) && isupper ((unsigned char)c))
86 static boolean parse_accesscheck
PARAMS((const struct parser_table
* entry
, char **argv
, int *arg_ptr
));
87 static boolean parse_amin
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
88 static boolean parse_and
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
89 static boolean parse_anewer
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
90 static boolean parse_cmin
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
91 static boolean parse_cnewer
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
92 static boolean parse_comma
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
93 static boolean parse_daystart
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
94 static boolean parse_delete
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
95 static boolean parse_d
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
96 static boolean parse_depth
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
97 static boolean parse_empty
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
98 static boolean parse_exec
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
99 static boolean parse_execdir
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
100 static boolean parse_false
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
101 static boolean parse_fls
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
102 static boolean parse_fprintf
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
103 static boolean parse_follow
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
104 static boolean parse_fprint
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
105 static boolean parse_fprint0
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
106 static boolean parse_fstype
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
107 static boolean parse_gid
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
108 static boolean parse_group
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
109 static boolean parse_help
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
110 static boolean parse_ilname
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
111 static boolean parse_iname
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
112 static boolean parse_inum
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
113 static boolean parse_ipath
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
114 static boolean parse_iregex
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
115 static boolean parse_iwholename
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
116 static boolean parse_links
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
117 static boolean parse_lname
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
118 static boolean parse_ls
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
119 static boolean parse_maxdepth
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
120 static boolean parse_mindepth
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
121 static boolean parse_mmin
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
122 static boolean parse_name
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
123 static boolean parse_negate
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
124 static boolean parse_newer
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
125 static boolean parse_newerXY
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
126 static boolean parse_noleaf
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
127 static boolean parse_nogroup
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
128 static boolean parse_nouser
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
129 static boolean parse_nowarn
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
130 static boolean parse_ok
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
131 static boolean parse_okdir
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
132 static boolean parse_or
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
133 static boolean parse_path
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
134 static boolean parse_perm
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
135 static boolean parse_print0
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
136 static boolean parse_printf
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
137 static boolean parse_prune
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
138 static boolean parse_regex
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
139 static boolean parse_regextype
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
140 static boolean parse_samefile
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
142 static boolean parse_show_control_chars
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
144 static boolean parse_size
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
145 static boolean parse_time
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
146 static boolean parse_true
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
147 static boolean parse_type
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
148 static boolean parse_uid
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
149 static boolean parse_used
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
150 static boolean parse_user
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
151 static boolean parse_version
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
152 static boolean parse_wholename
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
153 static boolean parse_xdev
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
154 static boolean parse_ignore_race
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
155 static boolean parse_noignore_race
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
156 static boolean parse_warn
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
157 static boolean parse_xtype
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
158 static boolean parse_quit
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
160 boolean parse_print
PARAMS((const struct parser_table
*, char *argv
[], int *arg_ptr
));
163 static boolean insert_type
PARAMS((char **argv
, int *arg_ptr
, const struct parser_table
*entry
, PRED_FUNC which_pred
));
164 static boolean insert_regex
PARAMS((char *argv
[], int *arg_ptr
, const struct parser_table
*entry
, int regex_options
));
165 static boolean
insert_fprintf (struct format_val
*vec
,
166 const struct parser_table
*entry
,
170 static struct segment
**make_segment
PARAMS((struct segment
**segment
, char *format
, int len
,
171 int kind
, char format_char
, char aux_format_char
,
172 struct predicate
*pred
));
173 static boolean insert_exec_ok
PARAMS((const char *action
, const struct parser_table
*entry
, int dirfd
, char *argv
[], int *arg_ptr
));
174 static boolean get_comp_type
PARAMS((const char **str
, enum comparison_type
*comp_type
));
175 static boolean get_relative_timestamp
PARAMS((const char *str
, struct time_val
*tval
, time_t origin
, double sec_per_unit
, const char *overflowmessage
));
176 static boolean get_num
PARAMS((const char *str
, uintmax_t *num
, enum comparison_type
*comp_type
));
177 static struct predicate
* insert_num
PARAMS((char *argv
[], int *arg_ptr
, const struct parser_table
*entry
));
178 static void open_output_file (const char *path
, struct format_val
*p
);
179 static void open_stdout (struct format_val
*p
);
180 static boolean
stream_is_tty(FILE *fp
);
181 static boolean parse_noop
PARAMS((const struct parser_table
* entry
, char **argv
, int *arg_ptr
));
183 #define PASTE(x,y) x##y
184 #define STRINGIFY(s) #s
186 #define PARSE_OPTION(what,suffix) \
187 { (ARG_OPTION), (what), PASTE(parse_,suffix), NULL }
189 #define PARSE_POSOPT(what,suffix) \
190 { (ARG_POSITIONAL_OPTION), (what), PASTE(parse_,suffix), NULL }
192 #define PARSE_TEST(what,suffix) \
193 { (ARG_TEST), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) }
195 #define PARSE_TEST_NP(what,suffix) \
196 { (ARG_TEST), (what), PASTE(parse_,suffix), NULL }
198 #define PARSE_ACTION(what,suffix) \
199 { (ARG_ACTION), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) }
201 #define PARSE_ACTION_NP(what,suffix) \
202 { (ARG_ACTION), (what), PASTE(parse_,suffix), NULL }
204 #define PARSE_PUNCTUATION(what,suffix) \
205 { (ARG_PUNCTUATION), (what), PASTE(parse_,suffix), PASTE(pred_,suffix) }
208 /* Predicates we cannot handle in the usual way. If you add an entry
209 * to this table, double-check the switch statement in
210 * pred_sanity_check() to make sure that the new case is being
213 static struct parser_table
const parse_entry_newerXY
=
215 ARG_SPECIAL_PARSE
, "newerXY", parse_newerXY
, pred_newerXY
/* BSD */
218 /* GNU find predicates that are not mentioned in POSIX.2 are marked `GNU'.
219 If they are in some Unix versions of find, they are marked `Unix'. */
221 static struct parser_table
const parse_table
[] =
223 PARSE_PUNCTUATION("!", negate
),
224 PARSE_PUNCTUATION("not", negate
), /* GNU */
225 PARSE_PUNCTUATION("(", openparen
),
226 PARSE_PUNCTUATION(")", closeparen
),
227 PARSE_PUNCTUATION(",", comma
), /* GNU */
228 PARSE_PUNCTUATION("a", and),
229 PARSE_TEST ("amin", amin
), /* GNU */
230 PARSE_PUNCTUATION("and", and), /* GNU */
231 PARSE_TEST ("anewer", anewer
), /* GNU */
232 {ARG_TEST
, "atime", parse_time
, pred_atime
},
233 PARSE_TEST ("cmin", cmin
), /* GNU */
234 PARSE_TEST ("cnewer", cnewer
), /* GNU */
235 {ARG_TEST
, "ctime", parse_time
, pred_ctime
},
236 PARSE_POSOPT ("daystart", daystart
), /* GNU */
237 PARSE_ACTION ("delete", delete), /* GNU, Mac OS, FreeBSD */
238 PARSE_OPTION ("d", d
), /* Mac OS X, FreeBSD, NetBSD, OpenBSD, but deprecated in favour of -depth */
239 PARSE_OPTION ("depth", depth
),
240 PARSE_TEST ("empty", empty
), /* GNU */
241 {ARG_ACTION
, "exec", parse_exec
, pred_exec
}, /* POSIX */
242 {ARG_TEST
, "executable", parse_accesscheck
, pred_executable
}, /* GNU, 4.3.0+ */
243 PARSE_ACTION ("execdir", execdir
), /* *BSD, GNU */
244 PARSE_ACTION ("fls", fls
), /* GNU */
245 PARSE_POSOPT ("follow", follow
), /* GNU, Unix */
246 PARSE_ACTION ("fprint", fprint
), /* GNU */
247 PARSE_ACTION ("fprint0", fprint0
), /* GNU */
248 {ARG_ACTION
, "fprintf", parse_fprintf
, pred_fprintf
}, /* GNU */
249 PARSE_TEST ("fstype", fstype
), /* GNU, Unix */
250 PARSE_TEST ("gid", gid
), /* GNU */
251 PARSE_TEST ("group", group
),
252 PARSE_OPTION ("ignore_readdir_race", ignore_race
), /* GNU */
253 PARSE_TEST ("ilname", ilname
), /* GNU */
254 PARSE_TEST ("iname", iname
), /* GNU */
255 PARSE_TEST ("inum", inum
), /* GNU, Unix */
256 PARSE_TEST ("ipath", ipath
), /* GNU, deprecated in favour of iwholename */
257 PARSE_TEST_NP ("iregex", iregex
), /* GNU */
258 PARSE_TEST_NP ("iwholename", iwholename
), /* GNU */
259 PARSE_TEST ("links", links
),
260 PARSE_TEST ("lname", lname
), /* GNU */
261 PARSE_ACTION ("ls", ls
), /* GNU, Unix */
262 PARSE_OPTION ("maxdepth", maxdepth
), /* GNU */
263 PARSE_OPTION ("mindepth", mindepth
), /* GNU */
264 PARSE_TEST ("mmin", mmin
), /* GNU */
265 PARSE_OPTION ("mount", xdev
), /* Unix */
266 {ARG_TEST
, "mtime", parse_time
, pred_mtime
},
267 PARSE_TEST ("name", name
),
268 #ifdef UNIMPLEMENTED_UNIX
269 PARSE(ARG_UNIMPLEMENTED
, "ncpio", ncpio
), /* Unix */
271 PARSE_TEST ("newer", newer
),
272 {ARG_TEST
, "atime", parse_time
, pred_atime
},
273 PARSE_OPTION ("noleaf", noleaf
), /* GNU */
274 PARSE_TEST ("nogroup", nogroup
),
275 PARSE_TEST ("nouser", nouser
),
276 PARSE_OPTION ("noignore_readdir_race", noignore_race
), /* GNU */
277 PARSE_POSOPT ("nowarn", nowarn
), /* GNU */
278 PARSE_PUNCTUATION("o", or),
279 PARSE_PUNCTUATION("or", or), /* GNU */
280 PARSE_ACTION ("ok", ok
),
281 PARSE_ACTION ("okdir", okdir
), /* GNU (-execdir is BSD) */
282 PARSE_TEST ("path", path
), /* GNU, HP-UX, GNU prefers wholename */
283 PARSE_TEST ("perm", perm
),
284 PARSE_ACTION ("print", print
),
285 PARSE_ACTION ("print0", print0
), /* GNU */
286 {ARG_ACTION
, "printf", parse_printf
, NULL
}, /* GNU */
287 PARSE_ACTION ("prune", prune
),
288 PARSE_ACTION ("quit", quit
), /* GNU */
289 {ARG_TEST
, "readable", parse_accesscheck
, pred_readable
}, /* GNU, 4.3.0+ */
290 PARSE_TEST ("regex", regex
), /* GNU */
291 PARSE_OPTION ("regextype", regextype
), /* GNU */
292 PARSE_TEST ("samefile", samefile
), /* GNU */
294 PARSE_OPTION ("show-control-chars", show_control_chars
), /* GNU, 4.3.0+ */
296 PARSE_TEST ("size", size
),
297 PARSE_TEST ("type", type
),
298 PARSE_TEST ("uid", uid
), /* GNU */
299 PARSE_TEST ("used", used
), /* GNU */
300 PARSE_TEST ("user", user
),
301 PARSE_OPTION ("warn", warn
), /* GNU */
302 PARSE_TEST_NP ("wholename", wholename
), /* GNU, replaces -path */
303 {ARG_TEST
, "writable", parse_accesscheck
, pred_writable
}, /* GNU, 4.3.0+ */
304 PARSE_OPTION ("xdev", xdev
),
305 PARSE_TEST ("xtype", xtype
), /* GNU */
306 #ifdef UNIMPLEMENTED_UNIX
307 /* It's pretty ugly for find to know about archive formats.
308 Plus what it could do with cpio archives is very limited.
309 Better to leave it out. */
310 PARSE(ARG_UNIMPLEMENTED
, "cpio", cpio
), /* Unix */
312 /* gnulib's stdbool.h might have made true and false into macros,
313 * so we can't leave named 'true' and 'false' tokens, so we have
314 * to expeant the relevant entries longhand.
316 {ARG_TEST
, "false", parse_false
, pred_false
}, /* GNU */
317 {ARG_TEST
, "true", parse_true
, pred_true
}, /* GNU */
318 {ARG_NOOP
, "noop", NULL
, pred_true
}, /* GNU, internal use only */
320 /* Various other cases that don't fit neatly into our macro scheme. */
321 {ARG_TEST
, "help", parse_help
, NULL
}, /* GNU */
322 {ARG_TEST
, "-help", parse_help
, NULL
}, /* GNU */
323 {ARG_TEST
, "version", parse_version
, NULL
}, /* GNU */
324 {ARG_TEST
, "-version", parse_version
, NULL
}, /* GNU */
329 static const char *first_nonoption_arg
= NULL
;
330 static const struct parser_table
*noop
= NULL
;
333 static const struct parser_table
*
339 for (i
= 0; parse_table
[i
].parser_name
!= 0; i
++)
341 if (ARG_NOOP
==parse_table
[i
].type
)
343 noop
= &(parse_table
[i
]);
352 get_stat_Ytime(const struct stat
*p
,
354 struct timespec
*ret
)
359 *ret
= get_stat_atime(p
);
362 *ret
= get_stat_birthtime(p
);
363 return (ret
->tv_nsec
>= 0);
365 *ret
= get_stat_ctime(p
);
368 *ret
= get_stat_mtime(p
);
377 set_follow_state(enum SymlinkOption opt
)
379 if (options
.debug_options
& DebugStat
)
381 /* For DebugStat, the choice is made at runtime within debug_stat()
382 * by checking the contents of the symlink_handling variable.
384 options
.xstat
= debug_stat
;
390 case SYMLINK_ALWAYS_DEREF
: /* -L */
391 options
.xstat
= optionl_stat
;
392 options
.no_leaf_check
= true;
395 case SYMLINK_NEVER_DEREF
: /* -P (default) */
396 options
.xstat
= optionp_stat
;
397 /* Can't turn no_leaf_check off because the user might have specified
402 case SYMLINK_DEREF_ARGSONLY
: /* -H */
403 options
.xstat
= optionh_stat
;
404 options
.no_leaf_check
= true;
407 options
.symlink_handling
= opt
;
412 parse_begin_user_args (char **args
, int argno
, const struct predicate
*last
, const struct predicate
*predicates
)
418 first_nonoption_arg
= NULL
;
422 parse_end_user_args (char **args
, int argno
, const struct predicate
*last
, const struct predicate
*predicates
)
432 /* Check that it is legal to fid the given primary in its
433 * position and return it.
435 const struct parser_table
*
436 found_parser(const char *original_arg
, const struct parser_table
*entry
)
438 /* If this is an option, but we have already had a
439 * non-option argument, the user may be under the
440 * impression that the behaviour of the option
441 * argument is conditional on some preceding
442 * tests. This might typically be the case with,
443 * for example, -maxdepth.
445 * The options -daystart and -follow are exempt
446 * from this treatment, since their positioning
447 * in the command line does have an effect on
448 * subsequent tests but not previous ones. That
449 * might be intentional on the part of the user.
451 if (entry
->type
!= ARG_POSITIONAL_OPTION
)
453 /* Something other than -follow/-daystart.
454 * If this is an option, check if it followed
455 * a non-option and if so, issue a warning.
457 if (entry
->type
== ARG_OPTION
)
459 if ((first_nonoption_arg
!= NULL
)
460 && options
.warnings
)
462 /* option which follows a non-option */
464 _("warning: you have specified the %s "
465 "option after a non-option argument %s, "
466 "but options are not positional (%s affects "
467 "tests specified before it as well as those "
468 "specified after it). Please specify options "
469 "before other arguments.\n"),
477 /* Not an option or a positional option,
478 * so remember we've seen it in order to
479 * use it in a possible future warning message.
481 if (first_nonoption_arg
== NULL
)
483 first_nonoption_arg
= original_arg
;
492 /* Return a pointer to the parser function to invoke for predicate
494 Return NULL if SEARCH_NAME is not a valid predicate name. */
496 const struct parser_table
*
497 find_parser (char *search_name
)
500 const char *original_arg
= search_name
;
502 /* Ugh. Special case -newerXY. */
503 if (0 == strncmp("-newer", search_name
, 6)
504 && (8 == strlen(search_name
)))
506 return found_parser(original_arg
, &parse_entry_newerXY
);
509 if (*search_name
== '-')
512 for (i
= 0; parse_table
[i
].parser_name
!= 0; i
++)
514 if (strcmp (parse_table
[i
].parser_name
, search_name
) == 0)
516 return found_parser(original_arg
, &parse_table
[i
]);
523 estimate_file_age_success_rate(float num_days
)
527 /* Assume 1% of files have timestamps in the future */
530 else if (num_days
< 1)
532 /* Assume 30% of files have timestamps today */
535 else if (num_days
> 100)
537 /* Assume 30% of files are very old */
542 /* Assume 39% of files are between 1 and 100 days old. */
548 estimate_timestamp_success_rate(time_t when
)
550 int num_days
= (options
.cur_day_start
- when
) / 86400;
551 return estimate_file_age_success_rate(num_days
);
554 /* Collect an argument from the argument list, or
558 collect_arg(char **argv
, int *arg_ptr
, const char **collected_arg
)
560 if ((argv
== NULL
) || (argv
[*arg_ptr
] == NULL
))
562 *collected_arg
= NULL
;
567 *collected_arg
= argv
[*arg_ptr
];
574 collect_arg_stat_info(char **argv
, int *arg_ptr
, struct stat
*p
)
576 const char *filename
;
577 if (collect_arg(argv
, arg_ptr
, &filename
))
579 if (0 == (options
.xstat
)(filename
, p
))
585 fatal_file_error(filename
);
594 /* The parsers are responsible to continue scanning ARGV for
595 their arguments. Each parser knows what is and isn't
598 ARGV is the argument array.
599 *ARG_PTR is the index to start at in ARGV,
600 updated to point beyond the last element consumed.
602 The predicate structure is updated with the new information. */
606 parse_and (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
608 struct predicate
*our_pred
;
613 our_pred
= get_new_pred (entry
);
614 our_pred
->pred_func
= pred_and
;
615 our_pred
->p_type
= BI_OP
;
616 our_pred
->p_prec
= AND_PREC
;
617 our_pred
->need_stat
= our_pred
->need_type
= false;
622 parse_anewer (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
624 struct stat stat_newer
;
626 set_stat_placeholders(&stat_newer
);
627 if (collect_arg_stat_info(argv
, arg_ptr
, &stat_newer
))
629 struct predicate
*our_pred
= insert_primary (entry
);
630 our_pred
->args
.reftime
.xval
= XVAL_ATIME
;
631 our_pred
->args
.reftime
.ts
= get_stat_mtime(&stat_newer
);
632 our_pred
->args
.reftime
.kind
= COMP_GT
;
633 our_pred
->est_success_rate
= estimate_timestamp_success_rate(stat_newer
.st_mtime
);
640 parse_closeparen (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
642 struct predicate
*our_pred
;
647 our_pred
= get_new_pred (entry
);
648 our_pred
->pred_func
= pred_closeparen
;
649 our_pred
->p_type
= CLOSE_PAREN
;
650 our_pred
->p_prec
= NO_PREC
;
651 our_pred
->need_stat
= our_pred
->need_type
= false;
656 parse_cnewer (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
658 struct stat stat_newer
;
660 set_stat_placeholders(&stat_newer
);
661 if (collect_arg_stat_info(argv
, arg_ptr
, &stat_newer
))
663 struct predicate
*our_pred
= insert_primary (entry
);
664 our_pred
->args
.reftime
.xval
= XVAL_CTIME
; /* like -newercm */
665 our_pred
->args
.reftime
.ts
= get_stat_mtime(&stat_newer
);
666 our_pred
->args
.reftime
.kind
= COMP_GT
;
667 our_pred
->est_success_rate
= estimate_timestamp_success_rate(stat_newer
.st_mtime
);
674 parse_comma (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
676 struct predicate
*our_pred
;
681 our_pred
= get_new_pred (entry
);
682 our_pred
->pred_func
= pred_comma
;
683 our_pred
->p_type
= BI_OP
;
684 our_pred
->p_prec
= COMMA_PREC
;
685 our_pred
->need_stat
= our_pred
->need_type
= false;
686 our_pred
->est_success_rate
= 1.0f
;
691 parse_daystart (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
699 if (options
.full_days
== false)
701 options
.cur_day_start
+= DAYSECS
;
702 local
= localtime (&options
.cur_day_start
);
703 options
.cur_day_start
-= (local
704 ? (local
->tm_sec
+ local
->tm_min
* 60
705 + local
->tm_hour
* 3600)
706 : options
.cur_day_start
% DAYSECS
);
707 options
.full_days
= true;
713 parse_delete (const struct parser_table
* entry
, char *argv
[], int *arg_ptr
)
715 struct predicate
*our_pred
;
719 our_pred
= insert_primary (entry
);
720 our_pred
->side_effects
= our_pred
->no_default_print
= true;
721 /* -delete implies -depth */
722 options
.do_dir_first
= false;
724 /* We do not need stat information because we check for the case
725 * (errno==EISDIR) in pred_delete.
727 our_pred
->need_stat
= our_pred
->need_type
= false;
729 our_pred
->est_success_rate
= 1.0f
;
734 parse_depth (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
739 options
.do_dir_first
= false;
740 return parse_noop(entry
, argv
, arg_ptr
);
744 parse_d (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
746 if (options
.warnings
)
749 _("warning: the -d option is deprecated; please use -depth instead, because the latter is a POSIX-compliant feature."));
751 return parse_depth(entry
, argv
, arg_ptr
);
755 parse_empty (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
757 struct predicate
*our_pred
;
761 our_pred
= insert_primary (entry
);
762 our_pred
->est_success_rate
= 0.01f
; /* assume 1% of files are empty. */
767 parse_exec (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
769 return insert_exec_ok ("-exec", entry
, get_start_dirfd(), argv
, arg_ptr
);
773 parse_execdir (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
775 return insert_exec_ok ("-execdir", entry
, -1, argv
, arg_ptr
);
779 parse_false (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
781 struct predicate
*our_pred
;
786 our_pred
= insert_primary (entry
);
787 our_pred
->need_stat
= our_pred
->need_type
= false;
788 our_pred
->side_effects
= our_pred
->no_default_print
= false;
789 our_pred
->est_success_rate
= 0.0f
;
794 insert_fls (const struct parser_table
* entry
, const char *filename
)
796 struct predicate
*our_pred
= insert_primary (entry
);
798 open_output_file (filename
, &our_pred
->args
.printf_vec
);
800 open_stdout (&our_pred
->args
.printf_vec
);
801 our_pred
->side_effects
= our_pred
->no_default_print
= true;
802 our_pred
->est_success_rate
= 1.0f
;
808 parse_fls (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
810 const char *filename
;
811 return collect_arg(argv
, arg_ptr
, &filename
)
812 && insert_fls(entry
, filename
);
816 parse_follow (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
818 set_follow_state(SYMLINK_ALWAYS_DEREF
);
819 return parse_noop(entry
, argv
, arg_ptr
);
823 parse_fprint (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
825 struct predicate
*our_pred
;
826 const char *filename
;
827 if (collect_arg(argv
, arg_ptr
, &filename
))
829 our_pred
= insert_primary (entry
);
830 open_output_file (filename
, &our_pred
->args
.printf_vec
);
831 our_pred
->side_effects
= our_pred
->no_default_print
= true;
832 our_pred
->need_stat
= our_pred
->need_type
= false;
833 our_pred
->est_success_rate
= 1.0f
;
843 insert_fprint(const struct parser_table
* entry
, const char *filename
)
845 struct predicate
*our_pred
= insert_primary (entry
);
847 open_output_file (filename
, &our_pred
->args
.printf_vec
);
849 open_stdout (&our_pred
->args
.printf_vec
);
850 our_pred
->side_effects
= our_pred
->no_default_print
= true;
851 our_pred
->need_stat
= our_pred
->need_type
= false;
852 our_pred
->est_success_rate
= 1.0f
;
858 parse_fprint0 (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
860 const char *filename
;
861 if (collect_arg(argv
, arg_ptr
, &filename
))
862 return insert_fprint(entry
, filename
);
867 static float estimate_fstype_success_rate(const char *fsname
)
869 struct stat dir_stat
;
870 const char *dir
= "/";
871 if (0 == stat(dir
, &dir_stat
))
873 const char *fstype
= filesystem_type(&dir_stat
, dir
);
874 /* Assume most files are on the same file system type as the root fs. */
875 if (0 == strcmp(fsname
, fstype
))
885 parse_fstype (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
887 const char *typename
;
888 if (collect_arg(argv
, arg_ptr
, &typename
))
890 struct predicate
*our_pred
= insert_primary (entry
);
891 our_pred
->args
.str
= typename
;
893 /* This is an expensive operation, so although there are
894 * circumstances where it is selective, we ignore this fact
895 * because we probably don't want to promote this test to the
898 our_pred
->est_success_rate
= estimate_fstype_success_rate(typename
);
908 parse_gid (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
910 struct predicate
*p
= insert_num (argv
, arg_ptr
, entry
);
913 p
->est_success_rate
= (p
->args
.numinfo
.l_val
< 100) ? 0.99 : 0.2;
924 safe_atoi (const char *s
)
930 lval
= strtol(s
, &end
, 10);
931 if ( (LONG_MAX
== lval
) || (LONG_MIN
== lval
) )
933 /* max/min possible value, or an error. */
936 /* too big, or too small. */
937 error(1, errno
, "%s", s
);
941 /* not a valid number */
942 error(1, errno
, "%s", s
);
944 /* Otherwise, we do a range chack against INT_MAX and INT_MIN
949 if (lval
> INT_MAX
|| lval
< INT_MIN
)
951 /* The number was in range for long, but not int. */
953 error(1, errno
, "%s", s
);
957 error(1, errno
, "Unexpected suffix %s on %s",
958 quotearg_n_style(0, options
.err_quoting_style
, end
),
959 quotearg_n_style(1, options
.err_quoting_style
, s
));
963 error(1, errno
, "Expected an integer: %s",
964 quotearg_n_style(0, options
.err_quoting_style
, s
));
971 parse_group (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
973 const char *groupname
;
975 if (collect_arg(argv
, arg_ptr
, &groupname
))
978 struct predicate
*our_pred
;
979 struct group
*cur_gr
= getgrnam(groupname
);
983 gid
= cur_gr
->gr_gid
;
987 const int gid_len
= strspn (groupname
, "0123456789");
990 if (groupname
[gid_len
] == 0)
992 gid
= safe_atoi (groupname
);
996 /* XXX: no test in test suite for this */
997 error(1, 0, _("%s is not the name of an existing group and"
998 " it does not look like a numeric group ID "
999 "because it has the unexpected suffix %s"),
1000 quotearg_n_style(0, options
.err_quoting_style
, groupname
),
1001 quotearg_n_style(1, options
.err_quoting_style
, groupname
+gid_len
));
1009 /* XXX: no test in test suite for this */
1010 error(1, 0, _("%s is not the name of an existing group"),
1011 quotearg_n_style(0, options
.err_quoting_style
, groupname
));
1015 error(1, 0, _("argument to -group is empty, but should be a group name"));
1020 our_pred
= insert_primary (entry
);
1021 our_pred
->args
.gid
= gid
;
1022 our_pred
->est_success_rate
= (our_pred
->args
.numinfo
.l_val
< 100) ? 0.99 : 0.2;
1029 parse_help (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1035 usage(stdout
, 0, NULL
);
1037 default path is the current directory; default expression is -print\n\
1038 expression may consist of: operators, options, tests, and actions:\n"));
1040 operators (decreasing precedence; -and is implicit where no others are given):\n\
1041 ( EXPR ) ! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2\n\
1042 EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2\n"));
1044 positional options (always true): -daystart -follow -regextype\n\n\
1045 normal options (always true, specified before other expressions):\n\
1046 -depth --help -maxdepth LEVELS -mindepth LEVELS -mount -noleaf\n\
1047 --version -xdev -ignore_readdir_race -noignore_readdir_race\n"));
1049 tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N\n\
1050 -cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME\n\
1051 -ilname PATTERN -iname PATTERN -inum N -iwholename PATTERN -iregex PATTERN\n\
1052 -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE"));
1054 -nouser -nogroup -path PATTERN -perm [+-]MODE -regex PATTERN\n\
1055 -readable -writable -executable\n\
1056 -wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N\n\
1057 -used N -user NAME -xtype [bcdpfls]\n"));
1059 actions: -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print \n\
1060 -fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit\n\
1061 -exec COMMAND ; -exec COMMAND {} + -ok COMMAND ;\n\
1062 -execdir COMMAND ; -execdir COMMAND {} + -okdir COMMAND ;\n\
1064 puts (_("Report (and track progress on fixing) bugs via the findutils bug-reporting\n\
1065 page at http://savannah.gnu.org/ or, if you have no web access, by sending\n\
1066 email to <bug-findutils@gnu.org>."));
1071 estimate_pattern_match_rate(const char *pattern
, int is_regex
)
1073 if (strpbrk(pattern
, "*?[") || (is_regex
&& strpbrk(pattern
, ".")))
1075 /* A wildcard; assume the pattern matches most files. */
1085 parse_ilname (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1088 if (collect_arg(argv
, arg_ptr
, &name
))
1090 struct predicate
*our_pred
= insert_primary (entry
);
1091 our_pred
->args
.str
= name
;
1092 /* Use the generic glob pattern estimator to figure out how many
1093 * links will match, but bear in mind that most files won't be links.
1095 our_pred
->est_success_rate
= 0.1 * estimate_pattern_match_rate(name
, 0);
1105 /* sanity check the fnmatch() function to make sure that case folding
1106 * is supported (as opposed to just having the flag ignored).
1109 fnmatch_sanitycheck(void)
1111 static boolean checked
= false;
1114 if (0 != fnmatch("foo", "foo", 0)
1115 || 0 == fnmatch("Foo", "foo", 0)
1116 || 0 != fnmatch("Foo", "foo", FNM_CASEFOLD
))
1118 error (1, 0, _("sanity check of the fnmatch() library function failed."));
1128 check_name_arg(const char *pred
, const char *arg
)
1130 if (strchr(arg
, '/'))
1132 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'."),
1134 safely_quote_err_filename(0, arg
),
1135 safely_quote_err_filename(1, arg
));
1137 return true; /* allow it anyway */
1143 parse_iname (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1146 fnmatch_sanitycheck();
1147 if (collect_arg(argv
, arg_ptr
, &name
))
1149 if (check_name_arg("-iname", name
))
1151 struct predicate
*our_pred
= insert_primary (entry
);
1152 our_pred
->need_stat
= our_pred
->need_type
= false;
1153 our_pred
->args
.str
= name
;
1154 our_pred
->est_success_rate
= estimate_pattern_match_rate(name
, 0);
1162 parse_inum (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1164 struct predicate
*p
= insert_num (argv
, arg_ptr
, entry
);
1167 /* inode number is exact match only, so very low proportions of
1170 p
->est_success_rate
= 1e-6;
1179 /* -ipath is deprecated (at RMS's request) in favour of
1180 * -iwholename. See the node "GNU Manuals" in standards.texi
1181 * for the rationale for this (basically, GNU prefers the use
1182 * of the phrase "file name" to "path name"
1185 parse_ipath (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1188 _("warning: the predicate -ipath is deprecated; please use -iwholename instead."));
1190 return parse_iwholename(entry
, argv
, arg_ptr
);
1194 parse_iwholename (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1198 fnmatch_sanitycheck();
1199 if (collect_arg(argv
, arg_ptr
, &name
))
1201 struct predicate
*our_pred
= insert_primary_withpred (entry
, pred_ipath
);
1202 our_pred
->need_stat
= our_pred
->need_type
= false;
1203 our_pred
->args
.str
= name
;
1204 our_pred
->est_success_rate
= estimate_pattern_match_rate(name
, 0);
1211 parse_iregex (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1213 return insert_regex (argv
, arg_ptr
, entry
, RE_ICASE
|options
.regex_options
);
1217 parse_links (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1219 struct predicate
*p
= insert_num (argv
, arg_ptr
, entry
);
1222 if (p
->args
.numinfo
.l_val
== 1)
1223 p
->est_success_rate
= 0.99;
1224 else if (p
->args
.numinfo
.l_val
== 2)
1225 p
->est_success_rate
= 0.01;
1227 p
->est_success_rate
= 1e-3;
1237 parse_lname (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1240 fnmatch_sanitycheck();
1241 if (collect_arg(argv
, arg_ptr
, &name
))
1243 struct predicate
*our_pred
= insert_primary (entry
);
1244 our_pred
->args
.str
= name
;
1245 our_pred
->est_success_rate
= 0.1 * estimate_pattern_match_rate(name
, 0);
1252 parse_ls (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1256 return insert_fls(entry
, NULL
);
1260 insert_depthspec(const struct parser_table
* entry
, char **argv
, int *arg_ptr
,
1263 const char *depthstr
;
1265 const char *predicate
= argv
[(*arg_ptr
)-1];
1266 if (collect_arg(argv
, arg_ptr
, &depthstr
))
1268 depth_len
= strspn (depthstr
, "0123456789");
1269 if ((depth_len
> 0) && (depthstr
[depth_len
] == 0))
1271 (*limitptr
) = safe_atoi (depthstr
);
1274 return parse_noop(entry
, argv
, arg_ptr
);
1277 error(1, 0, _("Expected a positive decimal integer argument to %s, but got %s"),
1279 quotearg_n_style(0, options
.err_quoting_style
, depthstr
));
1282 /* missing argument */
1288 parse_maxdepth (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1290 return insert_depthspec(entry
, argv
, arg_ptr
, &options
.maxdepth
);
1294 parse_mindepth (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1296 return insert_depthspec(entry
, argv
, arg_ptr
, &options
.mindepth
);
1301 do_parse_xmin (const struct parser_table
* entry
, char **argv
, int *arg_ptr
, enum xval xv
)
1303 const char *minutes
;
1305 if (collect_arg(argv
, arg_ptr
, &minutes
))
1307 struct time_val tval
;
1309 if (get_relative_timestamp(minutes
, &tval
,
1310 options
.cur_day_start
+ DAYSECS
, 60,
1311 "arithmetic overflow while converting %s "
1312 "minutes to a number of seconds"))
1314 struct predicate
*our_pred
= insert_primary (entry
);
1315 our_pred
->args
.reftime
= tval
;
1316 our_pred
->est_success_rate
= estimate_timestamp_success_rate(tval
.ts
.tv_sec
);
1323 parse_amin (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1325 return do_parse_xmin(entry
, argv
, arg_ptr
, XVAL_ATIME
);
1329 parse_cmin (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1331 return do_parse_xmin(entry
, argv
, arg_ptr
, XVAL_CTIME
);
1336 parse_mmin (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1338 return do_parse_xmin(entry
, argv
, arg_ptr
, XVAL_MTIME
);
1342 parse_name (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1345 if (collect_arg(argv
, arg_ptr
, &name
))
1347 fnmatch_sanitycheck();
1348 if (check_name_arg("-name", name
))
1350 struct predicate
*our_pred
= insert_primary (entry
);
1351 our_pred
->need_stat
= our_pred
->need_type
= false;
1352 our_pred
->args
.str
= name
;
1353 our_pred
->est_success_rate
= estimate_pattern_match_rate(name
, 0);
1361 parse_negate (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1363 struct predicate
*our_pred
;
1368 our_pred
= get_new_pred_chk_op (entry
);
1369 our_pred
->pred_func
= pred_negate
;
1370 our_pred
->p_type
= UNI_OP
;
1371 our_pred
->p_prec
= NEGATE_PREC
;
1372 our_pred
->need_stat
= our_pred
->need_type
= false;
1377 parse_newer (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1379 struct predicate
*our_pred
;
1380 struct stat stat_newer
;
1382 set_stat_placeholders(&stat_newer
);
1383 if (collect_arg_stat_info(argv
, arg_ptr
, &stat_newer
))
1385 our_pred
= insert_primary (entry
);
1386 our_pred
->args
.reftime
.ts
= get_stat_mtime(&stat_newer
);
1387 our_pred
->args
.reftime
.xval
= XVAL_MTIME
;
1388 our_pred
->args
.reftime
.kind
= COMP_GT
;
1389 our_pred
->est_success_rate
= estimate_timestamp_success_rate(stat_newer
.st_mtime
);
1397 parse_newerXY (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1402 if ((argv
== NULL
) || (argv
[*arg_ptr
] == NULL
))
1406 else if (8u != strlen(argv
[*arg_ptr
]))
1413 const char validchars
[] = "aBcmt";
1415 assert (0 == strncmp("-newer", argv
[*arg_ptr
], 6));
1416 x
= argv
[*arg_ptr
][6];
1417 y
= argv
[*arg_ptr
][7];
1420 #if !defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) && !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC) && !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC)
1421 if ('B' == x
|| 'B' == y
)
1424 _("This system does not provide a way to find the birth time of a file."));
1429 /* -newertY (for any Y) is invalid. */
1431 || 0 == strchr(validchars
, x
)
1432 || 0 == strchr( validchars
, y
))
1438 struct predicate
*our_pred
;
1440 /* Because this item is ARG_SPECIAL_PARSE, we have to advance arg_ptr
1441 * past the test name (for most other tests, this is already done)
1445 our_pred
= insert_primary (entry
);
1451 our_pred
->args
.reftime
.xval
= XVAL_ATIME
;
1454 our_pred
->args
.reftime
.xval
= XVAL_BIRTHTIME
;
1457 our_pred
->args
.reftime
.xval
= XVAL_CTIME
;
1460 our_pred
->args
.reftime
.xval
= XVAL_MTIME
;
1463 assert (strchr(validchars
, x
));
1469 if (!get_date(&our_pred
->args
.reftime
.ts
,
1471 &options
.start_time
))
1474 _("I cannot figure out how to interpret %s as a date or time"),
1475 quotearg_n_style(0, options
.err_quoting_style
, argv
[*arg_ptr
]));
1480 struct stat stat_newer
;
1482 /* Stat the named file. */
1483 set_stat_placeholders(&stat_newer
);
1484 if ((*options
.xstat
) (argv
[*arg_ptr
], &stat_newer
))
1485 fatal_file_error(argv
[*arg_ptr
]);
1487 if (!get_stat_Ytime(&stat_newer
, y
, &our_pred
->args
.reftime
.ts
))
1489 /* We cannot extract a timestamp from the struct stat. */
1490 error(1, 0, _("Cannot obtain birth time of file %s"),
1491 safely_quote_err_filename(0, argv
[*arg_ptr
]));
1494 our_pred
->args
.reftime
.kind
= COMP_GT
;
1495 our_pred
->est_success_rate
= estimate_timestamp_success_rate(our_pred
->args
.reftime
.ts
.tv_sec
);
1498 assert (our_pred
->pred_func
!= NULL
);
1499 assert (our_pred
->pred_func
== pred_newerXY
);
1500 assert (our_pred
->need_stat
);
1508 parse_noleaf (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1510 options
.no_leaf_check
= true;
1511 return parse_noop(entry
, argv
, arg_ptr
);
1515 /* Arbitrary amount by which to increase size
1516 of `uid_unused' and `gid_unused'. */
1517 #define ALLOC_STEP 2048
1519 /* Boolean: if uid_unused[n] is nonzero, then UID n has no passwd entry. */
1520 char *uid_unused
= NULL
;
1522 /* Number of elements in `uid_unused'. */
1523 unsigned uid_allocated
;
1525 /* Similar for GIDs and group entries. */
1526 char *gid_unused
= NULL
;
1527 unsigned gid_allocated
;
1531 parse_nogroup (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1533 struct predicate
*our_pred
;
1538 our_pred
= insert_primary (entry
);
1539 our_pred
->est_success_rate
= 1e-4;
1541 if (gid_unused
== NULL
)
1545 gid_allocated
= ALLOC_STEP
;
1546 gid_unused
= xmalloc (gid_allocated
);
1547 memset (gid_unused
, 1, gid_allocated
);
1549 while ((gr
= getgrent ()) != NULL
)
1551 if ((unsigned) gr
->gr_gid
>= gid_allocated
)
1553 unsigned new_allocated
= (unsigned) gr
->gr_gid
+ ALLOC_STEP
;
1554 gid_unused
= xrealloc (gid_unused
, new_allocated
);
1555 memset (gid_unused
+ gid_allocated
, 1,
1556 new_allocated
- gid_allocated
);
1557 gid_allocated
= new_allocated
;
1559 gid_unused
[(unsigned) gr
->gr_gid
] = 0;
1568 parse_nouser (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1570 struct predicate
*our_pred
;
1575 our_pred
= insert_primary (entry
);
1576 our_pred
->est_success_rate
= 1e-3;
1578 if (uid_unused
== NULL
)
1582 uid_allocated
= ALLOC_STEP
;
1583 uid_unused
= xmalloc (uid_allocated
);
1584 memset (uid_unused
, 1, uid_allocated
);
1586 while ((pw
= getpwent ()) != NULL
)
1588 if ((unsigned) pw
->pw_uid
>= uid_allocated
)
1590 unsigned new_allocated
= (unsigned) pw
->pw_uid
+ ALLOC_STEP
;
1591 uid_unused
= xrealloc (uid_unused
, new_allocated
);
1592 memset (uid_unused
+ uid_allocated
, 1,
1593 new_allocated
- uid_allocated
);
1594 uid_allocated
= new_allocated
;
1596 uid_unused
[(unsigned) pw
->pw_uid
] = 0;
1605 parse_nowarn (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1607 options
.warnings
= false;
1608 return parse_noop(entry
, argv
, arg_ptr
);
1612 parse_ok (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1614 return insert_exec_ok ("-ok", entry
, get_start_dirfd(), argv
, arg_ptr
);
1618 parse_okdir (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1620 return insert_exec_ok ("-okdir", entry
, -1, argv
, arg_ptr
);
1624 parse_openparen (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1626 struct predicate
*our_pred
;
1631 our_pred
= get_new_pred_chk_op (entry
);
1632 our_pred
->pred_func
= pred_openparen
;
1633 our_pred
->p_type
= OPEN_PAREN
;
1634 our_pred
->p_prec
= NO_PREC
;
1635 our_pred
->need_stat
= our_pred
->need_type
= false;
1640 parse_or (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1642 struct predicate
*our_pred
;
1647 our_pred
= get_new_pred (entry
);
1648 our_pred
->pred_func
= pred_or
;
1649 our_pred
->p_type
= BI_OP
;
1650 our_pred
->p_prec
= OR_PREC
;
1651 our_pred
->need_stat
= our_pred
->need_type
= false;
1655 /* -path is deprecated (at RMS's request) in favour of
1656 * -iwholename. See the node "GNU Manuals" in standards.texi
1657 * for the rationale for this (basically, GNU prefers the use
1658 * of the phrase "file name" to "path name".
1660 * We do not issue a warning that this usage is deprecated
1661 * since HPUX find supports this predicate also.
1664 parse_path (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1666 return parse_wholename(entry
, argv
, arg_ptr
);
1670 parse_wholename (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1673 if (collect_arg(argv
, arg_ptr
, &name
))
1675 struct predicate
*our_pred
= insert_primary_withpred (entry
, pred_path
);
1676 our_pred
->need_stat
= our_pred
->need_type
= false;
1677 our_pred
->args
.str
= name
;
1678 our_pred
->est_success_rate
= estimate_pattern_match_rate(name
, 0);
1685 parse_perm (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1690 boolean havekind
= false;
1691 enum permissions_type kind
= PERM_EXACT
;
1692 struct mode_change
*change
= NULL
;
1693 struct predicate
*our_pred
;
1694 const char *perm_expr
;
1696 if (!collect_arg(argv
, arg_ptr
, &perm_expr
))
1699 switch (perm_expr
[0])
1703 kind
= PERM_AT_LEAST
;
1709 change
= mode_compile (perm_expr
);
1712 /* Most likely the caller is an old script that is still
1713 * using the obsolete GNU syntax '-perm +MODE'. This old
1714 * syntax was withdrawn in favor of '-perm /MODE' because
1715 * it is incompatible with POSIX in some cases, but we
1716 * still support uses of it that are not incompatible with
1725 /* This is a POSIX-compatible usage */
1733 case '/': /* GNU extension */
1741 /* For example, '-perm 0644', which is valid and matches
1742 * only files whose mode is exactly 0644.
1753 change
= mode_compile (perm_expr
+ mode_start
);
1755 error (1, 0, _("invalid mode %s"),
1756 quotearg_n_style(0, options
.err_quoting_style
, perm_expr
));
1758 perm_val
[0] = mode_adjust (0, false, 0, change
, NULL
);
1759 perm_val
[1] = mode_adjust (0, true, 0, change
, NULL
);
1762 if (('/' == perm_expr
[0]) && (0 == perm_val
[0]) && (0 == perm_val
[1]))
1764 /* The meaning of -perm /000 will change in the future. It
1765 * currently matches no files, but like -perm -000 it should
1768 * Starting in 2005, we used to issue a warning message
1769 * informing the user that the behaviour would change in the
1770 * future. We have now changed the behaviour and issue a
1771 * warning message that the behaviour recently changed.
1774 _("warning: you have specified a mode pattern %s (which is "
1775 "equivalent to /000). The meaning of -perm /000 has now been "
1776 "changed to be consistent with -perm -000; that is, while it "
1777 "used to match no files, it now matches all files."),
1780 kind
= PERM_AT_LEAST
;
1783 /* The "magic" number below is just the fraction of files on my
1784 * own system that "-type l -xtype l" fails for (i.e. unbroken symlinks).
1785 * Actual totals are 1472 and 1073833.
1787 rate
= 0.9986; /* probably matches anything but a broken symlink */
1790 our_pred
= insert_primary (entry
);
1791 our_pred
->est_success_rate
= rate
;
1794 our_pred
->args
.perm
.kind
= kind
;
1799 switch (perm_expr
[0])
1802 our_pred
->args
.perm
.kind
= PERM_AT_LEAST
;
1805 our_pred
->args
.perm
.kind
= PERM_ANY
;
1808 our_pred
->args
.perm
.kind
= PERM_EXACT
;
1812 memcpy (our_pred
->args
.perm
.val
, perm_val
, sizeof perm_val
);
1817 parse_print (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1819 struct predicate
*our_pred
;
1824 our_pred
= insert_primary (entry
);
1825 /* -print has the side effect of printing. This prevents us
1826 from doing undesired multiple printing when the user has
1827 already specified -print. */
1828 our_pred
->side_effects
= our_pred
->no_default_print
= true;
1829 our_pred
->need_stat
= our_pred
->need_type
= false;
1830 open_stdout(&our_pred
->args
.printf_vec
);
1835 parse_print0 (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1837 return insert_fprint(entry
, NULL
);
1841 parse_printf (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1844 if (collect_arg(argv
, arg_ptr
, &format
))
1846 struct format_val fmt
;
1848 return insert_fprintf (&fmt
, entry
, pred_fprintf
, format
);
1854 parse_fprintf (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1856 const char *format
, *filename
;
1857 if (collect_arg(argv
, arg_ptr
, &filename
))
1859 if (collect_arg(argv
, arg_ptr
, &format
))
1861 struct format_val fmt
;
1862 open_output_file (filename
, &fmt
);
1863 return insert_fprintf (&fmt
, entry
, pred_fprintf
, format
);
1870 parse_prune (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1872 struct predicate
*our_pred
;
1877 our_pred
= insert_primary (entry
);
1878 our_pred
->need_stat
= our_pred
->need_type
= false;
1879 /* -prune has a side effect that it does not descend into
1880 the current directory. */
1881 our_pred
->side_effects
= true;
1882 our_pred
->no_default_print
= false;
1887 parse_quit (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1889 struct predicate
*our_pred
= insert_primary (entry
);
1892 our_pred
->need_stat
= our_pred
->need_type
= false;
1893 our_pred
->side_effects
= true; /* Exiting is a side effect... */
1894 our_pred
->no_default_print
= false; /* Don't inhibit the default print, though. */
1895 our_pred
->est_success_rate
= 1.0f
;
1901 parse_regextype (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1903 const char *type_name
;
1904 if (collect_arg(argv
, arg_ptr
, &type_name
))
1906 /* collect the regex type name */
1907 options
.regex_options
= get_regex_type(type_name
);
1908 return parse_noop(entry
, argv
, arg_ptr
);
1915 parse_regex (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1917 return insert_regex (argv
, arg_ptr
, entry
, options
.regex_options
);
1921 insert_regex (char **argv
, int *arg_ptr
, const struct parser_table
*entry
, int regex_options
)
1924 if (collect_arg(argv
, arg_ptr
, &rx
))
1926 struct re_pattern_buffer
*re
;
1927 const char *error_message
;
1928 struct predicate
*our_pred
= insert_primary_withpred (entry
, pred_regex
);
1929 our_pred
->need_stat
= our_pred
->need_type
= false;
1930 re
= xmalloc (sizeof (struct re_pattern_buffer
));
1931 our_pred
->args
.regex
= re
;
1932 re
->allocated
= 100;
1933 re
->buffer
= xmalloc (re
->allocated
);
1936 re_set_syntax(regex_options
);
1937 re
->syntax
= regex_options
;
1938 re
->translate
= NULL
;
1940 error_message
= re_compile_pattern (rx
, strlen(rx
), re
);
1942 error (1, 0, "%s", error_message
);
1943 our_pred
->est_success_rate
= estimate_pattern_match_rate(rx
, 1);
1950 parse_size (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
1952 struct predicate
*our_pred
;
1955 enum comparison_type c_type
;
1960 /* XXX: cannot (yet) convert to ue collect_arg() as this
1961 * function modifies the args in-place.
1963 if ((argv
== NULL
) || (argv
[*arg_ptr
] == NULL
))
1966 len
= strlen (argv
[*arg_ptr
]);
1968 error (1, 0, _("invalid null argument to -size"));
1970 suffix
= argv
[*arg_ptr
][len
- 1];
1975 argv
[*arg_ptr
][len
- 1] = '\0';
1980 argv
[*arg_ptr
][len
- 1] = '\0';
1985 argv
[*arg_ptr
][len
- 1] = '\0';
1988 case 'M': /* Megabytes */
1989 blksize
= 1024*1024;
1990 argv
[*arg_ptr
][len
- 1] = '\0';
1993 case 'G': /* Gigabytes */
1994 blksize
= 1024*1024*1024;
1995 argv
[*arg_ptr
][len
- 1] = '\0';
2000 argv
[*arg_ptr
][len
- 1] = '\0';
2016 error (1, 0, _("invalid -size type `%c'"), argv
[*arg_ptr
][len
- 1]);
2018 /* TODO: accept fractional megabytes etc. ? */
2019 if (!get_num (argv
[*arg_ptr
], &num
, &c_type
))
2021 error(1, 0, _("Invalid argument `%s%c' to -size"), argv
[*arg_ptr
], (int)suffix
);
2024 our_pred
= insert_primary (entry
);
2025 our_pred
->args
.size
.kind
= c_type
;
2026 our_pred
->args
.size
.blocksize
= blksize
;
2027 our_pred
->args
.size
.size
= num
;
2028 our_pred
->need_stat
= true;
2029 our_pred
->need_type
= false;
2031 if (COMP_GT
== c_type
)
2032 our_pred
->est_success_rate
= (num
*blksize
> 20480) ? 0.1 : 0.9;
2033 else if (COMP_LT
== c_type
)
2034 our_pred
->est_success_rate
= (num
*blksize
> 20480) ? 0.9 : 0.1;
2036 our_pred
->est_success_rate
= 0.01;
2044 parse_samefile (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2046 /* General idea: stat the file, remember device and inode numbers.
2047 * If a candidate file matches those, it's the same file.
2049 struct predicate
*our_pred
;
2050 struct stat st
, fst
;
2053 set_stat_placeholders(&st
);
2054 if (!collect_arg_stat_info(argv
, arg_ptr
, &st
))
2057 set_stat_placeholders(&fst
);
2058 /* POSIX systems are free to re-use the inode number of a deleted
2059 * file. To ensure that we are not fooled by inode reuse, we hold
2060 * the file open if we can. This would prevent the system reusing
2063 fd
= -3; /* means, uninitialised */
2064 openflags
= O_RDONLY
;
2066 if (options
.symlink_handling
== SYMLINK_NEVER_DEREF
)
2068 if (options
.open_nofollow_available
)
2070 assert (O_NOFOLLOW
!= 0);
2071 openflags
|= O_NOFOLLOW
;
2072 fd
= -1; /* safe to open it. */
2076 if (S_ISLNK(st
.st_mode
))
2078 /* no way to ensure that a symlink will not be followed
2079 * by open(2), so fall back on using lstat(). Accept
2080 * the risk that the named file will be deleted and
2081 * replaced with another having the same inode.
2083 * Avoid opening the file.
2085 fd
= -2; /* Do not open it */
2090 /* Race condition here: the file might become a symlink here. */
2096 /* We want to dereference the symlink anyway */
2097 fd
= -1; /* safe to open it without O_NOFOLLOW */
2100 assert (fd
!= -3); /* check we made a decision */
2103 /* Race condition here. The file might become a
2104 * symbolic link in between out call to stat and
2107 fd
= open(argv
[*arg_ptr
], openflags
);
2111 /* We stat the file again here to prevent a race condition
2112 * between the first stat and the call to open(2).
2114 if (0 != fstat(fd
, &fst
))
2116 fatal_file_error(argv
[*arg_ptr
]);
2120 /* Worry about the race condition. If the file became a
2121 * symlink after our first stat and before our call to
2122 * open, fst may contain the stat information for the
2123 * destination of the link, not the link itself.
2125 if ((*options
.xstat
) (argv
[*arg_ptr
], &st
))
2126 fatal_file_error(argv
[*arg_ptr
]);
2128 if ((options
.symlink_handling
== SYMLINK_NEVER_DEREF
)
2129 && (!options
.open_nofollow_available
))
2131 if (S_ISLNK(st
.st_mode
))
2133 /* We lost the race. Leave the data in st. The
2134 * file descriptor points to the wrong thing.
2141 /* Several possibilities here:
2142 * 1. There was no race
2143 * 2. The file changed into a symlink after the stat and
2144 * before the open, and then back into a non-symlink
2145 * before the second stat.
2147 * In case (1) there is no problem. In case (2),
2148 * the stat() and fstat() calls will have returned
2149 * different data. O_NOFOLLOW was not available,
2150 * so the open() call may have followed a symlink
2151 * even if the -P option is in effect.
2153 if ((st
.st_dev
== fst
.st_dev
)
2154 && (st
.st_ino
== fst
.st_ino
))
2156 /* No race. No need to copy fst to st,
2157 * since they should be identical (modulo
2158 * differences in padding bytes).
2163 /* We lost the race. Leave the data in st. The
2164 * file descriptor points to the wrong thing.
2179 our_pred
= insert_primary (entry
);
2180 our_pred
->args
.samefileid
.ino
= st
.st_ino
;
2181 our_pred
->args
.samefileid
.dev
= st
.st_dev
;
2182 our_pred
->args
.samefileid
.fd
= fd
;
2183 our_pred
->need_type
= false;
2184 our_pred
->need_stat
= true;
2185 our_pred
->est_success_rate
= 0.01f
;
2190 /* This function is commented out partly because support for it is
2194 parse_show_control_chars (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2197 const char *errmsg
= _("The -show-control-chars option takes a single argument which "
2198 "must be 'literal' or 'safe'");
2200 if ((argv
== NULL
) || (argv
[*arg_ptr
] == NULL
))
2202 error (1, errno
, "%s", errmsg
);
2207 arg
= argv
[*arg_ptr
];
2209 if (0 == strcmp("literal", arg
))
2211 options
.literal_control_chars
= true;
2213 else if (0 == strcmp("safe", arg
))
2215 options
.literal_control_chars
= false;
2219 error (1, errno
, "%s", errmsg
);
2222 (*arg_ptr
)++; /* consume the argument. */
2230 parse_true (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2232 struct predicate
*our_pred
;
2237 our_pred
= insert_primary (entry
);
2238 our_pred
->need_stat
= our_pred
->need_type
= false;
2239 our_pred
->est_success_rate
= 1.0f
;
2244 parse_noop (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2247 return parse_true(get_noop(), argv
, arg_ptr
);
2251 parse_accesscheck (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2253 struct predicate
*our_pred
;
2256 our_pred
= insert_primary (entry
);
2257 our_pred
->need_stat
= our_pred
->need_type
= false;
2258 our_pred
->side_effects
= our_pred
->no_default_print
= false;
2259 if (pred_is(our_pred
, pred_executable
))
2260 our_pred
->est_success_rate
= 0.2;
2262 our_pred
->est_success_rate
= 0.9;
2267 parse_type (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2269 return insert_type (argv
, arg_ptr
, entry
, pred_type
);
2273 parse_uid (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2275 struct predicate
*p
= insert_num (argv
, arg_ptr
, entry
);
2278 p
->est_success_rate
= (p
->args
.numinfo
.l_val
< 100) ? 0.99 : 0.2;
2288 parse_used (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2290 struct predicate
*our_pred
;
2291 struct time_val tval
;
2292 const char *offset_str
;
2293 const char *errmsg
= "arithmetic overflow while converting %s days to a number of seconds";
2295 if (collect_arg(argv
, arg_ptr
, &offset_str
))
2297 /* The timespec is actually a delta value, so we use an origin of 0. */
2298 if (get_relative_timestamp(offset_str
, &tval
, 0, DAYSECS
, errmsg
))
2300 our_pred
= insert_primary (entry
);
2301 our_pred
->args
.reftime
= tval
;
2302 our_pred
->est_success_rate
= estimate_file_age_success_rate(tval
.ts
.tv_sec
/ DAYSECS
);
2307 error(1, 0, _("Invalid argument %s to -used"), offset_str
);
2313 return false; /* missing argument */
2318 parse_user (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2320 const char *username
;
2322 if (collect_arg(argv
, arg_ptr
, &username
))
2324 struct predicate
*our_pred
;
2326 struct passwd
*cur_pwd
= getpwnam(username
);
2328 if (cur_pwd
!= NULL
)
2330 uid
= cur_pwd
->pw_uid
;
2334 int uid_len
= strspn (username
, "0123456789");
2335 if (uid_len
&& (username
[uid_len
]==0))
2336 uid
= safe_atoi (username
);
2340 our_pred
= insert_primary (entry
);
2341 our_pred
->args
.uid
= uid
;
2342 our_pred
->est_success_rate
= (our_pred
->args
.uid
< 100) ? 0.99 : 0.2;
2349 parse_version (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2351 extern char *version_string
;
2359 display_findutils_version("find");
2360 printf (_("Features enabled: "));
2363 printf("CACHE_IDS ");
2371 printf("DEBUG_STAT ");
2374 #if defined USE_STRUCT_DIRENT_D_TYPE && defined HAVE_STRUCT_DIRENT_D_TYPE
2378 #if defined O_NOFOLLOW
2379 printf("O_NOFOLLOW(%s) ",
2380 (options
.open_nofollow_available
? "enabled" : "disabled"));
2383 #if defined LEAF_OPTIMISATION
2384 printf("LEAF_OPTIMISATION ");
2389 if (is_fts_enabled(&flags
))
2395 if (flags
& FTS_CWDFD
)
2401 printf("FTS_CWDFD");
2407 printf("CBO(level=%d) ", (int)(options
.optimisation_level
));
2412 /* For the moment, leave this as English in case someone wants
2413 to parse these strings. */
2422 parse_xdev (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2424 options
.stay_on_filesystem
= true;
2425 return parse_noop(entry
, argv
, arg_ptr
);
2429 parse_ignore_race (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2431 options
.ignore_readdir_race
= true;
2432 return parse_noop(entry
, argv
, arg_ptr
);
2436 parse_noignore_race (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2438 options
.ignore_readdir_race
= false;
2439 return parse_noop(entry
, argv
, arg_ptr
);
2443 parse_warn (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2445 options
.warnings
= true;
2446 return parse_noop(entry
, argv
, arg_ptr
);
2450 parse_xtype (const struct parser_table
* entry
, char **argv
, int *arg_ptr
)
2452 return insert_type (argv
, arg_ptr
, entry
, pred_xtype
);
2456 insert_type (char **argv
, int *arg_ptr
, const struct parser_table
*entry
, PRED_FUNC which_pred
)
2459 struct predicate
*our_pred
;
2461 const char *typeletter
;
2463 if (collect_arg(argv
, arg_ptr
, &typeletter
))
2465 if (strlen(typeletter
) != 1u)
2467 error(1, 0, _("Arguments to -type should contain only one letter"));
2471 switch (typeletter
[0])
2473 case 'b': /* block special */
2474 type_cell
= S_IFBLK
;
2477 case 'c': /* character special */
2478 type_cell
= S_IFCHR
;
2481 case 'd': /* directory */
2482 type_cell
= S_IFDIR
;
2485 case 'f': /* regular file */
2486 type_cell
= S_IFREG
;
2490 case 'l': /* symbolic link */
2491 type_cell
= S_IFLNK
;
2496 case 'p': /* pipe */
2497 type_cell
= S_IFIFO
;
2502 case 's': /* socket */
2503 type_cell
= S_IFSOCK
;
2508 case 'D': /* Solaris door */
2509 type_cell
= S_IFDOOR
;
2513 default: /* None of the above ... nuke 'em. */
2514 error(1, 0, _("Unknown argument to -type: %c"), (*typeletter
));
2517 our_pred
= insert_primary_withpred (entry
, which_pred
);
2518 our_pred
->est_success_rate
= rate
;
2520 /* Figure out if we will need to stat the file, because if we don't
2521 * need to follow symlinks, we can avoid a stat call by using
2522 * struct dirent.d_type.
2524 if (which_pred
== pred_xtype
)
2526 our_pred
->need_stat
= true;
2527 our_pred
->need_type
= false;
2531 our_pred
->need_stat
= false; /* struct dirent is enough */
2532 our_pred
->need_type
= true;
2534 our_pred
->args
.type
= type_cell
;
2541 /* Return true if the file accessed via FP is a terminal.
2544 stream_is_tty(FILE *fp
)
2546 int fd
= fileno(fp
);
2549 return false; /* not a valid stream */
2553 return isatty(fd
) ? true : false;
2561 /* XXX: do we need to pass FUNC to this function? */
2563 insert_fprintf (struct format_val
*vec
,
2564 const struct parser_table
*entry
, PRED_FUNC func
,
2565 const char *format_const
)
2567 char *format
= (char*)format_const
; /* XXX: casting away constness */
2568 register char *scan
; /* Current address in scanning `format'. */
2569 register char *scan2
; /* Address inside of element being scanned. */
2570 struct segment
**segmentp
; /* Address of current segment. */
2571 struct predicate
*our_pred
;
2573 our_pred
= insert_primary_withpred (entry
, func
);
2574 our_pred
->side_effects
= our_pred
->no_default_print
= true;
2575 our_pred
->args
.printf_vec
= *vec
;
2576 our_pred
->need_type
= false;
2577 our_pred
->need_stat
= false;
2578 our_pred
->p_cost
= NeedsNothing
;
2580 segmentp
= &our_pred
->args
.printf_vec
.segment
;
2583 for (scan
= format
; *scan
; scan
++)
2588 if (*scan2
>= '0' && *scan2
<= '7')
2592 for (i
= n
= 0; i
< 3 && (*scan2
>= '0' && *scan2
<= '7');
2594 n
= 8 * n
+ *scan2
- '0';
2609 make_segment (segmentp
, format
, scan
- format
,
2612 if (our_pred
->need_stat
&& (our_pred
->p_cost
< NeedsStatInfo
))
2613 our_pred
->p_cost
= NeedsStatInfo
;
2631 /* *scan = '\\'; * it already is */
2635 _("warning: unrecognized escape `\\%c'"), *scan2
);
2640 segmentp
= make_segment (segmentp
, format
, scan
- format
+ 1,
2643 format
= scan2
+ 1; /* Move past the escape. */
2644 scan
= scan2
; /* Incremented immediately by `for'. */
2646 else if (*scan
== '%')
2650 /* Trailing %. We don't like those. */
2651 error (1, 0, _("error: %s at end of format string"), scan
);
2653 else if (scan
[1] == '%')
2655 segmentp
= make_segment (segmentp
, format
, scan
- format
+ 1,
2662 /* Scan past flags, width and precision, to verify kind. */
2663 for (scan2
= scan
; *++scan2
&& strchr ("-+ #", *scan2
);)
2665 while (ISDIGIT (*scan2
))
2668 for (scan2
++; ISDIGIT (*scan2
); scan2
++)
2670 if (strchr ("abcdDfFgGhHiklmMnpPsStuUyY", *scan2
))
2672 segmentp
= make_segment (segmentp
, format
, scan2
- format
,
2673 KIND_FORMAT
, *scan2
, 0,
2678 else if (strchr ("ABCT", *scan2
) && scan2
[1])
2680 segmentp
= make_segment (segmentp
, format
, scan2
- format
,
2681 KIND_FORMAT
, scan2
[0], scan2
[1],
2689 /* An unrecognized % escape. Print the char after the %. */
2690 error (0, 0, _("warning: unrecognized format directive `%%%c'"),
2692 segmentp
= make_segment (segmentp
, format
, scan
- format
,
2702 make_segment (segmentp
, format
, scan
- format
, KIND_PLAIN
, 0, 0,
2707 /* Create a new fprintf segment in *SEGMENT, with type KIND,
2708 from the text in FORMAT, which has length LEN.
2709 Return the address of the `next' pointer of the new segment. */
2711 static struct segment
**
2712 make_segment (struct segment
**segment
,
2717 char aux_format_char
,
2718 struct predicate
*pred
)
2720 enum EvaluationCost mycost
= NeedsNothing
;
2723 *segment
= xmalloc (sizeof (struct segment
));
2725 (*segment
)->segkind
= kind
;
2726 (*segment
)->format_char
[0] = format_char
;
2727 (*segment
)->format_char
[1] = aux_format_char
;
2728 (*segment
)->next
= NULL
;
2729 (*segment
)->text_len
= len
;
2731 fmt
= (*segment
)->text
= xmalloc (len
+ sizeof "d");
2732 strncpy (fmt
, format
, len
);
2737 case KIND_PLAIN
: /* Plain text string, no % conversion. */
2738 case KIND_STOP
: /* Terminate argument, no newline. */
2739 assert (0 == format_char
);
2740 assert (0 == aux_format_char
);
2742 if (mycost
> pred
->p_cost
)
2743 pred
->p_cost
= NeedsNothing
;
2744 return &(*segment
)->next
;
2748 assert (kind
== KIND_FORMAT
);
2749 switch (format_char
)
2751 case 'l': /* object of symlink */
2752 pred
->need_stat
= true;
2753 mycost
= NeedsLinkName
;
2757 case 'y': /* file type */
2758 pred
->need_type
= true;
2763 case 'a': /* atime in `ctime' format */
2764 case 'A': /* atime in user-specified strftime format */
2765 case 'B': /* birth time in user-specified strftime format */
2766 case 'c': /* ctime in `ctime' format */
2767 case 'C': /* ctime in user-specified strftime format */
2768 case 'F': /* file system type */
2769 case 'g': /* group name */
2770 case 'i': /* inode number */
2771 case 'M': /* mode in `ls -l' format (eg., "drwxr-xr-x") */
2772 case 's': /* size in bytes */
2773 case 't': /* mtime in `ctime' format */
2774 case 'T': /* mtime in user-specified strftime format */
2775 case 'u': /* user name */
2776 pred
->need_stat
= true;
2777 mycost
= NeedsStatInfo
;
2781 case 'S': /* sparseness */
2782 pred
->need_stat
= true;
2783 mycost
= NeedsStatInfo
;
2787 case 'Y': /* symlink pointed file type */
2788 pred
->need_stat
= true;
2789 mycost
= NeedsType
; /* true for amortised effect */
2793 case 'f': /* basename of path */
2794 case 'h': /* leading directories part of path */
2795 case 'p': /* pathname */
2796 case 'P': /* pathname with ARGV element stripped */
2800 case 'H': /* ARGV element file was found under */
2804 /* Numeric items that one might expect to honour
2805 * #, 0, + flags but which do not.
2807 case 'G': /* GID number */
2808 case 'U': /* UID number */
2809 case 'b': /* size in 512-byte blocks (NOT birthtime in ctime fmt)*/
2810 case 'D': /* Filesystem device on which the file exits */
2811 case 'k': /* size in 1K blocks */
2812 case 'n': /* number of links */
2813 pred
->need_stat
= true;
2814 mycost
= NeedsStatInfo
;
2818 /* Numeric items that DO honour #, 0, + flags.
2820 case 'd': /* depth in search tree (0 = ARGV element) */
2824 case 'm': /* mode as octal number (perms only) */
2826 pred
->need_stat
= true;
2827 mycost
= NeedsStatInfo
;
2834 _("error: the format directive `%%%c' is reserved for future use"),
2841 if (mycost
> pred
->p_cost
)
2842 pred
->p_cost
= mycost
;
2843 return &(*segment
)->next
;
2847 check_path_safety(const char *action
, char **argv
)
2849 const char *path
= getenv("PATH");
2854 s
= next_element(path
, 1);
2855 while ((s
= next_element ((char *) NULL
, 1)) != NULL
)
2857 if (0 == strcmp(s
, "."))
2859 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)"),
2862 else if ('/' != s
[0])
2864 /* Relative paths are also dangerous in $PATH. */
2865 error(1, 0, _("The relative path %s is included in the PATH "
2866 "environment variable, which is insecure in "
2867 "combination with the %s action of find. "
2868 "Please remove that entry from $PATH"),
2869 safely_quote_err_filename(0, s
),
2876 /* handles both exec and ok predicate */
2878 new_insert_exec_ok (const char *action
,
2879 const struct parser_table
*entry
,
2884 int start
, end
; /* Indexes in ARGV of start & end of cmd. */
2885 int i
; /* Index into cmd args */
2886 int saw_braces
; /* True if previous arg was '{}'. */
2887 boolean allow_plus
; /* True if + is a valid terminator */
2888 int brace_count
; /* Number of instances of {}. */
2889 PRED_FUNC func
= entry
->pred_func
;
2890 enum BC_INIT_STATUS bcstatus
;
2892 struct predicate
*our_pred
;
2893 struct exec_val
*execp
; /* Pointer for efficiency. */
2895 if ((argv
== NULL
) || (argv
[*arg_ptr
] == NULL
))
2898 our_pred
= insert_primary_withpred (entry
, func
);
2899 our_pred
->side_effects
= our_pred
->no_default_print
= true;
2900 our_pred
->need_type
= our_pred
->need_stat
= false;
2902 execp
= &our_pred
->args
.exec_vec
;
2904 if ((func
!= pred_okdir
) && (func
!= pred_ok
))
2907 execp
->close_stdin
= false;
2912 /* If find reads stdin (i.e. for -ok and similar), close stdin
2913 * in the child to prevent some script from consiming the output
2914 * intended for find.
2916 execp
->close_stdin
= true;
2920 if ((func
== pred_execdir
) || (func
== pred_okdir
))
2922 options
.ignore_readdir_race
= false;
2923 check_path_safety(action
, argv
);
2924 execp
->use_current_dir
= true;
2928 execp
->use_current_dir
= false;
2931 our_pred
->args
.exec_vec
.multiple
= 0;
2933 /* Count the number of args with path replacements, up until the ';'.
2934 * Also figure out if the command is terminated by ";" or by "+".
2937 for (end
= start
, saw_braces
=0, brace_count
=0;
2939 && ((argv
[end
][0] != ';') || (argv
[end
][1] != '\0'));
2942 /* For -exec and -execdir, "{} +" can terminate the command. */
2944 && argv
[end
][0] == '+' && argv
[end
][1] == 0
2947 our_pred
->args
.exec_vec
.multiple
= 1;
2952 if (mbsstr (argv
[end
], "{}"))
2957 if (0 == end
&& (func
== pred_execdir
|| func
== pred_okdir
))
2959 /* The POSIX standard says that {} replacement should
2960 * occur even in the utility name. This is insecure
2961 * since it means we will be executing a command whose
2962 * name is chosen according to whatever find finds in
2963 * the file system. That can be influenced by an
2964 * attacker. Hence for -execdir and -okdir this is not
2965 * allowed. We can specify this as those options are
2966 * not defined by POSIX.
2968 error(1, 0, _("You may not use {} within the utility name for -execdir and -okdir, because this is a potential security problem."));
2973 /* Fail if no command given or no semicolon found. */
2974 if ((end
== start
) || (argv
[end
] == NULL
))
2981 if (our_pred
->args
.exec_vec
.multiple
&& brace_count
> 1)
2985 if (func
== pred_execdir
)
2991 _("Only one instance of {} is supported with -exec%s ... +"),
2995 /* We use a switch statement here so that the compiler warns us when
2996 * we forget to handle a newly invented enum value.
2998 * Like xargs, we allow 2KiB of headroom for the launched utility to
2999 * export its own environment variables before calling something
3002 bcstatus
= bc_init_controlinfo(&execp
->ctl
, 2048u);
3005 case BC_INIT_ENV_TOO_BIG
:
3006 case BC_INIT_CANNOT_ACCOMODATE_HEADROOM
:
3008 _("The environment is too large for exec()."));
3011 /* Good news. Carry on. */
3014 bc_use_sensible_arg_max(&execp
->ctl
);
3017 execp
->ctl
.exec_callback
= launch
;
3019 if (our_pred
->args
.exec_vec
.multiple
)
3021 /* "+" terminator, so we can just append our arguments after the
3022 * command and initial arguments.
3024 execp
->replace_vec
= NULL
;
3025 execp
->ctl
.replace_pat
= NULL
;
3026 execp
->ctl
.rplen
= 0;
3027 execp
->ctl
.lines_per_exec
= 0; /* no limit */
3028 execp
->ctl
.args_per_exec
= 0; /* no limit */
3030 /* remember how many arguments there are */
3031 execp
->ctl
.initial_argc
= (end
-start
) - 1;
3033 /* execp->state = xmalloc(sizeof struct buildcmd_state); */
3034 bc_init_state(&execp
->ctl
, &execp
->state
, execp
);
3036 /* Gather the initial arguments. Skip the {}. */
3037 for (i
=start
; i
<end
-1; ++i
)
3039 bc_push_arg(&execp
->ctl
, &execp
->state
,
3040 argv
[i
], strlen(argv
[i
])+1,
3047 /* Semicolon terminator - more than one {} is supported, so we
3048 * have to do brace-replacement.
3050 execp
->num_args
= end
- start
;
3052 execp
->ctl
.replace_pat
= "{}";
3053 execp
->ctl
.rplen
= strlen(execp
->ctl
.replace_pat
);
3054 execp
->ctl
.lines_per_exec
= 0; /* no limit */
3055 execp
->ctl
.args_per_exec
= 0; /* no limit */
3056 execp
->replace_vec
= xmalloc(sizeof(char*)*execp
->num_args
);
3059 /* execp->state = xmalloc(sizeof(*(execp->state))); */
3060 bc_init_state(&execp
->ctl
, &execp
->state
, execp
);
3062 /* Remember the (pre-replacement) arguments for later. */
3063 for (i
=0; i
<execp
->num_args
; ++i
)
3065 execp
->replace_vec
[i
] = argv
[i
+start
];
3069 if (argv
[end
] == NULL
)
3080 insert_exec_ok (const char *action
, const struct parser_table
*entry
, int dirfd
, char **argv
, int *arg_ptr
)
3082 return new_insert_exec_ok(action
, entry
, dirfd
, argv
, arg_ptr
);
3087 /* Get a timestamp and comparison type.
3089 STR is the ASCII representation.
3090 Set *NUM_DAYS to the number of days/minutes/whatever, taken as being
3091 relative to ORIGIN (usually the current moment or midnight).
3092 Thus the sense of the comparison type appears to be reversed.
3093 Set *COMP_TYPE to the kind of comparison that is requested.
3094 Issue OVERFLOWMESSAGE if overflow occurs.
3095 Return true if all okay, false if input error.
3097 Used by -atime, -ctime and -mtime (parsers) to
3098 get the appropriate information for a time predicate processor. */
3101 get_relative_timestamp (const char *str
,
3102 struct time_val
*result
,
3104 double sec_per_unit
,
3105 const char *overflowmessage
)
3108 double offset
, seconds
, f
;
3110 if (get_comp_type(&str
, &result
->kind
))
3112 /* Invert the sense of the comparison */
3113 switch (result
->kind
)
3115 case COMP_LT
: result
->kind
= COMP_GT
; break;
3116 case COMP_GT
: result
->kind
= COMP_LT
; break;
3120 /* Convert the ASCII number into floating-point. */
3121 if (xstrtod(str
, NULL
, &offset
, strtod
))
3123 /* Separate the floating point number the user specified
3124 * (which is a number of days, or minutes, etc) into an
3125 * integral number of seconds (SECONDS) and a fraction (F).
3127 f
= modf(offset
* sec_per_unit
, &seconds
);
3129 result
->ts
.tv_sec
= origin
- seconds
;
3130 result
->ts
.tv_nsec
= fabs(f
* 1e9
);
3132 /* Check for overflow. */
3133 checkval
= (uintmax_t)origin
- seconds
;
3134 if (checkval
!= result
->ts
.tv_sec
)
3136 /* an overflow has occurred. */
3137 error (1, 0, overflowmessage
, str
);
3143 /* Conversion from ASCII to double failed. */
3153 /* Insert a time predicate based on the information in ENTRY.
3154 ARGV is a pointer to the argument array.
3155 ARG_PTR is a pointer to an index into the array, incremented if
3158 Return true if input is valid, false if not.
3160 A new predicate node is assigned, along with an argument node
3161 obtained with malloc.
3163 Used by -atime, -ctime, and -mtime parsers. */
3166 parse_time (const struct parser_table
* entry
, char *argv
[], int *arg_ptr
)
3168 struct predicate
*our_pred
;
3169 struct time_val tval
;
3170 enum comparison_type comp
;
3171 const char *timearg
, *orig_timearg
;
3172 const char *errmsg
= "arithmetic overflow while converting %s days to a number of seconds";
3175 if (!collect_arg(argv
, arg_ptr
, &timearg
))
3177 orig_timearg
= timearg
;
3179 /* Decide the origin by previewing the comparison type. */
3180 origin
= options
.cur_day_start
;
3182 if (get_comp_type(&timearg
, &comp
))
3184 /* Remember, we invert the sense of the comparison, so this tests
3185 * against COMP_LT instead of COMP_GT...
3187 if (COMP_LT
== comp
)
3189 uintmax_t expected
= origin
+ (DAYSECS
-1);
3190 origin
+= (DAYSECS
-1);
3191 if (origin
!= expected
)
3194 _("arithmetic overflow when trying to calculate the end of today"));
3198 /* We discard the value of comp here, as get_relative_timestamp
3199 * will set tval.kind. For that to work, we have to restore
3200 * timearg so that it points to the +/- prefix, if any. get_comp_type()
3201 * will have advanced timearg, so we restore it.
3203 timearg
= orig_timearg
;
3205 if (!get_relative_timestamp(timearg
, &tval
, origin
, DAYSECS
, errmsg
))
3208 our_pred
= insert_primary (entry
);
3209 our_pred
->args
.reftime
= tval
;
3210 our_pred
->est_success_rate
= estimate_timestamp_success_rate(tval
.ts
.tv_sec
);
3212 if (options
.debug_options
& DebugExpressionTree
)
3216 fprintf (stderr
, "inserting %s\n", our_pred
->p_name
);
3217 fprintf (stderr
, " type: %s %s ",
3218 (tval
.kind
== COMP_GT
) ? "gt" :
3219 ((tval
.kind
== COMP_LT
) ? "lt" : ((tval
.kind
== COMP_EQ
) ? "eq" : "?")),
3220 (tval
.kind
== COMP_GT
) ? " >" :
3221 ((tval
.kind
== COMP_LT
) ? " <" : ((tval
.kind
== COMP_EQ
) ? ">=" : " ?")));
3222 t
= our_pred
->args
.reftime
.ts
.tv_sec
;
3223 fprintf (stderr
, "%ju %s", (uintmax_t) our_pred
->args
.reftime
.ts
.tv_sec
, ctime (&t
));
3224 if (tval
.kind
== COMP_EQ
)
3226 t
= our_pred
->args
.reftime
.ts
.tv_sec
+ DAYSECS
;
3227 fprintf (stderr
, " < %ju %s",
3228 (uintmax_t) t
, ctime (&t
));
3235 /* Get the comparison type prefix (if any) from a number argument.
3236 The prefix is at *STR.
3237 Set *COMP_TYPE to the kind of comparison that is requested.
3238 Advance *STR beyond any initial comparison prefix.
3240 Return true if all okay, false if input error. */
3242 get_comp_type(const char **str
, enum comparison_type
*comp_type
)
3247 *comp_type
= COMP_GT
;
3251 *comp_type
= COMP_LT
;
3255 *comp_type
= COMP_EQ
;
3265 /* Get a number with comparison information.
3266 The sense of the comparison information is 'normal'; that is,
3267 '+' looks for a count > than the number and '-' less than.
3269 STR is the ASCII representation of the number.
3270 Set *NUM to the number.
3271 Set *COMP_TYPE to the kind of comparison that is requested.
3273 Return true if all okay, false if input error. */
3276 get_num (const char *str
,
3278 enum comparison_type
*comp_type
)
3285 /* Figure out the comparison type if the caller accepts one. */
3288 if (!get_comp_type(&str
, comp_type
))
3292 return xstrtoumax (str
, &pend
, 10, num
, "") == LONGINT_OK
;
3295 /* Insert a number predicate.
3296 ARGV is a pointer to the argument array.
3297 *ARG_PTR is an index into ARGV, incremented if all went well.
3298 *PRED is the predicate processor to insert.
3300 Return true if input is valid, false if error.
3302 A new predicate node is assigned, along with an argument node
3303 obtained with malloc.
3305 Used by -inum and -links parsers. */
3307 static struct predicate
*
3308 insert_num (char **argv
, int *arg_ptr
, const struct parser_table
*entry
)
3312 if (collect_arg(argv
, arg_ptr
, &numstr
))
3315 enum comparison_type c_type
;
3317 if (get_num (numstr
, &num
, &c_type
))
3319 struct predicate
*our_pred
= insert_primary (entry
);
3320 our_pred
->args
.numinfo
.kind
= c_type
;
3321 our_pred
->args
.numinfo
.l_val
= num
;
3323 if (options
.debug_options
& DebugExpressionTree
)
3325 fprintf (stderr
, "inserting %s\n", our_pred
->p_name
);
3326 fprintf (stderr
, " type: %s %s ",
3327 (c_type
== COMP_GT
) ? "gt" :
3328 ((c_type
== COMP_LT
) ? "lt" : ((c_type
== COMP_EQ
) ? "eq" : "?")),
3329 (c_type
== COMP_GT
) ? " >" :
3330 ((c_type
== COMP_LT
) ? " <" : ((c_type
== COMP_EQ
) ? " =" : " ?")));
3331 fprintf (stderr
, "%ju\n", our_pred
->args
.numinfo
.l_val
);
3340 open_output_file (const char *path
, struct format_val
*p
)
3343 p
->quote_opts
= clone_quoting_options (NULL
);
3345 if (!strcmp (path
, "/dev/stderr"))
3348 p
->filename
= _("standard error");
3350 else if (!strcmp (path
, "/dev/stdout"))
3353 p
->filename
= _("standard output");
3357 p
->stream
= fopen_safer (path
, "w");
3360 if (p
->stream
== NULL
)
3362 fatal_file_error(path
);
3366 p
->dest_is_tty
= stream_is_tty(p
->stream
);
3370 open_stdout (struct format_val
*p
)
3372 open_output_file("/dev/stdout", p
);