Issue states messages in a way which indicates more clearly what's
[findutils.git] / find / util.c
blobaf54ad3cf9ccd2b6630f1a4bf575cac8dc1c3828
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 { "stat", DebugStat, "Trace calls to stat(2) and lstat(2)" },
65 { "opt", DebugExpressionTree|DebugTreeOpt, "Show diagnostic information relating to optimisation" }
67 #define N_DEBUGASSOC (sizeof(debugassoc)/sizeof(debugassoc[0]))
72 /* Add a primary of predicate type PRED_FUNC (described by ENTRY) to the predicate input list.
74 Return a pointer to the predicate node just inserted.
76 Fills in the following cells of the new predicate node:
78 pred_func PRED_FUNC
79 args(.str) NULL
80 p_type PRIMARY_TYPE
81 p_prec NO_PREC
83 Other cells that need to be filled in are defaulted by
84 get_new_pred_chk_op, which is used to insure that the prior node is
85 either not there at all (we are the very first node) or is an
86 operator. */
88 struct predicate *
89 insert_primary_withpred (const struct parser_table *entry, PRED_FUNC pred_func)
91 struct predicate *new_pred;
93 new_pred = get_new_pred_chk_op (entry);
94 new_pred->pred_func = pred_func;
95 new_pred->p_name = entry->parser_name;
96 new_pred->args.str = NULL;
97 new_pred->p_type = PRIMARY_TYPE;
98 new_pred->p_prec = NO_PREC;
99 return new_pred;
102 /* Add a primary described by ENTRY to the predicate input list.
104 Return a pointer to the predicate node just inserted.
106 Fills in the following cells of the new predicate node:
108 pred_func PRED_FUNC
109 args(.str) NULL
110 p_type PRIMARY_TYPE
111 p_prec NO_PREC
113 Other cells that need to be filled in are defaulted by
114 get_new_pred_chk_op, which is used to insure that the prior node is
115 either not there at all (we are the very first node) or is an
116 operator. */
117 struct predicate *
118 insert_primary (const struct parser_table *entry)
120 assert(entry->pred_func != NULL);
121 return insert_primary_withpred(entry, entry->pred_func);
126 static void
127 show_valid_debug_options(FILE *fp, int full)
129 int i;
130 if (full)
132 fprintf(fp, "Valid arguments for -D:\n");
133 for (i=0; i<N_DEBUGASSOC; ++i)
135 fprintf(fp, "%-10s %s\n",
136 debugassoc[i].name,
137 debugassoc[i].docstring);
140 else
142 for (i=0; i<N_DEBUGASSOC; ++i)
144 fprintf(fp, "%s%s", (i>0 ? "|" : ""), debugassoc[i].name);
149 void
150 usage (FILE *fp, int status, char *msg)
152 size_t i;
154 if (msg)
155 fprintf (fp, "%s: %s\n", program_name, msg);
157 fprintf (fp, _("Usage: %s [-H] [-L] [-P] [-Olevel] [-D "), program_name);
158 show_valid_debug_options(fp, 0);
159 fprintf (fp, _("] [path...] [expression]\n"));
160 if (0 != status)
161 exit (status);
165 /* Get the stat information for a file, if it is
166 * not already known.
169 get_statinfo (const char *pathname, const char *name, struct stat *p)
171 if (!state.have_stat && (*options.xstat) (name, p) != 0)
173 if (!options.ignore_readdir_race || (errno != ENOENT) )
175 error (0, errno, "%s", pathname);
176 state.exit_status = 1;
178 return -1;
180 state.have_stat = true;
181 state.have_type = true;
182 state.type = p->st_mode;
183 return 0;
187 /* Get the stat/type information for a file, if it is
188 * not already known.
191 get_info (const char *pathname,
192 const char *name,
193 struct stat *p,
194 struct predicate *pred_ptr)
196 /* If we need the full stat info, or we need the type info but don't
197 * already have it, stat the file now.
199 (void) name;
200 if (pred_ptr->need_stat)
202 return get_statinfo(pathname, state.rel_pathname, p);
204 if ((pred_ptr->need_type && (0 == state.have_type)))
206 return get_statinfo(pathname, state.rel_pathname, p);
208 return 0;
211 /* Determine if we can use O_NOFOLLOW.
213 #if defined(O_NOFOLLOW)
214 boolean
215 check_nofollow(void)
217 struct utsname uts;
218 float release;
220 if (0 == uname(&uts))
222 /* POSIX requires that atof() ignore "unrecognised suffixes". */
223 release = atof(uts.release);
225 if (0 == strcmp("Linux", uts.sysname))
227 /* Linux kernels 2.1.126 and earlier ignore the O_NOFOLLOW flag. */
228 return release >= 2.2; /* close enough */
230 else if (0 == strcmp("FreeBSD", uts.sysname))
232 /* FreeBSD 3.0-CURRENT and later support it */
233 return release >= 3.1;
237 /* Well, O_NOFOLLOW was defined, so we'll try to use it. */
238 return true;
240 #endif
244 /* Examine the predicate list for instances of -execdir or -okdir
245 * which have been terminated with '+' (build argument list) rather
246 * than ';' (singles only). If there are any, run them (this will
247 * have no effect if there are no arguments waiting).
249 void
250 complete_pending_execdirs(struct predicate *p)
252 #if defined(NEW_EXEC)
253 if (NULL == p)
254 return;
256 complete_pending_execdirs(p->pred_left);
258 if (p->pred_func == pred_execdir || p->pred_func == pred_okdir)
260 /* It's an exec-family predicate. p->args.exec_val is valid. */
261 if (p->args.exec_vec.multiple)
263 struct exec_val *execp = &p->args.exec_vec;
265 /* This one was terminated by '+' and so might have some
266 * left... Run it if necessary.
268 if (execp->state.todo)
270 /* There are not-yet-executed arguments. */
271 launch (&execp->ctl, &execp->state);
276 complete_pending_execdirs(p->pred_right);
277 #else
278 /* nothing to do. */
279 return;
280 #endif
284 /* Examine the predicate list for instances of -exec which have been
285 * terminated with '+' (build argument list) rather than ';' (singles
286 * only). If there are any, run them (this will have no effect if
287 * there are no arguments waiting).
289 void
290 complete_pending_execs(struct predicate *p)
292 #if defined(NEW_EXEC)
293 if (NULL == p)
294 return;
296 complete_pending_execs(p->pred_left);
298 /* It's an exec-family predicate then p->args.exec_val is valid
299 * and we can check it.
301 if (p->pred_func == pred_exec && p->args.exec_vec.multiple)
303 struct exec_val *execp = &p->args.exec_vec;
305 /* This one was terminated by '+' and so might have some
306 * left... Run it if necessary. Set state.exit_status if
307 * there are any problems.
309 if (execp->state.todo)
311 /* There are not-yet-executed arguments. */
312 launch (&execp->ctl, &execp->state);
316 complete_pending_execs(p->pred_right);
317 #else
318 /* nothing to do. */
319 return;
320 #endif
324 /* Complete any outstanding commands.
326 void
327 cleanup(void)
329 struct predicate *eval_tree = get_eval_tree();
330 if (eval_tree)
332 complete_pending_execs(eval_tree);
333 complete_pending_execdirs(eval_tree);
338 static int
339 fallback_stat(const char *name, struct stat *p, int prev_rv)
341 /* Our original stat() call failed. Perhaps we can't follow a
342 * symbolic link. If that might be the problem, lstat() the link.
343 * Otherwise, admit defeat.
345 switch (errno)
347 case ENOENT:
348 case ENOTDIR:
349 if (options.debug_options & DebugStat)
350 fprintf(stderr, "fallback_stat(): stat(%s) failed; falling back on lstat()\n", name);
351 return lstat(name, p);
353 case EACCES:
354 case EIO:
355 case ELOOP:
356 case ENAMETOOLONG:
357 #ifdef EOVERFLOW
358 case EOVERFLOW: /* EOVERFLOW is not #defined on UNICOS. */
359 #endif
360 default:
361 return prev_rv;
366 /* optionh_stat() implements the stat operation when the -H option is
367 * in effect.
369 * If the item to be examined is a command-line argument, we follow
370 * symbolic links. If the stat() call fails on the command-line item,
371 * we fall back on the properties of the symbolic link.
373 * If the item to be examined is not a command-line argument, we
374 * examine the link itself.
376 int
377 optionh_stat(const char *name, struct stat *p)
379 if (0 == state.curdepth)
381 /* This file is from the command line; deference the link (if it
382 * is a link).
384 int rv = stat(name, p);
385 if (0 == rv)
386 return 0; /* success */
387 else
388 return fallback_stat(name, p, rv);
390 else
392 /* Not a file on the command line; do not dereference the link.
394 return lstat(name, p);
398 /* optionl_stat() implements the stat operation when the -L option is
399 * in effect. That option makes us examine the thing the symbolic
400 * link points to, not the symbolic link itself.
402 int
403 optionl_stat(const char *name, struct stat *p)
405 int rv = stat(name, p);
406 if (0 == rv)
407 return 0; /* normal case. */
408 else
409 return fallback_stat(name, p, rv);
412 /* optionp_stat() implements the stat operation when the -P option is
413 * in effect (this is also the default). That option makes us examine
414 * the symbolic link itself, not the thing it points to.
416 int
417 optionp_stat(const char *name, struct stat *p)
419 return lstat(name, p);
423 static uintmax_t stat_count = 0u;
426 debug_stat (const char *file, struct stat *bufp)
428 ++stat_count;
429 fprintf (stderr, "debug_stat (%s)\n", file);
430 switch (options.symlink_handling)
432 case SYMLINK_ALWAYS_DEREF:
433 return optionl_stat(file, bufp);
434 case SYMLINK_DEREF_ARGSONLY:
435 return optionh_stat(file, bufp);
436 case SYMLINK_NEVER_DEREF:
437 return optionp_stat(file, bufp);
439 /*NOTREACHED*/
440 assert(false);
441 return -1;
446 following_links(void)
448 switch (options.symlink_handling)
450 case SYMLINK_ALWAYS_DEREF:
451 return 1;
452 case SYMLINK_DEREF_ARGSONLY:
453 return (state.curdepth == 0);
454 case SYMLINK_NEVER_DEREF:
455 default:
456 return 0;
461 /* Take a "mode" indicator and fill in the files of 'state'.
464 digest_mode(mode_t mode,
465 const char *pathname,
466 const char *name,
467 struct stat *pstat,
468 boolean leaf)
470 /* If we know the type of the directory entry, and it is not a
471 * symbolic link, we may be able to avoid a stat() or lstat() call.
473 if (mode)
475 if (S_ISLNK(mode) && following_links())
477 /* mode is wrong because we should have followed the symlink. */
478 if (get_statinfo(pathname, name, pstat) != 0)
479 return 0;
480 mode = state.type = pstat->st_mode;
481 state.have_type = true;
483 else
485 state.have_type = true;
486 pstat->st_mode = state.type = mode;
489 else
491 /* Mode is not yet known; may have to stat the file unless we
492 * can deduce that it is not a directory (which is all we need to
493 * know at this stage)
495 if (leaf)
497 state.have_stat = false;
498 state.have_type = false;;
499 state.type = 0;
501 else
503 if (get_statinfo(pathname, name, pstat) != 0)
504 return 0;
506 /* If -L is in effect and we are dealing with a symlink,
507 * st_mode is the mode of the pointed-to file, while mode is
508 * the mode of the directory entry (S_IFLNK). Hence now
509 * that we have the stat information, override "mode".
511 state.type = pstat->st_mode;
512 state.have_type = true;
516 /* success. */
517 return 1;
521 /* Return true if there are no predicates with no_default_print in
522 predicate list PRED, false if there are any.
523 Returns true if default print should be performed */
525 boolean
526 default_prints (struct predicate *pred)
528 while (pred != NULL)
530 if (pred->no_default_print)
531 return (false);
532 pred = pred->pred_next;
534 return (true);
537 boolean
538 looks_like_expression(const char *arg, boolean leading)
540 switch (arg[0])
542 case '-':
543 if (arg[1]) /* "-foo" is an expression. */
544 return true;
545 else
546 return false; /* Just "-" is a filename. */
547 break;
549 case ')':
550 case ',':
551 if (arg[1])
552 return false; /* )x and ,z are not expressions */
553 else
554 return !leading; /* A leading ) or , is not either */
556 /* ( and ! are part of an expression, but (2 and !foo are
557 * filenames.
559 case '!':
560 case '(':
561 if (arg[1])
562 return false;
563 else
564 return true;
566 default:
567 return false;
571 static void
572 process_debug_options(char *arg)
574 const char *p;
575 char *token_context = NULL;
576 const char delimiters[] = ",";
577 boolean empty = true;
578 size_t i;
580 p = strtok_r(arg, delimiters, &token_context);
581 while (p)
583 empty = false;
585 for (i=0; i<N_DEBUGASSOC; ++i)
587 if (0 == strcmp(debugassoc[i].name, p))
589 options.debug_options |= debugassoc[i].val;
590 break;
593 if (i >= N_DEBUGASSOC)
595 error(0, 0, _("Ignoring unrecognised debug flag %s"),
596 quotearg_n_style(0, locale_quoting_style, arg));
598 p = strtok_r(NULL, delimiters, &token_context);
600 if (empty)
602 error(1, 0, _("Empty argument to the -D option."));
604 else if (options.debug_options & DebugHelp)
606 show_valid_debug_options(stdout, 1);
607 exit(0);
611 static void
612 process_optimisation_option(const char *arg)
614 if (0 == arg[0])
616 error(1, 0, _("The -O option must be immediately followed by a decimal integer"));
618 else
620 unsigned long opt_level;
621 char *end;
623 if (!isdigit( (unsigned char) arg[0] ))
625 error(1, 0, _("Please specify a decimal number immediately after -O"));
627 else
629 int prev_errno = errno;
630 errno = 0;
632 opt_level = strtoul(arg, &end, 10);
633 if ( (0==opt_level) && (end==arg) )
635 error(1, 0, _("Please specify a decimal number immediately after -O"));
637 else if (*end)
639 /* unwanted trailing characters. */
640 error(1, 0, _("Invalid optimisation level %s"), arg);
642 else if ( (ULONG_MAX==opt_level) && errno)
644 error(1, errno, _("Invalid optimisation level %s"), arg);
646 else if (opt_level > USHRT_MAX)
648 /* tricky to test, as on some platforms USHORT_MAX and ULONG_MAX
649 * can have the same value, though this is unusual.
651 error(1, 0, _("Optimisation level %lu is too high. "
652 "If you want to find files very quickly, "
653 "consider using GNU locate."),
654 opt_level);
656 else
658 options.optimisation_level = opt_level;
659 errno = prev_errno;
666 process_leading_options(int argc, char *argv[])
668 int i, end_of_leading_options;
670 for (i=1; (end_of_leading_options = i) < argc; ++i)
672 if (0 == strcmp("-H", argv[i]))
674 /* Meaning: dereference symbolic links on command line, but nowhere else. */
675 set_follow_state(SYMLINK_DEREF_ARGSONLY);
677 else if (0 == strcmp("-L", argv[i]))
679 /* Meaning: dereference all symbolic links. */
680 set_follow_state(SYMLINK_ALWAYS_DEREF);
682 else if (0 == strcmp("-P", argv[i]))
684 /* Meaning: never dereference symbolic links (default). */
685 set_follow_state(SYMLINK_NEVER_DEREF);
687 else if (0 == strcmp("--", argv[i]))
689 /* -- signifies the end of options. */
690 end_of_leading_options = i+1; /* Next time start with the next option */
691 break;
693 else if (0 == strcmp("-D", argv[i]))
695 process_debug_options(argv[i+1]);
696 ++i; /* skip the argument too. */
698 else if (0 == strncmp("-O", argv[i], 2))
700 process_optimisation_option(argv[i]+2);
702 else
704 /* Hmm, must be one of
705 * (a) A path name
706 * (b) A predicate
708 end_of_leading_options = i; /* Next time start with this option */
709 break;
712 return end_of_leading_options;
715 void
716 set_option_defaults(struct options *p)
718 /* We call check_nofollow() before setlocale() because the numbers
719 * for which we check (in the results of uname) definitiely have "."
720 * as the decimal point indicator even under locales for which that
721 * is not normally true. Hence atof() would do the wrong thing
722 * if we call it after setlocale().
724 #ifdef O_NOFOLLOW
725 p->open_nofollow_available = check_nofollow();
726 #else
727 p->open_nofollow_available = false;
728 #endif
730 p->regex_options = RE_SYNTAX_EMACS;
732 if (isatty(0))
734 p->warnings = true;
735 p->literal_control_chars = false;
737 else
739 p->warnings = false;
740 p->literal_control_chars = false; /* may change */
744 p->do_dir_first = true;
745 p->maxdepth = p->mindepth = -1;
746 p->start_time = time (NULL);
747 p->cur_day_start = p->start_time - DAYSECS;
748 p->full_days = false;
749 p->stay_on_filesystem = false;
750 p->ignore_readdir_race = false;
752 if (getenv("POSIXLY_CORRECT"))
753 p->output_block_size = 512;
754 else
755 p->output_block_size = 1024;
757 p->debug_options = 0uL;
758 p->optimisation_level = 0;
760 if (getenv("FIND_BLOCK_SIZE"))
762 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"));
765 #if LEAF_OPTIMISATION
766 /* The leaf optimisation is enabled. */
767 p->no_leaf_check = false;
768 #else
769 /* The leaf optimisation is disabled. */
770 p->no_leaf_check = true;
771 #endif
773 set_follow_state(SYMLINK_NEVER_DEREF); /* The default is equivalent to -P. */