1 /* util.c -- functions for initializing new tree elements, and other things.
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004, 2005,
3 2008 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/>.
23 #ifdef HAVE_SYS_UTSNAME_H
24 #include <sys/utsname.h>
42 # define _(Text) gettext (Text)
47 # define N_(String) gettext_noop (String)
49 /* See locate.c for explanation as to why not use (String) */
50 # define N_(String) String
54 struct debug_option_assoc
60 static struct debug_option_assoc debugassoc
[] =
62 { "help", DebugHelp
, "Explain the various -D options" },
63 { "tree", DebugExpressionTree
, "Display the expression tree" },
64 { "search",DebugSearch
, "Navigate the directory tree verbosely" },
65 { "stat", DebugStat
, "Trace calls to stat(2) and lstat(2)" },
66 { "rates", DebugSuccessRates
, "Indicate how often each predicate succeeded" },
67 { "opt", DebugExpressionTree
|DebugTreeOpt
, "Show diagnostic information relating to optimisation" },
68 { "exec", DebugExec
, "Show diagnostic information relating to -exec, -execdir, -ok and -okdir" }
70 #define N_DEBUGASSOC (sizeof(debugassoc)/sizeof(debugassoc[0]))
75 /* Add a primary of predicate type PRED_FUNC (described by ENTRY) to the predicate input list.
77 Return a pointer to the predicate node just inserted.
79 Fills in the following cells of the new predicate node:
86 Other cells that need to be filled in are defaulted by
87 get_new_pred_chk_op, which is used to insure that the prior node is
88 either not there at all (we are the very first node) or is an
92 insert_primary_withpred (const struct parser_table
*entry
, PRED_FUNC pred_func
)
94 struct predicate
*new_pred
;
96 new_pred
= get_new_pred_chk_op (entry
);
97 new_pred
->pred_func
= pred_func
;
98 new_pred
->p_name
= entry
->parser_name
;
99 new_pred
->args
.str
= NULL
;
100 new_pred
->p_type
= PRIMARY_TYPE
;
101 new_pred
->p_prec
= NO_PREC
;
105 /* Add a primary described by ENTRY to the predicate input list.
107 Return a pointer to the predicate node just inserted.
109 Fills in the following cells of the new predicate node:
116 Other cells that need to be filled in are defaulted by
117 get_new_pred_chk_op, which is used to insure that the prior node is
118 either not there at all (we are the very first node) or is an
121 insert_primary (const struct parser_table
*entry
)
123 assert (entry
->pred_func
!= NULL
);
124 return insert_primary_withpred(entry
, entry
->pred_func
);
130 show_valid_debug_options(FILE *fp
, int full
)
135 fprintf(fp
, "Valid arguments for -D:\n");
136 for (i
=0; i
<N_DEBUGASSOC
; ++i
)
138 fprintf(fp
, "%-10s %s\n",
140 debugassoc
[i
].docstring
);
145 for (i
=0; i
<N_DEBUGASSOC
; ++i
)
147 fprintf(fp
, "%s%s", (i
>0 ? "|" : ""), debugassoc
[i
].name
);
153 usage (FILE *fp
, int status
, char *msg
)
156 fprintf (fp
, "%s: %s\n", program_name
, msg
);
158 fprintf (fp
, _("Usage: %s [-H] [-L] [-P] [-Olevel] [-D "), program_name
);
159 show_valid_debug_options(fp
, 0);
160 fprintf (fp
, _("] [path...] [expression]\n"));
166 set_stat_placeholders(struct stat
*p
)
168 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
171 #if HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC
172 p
->st_birthtimensec
= 0;
174 #if HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC
175 p
->st_birthtimespec
.tv_nsec
= -1;
177 #if HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_SEC
178 p
->st_birthtimespec
.tv_sec
= 0;
183 /* Get the stat information for a file, if it is
187 get_statinfo (const char *pathname
, const char *name
, struct stat
*p
)
189 /* Set markers in fields so we have a good idea if the implementation
190 * didn't bother to set them (e.g., NetBSD st_birthtimespec for MS-DOS
193 if (!state
.have_stat
)
195 set_stat_placeholders(p
);
196 if (0 == (*options
.xstat
) (name
, p
))
198 if (00000 == p
->st_mode
)
200 /* Savannah bug #16378. */
201 error(0, 0, _("Warning: file %s appears to have mode 0000"),
202 quotearg_n_style(0, options
.err_quoting_style
, name
));
207 if (!options
.ignore_readdir_race
|| (errno
!= ENOENT
) )
209 error (0, errno
, "%s",
210 safely_quote_err_filename(0, pathname
));
211 state
.exit_status
= 1;
216 state
.have_stat
= true;
217 state
.have_type
= true;
218 state
.type
= p
->st_mode
;
224 /* Get the stat/type information for a file, if it is
228 get_info (const char *pathname
,
230 struct predicate
*pred_ptr
)
232 boolean todo
= false;
234 /* If we need the full stat info, or we need the type info but don't
235 * already have it, stat the file now.
237 if (pred_ptr
->need_stat
)
239 else if ((pred_ptr
->need_type
&& (0 == state
.have_type
)))
243 return get_statinfo(pathname
, state
.rel_pathname
, p
);
248 /* Determine if we can use O_NOFOLLOW.
250 #if defined O_NOFOLLOW
262 if (0 == uname(&uts
))
264 /* POSIX requires that atof() ignore "unrecognised suffixes". */
265 release
= atof(uts
.release
);
267 if (0 == strcmp("Linux", uts
.sysname
))
269 /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
270 return release
>= 2.2; /* close enough */
272 else if (0 == strcmp("FreeBSD", uts
.sysname
))
274 /* FreeBSD 3.0-CURRENT and later support it */
275 return release
>= 3.1;
279 /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
286 /* Examine the predicate list for instances of -execdir or -okdir
287 * which have been terminated with '+' (build argument list) rather
288 * than ';' (singles only). If there are any, run them (this will
289 * have no effect if there are no arguments waiting).
292 do_complete_pending_execdirs(struct predicate
*p
, int dir_fd
)
297 assert (state
.execdirs_outstanding
);
299 do_complete_pending_execdirs(p
->pred_left
, dir_fd
);
301 if (pred_is(p
, pred_execdir
) || pred_is(p
, pred_okdir
))
303 /* It's an exec-family predicate. p->args.exec_val is valid. */
304 if (p
->args
.exec_vec
.multiple
)
306 struct exec_val
*execp
= &p
->args
.exec_vec
;
308 /* This one was terminated by '+' and so might have some
309 * left... Run it if necessary.
311 if (execp
->state
.todo
)
313 /* There are not-yet-executed arguments. */
314 launch (&execp
->ctl
, &execp
->state
);
319 do_complete_pending_execdirs(p
->pred_right
, dir_fd
);
323 complete_pending_execdirs(int dir_fd
)
325 if (state
.execdirs_outstanding
)
327 do_complete_pending_execdirs(get_eval_tree(), dir_fd
);
328 state
.execdirs_outstanding
= false;
334 /* Examine the predicate list for instances of -exec which have been
335 * terminated with '+' (build argument list) rather than ';' (singles
336 * only). If there are any, run them (this will have no effect if
337 * there are no arguments waiting).
340 complete_pending_execs(struct predicate
*p
)
345 complete_pending_execs(p
->pred_left
);
347 /* It's an exec-family predicate then p->args.exec_val is valid
348 * and we can check it.
350 /* XXX: what about pred_ok() ? */
351 if (pred_is(p
, pred_exec
) && p
->args
.exec_vec
.multiple
)
353 struct exec_val
*execp
= &p
->args
.exec_vec
;
355 /* This one was terminated by '+' and so might have some
356 * left... Run it if necessary. Set state.exit_status if
357 * there are any problems.
359 if (execp
->state
.todo
)
361 /* There are not-yet-executed arguments. */
362 launch (&execp
->ctl
, &execp
->state
);
366 complete_pending_execs(p
->pred_right
);
370 traverse_tree(struct predicate
*tree
,
371 void (*callback
)(struct predicate
*))
374 traverse_tree(tree
->pred_left
, callback
);
378 if (tree
->pred_right
)
379 traverse_tree(tree
->pred_right
, callback
);
383 flush_and_close_output_files(struct predicate
*p
)
385 if (pred_is(p
, pred_fprint
)
386 || pred_is(p
, pred_fprintf
)
387 || pred_is(p
, pred_fls
)
388 || pred_is(p
, pred_fprint0
))
390 FILE *f
= p
->args
.printf_vec
.stream
;
393 if (f
== stdout
|| f
== stderr
)
394 failed
= fflush(p
->args
.printf_vec
.stream
) == EOF
;
396 failed
= fclose(p
->args
.printf_vec
.stream
) == EOF
;
399 nonfatal_file_error(p
->args
.printf_vec
.filename
);
401 else if (pred_is(p
, pred_print
))
403 if (fflush(p
->args
.printf_vec
.stream
) == EOF
)
405 nonfatal_file_error(p
->args
.printf_vec
.filename
);
408 else if (pred_is(p
, pred_ls
) || pred_is(p
, pred_print0
))
410 if (fflush(stdout
) == EOF
)
412 /* XXX: migrate to printf_vec. */
413 nonfatal_file_error("standard output");
418 /* Complete any outstanding commands.
423 struct predicate
*eval_tree
= get_eval_tree();
426 traverse_tree(eval_tree
, complete_pending_execs
);
427 complete_pending_execdirs(get_current_dirfd());
428 traverse_tree(eval_tree
, flush_and_close_output_files
);
432 /* Savannah bug #16378 manifests as an assertion failure in pred_type()
433 * when an NFS server returns st_mode with value 0 (of course the stat(2)
434 * system call is itself returning 0 in this case).
436 #undef DEBUG_SV_BUG_16378
437 #if defined DEBUG_SV_BUG_16378
438 static int hook_fstatat(int fd
, const char *name
, struct stat
*p
, int flags
)
440 static int warned
= 0;
444 /* No use of _() here; no point asking translators to translate a debug msg */
446 "Warning: some debug code is enabled for Savannah bug #16378; "
447 "this should not occur in released versions of findutils!");
451 if (0 == strcmp(name
, "./mode0file")
452 || 0 == strcmp(name
, "mode0file"))
454 time_t now
= time(NULL
);
460 p
->st_mode
= 0; /* SV bug #16378 */
462 p
->st_uid
= geteuid();
465 p
->st_blksize
= 32768;
466 p
->st_atime
= now
-1*day
;
467 p
->st_mtime
= now
-2*day
;
468 p
->st_ctime
= now
-3*day
;
472 return fstatat(fd
, name
, p
, flags
);
476 # define fstatat(fd,name,p,flags) hook_fstatat((fd),(name),(p),(flags))
481 fallback_stat(const char *name
, struct stat
*p
, int prev_rv
)
483 /* Our original stat() call failed. Perhaps we can't follow a
484 * symbolic link. If that might be the problem, lstat() the link.
485 * Otherwise, admit defeat.
491 if (options
.debug_options
& DebugStat
)
492 fprintf(stderr
, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name
);
493 return fstatat(state
.cwd_dir_fd
, name
, p
, AT_SYMLINK_NOFOLLOW
);
500 case EOVERFLOW
: /* EOVERFLOW is not #defined on UNICOS. */
508 /* optionh_stat() implements the stat operation when the -H option is
511 * If the item to be examined is a command-line argument, we follow
512 * symbolic links. If the stat() call fails on the command-line item,
513 * we fall back on the properties of the symbolic link.
515 * If the item to be examined is not a command-line argument, we
516 * examine the link itself.
519 optionh_stat(const char *name
, struct stat
*p
)
521 if (AT_FDCWD
!= state
.cwd_dir_fd
)
522 assert (state
.cwd_dir_fd
>= 0);
523 set_stat_placeholders(p
);
524 if (0 == state
.curdepth
)
526 /* This file is from the command line; deference the link (if it
530 rv
= fstatat(state
.cwd_dir_fd
, name
, p
, 0);
532 return 0; /* success */
534 return fallback_stat(name
, p
, rv
);
538 /* Not a file on the command line; do not dereference the link.
540 return fstatat(state
.cwd_dir_fd
, name
, p
, AT_SYMLINK_NOFOLLOW
);
544 /* optionl_stat() implements the stat operation when the -L option is
545 * in effect. That option makes us examine the thing the symbolic
546 * link points to, not the symbolic link itself.
549 optionl_stat(const char *name
, struct stat
*p
)
552 if (AT_FDCWD
!= state
.cwd_dir_fd
)
553 assert (state
.cwd_dir_fd
>= 0);
555 set_stat_placeholders(p
);
556 rv
= fstatat(state
.cwd_dir_fd
, name
, p
, 0);
558 return 0; /* normal case. */
560 return fallback_stat(name
, p
, rv
);
563 /* optionp_stat() implements the stat operation when the -P option is
564 * in effect (this is also the default). That option makes us examine
565 * the symbolic link itself, not the thing it points to.
568 optionp_stat(const char *name
, struct stat
*p
)
570 assert ((state
.cwd_dir_fd
>= 0) || (state
.cwd_dir_fd
==AT_FDCWD
));
571 set_stat_placeholders(p
);
572 return fstatat(state
.cwd_dir_fd
, name
, p
, AT_SYMLINK_NOFOLLOW
);
576 static uintmax_t stat_count
= 0u;
579 debug_stat (const char *file
, struct stat
*bufp
)
582 fprintf (stderr
, "debug_stat (%s)\n", file
);
584 switch (options
.symlink_handling
)
586 case SYMLINK_ALWAYS_DEREF
:
587 return optionl_stat(file
, bufp
);
588 case SYMLINK_DEREF_ARGSONLY
:
589 return optionh_stat(file
, bufp
);
590 case SYMLINK_NEVER_DEREF
:
591 return optionp_stat(file
, bufp
);
600 following_links(void)
602 switch (options
.symlink_handling
)
604 case SYMLINK_ALWAYS_DEREF
:
606 case SYMLINK_DEREF_ARGSONLY
:
607 return (state
.curdepth
== 0);
608 case SYMLINK_NEVER_DEREF
:
615 /* Take a "mode" indicator and fill in the files of 'state'.
618 digest_mode(mode_t mode
,
619 const char *pathname
,
624 /* If we know the type of the directory entry, and it is not a
625 * symbolic link, we may be able to avoid a stat() or lstat() call.
629 if (S_ISLNK(mode
) && following_links())
631 /* mode is wrong because we should have followed the symlink. */
632 if (get_statinfo(pathname
, name
, pstat
) != 0)
634 mode
= state
.type
= pstat
->st_mode
;
635 state
.have_type
= true;
639 state
.have_type
= true;
640 pstat
->st_mode
= state
.type
= mode
;
645 /* Mode is not yet known; may have to stat the file unless we
646 * can deduce that it is not a directory (which is all we need to
647 * know at this stage)
651 state
.have_stat
= false;
652 state
.have_type
= false;;
657 if (get_statinfo(pathname
, name
, pstat
) != 0)
660 /* If -L is in effect and we are dealing with a symlink,
661 * st_mode is the mode of the pointed-to file, while mode is
662 * the mode of the directory entry (S_IFLNK). Hence now
663 * that we have the stat information, override "mode".
665 state
.type
= pstat
->st_mode
;
666 state
.have_type
= true;
675 /* Return true if there are no predicates with no_default_print in
676 predicate list PRED, false if there are any.
677 Returns true if default print should be performed */
680 default_prints (struct predicate
*pred
)
684 if (pred
->no_default_print
)
686 pred
= pred
->pred_next
;
692 looks_like_expression(const char *arg
, boolean leading
)
697 if (arg
[1]) /* "-foo" is an expression. */
700 return false; /* Just "-" is a filename. */
706 return false; /* )x and ,z are not expressions */
708 return !leading
; /* A leading ) or , is not either */
710 /* ( and ! are part of an expression, but (2 and !foo are
726 process_debug_options(char *arg
)
729 char *token_context
= NULL
;
730 const char delimiters
[] = ",";
731 boolean empty
= true;
734 p
= strtok_r(arg
, delimiters
, &token_context
);
739 for (i
=0; i
<N_DEBUGASSOC
; ++i
)
741 if (0 == strcmp(debugassoc
[i
].name
, p
))
743 options
.debug_options
|= debugassoc
[i
].val
;
747 if (i
>= N_DEBUGASSOC
)
749 error(0, 0, _("Ignoring unrecognised debug flag %s"),
750 quotearg_n_style(0, options
.err_quoting_style
, arg
));
752 p
= strtok_r(NULL
, delimiters
, &token_context
);
756 error(1, 0, _("Empty argument to the -D option."));
758 else if (options
.debug_options
& DebugHelp
)
760 show_valid_debug_options(stdout
, 1);
766 process_optimisation_option(const char *arg
)
770 error(1, 0, _("The -O option must be immediately followed by a decimal integer"));
774 unsigned long opt_level
;
777 if (!isdigit( (unsigned char) arg
[0] ))
779 error(1, 0, _("Please specify a decimal number immediately after -O"));
783 int prev_errno
= errno
;
786 opt_level
= strtoul(arg
, &end
, 10);
787 if ( (0==opt_level
) && (end
==arg
) )
789 error(1, 0, _("Please specify a decimal number immediately after -O"));
793 /* unwanted trailing characters. */
794 error(1, 0, _("Invalid optimisation level %s"), arg
);
796 else if ( (ULONG_MAX
==opt_level
) && errno
)
798 error(1, errno
, _("Invalid optimisation level %s"), arg
);
800 else if (opt_level
> USHRT_MAX
)
802 /* tricky to test, as on some platforms USHORT_MAX and ULONG_MAX
803 * can have the same value, though this is unusual.
805 error(1, 0, _("Optimisation level %lu is too high. "
806 "If you want to find files very quickly, "
807 "consider using GNU locate."),
812 options
.optimisation_level
= opt_level
;
820 process_leading_options(int argc
, char *argv
[])
822 int i
, end_of_leading_options
;
824 for (i
=1; (end_of_leading_options
= i
) < argc
; ++i
)
826 if (0 == strcmp("-H", argv
[i
]))
828 /* Meaning: dereference symbolic links on command line, but nowhere else. */
829 set_follow_state(SYMLINK_DEREF_ARGSONLY
);
831 else if (0 == strcmp("-L", argv
[i
]))
833 /* Meaning: dereference all symbolic links. */
834 set_follow_state(SYMLINK_ALWAYS_DEREF
);
836 else if (0 == strcmp("-P", argv
[i
]))
838 /* Meaning: never dereference symbolic links (default). */
839 set_follow_state(SYMLINK_NEVER_DEREF
);
841 else if (0 == strcmp("--", argv
[i
]))
843 /* -- signifies the end of options. */
844 end_of_leading_options
= i
+1; /* Next time start with the next option */
847 else if (0 == strcmp("-D", argv
[i
]))
849 process_debug_options(argv
[i
+1]);
850 ++i
; /* skip the argument too. */
852 else if (0 == strncmp("-O", argv
[i
], 2))
854 process_optimisation_option(argv
[i
]+2);
858 /* Hmm, must be one of
862 end_of_leading_options
= i
; /* Next time start with this option */
866 return end_of_leading_options
;
869 static struct timespec
872 struct timespec retval
;
876 if (0 == gettimeofday(&tv
, NULL
))
878 retval
.tv_sec
= tv
.tv_sec
;
879 retval
.tv_nsec
= tv
.tv_usec
* 1000; /* convert unit from microseconds to nanoseconds */
883 assert (t
!= (time_t)-1);
890 set_option_defaults(struct options
*p
)
892 if (getenv("POSIXLY_CORRECT"))
893 p
->posixly_correct
= true;
895 p
->posixly_correct
= false;
897 /* We call check_nofollow() before setlocale() because the numbers
898 * for which we check (in the results of uname) definitiely have "."
899 * as the decimal point indicator even under locales for which that
900 * is not normally true. Hence atof() would do the wrong thing
901 * if we call it after setlocale().
904 p
->open_nofollow_available
= check_nofollow();
906 p
->open_nofollow_available
= false;
909 p
->regex_options
= RE_SYNTAX_EMACS
;
914 p
->literal_control_chars
= false;
919 p
->literal_control_chars
= false; /* may change */
921 if (p
->posixly_correct
)
926 p
->do_dir_first
= true;
927 p
->explicit_depth
= false;
928 p
->maxdepth
= p
->mindepth
= -1;
930 p
->start_time
= now();
931 p
->cur_day_start
.tv_sec
= p
->start_time
.tv_sec
- DAYSECS
;
932 p
->cur_day_start
.tv_nsec
= p
->start_time
.tv_nsec
;
934 p
->full_days
= false;
935 p
->stay_on_filesystem
= false;
936 p
->ignore_readdir_race
= false;
938 if (p
->posixly_correct
)
939 p
->output_block_size
= 512;
941 p
->output_block_size
= 1024;
943 p
->debug_options
= 0uL;
944 p
->optimisation_level
= 2;
946 if (getenv("FIND_BLOCK_SIZE"))
948 error (1, 0, _("The environment variable FIND_BLOCK_SIZE is not supported, the only thing that affects the block size is the POSIXLY_CORRECT environment variable"));
951 #if LEAF_OPTIMISATION
952 /* The leaf optimisation is enabled. */
953 p
->no_leaf_check
= false;
955 /* The leaf optimisation is disabled. */
956 p
->no_leaf_check
= true;
959 set_follow_state(SYMLINK_NEVER_DEREF
); /* The default is equivalent to -P. */
961 p
->err_quoting_style
= locale_quoting_style
;
967 * Returns the fd for the directory we started in.
969 int get_start_dirfd(void)
971 return starting_desc
;
978 apply_predicate(const char *pathname
, struct stat
*stat_buf
, struct predicate
*p
)
982 if (p
->need_stat
|| p
->need_type
)
984 /* We may need a stat here. */
985 if (get_info(pathname
, stat_buf
, p
) != 0)
988 if ((p
->pred_func
)(pathname
, stat_buf
, p
))
990 ++(p
->perf
.successes
);
1000 /* safely_quote_err_filename
1004 safely_quote_err_filename (int n
, char const *arg
)
1006 return quotearg_n_style (n
, options
.err_quoting_style
, arg
);
1012 report_file_err(int exitval
, int errno_value
, const char *name
)
1014 /* It is important that the errno value is passed in as a function
1015 * argument before we call safely_quote_err_filename(), because otherwise
1016 * we might find that safely_quote_err_filename() changes errno.
1018 if (state
.exit_status
< 1)
1019 state
.exit_status
= 1;
1021 error (exitval
, errno_value
, "%s", safely_quote_err_filename(0, name
));
1028 fatal_file_error(const char *name
)
1030 report_file_err(1, errno
, name
);
1036 nonfatal_file_error(const char *name
)
1038 report_file_err(0, errno
, name
);