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)
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.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>. */
29 #define USE_SAFE_CHDIR 1
41 #include "../gnulib/lib/xalloc.h"
42 #include "../gnulib/lib/human.h"
43 #include "../gnulib/lib/canonicalize.h"
46 #include "savedirinfo.h"
56 # define _(Text) gettext (Text)
59 #define textdomain(Domain)
60 #define bindtextdomain(Package, Directory)
63 # define N_(String) gettext_noop (String)
65 /* See locate.c for explanation as to why not use (String) */
66 # define N_(String) String
69 #define apply_predicate(pathname, stat_buf_ptr, node) \
70 (*(node)->pred_func)((pathname), (stat_buf_ptr), (node))
73 static void init_mounted_dev_list(void);
74 static void process_top_path
PARAMS((char *pathname
, mode_t mode
));
75 static int process_path
PARAMS((char *pathname
, char *name
, boolean leaf
, char *parent
, mode_t type
));
76 static void process_dir
PARAMS((char *pathname
, char *name
, int pathlen
, struct stat
*statp
, char *parent
));
78 static void complete_pending_execdirs(struct predicate
*p
);
79 static void complete_pending_execs (struct predicate
*p
);
83 static boolean default_prints
PARAMS((struct predicate
*pred
));
85 /* Name this program was run with. */
88 /* All predicates for each path to process. */
89 struct predicate
*predicates
;
91 /* The last predicate allocated. */
92 struct predicate
*last_pred
;
94 /* The root of the evaluation tree. */
95 static struct predicate
*eval_tree
= NULL
;
98 struct options options
;
101 /* The full path of the initial working directory, or "." if
102 STARTING_DESC is nonnegative. */
103 char const *starting_dir
= ".";
105 /* A file descriptor open to the initial working directory.
106 Doing it this way allows us to work when the i.w.d. has
107 unreadable parents. */
110 /* The stat buffer of the initial working directory. */
111 struct stat starting_stat_buf
;
113 enum ChdirSymlinkHandling
115 SymlinkHandleDefault
, /* Normally the right choice */
116 SymlinkFollowOk
/* see comment in process_top_path() */
120 enum TraversalDirection
128 following_links(void)
130 switch (options
.symlink_handling
)
132 case SYMLINK_ALWAYS_DEREF
:
134 case SYMLINK_DEREF_ARGSONLY
:
135 return (state
.curdepth
== 0);
136 case SYMLINK_NEVER_DEREF
:
144 fallback_stat(const char *name
, struct stat
*p
, int prev_rv
)
146 /* Our original stat() call failed. Perhaps we can't follow a
147 * symbolic link. If that might be the problem, lstat() the link.
148 * Otherwise, admit defeat.
155 fprintf(stderr
, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name
);
157 return lstat(name
, p
);
164 case EOVERFLOW
: /* EOVERFLOW is not #defined on UNICOS. */
172 /* optionh_stat() implements the stat operation when the -H option is
175 * If the item to be examined is a command-line argument, we follow
176 * symbolic links. If the stat() call fails on the command-line item,
177 * we fall back on the properties of the symbolic link.
179 * If the item to be examined is not a command-line argument, we
180 * examine the link itself.
183 optionh_stat(const char *name
, struct stat
*p
)
185 if (0 == state
.curdepth
)
187 /* This file is from the command line; deference the link (if it
190 int rv
= stat(name
, p
);
192 return 0; /* success */
194 return fallback_stat(name
, p
, rv
);
198 /* Not a file on the command line; do not derefernce the link.
200 return lstat(name
, p
);
204 /* optionl_stat() implements the stat operation when the -L option is
205 * in effect. That option makes us examine the thing the symbolic
206 * link points to, not the symbolic link itself.
209 optionl_stat(const char *name
, struct stat
*p
)
211 int rv
= stat(name
, p
);
213 return 0; /* normal case. */
215 return fallback_stat(name
, p
, rv
);
218 /* optionp_stat() implements the stat operation when the -P option is
219 * in effect (this is also the default). That option makes us examine
220 * the symbolic link itself, not the thing it points to.
223 optionp_stat(const char *name
, struct stat
*p
)
225 return lstat(name
, p
);
229 static uintmax_t stat_count
= 0u;
232 debug_stat (const char *file
, struct stat
*bufp
)
235 fprintf (stderr
, "debug_stat (%s)\n", file
);
236 switch (options
.symlink_handling
)
238 case SYMLINK_ALWAYS_DEREF
:
239 return optionl_stat(file
, bufp
);
240 case SYMLINK_DEREF_ARGSONLY
:
241 return optionh_stat(file
, bufp
);
242 case SYMLINK_NEVER_DEREF
:
243 return optionp_stat(file
, bufp
);
246 #endif /* DEBUG_STAT */
249 set_follow_state(enum SymlinkOption opt
)
253 case SYMLINK_ALWAYS_DEREF
: /* -L */
254 options
.xstat
= optionl_stat
;
255 options
.no_leaf_check
= true;
258 case SYMLINK_NEVER_DEREF
: /* -P (default) */
259 options
.xstat
= optionp_stat
;
260 /* Can't turn no_leaf_check off because the user might have specified
265 case SYMLINK_DEREF_ARGSONLY
: /* -H */
266 options
.xstat
= optionh_stat
;
267 options
.no_leaf_check
= true;
270 options
.symlink_handling
= opt
;
272 /* For DBEUG_STAT, the choice is made at runtime within debug_stat()
273 * by checking the contents of the symlink_handling variable.
275 #if defined(DEBUG_STAT)
276 options
.xstat
= debug_stat
;
277 #endif /* !DEBUG_STAT */
281 /* Complete any outstanding commands.
288 complete_pending_execs(eval_tree
);
289 complete_pending_execdirs(eval_tree
);
293 /* Get the stat information for a file, if it is
297 get_statinfo (const char *pathname
, const char *name
, struct stat
*p
)
299 if (!state
.have_stat
&& (*options
.xstat
) (name
, p
) != 0)
301 if (!options
.ignore_readdir_race
|| (errno
!= ENOENT
) )
303 error (0, errno
, "%s", pathname
);
304 state
.exit_status
= 1;
308 state
.have_stat
= true;
309 state
.have_type
= true;
310 state
.type
= p
->st_mode
;
314 /* Get the stat/type information for a file, if it is
318 get_info (const char *pathname
,
321 struct predicate
*pred_ptr
)
323 /* If we need the full stat info, or we need the type info but don't
324 * already have it, stat the file now.
327 if (pred_ptr
->need_stat
)
329 return get_statinfo(pathname
, state
.rel_pathname
, p
);
331 if ((pred_ptr
->need_type
&& (0 == state
.have_type
)))
333 return get_statinfo(pathname
, state
.rel_pathname
, p
);
339 main (int argc
, char **argv
)
342 PFB parse_function
; /* Pointer to the function which parses. */
343 struct predicate
*cur_pred
;
344 char *predicate_name
; /* Name of predicate being parsed. */
345 int end_of_leading_options
= 0; /* First arg after any -H/-L etc. */
346 program_name
= argv
[0];
348 #ifdef HAVE_SETLOCALE
349 setlocale (LC_ALL
, "");
351 bindtextdomain (PACKAGE
, LOCALEDIR
);
352 textdomain (PACKAGE
);
353 atexit (close_stdout
);
358 options
.warnings
= true;
362 options
.warnings
= false;
368 options
.do_dir_first
= true;
369 options
.maxdepth
= options
.mindepth
= -1;
370 options
.start_time
= time (NULL
);
371 options
.cur_day_start
= options
.start_time
- DAYSECS
;
372 options
.full_days
= false;
373 options
.stay_on_filesystem
= false;
374 options
.ignore_readdir_race
= false;
376 state
.exit_status
= 0;
378 #if defined(DEBUG_STAT)
379 options
.xstat
= debug_stat
;
380 #endif /* !DEBUG_STAT */
382 if (getenv("POSIXLY_CORRECT"))
383 options
.output_block_size
= 512;
385 options
.output_block_size
= 1024;
387 if (getenv("FIND_BLOCK_SIZE"))
389 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"));
392 options
.no_leaf_check
= false;
393 set_follow_state(SYMLINK_NEVER_DEREF
); /* The default is equivalent to -P. */
395 init_mounted_dev_list();
398 fprintf (stderr
, "cur_day_start = %s", ctime (&options
.cur_day_start
));
401 /* Check for -P, -H or -L options. */
402 for (i
=1; (end_of_leading_options
= i
) < argc
; ++i
)
404 if (0 == strcmp("-H", argv
[i
]))
406 /* Meaning: dereference symbolic links on command line, but nowhere else. */
407 set_follow_state(SYMLINK_DEREF_ARGSONLY
);
409 else if (0 == strcmp("-L", argv
[i
]))
411 /* Meaning: dereference all symbolic links. */
412 set_follow_state(SYMLINK_ALWAYS_DEREF
);
414 else if (0 == strcmp("-P", argv
[i
]))
416 /* Meaning: never dereference symbolic links (default). */
417 set_follow_state(SYMLINK_NEVER_DEREF
);
419 else if (0 == strcmp("--", argv
[i
]))
421 /* -- signifies the end of options. */
422 end_of_leading_options
= i
+1; /* Next time start with the next option */
427 /* Hmm, must be one of
431 end_of_leading_options
= i
; /* Next time start with this option */
436 /* We are now processing the part of the "find" command line
437 * after the -H/-L options (if any).
440 /* fprintf(stderr, "rest: optind=%ld\n", (long)optind); */
442 /* Find where in ARGV the predicates begin. */
443 for (i
= end_of_leading_options
; i
< argc
&& strchr ("-!(),", argv
[i
][0]) == NULL
; i
++)
445 /* fprintf(stderr, "Looks like %s is not a predicate\n", argv[i]); */
449 /* Enclose the expression in `( ... )' so a default -print will
450 apply to the whole expression. */
451 parse_open (argv
, &argc
);
452 /* Build the input order list. */
455 if (strchr ("-!(),", argv
[i
][0]) == NULL
)
456 usage (_("paths must precede expression"));
457 predicate_name
= argv
[i
];
458 parse_function
= find_parser (predicate_name
);
459 if (parse_function
== NULL
)
460 /* Command line option not recognized */
461 error (1, 0, _("invalid predicate `%s'"), predicate_name
);
463 if (!(*parse_function
) (argv
, &i
))
466 /* Command line option requires an argument */
467 error (1, 0, _("missing argument to `%s'"), predicate_name
);
469 error (1, 0, _("invalid argument `%s' to `%s'"),
470 argv
[i
], predicate_name
);
473 if (predicates
->pred_next
== NULL
)
475 /* No predicates that do something other than set a global variable
476 were given; remove the unneeded initial `(' and add `-print'. */
477 cur_pred
= predicates
;
478 predicates
= last_pred
= predicates
->pred_next
;
479 free ((char *) cur_pred
);
480 parse_print (argv
, &argc
);
482 else if (!default_prints (predicates
->pred_next
))
484 /* One or more predicates that produce output were given;
485 remove the unneeded initial `('. */
486 cur_pred
= predicates
;
487 predicates
= predicates
->pred_next
;
488 free ((char *) cur_pred
);
492 /* `( user-supplied-expression ) -print'. */
493 parse_close (argv
, &argc
);
494 parse_print (argv
, &argc
);
498 fprintf (stderr
, _("Predicate List:\n"));
499 print_list (stderr
, predicates
);
502 /* Done parsing the predicates. Build the evaluation tree. */
503 cur_pred
= predicates
;
504 eval_tree
= get_expr (&cur_pred
, NO_PREC
);
506 /* Check if we have any left-over predicates (this fixes
507 * Debian bug #185202).
509 if (cur_pred
!= NULL
)
511 error (1, 0, _("unexpected extra predicate"));
515 fprintf (stderr
, _("Eval Tree:\n"));
516 print_tree (stderr
, eval_tree
, 0);
519 /* Rearrange the eval tree in optimal-predicate order. */
520 opt_expr (&eval_tree
);
522 /* Determine the point, if any, at which to stat the file. */
523 mark_stat (eval_tree
);
524 /* Determine the point, if any, at which to determine file type. */
525 mark_type (eval_tree
);
528 fprintf (stderr
, _("Optimized Eval Tree:\n"));
529 print_tree (stderr
, eval_tree
, 0);
530 fprintf (stderr
, _("Optimized command line:\n"));
531 print_optlist(stderr
, eval_tree
);
532 fprintf(stderr
, "\n");
535 starting_desc
= open (".", O_RDONLY
);
536 if (0 <= starting_desc
&& fchdir (starting_desc
) != 0)
538 close (starting_desc
);
541 if (starting_desc
< 0)
543 starting_dir
= xgetcwd ();
545 error (1, errno
, _("cannot get current directory"));
547 if ((*options
.xstat
) (".", &starting_stat_buf
) != 0)
548 error (1, errno
, _("cannot get current directory"));
550 /* If no paths are given, default to ".". */
551 for (i
= end_of_leading_options
; i
< argc
&& strchr ("-!(),", argv
[i
][0]) == NULL
; i
++)
553 process_top_path (argv
[i
], 0);
556 /* If there were no path arguments, default to ".". */
557 if (i
== end_of_leading_options
)
560 * We use a temporary variable here because some actions modify
561 * the path temporarily. Hence if we use a string constant,
562 * we get a coredump. The best example of this is if we say
563 * "find -printf %H" (note, not "find . -printf %H").
565 char defaultpath
[2] = ".";
566 process_top_path (defaultpath
, 0);
569 /* If "-exec ... {} +" has been used, there may be some
570 * partially-full command lines which have been built,
571 * but which are not yet complete. Execute those now.
574 return state
.exit_status
;
579 specific_dirname(const char *dir
)
583 if (0 == strcmp(".", dir
))
585 /* OK, what's '.'? */
586 if (NULL
!= getcwd(dirname
, sizeof(dirname
)))
588 return strdup(dirname
);
597 char *result
= canonicalize_filename_mode(dir
, CAN_EXISTING
);
605 static dev_t
*mounted_devices
= NULL
;
606 static size_t num_mounted_devices
= 0u;
610 init_mounted_dev_list()
612 assert(NULL
== mounted_devices
);
613 assert(0 == num_mounted_devices
);
614 mounted_devices
= get_mounted_devices(&num_mounted_devices
);
618 refresh_mounted_dev_list(void)
622 free(mounted_devices
);
625 num_mounted_devices
= 0u;
626 init_mounted_dev_list();
630 /* Search for device DEV in the array LIST, which is of size N. */
632 dev_present(dev_t dev
, const dev_t
*list
, size_t n
)
638 if ( (*list
++) == dev
)
645 enum MountPointStateChange
647 MountPointRecentlyMounted
,
648 MountPointRecentlyUnmounted
,
649 MountPointStateUnchanged
654 static enum MountPointStateChange
655 get_mount_state(dev_t newdev
)
657 int new_is_present
, new_was_present
;
659 new_was_present
= dev_present(newdev
, mounted_devices
, num_mounted_devices
);
660 refresh_mounted_dev_list();
661 new_is_present
= dev_present(newdev
, mounted_devices
, num_mounted_devices
);
663 if (new_was_present
== new_is_present
)
664 return MountPointStateUnchanged
;
665 else if (new_is_present
)
666 return MountPointRecentlyMounted
;
668 return MountPointRecentlyUnmounted
;
672 /* Return non-zero if FS is the name of a filesystem that is likely to
676 fs_likely_to_be_automounted(const char *fs
)
678 return ( (0==strcmp(fs
, "nfs")) || (0==strcmp(fs
, "autofs")) || (0==strcmp(fs
, "subfs")));
681 enum WdSanityCheckFatality
683 FATAL_IF_SANITY_CHECK_FAILS
,
684 NON_FATAL_IF_SANITY_CHECK_FAILS
688 /* Examine the results of the stat() of a directory from before we
689 * entered or left it, with the results of stat()ing it afterward. If
690 * these are different, the filesystem tree has been modified while we
691 * were traversing it. That might be an attempt to use a race
692 * condition to persuade find to do something it didn't intend
693 * (e.g. an attempt by an ordinary user to exploit the fact that root
694 * sometimes runs find on the whole filesystem). However, this can
695 * also happen if automount is running (certainly on Solaris). With
696 * automount, moving into a directory can cause a filesystem to be
699 * To cope sensibly with this, we will raise an error if we see the
700 * device number change unless we are chdir()ing into a subdirectory,
701 * and the directory we moved into has been mounted or unmounted "recently".
702 * Here "recently" means since we started "find" or we last re-read
703 * the /etc/mnttab file.
705 * If the device number does not change but the inode does, that is a
708 * If the device number and inode are both the same, we are happy.
710 * If a filesystem is (un)mounted as we chdir() into the directory, that
711 * may mean that we're now examining a section of the filesystem that might
712 * have been excluded from consideration (via -prune or -quit for example).
713 * Hence we print a warning message to indicate that the output of find
714 * might be inconsistent due to the change in the filesystem.
717 wd_sanity_check(const char *thing_to_stat
,
718 const char *program_name
,
722 struct stat
*newinfo
,
725 enum TraversalDirection direction
,
726 enum WdSanityCheckFatality isfatal
,
727 boolean
*changed
) /* output parameter */
730 char *specific_what
= NULL
;
735 if ((*options
.xstat
) (".", newinfo
) != 0)
736 error (1, errno
, "%s", thing_to_stat
);
738 if (old_dev
!= newinfo
->st_dev
)
741 specific_what
= specific_dirname(what
);
742 fstype
= filesystem_type(newinfo
);
743 silent
= fs_likely_to_be_automounted(fstype
);
745 /* This condition is rare, so once we are here it is
746 * reasonable to perform an expensive computation to
747 * determine if we should continue or fail.
749 if (TraversingDown
== direction
)
751 /* We stat()ed a directory, chdir()ed into it (we know this
752 * since direction is TraversingDown), stat()ed it again,
753 * and noticed that the device numbers are different. Check
754 * if the filesystem was recently mounted.
756 * If it was, it looks like chdir()ing into the directory
757 * caused a filesystem to be mounted. Maybe automount is
758 * running. Anyway, that's probably OK - but it happens
759 * only when we are moving downward.
761 * We also allow for the possibility that a similar thing
762 * has happened with the unmounting of a filesystem. This
763 * is much rarer, as it relies on an automounter timeout
764 * occurring at exactly the wrong moment.
766 enum MountPointStateChange transition
= get_mount_state(newinfo
->st_dev
);
769 case MountPointRecentlyUnmounted
:
770 isfatal
= NON_FATAL_IF_SANITY_CHECK_FAILS
;
774 _("Warning: filesystem %s has recently been unmounted."),
779 case MountPointRecentlyMounted
:
780 isfatal
= NON_FATAL_IF_SANITY_CHECK_FAILS
;
784 _("Warning: filesystem %s has recently been mounted."),
789 case MountPointStateUnchanged
:
790 /* leave isfatal as it is */
795 if (FATAL_IF_SANITY_CHECK_FAILS
== isfatal
)
797 fstype
= filesystem_type(newinfo
);
799 _("%s%s changed during execution of %s (old device number %ld, new device number %ld, filesystem type is %s) [ref %ld]"),
804 (long) newinfo
->st_dev
,
812 /* Since the device has changed under us, the inode number
813 * will almost certainly also be different. However, we have
814 * already decided that this is not a problem. Hence we return
815 * without checking the inode number.
822 /* Device number was the same, check if the inode has changed. */
823 if (old_ino
!= newinfo
->st_ino
)
826 specific_what
= specific_dirname(what
);
827 fstype
= filesystem_type(newinfo
);
829 error ((isfatal
== FATAL_IF_SANITY_CHECK_FAILS
) ? 1 : 0,
830 0, /* no relevant errno value */
831 _("%s%s changed during execution of %s (old inode number %ld, new inode number %ld, filesystem type is %s) [ref %ld]"),
836 (long) newinfo
->st_ino
,
849 SafeChdirFailSymlink
,
852 SafeChdirFailWouldBeUnableToReturn
,
853 SafeChdirFailChdirFailed
,
854 SafeChdirFailNonexistent
857 /* Safely perform a change in directory.
860 static enum SafeChdirStatus
861 safely_chdir(const char *dest
,
862 enum TraversalDirection direction
,
863 struct stat
*statbuf_dest
,
864 enum ChdirSymlinkHandling symlink_handling
)
866 struct stat statbuf_arrived
;
868 int saved_errno
; /* specific_dirname() changes errno. */
870 boolean rv_set
= false;
872 /* We're about to leave a directory. If there are any -execdir
873 * argument lists which have been built but have not yet been
874 * processed, do them now because they must be done in the same
877 complete_pending_execdirs(eval_tree
);
880 saved_errno
= errno
= 0;
881 dotfd
= open(".", O_RDONLY
);
884 /* Stat the directory we're going to. */
885 if (0 == options
.xstat(dest
, statbuf_dest
))
888 /* symlink_handling might be set to SymlinkFollowOk, which
889 * would allow us to chdir() into a symbolic link. This is
890 * only useful for the case where the directory we're
891 * chdir()ing into is the basename of a command line
892 * argument, for example where "foo/bar/baz" is specified on
893 * the command line. When -P is in effect (the default),
894 * baz will not be followed if it is a symlink, but if bar
895 * is a symlink, it _should_ be followed. Hence we need the
896 * ability to override the policy set by following_links().
898 if (!following_links() && S_ISLNK(statbuf_dest
->st_mode
))
900 /* We're not supposed to be following links, but this is
901 * a link. Check symlink_handling to see if we should
902 * make a special exception.
904 if (symlink_handling
== SymlinkFollowOk
)
906 /* We need to re-stat() the file so that the
907 * sanity check can pass.
909 if (0 != stat(dest
, statbuf_dest
))
911 rv
= SafeChdirFailNonexistent
;
919 /* Not following symlinks, so the attempt to
920 * chdir() into a symlink should be prevented.
922 rv
= SafeChdirFailSymlink
;
924 saved_errno
= 0; /* silence the error message */
930 /* Although the immediately following chdir() would detect
931 * the fact that this is not a directory for us, this would
932 * result in an extra system call that fails. Anybody
933 * examining the system-call trace should ideally not be
934 * concerned that something is actually failing.
936 if (!S_ISDIR(statbuf_dest
->st_mode
))
938 rv
= SafeChdirFailNotDir
;
940 saved_errno
= 0; /* silence the error message */
945 fprintf(stderr
, "safely_chdir(): chdir(\"%s\")\n", dest
);
947 if (0 == chdir(dest
))
949 /* check we ended up where we wanted to go */
950 boolean changed
= false;
951 wd_sanity_check(".", program_name
, ".",
952 statbuf_dest
->st_dev
,
953 statbuf_dest
->st_ino
,
955 0, __LINE__
, direction
,
956 FATAL_IF_SANITY_CHECK_FAILS
,
964 if (ENOENT
== saved_errno
)
966 rv
= SafeChdirFailNonexistent
;
968 if (options
.ignore_readdir_race
)
969 errno
= 0; /* don't issue err msg */
971 name
= specific_dirname(dest
);
973 else if (ENOTDIR
== saved_errno
)
975 /* This can happen if the we stat a directory,
976 * and then filesystem activity changes it into
979 saved_errno
= 0; /* don't issue err msg */
980 rv
= SafeChdirFailNotDir
;
985 rv
= SafeChdirFailChdirFailed
;
987 name
= specific_dirname(dest
);
995 rv
= SafeChdirFailStat
;
997 name
= specific_dirname(dest
);
998 if ( (ENOENT
== saved_errno
) || (0 == state
.curdepth
))
999 saved_errno
= 0; /* don't issue err msg */
1005 /* We do not have read permissions on "." */
1006 rv
= SafeChdirFailWouldBeUnableToReturn
;
1013 /* We use the same exit path for successs or failure.
1014 * which has occurred is recorded in RV.
1019 errno
= saved_errno
;
1021 /* do not call error() as this would result in a duplicate error message
1022 * when the caller does the same thing.
1039 /* Safely go back to the starting directory. */
1043 struct stat stat_buf
;
1046 if (starting_desc
< 0)
1049 fprintf(stderr
, "chdir_back(): chdir(\"%s\")\n", starting_dir
);
1051 if (chdir (starting_dir
) != 0)
1052 error (1, errno
, "%s", starting_dir
);
1054 wd_sanity_check(starting_dir
,
1057 starting_stat_buf
.st_dev
,
1058 starting_stat_buf
.st_ino
,
1059 &stat_buf
, 0, __LINE__
,
1061 FATAL_IF_SANITY_CHECK_FAILS
,
1067 fprintf(stderr
, "chdir_back(): chdir(<starting-point>)\n");
1069 if (fchdir (starting_desc
) != 0)
1070 error (1, errno
, "%s", starting_dir
);
1074 /* Descend PATHNAME, which is a command-line argument.
1075 Actions like -execdir assume that we are in the
1076 parent directory of the file we're examining,
1077 and on entry to this function our working directory
1078 is whetever it was when find was invoked. Therefore
1079 If PATHNAME is "." we just leave things as they are.
1080 Otherwise, we figure out what the parent directory is,
1084 process_top_path (char *pathname
, mode_t mode
)
1087 char *parent_dir
= dir_name(pathname
);
1088 char *base
= base_name(pathname
);
1091 state
.path_length
= strlen (pathname
);
1093 if (0 == strcmp(pathname
, parent_dir
))
1100 enum TraversalDirection direction
;
1101 enum SafeChdirStatus chdir_status
;
1105 if (0 == strcmp(base
, ".."))
1106 direction
= TraversingUp
;
1108 direction
= TraversingDown
;
1110 /* We pass SymlinkFollowOk to safely_chdir(), which allows it to
1111 * chdir() into a symbolic link. This is only useful for the
1112 * case where the directory we're chdir()ing into is the
1113 * basename of a command line argument, for example where
1114 * "foo/bar/baz" is specified on the command line. When -P is
1115 * in effect (the default), baz will not be followed if it is a
1116 * symlink, but if bar is a symlink, it _should_ be followed.
1117 * Hence we need the ability to override the policy set by
1118 * following_links().
1120 chdir_status
= safely_chdir(parent_dir
, direction
, &st
, SymlinkFollowOk
);
1121 if (SafeChdirOK
!= chdir_status
)
1124 error (0, errno
, "%s", parent_dir
);
1126 error (0, 0, "Failed to safely change directory into `%s'",
1129 /* We can't process this command-line argument. */
1130 state
.exit_status
= 1;
1138 process_path (pathname
, base
, false, ".", mode
);
1139 complete_pending_execdirs(eval_tree
);
1148 /* Info on each directory in the current tree branch, to avoid
1149 getting stuck in symbolic link loops. */
1150 static struct dir_id
*dir_ids
= NULL
;
1151 /* Entries allocated in `dir_ids'. */
1152 static int dir_alloc
= 0;
1153 /* Index in `dir_ids' of directory currently being searched.
1154 This is always the last valid entry. */
1155 static int dir_curr
= -1;
1156 /* (Arbitrary) number of entries to grow `dir_ids' by. */
1157 #define DIR_ALLOC_STEP 32
1161 /* We've detected a filesystem loop. This is caused by one of
1164 * 1. Option -L is in effect and we've hit a symbolic link that
1165 * points to an ancestor. This is harmless. We won't traverse the
1168 * 2. We have hit a real cycle in the directory hierarchy. In this
1169 * case, we issue a diagnostic message (POSIX requires this) and we
1170 * skip that directory entry.
1173 issue_loop_warning(const char *name
, const char *pathname
, int level
)
1175 struct stat stbuf_link
;
1176 if (lstat(name
, &stbuf_link
) != 0)
1177 stbuf_link
.st_mode
= S_IFREG
;
1179 if (S_ISLNK(stbuf_link
.st_mode
))
1182 _("Symbolic link `%s' is part of a loop in the directory hierarchy; we have already visited the directory to which it points."),
1187 int distance
= 1 + (dir_curr
-level
);
1188 /* We have found an infinite loop. POSIX requires us to
1189 * issue a diagnostic. Usually we won't get to here
1190 * because when the leaf optimisation is on, it will cause
1191 * the subdirectory to be skipped. If /a/b/c/d is a hard
1192 * link to /a/b, then the link count of /a/b/c is 2,
1193 * because the ".." entry of /b/b/c/d points to /a, not
1197 _("Filesystem loop detected; `%s' has the same device number and inode as a directory which is %d %s."),
1201 _("level higher in the filesystem hierarchy") :
1202 _("levels higher in the filesystem hierarchy")));
1206 /* Recursively descend path PATHNAME, applying the predicates.
1207 LEAF is true if PATHNAME is known to be in a directory that has no
1208 more unexamined subdirectories, and therefore it is not a directory.
1209 Knowing this allows us to avoid calling stat as long as possible for
1212 NAME is PATHNAME relative to the current directory. We access NAME
1215 PARENT is the path of the parent of NAME, relative to find's
1218 Return nonzero iff PATHNAME is a directory. */
1221 process_path (char *pathname
, char *name
, boolean leaf
, char *parent
,
1224 struct stat stat_buf
;
1225 static dev_t root_dev
; /* Device ID of current argument pathname. */
1228 /* Assume it is a non-directory initially. */
1229 stat_buf
.st_mode
= 0;
1230 state
.rel_pathname
= name
;
1232 state
.have_stat
= false;
1233 state
.have_type
= false;
1235 /* If we know the type of the directory entry, and it is not a
1236 * symbolic link, we may be able to avoid a stat() or lstat() call.
1240 if (S_ISLNK(mode
) && following_links())
1242 /* mode is wrong because we should have followed the symlink. */
1243 if (get_statinfo(pathname
, name
, &stat_buf
) != 0)
1245 mode
= state
.type
= stat_buf
.st_mode
;
1246 state
.have_type
= true;
1250 state
.have_type
= true;
1251 stat_buf
.st_mode
= state
.type
= mode
;
1256 /* Mode is not yet known; may have to stat the file unless we
1257 * can deduce that it is not a directory (which is all we need to
1258 * know at this stage)
1262 state
.have_stat
= false;
1263 state
.have_type
= false;;
1268 if (get_statinfo(pathname
, name
, &stat_buf
) != 0)
1271 /* If -L is in effect and we are dealing with a symlink,
1272 * st_mode is the mode of the pointed-to file, while mode is
1273 * the mode of the directory entry (S_IFLNK). Hence now
1274 * that we have the stat information, override "mode".
1276 state
.type
= stat_buf
.st_mode
;
1277 state
.have_type
= true;
1281 if (!S_ISDIR (state
.type
))
1283 if (state
.curdepth
>= options
.mindepth
)
1284 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1288 /* From here on, we're working on a directory. */
1291 /* Now we really need to stat the directory, even if we knoe the
1292 * type, because we need information like struct stat.st_rdev.
1294 if (get_statinfo(pathname
, name
, &stat_buf
) != 0)
1297 state
.have_stat
= true;
1298 mode
= state
.type
= stat_buf
.st_mode
; /* use full info now that we have it. */
1299 state
.stop_at_current_level
=
1300 options
.maxdepth
>= 0
1301 && state
.curdepth
>= options
.maxdepth
;
1303 /* If we've already seen this directory on this branch,
1304 don't descend it again. */
1305 for (i
= 0; i
<= dir_curr
; i
++)
1306 if (stat_buf
.st_ino
== dir_ids
[i
].ino
&&
1307 stat_buf
.st_dev
== dir_ids
[i
].dev
)
1309 state
.stop_at_current_level
= true;
1310 issue_loop_warning(name
, pathname
, i
);
1313 if (dir_alloc
<= ++dir_curr
)
1315 dir_alloc
+= DIR_ALLOC_STEP
;
1316 dir_ids
= (struct dir_id
*)
1317 xrealloc ((char *) dir_ids
, dir_alloc
* sizeof (struct dir_id
));
1319 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1320 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1322 if (options
.stay_on_filesystem
)
1324 if (state
.curdepth
== 0)
1325 root_dev
= stat_buf
.st_dev
;
1326 else if (stat_buf
.st_dev
!= root_dev
)
1327 state
.stop_at_current_level
= true;
1330 if (options
.do_dir_first
&& state
.curdepth
>= options
.mindepth
)
1331 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1334 fprintf(stderr
, "pathname = %s, stop_at_current_level = %d\n",
1335 pathname
, state
.stop_at_current_level
);
1338 if (state
.stop_at_current_level
== false)
1339 /* Scan directory on disk. */
1340 process_dir (pathname
, name
, strlen (pathname
), &stat_buf
, parent
);
1342 if (options
.do_dir_first
== false && state
.curdepth
>= options
.mindepth
)
1344 state
.rel_pathname
= name
;
1345 apply_predicate (pathname
, &stat_buf
, eval_tree
);
1353 /* Examine the predicate list for instances of -execdir or -okdir
1354 * which have been terminated with '+' (build argument list) rather
1355 * than ';' (singles only). If there are any, run them (this will
1356 * have no effect if there are no arguments waiting).
1359 complete_pending_execdirs(struct predicate
*p
)
1361 #if defined(NEW_EXEC)
1365 complete_pending_execdirs(p
->pred_left
);
1367 if (p
->pred_func
== pred_execdir
|| p
->pred_func
== pred_okdir
)
1369 /* It's an exec-family predicate. p->args.exec_val is valid. */
1370 if (p
->args
.exec_vec
.multiple
)
1372 struct exec_val
*execp
= &p
->args
.exec_vec
;
1374 /* This one was terminated by '+' and so might have some
1375 * left... Run it if neccessary.
1377 if (execp
->state
.todo
)
1379 /* There are not-yet-executed arguments. */
1380 launch (&execp
->ctl
, &execp
->state
);
1385 complete_pending_execdirs(p
->pred_right
);
1387 /* nothing to do. */
1392 /* Examine the predicate list for instances of -exec which have been
1393 * terminated with '+' (build argument list) rather than ';' (singles
1394 * only). If there are any, run them (this will have no effect if
1395 * there are no arguments waiting).
1398 complete_pending_execs(struct predicate
*p
)
1400 #if defined(NEW_EXEC)
1404 complete_pending_execs(p
->pred_left
);
1406 /* It's an exec-family predicate then p->args.exec_val is valid
1407 * and we can check it.
1409 if (p
->pred_func
== pred_exec
&& p
->args
.exec_vec
.multiple
)
1411 struct exec_val
*execp
= &p
->args
.exec_vec
;
1413 /* This one was terminated by '+' and so might have some
1414 * left... Run it if neccessary. Set state.exit_status if
1415 * there are any problems.
1417 if (execp
->state
.todo
)
1419 /* There are not-yet-executed arguments. */
1420 launch (&execp
->ctl
, &execp
->state
);
1424 complete_pending_execs(p
->pred_right
);
1426 /* nothing to do. */
1432 /* Scan directory PATHNAME and recurse through process_path for each entry.
1434 PATHLEN is the length of PATHNAME.
1436 NAME is PATHNAME relative to the current directory.
1438 STATP is the results of *options.xstat on it.
1440 PARENT is the path of the parent of NAME, relative to find's
1441 starting directory. */
1444 process_dir (char *pathname
, char *name
, int pathlen
, struct stat
*statp
, char *parent
)
1446 char *name_space
; /* Names of files in PATHNAME. */
1447 int subdirs_left
; /* Number of unexamined subdirs in PATHNAME. */
1448 int idx
; /* Which entry are we on? */
1449 struct stat stat_buf
;
1450 struct savedir_dirinfo
*dirinfo
;
1452 subdirs_left
= statp
->st_nlink
- 2; /* Account for name and ".". */
1455 name_space
= savedirinfo (name
, &dirinfo
);
1457 if (name_space
== NULL
)
1460 error (0, errno
, "%s", pathname
);
1461 state
.exit_status
= 1;
1465 register char *namep
; /* Current point in `name_space'. */
1466 char *cur_path
; /* Full path of each file to process. */
1467 char *cur_name
; /* Base name of each file to process. */
1468 unsigned cur_path_size
; /* Bytes allocated for `cur_path'. */
1469 register unsigned file_len
; /* Length of each path to process. */
1470 register unsigned pathname_len
; /* PATHLEN plus trailing '/'. */
1472 if (pathname
[pathlen
- 1] == '/')
1473 pathname_len
= pathlen
+ 1; /* For '\0'; already have '/'. */
1475 pathname_len
= pathlen
+ 2; /* For '/' and '\0'. */
1479 /* We're about to leave the directory. If there are any
1480 * -execdir argument lists which have been built but have not
1481 * yet been processed, do them now because they must be done in
1482 * the same directory.
1484 complete_pending_execdirs(eval_tree
);
1487 if (strcmp (name
, "."))
1489 enum SafeChdirStatus status
= safely_chdir (name
, TraversingDown
, &stat_buf
, SymlinkHandleDefault
);
1493 /* If there had been a change but wd_sanity_check()
1494 * accepted it, we need to accept that on the
1495 * way back up as well, so modify our record
1496 * of what we think we should see later.
1497 * If there was no change, the assignments are a no-op.
1499 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1500 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1503 case SafeChdirFailNonexistent
:
1504 case SafeChdirFailStat
:
1505 case SafeChdirFailWouldBeUnableToReturn
:
1506 case SafeChdirFailSymlink
:
1507 case SafeChdirFailNotDir
:
1508 case SafeChdirFailChdirFailed
:
1509 error (0, errno
, "%s", pathname
);
1510 state
.exit_status
= 1;
1515 if (0 != strcmp (name
, "."))
1518 fprintf(stderr
, "process_dir(): chdir(\"%s\")\n", name
);
1520 if (chdir (name
) < 0)
1522 error (0, errno
, "%s", pathname
);
1529 /* Check that we are where we should be. */
1532 boolean changed
= false;
1533 wd_sanity_check(pathname
,
1536 dir_ids
[dir_curr
].dev
,
1537 dir_ids
[dir_curr
].ino
,
1538 &stat_buf
, 0, __LINE__
,
1540 FATAL_IF_SANITY_CHECK_FAILS
,
1544 /* If there had been a change but wd_sanity_check()
1545 * accepted it, we need to accept that on the
1546 * way back up as well, so modify our record
1547 * of what we think we should see later.
1549 dir_ids
[dir_curr
].dev
= stat_buf
.st_dev
;
1550 dir_ids
[dir_curr
].ino
= stat_buf
.st_ino
;
1555 for (idx
=0, namep
= name_space
; *namep
; namep
+= file_len
- pathname_len
+ 1, ++idx
)
1557 /* savedirinfo() may return dirinfo=NULL if extended information
1560 mode_t mode
= dirinfo
? dirinfo
[idx
].type_info
: 0;
1562 /* Append this directory entry's name to the path being searched. */
1563 file_len
= pathname_len
+ strlen (namep
);
1564 if (file_len
> cur_path_size
)
1566 while (file_len
> cur_path_size
)
1567 cur_path_size
+= 1024;
1570 cur_path
= xmalloc (cur_path_size
);
1571 strcpy (cur_path
, pathname
);
1572 cur_path
[pathname_len
- 2] = '/';
1574 cur_name
= cur_path
+ pathname_len
- 1;
1575 strcpy (cur_name
, namep
);
1578 if (!options
.no_leaf_check
)
1580 if (mode
&& S_ISDIR(mode
) && (subdirs_left
== 0))
1582 /* This is a subdirectory, but the number of directories we
1583 * have found now exceeds the number we would expect given
1584 * the hard link count on the parent. This is likely to be
1585 * a bug in the filesystem driver (e.g. Linux's
1586 * /proc filesystem) or may just be a fact that the OS
1587 * doesn't really handle hard links with Unix semantics.
1588 * In the latter case, -noleaf should be used routinely.
1590 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."),
1592 state
.exit_status
= 1; /* We know the result is wrong, now */
1593 options
.no_leaf_check
= true; /* Don't make same
1595 subdirs_left
= 1; /* band-aid for this iteration. */
1598 /* Normal case optimization. On normal Unix
1599 filesystems, a directory that has no subdirectories
1600 has two links: its name, and ".". Any additional
1601 links are to the ".." entries of its subdirectories.
1602 Once we have processed as many subdirectories as
1603 there are additional links, we know that the rest of
1604 the entries are non-directories -- in other words,
1606 subdirs_left
-= process_path (cur_path
, cur_name
,
1607 subdirs_left
== 0, pathname
,
1612 /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems
1613 mounted, which don't have Unix-like directory link counts. */
1614 process_path (cur_path
, cur_name
, false, pathname
, mode
);
1621 /* We're about to leave the directory. If there are any
1622 * -execdir argument lists which have been built but have not
1623 * yet been processed, do them now because they must be done in
1624 * the same directory.
1626 complete_pending_execdirs(eval_tree
);
1629 if (strcmp (name
, "."))
1631 enum SafeChdirStatus status
;
1633 boolean changed
= false;
1635 /* We could go back and do the next command-line arg
1636 instead, maybe using longjmp. */
1638 boolean deref
= following_links() ? true : false;
1640 if ( (state
.curdepth
>0) && !deref
)
1648 status
= safely_chdir (dir
, TraversingUp
, &stat_buf
, SymlinkHandleDefault
);
1654 case SafeChdirFailNonexistent
:
1655 case SafeChdirFailStat
:
1656 case SafeChdirFailWouldBeUnableToReturn
:
1657 case SafeChdirFailSymlink
:
1658 case SafeChdirFailNotDir
:
1659 case SafeChdirFailChdirFailed
:
1660 error (1, errno
, "%s", pathname
);
1666 did
.dev
= dir_ids
[dir_curr
-1].dev
;
1667 did
.ino
= dir_ids
[dir_curr
-1].ino
;
1671 did
.dev
= starting_stat_buf
.st_dev
;
1672 did
.ino
= starting_stat_buf
.st_ino
;
1675 wd_sanity_check(pathname
,
1684 FATAL_IF_SANITY_CHECK_FAILS
,
1688 if (strcmp (name
, "."))
1690 /* We could go back and do the next command-line arg
1691 instead, maybe using longjmp. */
1693 boolean deref
= following_links() ? true : false;
1704 fprintf(stderr
, "process_dir(): chdir(\"%s\")\n", dir
);
1706 if (chdir (dir
) != 0)
1707 error (1, errno
, "%s", parent
);
1709 /* Check that we are where we should be. */
1712 boolean changed
= false;
1714 int problem_is_with_parent
;
1716 memset(&tmp
, 0, sizeof(tmp
));
1719 tmp
.st_dev
= dir_ids
[dir_curr
-1].dev
;
1720 tmp
.st_ino
= dir_ids
[dir_curr
-1].ino
;
1724 tmp
.st_dev
= starting_stat_buf
.st_dev
;
1725 tmp
.st_ino
= starting_stat_buf
.st_ino
;
1728 problem_is_with_parent
= deref
? 1 : 0;
1729 wd_sanity_check(pathname
,
1735 problem_is_with_parent
, __LINE__
,
1737 FATAL_IF_SANITY_CHECK_FAILS
,
1750 /* Return true if there are no predicates with no_default_print in
1751 predicate list PRED, false if there are any.
1752 Returns true if default print should be performed */
1755 default_prints (struct predicate
*pred
)
1757 while (pred
!= NULL
)
1759 if (pred
->no_default_print
)
1761 pred
= pred
->pred_next
;