1 /* find -- search for files in a directory hierarchy (fts version)
2 Copyright (C) 1990, 91, 92, 93, 94, 2000,
3 2003, 2004, 2005 Free Software Foundation, Inc.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2, or (at your option)
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 /* GNU find was written by Eric Decker <cire@cisco.com>,
21 with enhancements by David MacKenzie <djm@gnu.org>,
22 Jay Plett <jay@silence.princeton.nj.us>,
23 and Tim Wood <axolotl!tim@toad.com>.
24 The idea for -print0 and xargs -0 came from
25 Dan Bernstein <brnstnd@kramden.acf.nyu.edu>.
26 Improvements have been made by James Youngman <jay@gnu.org>.
33 #define USE_SAFE_CHDIR 1
34 #undef STAT_MOUNTPOINTS
47 #include "../gnulib/lib/xalloc.h"
60 # define _(Text) gettext (Text)
63 #define textdomain(Domain)
64 #define bindtextdomain(Package, Directory)
67 # define N_(String) gettext_noop (String)
69 /* See locate.c for explanation as to why not use (String) */
70 # define N_(String) String
74 #ifdef STAT_MOUNTPOINTS
75 static void init_mounted_dev_list(void);
78 /* We have encountered an error which shoudl affect the exit status.
79 * This is normally used to change the exit status from 0 to 1.
80 * However, if the exit status is already 2 for example, we don't want to
84 error_severity(int level
)
86 if (state
.exit_status
< level
)
87 state
.exit_status
= level
;
91 #define STRINGIFY(X) #X
92 #define HANDLECASE(N) case N: return #N;
95 get_fts_info_name(int info
)
102 HANDLECASE(FTS_DEFAULT
);
108 HANDLECASE(FTS_INIT
);
110 HANDLECASE(FTS_NSOK
);
112 HANDLECASE(FTS_SLNONE
);
115 sprintf(buf
, "[%d]", info
);
123 visit(FTS
*p
, FTSENT
*ent
, struct stat
*pstat
)
125 state
.curdepth
= ent
->fts_level
;
126 state
.have_stat
= (ent
->fts_info
!= FTS_NS
) && (ent
->fts_info
!= FTS_NSOK
);
127 state
.rel_pathname
= ent
->fts_accpath
;
129 /* Apply the predicates to this path. */
130 (*(eval_tree
)->pred_func
)(ent
->fts_path
, pstat
, eval_tree
);
132 /* Deal with any side effects of applying the predicates. */
133 if (state
.stop_at_current_level
)
135 fts_set(p
, ent
, FTS_SKIP
);
140 partial_quotearg_n(int n
, char *s
, size_t len
, enum quoting_style style
)
144 return quotearg_n_style(n
, style
, "");
153 result
= quotearg_n_style(n
, style
, s
);
160 /* We've detected a filesystem loop. This is caused by one of
163 * 1. Option -L is in effect and we've hit a symbolic link that
164 * points to an ancestor. This is harmless. We won't traverse the
167 * 2. We have hit a real cycle in the directory hierarchy. In this
168 * case, we issue a diagnostic message (POSIX requires this) and we
169 * skip that directory entry.
172 issue_loop_warning(FTSENT
* ent
)
174 if (S_ISLNK(ent
->fts_statp
->st_mode
))
177 _("Symbolic link %s is part of a loop in the directory hierarchy; we have already visited the directory to which it points."),
178 quotearg_n_style(0, locale_quoting_style
, ent
->fts_path
));
182 /* We have found an infinite loop. POSIX requires us to
183 * issue a diagnostic. Usually we won't get to here
184 * because when the leaf optimisation is on, it will cause
185 * the subdirectory to be skipped. If /a/b/c/d is a hard
186 * link to /a/b, then the link count of /a/b/c is 2,
187 * because the ".." entry of /b/b/c/d points to /a, not
191 _("Filesystem loop detected; "
192 "%s is part of the same filesystem loop as %s."),
193 quotearg_n_style(0, locale_quoting_style
, ent
->fts_path
),
194 partial_quotearg_n(1,
195 ent
->fts_cycle
->fts_path
,
196 ent
->fts_cycle
->fts_pathlen
,
197 locale_quoting_style
));
202 * Return true if NAME corresponds to a file which forms part of a
203 * symbolic link loop. The command
204 * rm -f a b; ln -s a b; ln -s b a
205 * produces such a loop.
208 symlink_loop(const char *name
)
212 if (following_links())
213 rv
= stat(name
, &stbuf
);
215 rv
= lstat(name
, &stbuf
);
216 return (0 != rv
) && (ELOOP
== errno
);
221 consider_visiting(FTS
*p
, FTSENT
*ent
)
228 "consider_visiting: end->fts_info=%s, ent->fts_path=%s\n",
229 get_fts_info_name(ent
->fts_info
),
230 quotearg_n(0, ent
->fts_path
, locale_quoting_style
));
233 /* Cope with various error conditions. */
234 if (ent
->fts_info
== FTS_ERR
235 || ent
->fts_info
== FTS_NS
236 || ent
->fts_info
== FTS_DNR
)
238 error(0, ent
->fts_errno
, ent
->fts_path
);
242 else if (ent
->fts_info
== FTS_DC
)
244 issue_loop_warning(ent
);
248 else if (ent
->fts_info
== FTS_SLNONE
)
250 /* fts_read() claims that ent->fts_accpath is a broken symbolic
251 * link. That would be fine, but if this is part of a symbolic
252 * link loop, we diagnose the problem and also ensure that the
253 * eventual return value is nonzero. Note that while the path
254 * we stat is local (fts_accpath), we print the fill path name
255 * of the file (fts_path) in the error message.
257 if (symlink_loop(ent
->fts_accpath
))
259 error(0, ELOOP
, ent
->fts_path
);
265 /* Not an error, cope with the usual cases. */
266 if (ent
->fts_info
== FTS_NSOK
)
268 state
.have_stat
= false;
273 state
.have_stat
= true;
274 statbuf
= *(ent
->fts_statp
);
275 mode
= statbuf
.st_mode
;
278 if (0 == ent
->fts_level
&& (0u == state
.starting_path_length
))
279 state
.starting_path_length
= ent
->fts_pathlen
;
281 if (0 != digest_mode(mode
, ent
->fts_path
, ent
->fts_name
, &statbuf
, 0))
283 /* examine this item. */
286 if (S_ISDIR(statbuf
.st_mode
) && (ent
->fts_info
== FTS_NSOK
))
288 /* This is a directory, but fts did not stat it, so
289 * presumably would not be planning to search its
290 * children. Force a stat of the file so that the
291 * children can be checked.
293 fts_set(p
, ent
, FTS_AGAIN
);
297 if (options
.maxdepth
>= 0 && (ent
->fts_level
> options
.maxdepth
))
300 fts_set(p
, ent
, FTS_SKIP
);
302 else if ( (ent
->fts_info
== FTS_D
) && !options
.do_dir_first
)
304 /* this is the preorder visit, but user said -depth */
307 else if ( (ent
->fts_info
== FTS_DP
) && options
.do_dir_first
)
309 /* this is the postorder visit, but user didn't say -depth */
312 else if (ent
->fts_level
< options
.mindepth
)
319 visit(p
, ent
, &statbuf
);
323 if (ent
->fts_info
== FTS_DP
)
325 /* we're leaving a directory. */
326 state
.stop_at_current_level
= false;
327 complete_pending_execdirs(eval_tree
);
345 ftsoptions
= FTS_NOSTAT
;
346 switch (options
.symlink_handling
)
348 case SYMLINK_ALWAYS_DEREF
:
349 ftsoptions
|= FTS_COMFOLLOW
|FTS_LOGICAL
;
352 case SYMLINK_DEREF_ARGSONLY
:
353 ftsoptions
|= FTS_COMFOLLOW
;
356 case SYMLINK_NEVER_DEREF
:
357 ftsoptions
|= FTS_PHYSICAL
;
361 if (options
.stay_on_filesystem
)
362 ftsoptions
|= FTS_XDEV
;
364 p
= fts_open(arglist
, ftsoptions
, NULL
);
368 _("cannot search %s"),
369 quotearg_n_style(0, locale_quoting_style
, arg
));
373 while ( (ent
=fts_read(p
)) != NULL
)
375 consider_visiting(p
, ent
);
384 process_all_startpoints(int argc
, char *argv
[])
388 /* figure out how many start points there are */
389 for (i
= 0; i
< argc
&& !looks_like_expression(argv
[i
]); i
++)
397 * We use a temporary variable here because some actions modify
398 * the path temporarily. Hence if we use a string constant,
399 * we get a coredump. The best example of this is if we say
400 * "find -printf %H" (note, not "find . -printf %H").
402 char defaultpath
[2] = ".";
411 main (int argc
, char **argv
)
414 const struct parser_table
*parse_entry
; /* Pointer to the parsing table entry for this expression. */
415 struct predicate
*cur_pred
;
416 char *predicate_name
; /* Name of predicate being parsed. */
417 int end_of_leading_options
= 0; /* First arg after any -H/-L etc. */
418 program_name
= argv
[0];
419 const struct parser_table
*entry_close
, *entry_print
, *entry_open
;
422 /* We call check_nofollow() before setlocale() because the numbers
423 * for which we check (in the results of uname) definitiely have "."
424 * as the decimal point indicator even under locales for which that
425 * is not normally true. Hence atof() would do the wrong thing
426 * if we call it after setlocale().
429 options
.open_nofollow_available
= check_nofollow();
431 options
.open_nofollow_available
= false;
434 options
.regex_options
= RE_SYNTAX_EMACS
;
436 #ifdef HAVE_SETLOCALE
437 setlocale (LC_ALL
, "");
440 bindtextdomain (PACKAGE
, LOCALEDIR
);
441 textdomain (PACKAGE
);
442 atexit (close_stdout
);
447 options
.warnings
= true;
448 options
.literal_control_chars
= false;
452 options
.warnings
= false;
453 options
.literal_control_chars
= false; /* may change */
459 options
.do_dir_first
= true;
460 options
.maxdepth
= options
.mindepth
= -1;
461 options
.start_time
= time (NULL
);
462 options
.cur_day_start
= options
.start_time
- DAYSECS
;
463 options
.full_days
= false;
464 options
.stay_on_filesystem
= false;
465 options
.ignore_readdir_race
= false;
467 state
.exit_status
= 0;
469 #if defined(DEBUG_STAT)
470 options
.xstat
= debug_stat
;
471 #endif /* !DEBUG_STAT */
473 if (getenv("POSIXLY_CORRECT"))
474 options
.output_block_size
= 512;
476 options
.output_block_size
= 1024;
478 if (getenv("FIND_BLOCK_SIZE"))
480 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"));
483 #if LEAF_OPTIMISATION
484 /* The leaf optimisation is enabled. */
485 options
.no_leaf_check
= false;
487 /* The leaf optimisation is disabled. */
488 options
.no_leaf_check
= true;
491 set_follow_state(SYMLINK_NEVER_DEREF
); /* The default is equivalent to -P. */
494 fprintf (stderr
, "cur_day_start = %s", ctime (&options
.cur_day_start
));
497 /* Check for -P, -H or -L options. */
498 for (i
=1; (end_of_leading_options
= i
) < argc
; ++i
)
500 if (0 == strcmp("-H", argv
[i
]))
502 /* Meaning: dereference symbolic links on command line, but nowhere else. */
503 set_follow_state(SYMLINK_DEREF_ARGSONLY
);
505 else if (0 == strcmp("-L", argv
[i
]))
507 /* Meaning: dereference all symbolic links. */
508 set_follow_state(SYMLINK_ALWAYS_DEREF
);
510 else if (0 == strcmp("-P", argv
[i
]))
512 /* Meaning: never dereference symbolic links (default). */
513 set_follow_state(SYMLINK_NEVER_DEREF
);
515 else if (0 == strcmp("--", argv
[i
]))
517 /* -- signifies the end of options. */
518 end_of_leading_options
= i
+1; /* Next time start with the next option */
523 /* Hmm, must be one of
527 end_of_leading_options
= i
; /* Next time start with this option */
532 /* We are now processing the part of the "find" command line
533 * after the -H/-L options (if any).
536 /* fprintf(stderr, "rest: optind=%ld\n", (long)optind); */
538 /* Find where in ARGV the predicates begin. */
539 for (i
= end_of_leading_options
; i
< argc
&& !looks_like_expression(argv
[i
]); i
++)
541 /* fprintf(stderr, "Looks like %s is not a predicate\n", argv[i]); */
545 /* Enclose the expression in `( ... )' so a default -print will
546 apply to the whole expression. */
547 entry_open
= find_parser("(");
548 entry_close
= find_parser(")");
549 entry_print
= find_parser("print");
550 assert(entry_open
!= NULL
);
551 assert(entry_close
!= NULL
);
552 assert(entry_print
!= NULL
);
554 parse_open (entry_open
, argv
, &argc
);
555 parse_begin_user_args(argv
, argc
, last_pred
, predicates
);
556 pred_sanity_check(last_pred
);
558 /* Build the input order list. */
561 if (!looks_like_expression(argv
[i
]))
563 if (0 != strcmp(argv
[i
], ")"))
565 error (0, 0, _("paths must precede expression: %s"), argv
[i
]);
570 predicate_name
= argv
[i
];
571 parse_entry
= find_parser (predicate_name
);
572 if (parse_entry
== NULL
)
574 /* Command line option not recognized */
575 error (1, 0, _("invalid predicate `%s'"), predicate_name
);
579 if (!(*(parse_entry
->parser_func
)) (parse_entry
, argv
, &i
))
582 /* Command line option requires an argument */
583 error (1, 0, _("missing argument to `%s'"), predicate_name
);
585 error (1, 0, _("invalid argument `%s' to `%s'"),
586 argv
[i
], predicate_name
);
589 pred_sanity_check(last_pred
);
590 pred_sanity_check(predicates
); /* XXX: expensive */
592 parse_end_user_args(argv
, argc
, last_pred
, predicates
);
594 if (predicates
->pred_next
== NULL
)
596 /* No predicates that do something other than set a global variable
597 were given; remove the unneeded initial `(' and add `-print'. */
598 cur_pred
= predicates
;
599 predicates
= last_pred
= predicates
->pred_next
;
600 free ((char *) cur_pred
);
601 parse_print (entry_print
, argv
, &argc
);
602 pred_sanity_check(last_pred
);
603 pred_sanity_check(predicates
); /* XXX: expensive */
605 else if (!default_prints (predicates
->pred_next
))
607 /* One or more predicates that produce output were given;
608 remove the unneeded initial `('. */
609 cur_pred
= predicates
;
610 predicates
= predicates
->pred_next
;
611 pred_sanity_check(predicates
); /* XXX: expensive */
612 free ((char *) cur_pred
);
616 /* `( user-supplied-expression ) -print'. */
617 parse_close (entry_close
, argv
, &argc
);
618 pred_sanity_check(last_pred
);
619 parse_print (entry_print
, argv
, &argc
);
620 pred_sanity_check(last_pred
);
621 pred_sanity_check(predicates
); /* XXX: expensive */
625 fprintf (stderr
, "Predicate List:\n");
626 print_list (stderr
, predicates
);
629 /* do a sanity check */
630 pred_sanity_check(predicates
);
632 /* Done parsing the predicates. Build the evaluation tree. */
633 cur_pred
= predicates
;
634 eval_tree
= get_expr (&cur_pred
, NO_PREC
);
636 /* Check if we have any left-over predicates (this fixes
637 * Debian bug #185202).
639 if (cur_pred
!= NULL
)
641 error (1, 0, _("unexpected extra predicate"));
645 fprintf (stderr
, "Eval Tree:\n");
646 print_tree (stderr
, eval_tree
, 0);
649 /* Rearrange the eval tree in optimal-predicate order. */
650 opt_expr (&eval_tree
);
652 /* Determine the point, if any, at which to stat the file. */
653 mark_stat (eval_tree
);
654 /* Determine the point, if any, at which to determine file type. */
655 mark_type (eval_tree
);
658 fprintf (stderr
, "Optimized Eval Tree:\n");
659 print_tree (stderr
, eval_tree
, 0);
660 fprintf (stderr
, "Optimized command line:\n");
661 print_optlist(stderr
, eval_tree
);
662 fprintf(stderr
, "\n");
665 /* safely_chdir() needs to check that it has ended up in the right place.
666 * To avoid bailing out when something gets automounted, it checks if
667 * the target directory appears to have had a directory mounted on it as
668 * we chdir()ed. The problem with this is that in order to notice that
669 * a filesystem was mounted, we would need to lstat() all the mount points.
670 * That strategy loses if our machine is a client of a dead NFS server.
672 * Hence if safely_chdir() and wd_sanity_check() can manage without needing
673 * to know the mounted device list, we do that.
675 if (!options
.open_nofollow_available
)
677 #ifdef STAT_MOUNTPOINTS
678 init_mounted_dev_list();
683 starting_desc
= open (".", O_RDONLY
);
684 if (0 <= starting_desc
&& fchdir (starting_desc
) != 0)
686 close (starting_desc
);
689 if (starting_desc
< 0)
691 starting_dir
= xgetcwd ();
693 error (1, errno
, _("cannot get current directory"));
697 process_all_startpoints(argc
-end_of_leading_options
, argv
+end_of_leading_options
);
699 /* If "-exec ... {} +" has been used, there may be some
700 * partially-full command lines which have been built,
701 * but which are not yet complete. Execute those now.
704 return state
.exit_status
;
707 boolean
is_fts_enabled()
709 /* this version of find (i.e. this main()) uses fts. */