Fixed SourceForge bug 12181 (find -H symlink-to-dir reports 'Too many Symbolic links...
[findutils.git] / find / find.c
blobdf96680a81e6db7bba6fc9bf5f9837ab78e193a7
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
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 derefernce 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 DBEUG_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 PFB 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 dirname[1024];
658 if (0 == strcmp(".", dir))
660 /* OK, what's '.'? */
661 if (NULL != getcwd(dirname, sizeof(dirname)))
663 return strdup(dirname);
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 *program_name,
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 program_name,
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 program_name,
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() tro 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_handling)
971 struct stat statbuf_arrived;
972 int rv, dotfd=-1;
973 int saved_errno; /* specific_dirname() changes errno. */
974 boolean rv_set = false;
975 int tries = 0;
976 enum WdSanityCheckFatality isfatal = RETRY_IF_SANITY_CHECK_FAILS;
978 saved_errno = errno = 0;
980 dotfd = open(".", O_RDONLY);
982 /* We jump back to here if wd_sanity_check()
983 * recoverably triggers an alert.
985 retry:
986 ++tries;
988 if (dotfd >= 0)
990 /* Stat the directory we're going to. */
991 if (0 == options.xstat(dest, statbuf_dest))
993 #ifdef S_ISLNK
994 /* symlink_handling might be set to SymlinkFollowOk, which
995 * would allow us to chdir() into a symbolic link. This is
996 * only useful for the case where the directory we're
997 * chdir()ing into is the basename of a command line
998 * argument, for example where "foo/bar/baz" is specified on
999 * the command line. When -P is in effect (the default),
1000 * baz will not be followed if it is a symlink, but if bar
1001 * is a symlink, it _should_ be followed. Hence we need the
1002 * ability to override the policy set by following_links().
1004 if (!following_links() && S_ISLNK(statbuf_dest->st_mode))
1006 /* We're not supposed to be following links, but this is
1007 * a link. Check symlink_handling to see if we should
1008 * make a special exception.
1010 if (symlink_handling == SymlinkFollowOk)
1012 /* We need to re-stat() the file so that the
1013 * sanity check can pass.
1015 if (0 != stat(dest, statbuf_dest))
1017 rv = SafeChdirFailNonexistent;
1018 rv_set = true;
1019 saved_errno = errno;
1020 goto fail;
1023 else
1025 /* Not following symlinks, so the attempt to
1026 * chdir() into a symlink should be prevented.
1028 rv = SafeChdirFailSymlink;
1029 rv_set = true;
1030 saved_errno = 0; /* silence the error message */
1031 goto fail;
1034 #endif
1035 #ifdef S_ISDIR
1036 /* Although the immediately following chdir() would detect
1037 * the fact that this is not a directory for us, this would
1038 * result in an extra system call that fails. Anybody
1039 * examining the system-call trace should ideally not be
1040 * concerned that something is actually failing.
1042 if (!S_ISDIR(statbuf_dest->st_mode))
1044 rv = SafeChdirFailNotDir;
1045 rv_set = true;
1046 saved_errno = 0; /* silence the error message */
1047 goto fail;
1049 #endif
1050 #ifdef DEBUG_STAT
1051 fprintf(stderr, "safely_chdir(): chdir(\"%s\")\n", dest);
1052 #endif
1053 if (0 == chdir(dest))
1055 /* check we ended up where we wanted to go */
1056 boolean changed = false;
1057 if (!wd_sanity_check(".", program_name, ".",
1058 statbuf_dest->st_dev,
1059 statbuf_dest->st_ino,
1060 &statbuf_arrived,
1061 0, __LINE__, direction,
1062 isfatal,
1063 &changed))
1065 /* Only allow one failure. */
1066 if ((RETRY_IF_SANITY_CHECK_FAILS == isfatal)
1067 && (0 == fchdir(dotfd)))
1069 isfatal = FATAL_IF_SANITY_CHECK_FAILS;
1070 goto retry;
1072 else
1074 /* XXX: not sure what to use as an excuse here. */
1075 rv = SafeChdirFailNonexistent;
1076 rv_set = true;
1077 saved_errno = 0;
1078 goto fail;
1082 close(dotfd);
1083 return SafeChdirOK;
1085 else
1087 saved_errno = errno;
1088 if (ENOENT == saved_errno)
1090 rv = SafeChdirFailNonexistent;
1091 rv_set = true;
1092 if (options.ignore_readdir_race)
1093 errno = 0; /* don't issue err msg */
1095 else if (ENOTDIR == saved_errno)
1097 /* This can happen if the we stat a directory,
1098 * and then filesystem activity changes it into
1099 * a non-directory.
1101 saved_errno = 0; /* don't issue err msg */
1102 rv = SafeChdirFailNotDir;
1103 rv_set = true;
1105 else
1107 rv = SafeChdirFailChdirFailed;
1108 rv_set = true;
1110 goto fail;
1113 else
1115 saved_errno = errno;
1116 rv = SafeChdirFailStat;
1117 rv_set = true;
1119 if ( (ENOENT == saved_errno) || (0 == state.curdepth))
1120 saved_errno = 0; /* don't issue err msg */
1121 goto fail;
1124 else
1126 /* We do not have read permissions on "." */
1127 rv = SafeChdirFailWouldBeUnableToReturn;
1128 rv_set = true;
1129 goto fail;
1132 /* This is the success path, so we clear errno. The caller probably
1133 * won't be calling error() anyway.
1135 saved_errno = 0;
1137 /* We use the same exit path for successs or failure.
1138 * which has occurred is recorded in RV.
1140 fail:
1141 /* We do not call error() as this would result in a duplicate error
1142 * message when the caller does the same thing.
1144 if (saved_errno)
1145 errno = saved_errno;
1147 if (dotfd >= 0)
1149 close(dotfd);
1150 dotfd = -1;
1152 assert(rv_set);
1153 return rv;
1156 #if defined(O_NOFOLLOW)
1157 /* Safely change working directory to the specified subdirectory. If
1158 * we are not allowed to follow symbolic links, we use open() with
1159 * O_NOFOLLOW, followed by fchdir(). This ensures that we don't
1160 * follow symbolic links (of course, we do follow them if the -L
1161 * option is in effect).
1163 static enum SafeChdirStatus
1164 safely_chdir_nofollow(const char *dest,
1165 enum TraversalDirection direction,
1166 struct stat *statbuf_dest,
1167 enum ChdirSymlinkHandling symlink_handling)
1169 int extraflags, fd;
1170 extraflags = 0;
1172 switch (symlink_handling)
1174 case SymlinkFollowOk:
1175 extraflags = 0;
1176 break;
1178 case SymlinkHandleDefault:
1179 if (following_links())
1180 extraflags = 0;
1181 else
1182 extraflags = O_NOFOLLOW;
1183 break;
1186 errno = 0;
1187 fd = open(dest, O_RDONLY|extraflags);
1188 if (fd < 0)
1190 switch (errno)
1192 case ELOOP:
1193 return SafeChdirFailSymlink; /* This is why we use O_NOFOLLOW */
1194 case ENOENT:
1195 return SafeChdirFailNonexistent;
1196 default:
1197 return SafeChdirFailChdirFailed;
1201 errno = 0;
1202 if (0 == fchdir(fd))
1204 close(fd);
1205 return SafeChdirOK;
1207 else
1209 int saved_errno = errno;
1210 close(fd);
1211 errno = saved_errno;
1213 switch (errno)
1215 case ENOTDIR:
1216 return SafeChdirFailNotDir;
1218 case EACCES:
1219 case EBADF: /* Shouldn't happen */
1220 case EINTR:
1221 case EIO:
1222 default:
1223 return SafeChdirFailChdirFailed;
1227 #endif
1229 static enum SafeChdirStatus
1230 safely_chdir(const char *dest,
1231 enum TraversalDirection direction,
1232 struct stat *statbuf_dest,
1233 enum ChdirSymlinkHandling symlink_handling)
1235 /* We're about to leave a directory. If there are any -execdir
1236 * argument lists which have been built but have not yet been
1237 * processed, do them now because they must be done in the same
1238 * directory.
1240 complete_pending_execdirs(eval_tree);
1242 #if defined(O_NOFOLLOW)
1243 if (options.open_nofollow_available)
1244 return safely_chdir_nofollow(dest, direction, statbuf_dest, symlink_handling);
1245 #endif
1246 return safely_chdir_lstat(dest, direction, statbuf_dest, symlink_handling);
1251 /* Safely go back to the starting directory. */
1252 static void
1253 chdir_back (void)
1255 struct stat stat_buf;
1256 boolean dummy;
1258 if (starting_desc < 0)
1260 #ifdef DEBUG_STAT
1261 fprintf(stderr, "chdir_back(): chdir(\"%s\")\n", starting_dir);
1262 #endif
1264 #ifdef STAT_MOUNTPOINTS
1265 /* We will need the mounted device list. Get it now if we don't
1266 * already have it.
1268 if (NULL == mounted_devices)
1269 init_mounted_dev_list();
1270 #endif
1272 if (chdir (starting_dir) != 0)
1273 error (1, errno, "%s", starting_dir);
1275 wd_sanity_check(starting_dir,
1276 program_name,
1277 starting_dir,
1278 starting_stat_buf.st_dev,
1279 starting_stat_buf.st_ino,
1280 &stat_buf, 0, __LINE__,
1281 TraversingUp,
1282 FATAL_IF_SANITY_CHECK_FAILS,
1283 &dummy);
1285 else
1287 #ifdef DEBUG_STAT
1288 fprintf(stderr, "chdir_back(): chdir(<starting-point>)\n");
1289 #endif
1290 if (fchdir (starting_desc) != 0)
1291 error (1, errno, "%s", starting_dir);
1295 /* Descend PATHNAME, which is a command-line argument.
1296 Actions like -execdir assume that we are in the
1297 parent directory of the file we're examining,
1298 and on entry to this function our working directory
1299 is whetever it was when find was invoked. Therefore
1300 If PATHNAME is "." we just leave things as they are.
1301 Otherwise, we figure out what the parent directory is,
1302 and move to that.
1304 static void
1305 process_top_path (char *pathname, mode_t mode)
1307 int dirchange;
1308 char *parent_dir = dir_name(pathname);
1309 char *base = base_name(pathname);
1311 state.curdepth = 0;
1312 state.path_length = strlen (pathname);
1314 if (0 == strcmp(pathname, parent_dir)
1315 || 0 == strcmp(parent_dir, "."))
1317 dirchange = 0;
1318 base = pathname;
1320 else
1322 enum TraversalDirection direction;
1323 enum SafeChdirStatus chdir_status;
1324 struct stat st;
1326 dirchange = 1;
1327 if (0 == strcmp(base, ".."))
1328 direction = TraversingUp;
1329 else
1330 direction = TraversingDown;
1332 /* We pass SymlinkFollowOk to safely_chdir(), which allows it to
1333 * chdir() into a symbolic link. This is only useful for the
1334 * case where the directory we're chdir()ing into is the
1335 * basename of a command line argument, for example where
1336 * "foo/bar/baz" is specified on the command line. When -P is
1337 * in effect (the default), baz will not be followed if it is a
1338 * symlink, but if bar is a symlink, it _should_ be followed.
1339 * Hence we need the ability to override the policy set by
1340 * following_links().
1342 chdir_status = safely_chdir(parent_dir, direction, &st, SymlinkFollowOk);
1343 if (SafeChdirOK != chdir_status)
1345 const char *what = (SafeChdirFailWouldBeUnableToReturn == chdir_status) ? "." : parent_dir;
1346 if (errno)
1347 error (0, errno, "%s", what);
1348 else
1349 error (0, 0, "Failed to safely change directory into `%s'",
1350 parent_dir);
1352 /* We can't process this command-line argument. */
1353 state.exit_status = 1;
1354 return;
1358 free (parent_dir);
1359 parent_dir = NULL;
1361 process_path (pathname, base, false, ".", mode);
1362 complete_pending_execdirs(eval_tree);
1364 if (dirchange)
1366 chdir_back();
1371 /* Info on each directory in the current tree branch, to avoid
1372 getting stuck in symbolic link loops. */
1373 static struct dir_id *dir_ids = NULL;
1374 /* Entries allocated in `dir_ids'. */
1375 static int dir_alloc = 0;
1376 /* Index in `dir_ids' of directory currently being searched.
1377 This is always the last valid entry. */
1378 static int dir_curr = -1;
1379 /* (Arbitrary) number of entries to grow `dir_ids' by. */
1380 #define DIR_ALLOC_STEP 32
1384 /* We've detected a filesystem loop. This is caused by one of
1385 * two things:
1387 * 1. Option -L is in effect and we've hit a symbolic link that
1388 * points to an ancestor. This is harmless. We won't traverse the
1389 * symbolic link.
1391 * 2. We have hit a real cycle in the directory hierarchy. In this
1392 * case, we issue a diagnostic message (POSIX requires this) and we
1393 * skip that directory entry.
1395 static void
1396 issue_loop_warning(const char *name, const char *pathname, int level)
1398 struct stat stbuf_link;
1399 if (lstat(name, &stbuf_link) != 0)
1400 stbuf_link.st_mode = S_IFREG;
1402 if (S_ISLNK(stbuf_link.st_mode))
1404 error(0, 0,
1405 _("Symbolic link `%s' is part of a loop in the directory hierarchy; we have already visited the directory to which it points."),
1406 pathname);
1408 else
1410 int distance = 1 + (dir_curr-level);
1411 /* We have found an infinite loop. POSIX requires us to
1412 * issue a diagnostic. Usually we won't get to here
1413 * because when the leaf optimisation is on, it will cause
1414 * the subdirectory to be skipped. If /a/b/c/d is a hard
1415 * link to /a/b, then the link count of /a/b/c is 2,
1416 * because the ".." entry of /b/b/c/d points to /a, not
1417 * to /a/b/c.
1419 error(0, 0,
1420 _("Filesystem loop detected; `%s' has the same device number and inode as a directory which is %d %s."),
1421 pathname,
1422 distance,
1423 (distance == 1 ?
1424 _("level higher in the filesystem hierarchy") :
1425 _("levels higher in the filesystem hierarchy")));
1429 /* Take a "mode" indicator and fill in the files of 'state'.
1431 static int
1432 digest_mode(mode_t mode,
1433 const char *pathname,
1434 const char *name,
1435 struct stat *pstat,
1436 boolean leaf)
1438 /* If we know the type of the directory entry, and it is not a
1439 * symbolic link, we may be able to avoid a stat() or lstat() call.
1441 if (mode)
1443 if (S_ISLNK(mode) && following_links())
1445 /* mode is wrong because we should have followed the symlink. */
1446 if (get_statinfo(pathname, name, pstat) != 0)
1447 return 0;
1448 mode = state.type = pstat->st_mode;
1449 state.have_type = true;
1451 else
1453 state.have_type = true;
1454 pstat->st_mode = state.type = mode;
1457 else
1459 /* Mode is not yet known; may have to stat the file unless we
1460 * can deduce that it is not a directory (which is all we need to
1461 * know at this stage)
1463 if (leaf)
1465 state.have_stat = false;
1466 state.have_type = false;;
1467 state.type = 0;
1469 else
1471 if (get_statinfo(pathname, name, pstat) != 0)
1472 return 0;
1474 /* If -L is in effect and we are dealing with a symlink,
1475 * st_mode is the mode of the pointed-to file, while mode is
1476 * the mode of the directory entry (S_IFLNK). Hence now
1477 * that we have the stat information, override "mode".
1479 state.type = pstat->st_mode;
1480 state.have_type = true;
1484 /* success. */
1485 return 1;
1490 /* Recursively descend path PATHNAME, applying the predicates.
1491 LEAF is true if PATHNAME is known to be in a directory that has no
1492 more unexamined subdirectories, and therefore it is not a directory.
1493 Knowing this allows us to avoid calling stat as long as possible for
1494 leaf files.
1496 NAME is PATHNAME relative to the current directory. We access NAME
1497 but print PATHNAME.
1499 PARENT is the path of the parent of NAME, relative to find's
1500 starting directory.
1502 Return nonzero iff PATHNAME is a directory. */
1504 static int
1505 process_path (char *pathname, char *name, boolean leaf, char *parent,
1506 mode_t mode)
1508 struct stat stat_buf;
1509 static dev_t root_dev; /* Device ID of current argument pathname. */
1510 int i;
1512 /* Assume it is a non-directory initially. */
1513 stat_buf.st_mode = 0;
1514 state.rel_pathname = name;
1515 state.type = 0;
1516 state.have_stat = false;
1517 state.have_type = false;
1519 if (!digest_mode(mode, pathname, name, &stat_buf, leaf))
1520 return 0;
1522 if (!S_ISDIR (state.type))
1524 if (state.curdepth >= options.mindepth)
1525 apply_predicate (pathname, &stat_buf, eval_tree);
1526 return 0;
1529 /* From here on, we're working on a directory. */
1532 /* Now we really need to stat the directory, even if we know the
1533 * type, because we need information like struct stat.st_rdev.
1535 if (get_statinfo(pathname, name, &stat_buf) != 0)
1536 return 0;
1538 state.have_stat = true;
1539 mode = state.type = stat_buf.st_mode; /* use full info now that we have it. */
1540 state.stop_at_current_level =
1541 options.maxdepth >= 0
1542 && state.curdepth >= options.maxdepth;
1544 /* If we've already seen this directory on this branch,
1545 don't descend it again. */
1546 for (i = 0; i <= dir_curr; i++)
1547 if (stat_buf.st_ino == dir_ids[i].ino &&
1548 stat_buf.st_dev == dir_ids[i].dev)
1550 state.stop_at_current_level = true;
1551 issue_loop_warning(name, pathname, i);
1554 if (dir_alloc <= ++dir_curr)
1556 dir_alloc += DIR_ALLOC_STEP;
1557 dir_ids = (struct dir_id *)
1558 xrealloc ((char *) dir_ids, dir_alloc * sizeof (struct dir_id));
1560 dir_ids[dir_curr].ino = stat_buf.st_ino;
1561 dir_ids[dir_curr].dev = stat_buf.st_dev;
1563 if (options.stay_on_filesystem)
1565 if (state.curdepth == 0)
1566 root_dev = stat_buf.st_dev;
1567 else if (stat_buf.st_dev != root_dev)
1568 state.stop_at_current_level = true;
1571 if (options.do_dir_first && state.curdepth >= options.mindepth)
1572 apply_predicate (pathname, &stat_buf, eval_tree);
1574 #ifdef DEBUG
1575 fprintf(stderr, "pathname = %s, stop_at_current_level = %d\n",
1576 pathname, state.stop_at_current_level);
1577 #endif /* DEBUG */
1579 if (state.stop_at_current_level == false)
1580 /* Scan directory on disk. */
1581 process_dir (pathname, name, strlen (pathname), &stat_buf, parent);
1583 if (options.do_dir_first == false && state.curdepth >= options.mindepth)
1585 /* The fields in 'state' are now out of date. Correct them.
1587 if (!digest_mode(mode, pathname, name, &stat_buf, leaf))
1588 return 0;
1590 state.rel_pathname = name;
1591 apply_predicate (pathname, &stat_buf, eval_tree);
1594 dir_curr--;
1596 return 1;
1599 /* Examine the predicate list for instances of -execdir or -okdir
1600 * which have been terminated with '+' (build argument list) rather
1601 * than ';' (singles only). If there are any, run them (this will
1602 * have no effect if there are no arguments waiting).
1604 static void
1605 complete_pending_execdirs(struct predicate *p)
1607 #if defined(NEW_EXEC)
1608 if (NULL == p)
1609 return;
1611 complete_pending_execdirs(p->pred_left);
1613 if (p->pred_func == pred_execdir || p->pred_func == pred_okdir)
1615 /* It's an exec-family predicate. p->args.exec_val is valid. */
1616 if (p->args.exec_vec.multiple)
1618 struct exec_val *execp = &p->args.exec_vec;
1620 /* This one was terminated by '+' and so might have some
1621 * left... Run it if neccessary.
1623 if (execp->state.todo)
1625 /* There are not-yet-executed arguments. */
1626 launch (&execp->ctl, &execp->state);
1631 complete_pending_execdirs(p->pred_right);
1632 #else
1633 /* nothing to do. */
1634 return;
1635 #endif
1638 /* Examine the predicate list for instances of -exec which have been
1639 * terminated with '+' (build argument list) rather than ';' (singles
1640 * only). If there are any, run them (this will have no effect if
1641 * there are no arguments waiting).
1643 static void
1644 complete_pending_execs(struct predicate *p)
1646 #if defined(NEW_EXEC)
1647 if (NULL == p)
1648 return;
1650 complete_pending_execs(p->pred_left);
1652 /* It's an exec-family predicate then p->args.exec_val is valid
1653 * and we can check it.
1655 if (p->pred_func == pred_exec && p->args.exec_vec.multiple)
1657 struct exec_val *execp = &p->args.exec_vec;
1659 /* This one was terminated by '+' and so might have some
1660 * left... Run it if neccessary. Set state.exit_status if
1661 * there are any problems.
1663 if (execp->state.todo)
1665 /* There are not-yet-executed arguments. */
1666 launch (&execp->ctl, &execp->state);
1670 complete_pending_execs(p->pred_right);
1671 #else
1672 /* nothing to do. */
1673 return;
1674 #endif
1678 /* Scan directory PATHNAME and recurse through process_path for each entry.
1680 PATHLEN is the length of PATHNAME.
1682 NAME is PATHNAME relative to the current directory.
1684 STATP is the results of *options.xstat on it.
1686 PARENT is the path of the parent of NAME, relative to find's
1687 starting directory. */
1689 static void
1690 process_dir (char *pathname, char *name, int pathlen, struct stat *statp, char *parent)
1692 char *name_space; /* Names of files in PATHNAME. */
1693 int subdirs_left; /* Number of unexamined subdirs in PATHNAME. */
1694 int idx; /* Which entry are we on? */
1695 struct stat stat_buf;
1696 struct savedir_dirinfo *dirinfo;
1698 subdirs_left = statp->st_nlink - 2; /* Account for name and ".". */
1700 errno = 0;
1701 name_space = savedirinfo (name, &dirinfo);
1703 if (name_space == NULL)
1705 assert(errno != 0);
1706 error (0, errno, "%s", pathname);
1707 state.exit_status = 1;
1709 else
1711 register char *namep; /* Current point in `name_space'. */
1712 char *cur_path; /* Full path of each file to process. */
1713 char *cur_name; /* Base name of each file to process. */
1714 unsigned cur_path_size; /* Bytes allocated for `cur_path'. */
1715 register unsigned file_len; /* Length of each path to process. */
1716 register unsigned pathname_len; /* PATHLEN plus trailing '/'. */
1718 if (pathname[pathlen - 1] == '/')
1719 pathname_len = pathlen + 1; /* For '\0'; already have '/'. */
1720 else
1721 pathname_len = pathlen + 2; /* For '/' and '\0'. */
1722 cur_path_size = 0;
1723 cur_path = NULL;
1725 /* We're about to leave the directory. If there are any
1726 * -execdir argument lists which have been built but have not
1727 * yet been processed, do them now because they must be done in
1728 * the same directory.
1730 complete_pending_execdirs(eval_tree);
1732 if (strcmp (name, "."))
1734 enum SafeChdirStatus status = safely_chdir (name, TraversingDown, &stat_buf, SymlinkHandleDefault);
1735 switch (status)
1737 case SafeChdirOK:
1738 /* If there had been a change but wd_sanity_check()
1739 * accepted it, we need to accept that on the
1740 * way back up as well, so modify our record
1741 * of what we think we should see later.
1742 * If there was no change, the assignments are a no-op.
1744 dir_ids[dir_curr].dev = stat_buf.st_dev;
1745 dir_ids[dir_curr].ino = stat_buf.st_ino;
1746 break;
1748 case SafeChdirFailWouldBeUnableToReturn:
1749 error (0, errno, ".");
1750 state.exit_status = 1;
1751 break;
1753 case SafeChdirFailNonexistent:
1754 case SafeChdirFailStat:
1755 case SafeChdirFailSymlink:
1756 case SafeChdirFailNotDir:
1757 case SafeChdirFailChdirFailed:
1758 error (0, errno, "%s", pathname);
1759 state.exit_status = 1;
1760 return;
1765 for (idx=0, namep = name_space; *namep; namep += file_len - pathname_len + 1, ++idx)
1767 /* savedirinfo() may return dirinfo=NULL if extended information
1768 * is not available.
1770 mode_t mode = dirinfo ? dirinfo[idx].type_info : 0;
1772 /* Append this directory entry's name to the path being searched. */
1773 file_len = pathname_len + strlen (namep);
1774 if (file_len > cur_path_size)
1776 while (file_len > cur_path_size)
1777 cur_path_size += 1024;
1778 if (cur_path)
1779 free (cur_path);
1780 cur_path = xmalloc (cur_path_size);
1781 strcpy (cur_path, pathname);
1782 cur_path[pathname_len - 2] = '/';
1784 cur_name = cur_path + pathname_len - 1;
1785 strcpy (cur_name, namep);
1787 state.curdepth++;
1788 if (!options.no_leaf_check)
1790 if (mode && S_ISDIR(mode) && (subdirs_left == 0))
1792 /* This is a subdirectory, but the number of directories we
1793 * have found now exceeds the number we would expect given
1794 * the hard link count on the parent. This is likely to be
1795 * a bug in the filesystem driver (e.g. Linux's
1796 * /proc filesystem) or may just be a fact that the OS
1797 * doesn't really handle hard links with Unix semantics.
1798 * In the latter case, -noleaf should be used routinely.
1800 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."),
1801 parent);
1802 state.exit_status = 1; /* We know the result is wrong, now */
1803 options.no_leaf_check = true; /* Don't make same
1804 mistake again */
1805 subdirs_left = 1; /* band-aid for this iteration. */
1808 /* Normal case optimization. On normal Unix
1809 filesystems, a directory that has no subdirectories
1810 has two links: its name, and ".". Any additional
1811 links are to the ".." entries of its subdirectories.
1812 Once we have processed as many subdirectories as
1813 there are additional links, we know that the rest of
1814 the entries are non-directories -- in other words,
1815 leaf files. */
1816 subdirs_left -= process_path (cur_path, cur_name,
1817 subdirs_left == 0, pathname,
1818 mode);
1820 else
1822 /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems
1823 mounted, which don't have Unix-like directory link counts. */
1824 process_path (cur_path, cur_name, false, pathname, mode);
1827 state.curdepth--;
1831 /* We're about to leave the directory. If there are any
1832 * -execdir argument lists which have been built but have not
1833 * yet been processed, do them now because they must be done in
1834 * the same directory.
1836 complete_pending_execdirs(eval_tree);
1839 if (strcmp (name, "."))
1841 enum SafeChdirStatus status;
1842 struct dir_id did;
1843 boolean changed = false;
1845 /* We could go back and do the next command-line arg
1846 instead, maybe using longjmp. */
1847 char const *dir;
1848 boolean deref = following_links() ? true : false;
1850 if ( (state.curdepth>0) && !deref)
1851 dir = "..";
1852 else
1854 chdir_back ();
1855 dir = parent;
1858 status = safely_chdir (dir, TraversingUp, &stat_buf, SymlinkHandleDefault);
1859 switch (status)
1861 case SafeChdirOK:
1862 break;
1864 case SafeChdirFailWouldBeUnableToReturn:
1865 error (1, errno, ".");
1866 return;
1868 case SafeChdirFailNonexistent:
1869 case SafeChdirFailStat:
1870 case SafeChdirFailSymlink:
1871 case SafeChdirFailNotDir:
1872 case SafeChdirFailChdirFailed:
1873 error (1, errno, "%s", pathname);
1874 return;
1877 if (dir_curr > 0)
1879 did.dev = dir_ids[dir_curr-1].dev;
1880 did.ino = dir_ids[dir_curr-1].ino;
1882 else
1884 did.dev = starting_stat_buf.st_dev;
1885 did.ino = starting_stat_buf.st_ino;
1889 if (cur_path)
1890 free (cur_path);
1891 free (name_space);
1892 free (dirinfo);
1896 /* Return true if there are no predicates with no_default_print in
1897 predicate list PRED, false if there are any.
1898 Returns true if default print should be performed */
1900 static boolean
1901 default_prints (struct predicate *pred)
1903 while (pred != NULL)
1905 if (pred->no_default_print)
1906 return (false);
1907 pred = pred->pred_next;
1909 return (true);