5 kx /* util.c -- functions for initializing new tree elements, and other things.
5 kx Copyright (C) 1990-2021 Free Software Foundation, Inc.
5 kx
5 kx This program is free software: you can redistribute it and/or modify
5 kx it under the terms of the GNU General Public License as published by
5 kx the Free Software Foundation, either version 3 of the License, or
5 kx (at your option) any later version.
5 kx
5 kx This program is distributed in the hope that it will be useful,
5 kx but WITHOUT ANY WARRANTY; without even the implied warranty of
5 kx MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
5 kx GNU General Public License for more details.
5 kx
5 kx You should have received a copy of the GNU General Public License
5 kx along with this program. If not, see <https://www.gnu.org/licenses/>.
5 kx */
5 kx
5 kx /* config.h must always come first. */
5 kx #include <config.h>
5 kx
5 kx /* system headers. */
5 kx #include <assert.h>
5 kx #include <ctype.h>
5 kx #include <errno.h>
5 kx #include <fcntl.h>
5 kx #include <limits.h>
5 kx #include <string.h>
5 kx #include <sys/stat.h> /* for fstatat() */
5 kx #include <sys/time.h>
5 kx #include <sys/utsname.h>
5 kx
5 kx /* gnulib headers. */
5 kx #include "error.h"
5 kx #include "fdleak.h"
5 kx #include "progname.h"
5 kx #include "quotearg.h"
5 kx #include "save-cwd.h"
5 kx #include "timespec.h"
5 kx #include "xalloc.h"
5 kx
5 kx /* find headers. */
5 kx #include "defs.h"
5 kx #include "die.h"
5 kx #include "dircallback.h"
5 kx #include "bugreports.h"
5 kx #include "system.h"
5 kx
5 kx
5 kx struct debug_option_assoc
5 kx {
5 kx const char *name;
5 kx int val;
5 kx const char *docstring;
5 kx };
5 kx static struct debug_option_assoc debugassoc[] =
5 kx {
5 kx { "exec", DebugExec, "Show diagnostic information relating to -exec, -execdir, -ok and -okdir" },
5 kx { "opt", DebugExpressionTree|DebugTreeOpt, "Show diagnostic information relating to optimisation" },
5 kx { "rates", DebugSuccessRates, "Indicate how often each predicate succeeded" },
5 kx { "search",DebugSearch, "Navigate the directory tree verbosely" },
5 kx { "stat", DebugStat, "Trace calls to stat(2) and lstat(2)" },
5 kx { "time", DebugTime, "Show diagnostic information relating to time-of-day and timestamp comparisons" },
5 kx { "tree", DebugExpressionTree, "Display the expression tree" },
5 kx
5 kx { "all", DebugAll, "Set all of the debug flags (but help)" },
5 kx { "help", DebugHelp, "Explain the various -D options" },
5 kx };
5 kx #define N_DEBUGASSOC (sizeof(debugassoc)/sizeof(debugassoc[0]))
5 kx
5 kx
5 kx
5 kx
5 kx /* Add a primary of predicate type PRED_FUNC (described by ENTRY) to the predicate input list.
5 kx
5 kx Return a pointer to the predicate node just inserted.
5 kx
5 kx Fills in the following cells of the new predicate node:
5 kx
5 kx pred_func PRED_FUNC
5 kx args(.str) NULL
5 kx p_type PRIMARY_TYPE
5 kx p_prec NO_PREC
5 kx
5 kx Other cells that need to be filled in are defaulted by
5 kx get_new_pred_chk_op, which is used to ensure that the prior node is
5 kx either not there at all (we are the very first node) or is an
5 kx operator. */
5 kx
5 kx struct predicate *
5 kx insert_primary_withpred (const struct parser_table *entry,
5 kx PRED_FUNC pred_func,
5 kx const char *arg)
5 kx {
5 kx struct predicate *new_pred;
5 kx
5 kx new_pred = get_new_pred_chk_op (entry, arg);
5 kx new_pred->pred_func = pred_func;
5 kx new_pred->p_name = entry->parser_name;
5 kx new_pred->args.str = NULL;
5 kx new_pred->p_type = PRIMARY_TYPE;
5 kx new_pred->p_prec = NO_PREC;
5 kx return new_pred;
5 kx }
5 kx
5 kx /* Add a primary described by ENTRY to the predicate input list.
5 kx
5 kx Return a pointer to the predicate node just inserted.
5 kx
5 kx Fills in the following cells of the new predicate node:
5 kx
5 kx pred_func PRED_FUNC
5 kx args(.str) NULL
5 kx p_type PRIMARY_TYPE
5 kx p_prec NO_PREC
5 kx
5 kx Other cells that need to be filled in are defaulted by
5 kx get_new_pred_chk_op, which is used to insure that the prior node is
5 kx either not there at all (we are the very first node) or is an
5 kx operator. */
5 kx struct predicate *
5 kx insert_primary (const struct parser_table *entry, const char *arg)
5 kx {
5 kx assert (entry->pred_func != NULL);
5 kx return insert_primary_withpred (entry, entry->pred_func, arg);
5 kx }
5 kx
5 kx struct predicate *
5 kx insert_primary_noarg (const struct parser_table *entry)
5 kx {
5 kx return insert_primary (entry, NULL);
5 kx }
5 kx
5 kx
5 kx
5 kx static void
5 kx show_valid_debug_options (int full)
5 kx {
5 kx size_t i;
5 kx fputs (_("Valid arguments for -D:\n"), stdout);
5 kx if (full)
5 kx {
5 kx for (i=0; i<N_DEBUGASSOC; ++i)
5 kx {
5 kx fprintf (stdout, "%-10s %s\n",
5 kx debugassoc[i].name,
5 kx debugassoc[i].docstring);
5 kx }
5 kx }
5 kx else
5 kx {
5 kx for (i=0; i<N_DEBUGASSOC; ++i)
5 kx {
5 kx fprintf (stdout, "%s%s", (i>0 ? ", " : ""), debugassoc[i].name);
5 kx }
5 kx }
5 kx }
5 kx
5 kx void
5 kx usage (int status)
5 kx {
5 kx if (status != EXIT_SUCCESS)
5 kx {
5 kx fprintf (stderr, _("Try '%s --help' for more information.\n"), program_name);
5 kx exit (status);
5 kx }
5 kx
5 kx #define HTL(t) fputs (t, stdout);
5 kx
5 kx fprintf (stdout, _("\
5 kx Usage: %s [-H] [-L] [-P] [-Olevel] [-D debugopts] [path...] [expression]\n"),
5 kx program_name);
5 kx
5 kx HTL (_("\n\
5 kx default path is the current directory; default expression is -print\n\
5 kx expression may consist of: operators, options, tests, and actions:\n"));
5 kx HTL (_("\
5 kx operators (decreasing precedence; -and is implicit where no others are given):\n\
5 kx ( EXPR ) ! EXPR -not EXPR EXPR1 -a EXPR2 EXPR1 -and EXPR2\n\
5 kx EXPR1 -o EXPR2 EXPR1 -or EXPR2 EXPR1 , EXPR2\n"));
5 kx HTL (_("\
5 kx positional options (always true): -daystart -follow -regextype\n\n\
5 kx normal options (always true, specified before other expressions):\n\
5 kx -depth --help -maxdepth LEVELS -mindepth LEVELS -mount -noleaf\n\
5 kx --version -xdev -ignore_readdir_race -noignore_readdir_race\n"));
5 kx HTL (_("\
5 kx tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N\n\
5 kx -cnewer FILE -ctime N -empty -false -fstype TYPE -gid N -group NAME\n\
5 kx -ilname PATTERN -iname PATTERN -inum N -iwholename PATTERN -iregex PATTERN\n\
5 kx -links N -lname PATTERN -mmin N -mtime N -name PATTERN -newer FILE"));
5 kx HTL (_("\n\
5 kx -nouser -nogroup -path PATTERN -perm [-/]MODE -regex PATTERN\n\
5 kx -readable -writable -executable\n\
5 kx -wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N\n\
5 kx -used N -user NAME -xtype [bcdpfls]"));
5 kx HTL (_("\
5 kx -context CONTEXT\n"));
5 kx HTL (_("\n\
5 kx actions: -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print \n\
5 kx -fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit\n\
5 kx -exec COMMAND ; -exec COMMAND {} + -ok COMMAND ;\n\
5 kx -execdir COMMAND ; -execdir COMMAND {} + -okdir COMMAND ;\n\
5 kx \n"));
5 kx
5 kx show_valid_debug_options (0);
5 kx HTL (_("\n\
5 kx Use '-D help' for a description of the options, or see find(1)\n\
5 kx \n"));
5 kx
5 kx explain_how_to_report_bugs (stdout, program_name);
5 kx exit (status);
5 kx }
5 kx
5 kx void
5 kx set_stat_placeholders (struct stat *p)
5 kx {
5 kx (void) p; /* silence warning for systems lacking these fields. */
5 kx #if HAVE_STRUCT_STAT_ST_BIRTHTIME
5 kx p->st_birthtime = 0;
5 kx #endif
5 kx #if HAVE_STRUCT_STAT_ST_BIRTHTIMENSEC
5 kx p->st_birthtimensec = 0;
5 kx #endif
5 kx #if HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC
5 kx p->st_birthtimespec.tv_nsec = -1;
5 kx #endif
5 kx #if HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_SEC
5 kx p->st_birthtimespec.tv_sec = 0;
5 kx #else
5 kx /* Avoid pointless compiler warning about unused parameters if none of these
5 kx macros are set to nonzero values. */
5 kx (void) p;
5 kx #endif
5 kx }
5 kx
5 kx
5 kx /* Get the stat information for a file, if it is
5 kx * not already known. Returns 0 on success.
5 kx */
5 kx int
5 kx get_statinfo (const char *pathname, const char *name, struct stat *p)
5 kx {
5 kx /* Set markers in fields so we have a good idea if the implementation
5 kx * didn't bother to set them (e.g., NetBSD st_birthtimespec for MS-DOS
5 kx * files)
5 kx */
5 kx if (!state.have_stat)
5 kx {
5 kx set_stat_placeholders (p);
5 kx if (0 == (*options.xstat) (name, p))
5 kx {
5 kx if (00000 == p->st_mode)
5 kx {
5 kx /* Savannah bug #16378. */
5 kx error (0, 0, _("WARNING: file %s appears to have mode 0000"),
5 kx quotearg_n_style (0, options.err_quoting_style, name));
5 kx error_severity (1);
5 kx }
5 kx }
5 kx else
5 kx {
5 kx if (!options.ignore_readdir_race || (errno != ENOENT) )
5 kx {
5 kx nonfatal_target_file_error (errno, pathname);
5 kx }
5 kx return -1;
5 kx }
5 kx }
5 kx state.have_stat = true;
5 kx state.have_type = true;
5 kx state.type = p->st_mode;
5 kx
5 kx return 0;
5 kx }
5 kx
5 kx /* Get the stat/type/inode information for a file, if it is not
5 kx * already known. Returns 0 on success (or if we did nothing).
5 kx */
5 kx int
5 kx get_info (const char *pathname,
5 kx struct stat *p,
5 kx struct predicate *pred_ptr)
5 kx {
5 kx bool todo = false;
5 kx
5 kx /* If we need the full stat info, or we need the type info but don't
5 kx * already have it, stat the file now.
5 kx */
5 kx if (pred_ptr->need_stat)
5 kx {
5 kx todo = true; /* need full stat info */
5 kx }
5 kx else if (pred_ptr->need_type && !state.have_type)
5 kx {
5 kx todo = true; /* need to stat to get the type */
5 kx }
5 kx else if (pred_ptr->need_inum)
5 kx {
5 kx if (!p->st_ino)
5 kx {
5 kx todo = true; /* need to stat to get the inode number */
5 kx }
5 kx else if ((!state.have_type) || S_ISDIR(p->st_mode))
5 kx {
5 kx /* For now we decide not to trust struct dirent.d_ino for
5 kx * directory entries that are subdirectories, in case this
5 kx * subdirectory is a mount point. We also need to call a
5 kx * stat function if we don't have st_ino (i.e. it is zero).
5 kx */
5 kx todo = true;
5 kx }
5 kx }
5 kx if (todo)
5 kx {
5 kx int result = get_statinfo (pathname, state.rel_pathname, p);
5 kx if (result != 0)
5 kx {
5 kx return -1; /* failure. */
5 kx }
5 kx else
5 kx {
5 kx /* Verify some postconditions. We can't check st_mode for
5 kx non-zero-ness because of Savannah bug #16378 (which is
5 kx that broken NFS servers can return st_mode==0). */
5 kx if (pred_ptr->need_type)
5 kx {
5 kx assert (state.have_type);
5 kx }
5 kx if (pred_ptr->need_inum)
5 kx {
5 kx assert (p->st_ino);
5 kx }
5 kx return 0; /* success. */
5 kx }
5 kx }
5 kx else
5 kx {
5 kx return 0; /* success; nothing to do. */
5 kx }
5 kx }
5 kx
5 kx /* Determine if we can use O_NOFOLLOW.
5 kx */
5 kx #if defined O_NOFOLLOW
5 kx bool
5 kx check_nofollow (void)
5 kx {
5 kx struct utsname uts;
5 kx float release;
5 kx
5 kx if (0 == O_NOFOLLOW)
5 kx {
5 kx return false;
5 kx }
5 kx
5 kx if (0 == uname (&uts))
5 kx {
5 kx /* POSIX requires that atof ignores "unrecognised suffixes"; we specifically
5 kx * want that behaviour. */
5 kx double (*conversion)(const char*) = atof; /* avoid sc_prohibit_atoi_atof check. */
5 kx release = conversion (uts.release);
5 kx
5 kx if (0 == strcmp ("Linux", uts.sysname))
5 kx {
5 kx /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
5 kx return release >= 2.2f; /* close enough */
5 kx }
5 kx else if (0 == strcmp ("FreeBSD", uts.sysname))
5 kx {
5 kx /* FreeBSD 3.0-CURRENT and later support it */
5 kx return release >= 3.1f;
5 kx }
5 kx }
5 kx
5 kx /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
5 kx return true;
5 kx }
5 kx #endif
5 kx
5 kx
5 kx static int
5 kx exec_cb (void *context)
5 kx {
5 kx struct exec_val *execp = context;
5 kx bc_do_exec (&execp->ctl, &execp->state);
5 kx return 0;
5 kx }
5 kx
5 kx static void
5 kx do_exec (struct exec_val *execp)
5 kx {
5 kx run_in_dir (execp->wd_for_exec, exec_cb, execp);
5 kx if (execp->wd_for_exec != initial_wd)
5 kx {
5 kx free_cwd (execp->wd_for_exec);
5 kx free (execp->wd_for_exec);
5 kx execp->wd_for_exec = NULL;
5 kx }
5 kx }
5 kx
5 kx
5 kx /* Examine the predicate list for instances of -execdir or -okdir
5 kx * which have been terminated with '+' (build argument list) rather
5 kx * than ';' (singles only). If there are any, run them (this will
5 kx * have no effect if there are no arguments waiting).
5 kx */
5 kx static void
5 kx do_complete_pending_execdirs (struct predicate *p)
5 kx {
5 kx if (NULL == p)
5 kx return;
5 kx
5 kx assert (state.execdirs_outstanding);
5 kx
5 kx do_complete_pending_execdirs (p->pred_left);
5 kx
5 kx if (pred_is (p, pred_execdir) || pred_is(p, pred_okdir))
5 kx {
5 kx /* It's an exec-family predicate. p->args.exec_val is valid. */
5 kx if (p->args.exec_vec.multiple)
5 kx {
5 kx struct exec_val *execp = &p->args.exec_vec;
5 kx
5 kx /* This one was terminated by '+' and so might have some
5 kx * left... Run it if necessary.
5 kx */
5 kx if (execp->state.todo)
5 kx {
5 kx /* There are not-yet-executed arguments. */
5 kx do_exec (execp);
5 kx }
5 kx }
5 kx }
5 kx
5 kx do_complete_pending_execdirs (p->pred_right);
5 kx }
5 kx
5 kx void
5 kx complete_pending_execdirs (void)
5 kx {
5 kx if (state.execdirs_outstanding)
5 kx {
5 kx do_complete_pending_execdirs (get_eval_tree());
5 kx state.execdirs_outstanding = false;
5 kx }
5 kx }
5 kx
5 kx
5 kx
5 kx /* Examine the predicate list for instances of -exec which have been
5 kx * terminated with '+' (build argument list) rather than ';' (singles
5 kx * only). If there are any, run them (this will have no effect if
5 kx * there are no arguments waiting).
5 kx */
5 kx void
5 kx complete_pending_execs (struct predicate *p)
5 kx {
5 kx if (NULL == p)
5 kx return;
5 kx
5 kx complete_pending_execs (p->pred_left);
5 kx
5 kx /* It's an exec-family predicate then p->args.exec_val is valid
5 kx * and we can check it.
5 kx */
5 kx /* XXX: what about pred_ok() ? */
5 kx if (pred_is (p, pred_exec) && p->args.exec_vec.multiple)
5 kx {
5 kx struct exec_val *execp = &p->args.exec_vec;
5 kx
5 kx /* This one was terminated by '+' and so might have some
5 kx * left... Run it if necessary. Set state.exit_status if
5 kx * there are any problems.
5 kx */
5 kx if (execp->state.todo)
5 kx {
5 kx /* There are not-yet-executed arguments. */
5 kx bc_do_exec (&execp->ctl, &execp->state);
5 kx }
5 kx }
5 kx
5 kx complete_pending_execs (p->pred_right);
5 kx }
5 kx
5 kx void
5 kx record_initial_cwd (void)
5 kx {
5 kx initial_wd = xmalloc (sizeof (*initial_wd));
5 kx if (0 != save_cwd (initial_wd))
5 kx {
5 kx die (EXIT_FAILURE, errno,
5 kx _("Failed to save initial working directory%s%s"),
5 kx (initial_wd->desc < 0 && initial_wd->name) ? ": " : "",
5 kx (initial_wd->desc < 0 && initial_wd->name) ? initial_wd->name : "");
5 kx }
5 kx }
5 kx
5 kx static void
5 kx cleanup_initial_cwd (void)
5 kx {
5 kx if (0 == restore_cwd (initial_wd))
5 kx {
5 kx free_cwd (initial_wd);
5 kx free (initial_wd);
5 kx initial_wd = NULL;
5 kx }
5 kx else
5 kx {
5 kx /* since we may already be in atexit, die with _exit(). */
5 kx error (0, errno,
5 kx _("Failed to restore initial working directory%s%s"),
5 kx (initial_wd->desc < 0 && initial_wd->name) ? ": " : "",
5 kx (initial_wd->desc < 0 && initial_wd->name) ? initial_wd->name : "");
5 kx _exit (EXIT_FAILURE);
5 kx }
5 kx }
5 kx
5 kx
5 kx static void
5 kx traverse_tree (struct predicate *tree,
5 kx void (*callback)(struct predicate*))
5 kx {
5 kx if (tree->pred_left)
5 kx traverse_tree (tree->pred_left, callback);
5 kx
5 kx callback (tree);
5 kx
5 kx if (tree->pred_right)
5 kx traverse_tree (tree->pred_right, callback);
5 kx }
5 kx
5 kx /* After sharefile_destroy is called, our output file
5 kx * pointers will be dangling (fclose will already have
5 kx * been called on them). NULL these out.
5 kx */
5 kx static void
5 kx undangle_file_pointers (struct predicate *p)
5 kx {
5 kx if (pred_is (p, pred_fprint)
5 kx || pred_is (p, pred_fprintf)
5 kx || pred_is (p, pred_fls)
5 kx || pred_is (p, pred_fprint0))
5 kx {
5 kx /* The file was already fclose()d by sharefile_destroy. */
5 kx p->args.printf_vec.stream = NULL;
5 kx }
5 kx }
5 kx
5 kx /* Complete any outstanding commands.
5 kx * Flush and close any open files.
5 kx */
5 kx void
5 kx cleanup (void)
5 kx {
5 kx struct predicate *eval_tree = get_eval_tree ();
5 kx if (eval_tree)
5 kx {
5 kx traverse_tree (eval_tree, complete_pending_execs);
5 kx complete_pending_execdirs ();
5 kx }
5 kx
5 kx /* Close output files and NULL out references to them. */
5 kx sharefile_destroy (state.shared_files);
5 kx if (eval_tree)
5 kx traverse_tree (eval_tree, undangle_file_pointers);
5 kx
5 kx cleanup_initial_cwd ();
5 kx
5 kx if (fd_leak_check_is_enabled ())
5 kx {
5 kx complain_about_leaky_fds ();
5 kx forget_non_cloexec_fds ();
5 kx }
5 kx
5 kx if (fflush (stdout) == EOF)
5 kx nonfatal_nontarget_file_error (errno, "standard output");
5 kx }
5 kx
5 kx
5 kx static int
5 kx fallback_stat (const char *name, struct stat *p, int prev_rv)
5 kx {
5 kx /* Our original stat() call failed. Perhaps we can't follow a
5 kx * symbolic link. If that might be the problem, lstat() the link.
5 kx * Otherwise, admit defeat.
5 kx */
5 kx switch (errno)
5 kx {
5 kx case ENOENT:
5 kx case ENOTDIR:
5 kx if (options.debug_options & DebugStat)
5 kx fprintf(stderr, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name);
5 kx return fstatat(state.cwd_dir_fd, name, p, AT_SYMLINK_NOFOLLOW);
5 kx
5 kx case EACCES:
5 kx case EIO:
5 kx case ELOOP:
5 kx case ENAMETOOLONG:
5 kx #ifdef EOVERFLOW
5 kx case EOVERFLOW: /* EOVERFLOW is not #defined on UNICOS. */
5 kx #endif
5 kx default:
5 kx return prev_rv;
5 kx }
5 kx }
5 kx
5 kx
5 kx /* optionh_stat() implements the stat operation when the -H option is
5 kx * in effect.
5 kx *
5 kx * If the item to be examined is a command-line argument, we follow
5 kx * symbolic links. If the stat() call fails on the command-line item,
5 kx * we fall back on the properties of the symbolic link.
5 kx *
5 kx * If the item to be examined is not a command-line argument, we
5 kx * examine the link itself.
5 kx */
5 kx int
5 kx optionh_stat (const char *name, struct stat *p)
5 kx {
5 kx if (AT_FDCWD != state.cwd_dir_fd)
5 kx assert (state.cwd_dir_fd >= 0);
5 kx set_stat_placeholders (p);
5 kx if (0 == state.curdepth)
5 kx {
5 kx /* This file is from the command line; deference the link (if it
5 kx * is a link).
5 kx */
5 kx int rv;
5 kx rv = fstatat (state.cwd_dir_fd, name, p, 0);
5 kx if (0 == rv)
5 kx return 0; /* success */
5 kx else
5 kx return fallback_stat (name, p, rv);
5 kx }
5 kx else
5 kx {
5 kx /* Not a file on the command line; do not dereference the link.
5 kx */
5 kx return fstatat (state.cwd_dir_fd, name, p, AT_SYMLINK_NOFOLLOW);
5 kx }
5 kx }
5 kx
5 kx /* optionl_stat() implements the stat operation when the -L option is
5 kx * in effect. That option makes us examine the thing the symbolic
5 kx * link points to, not the symbolic link itself.
5 kx */
5 kx int
5 kx optionl_stat(const char *name, struct stat *p)
5 kx {
5 kx int rv;
5 kx if (AT_FDCWD != state.cwd_dir_fd)
5 kx assert (state.cwd_dir_fd >= 0);
5 kx
5 kx set_stat_placeholders (p);
5 kx rv = fstatat (state.cwd_dir_fd, name, p, 0);
5 kx if (0 == rv)
5 kx return 0; /* normal case. */
5 kx else
5 kx return fallback_stat (name, p, rv);
5 kx }
5 kx
5 kx /* optionp_stat() implements the stat operation when the -P option is
5 kx * in effect (this is also the default). That option makes us examine
5 kx * the symbolic link itself, not the thing it points to.
5 kx */
5 kx int
5 kx optionp_stat (const char *name, struct stat *p)
5 kx {
5 kx assert ((state.cwd_dir_fd >= 0) || (state.cwd_dir_fd==AT_FDCWD));
5 kx set_stat_placeholders (p);
5 kx return fstatat (state.cwd_dir_fd, name, p, AT_SYMLINK_NOFOLLOW);
5 kx }
5 kx
5 kx
5 kx static uintmax_t stat_count = 0u;
5 kx
5 kx int
5 kx debug_stat (const char *file, struct stat *bufp)
5 kx {
5 kx ++stat_count;
5 kx fprintf (stderr, "debug_stat (%s)\n", file);
5 kx
5 kx switch (options.symlink_handling)
5 kx {
5 kx case SYMLINK_ALWAYS_DEREF:
5 kx return optionl_stat (file, bufp);
5 kx case SYMLINK_DEREF_ARGSONLY:
5 kx return optionh_stat (file, bufp);
5 kx case SYMLINK_NEVER_DEREF:
5 kx return optionp_stat (file, bufp);
5 kx }
5 kx /*NOTREACHED*/
5 kx assert (0);
5 kx return -1;
5 kx }
5 kx
5 kx
5 kx bool
5 kx following_links(void)
5 kx {
5 kx switch (options.symlink_handling)
5 kx {
5 kx case SYMLINK_ALWAYS_DEREF:
5 kx return true;
5 kx case SYMLINK_DEREF_ARGSONLY:
5 kx return (state.curdepth == 0);
5 kx case SYMLINK_NEVER_DEREF:
5 kx default:
5 kx return false;
5 kx }
5 kx }
5 kx
5 kx
5 kx /* Take a "mode" indicator and fill in the files of 'state'.
5 kx */
5 kx bool
5 kx digest_mode (mode_t *mode,
5 kx const char *pathname,
5 kx const char *name,
5 kx struct stat *pstat,
5 kx bool leaf)
5 kx {
5 kx /* If we know the type of the directory entry, and it is not a
5 kx * symbolic link, we may be able to avoid a stat() or lstat() call.
5 kx */
5 kx if (*mode)
5 kx {
5 kx if (S_ISLNK(*mode) && following_links())
5 kx {
5 kx /* mode is wrong because we should have followed the symlink. */
5 kx if (get_statinfo (pathname, name, pstat) != 0)
5 kx return false;
5 kx *mode = state.type = pstat->st_mode;
5 kx state.have_type = true;
5 kx }
5 kx else
5 kx {
5 kx state.have_type = true;
5 kx pstat->st_mode = state.type = *mode;
5 kx }
5 kx }
5 kx else
5 kx {
5 kx /* Mode is not yet known; may have to stat the file unless we
5 kx * can deduce that it is not a directory (which is all we need to
5 kx * know at this stage)
5 kx */
5 kx if (leaf)
5 kx {
5 kx state.have_stat = false;
5 kx state.have_type = false;
5 kx state.type = 0;
5 kx }
5 kx else
5 kx {
5 kx if (get_statinfo (pathname, name, pstat) != 0)
5 kx return false;
5 kx
5 kx /* If -L is in effect and we are dealing with a symlink,
5 kx * st_mode is the mode of the pointed-to file, while mode is
5 kx * the mode of the directory entry (S_IFLNK). Hence now
5 kx * that we have the stat information, override "mode".
5 kx */
5 kx state.type = *mode = pstat->st_mode;
5 kx state.have_type = true;
5 kx }
5 kx }
5 kx
5 kx /* success. */
5 kx return true;
5 kx }
5 kx
5 kx
5 kx /* Return true if there are no predicates with no_default_print in
5 kx predicate list PRED, false if there are any.
5 kx Returns true if default print should be performed */
5 kx
5 kx bool
5 kx default_prints (struct predicate *pred)
5 kx {
5 kx while (pred != NULL)
5 kx {
5 kx if (pred->no_default_print)
5 kx return (false);
5 kx pred = pred->pred_next;
5 kx }
5 kx return (true);
5 kx }
5 kx
5 kx bool
5 kx looks_like_expression (const char *arg, bool leading)
5 kx {
5 kx switch (arg[0])
5 kx {
5 kx case '-':
5 kx if (arg[1]) /* "-foo" is an expression. */
5 kx return true;
5 kx else
5 kx return false; /* Just "-" is a filename. */
5 kx break;
5 kx
5 kx case ')':
5 kx case ',':
5 kx if (arg[1])
5 kx return false; /* )x and ,z are not expressions */
5 kx else
5 kx return !leading; /* A leading ) or , is not either */
5 kx
5 kx /* ( and ! are part of an expression, but (2 and !foo are
5 kx * filenames.
5 kx */
5 kx case '!':
5 kx case '(':
5 kx if (arg[1])
5 kx return false;
5 kx else
5 kx return true;
5 kx
5 kx default:
5 kx return false;
5 kx }
5 kx }
5 kx
5 kx static void
5 kx process_debug_options (char *arg)
5 kx {
5 kx const char *p;
5 kx char *token_context = NULL;
5 kx const char delimiters[] = ",";
5 kx bool empty = true;
5 kx size_t i;
5 kx
5 kx p = strtok_r (arg, delimiters, &token_context);
5 kx while (p)
5 kx {
5 kx empty = false;
5 kx
5 kx for (i=0; i<N_DEBUGASSOC; ++i)
5 kx {
5 kx if (0 == strcmp (debugassoc[i].name, p))
5 kx {
5 kx options.debug_options |= debugassoc[i].val;
5 kx break;
5 kx }
5 kx }
5 kx if (i >= N_DEBUGASSOC)
5 kx {
5 kx error (0, 0, _("Ignoring unrecognised debug flag %s"),
5 kx quotearg_n_style (0, options.err_quoting_style, arg));
5 kx }
5 kx p = strtok_r (NULL, delimiters, &token_context);
5 kx }
5 kx if (empty)
5 kx {
5 kx error (0, 0, _("Empty argument to the -D option."));
5 kx usage (EXIT_FAILURE);
5 kx }
5 kx else if (options.debug_options & DebugHelp)
5 kx {
5 kx show_valid_debug_options (1);
5 kx exit (EXIT_SUCCESS);
5 kx }
5 kx }
5 kx
5 kx
5 kx static void
5 kx process_optimisation_option (const char *arg)
5 kx {
5 kx if (0 == arg[0])
5 kx {
5 kx die (EXIT_FAILURE, 0,
5 kx _("The -O option must be immediately followed by a decimal integer"));
5 kx }
5 kx else
5 kx {
5 kx unsigned long opt_level;
5 kx char *end;
5 kx
5 kx if (!isdigit ( (unsigned char) arg[0] ))
5 kx {
5 kx die (EXIT_FAILURE, 0,
5 kx _("Please specify a decimal number immediately after -O"));
5 kx }
5 kx else
5 kx {
5 kx int prev_errno = errno;
5 kx errno = 0;
5 kx
5 kx opt_level = strtoul (arg, &end, 10);
5 kx if ( (0==opt_level) && (end==arg) )
5 kx {
5 kx die (EXIT_FAILURE, 0,
5 kx _("Please specify a decimal number immediately after -O"));
5 kx }
5 kx else if (*end)
5 kx {
5 kx /* unwanted trailing characters. */
5 kx die (EXIT_FAILURE, 0, _("Invalid optimisation level %s"), arg);
5 kx }
5 kx else if ( (ULONG_MAX==opt_level) && errno)
5 kx {
5 kx die (EXIT_FAILURE, errno,
5 kx _("Invalid optimisation level %s"), arg);
5 kx }
5 kx else if (opt_level > USHRT_MAX)
5 kx {
5 kx /* tricky to test, as on some platforms USHORT_MAX and ULONG_MAX
5 kx * can have the same value, though this is unusual.
5 kx */
5 kx die (EXIT_FAILURE, 0,
5 kx _("Optimisation level %lu is too high. "
5 kx "If you want to find files very quickly, "
5 kx "consider using GNU locate."),
5 kx opt_level);
5 kx }
5 kx else
5 kx {
5 kx options.optimisation_level = opt_level;
5 kx errno = prev_errno;
5 kx }
5 kx }
5 kx }
5 kx }
5 kx
5 kx int
5 kx process_leading_options (int argc, char *argv[])
5 kx {
5 kx int i, end_of_leading_options;
5 kx
5 kx for (i=1; (end_of_leading_options = i) < argc; ++i)
5 kx {
5 kx if (0 == strcmp ("-H", argv[i]))
5 kx {
5 kx /* Meaning: dereference symbolic links on command line, but nowhere else. */
5 kx set_follow_state (SYMLINK_DEREF_ARGSONLY);
5 kx }
5 kx else if (0 == strcmp ("-L", argv[i]))
5 kx {
5 kx /* Meaning: dereference all symbolic links. */
5 kx set_follow_state (SYMLINK_ALWAYS_DEREF);
5 kx }
5 kx else if (0 == strcmp ("-P", argv[i]))
5 kx {
5 kx /* Meaning: never dereference symbolic links (default). */
5 kx set_follow_state (SYMLINK_NEVER_DEREF);
5 kx }
5 kx else if (0 == strcmp ("--", argv[i]))
5 kx {
5 kx /* -- signifies the end of options. */
5 kx end_of_leading_options = i+1; /* Next time start with the next option */
5 kx break;
5 kx }
5 kx else if (0 == strcmp ("-D", argv[i]))
5 kx {
5 kx if (argc <= i+1)
5 kx {
5 kx error (0, 0, _("Missing argument after the -D option."));
5 kx usage (EXIT_FAILURE);
5 kx }
5 kx process_debug_options (argv[i+1]);
5 kx ++i; /* skip the argument too. */
5 kx }
5 kx else if (0 == strncmp ("-O", argv[i], 2))
5 kx {
5 kx process_optimisation_option (argv[i]+2);
5 kx }
5 kx else
5 kx {
5 kx /* Hmm, must be one of
5 kx * (a) A path name
5 kx * (b) A predicate
5 kx */
5 kx end_of_leading_options = i; /* Next time start with this option */
5 kx break;
5 kx }
5 kx }
5 kx return end_of_leading_options;
5 kx }
5 kx
5 kx static struct timespec
5 kx now(void)
5 kx {
5 kx struct timespec retval;
5 kx struct timeval tv;
5 kx time_t t;
5 kx
5 kx if (0 == gettimeofday (&tv, NULL))
5 kx {
5 kx retval.tv_sec = tv.tv_sec;
5 kx retval.tv_nsec = tv.tv_usec * 1000; /* convert unit from microseconds to nanoseconds */
5 kx return retval;
5 kx }
5 kx t = time (NULL);
5 kx assert (t != (time_t)-1);
5 kx retval.tv_sec = t;
5 kx retval.tv_nsec = 0;
5 kx return retval;
5 kx }
5 kx
5 kx void
5 kx set_option_defaults (struct options *p)
5 kx {
5 kx if (getenv ("POSIXLY_CORRECT"))
5 kx p->posixly_correct = true;
5 kx else
5 kx p->posixly_correct = false;
5 kx
5 kx /* We call check_nofollow() before setlocale() because the numbers
5 kx * for which we check (in the results of uname) definitiely have "."
5 kx * as the decimal point indicator even under locales for which that
5 kx * is not normally true. Hence atof would do the wrong thing
5 kx * if we call it after setlocale().
5 kx */
5 kx #ifdef O_NOFOLLOW
5 kx p->open_nofollow_available = check_nofollow ();
5 kx #else
5 kx p->open_nofollow_available = false;
5 kx #endif
5 kx
5 kx p->regex_options = RE_SYNTAX_EMACS;
5 kx
5 kx if (isatty (0))
5 kx {
5 kx p->warnings = false;
5 kx p->literal_control_chars = false;
5 kx }
5 kx else
5 kx {
5 kx p->warnings = false;
5 kx p->literal_control_chars = false; /* may change */
5 kx }
5 kx if (p->posixly_correct)
5 kx {
5 kx p->warnings = false;
5 kx }
5 kx
5 kx p->do_dir_first = true;
5 kx p->explicit_depth = false;
5 kx p->maxdepth = p->mindepth = -1;
5 kx
5 kx p->start_time = now ();
5 kx p->cur_day_start.tv_sec = p->start_time.tv_sec - DAYSECS;
5 kx p->cur_day_start.tv_nsec = p->start_time.tv_nsec;
5 kx
5 kx p->full_days = false;
5 kx p->stay_on_filesystem = false;
5 kx p->ignore_readdir_race = false;
5 kx
5 kx if (p->posixly_correct)
5 kx p->output_block_size = 512;
5 kx else
5 kx p->output_block_size = 1024;
5 kx
5 kx p->debug_options = 0uL;
5 kx p->optimisation_level = 2;
5 kx
5 kx if (getenv ("FIND_BLOCK_SIZE"))
5 kx {
5 kx die (EXIT_FAILURE, 0,
5 kx _("The environment variable FIND_BLOCK_SIZE is not supported, "
5 kx "the only thing that affects the block size is the "
5 kx "POSIXLY_CORRECT environment variable"));
5 kx }
5 kx
5 kx #if LEAF_OPTIMISATION
5 kx /* The leaf optimisation is enabled. */
5 kx p->no_leaf_check = false;
5 kx #else
5 kx /* The leaf optimisation is disabled. */
5 kx p->no_leaf_check = true;
5 kx #endif
5 kx
5 kx set_follow_state (SYMLINK_NEVER_DEREF); /* The default is equivalent to -P. */
5 kx
5 kx p->err_quoting_style = locale_quoting_style;
5 kx }
5 kx
5 kx
5 kx /* apply_predicate
5 kx *
5 kx */
5 kx bool
5 kx apply_predicate(const char *pathname, struct stat *stat_buf, struct predicate *p)
5 kx {
5 kx ++p->perf.visits;
5 kx
5 kx if (p->need_stat || p->need_type || p->need_inum)
5 kx {
5 kx /* We may need a stat here. */
5 kx if (get_info(pathname, stat_buf, p) != 0)
5 kx return false;
5 kx }
5 kx if ((p->pred_func)(pathname, stat_buf, p))
5 kx {
5 kx ++(p->perf.successes);
5 kx return true;
5 kx }
5 kx else
5 kx {
5 kx return false;
5 kx }
5 kx }
5 kx
5 kx
5 kx /* is_exec_in_local_dir
5 kx *
5 kx */
5 kx bool
5 kx is_exec_in_local_dir (const PRED_FUNC pred_func)
5 kx {
5 kx return pred_execdir == pred_func || pred_okdir == pred_func;
5 kx }
5 kx
5 kx /* safely_quote_err_filename
5 kx *
5 kx */
5 kx const char *
5 kx safely_quote_err_filename (int n, char const *arg)
5 kx {
5 kx return quotearg_n_style (n, options.err_quoting_style, arg);
5 kx }
5 kx
5 kx /* We have encountered an error which should affect the exit status.
5 kx * This is normally used to change the exit status from 0 to 1.
5 kx * However, if the exit status is already 2 for example, we don't want to
5 kx * reduce it to 1.
5 kx */
5 kx void
5 kx error_severity (int level)
5 kx {
5 kx if (state.exit_status < level)
5 kx state.exit_status = level;
5 kx }
5 kx
5 kx
5 kx /* report_file_err
5 kx */
5 kx static void
5 kx report_file_err(int exitval, int errno_value,
5 kx bool is_target_file, const char *name)
5 kx {
5 kx /* It is important that the errno value is passed in as a function
5 kx * argument before we call safely_quote_err_filename(), because otherwise
5 kx * we might find that safely_quote_err_filename() changes errno.
5 kx */
5 kx if (!is_target_file || !state.already_issued_stat_error_msg)
5 kx {
5 kx error (exitval, errno_value, "%s", safely_quote_err_filename (0, name));
5 kx error_severity (1);
5 kx }
5 kx if (is_target_file)
5 kx {
5 kx state.already_issued_stat_error_msg = true;
5 kx }
5 kx }
5 kx
5 kx /* nonfatal_target_file_error
5 kx */
5 kx void
5 kx nonfatal_target_file_error (int errno_value, const char *name)
5 kx {
5 kx report_file_err (0, errno_value, true, name);
5 kx }
5 kx
5 kx /* fatal_target_file_error
5 kx *
5 kx * Report an error on a target file (i.e. a file we are searching).
5 kx * Such errors are only reported once per searched file.
5 kx *
5 kx */
5 kx void
5 kx fatal_target_file_error(int errno_value, const char *name)
5 kx {
5 kx report_file_err (1, errno_value, true, name);
5 kx /*NOTREACHED*/
5 kx abort ();
5 kx }
5 kx
5 kx /* nonfatal_nontarget_file_error
5 kx *
5 kx */
5 kx void
5 kx nonfatal_nontarget_file_error (int errno_value, const char *name)
5 kx {
5 kx report_file_err (0, errno_value, false, name);
5 kx }
5 kx
5 kx /* fatal_nontarget_file_error
5 kx *
5 kx */
5 kx void
5 kx fatal_nontarget_file_error(int errno_value, const char *name)
5 kx {
5 kx /* We're going to exit fatally, so make sure we always isssue the error
5 kx * message, even if it will be duplicate. Motivation: otherwise it may
5 kx * not be clear what went wrong.
5 kx */
5 kx state.already_issued_stat_error_msg = false;
5 kx report_file_err (1, errno_value, false, name);
5 kx /*NOTREACHED*/
5 kx abort ();
5 kx }