1 /* find -- search for files in a directory hierarchy
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003 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)
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,
19 /* GNU find was written by Eric Decker <cire@cisco.com>,
20 with enhancements by David MacKenzie <djm@gnu.ai.mit.edu>,
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>. */
28 #define USE_SAFE_CHDIR 1
39 #include "../gnulib/lib/xalloc.h"
40 #include "../gnulib/lib/human.h"
41 #include "../gnulib/lib/canonicalize.h"
43 #include "../gnulib/lib/savedir.h"
51 # define _(Text) gettext (Text)
54 #define textdomain(Domain)
55 #define bindtextdomain(Package, Directory)
58 # define N_(String) gettext_noop (String)
60 /* See locate.c for explanation as to why not use (String) */
61 # define N_(String) String
64 #define apply_predicate(pathname, stat_buf_ptr, node) \
65 (*(node)->pred_func)((pathname), (stat_buf_ptr), (node))
68 static void init_mounted_dev_list(void);
69 static void process_top_path
PARAMS((char *pathname
));
70 static int process_path
PARAMS((char *pathname
, char *name
, boolean leaf
, char *parent
));
71 static void process_dir
PARAMS((char *pathname
, char *name
, int pathlen
, struct stat
*statp
, char *parent
));
75 static boolean default_prints
PARAMS((struct predicate
*pred
));
77 /* Name this program was run with. */
80 /* All predicates for each path to process. */
81 struct predicate
*predicates
;
83 /* The last predicate allocated. */
84 struct predicate
*last_pred
;
86 /* The root of the evaluation tree. */
87 static struct predicate
*eval_tree
;
89 /* If true, process directory before contents. True unless -depth given. */
92 /* If >=0, don't descend more than this many levels of subdirectories. */
95 /* If >=0, don't process files above this level. */
98 /* Current depth; 0 means current path is a command line arg. */
101 /* Output block size. */
102 int output_block_size
;
104 /* Time at start of execution. */
107 /* Seconds between 00:00 1/1/70 and either one day before now
108 (the default), or the start of today (if -daystart is given). */
109 time_t cur_day_start
;
111 /* If true, cur_day_start has been adjusted to the start of the day. */
114 /* If true, do not assume that files in directories with nlink == 2
115 are non-directories. */
116 boolean no_leaf_check
;
118 /* If true, don't cross filesystem boundaries. */
119 boolean stay_on_filesystem
;
121 /* If true, don't descend past current directory.
122 Can be set by -prune, -maxdepth, and -xdev/-mount. */
123 boolean stop_at_current_level
;
125 /* The full path of the initial working directory, or "." if
126 STARTING_DESC is nonnegative. */
127 char const *starting_dir
= ".";
129 /* A file descriptor open to the initial working directory.
130 Doing it this way allows us to work when the i.w.d. has
131 unreadable parents. */
134 /* The stat buffer of the initial working directory. */
135 struct stat starting_stat_buf
;
137 /* If true, we have called stat on the current path. */
140 /* The file being operated on, relative to the current directory.
141 Used for stat, readlink, remove, and opendir. */
144 /* Length of current path. */
147 /* true if following symlinks. Should be consistent with xstat. */
148 /* boolean dereference; */
149 enum SymlinkOption symlink_handling
;
152 /* Pointer to the function used to stat files. */
155 /* Status value to return to system. */
158 /* If true, we ignore the problem where we find that a directory entry
159 * no longer exists by the time we get around to processing it.
161 boolean ignore_readdir_race
;
164 /* If true, we issue warning messages
169 enum TraversalDirection
177 following_links(void)
179 switch (symlink_handling
)
181 case SYMLINK_ALWAYS_DEREF
:
183 case SYMLINK_DEREF_ARGSONLY
:
184 return (curdepth
== 0);
185 case SYMLINK_NEVER_DEREF
:
193 fallback_stat(const char *name
, struct stat
*p
, int prev_rv
)
195 /* Our original stat() call failed. Perhaps we can't follow a
196 * symbolic link. If that might be the problem, lstat() the link.
197 * Otherwise, admit defeat.
204 fprintf(stderr
, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name
);
206 return lstat(name
, p
);
219 /* optionh_stat() implements the stat operation when the -H option is
222 * If the item to be examined is a command-line argument, we follow
223 * symbolic links. If the stat() call fails on the command-line item,
224 * we fall back on the properties of the symbolic link.
226 * If the item to be examined is not a command-line argument, we
227 * examine the link itself.
230 optionh_stat(const char *name
, struct stat
*p
)
234 /* This file is from the command line; deference the link (if it
237 int rv
= stat(name
, p
);
239 return 0; /* success */
241 return fallback_stat(name
, p
, rv
);
245 /* Not a file on the command line; do not derefernce the link.
247 return lstat(name
, p
);
251 /* optionl_stat() implements the stat operation when the -L option is
252 * in effect. That option makes us examine the thing the symbolic
253 * link points to, not the symbolic link itself.
256 optionl_stat(const char *name
, struct stat
*p
)
258 int rv
= stat(name
, p
);
260 return 0; /* normal case. */
262 return fallback_stat(name
, p
, rv
);
265 /* optionp_stat() implements the stat operation when the -P option is
266 * in effect (this is also the default). That option makes us examine
267 * the symbolic link itself, not the thing it points to.
270 optionp_stat(const char *name
, struct stat
*p
)
272 return lstat(name
, p
);
276 static uintmax_t stat_count
= 0u;
279 debug_stat (const char *file
, struct stat
*bufp
)
282 fprintf (stderr
, "debug_stat (%s)\n", file
);
283 switch (symlink_handling
)
285 case SYMLINK_ALWAYS_DEREF
:
286 return optionl_stat(file
, bufp
);
287 case SYMLINK_DEREF_ARGSONLY
:
288 return optionh_stat(file
, bufp
);
289 case SYMLINK_NEVER_DEREF
:
290 return optionp_stat(file
, bufp
);
293 #endif /* DEBUG_STAT */
296 set_follow_state(enum SymlinkOption opt
)
300 case SYMLINK_ALWAYS_DEREF
: /* -L */
301 xstat
= optionl_stat
;
302 no_leaf_check
= true;
305 case SYMLINK_NEVER_DEREF
: /* -P (default) */
306 xstat
= optionp_stat
;
307 /* Can't turn no_leaf_check off because the user might have specified
312 case SYMLINK_DEREF_ARGSONLY
: /* -H */
313 xstat
= optionh_stat
;
314 no_leaf_check
= true;
317 symlink_handling
= opt
;
319 /* For DBEUG_STAT, the choice is made at runtime within debug_stat()
320 * by checking the contents of the symlink_handling variable.
322 #if defined(DEBUG_STAT)
324 #endif /* !DEBUG_STAT */
329 main (int argc
, char **argv
)
332 PFB parse_function
; /* Pointer to the function which parses. */
333 struct predicate
*cur_pred
;
334 char *predicate_name
; /* Name of predicate being parsed. */
335 int end_of_leading_options
= 0; /* First arg after any -H/-L etc. */
336 program_name
= argv
[0];
338 #ifdef HAVE_SETLOCALE
339 setlocale (LC_ALL
, "");
341 bindtextdomain (PACKAGE
, LOCALEDIR
);
342 textdomain (PACKAGE
);
357 maxdepth
= mindepth
= -1;
358 start_time
= time (NULL
);
359 cur_day_start
= start_time
- DAYSECS
;
361 stay_on_filesystem
= false;
362 ignore_readdir_race
= false;
365 #if defined(DEBUG_STAT)
367 #endif /* !DEBUG_STAT */
370 human_block_size (getenv ("FIND_BLOCK_SIZE"), 0, &output_block_size
);
372 if (getenv("POSIXLY_CORRECT"))
373 output_block_size
= 512;
375 output_block_size
= 1024;
377 if (getenv("FIND_BLOCK_SIZE"))
379 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"));
382 no_leaf_check
= false;
383 set_follow_state(SYMLINK_NEVER_DEREF
); /* The default is equivalent to -P. */
385 init_mounted_dev_list();
390 fprintf (stderr
, "cur_day_start = %s", ctime (&cur_day_start
));
393 /* Check for -P, -H or -L options. */
394 for (i
=1; (end_of_leading_options
= i
) < argc
; ++i
)
396 if (0 == strcmp("-H", argv
[i
]))
398 /* Meaning: dereference symbolic links on command line, but nowhere else. */
399 set_follow_state(SYMLINK_DEREF_ARGSONLY
);
401 else if (0 == strcmp("-L", argv
[i
]))
403 /* Meaning: dereference all symbolic links. */
404 set_follow_state(SYMLINK_ALWAYS_DEREF
);
406 else if (0 == strcmp("-P", argv
[i
]))
408 /* Meaning: never dereference symbolic links (default). */
409 set_follow_state(SYMLINK_NEVER_DEREF
);
411 else if (0 == strcmp("--", argv
[i
]))
413 /* -- signifies the end of options. */
414 end_of_leading_options
= i
+1; /* Next time start with the next option */
419 /* Hmm, must be one of
423 end_of_leading_options
= i
; /* Next time start with this option */
428 /* We are now processing the part of the "find" command line
429 * after the -H/-L options (if any).
432 /* fprintf(stderr, "rest: optind=%ld\n", (long)optind); */
434 /* Find where in ARGV the predicates begin. */
435 for (i
= end_of_leading_options
; i
< argc
&& strchr ("-!(),", argv
[i
][0]) == NULL
; i
++)
437 /* fprintf(stderr, "Looks like %s is not a predicate\n", argv[i]); */
441 /* Enclose the expression in `( ... )' so a default -print will
442 apply to the whole expression. */
443 parse_open (argv
, &argc
);
444 /* Build the input order list. */
447 if (strchr ("-!(),", argv
[i
][0]) == NULL
)
448 usage (_("paths must precede expression"));
449 predicate_name
= argv
[i
];
450 parse_function
= find_parser (predicate_name
);
451 if (parse_function
== NULL
)
452 /* Command line option not recognized */
453 error (1, 0, _("invalid predicate `%s'"), predicate_name
);
455 if (!(*parse_function
) (argv
, &i
))
458 /* Command line option requires an argument */
459 error (1, 0, _("missing argument to `%s'"), predicate_name
);
461 error (1, 0, _("invalid argument `%s' to `%s'"),
462 argv
[i
], predicate_name
);
465 if (predicates
->pred_next
== NULL
)
467 /* No predicates that do something other than set a global variable
468 were given; remove the unneeded initial `(' and add `-print'. */
469 cur_pred
= predicates
;
470 predicates
= last_pred
= predicates
->pred_next
;
471 free ((char *) cur_pred
);
472 parse_print (argv
, &argc
);
474 else if (!default_prints (predicates
->pred_next
))
476 /* One or more predicates that produce output were given;
477 remove the unneeded initial `('. */
478 cur_pred
= predicates
;
479 predicates
= predicates
->pred_next
;
480 free ((char *) cur_pred
);
484 /* `( user-supplied-expression ) -print'. */
485 parse_close (argv
, &argc
);
486 parse_print (argv
, &argc
);
490 fprintf (stderr
, _("Predicate List:\n"));
491 print_list (stderr
, predicates
);
494 /* Done parsing the predicates. Build the evaluation tree. */
495 cur_pred
= predicates
;
496 eval_tree
= get_expr (&cur_pred
, NO_PREC
);
498 /* Check if we have any left-over predicates (this fixes
499 * Debian bug #185202).
501 if (cur_pred
!= NULL
)
503 error (1, 0, _("unexpected extra predicate"));
507 fprintf (stderr
, _("Eval Tree:\n"));
508 print_tree (stderr
, eval_tree
, 0);
511 /* Rearrange the eval tree in optimal-predicate order. */
512 opt_expr (&eval_tree
);
514 /* Determine the point, if any, at which to stat the file. */
515 mark_stat (eval_tree
);
518 fprintf (stderr
, _("Optimized Eval Tree:\n"));
519 print_tree (stderr
, eval_tree
, 0);
520 fprintf (stderr
, _("Optimized command line:\n"));
521 print_optlist(stderr
, eval_tree
);
522 fprintf(stderr
, "\n");
525 starting_desc
= open (".", O_RDONLY
);
526 if (0 <= starting_desc
&& fchdir (starting_desc
) != 0)
528 close (starting_desc
);
531 if (starting_desc
< 0)
533 starting_dir
= xgetcwd ();
535 error (1, errno
, _("cannot get current directory"));
537 if ((*xstat
) (".", &starting_stat_buf
) != 0)
538 error (1, errno
, _("cannot get current directory"));
540 /* If no paths are given, default to ".". */
541 for (i
= end_of_leading_options
; i
< argc
&& strchr ("-!(),", argv
[i
][0]) == NULL
; i
++)
543 process_top_path (argv
[i
]);
546 /* If there were no path arguments, default to ".". */
547 if (i
== end_of_leading_options
)
550 * We use a temporary variable here because some actions modify
551 * the path temporarily. Hence if we use a string constant,
552 * we get a coredump. The best example of this is if we say
553 * "find -printf %H" (note, not "find . -printf %H").
555 char defaultpath
[2] = ".";
556 process_top_path (defaultpath
);
565 specific_dirname(const char *dir
)
569 if (0 == strcmp(".", dir
))
571 /* OK, what's '.'? */
572 if (NULL
!= getcwd(dirname
, sizeof(dirname
)))
574 return strdup(dirname
);
583 char *result
= canonicalize_filename_mode(dir
, CAN_EXISTING
);
591 static dev_t
*mounted_devices
= NULL
;
592 static size_t num_mounted_devices
= 0u;
596 init_mounted_dev_list()
598 assert(NULL
== mounted_devices
);
599 assert(0 == num_mounted_devices
);
600 mounted_devices
= get_mounted_devices(&num_mounted_devices
);
604 refresh_mounted_dev_list(void)
608 free(mounted_devices
);
611 num_mounted_devices
= 0u;
612 init_mounted_dev_list();
616 /* Search for device DEV in the array LIST, which is of size N. */
618 dev_present(dev_t dev
, const dev_t
*list
, size_t n
)
624 if ( (*list
++) == dev
)
631 enum MountPointStateChange
633 MountPointRecentlyMounted
,
634 MountPointRecentlyUnmounted
,
635 MountPointStateUnchanged
640 static enum MountPointStateChange
641 get_mount_state(dev_t newdev
)
643 int new_is_present
, new_was_present
;
645 new_was_present
= dev_present(newdev
, mounted_devices
, num_mounted_devices
);
646 refresh_mounted_dev_list();
647 new_is_present
= dev_present(newdev
, mounted_devices
, num_mounted_devices
);
649 if (new_was_present
== new_is_present
)
650 return MountPointStateUnchanged
;
651 else if (new_is_present
)
652 return MountPointRecentlyMounted
;
654 return MountPointRecentlyUnmounted
;
658 /* Return non-zero if FS is the name of a filesystem that is likely to
662 fs_likely_to_be_automounted(const char *fs
)
664 return ( (0==strcmp(fs
, "nfs")) || (0==strcmp(fs
, "autofs")));
667 enum WdSanityCheckFatality
669 FATAL_IF_SANITY_CHECK_FAILS
,
670 NON_FATAL_IF_SANITY_CHECK_FAILS
674 /* Examine the results of the stat() of a directory from before we
675 * entered or left it, with the results of stat()ing it afterward. If
676 * these are different, the filesystem tree has been modified while we
677 * were traversing it. That might be an attempt to use a race
678 * condition to persuade find to do something it didn't intend
679 * (e.g. an attempt by an ordinary user to exploit the fact that root
680 * sometimes runs find on the whole filesystem). However, this can
681 * also happen if automount is running (certainly on Solaris). With
682 * automount, moving into a directory can cause a filesystem to be
685 * To cope sensibly with this, we will raise an error if we see the
686 * device number change unless we are chdir()ing into a subdirectory,
687 * and the directory we moved into has been mounted or unmounted "recently".
688 * Here "recently" means since we started "find" or we last re-read
689 * the /etc/mnttab file.
691 * If the device number does not change but the inode does, that is a
694 * If the device number and inode are both the same, we are happy.
696 * If a filesystem is (un)mounted as we chdir() into the directory, that
697 * may mean that we're now examining a section of the filesystem that might
698 * have been excluded from consideration (via -prune or -quit for example).
699 * Hence we print a warning message to indicate that the output of find
700 * might be inconsistent due to the change in the filesystem.
703 wd_sanity_check(const char *thing_to_stat
,
704 const char *program_name
,
708 struct stat
*newinfo
,
711 enum TraversalDirection direction
,
712 enum WdSanityCheckFatality isfatal
,
713 boolean
*changed
) /* output parameter */
716 char *specific_what
= NULL
;
721 if ((*xstat
) (".", newinfo
) != 0)
722 error (1, errno
, "%s", thing_to_stat
);
724 if (old_dev
!= newinfo
->st_dev
)
727 specific_what
= specific_dirname(what
);
728 fstype
= filesystem_type(thing_to_stat
, ".", newinfo
);
729 silent
= fs_likely_to_be_automounted(fstype
);
731 /* This condition is rare, so once we are here it is
732 * reasonable to perform an expensive computation to
733 * determine if we should continue or fail.
735 if (TraversingDown
== direction
)
737 /* We stat()ed a directory, chdir()ed into it (we know this
738 * since direction is TraversingDown), stat()ed it again,
739 * and noticed that the device numbers are different. Check
740 * if the filesystem was recently mounted.
742 * If it was, it looks like chdir()ing into the directory
743 * caused a filesystem to be mounted. Maybe automount is
744 * running. Anyway, that's probably OK - but it happens
745 * only when we are moving downward.
747 * We also allow for the possibility that a similar thing
748 * has happened with the unmounting of a filesystem. This
749 * is much rarer, as it relies on an automounter timeout
750 * occurring at exactly the wrong moment.
752 enum MountPointStateChange transition
= get_mount_state(newinfo
->st_dev
);
755 case MountPointRecentlyUnmounted
:
756 isfatal
= NON_FATAL_IF_SANITY_CHECK_FAILS
;
760 _("Warning: filesystem %s has recently been unmounted."),
765 case MountPointRecentlyMounted
:
766 isfatal
= NON_FATAL_IF_SANITY_CHECK_FAILS
;
770 _("Warning: filesystem %s has recently been mounted."),
775 case MountPointStateUnchanged
:
776 /* leave isfatal as it is */
781 if (FATAL_IF_SANITY_CHECK_FAILS
== isfatal
)
783 fstype
= filesystem_type(thing_to_stat
, ".", newinfo
);
785 _("%s%s changed during execution of %s (old device number %ld, new device number %ld, filesystem type is %s) [ref %ld]"),
790 (long) newinfo
->st_dev
,
798 /* Since the device has changed under us, the inode number
799 * will almost certainly also be different. However, we have
800 * already decided that this is not a problem. Hence we return
801 * without checking the inode number.
808 /* Device number was the same, check if the inode has changed. */
809 if (old_ino
!= newinfo
->st_ino
)
812 specific_what
= specific_dirname(what
);
813 fstype
= filesystem_type(thing_to_stat
, ".", newinfo
);
815 error ((isfatal
== FATAL_IF_SANITY_CHECK_FAILS
) ? 1 : 0,
816 0, /* no relevant errno value */
817 _("%s%s changed during execution of %s (old inode number %ld, new inode number %ld, filesystem type is %s) [ref %ld]"),
822 (long) newinfo
->st_ino
,
835 SafeChdirFailSymlink
,
838 SafeChdirFailWouldBeUnableToReturn
,
839 SafeChdirFailChdirFailed
,
840 SafeChdirFailNonexistent
843 /* Safely perform a change in directory.
847 safely_chdir(const char *dest
,
848 enum TraversalDirection direction
,
849 struct stat
*statbuf_dest
)
851 struct stat statbuf_arrived
;
853 int saved_errno
; /* specific_dirname() changes errno. */
855 boolean rv_set
= false;
857 saved_errno
= errno
= 0;
858 dotfd
= open(".", O_RDONLY
);
861 /* Stat the directory we're going to. */
862 if (0 == xstat(dest
, statbuf_dest
))
865 if (!following_links() && S_ISLNK(statbuf_dest
->st_mode
))
867 rv
= SafeChdirFailSymlink
;
869 saved_errno
= 0; /* silence the error message */
874 /* Although the immediately following chdir() would detect
875 * the fact that this is not a directory for us, this would
876 * result in an extra system call that fails. Anybody
877 * examining the system-call trace should ideally not be
878 * concerned that something is actually failing.
880 if (!S_ISDIR(statbuf_dest
->st_mode
))
882 rv
= SafeChdirFailNotDir
;
884 saved_errno
= 0; /* silence the error message */
888 if (0 == chdir(dest
))
890 /* check we ended up where we wanted to go */
891 boolean changed
= false;
892 wd_sanity_check(".", program_name
, ".",
893 statbuf_dest
->st_dev
,
894 statbuf_dest
->st_ino
,
896 0, __LINE__
, direction
,
897 FATAL_IF_SANITY_CHECK_FAILS
,
905 if (ENOENT
== saved_errno
)
907 rv
= SafeChdirFailNonexistent
;
909 if (ignore_readdir_race
)
910 errno
= 0; /* don't issue err msg */
912 name
= specific_dirname(dest
);
914 else if (ENOTDIR
== saved_errno
)
916 /* This can happen if the we stat a directory,
917 * and then filesystem activity changes it into
920 saved_errno
= 0; /* don't issue err msg */
921 rv
= SafeChdirFailNotDir
;
926 rv
= SafeChdirFailChdirFailed
;
928 name
= specific_dirname(dest
);
936 rv
= SafeChdirFailStat
;
938 name
= specific_dirname(dest
);
939 if ( (ENOENT
== saved_errno
) || (0 == curdepth
))
940 saved_errno
= 0; /* don't issue err msg */
946 /* We do not have read permissions on "." */
947 rv
= SafeChdirFailWouldBeUnableToReturn
;
954 /* We use the same exit path for successs or failure.
955 * which has occurred is recorded in RV.
962 /* do not call error() as this would result in a duplicate error message
963 * when the caller does the same thing.
967 name
= specific_dirname(".");
968 error(0, saved_errno
, "%s", name
);
985 /* Safely go back to the starting directory. */
989 struct stat stat_buf
;
992 if (starting_desc
< 0)
994 if (chdir (starting_dir
) != 0)
995 error (1, errno
, "%s", starting_dir
);
997 wd_sanity_check(starting_dir
,
1000 starting_stat_buf
.st_dev
,
1001 starting_stat_buf
.st_ino
,
1002 &stat_buf
, 0, __LINE__
,
1004 FATAL_IF_SANITY_CHECK_FAILS
,
1009 if (fchdir (starting_desc
) != 0)
1010 error (1, errno
, "%s", starting_dir
);
1014 /* Descend PATHNAME, which is a command-line argument. */
1016 process_top_path (char *pathname
)
1018 process_path (pathname
, pathname
, false, ".");
1023 old_process_top_path (char *pathname
)
1025 struct stat stat_buf
, cur_stat_buf
;
1029 path_length
= strlen (pathname
);
1031 /* We stat each pathname given on the command-line twice --
1032 once here and once in process_path. It's not too bad, though,
1033 since the kernel can read the stat information out of its inode
1034 cache the second time. */
1036 if ((*xstat
) (pathname
, &stat_buf
) == 0 && S_ISDIR (stat_buf
.st_mode
))
1038 enum SafeChdirStatus rv
= safely_chdir(pathname
, TraversingDown
, &stat_buf
);
1043 process_path (pathname
, ".", false, ".");
1047 case SafeChdirFailNonexistent
:
1048 case SafeChdirFailStat
:
1049 case SafeChdirFailWouldBeUnableToReturn
:
1050 case SafeChdirFailSymlink
:
1051 case SafeChdirFailNotDir
:
1052 case SafeChdirFailChdirFailed
:
1053 if ((SafeChdirFailNonexistent
==rv
) && !ignore_readdir_race
)
1055 error (0, errno
, "%s", pathname
);
1060 process_path (pathname
, pathname
, false, ".");
1068 /* Not a directory */
1069 process_path (pathname
, pathname
, false, ".");
1072 if ((*xstat
) (pathname
, &stat_buf
) == 0 && S_ISDIR (stat_buf
.st_mode
))
1074 if (chdir (pathname
) < 0)
1076 if (!ignore_readdir_race
|| (errno
!= ENOENT
) )
1078 error (0, errno
, "%s", pathname
);
1084 /* Check that we are where we should be. */
1085 wd_sanity_check(pathname
, program_name
,
1089 &cur_stat_buf
, 0, __LINE__
,
1091 FATAL_IF_SANITY_CHECK_FAILS
,
1094 process_path (pathname
, ".", false, ".");
1099 process_path (pathname
, pathname
, false, ".");
1104 /* Info on each directory in the current tree branch, to avoid
1105 getting stuck in symbolic link loops. */
1111 static struct dir_id
*dir_ids
= NULL
;
1112 /* Entries allocated in `dir_ids'. */
1113 static int dir_alloc
= 0;
1114 /* Index in `dir_ids' of directory currently being searched.
1115 This is always the last valid entry. */
1116 static int dir_curr
= -1;
1117 /* (Arbitrary) number of entries to grow `dir_ids' by. */
1118 #define DIR_ALLOC_STEP 32
1122 /* We've detected a filesystem loop. This is caused by one of
1125 * 1. Option -L is in effect and we've hit a symbolic link that
1126 * points to an ancestor. This is harmless. We won't traverse the
1129 * 2. We have hit a real cycle in the directory hierarchy. In this
1130 * case, we issue a diagnostic message (POSIX requires this) and we
1131 * skip that directory entry.
1134 issue_loop_warning(const char *name
, const char *pathname
, int level
)
1136 struct stat stbuf_link
;
1137 if (lstat(name
, &stbuf_link
) != 0)
1138 stbuf_link
.st_mode
= S_IFREG
;
1140 if (S_ISLNK(stbuf_link
.st_mode
))
1143 _("Symbolic link `%s' is part of a loop in the directory hierarchy; we have already visited the directory to which it points."),
1148 int distance
= 1 + (dir_curr
-level
);
1149 /* We have found an infinite loop. POSIX requires us to
1150 * issue a diagnostic. Usually we won't get to here
1151 * because when the leaf optimisation is on, it will cause
1152 * the subdirectory to be skipped. If /a/b/c/d is a hard
1153 * link to /a/b, then the link count of /a/b/c is 2,
1154 * because the ".." entry of /b/b/c/d points to /a, not
1158 _("Filesystem loop detected; `%s' has the same device number and inode as a directory which is %d %s."),
1162 _("level higher in the filesystem hierarchy") :
1163 _("levels higher in the filesystem hierarchy")));
1167 /* Recursively descend path PATHNAME, applying the predicates.
1168 LEAF is true if PATHNAME is known to be in a directory that has no
1169 more unexamined subdirectories, and therefore it is not a directory.
1170 Knowing this allows us to avoid calling stat as long as possible for
1173 NAME is PATHNAME relative to the current directory. We access NAME
1176 PARENT is the path of the parent of NAME, relative to find's
1179 Return nonzero iff PATHNAME is a directory. */
1182 process_path (char *pathname
, char *name
, boolean leaf
, char *parent
)
1184 struct stat stat_buf
;
1185 static dev_t root_dev
; /* Device ID of current argument pathname. */
1188 /* Assume it is a non-directory initially. */
1189 stat_buf
.st_mode
= 0;
1191 rel_pathname
= name
;
1197 if ((*xstat
) (name
, &stat_buf
) != 0)
1199 if (!ignore_readdir_race
|| (errno
!= ENOENT
) )
1201 error (0, errno
, "%s", pathname
);
1209 if (!S_ISDIR (stat_buf
.st_mode
))
1211 if (curdepth
>= mindepth
)
1212 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1216 /* From here on, we're working on a directory. */
1218 stop_at_current_level
= maxdepth
>= 0 && curdepth
>= maxdepth
;
1220 /* If we've already seen this directory on this branch,
1221 don't descend it again. */
1222 for (i
= 0; i
<= dir_curr
; i
++)
1223 if (stat_buf
.st_ino
== dir_ids
[i
].ino
&&
1224 stat_buf
.st_dev
== dir_ids
[i
].dev
)
1226 stop_at_current_level
= true;
1227 issue_loop_warning(name
, pathname
, i
);
1230 if (dir_alloc
<= ++dir_curr
)
1232 dir_alloc
+= DIR_ALLOC_STEP
;
1233 dir_ids
= (struct dir_id
*)
1234 xrealloc ((char *) dir_ids
, dir_alloc
* sizeof (struct dir_id
));
1236 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1237 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1239 if (stay_on_filesystem
)
1242 root_dev
= stat_buf
.st_dev
;
1243 else if (stat_buf
.st_dev
!= root_dev
)
1244 stop_at_current_level
= true;
1247 if (do_dir_first
&& curdepth
>= mindepth
)
1248 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1251 fprintf(stderr
, "pathname = %s, stop_at_current_level = %d\n",
1252 pathname
, stop_at_current_level
);
1255 if (stop_at_current_level
== false)
1256 /* Scan directory on disk. */
1257 process_dir (pathname
, name
, strlen (pathname
), &stat_buf
, parent
);
1259 if (do_dir_first
== false && curdepth
>= mindepth
)
1261 rel_pathname
= name
;
1262 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1270 /* Scan directory PATHNAME and recurse through process_path for each entry.
1272 PATHLEN is the length of PATHNAME.
1274 NAME is PATHNAME relative to the current directory.
1276 STATP is the results of *xstat on it.
1278 PARENT is the path of the parent of NAME, relative to find's
1279 starting directory. */
1282 process_dir (char *pathname
, char *name
, int pathlen
, struct stat
*statp
, char *parent
)
1284 char *name_space
; /* Names of files in PATHNAME. */
1285 int subdirs_left
; /* Number of unexamined subdirs in PATHNAME. */
1286 struct stat stat_buf
;
1288 subdirs_left
= statp
->st_nlink
- 2; /* Account for name and ".". */
1291 name_space
= savedir (name
);
1292 if (name_space
== NULL
)
1295 error (0, errno
, "%s", pathname
);
1300 register char *namep
; /* Current point in `name_space'. */
1301 char *cur_path
; /* Full path of each file to process. */
1302 char *cur_name
; /* Base name of each file to process. */
1303 unsigned cur_path_size
; /* Bytes allocated for `cur_path'. */
1304 register unsigned file_len
; /* Length of each path to process. */
1305 register unsigned pathname_len
; /* PATHLEN plus trailing '/'. */
1307 if (pathname
[pathlen
- 1] == '/')
1308 pathname_len
= pathlen
+ 1; /* For '\0'; already have '/'. */
1310 pathname_len
= pathlen
+ 2; /* For '/' and '\0'. */
1315 if (strcmp (name
, "."))
1317 enum SafeChdirStatus status
= safely_chdir (name
, TraversingDown
, &stat_buf
);
1321 /* If there had been a change but wd_sanity_check()
1322 * accepted it, we need to accept that on the
1323 * way back up as well, so modify our record
1324 * of what we think we should see later.
1325 * If there was no change, the assignments are a no-op.
1327 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1328 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1331 case SafeChdirFailNonexistent
:
1332 case SafeChdirFailStat
:
1333 case SafeChdirFailWouldBeUnableToReturn
:
1334 case SafeChdirFailSymlink
:
1335 case SafeChdirFailNotDir
:
1336 case SafeChdirFailChdirFailed
:
1337 error (0, errno
, "%s", pathname
);
1343 if (strcmp (name
, ".") && chdir (name
) < 0)
1345 error (0, errno
, "%s", pathname
);
1350 /* Check that we are where we should be. */
1353 boolean changed
= false;
1354 wd_sanity_check(pathname
,
1357 dir_ids
[dir_curr
].dev
,
1358 dir_ids
[dir_curr
].ino
,
1359 &stat_buf
, 0, __LINE__
,
1361 FATAL_IF_SANITY_CHECK_FAILS
,
1365 /* If there had been a change but wd_sanity_check()
1366 * accepted it, we need to accept that on the
1367 * way back up as well, so modify our record
1368 * of what we think we should see later.
1370 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1371 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1376 for (namep
= name_space
; *namep
; namep
+= file_len
- pathname_len
+ 1)
1378 /* Append this directory entry's name to the path being searched. */
1379 file_len
= pathname_len
+ strlen (namep
);
1380 if (file_len
> cur_path_size
)
1382 while (file_len
> cur_path_size
)
1383 cur_path_size
+= 1024;
1386 cur_path
= xmalloc (cur_path_size
);
1387 strcpy (cur_path
, pathname
);
1388 cur_path
[pathname_len
- 2] = '/';
1390 cur_name
= cur_path
+ pathname_len
- 1;
1391 strcpy (cur_name
, namep
);
1395 /* Normal case optimization.
1396 On normal Unix filesystems, a directory that has no
1397 subdirectories has two links: its name, and ".". Any
1398 additional links are to the ".." entries of its
1399 subdirectories. Once we have processed as many
1400 subdirectories as there are additional links, we know
1401 that the rest of the entries are non-directories --
1402 in other words, leaf files. */
1403 subdirs_left
-= process_path (cur_path
, cur_name
,
1404 subdirs_left
== 0, pathname
);
1406 /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems
1407 mounted, which don't have Unix-like directory link counts. */
1408 process_path (cur_path
, cur_name
, false, pathname
);
1412 if (strcmp (name
, "."))
1414 enum SafeChdirStatus status
;
1416 boolean changed
= false;
1418 /* We could go back and do the next command-line arg
1419 instead, maybe using longjmp. */
1421 boolean deref
= following_links() ? true : false;
1423 if ( (curdepth
>0) && !deref
)
1431 status
= safely_chdir (dir
, TraversingUp
, &stat_buf
);
1437 case SafeChdirFailNonexistent
:
1438 case SafeChdirFailStat
:
1439 case SafeChdirFailWouldBeUnableToReturn
:
1440 case SafeChdirFailSymlink
:
1441 case SafeChdirFailNotDir
:
1442 case SafeChdirFailChdirFailed
:
1443 error (1, errno
, "%s", pathname
);
1449 did
.dev
= dir_ids
[dir_curr
-1].dev
;
1450 did
.ino
= dir_ids
[dir_curr
-1].ino
;
1454 did
.dev
= starting_stat_buf
.st_dev
;
1455 did
.ino
= starting_stat_buf
.st_ino
;
1458 wd_sanity_check(pathname
,
1467 FATAL_IF_SANITY_CHECK_FAILS
,
1471 if (strcmp (name
, "."))
1473 /* We could go back and do the next command-line arg
1474 instead, maybe using longjmp. */
1476 boolean deref
= following_links() ? true : false;
1486 if (chdir (dir
) != 0)
1487 error (1, errno
, "%s", parent
);
1489 /* Check that we are where we should be. */
1492 boolean changed
= false;
1494 int problem_is_with_parent
;
1496 memset(&tmp
, 0, sizeof(tmp
));
1499 tmp
.st_dev
= dir_ids
[dir_curr
-1].dev
;
1500 tmp
.st_ino
= dir_ids
[dir_curr
-1].ino
;
1504 tmp
.st_dev
= starting_stat_buf
.st_dev
;
1505 tmp
.st_ino
= starting_stat_buf
.st_ino
;
1508 problem_is_with_parent
= deref
? 1 : 0;
1509 wd_sanity_check(pathname
,
1515 problem_is_with_parent
, __LINE__
,
1517 FATAL_IF_SANITY_CHECK_FAILS
,
1529 /* Return true if there are no predicates with no_default_print in
1530 predicate list PRED, false if there are any.
1531 Returns true if default print should be performed */
1534 default_prints (struct predicate
*pred
)
1536 while (pred
!= NULL
)
1538 if (pred
->no_default_print
)
1540 pred
= pred
->pred_next
;