Define the m4 macro MKINSTALLDIRS ourselves, because po/Makefile.in.in needs it but...
[findutils.git] / find / util.c
blob56e7bb418e4e1329918cb0f262a5a9c33bed2e26
1 /* util.c -- functions for initializing new tree elements, and other things.
2 Copyright (C) 1990, 91, 92, 93, 94, 2000, 2003, 2004, 2005 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.
20 #include "defs.h"
22 #ifdef HAVE_FCNTL_H
23 #include <fcntl.h>
24 #else
25 #include <sys/file.h>
26 #endif
27 #ifdef HAVE_SYS_UTSNAME_H
28 #include <sys/utsname.h>
29 #endif
31 #include "xalloc.h"
32 #include "quotearg.h"
35 #if ENABLE_NLS
36 # include <libintl.h>
37 # define _(Text) gettext (Text)
38 #else
39 # define _(Text) Text
40 #endif
41 #ifdef gettext_noop
42 # define N_(String) gettext_noop (String)
43 #else
44 /* See locate.c for explanation as to why not use (String) */
45 # define N_(String) String
46 #endif
48 #include <ctype.h>
49 #include <string.h>
50 #include <limits.h>
51 #include <assert.h>
54 struct debug_option_assoc
56 char *name;
57 int val;
58 char *docstring;
60 static struct debug_option_assoc debugassoc[] =
62 { "help", DebugHelp, "Explain the various -D options" },
63 { "tree", DebugExpressionTree, "Display the expression tree" },
64 { "search",DebugSearch, "Navigate the directory tree verbosely" },
65 { "stat", DebugStat, "Trace calls to stat(2) and lstat(2)" },
66 { "opt", DebugExpressionTree|DebugTreeOpt, "Show diagnostic information relating to optimisation" }
68 #define N_DEBUGASSOC (sizeof(debugassoc)/sizeof(debugassoc[0]))
73 /* Add a primary of predicate type PRED_FUNC (described by ENTRY) to the predicate input list.
75 Return a pointer to the predicate node just inserted.
77 Fills in the following cells of the new predicate node:
79 pred_func PRED_FUNC
80 args(.str) NULL
81 p_type PRIMARY_TYPE
82 p_prec NO_PREC
84 Other cells that need to be filled in are defaulted by
85 get_new_pred_chk_op, which is used to insure that the prior node is
86 either not there at all (we are the very first node) or is an
87 operator. */
89 struct predicate *
90 insert_primary_withpred (const struct parser_table *entry, PRED_FUNC pred_func)
92 struct predicate *new_pred;
94 new_pred = get_new_pred_chk_op (entry);
95 new_pred->pred_func = pred_func;
96 new_pred->p_name = entry->parser_name;
97 new_pred->args.str = NULL;
98 new_pred->p_type = PRIMARY_TYPE;
99 new_pred->p_prec = NO_PREC;
100 return new_pred;
103 /* Add a primary described by ENTRY to the predicate input list.
105 Return a pointer to the predicate node just inserted.
107 Fills in the following cells of the new predicate node:
109 pred_func PRED_FUNC
110 args(.str) NULL
111 p_type PRIMARY_TYPE
112 p_prec NO_PREC
114 Other cells that need to be filled in are defaulted by
115 get_new_pred_chk_op, which is used to insure that the prior node is
116 either not there at all (we are the very first node) or is an
117 operator. */
118 struct predicate *
119 insert_primary (const struct parser_table *entry)
121 assert(entry->pred_func != NULL);
122 return insert_primary_withpred(entry, entry->pred_func);
127 static void
128 show_valid_debug_options(FILE *fp, int full)
130 int i;
131 if (full)
133 fprintf(fp, "Valid arguments for -D:\n");
134 for (i=0; i<N_DEBUGASSOC; ++i)
136 fprintf(fp, "%-10s %s\n",
137 debugassoc[i].name,
138 debugassoc[i].docstring);
141 else
143 for (i=0; i<N_DEBUGASSOC; ++i)
145 fprintf(fp, "%s%s", (i>0 ? "|" : ""), debugassoc[i].name);
150 void
151 usage (FILE *fp, int status, char *msg)
153 size_t i;
155 if (msg)
156 fprintf (fp, "%s: %s\n", program_name, msg);
158 fprintf (fp, _("Usage: %s [-H] [-L] [-P] [-Olevel] [-D "), program_name);
159 show_valid_debug_options(fp, 0);
160 fprintf (fp, _("] [path...] [expression]\n"));
161 if (0 != status)
162 exit (status);
166 /* Get the stat information for a file, if it is
167 * not already known.
170 get_statinfo (const char *pathname, const char *name, struct stat *p)
172 if (!state.have_stat && (*options.xstat) (name, p) != 0)
174 if (!options.ignore_readdir_race || (errno != ENOENT) )
176 error (0, errno, "%s", pathname);
177 state.exit_status = 1;
179 return -1;
181 state.have_stat = true;
182 state.have_type = true;
183 state.type = p->st_mode;
184 return 0;
188 /* Get the stat/type information for a file, if it is
189 * not already known.
192 get_info (const char *pathname,
193 const char *name,
194 struct stat *p,
195 struct predicate *pred_ptr)
197 /* If we need the full stat info, or we need the type info but don't
198 * already have it, stat the file now.
200 (void) name;
201 if (pred_ptr->need_stat)
203 return get_statinfo(pathname, state.rel_pathname, p);
205 if ((pred_ptr->need_type && (0 == state.have_type)))
207 return get_statinfo(pathname, state.rel_pathname, p);
209 return 0;
212 /* Determine if we can use O_NOFOLLOW.
214 #if defined(O_NOFOLLOW)
215 boolean
216 check_nofollow(void)
218 struct utsname uts;
219 float release;
221 if (0 == uname(&uts))
223 /* POSIX requires that atof() ignore "unrecognised suffixes". */
224 release = atof(uts.release);
226 if (0 == strcmp("Linux", uts.sysname))
228 /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
229 return release >= 2.2; /* close enough */
231 else if (0 == strcmp("FreeBSD", uts.sysname))
233 /* FreeBSD 3.0-CURRENT and later support it */
234 return release >= 3.1;
238 /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
239 return true;
241 #endif
245 /* Examine the predicate list for instances of -execdir or -okdir
246 * which have been terminated with '+' (build argument list) rather
247 * than ';' (singles only). If there are any, run them (this will
248 * have no effect if there are no arguments waiting).
250 void
251 complete_pending_execdirs(struct predicate *p)
253 #if defined(NEW_EXEC)
254 if (NULL == p)
255 return;
257 complete_pending_execdirs(p->pred_left);
259 if (p->pred_func == pred_execdir || p->pred_func == pred_okdir)
261 /* It's an exec-family predicate. p->args.exec_val is valid. */
262 if (p->args.exec_vec.multiple)
264 struct exec_val *execp = &p->args.exec_vec;
266 /* This one was terminated by '+' and so might have some
267 * left... Run it if necessary.
269 if (execp->state.todo)
271 /* There are not-yet-executed arguments. */
272 launch (&execp->ctl, &execp->state);
277 complete_pending_execdirs(p->pred_right);
278 #else
279 /* nothing to do. */
280 return;
281 #endif
285 /* Examine the predicate list for instances of -exec which have been
286 * terminated with '+' (build argument list) rather than ';' (singles
287 * only). If there are any, run them (this will have no effect if
288 * there are no arguments waiting).
290 void
291 complete_pending_execs(struct predicate *p)
293 #if defined(NEW_EXEC)
294 if (NULL == p)
295 return;
297 complete_pending_execs(p->pred_left);
299 /* It's an exec-family predicate then p->args.exec_val is valid
300 * and we can check it.
302 if (p->pred_func == pred_exec && p->args.exec_vec.multiple)
304 struct exec_val *execp = &p->args.exec_vec;
306 /* This one was terminated by '+' and so might have some
307 * left... Run it if necessary. Set state.exit_status if
308 * there are any problems.
310 if (execp->state.todo)
312 /* There are not-yet-executed arguments. */
313 launch (&execp->ctl, &execp->state);
317 complete_pending_execs(p->pred_right);
318 #else
319 /* nothing to do. */
320 return;
321 #endif
325 /* Complete any outstanding commands.
327 void
328 cleanup(void)
330 struct predicate *eval_tree = get_eval_tree();
331 if (eval_tree)
333 complete_pending_execs(eval_tree);
334 complete_pending_execdirs(eval_tree);
339 static int
340 fallback_stat(const char *name, struct stat *p, int prev_rv)
342 /* Our original stat() call failed. Perhaps we can't follow a
343 * symbolic link. If that might be the problem, lstat() the link.
344 * Otherwise, admit defeat.
346 switch (errno)
348 case ENOENT:
349 case ENOTDIR:
350 if (options.debug_options & DebugStat)
351 fprintf(stderr, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name);
352 return lstat(name, p);
354 case EACCES:
355 case EIO:
356 case ELOOP:
357 case ENAMETOOLONG:
358 #ifdef EOVERFLOW
359 case EOVERFLOW: /* EOVERFLOW is not #defined on UNICOS. */
360 #endif
361 default:
362 return prev_rv;
367 /* optionh_stat() implements the stat operation when the -H option is
368 * in effect.
370 * If the item to be examined is a command-line argument, we follow
371 * symbolic links. If the stat() call fails on the command-line item,
372 * we fall back on the properties of the symbolic link.
374 * If the item to be examined is not a command-line argument, we
375 * examine the link itself.
377 int
378 optionh_stat(const char *name, struct stat *p)
380 if (0 == state.curdepth)
382 /* This file is from the command line; deference the link (if it
383 * is a link).
385 int rv = stat(name, p);
386 if (0 == rv)
387 return 0; /* success */
388 else
389 return fallback_stat(name, p, rv);
391 else
393 /* Not a file on the command line; do not dereference the link.
395 return lstat(name, p);
399 /* optionl_stat() implements the stat operation when the -L option is
400 * in effect. That option makes us examine the thing the symbolic
401 * link points to, not the symbolic link itself.
403 int
404 optionl_stat(const char *name, struct stat *p)
406 int rv = stat(name, p);
407 if (0 == rv)
408 return 0; /* normal case. */
409 else
410 return fallback_stat(name, p, rv);
413 /* optionp_stat() implements the stat operation when the -P option is
414 * in effect (this is also the default). That option makes us examine
415 * the symbolic link itself, not the thing it points to.
417 int
418 optionp_stat(const char *name, struct stat *p)
420 return lstat(name, p);
424 static uintmax_t stat_count = 0u;
427 debug_stat (const char *file, struct stat *bufp)
429 ++stat_count;
430 fprintf (stderr, "debug_stat (%s)\n", file);
431 switch (options.symlink_handling)
433 case SYMLINK_ALWAYS_DEREF:
434 return optionl_stat(file, bufp);
435 case SYMLINK_DEREF_ARGSONLY:
436 return optionh_stat(file, bufp);
437 case SYMLINK_NEVER_DEREF:
438 return optionp_stat(file, bufp);
440 /*NOTREACHED*/
441 assert(false);
442 return -1;
447 following_links(void)
449 switch (options.symlink_handling)
451 case SYMLINK_ALWAYS_DEREF:
452 return 1;
453 case SYMLINK_DEREF_ARGSONLY:
454 return (state.curdepth == 0);
455 case SYMLINK_NEVER_DEREF:
456 default:
457 return 0;
462 /* Take a "mode" indicator and fill in the files of 'state'.
465 digest_mode(mode_t mode,
466 const char *pathname,
467 const char *name,
468 struct stat *pstat,
469 boolean leaf)
471 /* If we know the type of the directory entry, and it is not a
472 * symbolic link, we may be able to avoid a stat() or lstat() call.
474 if (mode)
476 if (S_ISLNK(mode) && following_links())
478 /* mode is wrong because we should have followed the symlink. */
479 if (get_statinfo(pathname, name, pstat) != 0)
480 return 0;
481 mode = state.type = pstat->st_mode;
482 state.have_type = true;
484 else
486 state.have_type = true;
487 pstat->st_mode = state.type = mode;
490 else
492 /* Mode is not yet known; may have to stat the file unless we
493 * can deduce that it is not a directory (which is all we need to
494 * know at this stage)
496 if (leaf)
498 state.have_stat = false;
499 state.have_type = false;;
500 state.type = 0;
502 else
504 if (get_statinfo(pathname, name, pstat) != 0)
505 return 0;
507 /* If -L is in effect and we are dealing with a symlink,
508 * st_mode is the mode of the pointed-to file, while mode is
509 * the mode of the directory entry (S_IFLNK). Hence now
510 * that we have the stat information, override "mode".
512 state.type = pstat->st_mode;
513 state.have_type = true;
517 /* success. */
518 return 1;
522 /* Return true if there are no predicates with no_default_print in
523 predicate list PRED, false if there are any.
524 Returns true if default print should be performed */
526 boolean
527 default_prints (struct predicate *pred)
529 while (pred != NULL)
531 if (pred->no_default_print)
532 return (false);
533 pred = pred->pred_next;
535 return (true);
538 boolean
539 looks_like_expression(const char *arg, boolean leading)
541 switch (arg[0])
543 case '-':
544 if (arg[1]) /* "-foo" is an expression. */
545 return true;
546 else
547 return false; /* Just "-" is a filename. */
548 break;
550 case ')':
551 case ',':
552 if (arg[1])
553 return false; /* )x and ,z are not expressions */
554 else
555 return !leading; /* A leading ) or , is not either */
557 /* ( and ! are part of an expression, but (2 and !foo are
558 * filenames.
560 case '!':
561 case '(':
562 if (arg[1])
563 return false;
564 else
565 return true;
567 default:
568 return false;
572 static void
573 process_debug_options(char *arg)
575 const char *p;
576 char *token_context = NULL;
577 const char delimiters[] = ",";
578 boolean empty = true;
579 size_t i;
581 p = strtok_r(arg, delimiters, &token_context);
582 while (p)
584 empty = false;
586 for (i=0; i<N_DEBUGASSOC; ++i)
588 if (0 == strcmp(debugassoc[i].name, p))
590 options.debug_options |= debugassoc[i].val;
591 break;
594 if (i >= N_DEBUGASSOC)
596 error(0, 0, _("Ignoring unrecognised debug flag %s"),
597 quotearg_n_style(0, locale_quoting_style, arg));
599 p = strtok_r(NULL, delimiters, &token_context);
601 if (empty)
603 error(1, 0, _("Empty argument to the -D option."));
605 else if (options.debug_options & DebugHelp)
607 show_valid_debug_options(stdout, 1);
608 exit(0);
612 static void
613 process_optimisation_option(const char *arg)
615 if (0 == arg[0])
617 error(1, 0, _("The -O option must be immediately followed by a decimal integer"));
619 else
621 unsigned long opt_level;
622 char *end;
624 if (!isdigit( (unsigned char) arg[0] ))
626 error(1, 0, _("Please specify a decimal number immediately after -O"));
628 else
630 int prev_errno = errno;
631 errno = 0;
633 opt_level = strtoul(arg, &end, 10);
634 if ( (0==opt_level) && (end==arg) )
636 error(1, 0, _("Please specify a decimal number immediately after -O"));
638 else if (*end)
640 /* unwanted trailing characters. */
641 error(1, 0, _("Invalid optimisation level %s"), arg);
643 else if ( (ULONG_MAX==opt_level) && errno)
645 error(1, errno, _("Invalid optimisation level %s"), arg);
647 else if (opt_level > USHRT_MAX)
649 /* tricky to test, as on some platforms USHORT_MAX and ULONG_MAX
650 * can have the same value, though this is unusual.
652 error(1, 0, _("Optimisation level %lu is too high. "
653 "If you want to find files very quickly, "
654 "consider using GNU locate."),
655 opt_level);
657 else
659 options.optimisation_level = opt_level;
660 errno = prev_errno;
667 process_leading_options(int argc, char *argv[])
669 int i, end_of_leading_options;
671 for (i=1; (end_of_leading_options = i) < argc; ++i)
673 if (0 == strcmp("-H", argv[i]))
675 /* Meaning: dereference symbolic links on command line, but nowhere else. */
676 set_follow_state(SYMLINK_DEREF_ARGSONLY);
678 else if (0 == strcmp("-L", argv[i]))
680 /* Meaning: dereference all symbolic links. */
681 set_follow_state(SYMLINK_ALWAYS_DEREF);
683 else if (0 == strcmp("-P", argv[i]))
685 /* Meaning: never dereference symbolic links (default). */
686 set_follow_state(SYMLINK_NEVER_DEREF);
688 else if (0 == strcmp("--", argv[i]))
690 /* -- signifies the end of options. */
691 end_of_leading_options = i+1; /* Next time start with the next option */
692 break;
694 else if (0 == strcmp("-D", argv[i]))
696 process_debug_options(argv[i+1]);
697 ++i; /* skip the argument too. */
699 else if (0 == strncmp("-O", argv[i], 2))
701 process_optimisation_option(argv[i]+2);
703 else
705 /* Hmm, must be one of
706 * (a) A path name
707 * (b) A predicate
709 end_of_leading_options = i; /* Next time start with this option */
710 break;
713 return end_of_leading_options;
716 void
717 set_option_defaults(struct options *p)
719 /* We call check_nofollow() before setlocale() because the numbers
720 * for which we check (in the results of uname) definitiely have "."
721 * as the decimal point indicator even under locales for which that
722 * is not normally true. Hence atof() would do the wrong thing
723 * if we call it after setlocale().
725 #ifdef O_NOFOLLOW
726 p->open_nofollow_available = check_nofollow();
727 #else
728 p->open_nofollow_available = false;
729 #endif
731 p->regex_options = RE_SYNTAX_EMACS;
733 if (isatty(0))
735 p->warnings = true;
736 p->literal_control_chars = false;
738 else
740 p->warnings = false;
741 p->literal_control_chars = false; /* may change */
745 p->do_dir_first = true;
746 p->maxdepth = p->mindepth = -1;
747 p->start_time = time (NULL);
748 p->cur_day_start = p->start_time - DAYSECS;
749 p->full_days = false;
750 p->stay_on_filesystem = false;
751 p->ignore_readdir_race = false;
753 if (getenv("POSIXLY_CORRECT"))
754 p->output_block_size = 512;
755 else
756 p->output_block_size = 1024;
758 p->debug_options = 0uL;
759 p->optimisation_level = 0;
761 if (getenv("FIND_BLOCK_SIZE"))
763 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"));
766 #if LEAF_OPTIMISATION
767 /* The leaf optimisation is enabled. */
768 p->no_leaf_check = false;
769 #else
770 /* The leaf optimisation is disabled. */
771 p->no_leaf_check = true;
772 #endif
774 set_follow_state(SYMLINK_NEVER_DEREF); /* The default is equivalent to -P. */