Applied (trivial) Martin Buchholz patch for typos/spelling errors, mostly in code...
[findutils.git] / find / find.c
blob5c2c75c585d01ce4f40a15aa73b2af7a88ad603e
1 /* find -- search for files in a directory hierarchy
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 USA.*/
19 /* GNU find was written by Eric Decker <cire@cisco.com>,
20 with enhancements by David MacKenzie <djm@gnu.org>,
21 Jay Plett <jay@silence.princeton.nj.us>,
22 and Tim Wood <axolotl!tim@toad.com>.
23 The idea for -print0 and xargs -0 came from
24 Dan Bernstein <brnstnd@kramden.acf.nyu.edu>. */
27 #include "defs.h"
29 #define USE_SAFE_CHDIR 1
30 #undef STAT_MOUNTPOINTS
33 #include <errno.h>
34 #include <assert.h>
37 #ifdef HAVE_FCNTL_H
38 #include <fcntl.h>
39 #else
40 #include <sys/file.h>
41 #endif
43 #ifdef HAVE_SYS_UTSNAME_H
44 #include <sys/utsname.h>
45 #endif
47 #include "../gnulib/lib/xalloc.h"
48 #include "../gnulib/lib/human.h"
49 #include "../gnulib/lib/canonicalize.h"
50 #include "closeout.h"
51 #include <modetype.h>
52 #include "savedirinfo.h"
53 #include "buildcmd.h"
54 #include "dirname.h"
56 #ifdef HAVE_LOCALE_H
57 #include <locale.h>
58 #endif
60 #if ENABLE_NLS
61 # include <libintl.h>
62 # define _(Text) gettext (Text)
63 #else
64 # define _(Text) Text
65 #define textdomain(Domain)
66 #define bindtextdomain(Package, Directory)
67 #endif
68 #ifdef gettext_noop
69 # define N_(String) gettext_noop (String)
70 #else
71 /* See locate.c for explanation as to why not use (String) */
72 # define N_(String) String
73 #endif
75 #define apply_predicate(pathname, stat_buf_ptr, node) \
76 (*(node)->pred_func)((pathname), (stat_buf_ptr), (node))
78 #ifdef STAT_MOUNTPOINTS
79 static void init_mounted_dev_list(void);
80 #endif
82 static void process_top_path PARAMS((char *pathname, mode_t mode));
83 static int process_path PARAMS((char *pathname, char *name, boolean leaf, char *parent, mode_t type));
84 static void process_dir PARAMS((char *pathname, char *name, int pathlen, struct stat *statp, char *parent));
86 static void complete_pending_execdirs(struct predicate *p);
87 static void complete_pending_execs (struct predicate *p);
91 static boolean default_prints PARAMS((struct predicate *pred));
93 /* Name this program was run with. */
94 char *program_name;
96 /* All predicates for each path to process. */
97 struct predicate *predicates;
99 /* The last predicate allocated. */
100 struct predicate *last_pred;
102 /* The root of the evaluation tree. */
103 static struct predicate *eval_tree = NULL;
106 struct options options;
107 struct state state;
109 /* The full path of the initial working directory, or "." if
110 STARTING_DESC is nonnegative. */
111 char const *starting_dir = ".";
113 /* A file descriptor open to the initial working directory.
114 Doing it this way allows us to work when the i.w.d. has
115 unreadable parents. */
116 int starting_desc;
118 /* The stat buffer of the initial working directory. */
119 struct stat starting_stat_buf;
121 enum ChdirSymlinkHandling
123 SymlinkHandleDefault, /* Normally the right choice */
124 SymlinkFollowOk /* see comment in process_top_path() */
128 enum TraversalDirection
130 TraversingUp,
131 TraversingDown
134 enum WdSanityCheckFatality
136 FATAL_IF_SANITY_CHECK_FAILS,
137 RETRY_IF_SANITY_CHECK_FAILS,
138 NON_FATAL_IF_SANITY_CHECK_FAILS
143 following_links(void)
145 switch (options.symlink_handling)
147 case SYMLINK_ALWAYS_DEREF:
148 return 1;
149 case SYMLINK_DEREF_ARGSONLY:
150 return (state.curdepth == 0);
151 case SYMLINK_NEVER_DEREF:
152 default:
153 return 0;
158 static int
159 fallback_stat(const char *name, struct stat *p, int prev_rv)
161 /* Our original stat() call failed. Perhaps we can't follow a
162 * symbolic link. If that might be the problem, lstat() the link.
163 * Otherwise, admit defeat.
165 switch (errno)
167 case ENOENT:
168 case ENOTDIR:
169 #ifdef DEBUG_STAT
170 fprintf(stderr, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name);
171 #endif
172 return lstat(name, p);
174 case EACCES:
175 case EIO:
176 case ELOOP:
177 case ENAMETOOLONG:
178 #ifdef EOVERFLOW
179 case EOVERFLOW: /* EOVERFLOW is not #defined on UNICOS. */
180 #endif
181 default:
182 return prev_rv;
187 /* optionh_stat() implements the stat operation when the -H option is
188 * in effect.
190 * If the item to be examined is a command-line argument, we follow
191 * symbolic links. If the stat() call fails on the command-line item,
192 * we fall back on the properties of the symbolic link.
194 * If the item to be examined is not a command-line argument, we
195 * examine the link itself.
197 int
198 optionh_stat(const char *name, struct stat *p)
200 if (0 == state.curdepth)
202 /* This file is from the command line; deference the link (if it
203 * is a link).
205 int rv = stat(name, p);
206 if (0 == rv)
207 return 0; /* success */
208 else
209 return fallback_stat(name, p, rv);
211 else
213 /* Not a file on the command line; do not dereference the link.
215 return lstat(name, p);
219 /* optionl_stat() implements the stat operation when the -L option is
220 * in effect. That option makes us examine the thing the symbolic
221 * link points to, not the symbolic link itself.
223 int
224 optionl_stat(const char *name, struct stat *p)
226 int rv = stat(name, p);
227 if (0 == rv)
228 return 0; /* normal case. */
229 else
230 return fallback_stat(name, p, rv);
233 /* optionp_stat() implements the stat operation when the -P option is
234 * in effect (this is also the default). That option makes us examine
235 * the symbolic link itself, not the thing it points to.
237 int
238 optionp_stat(const char *name, struct stat *p)
240 return lstat(name, p);
243 #ifdef DEBUG_STAT
244 static uintmax_t stat_count = 0u;
246 static int
247 debug_stat (const char *file, struct stat *bufp)
249 ++stat_count;
250 fprintf (stderr, "debug_stat (%s)\n", file);
251 switch (options.symlink_handling)
253 case SYMLINK_ALWAYS_DEREF:
254 return optionl_stat(file, bufp);
255 case SYMLINK_DEREF_ARGSONLY:
256 return optionh_stat(file, bufp);
257 case SYMLINK_NEVER_DEREF:
258 return optionp_stat(file, bufp);
261 #endif /* DEBUG_STAT */
263 void
264 set_follow_state(enum SymlinkOption opt)
266 switch (opt)
268 case SYMLINK_ALWAYS_DEREF: /* -L */
269 options.xstat = optionl_stat;
270 options.no_leaf_check = true;
271 break;
273 case SYMLINK_NEVER_DEREF: /* -P (default) */
274 options.xstat = optionp_stat;
275 /* Can't turn no_leaf_check off because the user might have specified
276 * -noleaf anyway
278 break;
280 case SYMLINK_DEREF_ARGSONLY: /* -H */
281 options.xstat = optionh_stat;
282 options.no_leaf_check = true;
285 options.symlink_handling = opt;
287 /* For DEBUG_STAT, the choice is made at runtime within debug_stat()
288 * by checking the contents of the symlink_handling variable.
290 #if defined(DEBUG_STAT)
291 options.xstat = debug_stat;
292 #endif /* !DEBUG_STAT */
296 /* Complete any outstanding commands.
298 void
299 cleanup(void)
301 if (eval_tree)
303 complete_pending_execs(eval_tree);
304 complete_pending_execdirs(eval_tree);
308 /* Get the stat information for a file, if it is
309 * not already known.
312 get_statinfo (const char *pathname, const char *name, struct stat *p)
314 if (!state.have_stat && (*options.xstat) (name, p) != 0)
316 if (!options.ignore_readdir_race || (errno != ENOENT) )
318 error (0, errno, "%s", pathname);
319 state.exit_status = 1;
321 return -1;
323 state.have_stat = true;
324 state.have_type = true;
325 state.type = p->st_mode;
326 return 0;
329 /* Get the stat/type information for a file, if it is
330 * not already known.
333 get_info (const char *pathname,
334 const char *name,
335 struct stat *p,
336 struct predicate *pred_ptr)
338 /* If we need the full stat info, or we need the type info but don't
339 * already have it, stat the file now.
341 (void) name;
342 if (pred_ptr->need_stat)
344 return get_statinfo(pathname, state.rel_pathname, p);
346 if ((pred_ptr->need_type && (0 == state.have_type)))
348 return get_statinfo(pathname, state.rel_pathname, p);
350 return 0;
353 /* Determine if we can use O_NOFOLLOW.
355 #if defined(O_NOFOLLOW)
356 static boolean
357 check_nofollow(void)
359 struct utsname uts;
360 float release;
362 if (0 == uname(&uts))
364 /* POSIX requires that atof() ignore "unrecognised suffixes". */
365 release = atof(uts.release);
367 if (0 == strcmp("Linux", uts.sysname))
369 /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
370 return release >= 2.2; /* close enough */
372 else if (0 == strcmp("FreeBSD", uts.sysname))
374 /* FreeBSD 3.0-CURRENT and later support it */
375 return release >= 3.1;
379 /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
380 return true;
382 #endif
385 main (int argc, char **argv)
387 int i;
388 PARSE_FUNC parse_function; /* Pointer to the function which parses. */
389 struct predicate *cur_pred;
390 char *predicate_name; /* Name of predicate being parsed. */
391 int end_of_leading_options = 0; /* First arg after any -H/-L etc. */
392 program_name = argv[0];
394 /* We call check_nofollow() before setlocale() because the numbers
395 * for which we check (in the results of uname) definitiely have "."
396 * as the decimal point indicator even under locales for which that
397 * is not normally true. Hence atof() would do the wrong thing
398 * if we call it after setlocale().
400 #ifdef O_NOFOLLOW
401 options.open_nofollow_available = check_nofollow();
402 #else
403 options.open_nofollow_available = false;
404 #endif
407 #ifdef HAVE_SETLOCALE
408 setlocale (LC_ALL, "");
409 #endif
410 bindtextdomain (PACKAGE, LOCALEDIR);
411 textdomain (PACKAGE);
412 atexit (close_stdout);
415 if (isatty(0))
417 options.warnings = true;
419 else
421 options.warnings = false;
425 predicates = NULL;
426 last_pred = NULL;
427 options.do_dir_first = true;
428 options.maxdepth = options.mindepth = -1;
429 options.start_time = time (NULL);
430 options.cur_day_start = options.start_time - DAYSECS;
431 options.full_days = false;
432 options.stay_on_filesystem = false;
433 options.ignore_readdir_race = false;
435 state.exit_status = 0;
437 #if defined(DEBUG_STAT)
438 options.xstat = debug_stat;
439 #endif /* !DEBUG_STAT */
441 if (getenv("POSIXLY_CORRECT"))
442 options.output_block_size = 512;
443 else
444 options.output_block_size = 1024;
446 if (getenv("FIND_BLOCK_SIZE"))
448 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"));
451 options.no_leaf_check = false;
452 set_follow_state(SYMLINK_NEVER_DEREF); /* The default is equivalent to -P. */
454 #ifdef DEBUG
455 fprintf (stderr, "cur_day_start = %s", ctime (&options.cur_day_start));
456 #endif /* DEBUG */
458 /* Check for -P, -H or -L options. */
459 for (i=1; (end_of_leading_options = i) < argc; ++i)
461 if (0 == strcmp("-H", argv[i]))
463 /* Meaning: dereference symbolic links on command line, but nowhere else. */
464 set_follow_state(SYMLINK_DEREF_ARGSONLY);
466 else if (0 == strcmp("-L", argv[i]))
468 /* Meaning: dereference all symbolic links. */
469 set_follow_state(SYMLINK_ALWAYS_DEREF);
471 else if (0 == strcmp("-P", argv[i]))
473 /* Meaning: never dereference symbolic links (default). */
474 set_follow_state(SYMLINK_NEVER_DEREF);
476 else if (0 == strcmp("--", argv[i]))
478 /* -- signifies the end of options. */
479 end_of_leading_options = i+1; /* Next time start with the next option */
480 break;
482 else
484 /* Hmm, must be one of
485 * (a) A path name
486 * (b) A predicate
488 end_of_leading_options = i; /* Next time start with this option */
489 break;
493 /* We are now processing the part of the "find" command line
494 * after the -H/-L options (if any).
497 /* fprintf(stderr, "rest: optind=%ld\n", (long)optind); */
499 /* Find where in ARGV the predicates begin. */
500 for (i = end_of_leading_options; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++)
502 /* fprintf(stderr, "Looks like %s is not a predicate\n", argv[i]); */
503 /* Do nothing. */ ;
506 /* Enclose the expression in `( ... )' so a default -print will
507 apply to the whole expression. */
508 parse_open (argv, &argc);
509 /* Build the input order list. */
510 while (i < argc)
512 if (strchr ("-!(),", argv[i][0]) == NULL)
513 usage (_("paths must precede expression"));
514 predicate_name = argv[i];
515 parse_function = find_parser (predicate_name);
516 if (parse_function == NULL)
517 /* Command line option not recognized */
518 error (1, 0, _("invalid predicate `%s'"), predicate_name);
519 i++;
520 if (!(*parse_function) (argv, &i))
522 if (argv[i] == NULL)
523 /* Command line option requires an argument */
524 error (1, 0, _("missing argument to `%s'"), predicate_name);
525 else
526 error (1, 0, _("invalid argument `%s' to `%s'"),
527 argv[i], predicate_name);
530 if (predicates->pred_next == NULL)
532 /* No predicates that do something other than set a global variable
533 were given; remove the unneeded initial `(' and add `-print'. */
534 cur_pred = predicates;
535 predicates = last_pred = predicates->pred_next;
536 free ((char *) cur_pred);
537 parse_print (argv, &argc);
539 else if (!default_prints (predicates->pred_next))
541 /* One or more predicates that produce output were given;
542 remove the unneeded initial `('. */
543 cur_pred = predicates;
544 predicates = predicates->pred_next;
545 free ((char *) cur_pred);
547 else
549 /* `( user-supplied-expression ) -print'. */
550 parse_close (argv, &argc);
551 parse_print (argv, &argc);
554 #ifdef DEBUG
555 fprintf (stderr, "Predicate List:\n");
556 print_list (stderr, predicates);
557 #endif /* DEBUG */
559 /* Done parsing the predicates. Build the evaluation tree. */
560 cur_pred = predicates;
561 eval_tree = get_expr (&cur_pred, NO_PREC);
563 /* Check if we have any left-over predicates (this fixes
564 * Debian bug #185202).
566 if (cur_pred != NULL)
568 error (1, 0, _("unexpected extra predicate"));
571 #ifdef DEBUG
572 fprintf (stderr, "Eval Tree:\n");
573 print_tree (stderr, eval_tree, 0);
574 #endif /* DEBUG */
576 /* Rearrange the eval tree in optimal-predicate order. */
577 opt_expr (&eval_tree);
579 /* Determine the point, if any, at which to stat the file. */
580 mark_stat (eval_tree);
581 /* Determine the point, if any, at which to determine file type. */
582 mark_type (eval_tree);
584 #ifdef DEBUG
585 fprintf (stderr, "Optimized Eval Tree:\n");
586 print_tree (stderr, eval_tree, 0);
587 fprintf (stderr, "Optimized command line:\n");
588 print_optlist(stderr, eval_tree);
589 fprintf(stderr, "\n");
590 #endif /* DEBUG */
592 /* safely_chdir() needs to check that it has ended up in the right place.
593 * To avoid bailing out when something gets automounted, it checks if
594 * the target directory appears to have had a directory mounted on it as
595 * we chdir()ed. The problem with this is that in order to notice that
596 * a filesystem was mounted, we would need to lstat() all the mount points.
597 * That strategy loses if our machine is a client of a dead NFS server.
599 * Hence if safely_chdir() and wd_sanity_check() can manage without needing
600 * to know the mounted device list, we do that.
602 if (!options.open_nofollow_available)
604 #ifdef STAT_MOUNTPOINTS
605 init_mounted_dev_list();
606 #endif
610 starting_desc = open (".", O_RDONLY);
611 if (0 <= starting_desc && fchdir (starting_desc) != 0)
613 close (starting_desc);
614 starting_desc = -1;
616 if (starting_desc < 0)
618 starting_dir = xgetcwd ();
619 if (! starting_dir)
620 error (1, errno, _("cannot get current directory"));
622 if ((*options.xstat) (".", &starting_stat_buf) != 0)
623 error (1, errno, _("cannot get current directory"));
625 /* If no paths are given, default to ".". */
626 for (i = end_of_leading_options; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++)
628 process_top_path (argv[i], 0);
631 /* If there were no path arguments, default to ".". */
632 if (i == end_of_leading_options)
635 * We use a temporary variable here because some actions modify
636 * the path temporarily. Hence if we use a string constant,
637 * we get a coredump. The best example of this is if we say
638 * "find -printf %H" (note, not "find . -printf %H").
640 char defaultpath[2] = ".";
641 process_top_path (defaultpath, 0);
644 /* If "-exec ... {} +" has been used, there may be some
645 * partially-full command lines which have been built,
646 * but which are not yet complete. Execute those now.
648 cleanup();
649 return state.exit_status;
653 static char *
654 specific_dirname(const char *dir)
656 char dirbuf[1024];
658 if (0 == strcmp(".", dir))
660 /* OK, what's '.'? */
661 if (NULL != getcwd(dirbuf, sizeof(dirbuf)))
663 return strdup(dirbuf);
665 else
667 return strdup(dir);
670 else
672 char *result = canonicalize_filename_mode(dir, CAN_EXISTING);
673 if (NULL == result)
674 return strdup(dir);
675 else
676 return result;
682 /* Return non-zero if FS is the name of a filesystem that is likely to
683 * be automounted
685 static int
686 fs_likely_to_be_automounted(const char *fs)
688 return ( (0==strcmp(fs, "nfs")) || (0==strcmp(fs, "autofs")) || (0==strcmp(fs, "subfs")));
693 #ifdef STAT_MOUNTPOINTS
694 static dev_t *mounted_devices = NULL;
695 static size_t num_mounted_devices = 0u;
698 static void
699 init_mounted_dev_list()
701 assert(NULL == mounted_devices);
702 assert(0 == num_mounted_devices);
703 mounted_devices = get_mounted_devices(&num_mounted_devices);
706 static void
707 refresh_mounted_dev_list(void)
709 if (mounted_devices)
711 free(mounted_devices);
712 mounted_devices = 0;
714 num_mounted_devices = 0u;
715 init_mounted_dev_list();
719 /* Search for device DEV in the array LIST, which is of size N. */
720 static int
721 dev_present(dev_t dev, const dev_t *list, size_t n)
723 if (list)
725 while (n-- > 0u)
727 if ( (*list++) == dev )
728 return 1;
731 return 0;
734 enum MountPointStateChange
736 MountPointRecentlyMounted,
737 MountPointRecentlyUnmounted,
738 MountPointStateUnchanged
743 static enum MountPointStateChange
744 get_mount_state(dev_t newdev)
746 int new_is_present, new_was_present;
748 new_was_present = dev_present(newdev, mounted_devices, num_mounted_devices);
749 refresh_mounted_dev_list();
750 new_is_present = dev_present(newdev, mounted_devices, num_mounted_devices);
752 if (new_was_present == new_is_present)
753 return MountPointStateUnchanged;
754 else if (new_is_present)
755 return MountPointRecentlyMounted;
756 else
757 return MountPointRecentlyUnmounted;
762 /* We stat()ed a directory, chdir()ed into it (we know this
763 * since direction is TraversingDown), stat()ed it again,
764 * and noticed that the device numbers are different. Check
765 * if the filesystem was recently mounted.
767 * If it was, it looks like chdir()ing into the directory
768 * caused a filesystem to be mounted. Maybe automount is
769 * running. Anyway, that's probably OK - but it happens
770 * only when we are moving downward.
772 * We also allow for the possibility that a similar thing
773 * has happened with the unmounting of a filesystem. This
774 * is much rarer, as it relies on an automounter timeout
775 * occurring at exactly the wrong moment.
777 static enum WdSanityCheckFatality
778 dirchange_is_fatal(const char *specific_what,
779 enum WdSanityCheckFatality isfatal,
780 int silent,
781 struct stat *newinfo)
783 enum MountPointStateChange transition = get_mount_state(newinfo->st_dev);
784 switch (transition)
786 case MountPointRecentlyUnmounted:
787 isfatal = NON_FATAL_IF_SANITY_CHECK_FAILS;
788 if (!silent)
790 error (0, 0,
791 _("Warning: filesystem %s has recently been unmounted."),
792 specific_what);
794 break;
796 case MountPointRecentlyMounted:
797 isfatal = NON_FATAL_IF_SANITY_CHECK_FAILS;
798 if (!silent)
800 error (0, 0,
801 _("Warning: filesystem %s has recently been mounted."),
802 specific_what);
804 break;
806 case MountPointStateUnchanged:
807 /* leave isfatal as it is */
808 break;
811 return isfatal;
815 #endif
819 /* Examine the results of the stat() of a directory from before we
820 * entered or left it, with the results of stat()ing it afterward. If
821 * these are different, the filesystem tree has been modified while we
822 * were traversing it. That might be an attempt to use a race
823 * condition to persuade find to do something it didn't intend
824 * (e.g. an attempt by an ordinary user to exploit the fact that root
825 * sometimes runs find on the whole filesystem). However, this can
826 * also happen if automount is running (certainly on Solaris). With
827 * automount, moving into a directory can cause a filesystem to be
828 * mounted there.
830 * To cope sensibly with this, we will raise an error if we see the
831 * device number change unless we are chdir()ing into a subdirectory,
832 * and the directory we moved into has been mounted or unmounted "recently".
833 * Here "recently" means since we started "find" or we last re-read
834 * the /etc/mnttab file.
836 * If the device number does not change but the inode does, that is a
837 * problem.
839 * If the device number and inode are both the same, we are happy.
841 * If a filesystem is (un)mounted as we chdir() into the directory, that
842 * may mean that we're now examining a section of the filesystem that might
843 * have been excluded from consideration (via -prune or -quit for example).
844 * Hence we print a warning message to indicate that the output of find
845 * might be inconsistent due to the change in the filesystem.
847 static boolean
848 wd_sanity_check(const char *thing_to_stat,
849 const char *progname,
850 const char *what,
851 dev_t old_dev,
852 ino_t old_ino,
853 struct stat *newinfo,
854 int parent,
855 int line_no,
856 enum TraversalDirection direction,
857 enum WdSanityCheckFatality isfatal,
858 boolean *changed) /* output parameter */
860 const char *fstype;
861 char *specific_what = NULL;
862 int silent = 0;
864 *changed = false;
866 if ((*options.xstat) (".", newinfo) != 0)
867 error (1, errno, "%s", thing_to_stat);
869 if (old_dev != newinfo->st_dev)
871 *changed = true;
872 specific_what = specific_dirname(what);
873 fstype = filesystem_type(newinfo);
874 silent = fs_likely_to_be_automounted(fstype);
876 /* This condition is rare, so once we are here it is
877 * reasonable to perform an expensive computation to
878 * determine if we should continue or fail.
880 if (TraversingDown == direction)
882 #ifdef STAT_MOUNTPOINTS
883 isfatal = dirchange_is_fatal(specific_what,isfatal,silent,newinfo);
884 #else
885 isfatal = RETRY_IF_SANITY_CHECK_FAILS;
886 #endif
889 switch (isfatal)
891 case FATAL_IF_SANITY_CHECK_FAILS:
893 fstype = filesystem_type(newinfo);
894 error (1, 0,
895 _("%s%s changed during execution of %s (old device number %ld, new device number %ld, filesystem type is %s) [ref %ld]"),
896 specific_what,
897 parent ? "/.." : "",
898 progname,
899 (long) old_dev,
900 (long) newinfo->st_dev,
901 fstype,
902 line_no);
903 /*NOTREACHED*/
904 return false;
907 case NON_FATAL_IF_SANITY_CHECK_FAILS:
909 /* Since the device has changed under us, the inode number
910 * will almost certainly also be different. However, we have
911 * already decided that this is not a problem. Hence we return
912 * without checking the inode number.
914 free(specific_what);
915 return true;
918 case RETRY_IF_SANITY_CHECK_FAILS:
919 return false;
923 /* Device number was the same, check if the inode has changed. */
924 if (old_ino != newinfo->st_ino)
926 *changed = true;
927 specific_what = specific_dirname(what);
928 fstype = filesystem_type(newinfo);
930 error ((isfatal == FATAL_IF_SANITY_CHECK_FAILS) ? 1 : 0,
931 0, /* no relevant errno value */
932 _("%s%s changed during execution of %s (old inode number %ld, new inode number %ld, filesystem type is %s) [ref %ld]"),
933 specific_what,
934 parent ? "/.." : "",
935 progname,
936 (long) old_ino,
937 (long) newinfo->st_ino,
938 fstype,
939 line_no);
940 free(specific_what);
941 return false;
944 return true;
947 enum SafeChdirStatus
949 SafeChdirOK,
950 SafeChdirFailSymlink,
951 SafeChdirFailNotDir,
952 SafeChdirFailStat,
953 SafeChdirFailWouldBeUnableToReturn,
954 SafeChdirFailChdirFailed,
955 SafeChdirFailNonexistent
958 /* Safely perform a change in directory. We do this by calling
959 * lstat() on the subdirectory, using chdir() to move into it, and
960 * then lstat()ing ".". We compare the results of the two stat calls
961 * to see if they are consistent. If not, we sound the alarm.
963 * If following_links() is true, we do follow symbolic links.
965 static enum SafeChdirStatus
966 safely_chdir_lstat(const char *dest,
967 enum TraversalDirection direction,
968 struct stat *statbuf_dest,
969 enum ChdirSymlinkHandling symlink_follow_option,
970 boolean *did_stat)
972 struct stat statbuf_arrived;
973 int rv, dotfd=-1;
974 int saved_errno; /* specific_dirname() changes errno. */
975 boolean rv_set = false;
976 boolean statflag = false;
977 int tries = 0;
978 enum WdSanityCheckFatality isfatal = RETRY_IF_SANITY_CHECK_FAILS;
980 saved_errno = errno = 0;
982 dotfd = open(".", O_RDONLY);
984 /* We jump back to here if wd_sanity_check()
985 * recoverably triggers an alert.
987 retry:
988 ++tries;
990 if (dotfd >= 0)
992 /* Stat the directory we're going to. */
993 if (0 == options.xstat(dest, statbuf_dest))
995 statflag = true;
997 #ifdef S_ISLNK
998 /* symlink_follow_option might be set to SymlinkFollowOk, which
999 * would allow us to chdir() into a symbolic link. This is
1000 * only useful for the case where the directory we're
1001 * chdir()ing into is the basename of a command line
1002 * argument, for example where "foo/bar/baz" is specified on
1003 * the command line. When -P is in effect (the default),
1004 * baz will not be followed if it is a symlink, but if bar
1005 * is a symlink, it _should_ be followed. Hence we need the
1006 * ability to override the policy set by following_links().
1008 if (!following_links() && S_ISLNK(statbuf_dest->st_mode))
1010 /* We're not supposed to be following links, but this is
1011 * a link. Check symlink_follow_option to see if we should
1012 * make a special exception.
1014 if (symlink_follow_option == SymlinkFollowOk)
1016 /* We need to re-stat() the file so that the
1017 * sanity check can pass.
1019 if (0 != stat(dest, statbuf_dest))
1021 rv = SafeChdirFailNonexistent;
1022 rv_set = true;
1023 saved_errno = errno;
1024 goto fail;
1026 statflag = true;
1028 else
1030 /* Not following symlinks, so the attempt to
1031 * chdir() into a symlink should be prevented.
1033 rv = SafeChdirFailSymlink;
1034 rv_set = true;
1035 saved_errno = 0; /* silence the error message */
1036 goto fail;
1039 #endif
1040 #ifdef S_ISDIR
1041 /* Although the immediately following chdir() would detect
1042 * the fact that this is not a directory for us, this would
1043 * result in an extra system call that fails. Anybody
1044 * examining the system-call trace should ideally not be
1045 * concerned that something is actually failing.
1047 if (!S_ISDIR(statbuf_dest->st_mode))
1049 rv = SafeChdirFailNotDir;
1050 rv_set = true;
1051 saved_errno = 0; /* silence the error message */
1052 goto fail;
1054 #endif
1055 #ifdef DEBUG_STAT
1056 fprintf(stderr, "safely_chdir(): chdir(\"%s\")\n", dest);
1057 #endif
1058 if (0 == chdir(dest))
1060 /* check we ended up where we wanted to go */
1061 boolean changed = false;
1062 if (!wd_sanity_check(".", program_name, ".",
1063 statbuf_dest->st_dev,
1064 statbuf_dest->st_ino,
1065 &statbuf_arrived,
1066 0, __LINE__, direction,
1067 isfatal,
1068 &changed))
1070 /* Only allow one failure. */
1071 if (RETRY_IF_SANITY_CHECK_FAILS == isfatal)
1073 if (0 == fchdir(dotfd))
1075 isfatal = FATAL_IF_SANITY_CHECK_FAILS;
1076 goto retry;
1078 else
1080 /* Failed to return to original directory,
1081 * but we know that the current working
1082 * directory is not the one that we intend
1083 * to be in. Since fchdir() failed, we
1084 * can't recover from this and so this error
1085 * is fatal.
1087 error(1, errno,
1088 "failed to return to parent directory");
1091 else
1093 /* XXX: not sure what to use as an excuse here. */
1094 rv = SafeChdirFailNonexistent;
1095 rv_set = true;
1096 saved_errno = 0;
1097 goto fail;
1101 close(dotfd);
1102 return SafeChdirOK;
1104 else
1106 saved_errno = errno;
1107 if (ENOENT == saved_errno)
1109 rv = SafeChdirFailNonexistent;
1110 rv_set = true;
1111 if (options.ignore_readdir_race)
1112 errno = 0; /* don't issue err msg */
1114 else if (ENOTDIR == saved_errno)
1116 /* This can happen if the we stat a directory,
1117 * and then filesystem activity changes it into
1118 * a non-directory.
1120 saved_errno = 0; /* don't issue err msg */
1121 rv = SafeChdirFailNotDir;
1122 rv_set = true;
1124 else
1126 rv = SafeChdirFailChdirFailed;
1127 rv_set = true;
1129 goto fail;
1132 else
1134 saved_errno = errno;
1135 rv = SafeChdirFailStat;
1136 rv_set = true;
1138 if ( (ENOENT == saved_errno) || (0 == state.curdepth))
1139 saved_errno = 0; /* don't issue err msg */
1140 goto fail;
1143 else
1145 /* We do not have read permissions on "." */
1146 rv = SafeChdirFailWouldBeUnableToReturn;
1147 rv_set = true;
1148 goto fail;
1151 /* This is the success path, so we clear errno. The caller probably
1152 * won't be calling error() anyway.
1154 saved_errno = 0;
1156 /* We use the same exit path for success or failure.
1157 * which has occurred is recorded in RV.
1159 fail:
1160 /* We do not call error() as this would result in a duplicate error
1161 * message when the caller does the same thing.
1163 if (saved_errno)
1164 errno = saved_errno;
1166 if (dotfd >= 0)
1168 close(dotfd);
1169 dotfd = -1;
1172 *did_stat = statflag;
1173 assert(rv_set);
1174 return rv;
1177 #if defined(O_NOFOLLOW)
1178 /* Safely change working directory to the specified subdirectory. If
1179 * we are not allowed to follow symbolic links, we use open() with
1180 * O_NOFOLLOW, followed by fchdir(). This ensures that we don't
1181 * follow symbolic links (of course, we do follow them if the -L
1182 * option is in effect).
1184 static enum SafeChdirStatus
1185 safely_chdir_nofollow(const char *dest,
1186 enum TraversalDirection direction,
1187 struct stat *statbuf_dest,
1188 enum ChdirSymlinkHandling symlink_follow_option,
1189 boolean *did_stat)
1191 int extraflags, fd;
1192 extraflags = 0;
1194 *did_stat = false;
1196 switch (symlink_follow_option)
1198 case SymlinkFollowOk:
1199 extraflags = 0;
1200 break;
1202 case SymlinkHandleDefault:
1203 if (following_links())
1204 extraflags = 0;
1205 else
1206 extraflags = O_NOFOLLOW;
1207 break;
1210 errno = 0;
1211 fd = open(dest, O_RDONLY|extraflags);
1212 if (fd < 0)
1214 switch (errno)
1216 case ELOOP:
1217 return SafeChdirFailSymlink; /* This is why we use O_NOFOLLOW */
1218 case ENOENT:
1219 return SafeChdirFailNonexistent;
1220 default:
1221 return SafeChdirFailChdirFailed;
1225 errno = 0;
1226 if (0 == fchdir(fd))
1228 close(fd);
1229 return SafeChdirOK;
1231 else
1233 int saved_errno = errno;
1234 close(fd);
1235 errno = saved_errno;
1237 switch (errno)
1239 case ENOTDIR:
1240 return SafeChdirFailNotDir;
1242 case EACCES:
1243 case EBADF: /* Shouldn't happen */
1244 case EINTR:
1245 case EIO:
1246 default:
1247 return SafeChdirFailChdirFailed;
1251 #endif
1253 static enum SafeChdirStatus
1254 safely_chdir(const char *dest,
1255 enum TraversalDirection direction,
1256 struct stat *statbuf_dest,
1257 enum ChdirSymlinkHandling symlink_follow_option,
1258 boolean *did_stat)
1260 /* We're about to leave a directory. If there are any -execdir
1261 * argument lists which have been built but have not yet been
1262 * processed, do them now because they must be done in the same
1263 * directory.
1265 complete_pending_execdirs(eval_tree);
1267 #if defined(O_NOFOLLOW)
1268 if (options.open_nofollow_available)
1269 return safely_chdir_nofollow(dest, direction, statbuf_dest, symlink_follow_option, did_stat);
1270 #endif
1271 return safely_chdir_lstat(dest, direction, statbuf_dest, symlink_follow_option, did_stat);
1276 /* Safely go back to the starting directory. */
1277 static void
1278 chdir_back (void)
1280 struct stat stat_buf;
1281 boolean dummy;
1283 if (starting_desc < 0)
1285 #ifdef DEBUG_STAT
1286 fprintf(stderr, "chdir_back(): chdir(\"%s\")\n", starting_dir);
1287 #endif
1289 #ifdef STAT_MOUNTPOINTS
1290 /* We will need the mounted device list. Get it now if we don't
1291 * already have it.
1293 if (NULL == mounted_devices)
1294 init_mounted_dev_list();
1295 #endif
1297 if (chdir (starting_dir) != 0)
1298 error (1, errno, "%s", starting_dir);
1300 wd_sanity_check(starting_dir,
1301 program_name,
1302 starting_dir,
1303 starting_stat_buf.st_dev,
1304 starting_stat_buf.st_ino,
1305 &stat_buf, 0, __LINE__,
1306 TraversingUp,
1307 FATAL_IF_SANITY_CHECK_FAILS,
1308 &dummy);
1310 else
1312 #ifdef DEBUG_STAT
1313 fprintf(stderr, "chdir_back(): chdir(<starting-point>)\n");
1314 #endif
1315 if (fchdir (starting_desc) != 0)
1316 error (1, errno, "%s", starting_dir);
1320 /* Move to the parent of a given directory and then call a function,
1321 * restoring the cwd. Don't bother changing directory if the
1322 * specified directory is a child of "." or is the root directory.
1324 static void
1325 at_top (char *pathname,
1326 mode_t mode,
1327 struct stat *pstat,
1328 void (*action)(char *pathname,
1329 char *basename,
1330 int mode,
1331 struct stat *pstat))
1333 int dirchange;
1334 char *parent_dir = dir_name(pathname);
1335 char *base = base_name(pathname);
1337 state.curdepth = 0;
1338 state.path_length = strlen (pathname);
1340 if (0 == strcmp(pathname, parent_dir)
1341 || 0 == strcmp(parent_dir, "."))
1343 dirchange = 0;
1344 base = pathname;
1346 else
1348 enum TraversalDirection direction;
1349 enum SafeChdirStatus chdir_status;
1350 struct stat st;
1351 boolean did_stat = false;
1353 dirchange = 1;
1354 if (0 == strcmp(base, ".."))
1355 direction = TraversingUp;
1356 else
1357 direction = TraversingDown;
1359 /* We pass SymlinkFollowOk to safely_chdir(), which allows it to
1360 * chdir() into a symbolic link. This is only useful for the
1361 * case where the directory we're chdir()ing into is the
1362 * basename of a command line argument, for example where
1363 * "foo/bar/baz" is specified on the command line. When -P is
1364 * in effect (the default), baz will not be followed if it is a
1365 * symlink, but if bar is a symlink, it _should_ be followed.
1366 * Hence we need the ability to override the policy set by
1367 * following_links().
1369 chdir_status = safely_chdir(parent_dir, direction, &st, SymlinkFollowOk, &did_stat);
1370 if (SafeChdirOK != chdir_status)
1372 const char *what = (SafeChdirFailWouldBeUnableToReturn == chdir_status) ? "." : parent_dir;
1373 if (errno)
1374 error (0, errno, "%s", what);
1375 else
1376 error (0, 0, "Failed to safely change directory into `%s'",
1377 parent_dir);
1379 /* We can't process this command-line argument. */
1380 state.exit_status = 1;
1381 return;
1385 free (parent_dir);
1386 parent_dir = NULL;
1388 action(pathname, base, mode, pstat);
1390 if (dirchange)
1392 chdir_back();
1397 static void do_process_top_dir(char *pathname,
1398 char *base,
1399 int mode,
1400 struct stat *pstat)
1402 process_path (pathname, base, false, ".", mode);
1403 complete_pending_execdirs(eval_tree);
1406 static void do_process_predicate(char *pathname,
1407 char *base,
1408 int mode,
1409 struct stat *pstat)
1411 state.rel_pathname = base;
1412 apply_predicate (pathname, pstat, eval_tree);
1418 /* Descend PATHNAME, which is a command-line argument.
1420 Actions like -execdir assume that we are in the
1421 parent directory of the file we're examining,
1422 and on entry to this function our working directory
1423 is whatever it was when find was invoked. Therefore
1424 If PATHNAME is "." we just leave things as they are.
1425 Otherwise, we figure out what the parent directory is,
1426 and move to that.
1428 static void
1429 process_top_path (char *pathname, mode_t mode)
1431 at_top(pathname, mode, NULL, do_process_top_dir);
1435 /* Info on each directory in the current tree branch, to avoid
1436 getting stuck in symbolic link loops. */
1437 static struct dir_id *dir_ids = NULL;
1438 /* Entries allocated in `dir_ids'. */
1439 static int dir_alloc = 0;
1440 /* Index in `dir_ids' of directory currently being searched.
1441 This is always the last valid entry. */
1442 static int dir_curr = -1;
1443 /* (Arbitrary) number of entries to grow `dir_ids' by. */
1444 #define DIR_ALLOC_STEP 32
1448 /* We've detected a filesystem loop. This is caused by one of
1449 * two things:
1451 * 1. Option -L is in effect and we've hit a symbolic link that
1452 * points to an ancestor. This is harmless. We won't traverse the
1453 * symbolic link.
1455 * 2. We have hit a real cycle in the directory hierarchy. In this
1456 * case, we issue a diagnostic message (POSIX requires this) and we
1457 * skip that directory entry.
1459 static void
1460 issue_loop_warning(const char *name, const char *pathname, int level)
1462 struct stat stbuf_link;
1463 if (lstat(name, &stbuf_link) != 0)
1464 stbuf_link.st_mode = S_IFREG;
1466 if (S_ISLNK(stbuf_link.st_mode))
1468 error(0, 0,
1469 _("Symbolic link `%s' is part of a loop in the directory hierarchy; we have already visited the directory to which it points."),
1470 pathname);
1472 else
1474 int distance = 1 + (dir_curr-level);
1475 /* We have found an infinite loop. POSIX requires us to
1476 * issue a diagnostic. Usually we won't get to here
1477 * because when the leaf optimisation is on, it will cause
1478 * the subdirectory to be skipped. If /a/b/c/d is a hard
1479 * link to /a/b, then the link count of /a/b/c is 2,
1480 * because the ".." entry of /b/b/c/d points to /a, not
1481 * to /a/b/c.
1483 error(0, 0,
1484 _("Filesystem loop detected; `%s' has the same device number and inode as a directory which is %d %s."),
1485 pathname,
1486 distance,
1487 (distance == 1 ?
1488 _("level higher in the filesystem hierarchy") :
1489 _("levels higher in the filesystem hierarchy")));
1493 /* Take a "mode" indicator and fill in the files of 'state'.
1495 static int
1496 digest_mode(mode_t mode,
1497 const char *pathname,
1498 const char *name,
1499 struct stat *pstat,
1500 boolean leaf)
1502 /* If we know the type of the directory entry, and it is not a
1503 * symbolic link, we may be able to avoid a stat() or lstat() call.
1505 if (mode)
1507 if (S_ISLNK(mode) && following_links())
1509 /* mode is wrong because we should have followed the symlink. */
1510 if (get_statinfo(pathname, name, pstat) != 0)
1511 return 0;
1512 mode = state.type = pstat->st_mode;
1513 state.have_type = true;
1515 else
1517 state.have_type = true;
1518 pstat->st_mode = state.type = mode;
1521 else
1523 /* Mode is not yet known; may have to stat the file unless we
1524 * can deduce that it is not a directory (which is all we need to
1525 * know at this stage)
1527 if (leaf)
1529 state.have_stat = false;
1530 state.have_type = false;;
1531 state.type = 0;
1533 else
1535 if (get_statinfo(pathname, name, pstat) != 0)
1536 return 0;
1538 /* If -L is in effect and we are dealing with a symlink,
1539 * st_mode is the mode of the pointed-to file, while mode is
1540 * the mode of the directory entry (S_IFLNK). Hence now
1541 * that we have the stat information, override "mode".
1543 state.type = pstat->st_mode;
1544 state.have_type = true;
1548 /* success. */
1549 return 1;
1554 /* Recursively descend path PATHNAME, applying the predicates.
1555 LEAF is true if PATHNAME is known to be in a directory that has no
1556 more unexamined subdirectories, and therefore it is not a directory.
1557 Knowing this allows us to avoid calling stat as long as possible for
1558 leaf files.
1560 NAME is PATHNAME relative to the current directory. We access NAME
1561 but print PATHNAME.
1563 PARENT is the path of the parent of NAME, relative to find's
1564 starting directory.
1566 Return nonzero iff PATHNAME is a directory. */
1568 static int
1569 process_path (char *pathname, char *name, boolean leaf, char *parent,
1570 mode_t mode)
1572 struct stat stat_buf;
1573 static dev_t root_dev; /* Device ID of current argument pathname. */
1574 int i;
1576 /* Assume it is a non-directory initially. */
1577 stat_buf.st_mode = 0;
1578 state.rel_pathname = name;
1579 state.type = 0;
1580 state.have_stat = false;
1581 state.have_type = false;
1583 if (!digest_mode(mode, pathname, name, &stat_buf, leaf))
1584 return 0;
1586 if (!S_ISDIR (state.type))
1588 if (state.curdepth >= options.mindepth)
1589 apply_predicate (pathname, &stat_buf, eval_tree);
1590 return 0;
1593 /* From here on, we're working on a directory. */
1596 /* Now we really need to stat the directory, even if we know the
1597 * type, because we need information like struct stat.st_rdev.
1599 if (get_statinfo(pathname, name, &stat_buf) != 0)
1600 return 0;
1602 state.have_stat = true;
1603 mode = state.type = stat_buf.st_mode; /* use full info now that we have it. */
1604 state.stop_at_current_level =
1605 options.maxdepth >= 0
1606 && state.curdepth >= options.maxdepth;
1608 /* If we've already seen this directory on this branch,
1609 don't descend it again. */
1610 for (i = 0; i <= dir_curr; i++)
1611 if (stat_buf.st_ino == dir_ids[i].ino &&
1612 stat_buf.st_dev == dir_ids[i].dev)
1614 state.stop_at_current_level = true;
1615 issue_loop_warning(name, pathname, i);
1618 if (dir_alloc <= ++dir_curr)
1620 dir_alloc += DIR_ALLOC_STEP;
1621 dir_ids = (struct dir_id *)
1622 xrealloc ((char *) dir_ids, dir_alloc * sizeof (struct dir_id));
1624 dir_ids[dir_curr].ino = stat_buf.st_ino;
1625 dir_ids[dir_curr].dev = stat_buf.st_dev;
1627 if (options.stay_on_filesystem)
1629 if (state.curdepth == 0)
1630 root_dev = stat_buf.st_dev;
1631 else if (stat_buf.st_dev != root_dev)
1632 state.stop_at_current_level = true;
1635 if (options.do_dir_first && state.curdepth >= options.mindepth)
1636 apply_predicate (pathname, &stat_buf, eval_tree);
1638 #ifdef DEBUG
1639 fprintf(stderr, "pathname = %s, stop_at_current_level = %d\n",
1640 pathname, state.stop_at_current_level);
1641 #endif /* DEBUG */
1643 if (state.stop_at_current_level == false)
1644 /* Scan directory on disk. */
1645 process_dir (pathname, name, strlen (pathname), &stat_buf, parent);
1647 if (options.do_dir_first == false && state.curdepth >= options.mindepth)
1649 /* The fields in 'state' are now out of date. Correct them.
1651 if (!digest_mode(mode, pathname, name, &stat_buf, leaf))
1652 return 0;
1654 if (0 == dir_curr)
1656 at_top(pathname, mode, &stat_buf, do_process_predicate);
1658 else
1660 do_process_predicate(pathname, name, mode, &stat_buf);
1664 dir_curr--;
1666 return 1;
1669 /* Examine the predicate list for instances of -execdir or -okdir
1670 * which have been terminated with '+' (build argument list) rather
1671 * than ';' (singles only). If there are any, run them (this will
1672 * have no effect if there are no arguments waiting).
1674 static void
1675 complete_pending_execdirs(struct predicate *p)
1677 #if defined(NEW_EXEC)
1678 if (NULL == p)
1679 return;
1681 complete_pending_execdirs(p->pred_left);
1683 if (p->pred_func == pred_execdir || p->pred_func == pred_okdir)
1685 /* It's an exec-family predicate. p->args.exec_val is valid. */
1686 if (p->args.exec_vec.multiple)
1688 struct exec_val *execp = &p->args.exec_vec;
1690 /* This one was terminated by '+' and so might have some
1691 * left... Run it if necessary.
1693 if (execp->state.todo)
1695 /* There are not-yet-executed arguments. */
1696 launch (&execp->ctl, &execp->state);
1701 complete_pending_execdirs(p->pred_right);
1702 #else
1703 /* nothing to do. */
1704 return;
1705 #endif
1708 /* Examine the predicate list for instances of -exec which have been
1709 * terminated with '+' (build argument list) rather than ';' (singles
1710 * only). If there are any, run them (this will have no effect if
1711 * there are no arguments waiting).
1713 static void
1714 complete_pending_execs(struct predicate *p)
1716 #if defined(NEW_EXEC)
1717 if (NULL == p)
1718 return;
1720 complete_pending_execs(p->pred_left);
1722 /* It's an exec-family predicate then p->args.exec_val is valid
1723 * and we can check it.
1725 if (p->pred_func == pred_exec && p->args.exec_vec.multiple)
1727 struct exec_val *execp = &p->args.exec_vec;
1729 /* This one was terminated by '+' and so might have some
1730 * left... Run it if necessary. Set state.exit_status if
1731 * there are any problems.
1733 if (execp->state.todo)
1735 /* There are not-yet-executed arguments. */
1736 launch (&execp->ctl, &execp->state);
1740 complete_pending_execs(p->pred_right);
1741 #else
1742 /* nothing to do. */
1743 return;
1744 #endif
1748 /* Scan directory PATHNAME and recurse through process_path for each entry.
1750 PATHLEN is the length of PATHNAME.
1752 NAME is PATHNAME relative to the current directory.
1754 STATP is the results of *options.xstat on it.
1756 PARENT is the path of the parent of NAME, relative to find's
1757 starting directory. */
1759 static void
1760 process_dir (char *pathname, char *name, int pathlen, struct stat *statp, char *parent)
1762 int subdirs_left; /* Number of unexamined subdirs in PATHNAME. */
1763 int idx; /* Which entry are we on? */
1764 struct stat stat_buf;
1766 #undef USE_OLD_SAVEDIR
1768 #if USE_OLD_SAVEDIR
1769 char *name_space; /* Names of files in PATHNAME. */
1770 struct savedir_extrainfo *extra;
1771 #else
1772 struct savedir_dirinfo *dirinfo;
1773 #endif
1774 subdirs_left = statp->st_nlink - 2; /* Account for name and ".". */
1776 errno = 0;
1777 #if USE_OLD_SAVEDIR
1778 name_space = savedirinfo (name, &extra);
1779 #else
1780 dirinfo = xsavedir(name, 0);
1781 #endif
1783 if (
1784 #if USE_OLD_SAVEDIR
1785 name_space
1786 #else
1787 dirinfo
1788 #endif
1789 == NULL)
1791 assert(errno != 0);
1792 error (0, errno, "%s", pathname);
1793 state.exit_status = 1;
1795 else
1797 register char *namep; /* Current point in `name_space'. */
1798 char *cur_path; /* Full path of each file to process. */
1799 char *cur_name; /* Base name of each file to process. */
1800 unsigned cur_path_size; /* Bytes allocated for `cur_path'. */
1801 register unsigned file_len; /* Length of each path to process. */
1802 register unsigned pathname_len; /* PATHLEN plus trailing '/'. */
1803 boolean did_stat = false;
1805 if (pathname[pathlen - 1] == '/')
1806 pathname_len = pathlen + 1; /* For '\0'; already have '/'. */
1807 else
1808 pathname_len = pathlen + 2; /* For '/' and '\0'. */
1809 cur_path_size = 0;
1810 cur_path = NULL;
1812 /* We're about to leave the directory. If there are any
1813 * -execdir argument lists which have been built but have not
1814 * yet been processed, do them now because they must be done in
1815 * the same directory.
1817 complete_pending_execdirs(eval_tree);
1819 if (strcmp (name, "."))
1821 enum SafeChdirStatus status = safely_chdir (name, TraversingDown, &stat_buf, SymlinkHandleDefault, &did_stat);
1822 switch (status)
1824 case SafeChdirOK:
1825 /* If there had been a change but wd_sanity_check()
1826 * accepted it, we need to accept that on the
1827 * way back up as well, so modify our record
1828 * of what we think we should see later.
1829 * If there was no change, the assignments are a no-op.
1831 * However, before performing the assignment, we need to
1832 * check that we have the stat information. If O_NOFOLLOW
1833 * is available, safely_chdir() will not have needed to use
1834 * stat(), and so stat_buf will just contain random data.
1836 if (!did_stat)
1838 /* If there is a link we need to follow it. Hence
1839 * the direct call to stat() not through (options.xstat)
1841 if (0 != stat(".", &stat_buf))
1842 break; /* skip the assignment. */
1844 dir_ids[dir_curr].dev = stat_buf.st_dev;
1845 dir_ids[dir_curr].ino = stat_buf.st_ino;
1847 break;
1849 case SafeChdirFailWouldBeUnableToReturn:
1850 error (0, errno, ".");
1851 state.exit_status = 1;
1852 break;
1854 case SafeChdirFailNonexistent:
1855 case SafeChdirFailStat:
1856 case SafeChdirFailSymlink:
1857 case SafeChdirFailNotDir:
1858 case SafeChdirFailChdirFailed:
1859 error (0, errno, "%s", pathname);
1860 state.exit_status = 1;
1861 return;
1865 #if USE_OLD_SAVEDIR
1866 for (idx=0, namep = name_space; *namep; namep += file_len - pathname_len + 1, ++idx)
1867 #else
1868 for (idx=0; idx < dirinfo->size; ++idx)
1869 #endif
1871 /* savedirinfo() may return dirinfo=NULL if extended information
1872 * is not available.
1874 #if USE_OLD_SAVEDIR
1875 mode_t mode = extra ? extra[idx].type_info : 0;
1876 #else
1877 mode_t mode = (dirinfo->entries[idx].flags & SavedirHaveFileType) ?
1878 dirinfo->entries[idx].type_info : 0;
1879 namep = dirinfo->entries[idx].name;
1880 #endif
1881 /* Append this directory entry's name to the path being searched. */
1882 file_len = pathname_len + strlen (namep);
1883 if (file_len > cur_path_size)
1885 while (file_len > cur_path_size)
1886 cur_path_size += 1024;
1887 if (cur_path)
1888 free (cur_path);
1889 cur_path = xmalloc (cur_path_size);
1890 strcpy (cur_path, pathname);
1891 cur_path[pathname_len - 2] = '/';
1893 cur_name = cur_path + pathname_len - 1;
1894 strcpy (cur_name, namep);
1896 state.curdepth++;
1897 if (!options.no_leaf_check)
1899 if (mode && S_ISDIR(mode) && (subdirs_left == 0))
1901 /* This is a subdirectory, but the number of directories we
1902 * have found now exceeds the number we would expect given
1903 * the hard link count on the parent. This is likely to be
1904 * a bug in the filesystem driver (e.g. Linux's
1905 * /proc filesystem) or may just be a fact that the OS
1906 * doesn't really handle hard links with Unix semantics.
1907 * In the latter case, -noleaf should be used routinely.
1909 error(0, 0, _("WARNING: Hard link count is wrong for %s: this may be a bug in your filesystem driver. Automatically turning on find's -noleaf option. Earlier results may have failed to include directories that should have been searched."),
1910 parent);
1911 state.exit_status = 1; /* We know the result is wrong, now */
1912 options.no_leaf_check = true; /* Don't make same
1913 mistake again */
1914 subdirs_left = 1; /* band-aid for this iteration. */
1917 /* Normal case optimization. On normal Unix
1918 filesystems, a directory that has no subdirectories
1919 has two links: its name, and ".". Any additional
1920 links are to the ".." entries of its subdirectories.
1921 Once we have processed as many subdirectories as
1922 there are additional links, we know that the rest of
1923 the entries are non-directories -- in other words,
1924 leaf files. */
1925 subdirs_left -= process_path (cur_path, cur_name,
1926 subdirs_left == 0, pathname,
1927 mode);
1929 else
1931 /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems
1932 mounted, which don't have Unix-like directory link counts. */
1933 process_path (cur_path, cur_name, false, pathname, mode);
1936 state.curdepth--;
1940 /* We're about to leave the directory. If there are any
1941 * -execdir argument lists which have been built but have not
1942 * yet been processed, do them now because they must be done in
1943 * the same directory.
1945 complete_pending_execdirs(eval_tree);
1948 if (strcmp (name, "."))
1950 enum SafeChdirStatus status;
1951 struct dir_id did;
1952 boolean did_stat = false;
1954 /* We could go back and do the next command-line arg
1955 instead, maybe using longjmp. */
1956 char const *dir;
1957 boolean deref = following_links() ? true : false;
1959 if ( (state.curdepth>0) && !deref)
1960 dir = "..";
1961 else
1963 chdir_back ();
1964 dir = parent;
1967 status = safely_chdir (dir, TraversingUp, &stat_buf, SymlinkHandleDefault, &did_stat);
1968 switch (status)
1970 case SafeChdirOK:
1971 break;
1973 case SafeChdirFailWouldBeUnableToReturn:
1974 error (1, errno, ".");
1975 return;
1977 case SafeChdirFailNonexistent:
1978 case SafeChdirFailStat:
1979 case SafeChdirFailSymlink:
1980 case SafeChdirFailNotDir:
1981 case SafeChdirFailChdirFailed:
1982 error (1, errno, "%s", pathname);
1983 return;
1986 if (dir_curr > 0)
1988 did.dev = dir_ids[dir_curr-1].dev;
1989 did.ino = dir_ids[dir_curr-1].ino;
1991 else
1993 did.dev = starting_stat_buf.st_dev;
1994 did.ino = starting_stat_buf.st_ino;
1998 if (cur_path)
1999 free (cur_path);
2000 #ifdef USE_OLD_SAVEDIR
2001 free (name_space);
2002 free (extra);
2003 #else
2004 free_dirinfo(dirinfo);
2005 #endif
2009 /* Return true if there are no predicates with no_default_print in
2010 predicate list PRED, false if there are any.
2011 Returns true if default print should be performed */
2013 static boolean
2014 default_prints (struct predicate *pred)
2016 while (pred != NULL)
2018 if (pred->no_default_print)
2019 return (false);
2020 pred = pred->pred_next;
2022 return (true);