Applied patch from Jim Meyering; if we open an output file but stderr is closed,...
[findutils.git] / find / find.c
blobfe2c1f451c0c0bb326b78be0f9885c5780e6e75b
1 /* find -- search for files in a directory hierarchy
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 USA.*/
19 /* GNU find was written by Eric Decker <cire@cisco.com>,
20 with enhancements by David MacKenzie <djm@gnu.org>,
21 Jay Plett <jay@silence.princeton.nj.us>,
22 and Tim Wood <axolotl!tim@toad.com>.
23 The idea for -print0 and xargs -0 came from
24 Dan Bernstein <brnstnd@kramden.acf.nyu.edu>. */
27 #include "defs.h"
29 #define USE_SAFE_CHDIR 1
30 #undef STAT_MOUNTPOINTS
33 #include <errno.h>
34 #include <assert.h>
37 #ifdef HAVE_FCNTL_H
38 #include <fcntl.h>
39 #else
40 #include <sys/file.h>
41 #endif
43 #ifdef HAVE_SYS_UTSNAME_H
44 #include <sys/utsname.h>
45 #endif
47 #include "../gnulib/lib/xalloc.h"
48 #include "../gnulib/lib/human.h"
49 #include "../gnulib/lib/canonicalize.h"
50 #include "closeout.h"
51 #include <modetype.h>
52 #include "savedirinfo.h"
53 #include "buildcmd.h"
54 #include "dirname.h"
55 #include "quote.h"
56 #include "quotearg.h"
58 #ifdef HAVE_LOCALE_H
59 #include <locale.h>
60 #endif
62 #if ENABLE_NLS
63 # include <libintl.h>
64 # define _(Text) gettext (Text)
65 #else
66 # define _(Text) Text
67 #define textdomain(Domain)
68 #define bindtextdomain(Package, Directory)
69 #endif
70 #ifdef gettext_noop
71 # define N_(String) gettext_noop (String)
72 #else
73 /* See locate.c for explanation as to why not use (String) */
74 # define N_(String) String
75 #endif
77 #define apply_predicate(pathname, stat_buf_ptr, node) \
78 (*(node)->pred_func)((pathname), (stat_buf_ptr), (node))
80 #ifdef STAT_MOUNTPOINTS
81 static void init_mounted_dev_list(void);
82 #endif
84 static void process_top_path PARAMS((char *pathname, mode_t mode));
85 static int process_path PARAMS((char *pathname, char *name, boolean leaf, char *parent, mode_t type));
86 static void process_dir PARAMS((char *pathname, char *name, int pathlen, struct stat *statp, char *parent));
88 static void complete_pending_execdirs(struct predicate *p);
89 static void complete_pending_execs (struct predicate *p);
93 static boolean default_prints PARAMS((struct predicate *pred));
95 /* Name this program was run with. */
96 char *program_name;
98 /* All predicates for each path to process. */
99 struct predicate *predicates;
101 /* The last predicate allocated. */
102 struct predicate *last_pred;
104 /* The root of the evaluation tree. */
105 static struct predicate *eval_tree = NULL;
108 struct options options;
109 struct state state;
111 /* The full path of the initial working directory, or "." if
112 STARTING_DESC is nonnegative. */
113 char const *starting_dir = ".";
115 /* A file descriptor open to the initial working directory.
116 Doing it this way allows us to work when the i.w.d. has
117 unreadable parents. */
118 int starting_desc;
120 /* The stat buffer of the initial working directory. */
121 struct stat starting_stat_buf;
123 enum ChdirSymlinkHandling
125 SymlinkHandleDefault, /* Normally the right choice */
126 SymlinkFollowOk /* see comment in process_top_path() */
130 enum TraversalDirection
132 TraversingUp,
133 TraversingDown
136 enum WdSanityCheckFatality
138 FATAL_IF_SANITY_CHECK_FAILS,
139 RETRY_IF_SANITY_CHECK_FAILS,
140 NON_FATAL_IF_SANITY_CHECK_FAILS
145 following_links(void)
147 switch (options.symlink_handling)
149 case SYMLINK_ALWAYS_DEREF:
150 return 1;
151 case SYMLINK_DEREF_ARGSONLY:
152 return (state.curdepth == 0);
153 case SYMLINK_NEVER_DEREF:
154 default:
155 return 0;
160 static int
161 fallback_stat(const char *name, struct stat *p, int prev_rv)
163 /* Our original stat() call failed. Perhaps we can't follow a
164 * symbolic link. If that might be the problem, lstat() the link.
165 * Otherwise, admit defeat.
167 switch (errno)
169 case ENOENT:
170 case ENOTDIR:
171 #ifdef DEBUG_STAT
172 fprintf(stderr, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name);
173 #endif
174 return lstat(name, p);
176 case EACCES:
177 case EIO:
178 case ELOOP:
179 case ENAMETOOLONG:
180 #ifdef EOVERFLOW
181 case EOVERFLOW: /* EOVERFLOW is not #defined on UNICOS. */
182 #endif
183 default:
184 return prev_rv;
189 /* optionh_stat() implements the stat operation when the -H option is
190 * in effect.
192 * If the item to be examined is a command-line argument, we follow
193 * symbolic links. If the stat() call fails on the command-line item,
194 * we fall back on the properties of the symbolic link.
196 * If the item to be examined is not a command-line argument, we
197 * examine the link itself.
199 int
200 optionh_stat(const char *name, struct stat *p)
202 if (0 == state.curdepth)
204 /* This file is from the command line; deference the link (if it
205 * is a link).
207 int rv = stat(name, p);
208 if (0 == rv)
209 return 0; /* success */
210 else
211 return fallback_stat(name, p, rv);
213 else
215 /* Not a file on the command line; do not dereference the link.
217 return lstat(name, p);
221 /* optionl_stat() implements the stat operation when the -L option is
222 * in effect. That option makes us examine the thing the symbolic
223 * link points to, not the symbolic link itself.
225 int
226 optionl_stat(const char *name, struct stat *p)
228 int rv = stat(name, p);
229 if (0 == rv)
230 return 0; /* normal case. */
231 else
232 return fallback_stat(name, p, rv);
235 /* optionp_stat() implements the stat operation when the -P option is
236 * in effect (this is also the default). That option makes us examine
237 * the symbolic link itself, not the thing it points to.
239 int
240 optionp_stat(const char *name, struct stat *p)
242 return lstat(name, p);
245 #ifdef DEBUG_STAT
246 static uintmax_t stat_count = 0u;
248 static int
249 debug_stat (const char *file, struct stat *bufp)
251 ++stat_count;
252 fprintf (stderr, "debug_stat (%s)\n", file);
253 switch (options.symlink_handling)
255 case SYMLINK_ALWAYS_DEREF:
256 return optionl_stat(file, bufp);
257 case SYMLINK_DEREF_ARGSONLY:
258 return optionh_stat(file, bufp);
259 case SYMLINK_NEVER_DEREF:
260 return optionp_stat(file, bufp);
263 #endif /* DEBUG_STAT */
265 void
266 set_follow_state(enum SymlinkOption opt)
268 switch (opt)
270 case SYMLINK_ALWAYS_DEREF: /* -L */
271 options.xstat = optionl_stat;
272 options.no_leaf_check = true;
273 break;
275 case SYMLINK_NEVER_DEREF: /* -P (default) */
276 options.xstat = optionp_stat;
277 /* Can't turn no_leaf_check off because the user might have specified
278 * -noleaf anyway
280 break;
282 case SYMLINK_DEREF_ARGSONLY: /* -H */
283 options.xstat = optionh_stat;
284 options.no_leaf_check = true;
287 options.symlink_handling = opt;
289 /* For DEBUG_STAT, the choice is made at runtime within debug_stat()
290 * by checking the contents of the symlink_handling variable.
292 #if defined(DEBUG_STAT)
293 options.xstat = debug_stat;
294 #endif /* !DEBUG_STAT */
298 /* Complete any outstanding commands.
300 void
301 cleanup(void)
303 if (eval_tree)
305 complete_pending_execs(eval_tree);
306 complete_pending_execdirs(eval_tree);
310 /* Get the stat information for a file, if it is
311 * not already known.
314 get_statinfo (const char *pathname, const char *name, struct stat *p)
316 if (!state.have_stat && (*options.xstat) (name, p) != 0)
318 if (!options.ignore_readdir_race || (errno != ENOENT) )
320 error (0, errno, "%s", pathname);
321 state.exit_status = 1;
323 return -1;
325 state.have_stat = true;
326 state.have_type = true;
327 state.type = p->st_mode;
328 return 0;
331 /* Get the stat/type information for a file, if it is
332 * not already known.
335 get_info (const char *pathname,
336 const char *name,
337 struct stat *p,
338 struct predicate *pred_ptr)
340 /* If we need the full stat info, or we need the type info but don't
341 * already have it, stat the file now.
343 (void) name;
344 if (pred_ptr->need_stat)
346 return get_statinfo(pathname, state.rel_pathname, p);
348 if ((pred_ptr->need_type && (0 == state.have_type)))
350 return get_statinfo(pathname, state.rel_pathname, p);
352 return 0;
355 /* Determine if we can use O_NOFOLLOW.
357 #if defined(O_NOFOLLOW)
358 static boolean
359 check_nofollow(void)
361 struct utsname uts;
362 float release;
364 if (0 == uname(&uts))
366 /* POSIX requires that atof() ignore "unrecognised suffixes". */
367 release = atof(uts.release);
369 if (0 == strcmp("Linux", uts.sysname))
371 /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
372 return release >= 2.2; /* close enough */
374 else if (0 == strcmp("FreeBSD", uts.sysname))
376 /* FreeBSD 3.0-CURRENT and later support it */
377 return release >= 3.1;
381 /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
382 return true;
384 #endif
387 main (int argc, char **argv)
389 int i;
390 const struct parser_table *parse_entry; /* Pointer to the parsing table entry for this expression. */
391 struct predicate *cur_pred;
392 char *predicate_name; /* Name of predicate being parsed. */
393 int end_of_leading_options = 0; /* First arg after any -H/-L etc. */
394 program_name = argv[0];
395 const struct parser_table *entry_close, *entry_print, *entry_open;
398 /* We call check_nofollow() before setlocale() because the numbers
399 * for which we check (in the results of uname) definitiely have "."
400 * as the decimal point indicator even under locales for which that
401 * is not normally true. Hence atof() would do the wrong thing
402 * if we call it after setlocale().
404 #ifdef O_NOFOLLOW
405 options.open_nofollow_available = check_nofollow();
406 #else
407 options.open_nofollow_available = false;
408 #endif
410 options.regex_options = RE_SYNTAX_POSIX_BASIC;
412 #ifdef HAVE_SETLOCALE
413 setlocale (LC_ALL, "");
414 #endif
415 bindtextdomain (PACKAGE, LOCALEDIR);
416 textdomain (PACKAGE);
417 atexit (close_stdout);
420 if (isatty(0))
422 options.warnings = true;
424 else
426 options.warnings = false;
430 predicates = NULL;
431 last_pred = NULL;
432 options.do_dir_first = true;
433 options.maxdepth = options.mindepth = -1;
434 options.start_time = time (NULL);
435 options.cur_day_start = options.start_time - DAYSECS;
436 options.full_days = false;
437 options.stay_on_filesystem = false;
438 options.ignore_readdir_race = false;
440 state.exit_status = 0;
442 #if defined(DEBUG_STAT)
443 options.xstat = debug_stat;
444 #endif /* !DEBUG_STAT */
446 if (getenv("POSIXLY_CORRECT"))
447 options.output_block_size = 512;
448 else
449 options.output_block_size = 1024;
451 if (getenv("FIND_BLOCK_SIZE"))
453 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"));
456 options.no_leaf_check = false;
457 set_follow_state(SYMLINK_NEVER_DEREF); /* The default is equivalent to -P. */
459 #ifdef DEBUG
460 fprintf (stderr, "cur_day_start = %s", ctime (&options.cur_day_start));
461 #endif /* DEBUG */
463 /* Check for -P, -H or -L options. */
464 for (i=1; (end_of_leading_options = i) < argc; ++i)
466 if (0 == strcmp("-H", argv[i]))
468 /* Meaning: dereference symbolic links on command line, but nowhere else. */
469 set_follow_state(SYMLINK_DEREF_ARGSONLY);
471 else if (0 == strcmp("-L", argv[i]))
473 /* Meaning: dereference all symbolic links. */
474 set_follow_state(SYMLINK_ALWAYS_DEREF);
476 else if (0 == strcmp("-P", argv[i]))
478 /* Meaning: never dereference symbolic links (default). */
479 set_follow_state(SYMLINK_NEVER_DEREF);
481 else if (0 == strcmp("--", argv[i]))
483 /* -- signifies the end of options. */
484 end_of_leading_options = i+1; /* Next time start with the next option */
485 break;
487 else
489 /* Hmm, must be one of
490 * (a) A path name
491 * (b) A predicate
493 end_of_leading_options = i; /* Next time start with this option */
494 break;
498 /* We are now processing the part of the "find" command line
499 * after the -H/-L options (if any).
502 /* fprintf(stderr, "rest: optind=%ld\n", (long)optind); */
504 /* Find where in ARGV the predicates begin. */
505 for (i = end_of_leading_options; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++)
507 /* fprintf(stderr, "Looks like %s is not a predicate\n", argv[i]); */
508 /* Do nothing. */ ;
511 /* Enclose the expression in `( ... )' so a default -print will
512 apply to the whole expression. */
513 entry_open = find_parser("(");
514 entry_close = find_parser(")");
515 entry_print = find_parser("print");
516 assert(entry_open != NULL);
517 assert(entry_close != NULL);
518 assert(entry_print != NULL);
520 parse_open (entry_open, argv, &argc);
521 pred_sanity_check(last_pred);
523 /* Build the input order list. */
524 while (i < argc)
526 if (strchr ("-!(),", argv[i][0]) == NULL)
527 usage (_("paths must precede expression"));
528 predicate_name = argv[i];
529 parse_entry = find_parser (predicate_name);
530 if (parse_entry == NULL)
532 /* Command line option not recognized */
533 error (1, 0, _("invalid predicate `%s'"), predicate_name);
536 i++;
537 if (!(*(parse_entry->parser_func)) (parse_entry, argv, &i))
539 if (argv[i] == NULL)
540 /* Command line option requires an argument */
541 error (1, 0, _("missing argument to `%s'"), predicate_name);
542 else
543 error (1, 0, _("invalid argument `%s' to `%s'"),
544 argv[i], predicate_name);
547 pred_sanity_check(last_pred);
548 pred_sanity_check(predicates); /* XXX: expensive */
551 if (predicates->pred_next == NULL)
553 /* No predicates that do something other than set a global variable
554 were given; remove the unneeded initial `(' and add `-print'. */
555 cur_pred = predicates;
556 predicates = last_pred = predicates->pred_next;
557 free ((char *) cur_pred);
558 parse_print (entry_print, argv, &argc);
559 pred_sanity_check(last_pred);
560 pred_sanity_check(predicates); /* XXX: expensive */
562 else if (!default_prints (predicates->pred_next))
564 /* One or more predicates that produce output were given;
565 remove the unneeded initial `('. */
566 cur_pred = predicates;
567 predicates = predicates->pred_next;
568 pred_sanity_check(predicates); /* XXX: expensive */
569 free ((char *) cur_pred);
571 else
573 /* `( user-supplied-expression ) -print'. */
574 parse_close (entry_close, argv, &argc);
575 pred_sanity_check(last_pred);
576 parse_print (entry_print, argv, &argc);
577 pred_sanity_check(last_pred);
578 pred_sanity_check(predicates); /* XXX: expensive */
581 #ifdef DEBUG
582 fprintf (stderr, "Predicate List:\n");
583 print_list (stderr, predicates);
584 #endif /* DEBUG */
586 /* do a sanity check */
587 pred_sanity_check(predicates);
589 /* Done parsing the predicates. Build the evaluation tree. */
590 cur_pred = predicates;
591 eval_tree = get_expr (&cur_pred, NO_PREC);
593 /* Check if we have any left-over predicates (this fixes
594 * Debian bug #185202).
596 if (cur_pred != NULL)
598 error (1, 0, _("unexpected extra predicate"));
601 #ifdef DEBUG
602 fprintf (stderr, "Eval Tree:\n");
603 print_tree (stderr, eval_tree, 0);
604 #endif /* DEBUG */
606 /* Rearrange the eval tree in optimal-predicate order. */
607 opt_expr (&eval_tree);
609 /* Determine the point, if any, at which to stat the file. */
610 mark_stat (eval_tree);
611 /* Determine the point, if any, at which to determine file type. */
612 mark_type (eval_tree);
614 #ifdef DEBUG
615 fprintf (stderr, "Optimized Eval Tree:\n");
616 print_tree (stderr, eval_tree, 0);
617 fprintf (stderr, "Optimized command line:\n");
618 print_optlist(stderr, eval_tree);
619 fprintf(stderr, "\n");
620 #endif /* DEBUG */
622 /* safely_chdir() needs to check that it has ended up in the right place.
623 * To avoid bailing out when something gets automounted, it checks if
624 * the target directory appears to have had a directory mounted on it as
625 * we chdir()ed. The problem with this is that in order to notice that
626 * a filesystem was mounted, we would need to lstat() all the mount points.
627 * That strategy loses if our machine is a client of a dead NFS server.
629 * Hence if safely_chdir() and wd_sanity_check() can manage without needing
630 * to know the mounted device list, we do that.
632 if (!options.open_nofollow_available)
634 #ifdef STAT_MOUNTPOINTS
635 init_mounted_dev_list();
636 #endif
640 starting_desc = open (".", O_RDONLY);
641 if (0 <= starting_desc && fchdir (starting_desc) != 0)
643 close (starting_desc);
644 starting_desc = -1;
646 if (starting_desc < 0)
648 starting_dir = xgetcwd ();
649 if (! starting_dir)
650 error (1, errno, _("cannot get current directory"));
652 if ((*options.xstat) (".", &starting_stat_buf) != 0)
653 error (1, errno, _("cannot get current directory"));
655 /* If no paths are given, default to ".". */
656 for (i = end_of_leading_options; i < argc && strchr ("-!(),", argv[i][0]) == NULL; i++)
658 process_top_path (argv[i], 0);
661 /* If there were no path arguments, default to ".". */
662 if (i == end_of_leading_options)
665 * We use a temporary variable here because some actions modify
666 * the path temporarily. Hence if we use a string constant,
667 * we get a coredump. The best example of this is if we say
668 * "find -printf %H" (note, not "find . -printf %H").
670 char defaultpath[2] = ".";
671 process_top_path (defaultpath, 0);
674 /* If "-exec ... {} +" has been used, there may be some
675 * partially-full command lines which have been built,
676 * but which are not yet complete. Execute those now.
678 cleanup();
679 return state.exit_status;
683 static char *
684 specific_dirname(const char *dir)
686 char dirbuf[1024];
688 if (0 == strcmp(".", dir))
690 /* OK, what's '.'? */
691 if (NULL != getcwd(dirbuf, sizeof(dirbuf)))
693 return strdup(dirbuf);
695 else
697 return strdup(dir);
700 else
702 char *result = canonicalize_filename_mode(dir, CAN_EXISTING);
703 if (NULL == result)
704 return strdup(dir);
705 else
706 return result;
712 /* Return non-zero if FS is the name of a filesystem that is likely to
713 * be automounted
715 static int
716 fs_likely_to_be_automounted(const char *fs)
718 return ( (0==strcmp(fs, "nfs")) || (0==strcmp(fs, "autofs")) || (0==strcmp(fs, "subfs")));
723 #ifdef STAT_MOUNTPOINTS
724 static dev_t *mounted_devices = NULL;
725 static size_t num_mounted_devices = 0u;
728 static void
729 init_mounted_dev_list()
731 assert(NULL == mounted_devices);
732 assert(0 == num_mounted_devices);
733 mounted_devices = get_mounted_devices(&num_mounted_devices);
736 static void
737 refresh_mounted_dev_list(void)
739 if (mounted_devices)
741 free(mounted_devices);
742 mounted_devices = 0;
744 num_mounted_devices = 0u;
745 init_mounted_dev_list();
749 /* Search for device DEV in the array LIST, which is of size N. */
750 static int
751 dev_present(dev_t dev, const dev_t *list, size_t n)
753 if (list)
755 while (n-- > 0u)
757 if ( (*list++) == dev )
758 return 1;
761 return 0;
764 enum MountPointStateChange
766 MountPointRecentlyMounted,
767 MountPointRecentlyUnmounted,
768 MountPointStateUnchanged
773 static enum MountPointStateChange
774 get_mount_state(dev_t newdev)
776 int new_is_present, new_was_present;
778 new_was_present = dev_present(newdev, mounted_devices, num_mounted_devices);
779 refresh_mounted_dev_list();
780 new_is_present = dev_present(newdev, mounted_devices, num_mounted_devices);
782 if (new_was_present == new_is_present)
783 return MountPointStateUnchanged;
784 else if (new_is_present)
785 return MountPointRecentlyMounted;
786 else
787 return MountPointRecentlyUnmounted;
792 /* We stat()ed a directory, chdir()ed into it (we know this
793 * since direction is TraversingDown), stat()ed it again,
794 * and noticed that the device numbers are different. Check
795 * if the filesystem was recently mounted.
797 * If it was, it looks like chdir()ing into the directory
798 * caused a filesystem to be mounted. Maybe automount is
799 * running. Anyway, that's probably OK - but it happens
800 * only when we are moving downward.
802 * We also allow for the possibility that a similar thing
803 * has happened with the unmounting of a filesystem. This
804 * is much rarer, as it relies on an automounter timeout
805 * occurring at exactly the wrong moment.
807 static enum WdSanityCheckFatality
808 dirchange_is_fatal(const char *specific_what,
809 enum WdSanityCheckFatality isfatal,
810 int silent,
811 struct stat *newinfo)
813 enum MountPointStateChange transition = get_mount_state(newinfo->st_dev);
814 switch (transition)
816 case MountPointRecentlyUnmounted:
817 isfatal = NON_FATAL_IF_SANITY_CHECK_FAILS;
818 if (!silent)
820 error (0, 0,
821 _("Warning: filesystem %s has recently been unmounted."),
822 specific_what);
824 break;
826 case MountPointRecentlyMounted:
827 isfatal = NON_FATAL_IF_SANITY_CHECK_FAILS;
828 if (!silent)
830 error (0, 0,
831 _("Warning: filesystem %s has recently been mounted."),
832 specific_what);
834 break;
836 case MountPointStateUnchanged:
837 /* leave isfatal as it is */
838 break;
841 return isfatal;
845 #endif
849 /* Examine the results of the stat() of a directory from before we
850 * entered or left it, with the results of stat()ing it afterward. If
851 * these are different, the filesystem tree has been modified while we
852 * were traversing it. That might be an attempt to use a race
853 * condition to persuade find to do something it didn't intend
854 * (e.g. an attempt by an ordinary user to exploit the fact that root
855 * sometimes runs find on the whole filesystem). However, this can
856 * also happen if automount is running (certainly on Solaris). With
857 * automount, moving into a directory can cause a filesystem to be
858 * mounted there.
860 * To cope sensibly with this, we will raise an error if we see the
861 * device number change unless we are chdir()ing into a subdirectory,
862 * and the directory we moved into has been mounted or unmounted "recently".
863 * Here "recently" means since we started "find" or we last re-read
864 * the /etc/mnttab file.
866 * If the device number does not change but the inode does, that is a
867 * problem.
869 * If the device number and inode are both the same, we are happy.
871 * If a filesystem is (un)mounted as we chdir() into the directory, that
872 * may mean that we're now examining a section of the filesystem that might
873 * have been excluded from consideration (via -prune or -quit for example).
874 * Hence we print a warning message to indicate that the output of find
875 * might be inconsistent due to the change in the filesystem.
877 static boolean
878 wd_sanity_check(const char *thing_to_stat,
879 const char *progname,
880 const char *what,
881 dev_t old_dev,
882 ino_t old_ino,
883 struct stat *newinfo,
884 int parent,
885 int line_no,
886 enum TraversalDirection direction,
887 enum WdSanityCheckFatality isfatal,
888 boolean *changed) /* output parameter */
890 const char *fstype;
891 char *specific_what = NULL;
892 int silent = 0;
894 *changed = false;
896 if ((*options.xstat) (".", newinfo) != 0)
897 error (1, errno, "%s", thing_to_stat);
899 if (old_dev != newinfo->st_dev)
901 *changed = true;
902 specific_what = specific_dirname(what);
903 fstype = filesystem_type(newinfo);
904 silent = fs_likely_to_be_automounted(fstype);
906 /* This condition is rare, so once we are here it is
907 * reasonable to perform an expensive computation to
908 * determine if we should continue or fail.
910 if (TraversingDown == direction)
912 #ifdef STAT_MOUNTPOINTS
913 isfatal = dirchange_is_fatal(specific_what,isfatal,silent,newinfo);
914 #else
915 isfatal = RETRY_IF_SANITY_CHECK_FAILS;
916 #endif
919 switch (isfatal)
921 case FATAL_IF_SANITY_CHECK_FAILS:
923 fstype = filesystem_type(newinfo);
924 error (1, 0,
925 _("%s%s changed during execution of %s (old device number %ld, new device number %ld, filesystem type is %s) [ref %ld]"),
926 specific_what,
927 parent ? "/.." : "",
928 progname,
929 (long) old_dev,
930 (long) newinfo->st_dev,
931 fstype,
932 line_no);
933 /*NOTREACHED*/
934 return false;
937 case NON_FATAL_IF_SANITY_CHECK_FAILS:
939 /* Since the device has changed under us, the inode number
940 * will almost certainly also be different. However, we have
941 * already decided that this is not a problem. Hence we return
942 * without checking the inode number.
944 free(specific_what);
945 return true;
948 case RETRY_IF_SANITY_CHECK_FAILS:
949 return false;
953 /* Device number was the same, check if the inode has changed. */
954 if (old_ino != newinfo->st_ino)
956 *changed = true;
957 specific_what = specific_dirname(what);
958 fstype = filesystem_type(newinfo);
960 error ((isfatal == FATAL_IF_SANITY_CHECK_FAILS) ? 1 : 0,
961 0, /* no relevant errno value */
962 _("%s%s changed during execution of %s (old inode number %ld, new inode number %ld, filesystem type is %s) [ref %ld]"),
963 specific_what,
964 parent ? "/.." : "",
965 progname,
966 (long) old_ino,
967 (long) newinfo->st_ino,
968 fstype,
969 line_no);
970 free(specific_what);
971 return false;
974 return true;
977 enum SafeChdirStatus
979 SafeChdirOK,
980 SafeChdirFailSymlink,
981 SafeChdirFailNotDir,
982 SafeChdirFailStat,
983 SafeChdirFailWouldBeUnableToReturn,
984 SafeChdirFailChdirFailed,
985 SafeChdirFailNonexistent
988 /* Safely perform a change in directory. We do this by calling
989 * lstat() on the subdirectory, using chdir() to move into it, and
990 * then lstat()ing ".". We compare the results of the two stat calls
991 * to see if they are consistent. If not, we sound the alarm.
993 * If following_links() is true, we do follow symbolic links.
995 static enum SafeChdirStatus
996 safely_chdir_lstat(const char *dest,
997 enum TraversalDirection direction,
998 struct stat *statbuf_dest,
999 enum ChdirSymlinkHandling symlink_follow_option,
1000 boolean *did_stat)
1002 struct stat statbuf_arrived;
1003 int rv, dotfd=-1;
1004 int saved_errno; /* specific_dirname() changes errno. */
1005 boolean rv_set = false;
1006 boolean statflag = false;
1007 int tries = 0;
1008 enum WdSanityCheckFatality isfatal = RETRY_IF_SANITY_CHECK_FAILS;
1010 saved_errno = errno = 0;
1012 dotfd = open(".", O_RDONLY);
1014 /* We jump back to here if wd_sanity_check()
1015 * recoverably triggers an alert.
1017 retry:
1018 ++tries;
1020 if (dotfd >= 0)
1022 /* Stat the directory we're going to. */
1023 if (0 == options.xstat(dest, statbuf_dest))
1025 statflag = true;
1027 #ifdef S_ISLNK
1028 /* symlink_follow_option might be set to SymlinkFollowOk, which
1029 * would allow us to chdir() into a symbolic link. This is
1030 * only useful for the case where the directory we're
1031 * chdir()ing into is the basename of a command line
1032 * argument, for example where "foo/bar/baz" is specified on
1033 * the command line. When -P is in effect (the default),
1034 * baz will not be followed if it is a symlink, but if bar
1035 * is a symlink, it _should_ be followed. Hence we need the
1036 * ability to override the policy set by following_links().
1038 if (!following_links() && S_ISLNK(statbuf_dest->st_mode))
1040 /* We're not supposed to be following links, but this is
1041 * a link. Check symlink_follow_option to see if we should
1042 * make a special exception.
1044 if (symlink_follow_option == SymlinkFollowOk)
1046 /* We need to re-stat() the file so that the
1047 * sanity check can pass.
1049 if (0 != stat(dest, statbuf_dest))
1051 rv = SafeChdirFailNonexistent;
1052 rv_set = true;
1053 saved_errno = errno;
1054 goto fail;
1056 statflag = true;
1058 else
1060 /* Not following symlinks, so the attempt to
1061 * chdir() into a symlink should be prevented.
1063 rv = SafeChdirFailSymlink;
1064 rv_set = true;
1065 saved_errno = 0; /* silence the error message */
1066 goto fail;
1069 #endif
1070 #ifdef S_ISDIR
1071 /* Although the immediately following chdir() would detect
1072 * the fact that this is not a directory for us, this would
1073 * result in an extra system call that fails. Anybody
1074 * examining the system-call trace should ideally not be
1075 * concerned that something is actually failing.
1077 if (!S_ISDIR(statbuf_dest->st_mode))
1079 rv = SafeChdirFailNotDir;
1080 rv_set = true;
1081 saved_errno = 0; /* silence the error message */
1082 goto fail;
1084 #endif
1085 #ifdef DEBUG_STAT
1086 fprintf(stderr, "safely_chdir(): chdir(\"%s\")\n", dest);
1087 #endif
1088 if (0 == chdir(dest))
1090 /* check we ended up where we wanted to go */
1091 boolean changed = false;
1092 if (!wd_sanity_check(".", program_name, ".",
1093 statbuf_dest->st_dev,
1094 statbuf_dest->st_ino,
1095 &statbuf_arrived,
1096 0, __LINE__, direction,
1097 isfatal,
1098 &changed))
1100 /* Only allow one failure. */
1101 if (RETRY_IF_SANITY_CHECK_FAILS == isfatal)
1103 if (0 == fchdir(dotfd))
1105 isfatal = FATAL_IF_SANITY_CHECK_FAILS;
1106 goto retry;
1108 else
1110 /* Failed to return to original directory,
1111 * but we know that the current working
1112 * directory is not the one that we intend
1113 * to be in. Since fchdir() failed, we
1114 * can't recover from this and so this error
1115 * is fatal.
1117 error(1, errno,
1118 "failed to return to parent directory");
1121 else
1123 /* XXX: not sure what to use as an excuse here. */
1124 rv = SafeChdirFailNonexistent;
1125 rv_set = true;
1126 saved_errno = 0;
1127 goto fail;
1131 close(dotfd);
1132 return SafeChdirOK;
1134 else
1136 saved_errno = errno;
1137 if (ENOENT == saved_errno)
1139 rv = SafeChdirFailNonexistent;
1140 rv_set = true;
1141 if (options.ignore_readdir_race)
1142 errno = 0; /* don't issue err msg */
1144 else if (ENOTDIR == saved_errno)
1146 /* This can happen if the we stat a directory,
1147 * and then filesystem activity changes it into
1148 * a non-directory.
1150 saved_errno = 0; /* don't issue err msg */
1151 rv = SafeChdirFailNotDir;
1152 rv_set = true;
1154 else
1156 rv = SafeChdirFailChdirFailed;
1157 rv_set = true;
1159 goto fail;
1162 else
1164 saved_errno = errno;
1165 rv = SafeChdirFailStat;
1166 rv_set = true;
1168 if ( (ENOENT == saved_errno) || (0 == state.curdepth))
1169 saved_errno = 0; /* don't issue err msg */
1170 goto fail;
1173 else
1175 /* We do not have read permissions on "." */
1176 rv = SafeChdirFailWouldBeUnableToReturn;
1177 rv_set = true;
1178 goto fail;
1181 /* This is the success path, so we clear errno. The caller probably
1182 * won't be calling error() anyway.
1184 saved_errno = 0;
1186 /* We use the same exit path for success or failure.
1187 * which has occurred is recorded in RV.
1189 fail:
1190 /* We do not call error() as this would result in a duplicate error
1191 * message when the caller does the same thing.
1193 if (saved_errno)
1194 errno = saved_errno;
1196 if (dotfd >= 0)
1198 close(dotfd);
1199 dotfd = -1;
1202 *did_stat = statflag;
1203 assert(rv_set);
1204 return rv;
1207 #if defined(O_NOFOLLOW)
1208 /* Safely change working directory to the specified subdirectory. If
1209 * we are not allowed to follow symbolic links, we use open() with
1210 * O_NOFOLLOW, followed by fchdir(). This ensures that we don't
1211 * follow symbolic links (of course, we do follow them if the -L
1212 * option is in effect).
1214 static enum SafeChdirStatus
1215 safely_chdir_nofollow(const char *dest,
1216 enum TraversalDirection direction,
1217 struct stat *statbuf_dest,
1218 enum ChdirSymlinkHandling symlink_follow_option,
1219 boolean *did_stat)
1221 int extraflags, fd;
1222 extraflags = 0;
1224 *did_stat = false;
1226 switch (symlink_follow_option)
1228 case SymlinkFollowOk:
1229 extraflags = 0;
1230 break;
1232 case SymlinkHandleDefault:
1233 if (following_links())
1234 extraflags = 0;
1235 else
1236 extraflags = O_NOFOLLOW;
1237 break;
1240 errno = 0;
1241 fd = open(dest, O_RDONLY|extraflags);
1242 if (fd < 0)
1244 switch (errno)
1246 case ELOOP:
1247 return SafeChdirFailSymlink; /* This is why we use O_NOFOLLOW */
1248 case ENOENT:
1249 return SafeChdirFailNonexistent;
1250 default:
1251 return SafeChdirFailChdirFailed;
1255 errno = 0;
1256 if (0 == fchdir(fd))
1258 close(fd);
1259 return SafeChdirOK;
1261 else
1263 int saved_errno = errno;
1264 close(fd);
1265 errno = saved_errno;
1267 switch (errno)
1269 case ENOTDIR:
1270 return SafeChdirFailNotDir;
1272 case EACCES:
1273 case EBADF: /* Shouldn't happen */
1274 case EINTR:
1275 case EIO:
1276 default:
1277 return SafeChdirFailChdirFailed;
1281 #endif
1283 static enum SafeChdirStatus
1284 safely_chdir(const char *dest,
1285 enum TraversalDirection direction,
1286 struct stat *statbuf_dest,
1287 enum ChdirSymlinkHandling symlink_follow_option,
1288 boolean *did_stat)
1290 /* We're about to leave a directory. If there are any -execdir
1291 * argument lists which have been built but have not yet been
1292 * processed, do them now because they must be done in the same
1293 * directory.
1295 complete_pending_execdirs(eval_tree);
1297 #if defined(O_NOFOLLOW)
1298 if (options.open_nofollow_available)
1299 return safely_chdir_nofollow(dest, direction, statbuf_dest, symlink_follow_option, did_stat);
1300 #endif
1301 return safely_chdir_lstat(dest, direction, statbuf_dest, symlink_follow_option, did_stat);
1306 /* Safely go back to the starting directory. */
1307 static void
1308 chdir_back (void)
1310 struct stat stat_buf;
1311 boolean dummy;
1313 if (starting_desc < 0)
1315 #ifdef DEBUG_STAT
1316 fprintf(stderr, "chdir_back(): chdir(\"%s\")\n", starting_dir);
1317 #endif
1319 #ifdef STAT_MOUNTPOINTS
1320 /* We will need the mounted device list. Get it now if we don't
1321 * already have it.
1323 if (NULL == mounted_devices)
1324 init_mounted_dev_list();
1325 #endif
1327 if (chdir (starting_dir) != 0)
1328 error (1, errno, "%s", starting_dir);
1330 wd_sanity_check(starting_dir,
1331 program_name,
1332 starting_dir,
1333 starting_stat_buf.st_dev,
1334 starting_stat_buf.st_ino,
1335 &stat_buf, 0, __LINE__,
1336 TraversingUp,
1337 FATAL_IF_SANITY_CHECK_FAILS,
1338 &dummy);
1340 else
1342 #ifdef DEBUG_STAT
1343 fprintf(stderr, "chdir_back(): chdir(<starting-point>)\n");
1344 #endif
1345 if (fchdir (starting_desc) != 0)
1346 error (1, errno, "%s", starting_dir);
1350 /* Move to the parent of a given directory and then call a function,
1351 * restoring the cwd. Don't bother changing directory if the
1352 * specified directory is a child of "." or is the root directory.
1354 static void
1355 at_top (char *pathname,
1356 mode_t mode,
1357 struct stat *pstat,
1358 void (*action)(char *pathname,
1359 char *basename,
1360 int mode,
1361 struct stat *pstat))
1363 int dirchange;
1364 char *parent_dir = dir_name(pathname);
1365 char *base = base_name(pathname);
1367 state.curdepth = 0;
1368 state.path_length = strlen (pathname);
1370 if (0 == strcmp(pathname, parent_dir)
1371 || 0 == strcmp(parent_dir, "."))
1373 dirchange = 0;
1374 base = pathname;
1376 else
1378 enum TraversalDirection direction;
1379 enum SafeChdirStatus chdir_status;
1380 struct stat st;
1381 boolean did_stat = false;
1383 dirchange = 1;
1384 if (0 == strcmp(base, ".."))
1385 direction = TraversingUp;
1386 else
1387 direction = TraversingDown;
1389 /* We pass SymlinkFollowOk to safely_chdir(), which allows it to
1390 * chdir() into a symbolic link. This is only useful for the
1391 * case where the directory we're chdir()ing into is the
1392 * basename of a command line argument, for example where
1393 * "foo/bar/baz" is specified on the command line. When -P is
1394 * in effect (the default), baz will not be followed if it is a
1395 * symlink, but if bar is a symlink, it _should_ be followed.
1396 * Hence we need the ability to override the policy set by
1397 * following_links().
1399 chdir_status = safely_chdir(parent_dir, direction, &st, SymlinkFollowOk, &did_stat);
1400 if (SafeChdirOK != chdir_status)
1402 const char *what = (SafeChdirFailWouldBeUnableToReturn == chdir_status) ? "." : parent_dir;
1403 if (errno)
1404 error (0, errno, "%s", what);
1405 else
1406 error (0, 0, "Failed to safely change directory into `%s'",
1407 parent_dir);
1409 /* We can't process this command-line argument. */
1410 state.exit_status = 1;
1411 return;
1415 free (parent_dir);
1416 parent_dir = NULL;
1418 action(pathname, base, mode, pstat);
1420 if (dirchange)
1422 chdir_back();
1427 static void do_process_top_dir(char *pathname,
1428 char *base,
1429 int mode,
1430 struct stat *pstat)
1432 process_path (pathname, base, false, ".", mode);
1433 complete_pending_execdirs(eval_tree);
1436 static void do_process_predicate(char *pathname,
1437 char *base,
1438 int mode,
1439 struct stat *pstat)
1441 state.rel_pathname = base;
1442 apply_predicate (pathname, pstat, eval_tree);
1448 /* Descend PATHNAME, which is a command-line argument.
1450 Actions like -execdir assume that we are in the
1451 parent directory of the file we're examining,
1452 and on entry to this function our working directory
1453 is whatever it was when find was invoked. Therefore
1454 If PATHNAME is "." we just leave things as they are.
1455 Otherwise, we figure out what the parent directory is,
1456 and move to that.
1458 static void
1459 process_top_path (char *pathname, mode_t mode)
1461 at_top(pathname, mode, NULL, do_process_top_dir);
1465 /* Info on each directory in the current tree branch, to avoid
1466 getting stuck in symbolic link loops. */
1467 static struct dir_id *dir_ids = NULL;
1468 /* Entries allocated in `dir_ids'. */
1469 static int dir_alloc = 0;
1470 /* Index in `dir_ids' of directory currently being searched.
1471 This is always the last valid entry. */
1472 static int dir_curr = -1;
1473 /* (Arbitrary) number of entries to grow `dir_ids' by. */
1474 #define DIR_ALLOC_STEP 32
1478 /* We've detected a filesystem loop. This is caused by one of
1479 * two things:
1481 * 1. Option -L is in effect and we've hit a symbolic link that
1482 * points to an ancestor. This is harmless. We won't traverse the
1483 * symbolic link.
1485 * 2. We have hit a real cycle in the directory hierarchy. In this
1486 * case, we issue a diagnostic message (POSIX requires this) and we
1487 * skip that directory entry.
1489 static void
1490 issue_loop_warning(const char *name, const char *pathname, int level)
1492 struct stat stbuf_link;
1493 if (lstat(name, &stbuf_link) != 0)
1494 stbuf_link.st_mode = S_IFREG;
1496 if (S_ISLNK(stbuf_link.st_mode))
1498 error(0, 0,
1499 _("Symbolic link `%s' is part of a loop in the directory hierarchy; we have already visited the directory to which it points."),
1500 pathname);
1502 else
1504 int distance = 1 + (dir_curr-level);
1505 /* We have found an infinite loop. POSIX requires us to
1506 * issue a diagnostic. Usually we won't get to here
1507 * because when the leaf optimisation is on, it will cause
1508 * the subdirectory to be skipped. If /a/b/c/d is a hard
1509 * link to /a/b, then the link count of /a/b/c is 2,
1510 * because the ".." entry of /b/b/c/d points to /a, not
1511 * to /a/b/c.
1513 error(0, 0,
1514 _("Filesystem loop detected; `%s' has the same device number and inode as a directory which is %d %s."),
1515 pathname,
1516 distance,
1517 (distance == 1 ?
1518 _("level higher in the filesystem hierarchy") :
1519 _("levels higher in the filesystem hierarchy")));
1523 /* Take a "mode" indicator and fill in the files of 'state'.
1525 static int
1526 digest_mode(mode_t mode,
1527 const char *pathname,
1528 const char *name,
1529 struct stat *pstat,
1530 boolean leaf)
1532 /* If we know the type of the directory entry, and it is not a
1533 * symbolic link, we may be able to avoid a stat() or lstat() call.
1535 if (mode)
1537 if (S_ISLNK(mode) && following_links())
1539 /* mode is wrong because we should have followed the symlink. */
1540 if (get_statinfo(pathname, name, pstat) != 0)
1541 return 0;
1542 mode = state.type = pstat->st_mode;
1543 state.have_type = true;
1545 else
1547 state.have_type = true;
1548 pstat->st_mode = state.type = mode;
1551 else
1553 /* Mode is not yet known; may have to stat the file unless we
1554 * can deduce that it is not a directory (which is all we need to
1555 * know at this stage)
1557 if (leaf)
1559 state.have_stat = false;
1560 state.have_type = false;;
1561 state.type = 0;
1563 else
1565 if (get_statinfo(pathname, name, pstat) != 0)
1566 return 0;
1568 /* If -L is in effect and we are dealing with a symlink,
1569 * st_mode is the mode of the pointed-to file, while mode is
1570 * the mode of the directory entry (S_IFLNK). Hence now
1571 * that we have the stat information, override "mode".
1573 state.type = pstat->st_mode;
1574 state.have_type = true;
1578 /* success. */
1579 return 1;
1584 /* Recursively descend path PATHNAME, applying the predicates.
1585 LEAF is true if PATHNAME is known to be in a directory that has no
1586 more unexamined subdirectories, and therefore it is not a directory.
1587 Knowing this allows us to avoid calling stat as long as possible for
1588 leaf files.
1590 NAME is PATHNAME relative to the current directory. We access NAME
1591 but print PATHNAME.
1593 PARENT is the path of the parent of NAME, relative to find's
1594 starting directory.
1596 Return nonzero iff PATHNAME is a directory. */
1598 static int
1599 process_path (char *pathname, char *name, boolean leaf, char *parent,
1600 mode_t mode)
1602 struct stat stat_buf;
1603 static dev_t root_dev; /* Device ID of current argument pathname. */
1604 int i;
1606 /* Assume it is a non-directory initially. */
1607 stat_buf.st_mode = 0;
1608 state.rel_pathname = name;
1609 state.type = 0;
1610 state.have_stat = false;
1611 state.have_type = false;
1613 if (!digest_mode(mode, pathname, name, &stat_buf, leaf))
1614 return 0;
1616 if (!S_ISDIR (state.type))
1618 if (state.curdepth >= options.mindepth)
1619 apply_predicate (pathname, &stat_buf, eval_tree);
1620 return 0;
1623 /* From here on, we're working on a directory. */
1626 /* Now we really need to stat the directory, even if we know the
1627 * type, because we need information like struct stat.st_rdev.
1629 if (get_statinfo(pathname, name, &stat_buf) != 0)
1630 return 0;
1632 state.have_stat = true;
1633 mode = state.type = stat_buf.st_mode; /* use full info now that we have it. */
1634 state.stop_at_current_level =
1635 options.maxdepth >= 0
1636 && state.curdepth >= options.maxdepth;
1638 /* If we've already seen this directory on this branch,
1639 don't descend it again. */
1640 for (i = 0; i <= dir_curr; i++)
1641 if (stat_buf.st_ino == dir_ids[i].ino &&
1642 stat_buf.st_dev == dir_ids[i].dev)
1644 state.stop_at_current_level = true;
1645 issue_loop_warning(name, pathname, i);
1648 if (dir_alloc <= ++dir_curr)
1650 dir_alloc += DIR_ALLOC_STEP;
1651 dir_ids = (struct dir_id *)
1652 xrealloc ((char *) dir_ids, dir_alloc * sizeof (struct dir_id));
1654 dir_ids[dir_curr].ino = stat_buf.st_ino;
1655 dir_ids[dir_curr].dev = stat_buf.st_dev;
1657 if (options.stay_on_filesystem)
1659 if (state.curdepth == 0)
1660 root_dev = stat_buf.st_dev;
1661 else if (stat_buf.st_dev != root_dev)
1662 state.stop_at_current_level = true;
1665 if (options.do_dir_first && state.curdepth >= options.mindepth)
1666 apply_predicate (pathname, &stat_buf, eval_tree);
1668 #ifdef DEBUG
1669 fprintf(stderr, "pathname = %s, stop_at_current_level = %d\n",
1670 pathname, state.stop_at_current_level);
1671 #endif /* DEBUG */
1673 if (state.stop_at_current_level == false)
1674 /* Scan directory on disk. */
1675 process_dir (pathname, name, strlen (pathname), &stat_buf, parent);
1677 if (options.do_dir_first == false && state.curdepth >= options.mindepth)
1679 /* The fields in 'state' are now out of date. Correct them.
1681 if (!digest_mode(mode, pathname, name, &stat_buf, leaf))
1682 return 0;
1684 if (0 == dir_curr)
1686 at_top(pathname, mode, &stat_buf, do_process_predicate);
1688 else
1690 do_process_predicate(pathname, name, mode, &stat_buf);
1694 dir_curr--;
1696 return 1;
1699 /* Examine the predicate list for instances of -execdir or -okdir
1700 * which have been terminated with '+' (build argument list) rather
1701 * than ';' (singles only). If there are any, run them (this will
1702 * have no effect if there are no arguments waiting).
1704 static void
1705 complete_pending_execdirs(struct predicate *p)
1707 #if defined(NEW_EXEC)
1708 if (NULL == p)
1709 return;
1711 complete_pending_execdirs(p->pred_left);
1713 if (p->pred_func == pred_execdir || p->pred_func == pred_okdir)
1715 /* It's an exec-family predicate. p->args.exec_val is valid. */
1716 if (p->args.exec_vec.multiple)
1718 struct exec_val *execp = &p->args.exec_vec;
1720 /* This one was terminated by '+' and so might have some
1721 * left... Run it if necessary.
1723 if (execp->state.todo)
1725 /* There are not-yet-executed arguments. */
1726 launch (&execp->ctl, &execp->state);
1731 complete_pending_execdirs(p->pred_right);
1732 #else
1733 /* nothing to do. */
1734 return;
1735 #endif
1738 /* Examine the predicate list for instances of -exec which have been
1739 * terminated with '+' (build argument list) rather than ';' (singles
1740 * only). If there are any, run them (this will have no effect if
1741 * there are no arguments waiting).
1743 static void
1744 complete_pending_execs(struct predicate *p)
1746 #if defined(NEW_EXEC)
1747 if (NULL == p)
1748 return;
1750 complete_pending_execs(p->pred_left);
1752 /* It's an exec-family predicate then p->args.exec_val is valid
1753 * and we can check it.
1755 if (p->pred_func == pred_exec && p->args.exec_vec.multiple)
1757 struct exec_val *execp = &p->args.exec_vec;
1759 /* This one was terminated by '+' and so might have some
1760 * left... Run it if necessary. Set state.exit_status if
1761 * there are any problems.
1763 if (execp->state.todo)
1765 /* There are not-yet-executed arguments. */
1766 launch (&execp->ctl, &execp->state);
1770 complete_pending_execs(p->pred_right);
1771 #else
1772 /* nothing to do. */
1773 return;
1774 #endif
1778 /* Scan directory PATHNAME and recurse through process_path for each entry.
1780 PATHLEN is the length of PATHNAME.
1782 NAME is PATHNAME relative to the current directory.
1784 STATP is the results of *options.xstat on it.
1786 PARENT is the path of the parent of NAME, relative to find's
1787 starting directory. */
1789 static void
1790 process_dir (char *pathname, char *name, int pathlen, struct stat *statp, char *parent)
1792 int subdirs_left; /* Number of unexamined subdirs in PATHNAME. */
1793 int idx; /* Which entry are we on? */
1794 struct stat stat_buf;
1796 #undef USE_OLD_SAVEDIR
1798 #if USE_OLD_SAVEDIR
1799 char *name_space; /* Names of files in PATHNAME. */
1800 struct savedir_extrainfo *extra;
1801 #else
1802 struct savedir_dirinfo *dirinfo;
1803 #endif
1804 subdirs_left = statp->st_nlink - 2; /* Account for name and ".". */
1806 errno = 0;
1807 #if USE_OLD_SAVEDIR
1808 name_space = savedirinfo (name, &extra);
1809 #else
1810 dirinfo = xsavedir(name, 0);
1811 #endif
1813 if (
1814 #if USE_OLD_SAVEDIR
1815 name_space
1816 #else
1817 dirinfo
1818 #endif
1819 == NULL)
1821 assert(errno != 0);
1822 error (0, errno, "%s", pathname);
1823 state.exit_status = 1;
1825 else
1827 register char *namep; /* Current point in `name_space'. */
1828 char *cur_path; /* Full path of each file to process. */
1829 char *cur_name; /* Base name of each file to process. */
1830 unsigned cur_path_size; /* Bytes allocated for `cur_path'. */
1831 register unsigned file_len; /* Length of each path to process. */
1832 register unsigned pathname_len; /* PATHLEN plus trailing '/'. */
1833 boolean did_stat = false;
1835 if (pathname[pathlen - 1] == '/')
1836 pathname_len = pathlen + 1; /* For '\0'; already have '/'. */
1837 else
1838 pathname_len = pathlen + 2; /* For '/' and '\0'. */
1839 cur_path_size = 0;
1840 cur_path = NULL;
1842 /* We're about to leave the directory. If there are any
1843 * -execdir argument lists which have been built but have not
1844 * yet been processed, do them now because they must be done in
1845 * the same directory.
1847 complete_pending_execdirs(eval_tree);
1849 if (strcmp (name, "."))
1851 enum SafeChdirStatus status = safely_chdir (name, TraversingDown, &stat_buf, SymlinkHandleDefault, &did_stat);
1852 switch (status)
1854 case SafeChdirOK:
1855 /* If there had been a change but wd_sanity_check()
1856 * accepted it, we need to accept that on the
1857 * way back up as well, so modify our record
1858 * of what we think we should see later.
1859 * If there was no change, the assignments are a no-op.
1861 * However, before performing the assignment, we need to
1862 * check that we have the stat information. If O_NOFOLLOW
1863 * is available, safely_chdir() will not have needed to use
1864 * stat(), and so stat_buf will just contain random data.
1866 if (!did_stat)
1868 /* If there is a link we need to follow it. Hence
1869 * the direct call to stat() not through (options.xstat)
1871 if (0 != stat(".", &stat_buf))
1872 break; /* skip the assignment. */
1874 dir_ids[dir_curr].dev = stat_buf.st_dev;
1875 dir_ids[dir_curr].ino = stat_buf.st_ino;
1877 break;
1879 case SafeChdirFailWouldBeUnableToReturn:
1880 error (0, errno, ".");
1881 state.exit_status = 1;
1882 break;
1884 case SafeChdirFailNonexistent:
1885 case SafeChdirFailStat:
1886 case SafeChdirFailSymlink:
1887 case SafeChdirFailNotDir:
1888 case SafeChdirFailChdirFailed:
1889 error (0, errno, "%s", pathname);
1890 state.exit_status = 1;
1891 return;
1895 #if USE_OLD_SAVEDIR
1896 for (idx=0, namep = name_space; *namep; namep += file_len - pathname_len + 1, ++idx)
1897 #else
1898 for (idx=0; idx < dirinfo->size; ++idx)
1899 #endif
1901 /* savedirinfo() may return dirinfo=NULL if extended information
1902 * is not available.
1904 #if USE_OLD_SAVEDIR
1905 mode_t mode = extra ? extra[idx].type_info : 0;
1906 #else
1907 mode_t mode = (dirinfo->entries[idx].flags & SavedirHaveFileType) ?
1908 dirinfo->entries[idx].type_info : 0;
1909 namep = dirinfo->entries[idx].name;
1910 #endif
1911 /* Append this directory entry's name to the path being searched. */
1912 file_len = pathname_len + strlen (namep);
1913 if (file_len > cur_path_size)
1915 while (file_len > cur_path_size)
1916 cur_path_size += 1024;
1917 if (cur_path)
1918 free (cur_path);
1919 cur_path = xmalloc (cur_path_size);
1920 strcpy (cur_path, pathname);
1921 cur_path[pathname_len - 2] = '/';
1923 cur_name = cur_path + pathname_len - 1;
1924 strcpy (cur_name, namep);
1926 state.curdepth++;
1927 if (!options.no_leaf_check)
1929 if (mode && S_ISDIR(mode) && (subdirs_left == 0))
1931 /* This is a subdirectory, but the number of directories we
1932 * have found now exceeds the number we would expect given
1933 * the hard link count on the parent. This is likely to be
1934 * a bug in the filesystem driver (e.g. Linux's
1935 * /proc filesystem) or may just be a fact that the OS
1936 * doesn't really handle hard links with Unix semantics.
1937 * In the latter case, -noleaf should be used routinely.
1939 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."),
1940 parent);
1941 state.exit_status = 1; /* We know the result is wrong, now */
1942 options.no_leaf_check = true; /* Don't make same
1943 mistake again */
1944 subdirs_left = 1; /* band-aid for this iteration. */
1947 /* Normal case optimization. On normal Unix
1948 filesystems, a directory that has no subdirectories
1949 has two links: its name, and ".". Any additional
1950 links are to the ".." entries of its subdirectories.
1951 Once we have processed as many subdirectories as
1952 there are additional links, we know that the rest of
1953 the entries are non-directories -- in other words,
1954 leaf files. */
1955 subdirs_left -= process_path (cur_path, cur_name,
1956 subdirs_left == 0, pathname,
1957 mode);
1959 else
1961 /* There might be weird (e.g., CD-ROM or MS-DOS) filesystems
1962 mounted, which don't have Unix-like directory link counts. */
1963 process_path (cur_path, cur_name, false, pathname, mode);
1966 state.curdepth--;
1970 /* We're about to leave the directory. If there are any
1971 * -execdir argument lists which have been built but have not
1972 * yet been processed, do them now because they must be done in
1973 * the same directory.
1975 complete_pending_execdirs(eval_tree);
1978 if (strcmp (name, "."))
1980 enum SafeChdirStatus status;
1981 struct dir_id did;
1982 boolean did_stat = false;
1984 /* We could go back and do the next command-line arg
1985 instead, maybe using longjmp. */
1986 char const *dir;
1987 boolean deref = following_links() ? true : false;
1989 if ( (state.curdepth>0) && !deref)
1990 dir = "..";
1991 else
1993 chdir_back ();
1994 dir = parent;
1997 status = safely_chdir (dir, TraversingUp, &stat_buf, SymlinkHandleDefault, &did_stat);
1998 switch (status)
2000 case SafeChdirOK:
2001 break;
2003 case SafeChdirFailWouldBeUnableToReturn:
2004 error (1, errno, ".");
2005 return;
2007 case SafeChdirFailNonexistent:
2008 case SafeChdirFailStat:
2009 case SafeChdirFailSymlink:
2010 case SafeChdirFailNotDir:
2011 case SafeChdirFailChdirFailed:
2012 error (1, errno, "%s", pathname);
2013 return;
2016 if (dir_curr > 0)
2018 did.dev = dir_ids[dir_curr-1].dev;
2019 did.ino = dir_ids[dir_curr-1].ino;
2021 else
2023 did.dev = starting_stat_buf.st_dev;
2024 did.ino = starting_stat_buf.st_ino;
2028 if (cur_path)
2029 free (cur_path);
2030 #ifdef USE_OLD_SAVEDIR
2031 free (name_space);
2032 free (extra);
2033 #else
2034 free_dirinfo(dirinfo);
2035 #endif
2039 /* Return true if there are no predicates with no_default_print in
2040 predicate list PRED, false if there are any.
2041 Returns true if default print should be performed */
2043 static boolean
2044 default_prints (struct predicate *pred)
2046 while (pred != NULL)
2048 if (pred->no_default_print)
2049 return (false);
2050 pred = pred->pred_next;
2052 return (true);